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/health"
25 "git.arvados.org/arvados.git/sdk/go/httpserver"
26 "github.com/coreos/go-systemd/daemon"
27 "github.com/julienschmidt/httprouter"
28 "github.com/prometheus/client_golang/prometheus"
29 "github.com/sirupsen/logrus"
32 type Handler interface {
35 // Done returns a channel that closes when the handler shuts
36 // itself down, or nil if this never happens.
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)
78 // prog is [keepstore, keep-web, git-httpd, ...] but the
79 // legacy config flags are [-legacy-keepstore-config,
80 // -legacy-keepweb-config, -legacy-git-httpd-config, ...]
81 legacyFlag := "-legacy-" + strings.Replace(prog, "keep-", "keep", 1) + "-config"
82 args = loader.MungeLegacyConfigArgs(log, args, legacyFlag)
84 versionFlag := flags.Bool("version", false, "Write version information to stdout and exit 0")
85 pprofAddr := flags.String("pprof", "", "Serve Go profile data at `[addr]:port`")
86 if ok, code := cmd.ParseFlags(flags, prog, args, "", stderr); !ok {
88 } else if *versionFlag {
89 return cmd.Version.RunCommand(prog, args, stdin, stdout, stderr)
94 log.Println(http.ListenAndServe(*pprofAddr, nil))
98 if strings.HasSuffix(prog, "controller") {
99 // Some config-loader checks try to make API calls via
100 // controller. Those can't be expected to work if this
101 // process _is_ the controller: we haven't started an
103 loader.SkipAPICalls = true
106 cfg, err := loader.Load()
110 cluster, err := cfg.GetCluster("")
115 // Now that we've read the config, replace the bootstrap
116 // logger with a new one according to the logging config.
117 log = ctxlog.New(stderr, cluster.SystemLogs.Format, cluster.SystemLogs.LogLevel)
118 logger := log.WithFields(logrus.Fields{
120 "ClusterID": cluster.ClusterID,
122 ctx := ctxlog.Context(c.ctx, logger)
124 listenURL, err := getListenAddr(cluster.Services, c.svcName, log)
128 ctx = context.WithValue(ctx, contextKeyURL{}, listenURL)
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.HandlerWithDeadline(cluster.API.RequestTimeout.Duration(),
138 httpserver.AddRequestIDs(
139 httpserver.LogRequests(
140 interceptHealthReqs(cluster.ManagementToken, handler.CheckHealth,
141 httpserver.NewRequestLimiter(cluster.API.MaxConcurrentRequests, handler, reg))))))
142 srv := &httpserver.Server{
144 Handler: ifCollectionInHost(instrumented, instrumented.ServeAPI(cluster.ManagementToken, instrumented)),
145 BaseContext: func(net.Listener) context.Context { return ctx },
147 Addr: listenURL.Host,
149 if listenURL.Scheme == "https" {
150 tlsconfig, err := tlsConfigWithCertUpdater(cluster, logger)
152 logger.WithError(err).Errorf("cannot start %s service on %s", c.svcName, listenURL.String())
155 srv.TLSConfig = tlsconfig
161 logger.WithFields(logrus.Fields{
164 "Service": c.svcName,
165 "Version": cmd.Version.String(),
167 if _, err := daemon.SdNotify(false, "READY=1"); err != nil {
168 logger.WithError(err).Errorf("error notifying init daemon")
171 // Shut down server if caller cancels context
176 // Shut down server if handler dies
187 // If an incoming request's target vhost has an embedded collection
188 // UUID or PDH, handle it with hTrue, otherwise handle it with
191 // Facilitates routing "http://collections.example/metrics" to metrics
192 // and "http://{uuid}.collections.example/metrics" to a file in a
194 func ifCollectionInHost(hTrue, hFalse http.Handler) http.Handler {
195 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
196 if arvados.CollectionIDFromDNSName(r.Host) != "" {
197 hTrue.ServeHTTP(w, r)
199 hFalse.ServeHTTP(w, r)
204 func interceptHealthReqs(mgtToken string, checkHealth func() error, next http.Handler) http.Handler {
205 mux := httprouter.New()
206 mux.Handler("GET", "/_health/ping", &health.Handler{
209 Routes: health.Routes{"ping": checkHealth},
212 return ifCollectionInHost(next, mux)
215 func getListenAddr(svcs arvados.Services, prog arvados.ServiceName, log logrus.FieldLogger) (arvados.URL, error) {
216 svc, ok := svcs.Map()[prog]
218 return arvados.URL{}, fmt.Errorf("unknown service name %q", prog)
221 if want := os.Getenv("ARVADOS_SERVICE_INTERNAL_URL"); want == "" {
222 } else if url, err := url.Parse(want); err != nil {
223 return arvados.URL{}, fmt.Errorf("$ARVADOS_SERVICE_INTERNAL_URL (%q): %s", want, err)
228 return arvados.URL(*url), nil
232 for url := range svc.InternalURLs {
233 listener, err := net.Listen("tcp", url.Host)
237 } else if strings.Contains(err.Error(), "cannot assign requested address") {
238 // If 'Host' specifies a different server than
239 // the current one, it'll resolve the hostname
240 // to IP address, and then fail because it
241 // can't bind an IP address it doesn't own.
244 errors = append(errors, fmt.Sprintf("tried %v, got %v", url, err))
248 return arvados.URL{}, fmt.Errorf("could not enable the %q service on this host: %s", prog, strings.Join(errors, "; "))
250 return arvados.URL{}, fmt.Errorf("configuration does not enable the %q service on this host", prog)
253 type contextKeyURL struct{}
255 func URLFromContext(ctx context.Context) (arvados.URL, bool) {
256 u, ok := ctx.Value(contextKeyURL{}).(arvados.URL)