15954: 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         "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         "git.arvados.org/arvados.git/sdk/go/health"
33         "github.com/sirupsen/logrus"
34 )
35
36 var Command cmd.Handler = bootCommand{}
37
38 type bootCommand struct{}
39
40 func (bootCommand) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
41         boot := &Booter{
42                 Stderr: stderr,
43                 logger: ctxlog.New(stderr, "json", "info"),
44         }
45
46         ctx := ctxlog.Context(context.Background(), boot.logger)
47         ctx, cancel := context.WithCancel(ctx)
48         defer cancel()
49
50         ch := make(chan os.Signal)
51         signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
52         go func() {
53                 for sig := range ch {
54                         boot.logger.WithField("signal", sig).Info("caught signal")
55                         cancel()
56                 }
57         }()
58
59         var err error
60         defer func() {
61                 if err != nil {
62                         boot.logger.WithError(err).Info("exiting")
63                 }
64         }()
65
66         flags := flag.NewFlagSet(prog, flag.ContinueOnError)
67         flags.SetOutput(stderr)
68         loader := config.NewLoader(stdin, boot.logger)
69         loader.SetupFlags(flags)
70         versionFlag := flags.Bool("version", false, "Write version information to stdout and exit 0")
71         flags.StringVar(&boot.SourcePath, "source", ".", "arvados source tree `directory`")
72         flags.StringVar(&boot.LibPath, "lib", "/var/lib/arvados", "`directory` to install dependencies and library files")
73         flags.StringVar(&boot.ClusterType, "type", "production", "cluster `type`: development, test, or production")
74         err = flags.Parse(args)
75         if err == flag.ErrHelp {
76                 err = nil
77                 return 0
78         } else if err != nil {
79                 return 2
80         } else if *versionFlag {
81                 return cmd.Version.RunCommand(prog, args, stdin, stdout, stderr)
82         } else if boot.ClusterType != "development" && boot.ClusterType != "test" && boot.ClusterType != "production" {
83                 err = fmt.Errorf("cluster type must be 'development', 'test', or 'production'")
84                 return 2
85         }
86
87         boot.Start(ctx, loader)
88         defer boot.Stop()
89         if boot.WaitReady() {
90                 fmt.Fprintln(stdout, boot.cluster.Services.Controller.ExternalURL)
91                 <-ctx.Done() // wait for signal
92                 return 0
93         } else {
94                 return 1
95         }
96 }
97
98 type Booter struct {
99         SourcePath  string // e.g., /home/username/src/arvados
100         LibPath     string // e.g., /var/lib/arvados
101         ClusterType string // e.g., production
102         Stderr      io.Writer
103
104         logger  logrus.FieldLogger
105         cluster *arvados.Cluster
106
107         ctx           context.Context
108         cancel        context.CancelFunc
109         done          chan struct{}
110         healthChecker *health.Aggregator
111
112         tempdir    string
113         configfile string
114         environ    []string // for child processes
115
116         setupRubyOnce sync.Once
117         setupRubyErr  error
118         goMutex       sync.Mutex
119 }
120
121 func (boot *Booter) Start(ctx context.Context, loader *config.Loader) {
122         boot.ctx, boot.cancel = context.WithCancel(ctx)
123         boot.done = make(chan struct{})
124         go func() {
125                 err := boot.run(loader)
126                 if err != nil {
127                         fmt.Fprintln(boot.Stderr, err)
128                 }
129                 close(boot.done)
130         }()
131 }
132
133 func (boot *Booter) run(loader *config.Loader) error {
134         cwd, err := os.Getwd()
135         if err != nil {
136                 return err
137         }
138         if !strings.HasPrefix(boot.SourcePath, "/") {
139                 boot.SourcePath = filepath.Join(cwd, boot.SourcePath)
140         }
141         boot.SourcePath, err = filepath.EvalSymlinks(boot.SourcePath)
142         if err != nil {
143                 return err
144         }
145
146         boot.tempdir, err = ioutil.TempDir("", "arvados-server-boot-")
147         if err != nil {
148                 return err
149         }
150         defer os.RemoveAll(boot.tempdir)
151
152         loader.SkipAPICalls = true
153         cfg, err := loader.Load()
154         if err != nil {
155                 return err
156         }
157
158         // Fill in any missing config keys, and write the resulting
159         // config in the temp dir for child services to use.
160         err = boot.autofillConfig(cfg, boot.logger)
161         if err != nil {
162                 return err
163         }
164         conffile, err := os.OpenFile(filepath.Join(boot.tempdir, "config.yml"), os.O_CREATE|os.O_WRONLY, 0777)
165         if err != nil {
166                 return err
167         }
168         defer conffile.Close()
169         err = json.NewEncoder(conffile).Encode(cfg)
170         if err != nil {
171                 return err
172         }
173         err = conffile.Close()
174         if err != nil {
175                 return err
176         }
177         boot.configfile = conffile.Name()
178
179         boot.environ = os.Environ()
180         boot.setEnv("ARVADOS_CONFIG", boot.configfile)
181         boot.setEnv("RAILS_ENV", boot.ClusterType)
182         boot.prependEnv("PATH", filepath.Join(boot.LibPath, "bin")+":")
183
184         boot.cluster, err = cfg.GetCluster("")
185         if err != nil {
186                 return err
187         }
188         // Now that we have the config, replace the bootstrap logger
189         // with a new one according to the logging config.
190         boot.logger = ctxlog.New(boot.Stderr, boot.cluster.SystemLogs.Format, boot.cluster.SystemLogs.LogLevel).WithFields(logrus.Fields{
191                 "PID": os.Getpid(),
192         })
193         boot.healthChecker = &health.Aggregator{Cluster: boot.cluster}
194
195         for _, dir := range []string{boot.LibPath, filepath.Join(boot.LibPath, "bin")} {
196                 if _, err = os.Stat(filepath.Join(dir, ".")); os.IsNotExist(err) {
197                         err = os.Mkdir(dir, 0755)
198                         if err != nil {
199                                 return err
200                         }
201                 } else if err != nil {
202                         return err
203                 }
204         }
205         err = boot.installGoProgram(boot.ctx, "cmd/arvados-server")
206         if err != nil {
207                 return err
208         }
209         err = boot.setupRubyEnv()
210         if err != nil {
211                 return err
212         }
213
214         var wg sync.WaitGroup
215         for _, cmpt := range []component{
216                 {name: "nginx", runFunc: runNginx},
217                 {name: "controller", cmdHandler: controller.Command},
218                 {name: "dispatchcloud", cmdHandler: dispatchcloud.Command, notIfTest: true},
219                 {name: "git-httpd", goProg: "services/arv-git-httpd"},
220                 {name: "health", goProg: "services/health"},
221                 {name: "keep-balance", goProg: "services/keep-balance", notIfTest: true},
222                 {name: "keepproxy", goProg: "services/keepproxy"},
223                 {name: "keepstore", goProg: "services/keepstore", svc: boot.cluster.Services.Keepstore},
224                 {name: "keep-web", goProg: "services/keep-web"},
225                 {name: "railsAPI", svc: boot.cluster.Services.RailsAPI, railsApp: "services/api"},
226                 {name: "workbench1", svc: boot.cluster.Services.Workbench1, railsApp: "apps/workbench"},
227                 {name: "ws", goProg: "services/ws"},
228         } {
229                 cmpt := cmpt
230                 wg.Add(1)
231                 go func() {
232                         defer wg.Done()
233                         defer boot.cancel()
234                         boot.logger.WithField("component", cmpt.name).Info("starting")
235                         err := cmpt.Run(boot.ctx, boot)
236                         if err != nil && err != context.Canceled {
237                                 boot.logger.WithError(err).WithField("component", cmpt.name).Error("exited")
238                         }
239                 }()
240         }
241         wg.Wait()
242         return nil
243 }
244
245 func (boot *Booter) Stop() {
246         boot.cancel()
247         <-boot.done
248 }
249
250 func (boot *Booter) WaitReady() bool {
251         for waiting := true; waiting; {
252                 time.Sleep(time.Second)
253                 if boot.ctx.Err() != nil {
254                         return false
255                 }
256                 if boot.healthChecker == nil {
257                         // not set up yet
258                         continue
259                 }
260                 resp := boot.healthChecker.ClusterHealth()
261                 // The overall health check (resp.Health=="OK") might
262                 // never pass due to missing components (like
263                 // arvados-dispatch-cloud in a test cluster), so
264                 // instead we wait for all configured components to
265                 // pass.
266                 waiting = false
267                 for _, check := range resp.Checks {
268                         if check.Health != "OK" {
269                                 waiting = true
270                         }
271                 }
272         }
273         return true
274 }
275
276 func (boot *Booter) prependEnv(key, prepend string) {
277         for i, s := range boot.environ {
278                 if strings.HasPrefix(s, key+"=") {
279                         boot.environ[i] = key + "=" + prepend + s[len(key)+1:]
280                         return
281                 }
282         }
283         boot.environ = append(boot.environ, key+"="+prepend)
284 }
285
286 func (boot *Booter) setEnv(key, val string) {
287         for i, s := range boot.environ {
288                 if strings.HasPrefix(s, key+"=") {
289                         boot.environ[i] = key + "=" + val
290                         return
291                 }
292         }
293         boot.environ = append(boot.environ, key+"="+val)
294 }
295
296 func (boot *Booter) installGoProgram(ctx context.Context, srcpath string) error {
297         boot.goMutex.Lock()
298         defer boot.goMutex.Unlock()
299         return boot.RunProgram(ctx, filepath.Join(boot.SourcePath, srcpath), nil, []string{"GOPATH=" + boot.LibPath}, "go", "install")
300 }
301
302 func (boot *Booter) setupRubyEnv() error {
303         buf, err := exec.Command("gem", "env", "gempath").Output() // /var/lib/arvados/.gem/ruby/2.5.0/bin:...
304         if err != nil || len(buf) == 0 {
305                 return fmt.Errorf("gem env gempath: %v", err)
306         }
307         gempath := string(bytes.Split(buf, []byte{':'})[0])
308         boot.prependEnv("PATH", gempath+"/bin:")
309         boot.setEnv("GEM_HOME", gempath)
310         boot.setEnv("GEM_PATH", gempath)
311         return nil
312 }
313
314 func (boot *Booter) lookPath(prog string) string {
315         for _, val := range boot.environ {
316                 if strings.HasPrefix(val, "PATH=") {
317                         for _, dir := range filepath.SplitList(val[5:]) {
318                                 path := filepath.Join(dir, prog)
319                                 if fi, err := os.Stat(path); err == nil && fi.Mode()&0111 != 0 {
320                                         return path
321                                 }
322                         }
323                 }
324         }
325         return prog
326 }
327
328 // Run prog with args, using dir as working directory. If ctx is
329 // cancelled while the child is running, RunProgram terminates the
330 // child, waits for it to exit, then returns.
331 //
332 // Child's environment will have our env vars, plus any given in env.
333 //
334 // Child's stdout will be written to output if non-nil, otherwise the
335 // boot command's stderr.
336 func (boot *Booter) RunProgram(ctx context.Context, dir string, output io.Writer, env []string, prog string, args ...string) error {
337         cmdline := fmt.Sprintf("%s", append([]string{prog}, args...))
338         fmt.Fprintf(boot.Stderr, "%s executing in %s\n", cmdline, dir)
339         cmd := exec.Command(boot.lookPath(prog), args...)
340         if output == nil {
341                 cmd.Stdout = boot.Stderr
342         } else {
343                 cmd.Stdout = output
344         }
345         cmd.Stderr = boot.Stderr
346         if strings.HasPrefix(dir, "/") {
347                 cmd.Dir = dir
348         } else {
349                 cmd.Dir = filepath.Join(boot.SourcePath, dir)
350         }
351         cmd.Env = append(env, boot.environ...)
352
353         exited := false
354         defer func() { exited = true }()
355         go func() {
356                 <-ctx.Done()
357                 log := ctxlog.FromContext(ctx).WithFields(logrus.Fields{"dir": dir, "cmdline": cmdline})
358                 for !exited {
359                         if cmd.Process == nil {
360                                 log.Debug("waiting for child process to start")
361                                 time.Sleep(time.Second / 2)
362                         } else {
363                                 log.WithField("PID", cmd.Process.Pid).Debug("sending SIGTERM")
364                                 cmd.Process.Signal(syscall.SIGTERM)
365                                 time.Sleep(5 * time.Second)
366                                 if !exited {
367                                         log.WithField("PID", cmd.Process.Pid).Warn("still waiting for child process to exit 5s after SIGTERM")
368                                 }
369                         }
370                 }
371         }()
372
373         err := cmd.Run()
374         if err != nil && ctx.Err() == nil {
375                 // Only report errors that happen before the context ends.
376                 return fmt.Errorf("%s: error: %v", cmdline, err)
377         }
378         return nil
379 }
380
381 type component struct {
382         name       string
383         svc        arvados.Service
384         cmdHandler cmd.Handler
385         runFunc    func(ctx context.Context, boot *Booter) error
386         railsApp   string // source dir in arvados tree, e.g., "services/api"
387         goProg     string // source dir in arvados tree, e.g., "services/keepstore"
388         notIfTest  bool   // don't run this component on a test cluster
389 }
390
391 func (cmpt *component) Run(ctx context.Context, boot *Booter) error {
392         if cmpt.notIfTest && boot.ClusterType == "test" {
393                 fmt.Fprintf(boot.Stderr, "skipping component %q in %s mode\n", cmpt.name, boot.ClusterType)
394                 <-ctx.Done()
395                 return nil
396         }
397         fmt.Fprintf(boot.Stderr, "starting component %q\n", cmpt.name)
398         if cmpt.cmdHandler != nil {
399                 errs := make(chan error, 1)
400                 go func() {
401                         defer close(errs)
402                         exitcode := cmpt.cmdHandler.RunCommand(cmpt.name, []string{"-config", boot.configfile}, bytes.NewBuffer(nil), boot.Stderr, boot.Stderr)
403                         if exitcode != 0 {
404                                 errs <- fmt.Errorf("exit code %d", exitcode)
405                         }
406                 }()
407                 select {
408                 case err := <-errs:
409                         return err
410                 case <-ctx.Done():
411                         // cmpt.cmdHandler.RunCommand() doesn't have
412                         // access to our context, so it won't shut
413                         // down by itself. We just abandon it.
414                         return nil
415                 }
416         }
417         if cmpt.goProg != "" {
418                 boot.RunProgram(ctx, cmpt.goProg, nil, nil, "go", "install")
419                 if ctx.Err() != nil {
420                         return nil
421                 }
422                 _, basename := filepath.Split(cmpt.goProg)
423                 if len(cmpt.svc.InternalURLs) > 0 {
424                         // Run one for each URL
425                         var wg sync.WaitGroup
426                         for u := range cmpt.svc.InternalURLs {
427                                 u := u
428                                 wg.Add(1)
429                                 go func() {
430                                         defer wg.Done()
431                                         boot.RunProgram(ctx, boot.tempdir, nil, []string{"ARVADOS_SERVICE_INTERNAL_URL=" + u.String()}, basename)
432                                 }()
433                         }
434                         wg.Wait()
435                 } else {
436                         // Just run one
437                         boot.RunProgram(ctx, boot.tempdir, nil, nil, basename)
438                 }
439                 return nil
440         }
441         if cmpt.runFunc != nil {
442                 return cmpt.runFunc(ctx, boot)
443         }
444         if cmpt.railsApp != "" {
445                 port, err := internalPort(cmpt.svc)
446                 if err != nil {
447                         return fmt.Errorf("bug: no InternalURLs for component %q: %v", cmpt.name, cmpt.svc.InternalURLs)
448                 }
449                 var buf bytes.Buffer
450                 err = boot.RunProgram(ctx, cmpt.railsApp, &buf, nil, "gem", "list", "--details", "bundler")
451                 if err != nil {
452                         return err
453                 }
454                 for _, version := range []string{"1.11.0", "1.17.3", "2.0.2"} {
455                         if !strings.Contains(buf.String(), "("+version+")") {
456                                 err = boot.RunProgram(ctx, cmpt.railsApp, nil, nil, "gem", "install", "--user", "bundler:1.11", "bundler:1.17.3", "bundler:2.0.2")
457                                 if err != nil {
458                                         return err
459                                 }
460                                 break
461                         }
462                 }
463                 err = boot.RunProgram(ctx, cmpt.railsApp, nil, nil, "bundle", "install", "--jobs", "4", "--path", filepath.Join(os.Getenv("HOME"), ".gem"))
464                 if err != nil {
465                         return err
466                 }
467                 err = boot.RunProgram(ctx, cmpt.railsApp, nil, nil, "bundle", "exec", "passenger-config", "build-native-support")
468                 if err != nil {
469                         return err
470                 }
471                 err = boot.RunProgram(ctx, cmpt.railsApp, nil, nil, "bundle", "exec", "passenger-config", "install-standalone-runtime")
472                 if err != nil {
473                         return err
474                 }
475                 err = boot.RunProgram(ctx, cmpt.railsApp, nil, nil, "bundle", "exec", "passenger-config", "validate-install")
476                 if err != nil {
477                         return err
478                 }
479                 err = boot.RunProgram(ctx, cmpt.railsApp, nil, nil, "bundle", "exec", "passenger", "start", "-p", port)
480                 if err != nil {
481                         return err
482                 }
483                 return nil
484         }
485         return fmt.Errorf("bug: component %q has nothing to run", cmpt.name)
486 }
487
488 func (boot *Booter) autofillConfig(cfg *arvados.Config, log logrus.FieldLogger) error {
489         cluster, err := cfg.GetCluster("")
490         if err != nil {
491                 return err
492         }
493         port := 9000
494         for _, svc := range []*arvados.Service{
495                 &cluster.Services.Controller,
496                 &cluster.Services.DispatchCloud,
497                 &cluster.Services.GitHTTP,
498                 &cluster.Services.Health,
499                 &cluster.Services.Keepproxy,
500                 &cluster.Services.Keepstore,
501                 &cluster.Services.RailsAPI,
502                 &cluster.Services.WebDAV,
503                 &cluster.Services.WebDAVDownload,
504                 &cluster.Services.Websocket,
505                 &cluster.Services.Workbench1,
506         } {
507                 if svc == &cluster.Services.DispatchCloud && boot.ClusterType == "test" {
508                         continue
509                 }
510                 if len(svc.InternalURLs) == 0 {
511                         port++
512                         svc.InternalURLs = map[arvados.URL]arvados.ServiceInstance{
513                                 arvados.URL{Scheme: "http", Host: fmt.Sprintf("localhost:%d", port)}: arvados.ServiceInstance{},
514                         }
515                 }
516                 if svc.ExternalURL.Host == "" && (svc == &cluster.Services.Controller ||
517                         svc == &cluster.Services.GitHTTP ||
518                         svc == &cluster.Services.Keepproxy ||
519                         svc == &cluster.Services.WebDAV ||
520                         svc == &cluster.Services.WebDAVDownload ||
521                         svc == &cluster.Services.Websocket ||
522                         svc == &cluster.Services.Workbench1) {
523                         port++
524                         svc.ExternalURL = arvados.URL{Scheme: "https", Host: fmt.Sprintf("localhost:%d", port)}
525                 }
526         }
527         if cluster.SystemRootToken == "" {
528                 cluster.SystemRootToken = randomHexString(64)
529         }
530         if cluster.ManagementToken == "" {
531                 cluster.ManagementToken = randomHexString(64)
532         }
533         if cluster.API.RailsSessionSecretToken == "" {
534                 cluster.API.RailsSessionSecretToken = randomHexString(64)
535         }
536         if cluster.Collections.BlobSigningKey == "" {
537                 cluster.Collections.BlobSigningKey = randomHexString(64)
538         }
539         if boot.ClusterType != "production" && cluster.Containers.DispatchPrivateKey == "" {
540                 buf, err := ioutil.ReadFile(filepath.Join(boot.SourcePath, "lib", "dispatchcloud", "test", "sshkey_dispatch"))
541                 if err != nil {
542                         return err
543                 }
544                 cluster.Containers.DispatchPrivateKey = string(buf)
545         }
546         if boot.ClusterType != "production" {
547                 cluster.TLS.Insecure = true
548         }
549         if boot.ClusterType == "test" {
550                 // Add a second keepstore process.
551                 port++
552                 cluster.Services.Keepstore.InternalURLs[arvados.URL{Scheme: "http", Host: fmt.Sprintf("localhost:%d", port)}] = arvados.ServiceInstance{}
553
554                 // Create a directory-backed volume for each keepstore
555                 // process.
556                 cluster.Volumes = map[string]arvados.Volume{}
557                 for url := range cluster.Services.Keepstore.InternalURLs {
558                         volnum := len(cluster.Volumes)
559                         datadir := fmt.Sprintf("%s/keep%d.data", boot.tempdir, volnum)
560                         if _, err = os.Stat(datadir + "/."); err == nil {
561                         } else if !os.IsNotExist(err) {
562                                 return err
563                         } else if err = os.Mkdir(datadir, 0777); err != nil {
564                                 return err
565                         }
566                         cluster.Volumes[fmt.Sprintf("zzzzz-nyw5e-%015d", volnum)] = arvados.Volume{
567                                 Driver:           "Directory",
568                                 DriverParameters: json.RawMessage(fmt.Sprintf(`{"Root":%q}`, datadir)),
569                                 AccessViaHosts: map[arvados.URL]arvados.VolumeAccess{
570                                         url: {},
571                                 },
572                         }
573                 }
574         }
575         cfg.Clusters[cluster.ClusterID] = *cluster
576         return nil
577 }
578
579 func randomHexString(chars int) string {
580         b := make([]byte, chars/2)
581         _, err := rand.Read(b)
582         if err != nil {
583                 panic(err)
584         }
585         return fmt.Sprintf("%x", b)
586 }
587
588 func internalPort(svc arvados.Service) (string, error) {
589         for u := range svc.InternalURLs {
590                 if _, p, err := net.SplitHostPort(u.Host); err != nil {
591                         return "", err
592                 } else if p != "" {
593                         return p, nil
594                 } else if u.Scheme == "https" {
595                         return "443", nil
596                 } else {
597                         return "80", nil
598                 }
599         }
600         return "", fmt.Errorf("service has no InternalURLs")
601 }
602
603 func externalPort(svc arvados.Service) (string, error) {
604         if _, p, err := net.SplitHostPort(svc.ExternalURL.Host); err != nil {
605                 return "", err
606         } else if p != "" {
607                 return p, nil
608         } else if svc.ExternalURL.Scheme == "https" {
609                 return "443", nil
610         } else {
611                 return "80", nil
612         }
613 }