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