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, internalURL, err := getListenAddr(cluster.Services, c.svcName, log)
128 ctx = context.WithValue(ctx, contextKeyURL{}, internalURL)
130 reg := prometheus.NewRegistry()
131 loader.RegisterMetrics(reg)
133 // arvados_version_running{version="1.2.3~4"} 1.0
134 mVersion := prometheus.NewGaugeVec(prometheus.GaugeOpts{
135 Namespace: "arvados",
136 Name: "version_running",
137 Help: "Indicated version is running.",
138 }, []string{"version"})
139 mVersion.WithLabelValues(cmd.Version.String()).Set(1)
140 reg.MustRegister(mVersion)
142 handler := c.newHandler(ctx, cluster, cluster.SystemRootToken, reg)
143 if err = handler.CheckHealth(); err != nil {
147 instrumented := httpserver.Instrument(reg, log,
148 httpserver.HandlerWithDeadline(cluster.API.RequestTimeout.Duration(),
149 httpserver.AddRequestIDs(
150 httpserver.Inspect(reg, cluster.ManagementToken,
151 httpserver.LogRequests(
152 interceptHealthReqs(cluster.ManagementToken, handler.CheckHealth,
153 httpserver.NewRequestLimiter(cluster.API.MaxConcurrentRequests, handler, reg)))))))
154 srv := &httpserver.Server{
156 Handler: ifCollectionInHost(instrumented, instrumented.ServeAPI(cluster.ManagementToken, instrumented)),
157 BaseContext: func(net.Listener) context.Context { return ctx },
159 Addr: listenURL.Host,
161 if listenURL.Scheme == "https" || listenURL.Scheme == "wss" {
162 tlsconfig, err := makeTLSConfig(cluster, logger)
164 logger.WithError(err).Errorf("cannot start %s service on %s", c.svcName, listenURL.String())
167 srv.TLSConfig = tlsconfig
173 logger.WithFields(logrus.Fields{
176 "Service": c.svcName,
177 "Version": cmd.Version.String(),
179 if _, err := daemon.SdNotify(false, "READY=1"); err != nil {
180 logger.WithError(err).Errorf("error notifying init daemon")
183 // Shut down server if caller cancels context
188 // Shut down server if handler dies
199 // If an incoming request's target vhost has an embedded collection
200 // UUID or PDH, handle it with hTrue, otherwise handle it with
203 // Facilitates routing "http://collections.example/metrics" to metrics
204 // and "http://{uuid}.collections.example/metrics" to a file in a
206 func ifCollectionInHost(hTrue, hFalse http.Handler) http.Handler {
207 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
208 if arvados.CollectionIDFromDNSName(r.Host) != "" {
209 hTrue.ServeHTTP(w, r)
211 hFalse.ServeHTTP(w, r)
216 func interceptHealthReqs(mgtToken string, checkHealth func() error, next http.Handler) http.Handler {
217 mux := httprouter.New()
218 mux.Handler("GET", "/_health/ping", &health.Handler{
221 Routes: health.Routes{"ping": checkHealth},
224 return ifCollectionInHost(next, mux)
227 // Determine listenURL (addr:port where server should bind) and
228 // internalURL (target url that client should connect to) for a
231 // If the config does not specify ListenURL, we check all of the
232 // configured InternalURLs. If there is exactly one that matches our
233 // hostname, or exactly one that matches a local interface address,
234 // then we use that as listenURL.
236 // Note that listenURL and internalURL may use different protocols
237 // (e.g., listenURL is http, but the service sits behind a proxy, so
238 // clients connect using https).
239 func getListenAddr(svcs arvados.Services, prog arvados.ServiceName, log logrus.FieldLogger) (arvados.URL, arvados.URL, error) {
240 svc, ok := svcs.Map()[prog]
242 return arvados.URL{}, arvados.URL{}, fmt.Errorf("unknown service name %q", prog)
245 if want := os.Getenv("ARVADOS_SERVICE_INTERNAL_URL"); want != "" {
246 url, err := url.Parse(want)
248 return arvados.URL{}, arvados.URL{}, fmt.Errorf("$ARVADOS_SERVICE_INTERNAL_URL (%q): %s", want, err)
253 for internalURL, conf := range svc.InternalURLs {
254 if internalURL.String() == url.String() {
255 listenURL := conf.ListenURL
256 if listenURL.Host == "" {
257 listenURL = internalURL
259 return listenURL, internalURL, nil
262 log.Warnf("possible configuration error: listening on %s (from $ARVADOS_SERVICE_INTERNAL_URL) even though configuration does not have a matching InternalURLs entry", url)
263 internalURL := arvados.URL(*url)
264 return internalURL, internalURL, nil
268 for internalURL, conf := range svc.InternalURLs {
269 listenURL := conf.ListenURL
270 if listenURL.Host == "" {
271 // If ListenURL is not specified, assume
272 // InternalURL is also usable as the listening
273 // proto/addr/port (i.e., simple case with no
274 // intermediate proxy/routing)
275 listenURL = internalURL
277 listenAddr := listenURL.Host
278 if _, _, err := net.SplitHostPort(listenAddr); err != nil {
279 // url "https://foo.example/" (with no
280 // explicit port name/number) means listen on
281 // the well-known port for the specified
282 // protocol, "foo.example:https".
283 port := listenURL.Scheme
284 if port == "ws" || port == "wss" {
285 port = "http" + port[2:]
287 listenAddr = net.JoinHostPort(listenAddr, port)
289 listener, err := net.Listen("tcp", listenAddr)
292 return listenURL, internalURL, nil
293 } else if strings.Contains(err.Error(), "cannot assign requested address") {
294 // If 'Host' specifies a different server than
295 // the current one, it'll resolve the hostname
296 // to IP address, and then fail because it
297 // can't bind an IP address it doesn't own.
300 errors = append(errors, fmt.Sprintf("%s: %s", listenURL, err))
304 return arvados.URL{}, arvados.URL{}, fmt.Errorf("could not enable the %q service on this host: %s", prog, strings.Join(errors, "; "))
306 return arvados.URL{}, arvados.URL{}, fmt.Errorf("configuration does not enable the %q service on this host", prog)
309 type contextKeyURL struct{}
311 func URLFromContext(ctx context.Context) (arvados.URL, bool) {
312 u, ok := ctx.Value(contextKeyURL{}).(arvados.URL)