Merge branch '15003-disable-config-warnings'
[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         "net/http"
15         "net/url"
16         "os"
17
18         "git.curoverse.com/arvados.git/lib/cmd"
19         "git.curoverse.com/arvados.git/lib/config"
20         "git.curoverse.com/arvados.git/sdk/go/arvados"
21         "git.curoverse.com/arvados.git/sdk/go/ctxlog"
22         "git.curoverse.com/arvados.git/sdk/go/httpserver"
23         "github.com/coreos/go-systemd/daemon"
24         "github.com/sirupsen/logrus"
25 )
26
27 type Handler interface {
28         http.Handler
29         CheckHealth() error
30 }
31
32 type NewHandlerFunc func(_ context.Context, _ *arvados.Cluster, _ *arvados.NodeProfile, token string) Handler
33
34 type command struct {
35         newHandler NewHandlerFunc
36         svcName    arvados.ServiceName
37         ctx        context.Context // enables tests to shutdown service; no public API yet
38 }
39
40 // Command returns a cmd.Handler that loads site config, calls
41 // newHandler with the current cluster and node configs, and brings up
42 // an http server with the returned handler.
43 //
44 // The handler is wrapped with server middleware (adding X-Request-ID
45 // headers, logging requests/responses, etc).
46 func Command(svcName arvados.ServiceName, newHandler NewHandlerFunc) cmd.Handler {
47         return &command{
48                 newHandler: newHandler,
49                 svcName:    svcName,
50                 ctx:        context.Background(),
51         }
52 }
53
54 func (c *command) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
55         log := ctxlog.New(stderr, "json", "info")
56
57         var err error
58         defer func() {
59                 if err != nil {
60                         log.WithError(err).Info("exiting")
61                 }
62         }()
63         flags := flag.NewFlagSet("", flag.ContinueOnError)
64         flags.SetOutput(stderr)
65         configFile := flags.String("config", arvados.DefaultConfigFile, "Site configuration `file`")
66         nodeProfile := flags.String("node-profile", "", "`Name` of NodeProfiles config entry to use (if blank, use $ARVADOS_NODE_PROFILE or hostname reported by OS)")
67         err = flags.Parse(args)
68         if err == flag.ErrHelp {
69                 err = nil
70                 return 0
71         } else if err != nil {
72                 return 2
73         }
74         // Logged warnings are discarded for now: the config template
75         // is incomplete, which causes extra warnings about keys that
76         // are really OK.
77         cfg, err := config.LoadFile(*configFile, ctxlog.New(ioutil.Discard, "json", "error"))
78         if err != nil {
79                 return 1
80         }
81         cluster, err := cfg.GetCluster("")
82         if err != nil {
83                 return 1
84         }
85         log = ctxlog.New(stderr, cluster.Logging.Format, cluster.Logging.Level).WithFields(logrus.Fields{
86                 "PID": os.Getpid(),
87         })
88         ctx := ctxlog.Context(c.ctx, log)
89
90         profileName := *nodeProfile
91         if profileName == "" {
92                 profileName = os.Getenv("ARVADOS_NODE_PROFILE")
93         }
94         profile, err := cluster.GetNodeProfile(profileName)
95         if err != nil {
96                 return 1
97         }
98         listen := profile.ServicePorts()[c.svcName]
99         if listen == "" {
100                 err = fmt.Errorf("configuration does not enable the %s service on this host", c.svcName)
101                 return 1
102         }
103
104         if cluster.SystemRootToken == "" {
105                 log.Warn("SystemRootToken missing from cluster config, falling back to ARVADOS_API_TOKEN environment variable")
106                 cluster.SystemRootToken = os.Getenv("ARVADOS_API_TOKEN")
107         }
108         if cluster.Services.Controller.ExternalURL.Host == "" {
109                 log.Warn("Services.Controller.ExternalURL missing from cluster config, falling back to ARVADOS_API_HOST(_INSECURE) environment variables")
110                 u, err := url.Parse("https://" + os.Getenv("ARVADOS_API_HOST"))
111                 if err != nil {
112                         err = fmt.Errorf("ARVADOS_API_HOST: %s", err)
113                         return 1
114                 }
115                 cluster.Services.Controller.ExternalURL = arvados.URL(*u)
116                 if i := os.Getenv("ARVADOS_API_HOST_INSECURE"); i != "" && i != "0" {
117                         cluster.TLS.Insecure = true
118                 }
119         }
120
121         handler := c.newHandler(ctx, cluster, profile, cluster.SystemRootToken)
122         if err = handler.CheckHealth(); err != nil {
123                 return 1
124         }
125         srv := &httpserver.Server{
126                 Server: http.Server{
127                         Handler: httpserver.AddRequestIDs(httpserver.LogRequests(log, handler)),
128                 },
129                 Addr: listen,
130         }
131         err = srv.Start()
132         if err != nil {
133                 return 1
134         }
135         log.WithFields(logrus.Fields{
136                 "Listen":  srv.Addr,
137                 "Service": c.svcName,
138         }).Info("listening")
139         if _, err := daemon.SdNotify(false, "READY=1"); err != nil {
140                 log.WithError(err).Errorf("error notifying init daemon")
141         }
142         go func() {
143                 <-ctx.Done()
144                 srv.Close()
145         }()
146         err = srv.Wait()
147         if err != nil {
148                 return 1
149         }
150         return 0
151 }
152
153 const rfc3339NanoFixed = "2006-01-02T15:04:05.000000000Z07:00"