17170: Merge branch 'master'
[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         "time"
14
15         "git.arvados.org/arvados.git/lib/cmd"
16         "git.arvados.org/arvados.git/lib/config"
17         "git.arvados.org/arvados.git/sdk/go/ctxlog"
18 )
19
20 var Command cmd.Handler = bootCommand{}
21
22 type supervisedTask interface {
23         // Execute the task. Run should return nil when the task is
24         // done enough to satisfy a dependency relationship (e.g., the
25         // service is running and ready). If the task starts a
26         // goroutine that fails after Run returns (e.g., the service
27         // shuts down), it should call fail().
28         Run(ctx context.Context, fail func(error), super *Supervisor) error
29         String() string
30 }
31
32 var errNeedConfigReload = errors.New("config changed, restart needed")
33
34 type bootCommand struct{}
35
36 func (bcmd bootCommand) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
37         logger := ctxlog.New(stderr, "json", "info")
38         ctx := ctxlog.Context(context.Background(), logger)
39         for {
40                 err := bcmd.run(ctx, prog, args, stdin, stdout, stderr)
41                 if err == errNeedConfigReload {
42                         continue
43                 } else if err != nil {
44                         logger.WithError(err).Info("exiting")
45                         return 1
46                 } else {
47                         return 0
48                 }
49         }
50 }
51
52 func (bcmd bootCommand) run(ctx context.Context, prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) error {
53         ctx, cancel := context.WithCancel(ctx)
54         defer cancel()
55         super := &Supervisor{
56                 Stderr: stderr,
57                 logger: ctxlog.FromContext(ctx),
58         }
59
60         flags := flag.NewFlagSet(prog, flag.ContinueOnError)
61         flags.SetOutput(stderr)
62         loader := config.NewLoader(stdin, super.logger)
63         loader.SetupFlags(flags)
64         versionFlag := flags.Bool("version", false, "Write version information to stdout and exit 0")
65         flags.StringVar(&super.SourcePath, "source", ".", "arvados source tree `directory`")
66         flags.StringVar(&super.ClusterType, "type", "production", "cluster `type`: development, test, or production")
67         flags.StringVar(&super.ListenHost, "listen-host", "localhost", "host name or interface address for service listeners")
68         flags.StringVar(&super.ControllerAddr, "controller-address", ":0", "desired controller address, `host:port` or `:port`")
69         flags.BoolVar(&super.OwnTemporaryDatabase, "own-temporary-database", false, "bring up a postgres server and create a temporary database")
70         timeout := flags.Duration("timeout", 0, "maximum time to wait for cluster to be ready")
71         shutdown := flags.Bool("shutdown", false, "shut down when the cluster becomes ready")
72         err := flags.Parse(args)
73         if err == flag.ErrHelp {
74                 return nil
75         } else if err != nil {
76                 return err
77         } else if *versionFlag {
78                 cmd.Version.RunCommand(prog, args, stdin, stdout, stderr)
79                 return nil
80         } else if super.ClusterType != "development" && super.ClusterType != "test" && super.ClusterType != "production" {
81                 return fmt.Errorf("cluster type must be 'development', 'test', or 'production'")
82         }
83
84         loader.SkipAPICalls = true
85         cfg, err := loader.Load()
86         if err != nil {
87                 return err
88         }
89
90         super.Start(ctx, cfg, loader.Path)
91         defer super.Stop()
92
93         var timer *time.Timer
94         if *timeout > 0 {
95                 timer = time.AfterFunc(*timeout, super.Stop)
96         }
97
98         url, ok := super.WaitReady()
99         if timer != nil && !timer.Stop() {
100                 return errors.New("boot timed out")
101         } else if !ok {
102                 super.logger.Error("boot failed")
103         } else {
104                 // Write controller URL to stdout. Nothing else goes
105                 // to stdout, so this provides an easy way for a
106                 // calling script to discover the controller URL when
107                 // everything is ready.
108                 fmt.Fprintln(stdout, url)
109                 if *shutdown {
110                         super.Stop()
111                         // Wait for children to exit. Don't report the
112                         // ensuing "context cancelled" error, though:
113                         // return nil to indicate successful startup.
114                         _ = super.Wait()
115                         fmt.Fprintln(stderr, "PASS - all services booted successfully")
116                         return nil
117                 }
118         }
119         // Wait for signal/crash + orderly shutdown
120         return super.Wait()
121 }