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/auth"
24 "git.arvados.org/arvados.git/sdk/go/ctxlog"
25 "git.arvados.org/arvados.git/sdk/go/health"
26 "git.arvados.org/arvados.git/sdk/go/httpserver"
27 "github.com/coreos/go-systemd/daemon"
28 "github.com/julienschmidt/httprouter"
29 "github.com/prometheus/client_golang/prometheus"
30 "github.com/prometheus/client_golang/prometheus/promhttp"
31 "github.com/sirupsen/logrus"
34 type Handler interface {
37 Done() <-chan struct{}
40 type NewHandlerFunc func(_ context.Context, _ *arvados.Cluster, token string, registry *prometheus.Registry) Handler
43 newHandler NewHandlerFunc
44 svcName arvados.ServiceName
45 ctx context.Context // enables tests to shutdown service; no public API yet
48 // Command returns a cmd.Handler that loads site config, calls
49 // newHandler with the current cluster and node configs, and brings up
50 // an http server with the returned handler.
52 // The handler is wrapped with server middleware (adding X-Request-ID
53 // headers, logging requests/responses, etc).
54 func Command(svcName arvados.ServiceName, newHandler NewHandlerFunc) cmd.Handler {
56 newHandler: newHandler,
58 ctx: context.Background(),
62 func (c *command) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
63 log := ctxlog.New(stderr, "json", "info")
68 log.WithError(err).Error("exiting")
72 flags := flag.NewFlagSet("", flag.ContinueOnError)
73 flags.SetOutput(stderr)
75 loader := config.NewLoader(stdin, log)
76 loader.SetupFlags(flags)
77 versionFlag := flags.Bool("version", false, "Write version information to stdout and exit 0")
78 pprofAddr := flags.String("pprof", "", "Serve Go profile data at `[addr]:port`")
79 if ok, code := cmd.ParseFlags(flags, prog, args, "", stderr); !ok {
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{
113 "ClusterID": cluster.ClusterID,
115 ctx := ctxlog.Context(c.ctx, logger)
117 listenURL, err := getListenAddr(cluster.Services, c.svcName, log)
121 ctx = context.WithValue(ctx, contextKeyURL{}, listenURL)
123 reg := prometheus.NewRegistry()
124 handler := c.newHandler(ctx, cluster, cluster.SystemRootToken, reg)
125 if err = handler.CheckHealth(); err != nil {
129 instrumented := httpserver.Instrument(reg, log,
130 httpserver.HandlerWithDeadline(cluster.API.RequestTimeout.Duration(),
131 httpserver.AddRequestIDs(
132 httpserver.LogRequests(
133 interceptHealthReqs(cluster.ManagementToken, handler.CheckHealth,
134 interceptMetricsReqs(cluster.ManagementToken, reg, log,
135 httpserver.NewRequestLimiter(cluster.API.MaxConcurrentRequests, handler, reg)))))))
136 srv := &httpserver.Server{
138 Handler: instrumented.ServeAPI(cluster.ManagementToken, instrumented),
139 BaseContext: func(net.Listener) context.Context { return ctx },
141 Addr: listenURL.Host,
143 if listenURL.Scheme == "https" {
144 tlsconfig, err := tlsConfigWithCertUpdater(cluster, logger)
146 logger.WithError(err).Errorf("cannot start %s service on %s", c.svcName, listenURL.String())
149 srv.TLSConfig = tlsconfig
155 logger.WithFields(logrus.Fields{
158 "Service": c.svcName,
159 "Version": cmd.Version.String(),
161 if _, err := daemon.SdNotify(false, "READY=1"); err != nil {
162 logger.WithError(err).Errorf("error notifying init daemon")
165 // Shut down server if caller cancels context
170 // Shut down server if handler dies
181 func interceptHealthReqs(mgtToken string, checkHealth func() error, next http.Handler) http.Handler {
182 mux := httprouter.New()
183 mux.Handler("GET", "/_health/ping", &health.Handler{
186 Routes: health.Routes{"ping": checkHealth},
192 func interceptMetricsReqs(mgtToken string, reg *prometheus.Registry, log logrus.FieldLogger, next http.Handler) http.Handler {
193 mux := httprouter.New()
194 metricsH := auth.RequireLiteralToken(mgtToken,
195 promhttp.HandlerFor(reg, promhttp.HandlerOpts{
198 mux.Handler("GET", "/metrics", metricsH)
199 mux.Handler("GET", "/metrics.json", metricsH)
204 func getListenAddr(svcs arvados.Services, prog arvados.ServiceName, log logrus.FieldLogger) (arvados.URL, error) {
205 svc, ok := svcs.Map()[prog]
207 return arvados.URL{}, fmt.Errorf("unknown service name %q", prog)
210 if want := os.Getenv("ARVADOS_SERVICE_INTERNAL_URL"); want == "" {
211 } else if url, err := url.Parse(want); err != nil {
212 return arvados.URL{}, fmt.Errorf("$ARVADOS_SERVICE_INTERNAL_URL (%q): %s", want, err)
217 return arvados.URL(*url), nil
221 for url := range svc.InternalURLs {
222 listener, err := net.Listen("tcp", url.Host)
226 } else if strings.Contains(err.Error(), "cannot assign requested address") {
227 // If 'Host' specifies a different server than
228 // the current one, it'll resolve the hostname
229 // to IP address, and then fail because it
230 // can't bind an IP address it doesn't own.
233 errors = append(errors, fmt.Sprintf("tried %v, got %v", url, err))
237 return arvados.URL{}, fmt.Errorf("could not enable the %q service on this host: %s", prog, strings.Join(errors, "; "))
239 return arvados.URL{}, fmt.Errorf("configuration does not enable the %q service on this host", prog)
242 type contextKeyURL struct{}
244 func URLFromContext(ctx context.Context) (arvados.URL, bool) {
245 u, ok := ctx.Value(contextKeyURL{}).(arvados.URL)