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.
19 "git.arvados.org/arvados.git/lib/cmd"
20 "git.arvados.org/arvados.git/lib/config"
21 "git.arvados.org/arvados.git/sdk/go/arvados"
22 "git.arvados.org/arvados.git/sdk/go/ctxlog"
23 "git.arvados.org/arvados.git/sdk/go/httpserver"
24 "github.com/coreos/go-systemd/daemon"
25 "github.com/prometheus/client_golang/prometheus"
26 "github.com/sirupsen/logrus"
29 type Handler interface {
32 Done() <-chan struct{}
35 type NewHandlerFunc func(_ context.Context, _ *arvados.Cluster, token string, registry *prometheus.Registry) Handler
38 newHandler NewHandlerFunc
39 svcName arvados.ServiceName
40 ctx context.Context // enables tests to shutdown service; no public API yet
43 // Command returns a cmd.Handler that loads site config, calls
44 // newHandler with the current cluster and node configs, and brings up
45 // an http server with the returned handler.
47 // The handler is wrapped with server middleware (adding X-Request-ID
48 // headers, logging requests/responses, etc).
49 func Command(svcName arvados.ServiceName, newHandler NewHandlerFunc) cmd.Handler {
51 newHandler: newHandler,
53 ctx: context.Background(),
57 func (c *command) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
58 log := ctxlog.New(stderr, "json", "info")
63 log.WithError(err).Error("exiting")
67 flags := flag.NewFlagSet("", flag.ContinueOnError)
68 flags.SetOutput(stderr)
70 loader := config.NewLoader(stdin, log)
71 loader.SetupFlags(flags)
72 versionFlag := flags.Bool("version", false, "Write version information to stdout and exit 0")
73 err = flags.Parse(args)
74 if err == flag.ErrHelp {
77 } else if err != nil {
79 } else if *versionFlag {
80 return cmd.Version.RunCommand(prog, args, stdin, stdout, stderr)
83 if strings.HasSuffix(prog, "controller") {
84 // Some config-loader checks try to make API calls via
85 // controller. Those can't be expected to work if this
86 // process _is_ the controller: we haven't started an
88 loader.SkipAPICalls = true
91 cfg, err := loader.Load()
95 cluster, err := cfg.GetCluster("")
100 // Now that we've read the config, replace the bootstrap
101 // logger with a new one according to the logging config.
102 log = ctxlog.New(stderr, cluster.SystemLogs.Format, cluster.SystemLogs.LogLevel)
103 logger := log.WithFields(logrus.Fields{
106 ctx := ctxlog.Context(c.ctx, logger)
108 listenURL, err := getListenAddr(cluster.Services, c.svcName, log)
112 ctx = context.WithValue(ctx, contextKeyURL{}, listenURL)
114 reg := prometheus.NewRegistry()
115 handler := c.newHandler(ctx, cluster, cluster.SystemRootToken, reg)
116 if err = handler.CheckHealth(); err != nil {
120 instrumented := httpserver.Instrument(reg, log,
121 httpserver.HandlerWithContext(ctx,
122 httpserver.AddRequestIDs(
123 httpserver.LogRequests(
124 httpserver.NewRequestLimiter(cluster.API.MaxConcurrentRequests, handler, reg)))))
125 srv := &httpserver.Server{
127 Handler: instrumented.ServeAPI(cluster.ManagementToken, instrumented),
129 Addr: listenURL.Host,
131 if listenURL.Scheme == "https" {
132 tlsconfig, err := tlsConfigWithCertUpdater(cluster, logger)
134 logger.WithError(err).Errorf("cannot start %s service on %s", c.svcName, listenURL.String())
137 srv.TLSConfig = tlsconfig
143 logger.WithFields(logrus.Fields{
146 "Service": c.svcName,
148 if _, err := daemon.SdNotify(false, "READY=1"); err != nil {
149 logger.WithError(err).Errorf("error notifying init daemon")
152 // Shut down server if caller cancels context
157 // Shut down server if handler dies
168 const rfc3339NanoFixed = "2006-01-02T15:04:05.000000000Z07:00"
170 func getListenAddr(svcs arvados.Services, prog arvados.ServiceName, log logrus.FieldLogger) (arvados.URL, error) {
171 svc, ok := svcs.Map()[prog]
173 return arvados.URL{}, fmt.Errorf("unknown service name %q", prog)
176 if want := os.Getenv("ARVADOS_SERVICE_INTERNAL_URL"); want == "" {
177 } else if url, err := url.Parse(want); err != nil {
178 return arvados.URL{}, fmt.Errorf("$ARVADOS_SERVICE_INTERNAL_URL (%q): %s", want, err)
183 return arvados.URL(*url), nil
187 for url := range svc.InternalURLs {
188 listener, err := net.Listen("tcp", url.Host)
192 } else if strings.Contains(err.Error(), "cannot assign requested address") {
193 // If 'Host' specifies a different server than
194 // the current one, it'll resolve the hostname
195 // to IP address, and then fail because it
196 // can't bind an IP address it doesn't own.
199 errors = append(errors, fmt.Sprintf("tried %v, got %v", url, err))
203 return arvados.URL{}, fmt.Errorf("could not enable the %q service on this host: %s", prog, strings.Join(errors, "; "))
205 return arvados.URL{}, fmt.Errorf("configuration does not enable the %q service on this host", prog)
208 type contextKeyURL struct{}
210 func URLFromContext(ctx context.Context) (arvados.URL, bool) {
211 u, ok := ctx.Value(contextKeyURL{}).(arvados.URL)