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