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 {
34 type NewHandlerFunc func(_ context.Context, _ *arvados.Cluster, token string, registry *prometheus.Registry) Handler
37 newHandler NewHandlerFunc
38 svcName arvados.ServiceName
39 ctx context.Context // enables tests to shutdown service; no public API yet
42 // Command returns a cmd.Handler that loads site config, calls
43 // newHandler with the current cluster and node configs, and brings up
44 // an http server with the returned handler.
46 // The handler is wrapped with server middleware (adding X-Request-ID
47 // headers, logging requests/responses, etc).
48 func Command(svcName arvados.ServiceName, newHandler NewHandlerFunc) cmd.Handler {
50 newHandler: newHandler,
52 ctx: context.Background(),
56 func (c *command) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
57 log := ctxlog.New(stderr, "json", "info")
62 log.WithError(err).Error("exiting")
66 flags := flag.NewFlagSet("", flag.ContinueOnError)
67 flags.SetOutput(stderr)
69 loader := config.NewLoader(stdin, log)
70 loader.SetupFlags(flags)
71 versionFlag := flags.Bool("version", false, "Write version information to stdout and exit 0")
72 err = flags.Parse(args)
73 if err == flag.ErrHelp {
76 } else if err != nil {
78 } else if *versionFlag {
79 return cmd.Version.RunCommand(prog, args, stdin, stdout, stderr)
82 if strings.HasSuffix(prog, "controller") {
83 // Some config-loader checks try to make API calls via
84 // controller. Those can't be expected to work if this
85 // process _is_ the controller: we haven't started an
87 loader.SkipAPICalls = true
90 cfg, err := loader.Load()
94 cluster, err := cfg.GetCluster("")
99 // Now that we've read the config, replace the bootstrap
100 // logger with a new one according to the logging config.
101 log = ctxlog.New(stderr, cluster.SystemLogs.Format, cluster.SystemLogs.LogLevel)
102 logger := log.WithFields(logrus.Fields{
105 ctx := ctxlog.Context(c.ctx, logger)
107 listenURL, err := getListenAddr(cluster.Services, c.svcName, log)
111 ctx = context.WithValue(ctx, contextKeyURL{}, listenURL)
113 reg := prometheus.NewRegistry()
114 handler := c.newHandler(ctx, cluster, cluster.SystemRootToken, reg)
115 if err = handler.CheckHealth(); err != nil {
119 instrumented := httpserver.Instrument(reg, log,
120 httpserver.HandlerWithContext(ctx,
121 httpserver.AddRequestIDs(
122 httpserver.LogRequests(
123 httpserver.NewRequestLimiter(cluster.API.MaxConcurrentRequests, handler, reg)))))
124 srv := &httpserver.Server{
126 Handler: instrumented.ServeAPI(cluster.ManagementToken, instrumented),
128 Addr: listenURL.Host,
130 if listenURL.Scheme == "https" {
131 tlsconfig, err := tlsConfigWithCertUpdater(cluster, logger)
133 logger.WithError(err).Errorf("cannot start %s service on %s", c.svcName, listenURL.String())
136 srv.TLSConfig = tlsconfig
142 logger.WithFields(logrus.Fields{
145 "Service": c.svcName,
147 if _, err := daemon.SdNotify(false, "READY=1"); err != nil {
148 logger.WithError(err).Errorf("error notifying init daemon")
161 const rfc3339NanoFixed = "2006-01-02T15:04:05.000000000Z07:00"
163 func getListenAddr(svcs arvados.Services, prog arvados.ServiceName, log logrus.FieldLogger) (arvados.URL, error) {
164 svc, ok := svcs.Map()[prog]
166 return arvados.URL{}, fmt.Errorf("unknown service name %q", prog)
169 if want := os.Getenv("ARVADOS_SERVICE_INTERNAL_URL"); want == "" {
170 } else if url, err := url.Parse(want); err != nil {
171 return arvados.URL{}, fmt.Errorf("$ARVADOS_SERVICE_INTERNAL_URL (%q): %s", want, err)
173 return arvados.URL(*url), nil
177 for url := range svc.InternalURLs {
178 listener, err := net.Listen("tcp", url.Host)
182 } else if strings.Contains(err.Error(), "cannot assign requested address") {
183 // If 'Host' specifies a different server than
184 // the current one, it'll resolve the hostname
185 // to IP address, and then fail because it
186 // can't bind an IP address it doesn't own.
189 errors = append(errors, fmt.Sprintf("tried %v, got %v", url, err))
193 return arvados.URL{}, fmt.Errorf("could not enable the %q service on this host: %s", prog, strings.Join(errors, "; "))
195 return arvados.URL{}, fmt.Errorf("configuration does not enable the %q service on this host", prog)
198 type contextKeyURL struct{}
200 func URLFromContext(ctx context.Context) (arvados.URL, bool) {
201 u, ok := ctx.Value(contextKeyURL{}).(arvados.URL)