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 if ok, code := cmd.ParseFlags(flags, prog, args, "", stderr); !ok {
77 } else if *versionFlag {
78 return cmd.Version.RunCommand(prog, args, stdin, stdout, stderr)
83 log.Println(http.ListenAndServe(*pprofAddr, nil))
87 if strings.HasSuffix(prog, "controller") {
88 // Some config-loader checks try to make API calls via
89 // controller. Those can't be expected to work if this
90 // process _is_ the controller: we haven't started an
92 loader.SkipAPICalls = true
95 cfg, err := loader.Load()
99 cluster, err := cfg.GetCluster("")
104 // Now that we've read the config, replace the bootstrap
105 // logger with a new one according to the logging config.
106 log = ctxlog.New(stderr, cluster.SystemLogs.Format, cluster.SystemLogs.LogLevel)
107 logger := log.WithFields(logrus.Fields{
109 "ClusterID": cluster.ClusterID,
111 ctx := ctxlog.Context(c.ctx, logger)
113 listenURL, err := getListenAddr(cluster.Services, c.svcName, log)
117 ctx = context.WithValue(ctx, contextKeyURL{}, listenURL)
119 reg := prometheus.NewRegistry()
120 handler := c.newHandler(ctx, cluster, cluster.SystemRootToken, reg)
121 if err = handler.CheckHealth(); err != nil {
125 instrumented := httpserver.Instrument(reg, log,
126 httpserver.HandlerWithDeadline(cluster.API.RequestTimeout.Duration(),
127 httpserver.AddRequestIDs(
128 httpserver.LogRequests(
129 httpserver.NewRequestLimiter(cluster.API.MaxConcurrentRequests, handler, reg)))))
130 srv := &httpserver.Server{
132 Handler: instrumented.ServeAPI(cluster.ManagementToken, instrumented),
133 BaseContext: func(net.Listener) context.Context { return ctx },
135 Addr: listenURL.Host,
137 if listenURL.Scheme == "https" {
138 tlsconfig, err := tlsConfigWithCertUpdater(cluster, logger)
140 logger.WithError(err).Errorf("cannot start %s service on %s", c.svcName, listenURL.String())
143 srv.TLSConfig = tlsconfig
149 logger.WithFields(logrus.Fields{
152 "Service": c.svcName,
153 "Version": cmd.Version.String(),
155 if _, err := daemon.SdNotify(false, "READY=1"); err != nil {
156 logger.WithError(err).Errorf("error notifying init daemon")
159 // Shut down server if caller cancels context
164 // Shut down server if handler dies
175 func getListenAddr(svcs arvados.Services, prog arvados.ServiceName, log logrus.FieldLogger) (arvados.URL, error) {
176 svc, ok := svcs.Map()[prog]
178 return arvados.URL{}, fmt.Errorf("unknown service name %q", prog)
181 if want := os.Getenv("ARVADOS_SERVICE_INTERNAL_URL"); want == "" {
182 } else if url, err := url.Parse(want); err != nil {
183 return arvados.URL{}, fmt.Errorf("$ARVADOS_SERVICE_INTERNAL_URL (%q): %s", want, err)
188 return arvados.URL(*url), nil
192 for url := range svc.InternalURLs {
193 listener, err := net.Listen("tcp", url.Host)
197 } else if strings.Contains(err.Error(), "cannot assign requested address") {
198 // If 'Host' specifies a different server than
199 // the current one, it'll resolve the hostname
200 // to IP address, and then fail because it
201 // can't bind an IP address it doesn't own.
204 errors = append(errors, fmt.Sprintf("tried %v, got %v", url, err))
208 return arvados.URL{}, fmt.Errorf("could not enable the %q service on this host: %s", prog, strings.Join(errors, "; "))
210 return arvados.URL{}, fmt.Errorf("configuration does not enable the %q service on this host", prog)
213 type contextKeyURL struct{}
215 func URLFromContext(ctx context.Context) (arvados.URL, bool) {
216 u, ok := ctx.Value(contextKeyURL{}).(arvados.URL)