15003: Merge branch 'master'
[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         "io/ioutil"
14         "log"
15         "net"
16         "net/http"
17         "net/url"
18         "os"
19         "strings"
20
21         "git.curoverse.com/arvados.git/lib/cmd"
22         "git.curoverse.com/arvados.git/lib/config"
23         "git.curoverse.com/arvados.git/sdk/go/arvados"
24         "git.curoverse.com/arvados.git/sdk/go/ctxlog"
25         "git.curoverse.com/arvados.git/sdk/go/httpserver"
26         "github.com/coreos/go-systemd/daemon"
27         "github.com/sirupsen/logrus"
28 )
29
30 type Handler interface {
31         http.Handler
32         CheckHealth() error
33 }
34
35 type NewHandlerFunc func(_ context.Context, _ *arvados.Cluster, token string) 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).Info("exiting")
64                 }
65         }()
66         flags := flag.NewFlagSet("", flag.ContinueOnError)
67         flags.SetOutput(stderr)
68         configFile := flags.String("config", arvados.DefaultConfigFile, "Site configuration `file`")
69         err = flags.Parse(args)
70         if err == flag.ErrHelp {
71                 err = nil
72                 return 0
73         } else if err != nil {
74                 return 2
75         }
76         // Logged warnings are discarded for now: the config template
77         // is incomplete, which causes extra warnings about keys that
78         // are really OK.
79         cfg, err := config.LoadFile(*configFile, ctxlog.New(ioutil.Discard, "json", "error"))
80         if err != nil {
81                 return 1
82         }
83         cluster, err := cfg.GetCluster("")
84         if err != nil {
85                 return 1
86         }
87         log = ctxlog.New(stderr, cluster.SystemLogs.Format, cluster.SystemLogs.LogLevel).WithFields(logrus.Fields{
88                 "PID": os.Getpid(),
89         })
90         ctx := ctxlog.Context(c.ctx, log)
91
92         listen, err := getListenAddr(cluster.Services, c.svcName)
93         if err != nil {
94                 return 1
95         }
96
97         if cluster.SystemRootToken == "" {
98                 log.Warn("SystemRootToken missing from cluster config, falling back to ARVADOS_API_TOKEN environment variable")
99                 cluster.SystemRootToken = os.Getenv("ARVADOS_API_TOKEN")
100         }
101         if cluster.Services.Controller.ExternalURL.Host == "" {
102                 log.Warn("Services.Controller.ExternalURL missing from cluster config, falling back to ARVADOS_API_HOST(_INSECURE) environment variables")
103                 u, err := url.Parse("https://" + os.Getenv("ARVADOS_API_HOST"))
104                 if err != nil {
105                         err = fmt.Errorf("ARVADOS_API_HOST: %s", err)
106                         return 1
107                 }
108                 cluster.Services.Controller.ExternalURL = arvados.URL(*u)
109                 if i := os.Getenv("ARVADOS_API_HOST_INSECURE"); i != "" && i != "0" {
110                         cluster.TLS.Insecure = true
111                 }
112         }
113
114         handler := c.newHandler(ctx, cluster, cluster.SystemRootToken)
115         if err = handler.CheckHealth(); err != nil {
116                 return 1
117         }
118         srv := &httpserver.Server{
119                 Server: http.Server{
120                         Handler: httpserver.AddRequestIDs(httpserver.LogRequests(log, handler)),
121                 },
122                 Addr: listen,
123         }
124         err = srv.Start()
125         if err != nil {
126                 return 1
127         }
128         log.WithFields(logrus.Fields{
129                 "Listen":  srv.Addr,
130                 "Service": c.svcName,
131         }).Info("listening")
132         if _, err := daemon.SdNotify(false, "READY=1"); err != nil {
133                 log.WithError(err).Errorf("error notifying init daemon")
134         }
135         go func() {
136                 <-ctx.Done()
137                 srv.Close()
138         }()
139         err = srv.Wait()
140         if err != nil {
141                 return 1
142         }
143         return 0
144 }
145
146 const rfc3339NanoFixed = "2006-01-02T15:04:05.000000000Z07:00"
147
148 func getListenAddr(svcs arvados.Services, prog arvados.ServiceName) (string, error) {
149         svc, ok := map[arvados.ServiceName]arvados.Service{
150                 arvados.ServiceNameController:    svcs.Controller,
151                 arvados.ServiceNameDispatchCloud: svcs.DispatchCloud,
152                 arvados.ServiceNameHealth:        svcs.Health,
153                 arvados.ServiceNameKeepbalance:   svcs.Keepbalance,
154                 arvados.ServiceNameKeepproxy:     svcs.Keepproxy,
155                 arvados.ServiceNameKeepstore:     svcs.Keepstore,
156                 arvados.ServiceNameKeepweb:       svcs.WebDAV,
157                 arvados.ServiceNameWebsocket:     svcs.Websocket,
158         }[prog]
159         if !ok {
160                 return "", fmt.Errorf("unknown service name %q", prog)
161         }
162         for url := range svc.InternalURLs {
163                 if strings.HasPrefix(url.Host, "localhost:") {
164                         return url.Host, nil
165                 }
166                 listener, err := net.Listen("tcp", url.Host)
167                 if err == nil {
168                         listener.Close()
169                         return url.Host, nil
170                 }
171                 log.Print(err)
172
173         }
174         return "", fmt.Errorf("configuration does not enable the %s service on this host", prog)
175 }