15954: Fix process start/stop race.
[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         "bytes"
9         "context"
10         "crypto/rand"
11         "encoding/json"
12         "flag"
13         "fmt"
14         "io"
15         "io/ioutil"
16         "net"
17         "os"
18         "os/exec"
19         "os/signal"
20         "path/filepath"
21         "strings"
22         "sync"
23         "syscall"
24         "time"
25
26         "git.arvados.org/arvados.git/lib/cmd"
27         "git.arvados.org/arvados.git/lib/config"
28         "git.arvados.org/arvados.git/lib/controller"
29         "git.arvados.org/arvados.git/lib/dispatchcloud"
30         "git.arvados.org/arvados.git/sdk/go/arvados"
31         "git.arvados.org/arvados.git/sdk/go/ctxlog"
32         "github.com/sirupsen/logrus"
33 )
34
35 var Command cmd.Handler = &bootCommand{}
36
37 type bootCommand struct {
38         sourcePath  string // e.g., /home/username/src/arvados
39         libPath     string // e.g., /var/lib/arvados
40         clusterType string // e.g., production
41
42         stdout io.Writer
43         stderr io.Writer
44
45         setupRubyOnce sync.Once
46         setupRubyErr  error
47         goMutex       sync.Mutex
48 }
49
50 func (boot *bootCommand) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
51         boot.stdout = stdout
52         boot.stderr = stderr
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
62         flags := flag.NewFlagSet(prog, flag.ContinueOnError)
63         flags.SetOutput(stderr)
64         loader := config.NewLoader(stdin, log)
65         loader.SetupFlags(flags)
66         versionFlag := flags.Bool("version", false, "Write version information to stdout and exit 0")
67         flags.StringVar(&boot.sourcePath, "source", ".", "arvados source tree `directory`")
68         flags.StringVar(&boot.libPath, "lib", "/var/lib/arvados", "`directory` to install dependencies and library files")
69         flags.StringVar(&boot.clusterType, "type", "production", "cluster `type`: development, test, or production")
70         err = flags.Parse(args)
71         if err == flag.ErrHelp {
72                 err = nil
73                 return 0
74         } else if err != nil {
75                 return 2
76         } else if *versionFlag {
77                 return cmd.Version.RunCommand(prog, args, stdin, stdout, stderr)
78         } else if boot.clusterType != "development" && boot.clusterType != "test" && boot.clusterType != "production" {
79                 err = fmt.Errorf("cluster type must be 'development', 'test', or 'production'")
80                 return 2
81         }
82
83         cwd, err := os.Getwd()
84         if err != nil {
85                 return 1
86         }
87         if !strings.HasPrefix(boot.sourcePath, "/") {
88                 boot.sourcePath = filepath.Join(cwd, boot.sourcePath)
89         }
90         boot.sourcePath, err = filepath.EvalSymlinks(boot.sourcePath)
91         if err != nil {
92                 return 1
93         }
94
95         loader.SkipAPICalls = true
96         cfg, err := loader.Load()
97         if err != nil {
98                 return 1
99         }
100
101         tempdir, err := ioutil.TempDir("", "arvados-server-boot-")
102         if err != nil {
103                 return 1
104         }
105         defer os.RemoveAll(tempdir)
106
107         // Fill in any missing config keys, and write the resulting
108         // config in the temp dir for child services to use.
109         err = boot.autofillConfig(cfg, log)
110         if err != nil {
111                 return 1
112         }
113         conffile, err := os.OpenFile(filepath.Join(tempdir, "config.yml"), os.O_CREATE|os.O_WRONLY, 0777)
114         if err != nil {
115                 return 1
116         }
117         defer conffile.Close()
118         err = json.NewEncoder(conffile).Encode(cfg)
119         if err != nil {
120                 return 1
121         }
122         err = conffile.Close()
123         if err != nil {
124                 return 1
125         }
126         os.Setenv("ARVADOS_CONFIG", conffile.Name())
127
128         os.Setenv("RAILS_ENV", boot.clusterType)
129
130         // Now that we have the config, replace the bootstrap logger
131         // with a new one according to the logging config.
132         cluster, err := cfg.GetCluster("")
133         if err != nil {
134                 return 1
135         }
136         log = ctxlog.New(stderr, cluster.SystemLogs.Format, cluster.SystemLogs.LogLevel)
137         logger := log.WithFields(logrus.Fields{
138                 "PID": os.Getpid(),
139         })
140         ctx := ctxlog.Context(context.Background(), logger)
141         ctx, cancel := context.WithCancel(ctx)
142         defer cancel()
143
144         ch := make(chan os.Signal)
145         signal.Notify(ch, syscall.SIGINT)
146         go func() {
147                 for sig := range ch {
148                         logger.WithField("signal", sig).Info("caught signal")
149                         cancel()
150                 }
151         }()
152
153         for _, dir := range []string{boot.libPath, filepath.Join(boot.libPath, "bin")} {
154                 if _, err = os.Stat(filepath.Join(dir, ".")); os.IsNotExist(err) {
155                         err = os.Mkdir(dir, 0755)
156                         if err != nil {
157                                 return 1
158                         }
159                 } else if err != nil {
160                         return 1
161                 }
162         }
163         os.Setenv("PATH", filepath.Join(boot.libPath, "bin")+":"+os.Getenv("PATH"))
164
165         err = boot.installGoProgram(ctx, "cmd/arvados-server")
166         if err != nil {
167                 return 1
168         }
169
170         var wg sync.WaitGroup
171         for _, cmpt := range []component{
172                 {name: "controller", cmdArgs: []string{"-config", conffile.Name()}, cmdHandler: controller.Command},
173                 {name: "dispatchcloud", cmdArgs: []string{"-config", conffile.Name()}, cmdHandler: dispatchcloud.Command, notIfTest: true},
174                 {name: "keepproxy", goProg: "services/keepproxy"},
175                 {name: "railsAPI", svc: cluster.Services.RailsAPI, railsApp: "services/api"},
176         } {
177                 cmpt := cmpt
178                 wg.Add(1)
179                 go func() {
180                         defer wg.Done()
181                         defer cancel()
182                         logger.WithField("component", cmpt.name).Info("starting")
183                         err := cmpt.Run(ctx, boot, stdout, stderr)
184                         if err != nil {
185                                 logger.WithError(err).WithField("component", cmpt.name).Info("exited")
186                         }
187                 }()
188         }
189         <-ctx.Done()
190         wg.Wait()
191         return 0
192 }
193
194 func (boot *bootCommand) installGoProgram(ctx context.Context, srcpath string) error {
195         boot.goMutex.Lock()
196         defer boot.goMutex.Unlock()
197         env := append([]string{"GOPATH=" + boot.libPath}, os.Environ()...)
198         return boot.RunProgram(ctx, filepath.Join(boot.sourcePath, srcpath), nil, env, "go", "install")
199 }
200
201 func (boot *bootCommand) setupRubyEnv() error {
202         boot.setupRubyOnce.Do(func() {
203                 buf, err := exec.Command("gem", "env", "gempath").Output() // /var/lib/arvados/.gem/ruby/2.5.0/bin:...
204                 if err != nil || len(buf) == 0 {
205                         boot.setupRubyErr = fmt.Errorf("gem env gempath: %v", err)
206                 }
207                 gempath := string(bytes.Split(buf, []byte{':'})[0])
208                 os.Setenv("PATH", gempath+"/bin:"+os.Getenv("PATH"))
209                 os.Setenv("GEM_HOME", gempath)
210                 os.Setenv("GEM_PATH", gempath)
211         })
212         return boot.setupRubyErr
213 }
214
215 func (boot *bootCommand) RunProgram(ctx context.Context, dir string, output io.Writer, env []string, prog string, args ...string) error {
216         cmdline := fmt.Sprintf("%s", append([]string{prog}, args...))
217         fmt.Fprintf(boot.stderr, "%s executing in %s\n", cmdline, dir)
218         cmd := exec.Command(prog, args...)
219         if output == nil {
220                 cmd.Stdout = boot.stderr
221         } else {
222                 cmd.Stdout = output
223         }
224         cmd.Stderr = boot.stderr
225         if strings.HasPrefix(dir, "/") {
226                 cmd.Dir = dir
227         } else {
228                 cmd.Dir = filepath.Join(boot.sourcePath, dir)
229         }
230         if env != nil {
231                 cmd.Env = env
232         }
233         go func() {
234                 <-ctx.Done()
235                 log := ctxlog.FromContext(ctx).WithFields(logrus.Fields{"dir": dir, "cmdline": cmdline})
236                 for cmd.ProcessState != nil {
237                         if cmd.Process == nil {
238                                 log.Infof("waiting for child process to start")
239                                 time.Sleep(time.Second)
240                         } else {
241                                 cmd.Process.Signal(syscall.SIGINT)
242                                 log.WithField("PID", cmd.Process.Pid).Infof("waiting for child process to exit after SIGINT")
243                                 time.Sleep(5 * time.Second)
244                         }
245                 }
246         }()
247         err := cmd.Run()
248         if err != nil {
249                 return fmt.Errorf("%s: error: %v", cmdline, err)
250         }
251         return nil
252 }
253
254 type component struct {
255         name       string
256         svc        arvados.Service
257         cmdHandler cmd.Handler
258         cmdArgs    []string
259         railsApp   string // source dir in arvados tree, e.g., "services/api"
260         goProg     string // source dir in arvados tree, e.g., "services/keepstore"
261         notIfTest  bool   // don't run this component on a test cluster
262 }
263
264 func (cmpt *component) Run(ctx context.Context, boot *bootCommand, stdout, stderr io.Writer) error {
265         if cmpt.notIfTest && boot.clusterType == "test" {
266                 fmt.Fprintf(stderr, "skipping component %q\n", cmpt.name)
267                 <-ctx.Done()
268                 return nil
269         }
270         fmt.Fprintf(stderr, "starting component %q\n", cmpt.name)
271         if cmpt.cmdHandler != nil {
272                 errs := make(chan error, 1)
273                 go func() {
274                         defer close(errs)
275                         exitcode := cmpt.cmdHandler.RunCommand(cmpt.name, cmpt.cmdArgs, bytes.NewBuffer(nil), stdout, stderr)
276                         if exitcode != 0 {
277                                 errs <- fmt.Errorf("exit code %d", exitcode)
278                         }
279                 }()
280                 select {
281                 case err := <-errs:
282                         return err
283                 case <-ctx.Done():
284                         // cmpt.cmdHandler.RunCommand() doesn't have
285                         // access to our context, so it won't shut
286                         // down by itself. We just abandon it.
287                         return nil
288                 }
289         }
290         if cmpt.goProg != "" {
291                 return boot.RunProgram(ctx, cmpt.goProg, nil, nil, "go", "run", ".")
292         }
293         if cmpt.railsApp != "" {
294                 port := "-"
295                 for u := range cmpt.svc.InternalURLs {
296                         if _, p, err := net.SplitHostPort(u.Host); err != nil {
297                                 return err
298                         } else if p != "" {
299                                 port = p
300                         } else if u.Scheme == "https" {
301                                 port = "443"
302                         } else {
303                                 port = "80"
304                         }
305                         break
306                 }
307                 if port == "-" {
308                         return fmt.Errorf("bug: no InternalURLs for component %q: %v", cmpt.name, cmpt.svc.InternalURLs)
309                 }
310
311                 err := boot.setupRubyEnv()
312                 if err != nil {
313                         return err
314                 }
315                 var buf bytes.Buffer
316                 err = boot.RunProgram(ctx, cmpt.railsApp, &buf, nil, "gem", "list", "--details", "bundler")
317                 if err != nil {
318                         return err
319                 }
320                 for _, version := range []string{"1.11.0", "1.17.3", "2.0.2"} {
321                         if !strings.Contains(buf.String(), "("+version+")") {
322                                 err = boot.RunProgram(ctx, cmpt.railsApp, nil, nil, "gem", "install", "--user", "bundler:1.11", "bundler:1.17.3", "bundler:2.0.2")
323                                 if err != nil {
324                                         return err
325                                 }
326                                 break
327                         }
328                 }
329                 err = boot.RunProgram(ctx, cmpt.railsApp, nil, nil, "bundle", "install", "--jobs", "4", "--path", filepath.Join(os.Getenv("HOME"), ".gem"))
330                 if err != nil {
331                         return err
332                 }
333                 err = boot.RunProgram(ctx, cmpt.railsApp, nil, nil, "bundle", "exec", "passenger-config", "build-native-support")
334                 if err != nil {
335                         return err
336                 }
337                 err = boot.RunProgram(ctx, cmpt.railsApp, nil, nil, "bundle", "exec", "passenger-config", "install-standalone-runtime")
338                 if err != nil {
339                         return err
340                 }
341                 err = boot.RunProgram(ctx, cmpt.railsApp, nil, nil, "bundle", "exec", "passenger-config", "validate-install")
342                 if err != nil {
343                         return err
344                 }
345                 err = boot.RunProgram(ctx, cmpt.railsApp, nil, nil, "bundle", "exec", "passenger", "start", "-p", port)
346                 if err != nil {
347                         return err
348                 }
349         }
350         return fmt.Errorf("bug: component %q has nothing to run", cmpt.name)
351 }
352
353 func (boot *bootCommand) autofillConfig(cfg *arvados.Config, log logrus.FieldLogger) error {
354         cluster, err := cfg.GetCluster("")
355         if err != nil {
356                 return err
357         }
358         port := 9000
359         for _, svc := range []*arvados.Service{
360                 &cluster.Services.Controller,
361                 &cluster.Services.DispatchCloud,
362                 &cluster.Services.RailsAPI,
363         } {
364                 if len(svc.InternalURLs) == 0 {
365                         port++
366                         svc.InternalURLs = map[arvados.URL]arvados.ServiceInstance{
367                                 arvados.URL{Scheme: "http", Host: fmt.Sprintf("localhost:%d", port)}: arvados.ServiceInstance{},
368                         }
369                 }
370         }
371         if cluster.Services.Controller.ExternalURL.Host == "" {
372                 for k := range cluster.Services.Controller.InternalURLs {
373                         cluster.Services.Controller.ExternalURL = k
374                 }
375         }
376         if cluster.SystemRootToken == "" {
377                 cluster.SystemRootToken = randomHexString(64)
378         }
379         if cluster.API.RailsSessionSecretToken == "" {
380                 cluster.API.RailsSessionSecretToken = randomHexString(64)
381         }
382         if cluster.Collections.BlobSigningKey == "" {
383                 cluster.Collections.BlobSigningKey = randomHexString(64)
384         }
385         if boot.clusterType != "production" && cluster.Containers.DispatchPrivateKey == "" {
386                 buf, err := ioutil.ReadFile(filepath.Join(boot.sourcePath, "lib", "dispatchcloud", "test", "sshkey_dispatch"))
387                 if err != nil {
388                         return err
389                 }
390                 cluster.Containers.DispatchPrivateKey = string(buf)
391         }
392         cfg.Clusters[cluster.ClusterID] = *cluster
393         return nil
394 }
395
396 func randomHexString(chars int) string {
397         b := make([]byte, chars/2)
398         _, err := rand.Read(b)
399         if err != nil {
400                 panic(err)
401         }
402         return fmt.Sprintf("%x", b)
403 }