Merge branch '18349-fed-request-id'
[arvados.git] / lib / service / cmd.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: Apache-2.0
4
5 // Package service provides a cmd.Handler that brings up a system service.
6 package service
7
8 import (
9         "context"
10         "flag"
11         "fmt"
12         "io"
13         "net"
14         "net/http"
15         _ "net/http/pprof"
16         "net/url"
17         "os"
18         "strings"
19
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"
28 )
29
30 type Handler interface {
31         http.Handler
32         CheckHealth() error
33         Done() <-chan struct{}
34 }
35
36 type NewHandlerFunc func(_ context.Context, _ *arvados.Cluster, token string, registry *prometheus.Registry) Handler
37
38 type command struct {
39         newHandler NewHandlerFunc
40         svcName    arvados.ServiceName
41         ctx        context.Context // enables tests to shutdown service; no public API yet
42 }
43
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.
47 //
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 {
51         return &command{
52                 newHandler: newHandler,
53                 svcName:    svcName,
54                 ctx:        context.Background(),
55         }
56 }
57
58 func (c *command) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
59         log := ctxlog.New(stderr, "json", "info")
60
61         var err error
62         defer func() {
63                 if err != nil {
64                         log.WithError(err).Error("exiting")
65                 }
66         }()
67
68         flags := flag.NewFlagSet("", flag.ContinueOnError)
69         flags.SetOutput(stderr)
70
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 {
76                 return code
77         } else if *versionFlag {
78                 return cmd.Version.RunCommand(prog, args, stdin, stdout, stderr)
79         }
80
81         if *pprofAddr != "" {
82                 go func() {
83                         log.Println(http.ListenAndServe(*pprofAddr, nil))
84                 }()
85         }
86
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
91                 // http server yet.
92                 loader.SkipAPICalls = true
93         }
94
95         cfg, err := loader.Load()
96         if err != nil {
97                 return 1
98         }
99         cluster, err := cfg.GetCluster("")
100         if err != nil {
101                 return 1
102         }
103
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{
108                 "PID":       os.Getpid(),
109                 "ClusterID": cluster.ClusterID,
110         })
111         ctx := ctxlog.Context(c.ctx, logger)
112
113         listenURL, err := getListenAddr(cluster.Services, c.svcName, log)
114         if err != nil {
115                 return 1
116         }
117         ctx = context.WithValue(ctx, contextKeyURL{}, listenURL)
118
119         reg := prometheus.NewRegistry()
120         handler := c.newHandler(ctx, cluster, cluster.SystemRootToken, reg)
121         if err = handler.CheckHealth(); err != nil {
122                 return 1
123         }
124
125         instrumented := httpserver.Instrument(reg, log,
126                 httpserver.HandlerWithDeadline(cluster.API.RequestTimeout.Duration(),
127                         httpserver.AddRequestIDs(
128                                 httpserver.LogRequests(
129                                         httpserver.NewRequestLimiter(cluster.API.MaxConcurrentRequests, handler, reg)))))
130         srv := &httpserver.Server{
131                 Server: http.Server{
132                         Handler:     instrumented.ServeAPI(cluster.ManagementToken, instrumented),
133                         BaseContext: func(net.Listener) context.Context { return ctx },
134                 },
135                 Addr: listenURL.Host,
136         }
137         if listenURL.Scheme == "https" {
138                 tlsconfig, err := tlsConfigWithCertUpdater(cluster, logger)
139                 if err != nil {
140                         logger.WithError(err).Errorf("cannot start %s service on %s", c.svcName, listenURL.String())
141                         return 1
142                 }
143                 srv.TLSConfig = tlsconfig
144         }
145         err = srv.Start()
146         if err != nil {
147                 return 1
148         }
149         logger.WithFields(logrus.Fields{
150                 "URL":     listenURL,
151                 "Listen":  srv.Addr,
152                 "Service": c.svcName,
153         }).Info("listening")
154         if _, err := daemon.SdNotify(false, "READY=1"); err != nil {
155                 logger.WithError(err).Errorf("error notifying init daemon")
156         }
157         go func() {
158                 // Shut down server if caller cancels context
159                 <-ctx.Done()
160                 srv.Close()
161         }()
162         go func() {
163                 // Shut down server if handler dies
164                 <-handler.Done()
165                 srv.Close()
166         }()
167         err = srv.Wait()
168         if err != nil {
169                 return 1
170         }
171         return 0
172 }
173
174 func getListenAddr(svcs arvados.Services, prog arvados.ServiceName, log logrus.FieldLogger) (arvados.URL, error) {
175         svc, ok := svcs.Map()[prog]
176         if !ok {
177                 return arvados.URL{}, fmt.Errorf("unknown service name %q", prog)
178         }
179
180         if want := os.Getenv("ARVADOS_SERVICE_INTERNAL_URL"); want == "" {
181         } else if url, err := url.Parse(want); err != nil {
182                 return arvados.URL{}, fmt.Errorf("$ARVADOS_SERVICE_INTERNAL_URL (%q): %s", want, err)
183         } else {
184                 if url.Path == "" {
185                         url.Path = "/"
186                 }
187                 return arvados.URL(*url), nil
188         }
189
190         errors := []string{}
191         for url := range svc.InternalURLs {
192                 listener, err := net.Listen("tcp", url.Host)
193                 if err == nil {
194                         listener.Close()
195                         return url, nil
196                 } else if strings.Contains(err.Error(), "cannot assign requested address") {
197                         // If 'Host' specifies a different server than
198                         // the current one, it'll resolve the hostname
199                         // to IP address, and then fail because it
200                         // can't bind an IP address it doesn't own.
201                         continue
202                 } else {
203                         errors = append(errors, fmt.Sprintf("tried %v, got %v", url, err))
204                 }
205         }
206         if len(errors) > 0 {
207                 return arvados.URL{}, fmt.Errorf("could not enable the %q service on this host: %s", prog, strings.Join(errors, "; "))
208         }
209         return arvados.URL{}, fmt.Errorf("configuration does not enable the %q service on this host", prog)
210 }
211
212 type contextKeyURL struct{}
213
214 func URLFromContext(ctx context.Context) (arvados.URL, bool) {
215         u, ok := ctx.Value(contextKeyURL{}).(arvados.URL)
216         return u, ok
217 }