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.
20 "git.arvados.org/arvados.git/lib/cmd"
21 "git.arvados.org/arvados.git/lib/config"
22 "git.arvados.org/arvados.git/sdk/go/arvados"
23 "git.arvados.org/arvados.git/sdk/go/ctxlog"
24 "git.arvados.org/arvados.git/sdk/go/httpserver"
25 "github.com/coreos/go-systemd/daemon"
26 "github.com/prometheus/client_golang/prometheus"
27 "github.com/sirupsen/logrus"
30 type Handler interface {
33 Done() <-chan struct{}
36 type NewHandlerFunc func(_ context.Context, _ *arvados.Cluster, token string, registry *prometheus.Registry) Handler
39 newHandler NewHandlerFunc
40 svcName arvados.ServiceName
41 ctx context.Context // enables tests to shutdown service; no public API yet
44 // Command returns a cmd.Handler that loads site config, calls
45 // newHandler with the current cluster and node configs, and brings up
46 // an http server with the returned handler.
48 // The handler is wrapped with server middleware (adding X-Request-ID
49 // headers, logging requests/responses, etc).
50 func Command(svcName arvados.ServiceName, newHandler NewHandlerFunc) cmd.Handler {
52 newHandler: newHandler,
54 ctx: context.Background(),
58 func (c *command) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
59 log := ctxlog.New(stderr, "json", "info")
64 log.WithError(err).Error("exiting")
68 flags := flag.NewFlagSet("", flag.ContinueOnError)
69 flags.SetOutput(stderr)
71 loader := config.NewLoader(stdin, log)
72 loader.SetupFlags(flags)
73 versionFlag := flags.Bool("version", false, "Write version information to stdout and exit 0")
74 pprofAddr := flags.String("pprof", "", "Serve Go profile data at `[addr]:port`")
75 err = flags.Parse(args)
76 if err == flag.ErrHelp {
79 } else if err != nil {
81 } else if *versionFlag {
82 return cmd.Version.RunCommand(prog, args, stdin, stdout, stderr)
87 log.Println(http.ListenAndServe(*pprofAddr, nil))
91 if strings.HasSuffix(prog, "controller") {
92 // Some config-loader checks try to make API calls via
93 // controller. Those can't be expected to work if this
94 // process _is_ the controller: we haven't started an
96 loader.SkipAPICalls = true
99 cfg, err := loader.Load()
103 cluster, err := cfg.GetCluster("")
108 // Now that we've read the config, replace the bootstrap
109 // logger with a new one according to the logging config.
110 log = ctxlog.New(stderr, cluster.SystemLogs.Format, cluster.SystemLogs.LogLevel)
111 logger := log.WithFields(logrus.Fields{
114 ctx := ctxlog.Context(c.ctx, logger)
116 listenURL, err := getListenAddr(cluster.Services, c.svcName, log)
120 ctx = context.WithValue(ctx, contextKeyURL{}, listenURL)
122 reg := prometheus.NewRegistry()
123 handler := c.newHandler(ctx, cluster, cluster.SystemRootToken, reg)
124 if err = handler.CheckHealth(); err != nil {
128 instrumented := httpserver.Instrument(reg, log,
129 httpserver.HandlerWithDeadline(cluster.API.RequestTimeout.Duration(),
130 httpserver.AddRequestIDs(
131 httpserver.LogRequests(
132 httpserver.NewRequestLimiter(cluster.API.MaxConcurrentRequests, handler, reg)))))
133 srv := &httpserver.Server{
135 Handler: instrumented.ServeAPI(cluster.ManagementToken, instrumented),
136 BaseContext: func(net.Listener) context.Context { return ctx },
138 Addr: listenURL.Host,
140 if listenURL.Scheme == "https" {
141 tlsconfig, err := tlsConfigWithCertUpdater(cluster, logger)
143 logger.WithError(err).Errorf("cannot start %s service on %s", c.svcName, listenURL.String())
146 srv.TLSConfig = tlsconfig
152 logger.WithFields(logrus.Fields{
155 "Service": c.svcName,
157 if _, err := daemon.SdNotify(false, "READY=1"); err != nil {
158 logger.WithError(err).Errorf("error notifying init daemon")
161 // Shut down server if caller cancels context
166 // Shut down server if handler dies
177 func getListenAddr(svcs arvados.Services, prog arvados.ServiceName, log logrus.FieldLogger) (arvados.URL, error) {
178 svc, ok := svcs.Map()[prog]
180 return arvados.URL{}, fmt.Errorf("unknown service name %q", prog)
183 if want := os.Getenv("ARVADOS_SERVICE_INTERNAL_URL"); want == "" {
184 } else if url, err := url.Parse(want); err != nil {
185 return arvados.URL{}, fmt.Errorf("$ARVADOS_SERVICE_INTERNAL_URL (%q): %s", want, err)
190 return arvados.URL(*url), nil
194 for url := range svc.InternalURLs {
195 listener, err := net.Listen("tcp", url.Host)
199 } else if strings.Contains(err.Error(), "cannot assign requested address") {
200 // If 'Host' specifies a different server than
201 // the current one, it'll resolve the hostname
202 // to IP address, and then fail because it
203 // can't bind an IP address it doesn't own.
206 errors = append(errors, fmt.Sprintf("tried %v, got %v", url, err))
210 return arvados.URL{}, fmt.Errorf("could not enable the %q service on this host: %s", prog, strings.Join(errors, "; "))
212 return arvados.URL{}, fmt.Errorf("configuration does not enable the %q service on this host", prog)
215 type contextKeyURL struct{}
217 func URLFromContext(ctx context.Context) (arvados.URL, bool) {
218 u, ok := ctx.Value(contextKeyURL{}).(arvados.URL)