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 listenURL, internalURL, err := getListenAddr(cluster.Services, c.svcName, log)
133 ctx = context.WithValue(ctx, contextKeyURL{}, internalURL)
135 reg := prometheus.NewRegistry()
136 loader.RegisterMetrics(reg)
138 // arvados_version_running{version="1.2.3~4"} 1.0
139 mVersion := prometheus.NewGaugeVec(prometheus.GaugeOpts{
140 Namespace: "arvados",
141 Name: "version_running",
142 Help: "Indicated version is running.",
143 }, []string{"version"})
144 mVersion.WithLabelValues(cmd.Version.String()).Set(1)
145 reg.MustRegister(mVersion)
147 handler := c.newHandler(ctx, cluster, cluster.SystemRootToken, reg)
148 if err = handler.CheckHealth(); err != nil {
152 instrumented := httpserver.Instrument(reg, log,
153 httpserver.HandlerWithDeadline(cluster.API.RequestTimeout.Duration(),
154 httpserver.AddRequestIDs(
155 httpserver.Inspect(reg, cluster.ManagementToken,
156 httpserver.LogRequests(
157 interceptHealthReqs(cluster.ManagementToken, handler.CheckHealth,
158 c.requestLimiter(handler, cluster, reg)))))))
159 srv := &httpserver.Server{
161 Handler: ifCollectionInHost(instrumented, instrumented.ServeAPI(cluster.ManagementToken, instrumented)),
162 BaseContext: func(net.Listener) context.Context { return ctx },
164 Addr: listenURL.Host,
166 if listenURL.Scheme == "https" || listenURL.Scheme == "wss" {
167 tlsconfig, err := makeTLSConfig(cluster, logger)
169 logger.WithError(err).Errorf("cannot start %s service on %s", c.svcName, listenURL.String())
172 srv.TLSConfig = tlsconfig
178 logger.WithFields(logrus.Fields{
181 "Service": c.svcName,
182 "Version": cmd.Version.String(),
184 if _, err := daemon.SdNotify(false, "READY=1"); err != nil {
185 logger.WithError(err).Errorf("error notifying init daemon")
188 // Shut down server if caller cancels context
193 // Shut down server if handler dies
197 go c.requestQueueDumpCheck(cluster, prog, reg, &srv.Server, logger)
205 // If SystemLogs.RequestQueueDumpDirectory is set, monitor the
206 // server's incoming HTTP request limiters. When the number of
207 // concurrent requests in any queue ("api" or "tunnel") exceeds 90% of
208 // its maximum slots, write the /_inspect/requests data to a JSON file
209 // in the specified directory.
210 func (c *command) requestQueueDumpCheck(cluster *arvados.Cluster, prog string, reg *prometheus.Registry, srv *http.Server, logger logrus.FieldLogger) {
211 outdir := cluster.SystemLogs.RequestQueueDumpDirectory
212 if outdir == "" || cluster.ManagementToken == "" {
215 logger = logger.WithField("worker", "RequestQueueDump")
216 outfile := outdir + "/" + prog + "-requests.json"
217 for range time.NewTicker(requestQueueDumpCheckInterval).C {
218 mfs, err := reg.Gather()
220 logger.WithError(err).Warn("error getting metrics")
223 cur := map[string]int{} // queue label => current
224 max := map[string]int{} // queue label => max
225 for _, mf := range mfs {
226 for _, m := range mf.GetMetric() {
227 for _, ml := range m.GetLabel() {
228 if ml.GetName() == "queue" {
229 n := int(m.GetGauge().GetValue())
230 if name := mf.GetName(); name == "arvados_concurrent_requests" {
232 } else if name == "arvados_max_concurrent_requests" {
240 for queue, n := range cur {
241 if n > 0 && max[queue] > 0 && n >= max[queue]*9/10 {
247 req, err := http.NewRequest("GET", "/_inspect/requests", nil)
249 logger.WithError(err).Warn("error in http.NewRequest")
252 req.Header.Set("Authorization", "Bearer "+cluster.ManagementToken)
253 resp := httptest.NewRecorder()
254 srv.Handler.ServeHTTP(resp, req)
255 if code := resp.Result().StatusCode; code != http.StatusOK {
256 logger.WithField("StatusCode", code).Warn("error getting /_inspect/requests")
259 err = os.WriteFile(outfile, resp.Body.Bytes(), 0777)
261 logger.WithError(err).Warn("error writing file")
268 // Set up a httpserver.RequestLimiter with separate queues/streams for
269 // API requests (obeying MaxConcurrentRequests etc) and gateway tunnel
270 // requests (obeying MaxGatewayTunnels).
271 func (c *command) requestLimiter(handler http.Handler, cluster *arvados.Cluster, reg *prometheus.Registry) http.Handler {
272 maxReqs := cluster.API.MaxConcurrentRequests
273 if maxRails := cluster.API.MaxConcurrentRailsRequests; maxRails > 0 &&
274 (maxRails < maxReqs || maxReqs == 0) &&
275 c.svcName == arvados.ServiceNameController {
276 // Ideally, we would accept up to
277 // MaxConcurrentRequests, and apply the
278 // MaxConcurrentRailsRequests limit only for requests
279 // that require calling upstream to RailsAPI. But for
280 // now we make the simplifying assumption that every
281 // controller request causes an upstream RailsAPI
285 rqAPI := &httpserver.RequestQueue{
287 MaxConcurrent: maxReqs,
288 MaxQueue: cluster.API.MaxQueuedRequests,
289 MaxQueueTimeForMinPriority: cluster.API.MaxQueueTimeForLockRequests.Duration(),
291 rqTunnel := &httpserver.RequestQueue{
293 MaxConcurrent: cluster.API.MaxGatewayTunnels,
296 return &httpserver.RequestLimiter{
298 Priority: c.requestPriority,
300 Queue: func(req *http.Request) *httpserver.RequestQueue {
301 if req.Method == http.MethodPost && reTunnelPath.MatchString(req.URL.Path) {
310 // reTunnelPath matches paths of API endpoints that go in the "tunnel"
312 var reTunnelPath = regexp.MustCompile(func() string {
313 rePathVar := regexp.MustCompile(`{.*?}`)
315 for _, endpoint := range []arvados.APIEndpoint{
316 arvados.EndpointContainerGatewayTunnel,
317 arvados.EndpointContainerGatewayTunnelCompat,
318 arvados.EndpointContainerSSH,
319 arvados.EndpointContainerSSHCompat,
324 out += `\Q/` + rePathVar.ReplaceAllString(endpoint.Path, `\E[^/]*\Q`) + `\E`
326 return "^(" + out + ")$"
329 func (c *command) requestPriority(req *http.Request, queued time.Time) int64 {
331 case req.Method == http.MethodPost && strings.HasPrefix(req.URL.Path, "/arvados/v1/containers/") && strings.HasSuffix(req.URL.Path, "/lock"):
332 // Return 503 immediately instead of queueing. We want
333 // to send feedback to dispatchcloud ASAP to stop
334 // bringing up new containers.
335 return httpserver.MinPriority
336 case req.Header.Get("Origin") != "":
337 // Handle interactive requests first. Positive
338 // priority is called "high" in aggregate metrics.
341 // Zero priority is called "normal" in aggregate
347 // If an incoming request's target vhost has an embedded collection
348 // UUID or PDH, handle it with hTrue, otherwise handle it with
351 // Facilitates routing "http://collections.example/metrics" to metrics
352 // and "http://{uuid}.collections.example/metrics" to a file in a
354 func ifCollectionInHost(hTrue, hFalse http.Handler) http.Handler {
355 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
356 if arvados.CollectionIDFromDNSName(r.Host) != "" {
357 hTrue.ServeHTTP(w, r)
359 hFalse.ServeHTTP(w, r)
364 func interceptHealthReqs(mgtToken string, checkHealth func() error, next http.Handler) http.Handler {
365 mux := httprouter.New()
366 mux.Handler("GET", "/_health/ping", &health.Handler{
369 Routes: health.Routes{"ping": checkHealth},
372 return ifCollectionInHost(next, mux)
375 // Determine listenURL (addr:port where server should bind) and
376 // internalURL (target url that client should connect to) for a
379 // If the config does not specify ListenURL, we check all of the
380 // configured InternalURLs. If there is exactly one that matches our
381 // hostname, or exactly one that matches a local interface address,
382 // then we use that as listenURL.
384 // Note that listenURL and internalURL may use different protocols
385 // (e.g., listenURL is http, but the service sits behind a proxy, so
386 // clients connect using https).
387 func getListenAddr(svcs arvados.Services, prog arvados.ServiceName, log logrus.FieldLogger) (arvados.URL, arvados.URL, error) {
388 svc, ok := svcs.Map()[prog]
390 return arvados.URL{}, arvados.URL{}, fmt.Errorf("unknown service name %q", prog)
393 if want := os.Getenv("ARVADOS_SERVICE_INTERNAL_URL"); want != "" {
394 url, err := url.Parse(want)
396 return arvados.URL{}, arvados.URL{}, fmt.Errorf("$ARVADOS_SERVICE_INTERNAL_URL (%q): %s", want, err)
401 for internalURL, conf := range svc.InternalURLs {
402 if internalURL.String() == url.String() {
403 listenURL := conf.ListenURL
404 if listenURL.Host == "" {
405 listenURL = internalURL
407 return listenURL, internalURL, nil
410 log.Warnf("possible configuration error: listening on %s (from $ARVADOS_SERVICE_INTERNAL_URL) even though configuration does not have a matching InternalURLs entry", url)
411 internalURL := arvados.URL(*url)
412 return internalURL, internalURL, nil
416 for internalURL, conf := range svc.InternalURLs {
417 listenURL := conf.ListenURL
418 if listenURL.Host == "" {
419 // If ListenURL is not specified, assume
420 // InternalURL is also usable as the listening
421 // proto/addr/port (i.e., simple case with no
422 // intermediate proxy/routing)
423 listenURL = internalURL
425 listenAddr := listenURL.Host
426 if _, _, err := net.SplitHostPort(listenAddr); err != nil {
427 // url "https://foo.example/" (with no
428 // explicit port name/number) means listen on
429 // the well-known port for the specified
430 // protocol, "foo.example:https".
431 port := listenURL.Scheme
432 if port == "ws" || port == "wss" {
433 port = "http" + port[2:]
435 listenAddr = net.JoinHostPort(listenAddr, port)
437 listener, err := net.Listen("tcp", listenAddr)
440 return listenURL, internalURL, nil
441 } else if strings.Contains(err.Error(), "cannot assign requested address") {
442 // If 'Host' specifies a different server than
443 // the current one, it'll resolve the hostname
444 // to IP address, and then fail because it
445 // can't bind an IP address it doesn't own.
448 errors = append(errors, fmt.Sprintf("%s: %s", listenURL, err))
452 return arvados.URL{}, arvados.URL{}, fmt.Errorf("could not enable the %q service on this host: %s", prog, strings.Join(errors, "; "))
454 return arvados.URL{}, arvados.URL{}, fmt.Errorf("configuration does not enable the %q service on this host", prog)
457 type contextKeyURL struct{}
459 func URLFromContext(ctx context.Context) (arvados.URL, bool) {
460 u, ok := ctx.Value(contextKeyURL{}).(arvados.URL)