15954: Refactor for better API.
[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: "ws", goProg: "services/ws"},
227         } {
228                 cmpt := cmpt
229                 wg.Add(1)
230                 go func() {
231                         defer wg.Done()
232                         defer boot.cancel()
233                         boot.logger.WithField("component", cmpt.name).Info("starting")
234                         err := cmpt.Run(boot.ctx, boot)
235                         if err != nil && err != context.Canceled {
236                                 boot.logger.WithError(err).WithField("component", cmpt.name).Error("exited")
237                         }
238                 }()
239         }
240         wg.Wait()
241         return nil
242 }
243
244 func (boot *Booter) Stop() {
245         boot.cancel()
246         <-boot.done
247 }
248
249 func (boot *Booter) WaitReady() bool {
250         for waiting := true; waiting; {
251                 time.Sleep(time.Second)
252                 if boot.ctx.Err() != nil {
253                         return false
254                 }
255                 if boot.healthChecker == nil {
256                         // not set up yet
257                         continue
258                 }
259                 resp := boot.healthChecker.ClusterHealth()
260                 // The overall health check (resp.Health=="OK") might
261                 // never pass due to missing components (like
262                 // arvados-dispatch-cloud in a test cluster), so
263                 // instead we wait for all configured components to
264                 // pass.
265                 waiting = false
266                 for _, check := range resp.Checks {
267                         if check.Health != "OK" {
268                                 waiting = true
269                         }
270                 }
271         }
272         return true
273 }
274
275 func (boot *Booter) prependEnv(key, prepend string) {
276         for i, s := range boot.environ {
277                 if strings.HasPrefix(s, key+"=") {
278                         boot.environ[i] = key + "=" + prepend + s[len(key)+1:]
279                         return
280                 }
281         }
282         boot.environ = append(boot.environ, key+"="+prepend)
283 }
284
285 func (boot *Booter) setEnv(key, val string) {
286         for i, s := range boot.environ {
287                 if strings.HasPrefix(s, key+"=") {
288                         boot.environ[i] = key + "=" + val
289                         return
290                 }
291         }
292         boot.environ = append(boot.environ, key+"="+val)
293 }
294
295 func (boot *Booter) installGoProgram(ctx context.Context, srcpath string) error {
296         boot.goMutex.Lock()
297         defer boot.goMutex.Unlock()
298         return boot.RunProgram(ctx, filepath.Join(boot.SourcePath, srcpath), nil, []string{"GOPATH=" + boot.LibPath}, "go", "install")
299 }
300
301 func (boot *Booter) setupRubyEnv() error {
302         buf, err := exec.Command("gem", "env", "gempath").Output() // /var/lib/arvados/.gem/ruby/2.5.0/bin:...
303         if err != nil || len(buf) == 0 {
304                 return fmt.Errorf("gem env gempath: %v", err)
305         }
306         gempath := string(bytes.Split(buf, []byte{':'})[0])
307         boot.prependEnv("PATH", gempath+"/bin:")
308         boot.setEnv("GEM_HOME", gempath)
309         boot.setEnv("GEM_PATH", gempath)
310         return nil
311 }
312
313 func (boot *Booter) lookPath(prog string) string {
314         for _, val := range boot.environ {
315                 if strings.HasPrefix(val, "PATH=") {
316                         for _, dir := range filepath.SplitList(val[5:]) {
317                                 path := filepath.Join(dir, prog)
318                                 if fi, err := os.Stat(path); err == nil && fi.Mode()&0111 != 0 {
319                                         return path
320                                 }
321                         }
322                 }
323         }
324         return prog
325 }
326
327 // Run prog with args, using dir as working directory. If ctx is
328 // cancelled while the child is running, RunProgram terminates the
329 // child, waits for it to exit, then returns.
330 //
331 // Child's environment will have our env vars, plus any given in env.
332 //
333 // Child's stdout will be written to output if non-nil, otherwise the
334 // boot command's stderr.
335 func (boot *Booter) RunProgram(ctx context.Context, dir string, output io.Writer, env []string, prog string, args ...string) error {
336         cmdline := fmt.Sprintf("%s", append([]string{prog}, args...))
337         fmt.Fprintf(boot.Stderr, "%s executing in %s\n", cmdline, dir)
338         cmd := exec.Command(boot.lookPath(prog), args...)
339         if output == nil {
340                 cmd.Stdout = boot.Stderr
341         } else {
342                 cmd.Stdout = output
343         }
344         cmd.Stderr = boot.Stderr
345         if strings.HasPrefix(dir, "/") {
346                 cmd.Dir = dir
347         } else {
348                 cmd.Dir = filepath.Join(boot.SourcePath, dir)
349         }
350         cmd.Env = append(env, boot.environ...)
351
352         exited := false
353         defer func() { exited = true }()
354         go func() {
355                 <-ctx.Done()
356                 log := ctxlog.FromContext(ctx).WithFields(logrus.Fields{"dir": dir, "cmdline": cmdline})
357                 for !exited {
358                         if cmd.Process == nil {
359                                 log.Debug("waiting for child process to start")
360                                 time.Sleep(time.Second / 2)
361                         } else {
362                                 log.WithField("PID", cmd.Process.Pid).Debug("sending SIGTERM")
363                                 cmd.Process.Signal(syscall.SIGTERM)
364                                 time.Sleep(5 * time.Second)
365                                 if !exited {
366                                         log.WithField("PID", cmd.Process.Pid).Warn("still waiting for child process to exit 5s after SIGTERM")
367                                 }
368                         }
369                 }
370         }()
371
372         err := cmd.Run()
373         if err != nil && ctx.Err() == nil {
374                 // Only report errors that happen before the context ends.
375                 return fmt.Errorf("%s: error: %v", cmdline, err)
376         }
377         return nil
378 }
379
380 type component struct {
381         name       string
382         svc        arvados.Service
383         cmdHandler cmd.Handler
384         runFunc    func(ctx context.Context, boot *Booter) error
385         railsApp   string // source dir in arvados tree, e.g., "services/api"
386         goProg     string // source dir in arvados tree, e.g., "services/keepstore"
387         notIfTest  bool   // don't run this component on a test cluster
388 }
389
390 func (cmpt *component) Run(ctx context.Context, boot *Booter) error {
391         if cmpt.notIfTest && boot.ClusterType == "test" {
392                 fmt.Fprintf(boot.Stderr, "skipping component %q in %s mode\n", cmpt.name, boot.ClusterType)
393                 <-ctx.Done()
394                 return nil
395         }
396         fmt.Fprintf(boot.Stderr, "starting component %q\n", cmpt.name)
397         if cmpt.cmdHandler != nil {
398                 errs := make(chan error, 1)
399                 go func() {
400                         defer close(errs)
401                         exitcode := cmpt.cmdHandler.RunCommand(cmpt.name, []string{"-config", boot.configfile}, bytes.NewBuffer(nil), boot.Stderr, boot.Stderr)
402                         if exitcode != 0 {
403                                 errs <- fmt.Errorf("exit code %d", exitcode)
404                         }
405                 }()
406                 select {
407                 case err := <-errs:
408                         return err
409                 case <-ctx.Done():
410                         // cmpt.cmdHandler.RunCommand() doesn't have
411                         // access to our context, so it won't shut
412                         // down by itself. We just abandon it.
413                         return nil
414                 }
415         }
416         if cmpt.goProg != "" {
417                 boot.RunProgram(ctx, cmpt.goProg, nil, nil, "go", "install")
418                 if ctx.Err() != nil {
419                         return nil
420                 }
421                 _, basename := filepath.Split(cmpt.goProg)
422                 if len(cmpt.svc.InternalURLs) > 0 {
423                         // Run one for each URL
424                         var wg sync.WaitGroup
425                         for u := range cmpt.svc.InternalURLs {
426                                 u := u
427                                 wg.Add(1)
428                                 go func() {
429                                         defer wg.Done()
430                                         boot.RunProgram(ctx, boot.tempdir, nil, []string{"ARVADOS_SERVICE_INTERNAL_URL=" + u.String()}, basename)
431                                 }()
432                         }
433                         wg.Wait()
434                 } else {
435                         // Just run one
436                         boot.RunProgram(ctx, boot.tempdir, nil, nil, basename)
437                 }
438                 return nil
439         }
440         if cmpt.runFunc != nil {
441                 return cmpt.runFunc(ctx, boot)
442         }
443         if cmpt.railsApp != "" {
444                 port, err := internalPort(cmpt.svc)
445                 if err != nil {
446                         return fmt.Errorf("bug: no InternalURLs for component %q: %v", cmpt.name, cmpt.svc.InternalURLs)
447                 }
448                 var buf bytes.Buffer
449                 err = boot.RunProgram(ctx, cmpt.railsApp, &buf, nil, "gem", "list", "--details", "bundler")
450                 if err != nil {
451                         return err
452                 }
453                 for _, version := range []string{"1.11.0", "1.17.3", "2.0.2"} {
454                         if !strings.Contains(buf.String(), "("+version+")") {
455                                 err = boot.RunProgram(ctx, cmpt.railsApp, nil, nil, "gem", "install", "--user", "bundler:1.11", "bundler:1.17.3", "bundler:2.0.2")
456                                 if err != nil {
457                                         return err
458                                 }
459                                 break
460                         }
461                 }
462                 err = boot.RunProgram(ctx, cmpt.railsApp, nil, nil, "bundle", "install", "--jobs", "4", "--path", filepath.Join(os.Getenv("HOME"), ".gem"))
463                 if err != nil {
464                         return err
465                 }
466                 err = boot.RunProgram(ctx, cmpt.railsApp, nil, nil, "bundle", "exec", "passenger-config", "build-native-support")
467                 if err != nil {
468                         return err
469                 }
470                 err = boot.RunProgram(ctx, cmpt.railsApp, nil, nil, "bundle", "exec", "passenger-config", "install-standalone-runtime")
471                 if err != nil {
472                         return err
473                 }
474                 err = boot.RunProgram(ctx, cmpt.railsApp, nil, nil, "bundle", "exec", "passenger-config", "validate-install")
475                 if err != nil {
476                         return err
477                 }
478                 err = boot.RunProgram(ctx, cmpt.railsApp, nil, nil, "bundle", "exec", "passenger", "start", "-p", port)
479                 if err != nil {
480                         return err
481                 }
482                 return nil
483         }
484         return fmt.Errorf("bug: component %q has nothing to run", cmpt.name)
485 }
486
487 func (boot *Booter) autofillConfig(cfg *arvados.Config, log logrus.FieldLogger) error {
488         cluster, err := cfg.GetCluster("")
489         if err != nil {
490                 return err
491         }
492         port := 9000
493         for _, svc := range []*arvados.Service{
494                 &cluster.Services.Controller,
495                 &cluster.Services.DispatchCloud,
496                 &cluster.Services.GitHTTP,
497                 &cluster.Services.Health,
498                 &cluster.Services.Keepproxy,
499                 &cluster.Services.Keepstore,
500                 &cluster.Services.RailsAPI,
501                 &cluster.Services.WebDAV,
502                 &cluster.Services.WebDAVDownload,
503                 &cluster.Services.Websocket,
504         } {
505                 if svc == &cluster.Services.DispatchCloud && boot.ClusterType == "test" {
506                         continue
507                 }
508                 if len(svc.InternalURLs) == 0 {
509                         port++
510                         svc.InternalURLs = map[arvados.URL]arvados.ServiceInstance{
511                                 arvados.URL{Scheme: "http", Host: fmt.Sprintf("localhost:%d", port)}: arvados.ServiceInstance{},
512                         }
513                 }
514                 if svc.ExternalURL.Host == "" && (svc == &cluster.Services.Controller ||
515                         svc == &cluster.Services.GitHTTP ||
516                         svc == &cluster.Services.Keepproxy ||
517                         svc == &cluster.Services.WebDAV ||
518                         svc == &cluster.Services.WebDAVDownload ||
519                         svc == &cluster.Services.Websocket) {
520                         port++
521                         svc.ExternalURL = arvados.URL{Scheme: "https", Host: fmt.Sprintf("localhost:%d", port)}
522                 }
523         }
524         if cluster.SystemRootToken == "" {
525                 cluster.SystemRootToken = randomHexString(64)
526         }
527         if cluster.ManagementToken == "" {
528                 cluster.ManagementToken = randomHexString(64)
529         }
530         if cluster.API.RailsSessionSecretToken == "" {
531                 cluster.API.RailsSessionSecretToken = randomHexString(64)
532         }
533         if cluster.Collections.BlobSigningKey == "" {
534                 cluster.Collections.BlobSigningKey = randomHexString(64)
535         }
536         if boot.ClusterType != "production" && cluster.Containers.DispatchPrivateKey == "" {
537                 buf, err := ioutil.ReadFile(filepath.Join(boot.SourcePath, "lib", "dispatchcloud", "test", "sshkey_dispatch"))
538                 if err != nil {
539                         return err
540                 }
541                 cluster.Containers.DispatchPrivateKey = string(buf)
542         }
543         if boot.ClusterType != "production" {
544                 cluster.TLS.Insecure = true
545         }
546         if boot.ClusterType == "test" {
547                 // Add a second keepstore process.
548                 port++
549                 cluster.Services.Keepstore.InternalURLs[arvados.URL{Scheme: "http", Host: fmt.Sprintf("localhost:%d", port)}] = arvados.ServiceInstance{}
550
551                 // Create a directory-backed volume for each keepstore
552                 // process.
553                 cluster.Volumes = map[string]arvados.Volume{}
554                 for url := range cluster.Services.Keepstore.InternalURLs {
555                         volnum := len(cluster.Volumes)
556                         datadir := fmt.Sprintf("%s/keep%d.data", boot.tempdir, volnum)
557                         if _, err = os.Stat(datadir + "/."); err == nil {
558                         } else if !os.IsNotExist(err) {
559                                 return err
560                         } else if err = os.Mkdir(datadir, 0777); err != nil {
561                                 return err
562                         }
563                         cluster.Volumes[fmt.Sprintf("zzzzz-nyw5e-%015d", volnum)] = arvados.Volume{
564                                 Driver:           "Directory",
565                                 DriverParameters: json.RawMessage(fmt.Sprintf(`{"Root":%q}`, datadir)),
566                                 AccessViaHosts: map[arvados.URL]arvados.VolumeAccess{
567                                         url: {},
568                                 },
569                         }
570                 }
571         }
572         cfg.Clusters[cluster.ClusterID] = *cluster
573         return nil
574 }
575
576 func randomHexString(chars int) string {
577         b := make([]byte, chars/2)
578         _, err := rand.Read(b)
579         if err != nil {
580                 panic(err)
581         }
582         return fmt.Sprintf("%x", b)
583 }
584
585 func internalPort(svc arvados.Service) (string, error) {
586         for u := range svc.InternalURLs {
587                 if _, p, err := net.SplitHostPort(u.Host); err != nil {
588                         return "", err
589                 } else if p != "" {
590                         return p, nil
591                 } else if u.Scheme == "https" {
592                         return "443", nil
593                 } else {
594                         return "80", nil
595                 }
596         }
597         return "", fmt.Errorf("service has no InternalURLs")
598 }
599
600 func externalPort(svc arvados.Service) (string, error) {
601         if _, p, err := net.SplitHostPort(svc.ExternalURL.Host); err != nil {
602                 return "", err
603         } else if p != "" {
604                 return p, nil
605         } else if svc.ExternalURL.Scheme == "https" {
606                 return "443", nil
607         } else {
608                 return "80", nil
609         }
610 }