9e45e0f7e828a340d5eee6d024eb9f8da21cf948
[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/health"
25         "git.arvados.org/arvados.git/sdk/go/httpserver"
26         "github.com/coreos/go-systemd/daemon"
27         "github.com/julienschmidt/httprouter"
28         "github.com/prometheus/client_golang/prometheus"
29         "github.com/sirupsen/logrus"
30 )
31
32 type Handler interface {
33         http.Handler
34         CheckHealth() error
35         // Done returns a channel that closes when the handler shuts
36         // itself down, or nil if this never happens.
37         Done() <-chan struct{}
38 }
39
40 type NewHandlerFunc func(_ context.Context, _ *arvados.Cluster, token string, registry *prometheus.Registry) Handler
41
42 type command struct {
43         newHandler NewHandlerFunc
44         svcName    arvados.ServiceName
45         ctx        context.Context // enables tests to shutdown service; no public API yet
46 }
47
48 // Command returns a cmd.Handler that loads site config, calls
49 // newHandler with the current cluster and node configs, and brings up
50 // an http server with the returned handler.
51 //
52 // The handler is wrapped with server middleware (adding X-Request-ID
53 // headers, logging requests/responses, etc).
54 func Command(svcName arvados.ServiceName, newHandler NewHandlerFunc) cmd.Handler {
55         return &command{
56                 newHandler: newHandler,
57                 svcName:    svcName,
58                 ctx:        context.Background(),
59         }
60 }
61
62 func (c *command) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
63         log := ctxlog.New(stderr, "json", "info")
64
65         var err error
66         defer func() {
67                 if err != nil {
68                         log.WithError(err).Error("exiting")
69                 }
70         }()
71
72         flags := flag.NewFlagSet("", flag.ContinueOnError)
73         flags.SetOutput(stderr)
74
75         loader := config.NewLoader(stdin, log)
76         loader.SetupFlags(flags)
77
78         // prog is [keepstore, keep-web, git-httpd, ...]  but the
79         // legacy config flags are [-legacy-keepstore-config,
80         // -legacy-keepweb-config, -legacy-git-httpd-config, ...]
81         legacyFlag := "-legacy-" + strings.Replace(prog, "keep-", "keep", 1) + "-config"
82         args = loader.MungeLegacyConfigArgs(log, args, legacyFlag)
83
84         versionFlag := flags.Bool("version", false, "Write version information to stdout and exit 0")
85         pprofAddr := flags.String("pprof", "", "Serve Go profile data at `[addr]:port`")
86         if ok, code := cmd.ParseFlags(flags, prog, args, "", stderr); !ok {
87                 return code
88         } else if *versionFlag {
89                 return cmd.Version.RunCommand(prog, args, stdin, stdout, stderr)
90         }
91
92         if *pprofAddr != "" {
93                 go func() {
94                         log.Println(http.ListenAndServe(*pprofAddr, nil))
95                 }()
96         }
97
98         if strings.HasSuffix(prog, "controller") {
99                 // Some config-loader checks try to make API calls via
100                 // controller. Those can't be expected to work if this
101                 // process _is_ the controller: we haven't started an
102                 // http server yet.
103                 loader.SkipAPICalls = true
104         }
105
106         cfg, err := loader.Load()
107         if err != nil {
108                 return 1
109         }
110         cluster, err := cfg.GetCluster("")
111         if err != nil {
112                 return 1
113         }
114
115         // Now that we've read the config, replace the bootstrap
116         // logger with a new one according to the logging config.
117         log = ctxlog.New(stderr, cluster.SystemLogs.Format, cluster.SystemLogs.LogLevel)
118         logger := log.WithFields(logrus.Fields{
119                 "PID":       os.Getpid(),
120                 "ClusterID": cluster.ClusterID,
121         })
122         ctx := ctxlog.Context(c.ctx, logger)
123
124         listenURL, internalURL, err := getListenAddr(cluster.Services, c.svcName, log)
125         if err != nil {
126                 return 1
127         }
128         ctx = context.WithValue(ctx, contextKeyURL{}, internalURL)
129
130         reg := prometheus.NewRegistry()
131         loader.RegisterMetrics(reg)
132
133         // arvados_version_running{version="1.2.3~4"} 1.0
134         mVersion := prometheus.NewGaugeVec(prometheus.GaugeOpts{
135                 Namespace: "arvados",
136                 Name:      "version_running",
137                 Help:      "Indicated version is running.",
138         }, []string{"version"})
139         mVersion.WithLabelValues(cmd.Version.String()).Set(1)
140         reg.MustRegister(mVersion)
141
142         handler := c.newHandler(ctx, cluster, cluster.SystemRootToken, reg)
143         if err = handler.CheckHealth(); err != nil {
144                 return 1
145         }
146
147         instrumented := httpserver.Instrument(reg, log,
148                 httpserver.HandlerWithDeadline(cluster.API.RequestTimeout.Duration(),
149                         httpserver.AddRequestIDs(
150                                 httpserver.LogRequests(
151                                         interceptHealthReqs(cluster.ManagementToken, handler.CheckHealth,
152                                                 httpserver.NewRequestLimiter(cluster.API.MaxConcurrentRequests, handler, reg))))))
153         srv := &httpserver.Server{
154                 Server: http.Server{
155                         Handler:     ifCollectionInHost(instrumented, instrumented.ServeAPI(cluster.ManagementToken, instrumented)),
156                         BaseContext: func(net.Listener) context.Context { return ctx },
157                 },
158                 Addr: listenURL.Host,
159         }
160         if listenURL.Scheme == "https" || listenURL.Scheme == "wss" {
161                 tlsconfig, err := tlsConfigWithCertUpdater(cluster, logger)
162                 if err != nil {
163                         logger.WithError(err).Errorf("cannot start %s service on %s", c.svcName, listenURL.String())
164                         return 1
165                 }
166                 srv.TLSConfig = tlsconfig
167         }
168         err = srv.Start()
169         if err != nil {
170                 return 1
171         }
172         logger.WithFields(logrus.Fields{
173                 "URL":     listenURL,
174                 "Listen":  srv.Addr,
175                 "Service": c.svcName,
176                 "Version": cmd.Version.String(),
177         }).Info("listening")
178         if _, err := daemon.SdNotify(false, "READY=1"); err != nil {
179                 logger.WithError(err).Errorf("error notifying init daemon")
180         }
181         go func() {
182                 // Shut down server if caller cancels context
183                 <-ctx.Done()
184                 srv.Close()
185         }()
186         go func() {
187                 // Shut down server if handler dies
188                 <-handler.Done()
189                 srv.Close()
190         }()
191         err = srv.Wait()
192         if err != nil {
193                 return 1
194         }
195         return 0
196 }
197
198 // If an incoming request's target vhost has an embedded collection
199 // UUID or PDH, handle it with hTrue, otherwise handle it with
200 // hFalse.
201 //
202 // Facilitates routing "http://collections.example/metrics" to metrics
203 // and "http://{uuid}.collections.example/metrics" to a file in a
204 // collection.
205 func ifCollectionInHost(hTrue, hFalse http.Handler) http.Handler {
206         return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
207                 if arvados.CollectionIDFromDNSName(r.Host) != "" {
208                         hTrue.ServeHTTP(w, r)
209                 } else {
210                         hFalse.ServeHTTP(w, r)
211                 }
212         })
213 }
214
215 func interceptHealthReqs(mgtToken string, checkHealth func() error, next http.Handler) http.Handler {
216         mux := httprouter.New()
217         mux.Handler("GET", "/_health/ping", &health.Handler{
218                 Token:  mgtToken,
219                 Prefix: "/_health/",
220                 Routes: health.Routes{"ping": checkHealth},
221         })
222         mux.NotFound = next
223         return ifCollectionInHost(next, mux)
224 }
225
226 // Determine listenURL (addr:port where server should bind) and
227 // internalURL (target url that client should connect to) for a
228 // service.
229 //
230 // If the config does not specify ListenURL, we check all of the
231 // configured InternalURLs. If there is exactly one that matches our
232 // hostname, or exactly one that matches a local interface address,
233 // then we use that as listenURL.
234 //
235 // Note that listenURL and internalURL may use different protocols
236 // (e.g., listenURL is http, but the service sits behind a proxy, so
237 // clients connect using https).
238 func getListenAddr(svcs arvados.Services, prog arvados.ServiceName, log logrus.FieldLogger) (arvados.URL, arvados.URL, error) {
239         svc, ok := svcs.Map()[prog]
240         if !ok {
241                 return arvados.URL{}, arvados.URL{}, fmt.Errorf("unknown service name %q", prog)
242         }
243
244         if want := os.Getenv("ARVADOS_SERVICE_INTERNAL_URL"); want != "" {
245                 url, err := url.Parse(want)
246                 if err != nil {
247                         return arvados.URL{}, arvados.URL{}, fmt.Errorf("$ARVADOS_SERVICE_INTERNAL_URL (%q): %s", want, err)
248                 }
249                 if url.Path == "" {
250                         url.Path = "/"
251                 }
252                 for internalURL, conf := range svc.InternalURLs {
253                         if internalURL.String() == url.String() {
254                                 listenURL := conf.ListenURL
255                                 if listenURL.Host == "" {
256                                         listenURL = internalURL
257                                 }
258                                 return listenURL, internalURL, nil
259                         }
260                 }
261                 log.Warnf("possible configuration error: listening on %s (from $ARVADOS_SERVICE_INTERNAL_URL) even though configuration does not have a matching InternalURLs entry", url)
262                 internalURL := arvados.URL(*url)
263                 return internalURL, internalURL, nil
264         }
265
266         errors := []string{}
267         for internalURL, conf := range svc.InternalURLs {
268                 listenURL := conf.ListenURL
269                 if listenURL.Host == "" {
270                         // If ListenURL is not specified, assume
271                         // InternalURL is also usable as the listening
272                         // proto/addr/port (i.e., simple case with no
273                         // intermediate proxy/routing)
274                         listenURL = internalURL
275                 }
276                 listenAddr := listenURL.Host
277                 if _, _, err := net.SplitHostPort(listenAddr); err != nil {
278                         // url "https://foo.example/" (with no
279                         // explicit port name/number) means listen on
280                         // the well-known port for the specified
281                         // protocol, "foo.example:https".
282                         listenAddr = net.JoinHostPort(listenAddr, listenURL.Scheme)
283                 }
284                 listener, err := net.Listen("tcp", listenAddr)
285                 if err == nil {
286                         listener.Close()
287                         return listenURL, internalURL, nil
288                 } else if strings.Contains(err.Error(), "cannot assign requested address") {
289                         // If 'Host' specifies a different server than
290                         // the current one, it'll resolve the hostname
291                         // to IP address, and then fail because it
292                         // can't bind an IP address it doesn't own.
293                         continue
294                 } else {
295                         errors = append(errors, fmt.Sprintf("%s: %s", listenURL, err))
296                 }
297         }
298         if len(errors) > 0 {
299                 return arvados.URL{}, arvados.URL{}, fmt.Errorf("could not enable the %q service on this host: %s", prog, strings.Join(errors, "; "))
300         }
301         return arvados.URL{}, arvados.URL{}, fmt.Errorf("configuration does not enable the %q service on this host", prog)
302 }
303
304 type contextKeyURL struct{}
305
306 func URLFromContext(ctx context.Context) (arvados.URL, bool) {
307         u, ok := ctx.Value(contextKeyURL{}).(arvados.URL)
308         return u, ok
309 }