18308: Merge branch 'main' into 18308-enable-collection-versioning
[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         })
110         ctx := ctxlog.Context(c.ctx, logger)
111
112         listenURL, err := getListenAddr(cluster.Services, c.svcName, log)
113         if err != nil {
114                 return 1
115         }
116         ctx = context.WithValue(ctx, contextKeyURL{}, listenURL)
117
118         reg := prometheus.NewRegistry()
119         handler := c.newHandler(ctx, cluster, cluster.SystemRootToken, reg)
120         if err = handler.CheckHealth(); err != nil {
121                 return 1
122         }
123
124         instrumented := httpserver.Instrument(reg, log,
125                 httpserver.HandlerWithDeadline(cluster.API.RequestTimeout.Duration(),
126                         httpserver.AddRequestIDs(
127                                 httpserver.LogRequests(
128                                         httpserver.NewRequestLimiter(cluster.API.MaxConcurrentRequests, handler, reg)))))
129         srv := &httpserver.Server{
130                 Server: http.Server{
131                         Handler:     instrumented.ServeAPI(cluster.ManagementToken, instrumented),
132                         BaseContext: func(net.Listener) context.Context { return ctx },
133                 },
134                 Addr: listenURL.Host,
135         }
136         if listenURL.Scheme == "https" {
137                 tlsconfig, err := tlsConfigWithCertUpdater(cluster, logger)
138                 if err != nil {
139                         logger.WithError(err).Errorf("cannot start %s service on %s", c.svcName, listenURL.String())
140                         return 1
141                 }
142                 srv.TLSConfig = tlsconfig
143         }
144         err = srv.Start()
145         if err != nil {
146                 return 1
147         }
148         logger.WithFields(logrus.Fields{
149                 "URL":     listenURL,
150                 "Listen":  srv.Addr,
151                 "Service": c.svcName,
152         }).Info("listening")
153         if _, err := daemon.SdNotify(false, "READY=1"); err != nil {
154                 logger.WithError(err).Errorf("error notifying init daemon")
155         }
156         go func() {
157                 // Shut down server if caller cancels context
158                 <-ctx.Done()
159                 srv.Close()
160         }()
161         go func() {
162                 // Shut down server if handler dies
163                 <-handler.Done()
164                 srv.Close()
165         }()
166         err = srv.Wait()
167         if err != nil {
168                 return 1
169         }
170         return 0
171 }
172
173 func getListenAddr(svcs arvados.Services, prog arvados.ServiceName, log logrus.FieldLogger) (arvados.URL, error) {
174         svc, ok := svcs.Map()[prog]
175         if !ok {
176                 return arvados.URL{}, fmt.Errorf("unknown service name %q", prog)
177         }
178
179         if want := os.Getenv("ARVADOS_SERVICE_INTERNAL_URL"); want == "" {
180         } else if url, err := url.Parse(want); err != nil {
181                 return arvados.URL{}, fmt.Errorf("$ARVADOS_SERVICE_INTERNAL_URL (%q): %s", want, err)
182         } else {
183                 if url.Path == "" {
184                         url.Path = "/"
185                 }
186                 return arvados.URL(*url), nil
187         }
188
189         errors := []string{}
190         for url := range svc.InternalURLs {
191                 listener, err := net.Listen("tcp", url.Host)
192                 if err == nil {
193                         listener.Close()
194                         return url, nil
195                 } else if strings.Contains(err.Error(), "cannot assign requested address") {
196                         // If 'Host' specifies a different server than
197                         // the current one, it'll resolve the hostname
198                         // to IP address, and then fail because it
199                         // can't bind an IP address it doesn't own.
200                         continue
201                 } else {
202                         errors = append(errors, fmt.Sprintf("tried %v, got %v", url, err))
203                 }
204         }
205         if len(errors) > 0 {
206                 return arvados.URL{}, fmt.Errorf("could not enable the %q service on this host: %s", prog, strings.Join(errors, "; "))
207         }
208         return arvados.URL{}, fmt.Errorf("configuration does not enable the %q service on this host", prog)
209 }
210
211 type contextKeyURL struct{}
212
213 func URLFromContext(ctx context.Context) (arvados.URL, bool) {
214         u, ok := ctx.Value(contextKeyURL{}).(arvados.URL)
215         return u, ok
216 }