1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: Apache-2.0
5 // Package service provides a cmd.Handler that brings up a system service.
23 "git.arvados.org/arvados.git/lib/cmd"
24 "git.arvados.org/arvados.git/lib/config"
25 "git.arvados.org/arvados.git/sdk/go/arvados"
26 "git.arvados.org/arvados.git/sdk/go/ctxlog"
27 "git.arvados.org/arvados.git/sdk/go/health"
28 "git.arvados.org/arvados.git/sdk/go/httpserver"
29 "github.com/coreos/go-systemd/daemon"
30 "github.com/julienschmidt/httprouter"
31 "github.com/prometheus/client_golang/prometheus"
32 "github.com/sirupsen/logrus"
35 type Handler interface {
38 // Done returns a channel that closes when the handler shuts
39 // itself down, or nil if this never happens.
40 Done() <-chan struct{}
43 type NewHandlerFunc func(_ context.Context, _ *arvados.Cluster, token string, registry *prometheus.Registry) Handler
46 newHandler NewHandlerFunc
47 svcName arvados.ServiceName
48 ctx context.Context // enables tests to shutdown service; no public API yet
51 var requestQueueDumpCheckInterval = time.Minute
53 // Command returns a cmd.Handler that loads site config, calls
54 // newHandler with the current cluster and node configs, and brings up
55 // an http server with the returned handler.
57 // The handler is wrapped with server middleware (adding X-Request-ID
58 // headers, logging requests/responses, etc).
59 func Command(svcName arvados.ServiceName, newHandler NewHandlerFunc) cmd.Handler {
61 newHandler: newHandler,
63 ctx: context.Background(),
67 func (c *command) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
68 log := ctxlog.New(stderr, "json", "info")
73 log.WithError(err).Error("exiting")
77 flags := flag.NewFlagSet("", flag.ContinueOnError)
78 flags.SetOutput(stderr)
80 loader := config.NewLoader(stdin, log)
81 loader.SetupFlags(flags)
83 // prog is [keepstore, keep-web, ...] but the
84 // legacy config flags are [-legacy-keepstore-config,
85 // -legacy-keepweb-config, ...]
86 legacyFlag := "-legacy-" + strings.Replace(prog, "keep-", "keep", 1) + "-config"
87 args = loader.MungeLegacyConfigArgs(log, args, legacyFlag)
89 versionFlag := flags.Bool("version", false, "Write version information to stdout and exit 0")
90 pprofAddr := flags.String("pprof", "", "Serve Go profile data at `[addr]:port`")
91 if ok, code := cmd.ParseFlags(flags, prog, args, "", stderr); !ok {
93 } else if *versionFlag {
94 return cmd.Version.RunCommand(prog, args, stdin, stdout, stderr)
99 log.Println(http.ListenAndServe(*pprofAddr, nil))
103 if strings.HasSuffix(prog, "controller") {
104 // Some config-loader checks try to make API calls via
105 // controller. Those can't be expected to work if this
106 // process _is_ the controller: we haven't started an
108 loader.SkipAPICalls = true
111 cfg, err := loader.Load()
115 cluster, err := cfg.GetCluster("")
120 // Now that we've read the config, replace the bootstrap
121 // logger with a new one according to the logging config.
122 log = ctxlog.New(stderr, cluster.SystemLogs.Format, cluster.SystemLogs.LogLevel)
123 logger := log.WithFields(logrus.Fields{
125 "ClusterID": cluster.ClusterID,
127 ctx := ctxlog.Context(c.ctx, logger)
129 // Check whether the caller is attempting to use environment
130 // variables to override cluster configuration, and advise
133 envhost := os.Getenv("ARVADOS_API_HOST")
134 if envhost != "" && envhost != cluster.Services.Controller.ExternalURL.Host {
135 logger.Warn("ARVADOS_API_HOST environment variable is present, but will not be used")
137 envins := os.Getenv("ARVADOS_API_HOST_INSECURE")
138 if envins != "" && (envins != "0") != cluster.TLS.Insecure {
139 logger.Warn("ARVADOS_API_HOST_INSECURE environment variable is present, but will not be used")
141 envtoken := os.Getenv("ARVADOS_API_TOKEN")
142 if envtoken != "" && envtoken != cluster.SystemRootToken {
143 logger.Warn("ARVADOS_API_TOKEN environment variable is present, but will not be used")
147 listenURL, internalURL, err := getListenAddr(cluster.Services, c.svcName, log)
151 ctx = context.WithValue(ctx, contextKeyURL{}, internalURL)
153 reg := prometheus.NewRegistry()
154 loader.RegisterMetrics(reg)
156 // arvados_version_running{version="1.2.3~4"} 1.0
157 mVersion := prometheus.NewGaugeVec(prometheus.GaugeOpts{
158 Namespace: "arvados",
159 Name: "version_running",
160 Help: "Indicated version is running.",
161 }, []string{"version"})
162 mVersion.WithLabelValues(cmd.Version.String()).Set(1)
163 reg.MustRegister(mVersion)
165 handler := c.newHandler(ctx, cluster, cluster.SystemRootToken, reg)
166 if err = handler.CheckHealth(); err != nil {
170 instrumented := httpserver.Instrument(reg, log,
171 httpserver.HandlerWithDeadline(cluster.API.RequestTimeout.Duration(),
172 httpserver.AddRequestIDs(
173 httpserver.Inspect(reg, cluster.ManagementToken,
174 httpserver.LogRequests(
175 interceptHealthReqs(cluster.ManagementToken, handler.CheckHealth,
176 c.requestLimiter(handler, cluster, reg)))))))
177 srv := &httpserver.Server{
179 Handler: ifCollectionInHost(instrumented, instrumented.ServeAPI(cluster.ManagementToken, instrumented)),
180 BaseContext: func(net.Listener) context.Context { return ctx },
182 Addr: listenURL.Host,
184 if listenURL.Scheme == "https" || listenURL.Scheme == "wss" {
185 tlsconfig, err := makeTLSConfig(cluster, logger)
187 logger.WithError(err).Errorf("cannot start %s service on %s", c.svcName, listenURL.String())
190 srv.TLSConfig = tlsconfig
196 logger.WithFields(logrus.Fields{
199 "Service": c.svcName,
200 "Version": cmd.Version.String(),
202 if _, err := daemon.SdNotify(false, "READY=1"); err != nil {
203 logger.WithError(err).Errorf("error notifying init daemon")
206 // Shut down server if caller cancels context
211 // Shut down server if handler dies
215 go c.requestQueueDumpCheck(cluster, prog, reg, &srv.Server, logger)
223 // If SystemLogs.RequestQueueDumpDirectory is set, monitor the
224 // server's incoming HTTP request limiters. When the number of
225 // concurrent requests in any queue ("api" or "tunnel") exceeds 90% of
226 // its maximum slots, write the /_inspect/requests data to a JSON file
227 // in the specified directory.
228 func (c *command) requestQueueDumpCheck(cluster *arvados.Cluster, prog string, reg *prometheus.Registry, srv *http.Server, logger logrus.FieldLogger) {
229 outdir := cluster.SystemLogs.RequestQueueDumpDirectory
230 if outdir == "" || cluster.ManagementToken == "" {
233 logger = logger.WithField("worker", "RequestQueueDump")
234 outfile := outdir + "/" + prog + "-requests.json"
235 for range time.NewTicker(requestQueueDumpCheckInterval).C {
236 mfs, err := reg.Gather()
238 logger.WithError(err).Warn("error getting metrics")
241 cur := map[string]int{} // queue label => current
242 max := map[string]int{} // queue label => max
243 for _, mf := range mfs {
244 for _, m := range mf.GetMetric() {
245 for _, ml := range m.GetLabel() {
246 if ml.GetName() == "queue" {
247 n := int(m.GetGauge().GetValue())
248 if name := mf.GetName(); name == "arvados_concurrent_requests" {
250 } else if name == "arvados_max_concurrent_requests" {
258 for queue, n := range cur {
259 if n > 0 && max[queue] > 0 && n >= max[queue]*9/10 {
265 req, err := http.NewRequest("GET", "/_inspect/requests", nil)
267 logger.WithError(err).Warn("error in http.NewRequest")
270 req.Header.Set("Authorization", "Bearer "+cluster.ManagementToken)
271 resp := httptest.NewRecorder()
272 srv.Handler.ServeHTTP(resp, req)
273 if code := resp.Result().StatusCode; code != http.StatusOK {
274 logger.WithField("StatusCode", code).Warn("error getting /_inspect/requests")
277 err = os.WriteFile(outfile, resp.Body.Bytes(), 0777)
279 logger.WithError(err).Warn("error writing file")
286 // Set up a httpserver.RequestLimiter with separate queues/streams for
287 // API requests (obeying MaxConcurrentRequests etc) and gateway tunnel
288 // requests (obeying MaxGatewayTunnels).
289 func (c *command) requestLimiter(handler http.Handler, cluster *arvados.Cluster, reg *prometheus.Registry) http.Handler {
290 maxReqs := cluster.API.MaxConcurrentRequests
291 if maxRails := cluster.API.MaxConcurrentRailsRequests; maxRails > 0 &&
292 (maxRails < maxReqs || maxReqs == 0) &&
293 c.svcName == arvados.ServiceNameController {
294 // Ideally, we would accept up to
295 // MaxConcurrentRequests, and apply the
296 // MaxConcurrentRailsRequests limit only for requests
297 // that require calling upstream to RailsAPI. But for
298 // now we make the simplifying assumption that every
299 // controller request causes an upstream RailsAPI
303 rqAPI := &httpserver.RequestQueue{
305 MaxConcurrent: maxReqs,
306 MaxQueue: cluster.API.MaxQueuedRequests,
307 MaxQueueTimeForMinPriority: cluster.API.MaxQueueTimeForLockRequests.Duration(),
309 rqTunnel := &httpserver.RequestQueue{
311 MaxConcurrent: cluster.API.MaxGatewayTunnels,
314 return &httpserver.RequestLimiter{
316 Priority: c.requestPriority,
318 Queue: func(req *http.Request) *httpserver.RequestQueue {
319 if req.Method == http.MethodPost && reTunnelPath.MatchString(req.URL.Path) {
328 // reTunnelPath matches paths of API endpoints that go in the "tunnel"
330 var reTunnelPath = regexp.MustCompile(func() string {
331 rePathVar := regexp.MustCompile(`{.*?}`)
333 for _, endpoint := range []arvados.APIEndpoint{
334 arvados.EndpointContainerGatewayTunnel,
335 arvados.EndpointContainerGatewayTunnelCompat,
336 arvados.EndpointContainerSSH,
337 arvados.EndpointContainerSSHCompat,
342 out += `\Q/` + rePathVar.ReplaceAllString(endpoint.Path, `\E[^/]*\Q`) + `\E`
344 return "^(" + out + ")$"
347 func (c *command) requestPriority(req *http.Request, queued time.Time) int64 {
349 case req.Method == http.MethodPost && strings.HasPrefix(req.URL.Path, "/arvados/v1/containers/") && strings.HasSuffix(req.URL.Path, "/lock"):
350 // Return 503 immediately instead of queueing. We want
351 // to send feedback to dispatchcloud ASAP to stop
352 // bringing up new containers.
353 return httpserver.MinPriority
354 case req.Header.Get("Origin") != "":
355 // Handle interactive requests first. Positive
356 // priority is called "high" in aggregate metrics.
359 // Zero priority is called "normal" in aggregate
365 // If an incoming request's target vhost has an embedded collection
366 // UUID or PDH, handle it with hTrue, otherwise handle it with
369 // Facilitates routing "http://collections.example/metrics" to metrics
370 // and "http://{uuid}.collections.example/metrics" to a file in a
372 func ifCollectionInHost(hTrue, hFalse http.Handler) http.Handler {
373 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
374 if arvados.CollectionIDFromDNSName(r.Host) != "" {
375 hTrue.ServeHTTP(w, r)
377 hFalse.ServeHTTP(w, r)
382 func interceptHealthReqs(mgtToken string, checkHealth func() error, next http.Handler) http.Handler {
383 mux := httprouter.New()
384 mux.Handler("GET", "/_health/ping", &health.Handler{
387 Routes: health.Routes{"ping": checkHealth},
390 return ifCollectionInHost(next, mux)
393 // Determine listenURL (addr:port where server should bind) and
394 // internalURL (target url that client should connect to) for a
397 // If the config does not specify ListenURL, we check all of the
398 // configured InternalURLs. If there is exactly one that matches our
399 // hostname, or exactly one that matches a local interface address,
400 // then we use that as listenURL.
402 // Note that listenURL and internalURL may use different protocols
403 // (e.g., listenURL is http, but the service sits behind a proxy, so
404 // clients connect using https).
405 func getListenAddr(svcs arvados.Services, prog arvados.ServiceName, log logrus.FieldLogger) (arvados.URL, arvados.URL, error) {
406 svc, ok := svcs.Map()[prog]
408 return arvados.URL{}, arvados.URL{}, fmt.Errorf("unknown service name %q", prog)
411 if want := os.Getenv("ARVADOS_SERVICE_INTERNAL_URL"); want != "" {
412 url, err := url.Parse(want)
414 return arvados.URL{}, arvados.URL{}, fmt.Errorf("$ARVADOS_SERVICE_INTERNAL_URL (%q): %s", want, err)
419 for internalURL, conf := range svc.InternalURLs {
420 if internalURL.String() == url.String() {
421 listenURL := conf.ListenURL
422 if listenURL.Host == "" {
423 listenURL = internalURL
425 return listenURL, internalURL, nil
428 log.Warnf("possible configuration error: listening on %s (from $ARVADOS_SERVICE_INTERNAL_URL) even though configuration does not have a matching InternalURLs entry", url)
429 internalURL := arvados.URL(*url)
430 return internalURL, internalURL, nil
434 for internalURL, conf := range svc.InternalURLs {
435 listenURL := conf.ListenURL
436 if listenURL.Host == "" {
437 // If ListenURL is not specified, assume
438 // InternalURL is also usable as the listening
439 // proto/addr/port (i.e., simple case with no
440 // intermediate proxy/routing)
441 listenURL = internalURL
443 listenAddr := listenURL.Host
444 if _, _, err := net.SplitHostPort(listenAddr); err != nil {
445 // url "https://foo.example/" (with no
446 // explicit port name/number) means listen on
447 // the well-known port for the specified
448 // protocol, "foo.example:https".
449 port := listenURL.Scheme
450 if port == "ws" || port == "wss" {
451 port = "http" + port[2:]
453 listenAddr = net.JoinHostPort(listenAddr, port)
455 listener, err := net.Listen("tcp", listenAddr)
458 return listenURL, internalURL, nil
459 } else if strings.Contains(err.Error(), "cannot assign requested address") {
460 // If 'Host' specifies a different server than
461 // the current one, it'll resolve the hostname
462 // to IP address, and then fail because it
463 // can't bind an IP address it doesn't own.
466 errors = append(errors, fmt.Sprintf("%s: %s", listenURL, err))
470 return arvados.URL{}, arvados.URL{}, fmt.Errorf("could not enable the %q service on this host: %s", prog, strings.Join(errors, "; "))
472 return arvados.URL{}, arvados.URL{}, fmt.Errorf("configuration does not enable the %q service on this host", prog)
475 type contextKeyURL struct{}
477 func URLFromContext(ctx context.Context) (arvados.URL, bool) {
478 u, ok := ctx.Value(contextKeyURL{}).(arvados.URL)