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