Merge branch '20602-controller-qos'
[arvados.git] / lib / service / cmd.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: Apache-2.0
4
5 // Package service provides a cmd.Handler that brings up a system service.
6 package service
7
8 import (
9         "context"
10         "flag"
11         "fmt"
12         "io"
13         "net"
14         "net/http"
15         "net/http/httptest"
16         _ "net/http/pprof"
17         "net/url"
18         "os"
19         "strings"
20         "time"
21
22         "git.arvados.org/arvados.git/lib/cmd"
23         "git.arvados.org/arvados.git/lib/config"
24         "git.arvados.org/arvados.git/sdk/go/arvados"
25         "git.arvados.org/arvados.git/sdk/go/ctxlog"
26         "git.arvados.org/arvados.git/sdk/go/health"
27         "git.arvados.org/arvados.git/sdk/go/httpserver"
28         "github.com/coreos/go-systemd/daemon"
29         "github.com/julienschmidt/httprouter"
30         "github.com/prometheus/client_golang/prometheus"
31         "github.com/sirupsen/logrus"
32 )
33
34 type Handler interface {
35         http.Handler
36         CheckHealth() error
37         // Done returns a channel that closes when the handler shuts
38         // itself down, or nil if this never happens.
39         Done() <-chan struct{}
40 }
41
42 type NewHandlerFunc func(_ context.Context, _ *arvados.Cluster, token string, registry *prometheus.Registry) Handler
43
44 type command struct {
45         newHandler NewHandlerFunc
46         svcName    arvados.ServiceName
47         ctx        context.Context // enables tests to shutdown service; no public API yet
48 }
49
50 var requestQueueDumpCheckInterval = time.Minute
51
52 // Command returns a cmd.Handler that loads site config, calls
53 // newHandler with the current cluster and node configs, and brings up
54 // an http server with the returned handler.
55 //
56 // The handler is wrapped with server middleware (adding X-Request-ID
57 // headers, logging requests/responses, etc).
58 func Command(svcName arvados.ServiceName, newHandler NewHandlerFunc) cmd.Handler {
59         return &command{
60                 newHandler: newHandler,
61                 svcName:    svcName,
62                 ctx:        context.Background(),
63         }
64 }
65
66 func (c *command) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
67         log := ctxlog.New(stderr, "json", "info")
68
69         var err error
70         defer func() {
71                 if err != nil {
72                         log.WithError(err).Error("exiting")
73                 }
74         }()
75
76         flags := flag.NewFlagSet("", flag.ContinueOnError)
77         flags.SetOutput(stderr)
78
79         loader := config.NewLoader(stdin, log)
80         loader.SetupFlags(flags)
81
82         // prog is [keepstore, keep-web, git-httpd, ...]  but the
83         // legacy config flags are [-legacy-keepstore-config,
84         // -legacy-keepweb-config, -legacy-git-httpd-config, ...]
85         legacyFlag := "-legacy-" + strings.Replace(prog, "keep-", "keep", 1) + "-config"
86         args = loader.MungeLegacyConfigArgs(log, args, legacyFlag)
87
88         versionFlag := flags.Bool("version", false, "Write version information to stdout and exit 0")
89         pprofAddr := flags.String("pprof", "", "Serve Go profile data at `[addr]:port`")
90         if ok, code := cmd.ParseFlags(flags, prog, args, "", stderr); !ok {
91                 return code
92         } else if *versionFlag {
93                 return cmd.Version.RunCommand(prog, args, stdin, stdout, stderr)
94         }
95
96         if *pprofAddr != "" {
97                 go func() {
98                         log.Println(http.ListenAndServe(*pprofAddr, nil))
99                 }()
100         }
101
102         if strings.HasSuffix(prog, "controller") {
103                 // Some config-loader checks try to make API calls via
104                 // controller. Those can't be expected to work if this
105                 // process _is_ the controller: we haven't started an
106                 // http server yet.
107                 loader.SkipAPICalls = true
108         }
109
110         cfg, err := loader.Load()
111         if err != nil {
112                 return 1
113         }
114         cluster, err := cfg.GetCluster("")
115         if err != nil {
116                 return 1
117         }
118
119         // Now that we've read the config, replace the bootstrap
120         // logger with a new one according to the logging config.
121         log = ctxlog.New(stderr, cluster.SystemLogs.Format, cluster.SystemLogs.LogLevel)
122         logger := log.WithFields(logrus.Fields{
123                 "PID":       os.Getpid(),
124                 "ClusterID": cluster.ClusterID,
125         })
126         ctx := ctxlog.Context(c.ctx, logger)
127
128         listenURL, internalURL, err := getListenAddr(cluster.Services, c.svcName, log)
129         if err != nil {
130                 return 1
131         }
132         ctx = context.WithValue(ctx, contextKeyURL{}, internalURL)
133
134         reg := prometheus.NewRegistry()
135         loader.RegisterMetrics(reg)
136
137         // arvados_version_running{version="1.2.3~4"} 1.0
138         mVersion := prometheus.NewGaugeVec(prometheus.GaugeOpts{
139                 Namespace: "arvados",
140                 Name:      "version_running",
141                 Help:      "Indicated version is running.",
142         }, []string{"version"})
143         mVersion.WithLabelValues(cmd.Version.String()).Set(1)
144         reg.MustRegister(mVersion)
145
146         handler := c.newHandler(ctx, cluster, cluster.SystemRootToken, reg)
147         if err = handler.CheckHealth(); err != nil {
148                 return 1
149         }
150
151         instrumented := httpserver.Instrument(reg, log,
152                 httpserver.HandlerWithDeadline(cluster.API.RequestTimeout.Duration(),
153                         httpserver.AddRequestIDs(
154                                 httpserver.Inspect(reg, cluster.ManagementToken,
155                                         httpserver.LogRequests(
156                                                 interceptHealthReqs(cluster.ManagementToken, handler.CheckHealth,
157                                                         &httpserver.RequestLimiter{
158                                                                 Handler:       handler,
159                                                                 MaxConcurrent: cluster.API.MaxConcurrentRequests,
160                                                                 MaxQueue:      cluster.API.MaxQueuedRequests,
161                                                                 Priority:      c.requestPriority,
162                                                                 Registry:      reg}))))))
163         srv := &httpserver.Server{
164                 Server: http.Server{
165                         Handler:     ifCollectionInHost(instrumented, instrumented.ServeAPI(cluster.ManagementToken, instrumented)),
166                         BaseContext: func(net.Listener) context.Context { return ctx },
167                 },
168                 Addr: listenURL.Host,
169         }
170         if listenURL.Scheme == "https" || listenURL.Scheme == "wss" {
171                 tlsconfig, err := makeTLSConfig(cluster, logger)
172                 if err != nil {
173                         logger.WithError(err).Errorf("cannot start %s service on %s", c.svcName, listenURL.String())
174                         return 1
175                 }
176                 srv.TLSConfig = tlsconfig
177         }
178         err = srv.Start()
179         if err != nil {
180                 return 1
181         }
182         logger.WithFields(logrus.Fields{
183                 "URL":     listenURL,
184                 "Listen":  srv.Addr,
185                 "Service": c.svcName,
186                 "Version": cmd.Version.String(),
187         }).Info("listening")
188         if _, err := daemon.SdNotify(false, "READY=1"); err != nil {
189                 logger.WithError(err).Errorf("error notifying init daemon")
190         }
191         go func() {
192                 // Shut down server if caller cancels context
193                 <-ctx.Done()
194                 srv.Close()
195         }()
196         go func() {
197                 // Shut down server if handler dies
198                 <-handler.Done()
199                 srv.Close()
200         }()
201         go c.requestQueueDumpCheck(cluster, prog, reg, &srv.Server, logger)
202         err = srv.Wait()
203         if err != nil {
204                 return 1
205         }
206         return 0
207 }
208
209 // If SystemLogs.RequestQueueDumpDirectory is set, monitor the
210 // server's incoming HTTP request queue size. When it exceeds 90% of
211 // API.MaxConcurrentRequests, write the /_inspect/requests data to a
212 // JSON file in the specified directory.
213 func (c *command) requestQueueDumpCheck(cluster *arvados.Cluster, prog string, reg *prometheus.Registry, srv *http.Server, logger logrus.FieldLogger) {
214         outdir := cluster.SystemLogs.RequestQueueDumpDirectory
215         if outdir == "" || cluster.ManagementToken == "" || cluster.API.MaxConcurrentRequests < 1 {
216                 return
217         }
218         logger = logger.WithField("worker", "RequestQueueDump")
219         outfile := outdir + "/" + prog + "-requests.json"
220         for range time.NewTicker(requestQueueDumpCheckInterval).C {
221                 mfs, err := reg.Gather()
222                 if err != nil {
223                         logger.WithError(err).Warn("error getting metrics")
224                         continue
225                 }
226                 dump := false
227                 for _, mf := range mfs {
228                         if mf.Name != nil && *mf.Name == "arvados_concurrent_requests" && len(mf.Metric) == 1 {
229                                 n := int(mf.Metric[0].GetGauge().GetValue())
230                                 if n > 0 && n >= cluster.API.MaxConcurrentRequests*9/10 {
231                                         dump = true
232                                         break
233                                 }
234                         }
235                 }
236                 if dump {
237                         req, err := http.NewRequest("GET", "/_inspect/requests", nil)
238                         if err != nil {
239                                 logger.WithError(err).Warn("error in http.NewRequest")
240                                 continue
241                         }
242                         req.Header.Set("Authorization", "Bearer "+cluster.ManagementToken)
243                         resp := httptest.NewRecorder()
244                         srv.Handler.ServeHTTP(resp, req)
245                         if code := resp.Result().StatusCode; code != http.StatusOK {
246                                 logger.WithField("StatusCode", code).Warn("error getting /_inspect/requests")
247                                 continue
248                         }
249                         err = os.WriteFile(outfile, resp.Body.Bytes(), 0777)
250                         if err != nil {
251                                 logger.WithError(err).Warn("error writing file")
252                                 continue
253                         }
254                 }
255         }
256 }
257
258 func (c *command) requestPriority(req *http.Request, queued time.Time) int64 {
259         switch {
260         case req.Method == http.MethodPost && strings.HasPrefix(req.URL.Path, "/arvados/v1/containers/") && strings.HasSuffix(req.URL.Path, "/lock"):
261                 // Return 503 immediately instead of queueing. We want
262                 // to send feedback to dispatchcloud ASAP to stop
263                 // bringing up new containers.
264                 return httpserver.IneligibleForQueuePriority
265         case req.Method == http.MethodPost && strings.HasPrefix(req.URL.Path, "/arvados/v1/logs"):
266                 // "Create log entry" is the most harmless kind of
267                 // request to drop.
268                 return 0
269         case req.Header.Get("Origin") != "":
270                 // Handle interactive requests first.
271                 return 2
272         default:
273                 return 1
274         }
275 }
276
277 // If an incoming request's target vhost has an embedded collection
278 // UUID or PDH, handle it with hTrue, otherwise handle it with
279 // hFalse.
280 //
281 // Facilitates routing "http://collections.example/metrics" to metrics
282 // and "http://{uuid}.collections.example/metrics" to a file in a
283 // collection.
284 func ifCollectionInHost(hTrue, hFalse http.Handler) http.Handler {
285         return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
286                 if arvados.CollectionIDFromDNSName(r.Host) != "" {
287                         hTrue.ServeHTTP(w, r)
288                 } else {
289                         hFalse.ServeHTTP(w, r)
290                 }
291         })
292 }
293
294 func interceptHealthReqs(mgtToken string, checkHealth func() error, next http.Handler) http.Handler {
295         mux := httprouter.New()
296         mux.Handler("GET", "/_health/ping", &health.Handler{
297                 Token:  mgtToken,
298                 Prefix: "/_health/",
299                 Routes: health.Routes{"ping": checkHealth},
300         })
301         mux.NotFound = next
302         return ifCollectionInHost(next, mux)
303 }
304
305 // Determine listenURL (addr:port where server should bind) and
306 // internalURL (target url that client should connect to) for a
307 // service.
308 //
309 // If the config does not specify ListenURL, we check all of the
310 // configured InternalURLs. If there is exactly one that matches our
311 // hostname, or exactly one that matches a local interface address,
312 // then we use that as listenURL.
313 //
314 // Note that listenURL and internalURL may use different protocols
315 // (e.g., listenURL is http, but the service sits behind a proxy, so
316 // clients connect using https).
317 func getListenAddr(svcs arvados.Services, prog arvados.ServiceName, log logrus.FieldLogger) (arvados.URL, arvados.URL, error) {
318         svc, ok := svcs.Map()[prog]
319         if !ok {
320                 return arvados.URL{}, arvados.URL{}, fmt.Errorf("unknown service name %q", prog)
321         }
322
323         if want := os.Getenv("ARVADOS_SERVICE_INTERNAL_URL"); want != "" {
324                 url, err := url.Parse(want)
325                 if err != nil {
326                         return arvados.URL{}, arvados.URL{}, fmt.Errorf("$ARVADOS_SERVICE_INTERNAL_URL (%q): %s", want, err)
327                 }
328                 if url.Path == "" {
329                         url.Path = "/"
330                 }
331                 for internalURL, conf := range svc.InternalURLs {
332                         if internalURL.String() == url.String() {
333                                 listenURL := conf.ListenURL
334                                 if listenURL.Host == "" {
335                                         listenURL = internalURL
336                                 }
337                                 return listenURL, internalURL, nil
338                         }
339                 }
340                 log.Warnf("possible configuration error: listening on %s (from $ARVADOS_SERVICE_INTERNAL_URL) even though configuration does not have a matching InternalURLs entry", url)
341                 internalURL := arvados.URL(*url)
342                 return internalURL, internalURL, nil
343         }
344
345         errors := []string{}
346         for internalURL, conf := range svc.InternalURLs {
347                 listenURL := conf.ListenURL
348                 if listenURL.Host == "" {
349                         // If ListenURL is not specified, assume
350                         // InternalURL is also usable as the listening
351                         // proto/addr/port (i.e., simple case with no
352                         // intermediate proxy/routing)
353                         listenURL = internalURL
354                 }
355                 listenAddr := listenURL.Host
356                 if _, _, err := net.SplitHostPort(listenAddr); err != nil {
357                         // url "https://foo.example/" (with no
358                         // explicit port name/number) means listen on
359                         // the well-known port for the specified
360                         // protocol, "foo.example:https".
361                         port := listenURL.Scheme
362                         if port == "ws" || port == "wss" {
363                                 port = "http" + port[2:]
364                         }
365                         listenAddr = net.JoinHostPort(listenAddr, port)
366                 }
367                 listener, err := net.Listen("tcp", listenAddr)
368                 if err == nil {
369                         listener.Close()
370                         return listenURL, internalURL, nil
371                 } else if strings.Contains(err.Error(), "cannot assign requested address") {
372                         // If 'Host' specifies a different server than
373                         // the current one, it'll resolve the hostname
374                         // to IP address, and then fail because it
375                         // can't bind an IP address it doesn't own.
376                         continue
377                 } else {
378                         errors = append(errors, fmt.Sprintf("%s: %s", listenURL, err))
379                 }
380         }
381         if len(errors) > 0 {
382                 return arvados.URL{}, arvados.URL{}, fmt.Errorf("could not enable the %q service on this host: %s", prog, strings.Join(errors, "; "))
383         }
384         return arvados.URL{}, arvados.URL{}, fmt.Errorf("configuration does not enable the %q service on this host", prog)
385 }
386
387 type contextKeyURL struct{}
388
389 func URLFromContext(ctx context.Context) (arvados.URL, bool) {
390         u, ok := ctx.Value(contextKeyURL{}).(arvados.URL)
391         return u, ok
392 }