Merge branch '20877-trashed-priority' refs #20877
[arvados.git] / lib / boot / cmd.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package boot
6
7 import (
8         "context"
9         "errors"
10         "flag"
11         "fmt"
12         "io"
13         "sort"
14         "time"
15
16         "git.arvados.org/arvados.git/lib/cmd"
17         "git.arvados.org/arvados.git/sdk/go/ctxlog"
18         "github.com/coreos/go-systemd/daemon"
19 )
20
21 var Command cmd.Handler = bootCommand{}
22
23 type supervisedTask interface {
24         // Execute the task. Run should return nil when the task is
25         // done enough to satisfy a dependency relationship (e.g., the
26         // service is running and ready). If the task starts a
27         // goroutine that fails after Run returns (e.g., the service
28         // shuts down), it should call fail().
29         Run(ctx context.Context, fail func(error), super *Supervisor) error
30         String() string
31 }
32
33 var errNeedConfigReload = errors.New("config changed, restart needed")
34 var errParseFlags = errors.New("error parsing command line arguments")
35
36 type bootCommand struct{}
37
38 func (bcmd bootCommand) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
39         logger := ctxlog.New(stderr, "json", "info")
40         ctx := ctxlog.Context(context.Background(), logger)
41         for {
42                 err := bcmd.run(ctx, prog, args, stdin, stdout, stderr)
43                 if err == errNeedConfigReload {
44                         continue
45                 } else if err == errParseFlags {
46                         return 2
47                 } else if err != nil {
48                         logger.WithError(err).Info("exiting")
49                         return 1
50                 } else {
51                         return 0
52                 }
53         }
54 }
55
56 func (bcmd bootCommand) run(ctx context.Context, prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) error {
57         ctx, cancel := context.WithCancel(ctx)
58         defer cancel()
59         super := &Supervisor{
60                 Stdin:  stdin,
61                 Stderr: stderr,
62                 logger: ctxlog.FromContext(ctx),
63         }
64
65         flags := flag.NewFlagSet(prog, flag.ContinueOnError)
66         versionFlag := flags.Bool("version", false, "Write version information to stdout and exit 0")
67         flags.StringVar(&super.ConfigPath, "config", "/etc/arvados/config.yml", "arvados config file `path`")
68         flags.StringVar(&super.SourcePath, "source", ".", "arvados source tree `directory`")
69         flags.StringVar(&super.ClusterType, "type", "production", "cluster `type`: development, test, or production")
70         flags.StringVar(&super.ListenHost, "listen-host", "127.0.0.1", "host name or interface address for internal services whose InternalURLs are not configured")
71         flags.StringVar(&super.ControllerAddr, "controller-address", ":0", "desired controller address, `host:port` or `:port`")
72         // Default for -workbench2-source is where `arvados-server
73         // install` puts its checkout.
74         flags.StringVar(&super.Workbench2Source, "workbench2-source", "/var/lib/arvados/arvados-workbench2", "path to arvados-workbench2 source tree")
75         flags.BoolVar(&super.NoWorkbench1, "no-workbench1", false, "do not run workbench1")
76         flags.BoolVar(&super.NoWorkbench2, "no-workbench2", false, "do not run workbench2")
77         flags.BoolVar(&super.OwnTemporaryDatabase, "own-temporary-database", false, "bring up a postgres server and create a temporary database")
78         timeout := flags.Duration("timeout", 0, "maximum time to wait for cluster to be ready")
79         shutdown := flags.Bool("shutdown", false, "shut down when the cluster becomes ready")
80         if ok, code := cmd.ParseFlags(flags, prog, args, "", stderr); !ok {
81                 if code == 0 {
82                         return nil
83                 } else {
84                         return errParseFlags
85                 }
86         } else if *versionFlag {
87                 cmd.Version.RunCommand(prog, args, stdin, stdout, stderr)
88                 return nil
89         } else if super.ClusterType != "development" && super.ClusterType != "test" && super.ClusterType != "production" {
90                 return fmt.Errorf("cluster type must be 'development', 'test', or 'production'")
91         }
92
93         super.Start(ctx)
94         defer super.Stop()
95
96         var timer *time.Timer
97         if *timeout > 0 {
98                 timer = time.AfterFunc(*timeout, super.Stop)
99         }
100
101         ok := super.WaitReady()
102         if timer != nil && !timer.Stop() {
103                 return errors.New("boot timed out")
104         } else if !ok {
105                 super.logger.Error("boot failed")
106         } else {
107                 // Write each cluster's controller URL, id, and URL
108                 // host:port to stdout.  Nothing else goes to stdout,
109                 // so this allows a calling script to determine when
110                 // the cluster is ready to use, and the controller's
111                 // host:port (which may have been dynamically assigned
112                 // depending on config/options).
113                 //
114                 // Sort output by cluster ID for convenience.
115                 var ids []string
116                 for id := range super.Clusters() {
117                         ids = append(ids, id)
118                 }
119                 sort.Strings(ids)
120                 for _, id := range ids {
121                         cc := super.Cluster(id)
122                         // Providing both scheme://host:port and
123                         // host:port is redundant, but convenient.
124                         fmt.Fprintln(stdout, cc.Services.Controller.ExternalURL, id, cc.Services.Controller.ExternalURL.Host)
125                 }
126                 // Write ".\n" to mark the end of the list of
127                 // controllers, in case the caller doesn't already
128                 // know how many clusters are coming up.
129                 fmt.Fprintln(stdout, ".")
130                 if *shutdown {
131                         super.Stop()
132                         // Wait for children to exit. Don't report the
133                         // ensuing "context cancelled" error, though:
134                         // return nil to indicate successful startup.
135                         _ = super.Wait()
136                         fmt.Fprintln(stderr, "PASS - all services booted successfully")
137                         return nil
138                 }
139         }
140         if _, err := daemon.SdNotify(false, "READY=1"); err != nil {
141                 super.logger.WithError(err).Errorf("error notifying init daemon")
142         }
143         // Wait for signal/crash + orderly shutdown
144         return super.Wait()
145 }