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 loader.RegisterMetrics(reg)
122 // arvados_version_running{version="1.2.3~4"} 1.0
123 mVersion := prometheus.NewGaugeVec(prometheus.GaugeOpts{
124 Namespace: "arvados",
125 Name: "version_running",
126 Help: "Indicated version is running.",
127 }, []string{"version"})
128 mVersion.WithLabelValues(cmd.Version.String()).Set(1)
129 reg.MustRegister(mVersion)
131 handler := c.newHandler(ctx, cluster, cluster.SystemRootToken, reg)
132 if err = handler.CheckHealth(); err != nil {
136 instrumented := httpserver.Instrument(reg, log,
137 httpserver.HandlerWithDeadline(cluster.API.RequestTimeout.Duration(),
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),
144 BaseContext: func(net.Listener) context.Context { return ctx },
146 Addr: listenURL.Host,
148 if listenURL.Scheme == "https" {
149 tlsconfig, err := tlsConfigWithCertUpdater(cluster, logger)
151 logger.WithError(err).Errorf("cannot start %s service on %s", c.svcName, listenURL.String())
154 srv.TLSConfig = tlsconfig
160 logger.WithFields(logrus.Fields{
163 "Service": c.svcName,
164 "Version": cmd.Version.String(),
166 if _, err := daemon.SdNotify(false, "READY=1"); err != nil {
167 logger.WithError(err).Errorf("error notifying init daemon")
170 // Shut down server if caller cancels context
175 // Shut down server if handler dies
186 func getListenAddr(svcs arvados.Services, prog arvados.ServiceName, log logrus.FieldLogger) (arvados.URL, error) {
187 svc, ok := svcs.Map()[prog]
189 return arvados.URL{}, fmt.Errorf("unknown service name %q", prog)
192 if want := os.Getenv("ARVADOS_SERVICE_INTERNAL_URL"); want == "" {
193 } else if url, err := url.Parse(want); err != nil {
194 return arvados.URL{}, fmt.Errorf("$ARVADOS_SERVICE_INTERNAL_URL (%q): %s", want, err)
199 return arvados.URL(*url), nil
203 for url := range svc.InternalURLs {
204 listener, err := net.Listen("tcp", url.Host)
208 } else if strings.Contains(err.Error(), "cannot assign requested address") {
209 // If 'Host' specifies a different server than
210 // the current one, it'll resolve the hostname
211 // to IP address, and then fail because it
212 // can't bind an IP address it doesn't own.
215 errors = append(errors, fmt.Sprintf("tried %v, got %v", url, err))
219 return arvados.URL{}, fmt.Errorf("could not enable the %q service on this host: %s", prog, strings.Join(errors, "; "))
221 return arvados.URL{}, fmt.Errorf("configuration does not enable the %q service on this host", prog)
224 type contextKeyURL struct{}
226 func URLFromContext(ctx context.Context) (arvados.URL, bool) {
227 u, ok := ctx.Value(contextKeyURL{}).(arvados.URL)