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