18947: Refactor keep-web as arvados-server command.
[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, err := getListenAddr(cluster.Services, c.svcName, log)
125         if err != nil {
126                 return 1
127         }
128         ctx = context.WithValue(ctx, contextKeyURL{}, listenURL)
129
130         reg := prometheus.NewRegistry()
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                                         interceptHealthReqs(cluster.ManagementToken, handler.CheckHealth,
141                                                 httpserver.NewRequestLimiter(cluster.API.MaxConcurrentRequests, handler, reg))))))
142         srv := &httpserver.Server{
143                 Server: http.Server{
144                         Handler:     ifCollectionInHost(instrumented, instrumented.ServeAPI(cluster.ManagementToken, instrumented)),
145                         BaseContext: func(net.Listener) context.Context { return ctx },
146                 },
147                 Addr: listenURL.Host,
148         }
149         if listenURL.Scheme == "https" {
150                 tlsconfig, err := tlsConfigWithCertUpdater(cluster, logger)
151                 if err != nil {
152                         logger.WithError(err).Errorf("cannot start %s service on %s", c.svcName, listenURL.String())
153                         return 1
154                 }
155                 srv.TLSConfig = tlsconfig
156         }
157         err = srv.Start()
158         if err != nil {
159                 return 1
160         }
161         logger.WithFields(logrus.Fields{
162                 "URL":     listenURL,
163                 "Listen":  srv.Addr,
164                 "Service": c.svcName,
165                 "Version": cmd.Version.String(),
166         }).Info("listening")
167         if _, err := daemon.SdNotify(false, "READY=1"); err != nil {
168                 logger.WithError(err).Errorf("error notifying init daemon")
169         }
170         go func() {
171                 // Shut down server if caller cancels context
172                 <-ctx.Done()
173                 srv.Close()
174         }()
175         go func() {
176                 // Shut down server if handler dies
177                 <-handler.Done()
178                 srv.Close()
179         }()
180         err = srv.Wait()
181         if err != nil {
182                 return 1
183         }
184         return 0
185 }
186
187 // If an incoming request's target vhost has an embedded collection
188 // UUID or PDH, handle it with hTrue, otherwise handle it with
189 // hFalse.
190 //
191 // Facilitates routing "http://collections.example/metrics" to metrics
192 // and "http://{uuid}.collections.example/metrics" to a file in a
193 // collection.
194 func ifCollectionInHost(hTrue, hFalse http.Handler) http.Handler {
195         return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
196                 if arvados.CollectionIDFromDNSName(r.Host) != "" {
197                         hTrue.ServeHTTP(w, r)
198                 } else {
199                         hFalse.ServeHTTP(w, r)
200                 }
201         })
202 }
203
204 func interceptHealthReqs(mgtToken string, checkHealth func() error, next http.Handler) http.Handler {
205         mux := httprouter.New()
206         mux.Handler("GET", "/_health/ping", &health.Handler{
207                 Token:  mgtToken,
208                 Prefix: "/_health/",
209                 Routes: health.Routes{"ping": checkHealth},
210         })
211         mux.NotFound = next
212         return ifCollectionInHost(next, mux)
213 }
214
215 func getListenAddr(svcs arvados.Services, prog arvados.ServiceName, log logrus.FieldLogger) (arvados.URL, error) {
216         svc, ok := svcs.Map()[prog]
217         if !ok {
218                 return arvados.URL{}, fmt.Errorf("unknown service name %q", prog)
219         }
220
221         if want := os.Getenv("ARVADOS_SERVICE_INTERNAL_URL"); want == "" {
222         } else if url, err := url.Parse(want); err != nil {
223                 return arvados.URL{}, fmt.Errorf("$ARVADOS_SERVICE_INTERNAL_URL (%q): %s", want, err)
224         } else {
225                 if url.Path == "" {
226                         url.Path = "/"
227                 }
228                 return arvados.URL(*url), nil
229         }
230
231         errors := []string{}
232         for url := range svc.InternalURLs {
233                 listener, err := net.Listen("tcp", url.Host)
234                 if err == nil {
235                         listener.Close()
236                         return url, nil
237                 } else if strings.Contains(err.Error(), "cannot assign requested address") {
238                         // If 'Host' specifies a different server than
239                         // the current one, it'll resolve the hostname
240                         // to IP address, and then fail because it
241                         // can't bind an IP address it doesn't own.
242                         continue
243                 } else {
244                         errors = append(errors, fmt.Sprintf("tried %v, got %v", url, err))
245                 }
246         }
247         if len(errors) > 0 {
248                 return arvados.URL{}, fmt.Errorf("could not enable the %q service on this host: %s", prog, strings.Join(errors, "; "))
249         }
250         return arvados.URL{}, fmt.Errorf("configuration does not enable the %q service on this host", prog)
251 }
252
253 type contextKeyURL struct{}
254
255 func URLFromContext(ctx context.Context) (arvados.URL, bool) {
256         u, ok := ctx.Value(contextKeyURL{}).(arvados.URL)
257         return u, ok
258 }