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 cfg, err := loader.Load()
86 cluster, err := cfg.GetCluster("")
91 // Now that we've read the config, replace the bootstrap
92 // logger with a new one according to the logging config.
93 log = ctxlog.New(stderr, cluster.SystemLogs.Format, cluster.SystemLogs.LogLevel)
94 logger := log.WithFields(logrus.Fields{
97 ctx := ctxlog.Context(c.ctx, logger)
99 listenURL, err := getListenAddr(cluster.Services, c.svcName)
103 ctx = context.WithValue(ctx, contextKeyURL{}, listenURL)
105 if cluster.SystemRootToken == "" {
106 logger.Warn("SystemRootToken missing from cluster config, falling back to ARVADOS_API_TOKEN environment variable")
107 cluster.SystemRootToken = os.Getenv("ARVADOS_API_TOKEN")
109 if cluster.Services.Controller.ExternalURL.Host == "" {
110 logger.Warn("Services.Controller.ExternalURL missing from cluster config, falling back to ARVADOS_API_HOST(_INSECURE) environment variables")
111 u, err := url.Parse("https://" + os.Getenv("ARVADOS_API_HOST"))
113 err = fmt.Errorf("ARVADOS_API_HOST: %s", err)
116 cluster.Services.Controller.ExternalURL = arvados.URL(*u)
117 if i := os.Getenv("ARVADOS_API_HOST_INSECURE"); i != "" && i != "0" {
118 cluster.TLS.Insecure = true
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.HandlerWithContext(ctx,
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),
137 Addr: listenURL.Host,
139 if listenURL.Scheme == "https" {
140 tlsconfig, err := tlsConfigWithCertUpdater(cluster, logger)
142 logger.WithError(err).Errorf("cannot start %s service on %s", c.svcName, listenURL.String())
145 srv.TLSConfig = tlsconfig
151 logger.WithFields(logrus.Fields{
154 "Service": c.svcName,
156 if _, err := daemon.SdNotify(false, "READY=1"); err != nil {
157 logger.WithError(err).Errorf("error notifying init daemon")
170 const rfc3339NanoFixed = "2006-01-02T15:04:05.000000000Z07:00"
172 func getListenAddr(svcs arvados.Services, prog arvados.ServiceName) (arvados.URL, error) {
173 svc, ok := svcs.Map()[prog]
175 return arvados.URL{}, fmt.Errorf("unknown service name %q", prog)
177 for url := range svc.InternalURLs {
178 if strings.HasPrefix(url.Host, "localhost:") {
181 listener, err := net.Listen("tcp", url.Host)
187 return arvados.URL{}, fmt.Errorf("configuration does not enable the %s service on this host", prog)
190 type contextKeyURL struct{}
192 func URLFromContext(ctx context.Context) (arvados.URL, bool) {
193 u, ok := ctx.Value(contextKeyURL{}).(arvados.URL)