1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
27 "git.arvados.org/arvados.git/lib/cmd"
28 "git.arvados.org/arvados.git/lib/config"
29 "git.arvados.org/arvados.git/sdk/go/arvados"
30 "git.arvados.org/arvados.git/sdk/go/ctxlog"
31 "git.arvados.org/arvados.git/sdk/go/health"
32 "github.com/sirupsen/logrus"
35 var Command cmd.Handler = bootCommand{}
37 type bootTask interface {
38 // Execute the task. Run should return nil when the task is
39 // done enough to satisfy a dependency relationship (e.g., the
40 // service is running and ready). If the task starts a
41 // goroutine that fails after Run returns (e.g., the service
42 // shuts down), it should call cancel.
43 Run(ctx context.Context, fail func(error), boot *Booter) error
47 type bootCommand struct{}
49 func (bootCommand) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
52 logger: ctxlog.New(stderr, "json", "info"),
55 ctx := ctxlog.Context(context.Background(), boot.logger)
56 ctx, cancel := context.WithCancel(ctx)
62 boot.logger.WithError(err).Info("exiting")
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 flags.StringVar(&boot.ListenHost, "listen-host", "localhost", "host name or interface address for service listeners")
75 flags.StringVar(&boot.ControllerAddr, "controller-address", ":0", "desired controller address, `host:port` or `:port`")
76 flags.BoolVar(&boot.OwnTemporaryDatabase, "own-temporary-database", false, "bring up a postgres server and create a temporary database")
77 err = flags.Parse(args)
78 if err == flag.ErrHelp {
81 } else if err != nil {
83 } else if *versionFlag {
84 return cmd.Version.RunCommand(prog, args, stdin, stdout, stderr)
85 } else if boot.ClusterType != "development" && boot.ClusterType != "test" && boot.ClusterType != "production" {
86 err = fmt.Errorf("cluster type must be 'development', 'test', or 'production'")
90 loader.SkipAPICalls = true
91 cfg, err := loader.Load()
98 if url, ok := boot.WaitReady(); ok {
99 fmt.Fprintln(stdout, url)
100 <-ctx.Done() // wait for signal
108 SourcePath string // e.g., /home/username/src/arvados
109 LibPath string // e.g., /var/lib/arvados
110 ClusterType string // e.g., production
111 ListenHost string // e.g., localhost
112 ControllerAddr string // e.g., 127.0.0.1:8000
113 OwnTemporaryDatabase bool
116 logger logrus.FieldLogger
117 cluster *arvados.Cluster
120 cancel context.CancelFunc
122 healthChecker *health.Aggregator
123 tasksReady map[string]chan bool
127 environ []string // for child processes
129 setupRubyOnce sync.Once
134 func (boot *Booter) Start(ctx context.Context, cfg *arvados.Config) {
135 boot.ctx, boot.cancel = context.WithCancel(ctx)
136 boot.done = make(chan struct{})
139 sigch := make(chan os.Signal)
140 signal.Notify(sigch, syscall.SIGINT, syscall.SIGTERM)
141 defer signal.Stop(sigch)
143 for sig := range sigch {
144 boot.logger.WithField("signal", sig).Info("caught signal")
151 fmt.Fprintln(boot.Stderr, err)
157 func (boot *Booter) run(cfg *arvados.Config) error {
158 cwd, err := os.Getwd()
162 if !strings.HasPrefix(boot.SourcePath, "/") {
163 boot.SourcePath = filepath.Join(cwd, boot.SourcePath)
165 boot.SourcePath, err = filepath.EvalSymlinks(boot.SourcePath)
170 boot.tempdir, err = ioutil.TempDir("", "arvados-server-boot-")
174 defer os.RemoveAll(boot.tempdir)
176 // Fill in any missing config keys, and write the resulting
177 // config in the temp dir for child services to use.
178 err = boot.autofillConfig(cfg, boot.logger)
182 conffile, err := os.OpenFile(filepath.Join(boot.tempdir, "config.yml"), os.O_CREATE|os.O_WRONLY, 0777)
186 defer conffile.Close()
187 err = json.NewEncoder(conffile).Encode(cfg)
191 err = conffile.Close()
195 boot.configfile = conffile.Name()
197 boot.environ = os.Environ()
199 boot.setEnv("ARVADOS_CONFIG", boot.configfile)
200 boot.setEnv("RAILS_ENV", boot.ClusterType)
201 boot.setEnv("TMPDIR", boot.tempdir)
202 boot.prependEnv("PATH", filepath.Join(boot.LibPath, "bin")+":")
204 boot.cluster, err = cfg.GetCluster("")
208 // Now that we have the config, replace the bootstrap logger
209 // with a new one according to the logging config.
210 loglevel := boot.cluster.SystemLogs.LogLevel
211 if s := os.Getenv("ARVADOS_DEBUG"); s != "" && s != "0" {
214 boot.logger = ctxlog.New(boot.Stderr, boot.cluster.SystemLogs.Format, loglevel).WithFields(logrus.Fields{
218 for _, dir := range []string{boot.LibPath, filepath.Join(boot.LibPath, "bin")} {
219 if _, err = os.Stat(filepath.Join(dir, ".")); os.IsNotExist(err) {
220 err = os.Mkdir(dir, 0755)
224 } else if err != nil {
228 err = boot.installGoProgram(boot.ctx, "cmd/arvados-server")
232 err = boot.setupRubyEnv()
238 createCertificates{},
241 runServiceCommand{name: "controller", svc: boot.cluster.Services.Controller, depends: []bootTask{runPostgreSQL{}}},
242 runGoProgram{src: "services/arv-git-httpd"},
243 runGoProgram{src: "services/health"},
244 runGoProgram{src: "services/keepproxy", depends: []bootTask{runPassenger{src: "services/api"}}},
245 runGoProgram{src: "services/keepstore", svc: boot.cluster.Services.Keepstore},
246 runGoProgram{src: "services/keep-web"},
247 runGoProgram{src: "services/ws", depends: []bootTask{runPostgreSQL{}}},
248 installPassenger{src: "services/api"},
249 runPassenger{src: "services/api", svc: boot.cluster.Services.RailsAPI, depends: []bootTask{createCertificates{}, runPostgreSQL{}, installPassenger{src: "services/api"}}},
250 installPassenger{src: "apps/workbench", depends: []bootTask{installPassenger{src: "services/api"}}}, // dependency ensures workbench doesn't delay api startup
251 runPassenger{src: "apps/workbench", svc: boot.cluster.Services.Workbench1, depends: []bootTask{installPassenger{src: "apps/workbench"}}},
254 if boot.ClusterType != "test" {
255 tasks = append(tasks,
256 runServiceCommand{name: "dispatch-cloud", svc: boot.cluster.Services.Controller},
257 runGoProgram{src: "services/keep-balance"},
260 boot.tasksReady = map[string]chan bool{}
261 for _, task := range tasks {
262 boot.tasksReady[task.String()] = make(chan bool)
264 for _, task := range tasks {
266 fail := func(err error) {
267 if boot.ctx.Err() != nil {
271 boot.logger.WithField("task", task.String()).WithError(err).Error("task failed")
274 boot.logger.WithField("task", task.String()).Info("starting")
275 err := task.Run(boot.ctx, fail, boot)
280 close(boot.tasksReady[task.String()])
283 err = boot.wait(boot.ctx, tasks...)
287 boot.logger.Info("all startup tasks are complete; starting health checks")
288 boot.healthChecker = &health.Aggregator{Cluster: boot.cluster}
290 boot.logger.Info("shutting down")
291 return boot.ctx.Err()
294 func (boot *Booter) wait(ctx context.Context, tasks ...bootTask) error {
295 for _, task := range tasks {
296 ch, ok := boot.tasksReady[task.String()]
298 return fmt.Errorf("no such task: %s", task)
300 boot.logger.WithField("task", task.String()).Info("waiting")
303 boot.logger.WithField("task", task.String()).Info("ready")
305 boot.logger.WithField("task", task.String()).Info("task was never ready")
312 func (boot *Booter) Stop() {
317 func (boot *Booter) WaitReady() (*arvados.URL, bool) {
318 for waiting := true; waiting; {
319 time.Sleep(time.Second)
320 if boot.ctx.Err() != nil {
323 if boot.healthChecker == nil {
327 resp := boot.healthChecker.ClusterHealth()
328 // The overall health check (resp.Health=="OK") might
329 // never pass due to missing components (like
330 // arvados-dispatch-cloud in a test cluster), so
331 // instead we wait for all configured components to
334 for target, check := range resp.Checks {
335 if check.Health != "OK" {
337 boot.logger.WithField("target", target).Debug("waiting")
341 u := boot.cluster.Services.Controller.ExternalURL
345 func (boot *Booter) prependEnv(key, prepend string) {
346 for i, s := range boot.environ {
347 if strings.HasPrefix(s, key+"=") {
348 boot.environ[i] = key + "=" + prepend + s[len(key)+1:]
352 boot.environ = append(boot.environ, key+"="+prepend)
355 var cleanEnvPrefixes = []string{
361 func (boot *Booter) cleanEnv() {
363 for _, s := range boot.environ {
365 for _, p := range cleanEnvPrefixes {
366 if strings.HasPrefix(s, p) {
372 cleaned = append(cleaned, s)
375 boot.environ = cleaned
378 func (boot *Booter) setEnv(key, val string) {
379 for i, s := range boot.environ {
380 if strings.HasPrefix(s, key+"=") {
381 boot.environ[i] = key + "=" + val
385 boot.environ = append(boot.environ, key+"="+val)
388 func (boot *Booter) installGoProgram(ctx context.Context, srcpath string) error {
390 defer boot.goMutex.Unlock()
391 return boot.RunProgram(ctx, filepath.Join(boot.SourcePath, srcpath), nil, []string{"GOPATH=" + boot.LibPath}, "go", "install")
394 func (boot *Booter) setupRubyEnv() error {
395 cmd := exec.Command("gem", "env", "gempath")
396 cmd.Env = boot.environ
397 buf, err := cmd.Output() // /var/lib/arvados/.gem/ruby/2.5.0/bin:...
398 if err != nil || len(buf) == 0 {
399 return fmt.Errorf("gem env gempath: %v", err)
401 gempath := string(bytes.Split(buf, []byte{':'})[0])
402 boot.prependEnv("PATH", gempath+"/bin:")
403 boot.setEnv("GEM_HOME", gempath)
404 boot.setEnv("GEM_PATH", gempath)
405 // Passenger install doesn't work unless $HOME is ~user
406 u, err := user.Current()
410 boot.setEnv("HOME", u.HomeDir)
414 func (boot *Booter) lookPath(prog string) string {
415 for _, val := range boot.environ {
416 if strings.HasPrefix(val, "PATH=") {
417 for _, dir := range filepath.SplitList(val[5:]) {
418 path := filepath.Join(dir, prog)
419 if fi, err := os.Stat(path); err == nil && fi.Mode()&0111 != 0 {
428 // Run prog with args, using dir as working directory. If ctx is
429 // cancelled while the child is running, RunProgram terminates the
430 // child, waits for it to exit, then returns.
432 // Child's environment will have our env vars, plus any given in env.
434 // Child's stdout will be written to output if non-nil, otherwise the
435 // boot command's stderr.
436 func (boot *Booter) RunProgram(ctx context.Context, dir string, output io.Writer, env []string, prog string, args ...string) error {
437 cmdline := fmt.Sprintf("%s", append([]string{prog}, args...))
438 fmt.Fprintf(boot.Stderr, "%s executing in %s\n", cmdline, dir)
441 if prog == "bundle" && len(args) > 2 && args[0] == "exec" {
444 if !strings.HasPrefix(dir, "/") {
445 logprefix = dir + ": " + logprefix
447 stderr := &logPrefixer{Writer: boot.Stderr, Prefix: []byte("[" + logprefix + "] ")}
449 cmd := exec.Command(boot.lookPath(prog), args...)
456 if strings.HasPrefix(dir, "/") {
459 cmd.Dir = filepath.Join(boot.SourcePath, dir)
461 cmd.Env = append(env, boot.environ...)
464 defer func() { exited = true }()
467 log := ctxlog.FromContext(ctx).WithFields(logrus.Fields{"dir": dir, "cmdline": cmdline})
469 if cmd.Process == nil {
470 log.Debug("waiting for child process to start")
471 time.Sleep(time.Second / 2)
473 log.WithField("PID", cmd.Process.Pid).Debug("sending SIGTERM")
474 cmd.Process.Signal(syscall.SIGTERM)
475 time.Sleep(5 * time.Second)
477 log.WithField("PID", cmd.Process.Pid).Warn("still waiting for child process to exit 5s after SIGTERM")
484 if err != nil && ctx.Err() == nil {
485 // Only report errors that happen before the context ends.
486 return fmt.Errorf("%s: error: %v", cmdline, err)
491 func (boot *Booter) autofillConfig(cfg *arvados.Config, log logrus.FieldLogger) error {
492 cluster, err := cfg.GetCluster("")
496 usedPort := map[string]bool{}
497 nextPort := func() string {
499 port, err := availablePort(":0")
506 usedPort[port] = true
510 if cluster.Services.Controller.ExternalURL.Host == "" {
511 h, p, err := net.SplitHostPort(boot.ControllerAddr)
519 p, err = availablePort(":0")
525 cluster.Services.Controller.ExternalURL = arvados.URL{Scheme: "https", Host: net.JoinHostPort(h, p)}
527 for _, svc := range []*arvados.Service{
528 &cluster.Services.Controller,
529 &cluster.Services.DispatchCloud,
530 &cluster.Services.GitHTTP,
531 &cluster.Services.Health,
532 &cluster.Services.Keepproxy,
533 &cluster.Services.Keepstore,
534 &cluster.Services.RailsAPI,
535 &cluster.Services.WebDAV,
536 &cluster.Services.WebDAVDownload,
537 &cluster.Services.Websocket,
538 &cluster.Services.Workbench1,
540 if svc == &cluster.Services.DispatchCloud && boot.ClusterType == "test" {
543 if svc.ExternalURL.Host == "" && (svc == &cluster.Services.Controller ||
544 svc == &cluster.Services.GitHTTP ||
545 svc == &cluster.Services.Keepproxy ||
546 svc == &cluster.Services.WebDAV ||
547 svc == &cluster.Services.WebDAVDownload ||
548 svc == &cluster.Services.Websocket ||
549 svc == &cluster.Services.Workbench1) {
550 svc.ExternalURL = arvados.URL{Scheme: "https", Host: fmt.Sprintf("%s:%s", boot.ListenHost, nextPort())}
552 if len(svc.InternalURLs) == 0 {
553 svc.InternalURLs = map[arvados.URL]arvados.ServiceInstance{
554 arvados.URL{Scheme: "http", Host: fmt.Sprintf("%s:%s", boot.ListenHost, nextPort())}: arvados.ServiceInstance{},
558 if cluster.SystemRootToken == "" {
559 cluster.SystemRootToken = randomHexString(64)
561 if cluster.ManagementToken == "" {
562 cluster.ManagementToken = randomHexString(64)
564 if cluster.API.RailsSessionSecretToken == "" {
565 cluster.API.RailsSessionSecretToken = randomHexString(64)
567 if cluster.Collections.BlobSigningKey == "" {
568 cluster.Collections.BlobSigningKey = randomHexString(64)
570 if boot.ClusterType != "production" && cluster.Containers.DispatchPrivateKey == "" {
571 buf, err := ioutil.ReadFile(filepath.Join(boot.SourcePath, "lib", "dispatchcloud", "test", "sshkey_dispatch"))
575 cluster.Containers.DispatchPrivateKey = string(buf)
577 if boot.ClusterType != "production" {
578 cluster.TLS.Insecure = true
580 if boot.ClusterType == "test" {
581 // Add a second keepstore process.
582 cluster.Services.Keepstore.InternalURLs[arvados.URL{Scheme: "http", Host: fmt.Sprintf("%s:%s", boot.ListenHost, nextPort())}] = arvados.ServiceInstance{}
584 // Create a directory-backed volume for each keepstore
586 cluster.Volumes = map[string]arvados.Volume{}
587 for url := range cluster.Services.Keepstore.InternalURLs {
588 volnum := len(cluster.Volumes)
589 datadir := fmt.Sprintf("%s/keep%d.data", boot.tempdir, volnum)
590 if _, err = os.Stat(datadir + "/."); err == nil {
591 } else if !os.IsNotExist(err) {
593 } else if err = os.Mkdir(datadir, 0777); err != nil {
596 cluster.Volumes[fmt.Sprintf(cluster.ClusterID+"-nyw5e-%015d", volnum)] = arvados.Volume{
598 DriverParameters: json.RawMessage(fmt.Sprintf(`{"Root":%q}`, datadir)),
599 AccessViaHosts: map[arvados.URL]arvados.VolumeAccess{
605 if boot.OwnTemporaryDatabase {
606 cluster.PostgreSQL.Connection = arvados.PostgreSQLConnection{
607 "client_encoding": "utf8",
610 "dbname": "arvados_test",
612 "password": "insecure_arvados_test",
616 cfg.Clusters[cluster.ClusterID] = *cluster
620 func randomHexString(chars int) string {
621 b := make([]byte, chars/2)
622 _, err := rand.Read(b)
626 return fmt.Sprintf("%x", b)
629 func internalPort(svc arvados.Service) (string, error) {
630 for u := range svc.InternalURLs {
631 if _, p, err := net.SplitHostPort(u.Host); err != nil {
635 } else if u.Scheme == "https" {
641 return "", fmt.Errorf("service has no InternalURLs")
644 func externalPort(svc arvados.Service) (string, error) {
645 if _, p, err := net.SplitHostPort(svc.ExternalURL.Host); err != nil {
649 } else if svc.ExternalURL.Scheme == "https" {
656 func availablePort(addr string) (string, error) {
657 ln, err := net.Listen("tcp", addr)
662 _, port, err := net.SplitHostPort(ln.Addr().String())
669 // Try to connect to addr until it works, then close ch. Give up if
671 func waitForConnect(ctx context.Context, addr string) error {
672 dialer := net.Dialer{Timeout: time.Second}
673 for ctx.Err() == nil {
674 conn, err := dialer.DialContext(ctx, "tcp", addr)
676 time.Sleep(time.Second / 10)