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