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.curoverse.com/arvados.git/lib/cmd"
20 "git.curoverse.com/arvados.git/lib/config"
21 "git.curoverse.com/arvados.git/sdk/go/arvados"
22 "git.curoverse.com/arvados.git/sdk/go/ctxlog"
23 "git.curoverse.com/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).Info("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)
111 ctx = context.WithValue(ctx, contextKeyURL{}, listenURL)
113 if cluster.SystemRootToken == "" {
114 logger.Warn("SystemRootToken missing from cluster config, falling back to ARVADOS_API_TOKEN environment variable")
115 cluster.SystemRootToken = os.Getenv("ARVADOS_API_TOKEN")
117 if cluster.Services.Controller.ExternalURL.Host == "" {
118 logger.Warn("Services.Controller.ExternalURL missing from cluster config, falling back to ARVADOS_API_HOST(_INSECURE) environment variables")
119 u, err := url.Parse("https://" + os.Getenv("ARVADOS_API_HOST"))
121 err = fmt.Errorf("ARVADOS_API_HOST: %s", err)
124 cluster.Services.Controller.ExternalURL = arvados.URL(*u)
125 if i := os.Getenv("ARVADOS_API_HOST_INSECURE"); i != "" && i != "0" {
126 cluster.TLS.Insecure = true
130 reg := prometheus.NewRegistry()
131 handler := c.newHandler(ctx, cluster, cluster.SystemRootToken, reg)
132 if err = handler.CheckHealth(); err != nil {
136 instrumented := httpserver.Instrument(reg, log,
137 httpserver.HandlerWithContext(ctx,
138 httpserver.AddRequestIDs(
139 httpserver.LogRequests(
140 httpserver.NewRequestLimiter(cluster.API.MaxConcurrentRequests, handler, reg)))))
141 srv := &httpserver.Server{
143 Handler: instrumented.ServeAPI(cluster.ManagementToken, instrumented),
145 Addr: listenURL.Host,
147 if listenURL.Scheme == "https" {
148 tlsconfig, err := tlsConfigWithCertUpdater(cluster, logger)
150 logger.WithError(err).Errorf("cannot start %s service on %s", c.svcName, listenURL.String())
153 srv.TLSConfig = tlsconfig
159 logger.WithFields(logrus.Fields{
162 "Service": c.svcName,
164 if _, err := daemon.SdNotify(false, "READY=1"); err != nil {
165 logger.WithError(err).Errorf("error notifying init daemon")
178 const rfc3339NanoFixed = "2006-01-02T15:04:05.000000000Z07:00"
180 func getListenAddr(svcs arvados.Services, prog arvados.ServiceName) (arvados.URL, error) {
181 svc, ok := svcs.Map()[prog]
183 return arvados.URL{}, fmt.Errorf("unknown service name %q", prog)
185 for url := range svc.InternalURLs {
186 if strings.HasPrefix(url.Host, "localhost:") {
189 listener, err := net.Listen("tcp", url.Host)
195 return arvados.URL{}, fmt.Errorf("configuration does not enable the %s 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)