|
| 1 | +package apiserver |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "encoding/json" |
| 6 | + "fmt" |
| 7 | + "net/http" |
| 8 | + "net/http/pprof" |
| 9 | + "regexp" |
| 10 | + "strconv" |
| 11 | + "sync" |
| 12 | + "time" |
| 13 | + |
| 14 | + "github.com/Sirupsen/logrus" |
| 15 | + |
| 16 | + "github.com/zalando-incubator/postgres-operator/pkg/spec" |
| 17 | + "github.com/zalando-incubator/postgres-operator/pkg/util" |
| 18 | + "github.com/zalando-incubator/postgres-operator/pkg/util/config" |
| 19 | +) |
| 20 | + |
| 21 | +const ( |
| 22 | + httpAPITimeout = time.Minute * 1 |
| 23 | + shutdownTimeout = time.Second * 10 |
| 24 | + httpReadTimeout = time.Millisecond * 100 |
| 25 | +) |
| 26 | + |
| 27 | +// ControllerInformer describes stats methods of a controller |
| 28 | +type controllerInformer interface { |
| 29 | + GetConfig() *spec.ControllerConfig |
| 30 | + GetOperatorConfig() *config.Config |
| 31 | + GetStatus() *spec.ControllerStatus |
| 32 | + TeamClusterList() map[string][]spec.NamespacedName |
| 33 | + ClusterStatus(team, cluster string) (*spec.ClusterStatus, error) |
| 34 | + ClusterLogs(team, cluster string) ([]*spec.LogEntry, error) |
| 35 | + WorkerLogs(workerID uint32) ([]*spec.LogEntry, error) |
| 36 | + ListQueue(workerID uint32) (*spec.QueueDump, error) |
| 37 | + GetWorkersCnt() uint32 |
| 38 | +} |
| 39 | + |
| 40 | +// Server describes HTTP API server |
| 41 | +type Server struct { |
| 42 | + logger *logrus.Entry |
| 43 | + http http.Server |
| 44 | + controller controllerInformer |
| 45 | +} |
| 46 | + |
| 47 | +var ( |
| 48 | + clusterStatusURL = regexp.MustCompile(`^/clusters/(?P<team>[a-zA-Z][a-zA-Z0-9]*)/(?P<cluster>[a-zA-Z][a-zA-Z0-9]*)/?$`) |
| 49 | + clusterLogsURL = regexp.MustCompile(`^/clusters/(?P<team>[a-zA-Z][a-zA-Z0-9]*)/(?P<cluster>[a-zA-Z][a-zA-Z0-9]*)/logs/?$`) |
| 50 | + teamURL = regexp.MustCompile(`^/clusters/(?P<team>[a-zA-Z][a-zA-Z0-9]*)/?$`) |
| 51 | + workerLogsURL = regexp.MustCompile(`^/workers/(?P<id>\d+)/logs/?$`) |
| 52 | + workerEventsQueueURL = regexp.MustCompile(`^/workers/(?P<id>\d+)/queue/?$`) |
| 53 | + workerAllQueue = regexp.MustCompile(`^/workers/all/queue/?$`) |
| 54 | + clustersURL = "/clusters/" |
| 55 | +) |
| 56 | + |
| 57 | +// New creates new HTTP API server |
| 58 | +func New(controller controllerInformer, port int, logger *logrus.Logger) *Server { |
| 59 | + s := &Server{ |
| 60 | + logger: logger.WithField("pkg", "apiserver"), |
| 61 | + controller: controller, |
| 62 | + } |
| 63 | + mux := http.NewServeMux() |
| 64 | + |
| 65 | + mux.Handle("/debug/pprof/", http.HandlerFunc(pprof.Index)) |
| 66 | + mux.Handle("/debug/pprof/cmdline", http.HandlerFunc(pprof.Cmdline)) |
| 67 | + mux.Handle("/debug/pprof/profile", http.HandlerFunc(pprof.Profile)) |
| 68 | + mux.Handle("/debug/pprof/symbol", http.HandlerFunc(pprof.Symbol)) |
| 69 | + mux.Handle("/debug/pprof/trace", http.HandlerFunc(pprof.Trace)) |
| 70 | + |
| 71 | + mux.Handle("/status/", http.HandlerFunc(s.controllerStatus)) |
| 72 | + mux.Handle("/config/", http.HandlerFunc(s.operatorConfig)) |
| 73 | + |
| 74 | + mux.HandleFunc("/clusters/", s.clusters) |
| 75 | + mux.HandleFunc("/workers/", s.workers) |
| 76 | + |
| 77 | + s.http = http.Server{ |
| 78 | + Addr: fmt.Sprintf(":%d", port), |
| 79 | + Handler: http.TimeoutHandler(mux, httpAPITimeout, ""), |
| 80 | + ReadTimeout: httpReadTimeout, |
| 81 | + } |
| 82 | + |
| 83 | + return s |
| 84 | +} |
| 85 | + |
| 86 | +// Run starts the HTTP server |
| 87 | +func (s *Server) Run(stopCh <-chan struct{}, wg *sync.WaitGroup) { |
| 88 | + defer wg.Done() |
| 89 | + |
| 90 | + go func() { |
| 91 | + err := s.http.ListenAndServe() |
| 92 | + if err != http.ErrServerClosed { |
| 93 | + s.logger.Fatalf("Could not start http server: %v", err) |
| 94 | + } |
| 95 | + }() |
| 96 | + s.logger.Infof("Listening on %s", s.http.Addr) |
| 97 | + |
| 98 | + <-stopCh |
| 99 | + |
| 100 | + ctx, cancel := context.WithTimeout(context.Background(), shutdownTimeout) |
| 101 | + defer cancel() |
| 102 | + err := s.http.Shutdown(ctx) |
| 103 | + if err == context.DeadlineExceeded { |
| 104 | + s.logger.Warnf("Shutdown timeout exceeded. closing http server") |
| 105 | + s.http.Close() |
| 106 | + } else if err != nil { |
| 107 | + s.logger.Errorf("Could not shutdown http server: %v", err) |
| 108 | + } |
| 109 | + s.logger.Infoln("Http server shut down") |
| 110 | +} |
| 111 | + |
| 112 | +func (s *Server) respond(obj interface{}, err error, w http.ResponseWriter) { |
| 113 | + w.Header().Set("Content-Type", "application/json") |
| 114 | + if err != nil { |
| 115 | + w.WriteHeader(http.StatusInternalServerError) |
| 116 | + json.NewEncoder(w).Encode(map[string]interface{}{"error": err.Error()}) |
| 117 | + return |
| 118 | + } |
| 119 | + |
| 120 | + err = json.NewEncoder(w).Encode(obj) |
| 121 | + if err != nil { |
| 122 | + w.WriteHeader(http.StatusInternalServerError) |
| 123 | + s.logger.Errorf("Could not encode: %v", err) |
| 124 | + } |
| 125 | +} |
| 126 | + |
| 127 | +func (s *Server) controllerStatus(w http.ResponseWriter, req *http.Request) { |
| 128 | + s.respond(s.controller.GetStatus(), nil, w) |
| 129 | +} |
| 130 | + |
| 131 | +func (s *Server) operatorConfig(w http.ResponseWriter, req *http.Request) { |
| 132 | + s.respond(map[string]interface{}{ |
| 133 | + "controller": s.controller.GetConfig(), |
| 134 | + "operator": s.controller.GetOperatorConfig(), |
| 135 | + }, nil, w) |
| 136 | +} |
| 137 | + |
| 138 | +func (s *Server) clusters(w http.ResponseWriter, req *http.Request) { |
| 139 | + var ( |
| 140 | + resp interface{} |
| 141 | + err error |
| 142 | + ) |
| 143 | + |
| 144 | + if matches := util.FindNamedStringSubmatch(clusterStatusURL, req.URL.Path); matches != nil { |
| 145 | + resp, err = s.controller.ClusterStatus(matches["team"], matches["cluster"]) |
| 146 | + } else if matches := util.FindNamedStringSubmatch(teamURL, req.URL.Path); matches != nil { |
| 147 | + teamClusters := s.controller.TeamClusterList() |
| 148 | + clusters, found := teamClusters[matches["team"]] |
| 149 | + if !found { |
| 150 | + s.respond(nil, fmt.Errorf("could not find clusters for the team"), w) |
| 151 | + } |
| 152 | + |
| 153 | + clusterNames := make([]string, 0) |
| 154 | + for _, cluster := range clusters { |
| 155 | + clusterNames = append(clusterNames, cluster.Name[len(matches["team"])+1:]) |
| 156 | + } |
| 157 | + |
| 158 | + s.respond(clusterNames, nil, w) |
| 159 | + return |
| 160 | + } else if matches := util.FindNamedStringSubmatch(clusterLogsURL, req.URL.Path); matches != nil { |
| 161 | + resp, err = s.controller.ClusterLogs(matches["team"], matches["cluster"]) |
| 162 | + } else if req.URL.Path == clustersURL { |
| 163 | + res := make(map[string][]string) |
| 164 | + for team, clusters := range s.controller.TeamClusterList() { |
| 165 | + for _, cluster := range clusters { |
| 166 | + res[team] = append(res[team], cluster.Name[len(team)+1:]) |
| 167 | + } |
| 168 | + } |
| 169 | + |
| 170 | + s.respond(res, nil, w) |
| 171 | + return |
| 172 | + } else { |
| 173 | + s.respond(nil, fmt.Errorf("page not found"), w) |
| 174 | + return |
| 175 | + } |
| 176 | + |
| 177 | + s.respond(resp, err, w) |
| 178 | +} |
| 179 | + |
| 180 | +func (s *Server) workers(w http.ResponseWriter, req *http.Request) { |
| 181 | + var ( |
| 182 | + resp interface{} |
| 183 | + err error |
| 184 | + ) |
| 185 | + |
| 186 | + if workerAllQueue.MatchString(req.URL.Path) { |
| 187 | + s.allQueues(w, req) |
| 188 | + return |
| 189 | + } else if matches := util.FindNamedStringSubmatch(workerLogsURL, req.URL.Path); matches != nil { |
| 190 | + workerID, _ := strconv.Atoi(matches["id"]) |
| 191 | + |
| 192 | + resp, err = s.controller.WorkerLogs(uint32(workerID)) |
| 193 | + } else if matches := util.FindNamedStringSubmatch(workerEventsQueueURL, req.URL.Path); matches != nil { |
| 194 | + workerID, _ := strconv.Atoi(matches["id"]) |
| 195 | + |
| 196 | + resp, err = s.controller.ListQueue(uint32(workerID)) |
| 197 | + } else { |
| 198 | + s.respond(nil, fmt.Errorf("page not found"), w) |
| 199 | + return |
| 200 | + } |
| 201 | + |
| 202 | + s.respond(resp, err, w) |
| 203 | +} |
| 204 | + |
| 205 | +func (s *Server) allQueues(w http.ResponseWriter, r *http.Request) { |
| 206 | + workersCnt := s.controller.GetWorkersCnt() |
| 207 | + resp := make(map[uint32]*spec.QueueDump, workersCnt) |
| 208 | + for i := uint32(0); i < workersCnt; i++ { |
| 209 | + queueDump, err := s.controller.ListQueue(i) |
| 210 | + if err != nil { |
| 211 | + s.respond(nil, err, w) |
| 212 | + return |
| 213 | + } |
| 214 | + |
| 215 | + resp[i] = queueDump |
| 216 | + } |
| 217 | + |
| 218 | + s.respond(resp, nil, w) |
| 219 | +} |
0 commit comments