Merge branch 'patch-1' of https://github.com/mr-c/arvados into mr-c-patch-1
[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/url"
16         "os"
17         "strings"
18
19         "git.arvados.org/arvados.git/lib/cmd"
20         "git.arvados.org/arvados.git/lib/config"
21         "git.arvados.org/arvados.git/sdk/go/arvados"
22         "git.arvados.org/arvados.git/sdk/go/ctxlog"
23         "git.arvados.org/arvados.git/sdk/go/httpserver"
24         "github.com/coreos/go-systemd/daemon"
25         "github.com/prometheus/client_golang/prometheus"
26         "github.com/sirupsen/logrus"
27 )
28
29 type Handler interface {
30         http.Handler
31         CheckHealth() error
32         Done() <-chan struct{}
33 }
34
35 type NewHandlerFunc func(_ context.Context, _ *arvados.Cluster, token string, registry *prometheus.Registry) Handler
36
37 type command struct {
38         newHandler NewHandlerFunc
39         svcName    arvados.ServiceName
40         ctx        context.Context // enables tests to shutdown service; no public API yet
41 }
42
43 // Command returns a cmd.Handler that loads site config, calls
44 // newHandler with the current cluster and node configs, and brings up
45 // an http server with the returned handler.
46 //
47 // The handler is wrapped with server middleware (adding X-Request-ID
48 // headers, logging requests/responses, etc).
49 func Command(svcName arvados.ServiceName, newHandler NewHandlerFunc) cmd.Handler {
50         return &command{
51                 newHandler: newHandler,
52                 svcName:    svcName,
53                 ctx:        context.Background(),
54         }
55 }
56
57 func (c *command) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
58         log := ctxlog.New(stderr, "json", "info")
59
60         var err error
61         defer func() {
62                 if err != nil {
63                         log.WithError(err).Error("exiting")
64                 }
65         }()
66
67         flags := flag.NewFlagSet("", flag.ContinueOnError)
68         flags.SetOutput(stderr)
69
70         loader := config.NewLoader(stdin, log)
71         loader.SetupFlags(flags)
72         versionFlag := flags.Bool("version", false, "Write version information to stdout and exit 0")
73         err = flags.Parse(args)
74         if err == flag.ErrHelp {
75                 err = nil
76                 return 0
77         } else if err != nil {
78                 return 2
79         } else if *versionFlag {
80                 return cmd.Version.RunCommand(prog, args, stdin, stdout, stderr)
81         }
82
83         if strings.HasSuffix(prog, "controller") {
84                 // Some config-loader checks try to make API calls via
85                 // controller. Those can't be expected to work if this
86                 // process _is_ the controller: we haven't started an
87                 // http server yet.
88                 loader.SkipAPICalls = true
89         }
90
91         cfg, err := loader.Load()
92         if err != nil {
93                 return 1
94         }
95         cluster, err := cfg.GetCluster("")
96         if err != nil {
97                 return 1
98         }
99
100         // Now that we've read the config, replace the bootstrap
101         // logger with a new one according to the logging config.
102         log = ctxlog.New(stderr, cluster.SystemLogs.Format, cluster.SystemLogs.LogLevel)
103         logger := log.WithFields(logrus.Fields{
104                 "PID": os.Getpid(),
105         })
106         ctx := ctxlog.Context(c.ctx, logger)
107
108         listenURL, err := getListenAddr(cluster.Services, c.svcName, log)
109         if err != nil {
110                 return 1
111         }
112         ctx = context.WithValue(ctx, contextKeyURL{}, listenURL)
113
114         reg := prometheus.NewRegistry()
115         handler := c.newHandler(ctx, cluster, cluster.SystemRootToken, reg)
116         if err = handler.CheckHealth(); err != nil {
117                 return 1
118         }
119
120         instrumented := httpserver.Instrument(reg, log,
121                 httpserver.HandlerWithContext(ctx,
122                         httpserver.AddRequestIDs(
123                                 httpserver.LogRequests(
124                                         httpserver.NewRequestLimiter(cluster.API.MaxConcurrentRequests, handler, reg)))))
125         srv := &httpserver.Server{
126                 Server: http.Server{
127                         Handler: instrumented.ServeAPI(cluster.ManagementToken, instrumented),
128                 },
129                 Addr: listenURL.Host,
130         }
131         if listenURL.Scheme == "https" {
132                 tlsconfig, err := tlsConfigWithCertUpdater(cluster, logger)
133                 if err != nil {
134                         logger.WithError(err).Errorf("cannot start %s service on %s", c.svcName, listenURL.String())
135                         return 1
136                 }
137                 srv.TLSConfig = tlsconfig
138         }
139         err = srv.Start()
140         if err != nil {
141                 return 1
142         }
143         logger.WithFields(logrus.Fields{
144                 "URL":     listenURL,
145                 "Listen":  srv.Addr,
146                 "Service": c.svcName,
147         }).Info("listening")
148         if _, err := daemon.SdNotify(false, "READY=1"); err != nil {
149                 logger.WithError(err).Errorf("error notifying init daemon")
150         }
151         go func() {
152                 // Shut down server if caller cancels context
153                 <-ctx.Done()
154                 srv.Close()
155         }()
156         go func() {
157                 // Shut down server if handler dies
158                 <-handler.Done()
159                 srv.Close()
160         }()
161         err = srv.Wait()
162         if err != nil {
163                 return 1
164         }
165         return 0
166 }
167
168 const rfc3339NanoFixed = "2006-01-02T15:04:05.000000000Z07:00"
169
170 func getListenAddr(svcs arvados.Services, prog arvados.ServiceName, log logrus.FieldLogger) (arvados.URL, error) {
171         svc, ok := svcs.Map()[prog]
172         if !ok {
173                 return arvados.URL{}, fmt.Errorf("unknown service name %q", prog)
174         }
175
176         if want := os.Getenv("ARVADOS_SERVICE_INTERNAL_URL"); want == "" {
177         } else if url, err := url.Parse(want); err != nil {
178                 return arvados.URL{}, fmt.Errorf("$ARVADOS_SERVICE_INTERNAL_URL (%q): %s", want, err)
179         } else {
180                 if url.Path == "" {
181                         url.Path = "/"
182                 }
183                 return arvados.URL(*url), nil
184         }
185
186         errors := []string{}
187         for url := range svc.InternalURLs {
188                 listener, err := net.Listen("tcp", url.Host)
189                 if err == nil {
190                         listener.Close()
191                         return url, nil
192                 } else if strings.Contains(err.Error(), "cannot assign requested address") {
193                         // If 'Host' specifies a different server than
194                         // the current one, it'll resolve the hostname
195                         // to IP address, and then fail because it
196                         // can't bind an IP address it doesn't own.
197                         continue
198                 } else {
199                         errors = append(errors, fmt.Sprintf("tried %v, got %v", url, err))
200                 }
201         }
202         if len(errors) > 0 {
203                 return arvados.URL{}, fmt.Errorf("could not enable the %q service on this host: %s", prog, strings.Join(errors, "; "))
204         }
205         return arvados.URL{}, fmt.Errorf("configuration does not enable the %q service on this host", prog)
206 }
207
208 type contextKeyURL struct{}
209
210 func URLFromContext(ctx context.Context) (arvados.URL, bool) {
211         u, ok := ctx.Value(contextKeyURL{}).(arvados.URL)
212         return u, ok
213 }