21316: Merge commit '1416f698b72de4b09350d9c2fb25c1405c3247bc' into 21316-left-panel...
[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         maxReqs := cluster.API.MaxConcurrentRequests
152         if maxRails := cluster.API.MaxConcurrentRailsRequests; maxRails > 0 &&
153                 (maxRails < maxReqs || maxReqs == 0) &&
154                 strings.HasSuffix(prog, "controller") {
155                 // Ideally, we would accept up to
156                 // MaxConcurrentRequests, and apply the
157                 // MaxConcurrentRailsRequests limit only for requests
158                 // that require calling upstream to RailsAPI. But for
159                 // now we make the simplifying assumption that every
160                 // controller request causes an upstream RailsAPI
161                 // request.
162                 maxReqs = maxRails
163         }
164         instrumented := httpserver.Instrument(reg, log,
165                 httpserver.HandlerWithDeadline(cluster.API.RequestTimeout.Duration(),
166                         httpserver.AddRequestIDs(
167                                 httpserver.Inspect(reg, cluster.ManagementToken,
168                                         httpserver.LogRequests(
169                                                 interceptHealthReqs(cluster.ManagementToken, handler.CheckHealth,
170                                                         &httpserver.RequestLimiter{
171                                                                 Handler:                    handler,
172                                                                 MaxConcurrent:              maxReqs,
173                                                                 MaxQueue:                   cluster.API.MaxQueuedRequests,
174                                                                 MaxQueueTimeForMinPriority: cluster.API.MaxQueueTimeForLockRequests.Duration(),
175                                                                 Priority:                   c.requestPriority,
176                                                                 Registry:                   reg}))))))
177         srv := &httpserver.Server{
178                 Server: http.Server{
179                         Handler:     ifCollectionInHost(instrumented, instrumented.ServeAPI(cluster.ManagementToken, instrumented)),
180                         BaseContext: func(net.Listener) context.Context { return ctx },
181                 },
182                 Addr: listenURL.Host,
183         }
184         if listenURL.Scheme == "https" || listenURL.Scheme == "wss" {
185                 tlsconfig, err := makeTLSConfig(cluster, logger)
186                 if err != nil {
187                         logger.WithError(err).Errorf("cannot start %s service on %s", c.svcName, listenURL.String())
188                         return 1
189                 }
190                 srv.TLSConfig = tlsconfig
191         }
192         err = srv.Start()
193         if err != nil {
194                 return 1
195         }
196         logger.WithFields(logrus.Fields{
197                 "URL":     listenURL,
198                 "Listen":  srv.Addr,
199                 "Service": c.svcName,
200                 "Version": cmd.Version.String(),
201         }).Info("listening")
202         if _, err := daemon.SdNotify(false, "READY=1"); err != nil {
203                 logger.WithError(err).Errorf("error notifying init daemon")
204         }
205         go func() {
206                 // Shut down server if caller cancels context
207                 <-ctx.Done()
208                 srv.Close()
209         }()
210         go func() {
211                 // Shut down server if handler dies
212                 <-handler.Done()
213                 srv.Close()
214         }()
215         go c.requestQueueDumpCheck(cluster, maxReqs, prog, reg, &srv.Server, logger)
216         err = srv.Wait()
217         if err != nil {
218                 return 1
219         }
220         return 0
221 }
222
223 // If SystemLogs.RequestQueueDumpDirectory is set, monitor the
224 // server's incoming HTTP request queue size. When it exceeds 90% of
225 // API.MaxConcurrentRequests, write the /_inspect/requests data to a
226 // JSON file in the specified directory.
227 func (c *command) requestQueueDumpCheck(cluster *arvados.Cluster, maxReqs int, prog string, reg *prometheus.Registry, srv *http.Server, logger logrus.FieldLogger) {
228         outdir := cluster.SystemLogs.RequestQueueDumpDirectory
229         if outdir == "" || cluster.ManagementToken == "" || maxReqs < 1 {
230                 return
231         }
232         logger = logger.WithField("worker", "RequestQueueDump")
233         outfile := outdir + "/" + prog + "-requests.json"
234         for range time.NewTicker(requestQueueDumpCheckInterval).C {
235                 mfs, err := reg.Gather()
236                 if err != nil {
237                         logger.WithError(err).Warn("error getting metrics")
238                         continue
239                 }
240                 dump := false
241                 for _, mf := range mfs {
242                         if mf.Name != nil && *mf.Name == "arvados_concurrent_requests" && len(mf.Metric) == 1 {
243                                 n := int(mf.Metric[0].GetGauge().GetValue())
244                                 if n > 0 && n >= maxReqs*9/10 {
245                                         dump = true
246                                         break
247                                 }
248                         }
249                 }
250                 if dump {
251                         req, err := http.NewRequest("GET", "/_inspect/requests", nil)
252                         if err != nil {
253                                 logger.WithError(err).Warn("error in http.NewRequest")
254                                 continue
255                         }
256                         req.Header.Set("Authorization", "Bearer "+cluster.ManagementToken)
257                         resp := httptest.NewRecorder()
258                         srv.Handler.ServeHTTP(resp, req)
259                         if code := resp.Result().StatusCode; code != http.StatusOK {
260                                 logger.WithField("StatusCode", code).Warn("error getting /_inspect/requests")
261                                 continue
262                         }
263                         err = os.WriteFile(outfile, resp.Body.Bytes(), 0777)
264                         if err != nil {
265                                 logger.WithError(err).Warn("error writing file")
266                                 continue
267                         }
268                 }
269         }
270 }
271
272 func (c *command) requestPriority(req *http.Request, queued time.Time) int64 {
273         switch {
274         case req.Method == http.MethodPost && strings.HasPrefix(req.URL.Path, "/arvados/v1/containers/") && strings.HasSuffix(req.URL.Path, "/lock"):
275                 // Return 503 immediately instead of queueing. We want
276                 // to send feedback to dispatchcloud ASAP to stop
277                 // bringing up new containers.
278                 return httpserver.MinPriority
279         case req.Method == http.MethodPost && strings.HasPrefix(req.URL.Path, "/arvados/v1/logs"):
280                 // "Create log entry" is the most harmless kind of
281                 // request to drop. Negative priority is called "low"
282                 // in aggregate metrics.
283                 return -1
284         case req.Header.Get("Origin") != "":
285                 // Handle interactive requests first. Positive
286                 // priority is called "high" in aggregate metrics.
287                 return 1
288         default:
289                 // Zero priority is called "normal" in aggregate
290                 // metrics.
291                 return 0
292         }
293 }
294
295 // If an incoming request's target vhost has an embedded collection
296 // UUID or PDH, handle it with hTrue, otherwise handle it with
297 // hFalse.
298 //
299 // Facilitates routing "http://collections.example/metrics" to metrics
300 // and "http://{uuid}.collections.example/metrics" to a file in a
301 // collection.
302 func ifCollectionInHost(hTrue, hFalse http.Handler) http.Handler {
303         return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
304                 if arvados.CollectionIDFromDNSName(r.Host) != "" {
305                         hTrue.ServeHTTP(w, r)
306                 } else {
307                         hFalse.ServeHTTP(w, r)
308                 }
309         })
310 }
311
312 func interceptHealthReqs(mgtToken string, checkHealth func() error, next http.Handler) http.Handler {
313         mux := httprouter.New()
314         mux.Handler("GET", "/_health/ping", &health.Handler{
315                 Token:  mgtToken,
316                 Prefix: "/_health/",
317                 Routes: health.Routes{"ping": checkHealth},
318         })
319         mux.NotFound = next
320         return ifCollectionInHost(next, mux)
321 }
322
323 // Determine listenURL (addr:port where server should bind) and
324 // internalURL (target url that client should connect to) for a
325 // service.
326 //
327 // If the config does not specify ListenURL, we check all of the
328 // configured InternalURLs. If there is exactly one that matches our
329 // hostname, or exactly one that matches a local interface address,
330 // then we use that as listenURL.
331 //
332 // Note that listenURL and internalURL may use different protocols
333 // (e.g., listenURL is http, but the service sits behind a proxy, so
334 // clients connect using https).
335 func getListenAddr(svcs arvados.Services, prog arvados.ServiceName, log logrus.FieldLogger) (arvados.URL, arvados.URL, error) {
336         svc, ok := svcs.Map()[prog]
337         if !ok {
338                 return arvados.URL{}, arvados.URL{}, fmt.Errorf("unknown service name %q", prog)
339         }
340
341         if want := os.Getenv("ARVADOS_SERVICE_INTERNAL_URL"); want != "" {
342                 url, err := url.Parse(want)
343                 if err != nil {
344                         return arvados.URL{}, arvados.URL{}, fmt.Errorf("$ARVADOS_SERVICE_INTERNAL_URL (%q): %s", want, err)
345                 }
346                 if url.Path == "" {
347                         url.Path = "/"
348                 }
349                 for internalURL, conf := range svc.InternalURLs {
350                         if internalURL.String() == url.String() {
351                                 listenURL := conf.ListenURL
352                                 if listenURL.Host == "" {
353                                         listenURL = internalURL
354                                 }
355                                 return listenURL, internalURL, nil
356                         }
357                 }
358                 log.Warnf("possible configuration error: listening on %s (from $ARVADOS_SERVICE_INTERNAL_URL) even though configuration does not have a matching InternalURLs entry", url)
359                 internalURL := arvados.URL(*url)
360                 return internalURL, internalURL, nil
361         }
362
363         errors := []string{}
364         for internalURL, conf := range svc.InternalURLs {
365                 listenURL := conf.ListenURL
366                 if listenURL.Host == "" {
367                         // If ListenURL is not specified, assume
368                         // InternalURL is also usable as the listening
369                         // proto/addr/port (i.e., simple case with no
370                         // intermediate proxy/routing)
371                         listenURL = internalURL
372                 }
373                 listenAddr := listenURL.Host
374                 if _, _, err := net.SplitHostPort(listenAddr); err != nil {
375                         // url "https://foo.example/" (with no
376                         // explicit port name/number) means listen on
377                         // the well-known port for the specified
378                         // protocol, "foo.example:https".
379                         port := listenURL.Scheme
380                         if port == "ws" || port == "wss" {
381                                 port = "http" + port[2:]
382                         }
383                         listenAddr = net.JoinHostPort(listenAddr, port)
384                 }
385                 listener, err := net.Listen("tcp", listenAddr)
386                 if err == nil {
387                         listener.Close()
388                         return listenURL, internalURL, nil
389                 } else if strings.Contains(err.Error(), "cannot assign requested address") {
390                         // If 'Host' specifies a different server than
391                         // the current one, it'll resolve the hostname
392                         // to IP address, and then fail because it
393                         // can't bind an IP address it doesn't own.
394                         continue
395                 } else {
396                         errors = append(errors, fmt.Sprintf("%s: %s", listenURL, err))
397                 }
398         }
399         if len(errors) > 0 {
400                 return arvados.URL{}, arvados.URL{}, fmt.Errorf("could not enable the %q service on this host: %s", prog, strings.Join(errors, "; "))
401         }
402         return arvados.URL{}, arvados.URL{}, fmt.Errorf("configuration does not enable the %q service on this host", prog)
403 }
404
405 type contextKeyURL struct{}
406
407 func URLFromContext(ctx context.Context) (arvados.URL, bool) {
408         u, ok := ctx.Value(contextKeyURL{}).(arvados.URL)
409         return u, ok
410 }