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