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/lib/service"
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"
36 var Command cmd.Handler = bootCommand{}
38 type bootTask interface {
39 // Execute the task. Run should return nil when the task is
40 // done enough to satisfy a dependency relationship (e.g., the
41 // service is running and ready). If the task starts a
42 // goroutine that fails after Run returns (e.g., the service
43 // shuts down), it should call cancel.
44 Run(ctx context.Context, fail func(error), boot *Booter) error
48 type bootCommand struct{}
50 func (bootCommand) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
53 logger: ctxlog.New(stderr, "json", "info"),
56 ctx := ctxlog.Context(context.Background(), boot.logger)
57 ctx, cancel := context.WithCancel(ctx)
63 boot.logger.WithError(err).Info("exiting")
67 flags := flag.NewFlagSet(prog, flag.ContinueOnError)
68 flags.SetOutput(stderr)
69 loader := config.NewLoader(stdin, boot.logger)
70 loader.SetupFlags(flags)
71 versionFlag := flags.Bool("version", false, "Write version information to stdout and exit 0")
72 flags.StringVar(&boot.SourcePath, "source", ".", "arvados source tree `directory`")
73 flags.StringVar(&boot.LibPath, "lib", "/var/lib/arvados", "`directory` to install dependencies and library files")
74 flags.StringVar(&boot.ClusterType, "type", "production", "cluster `type`: development, test, or production")
75 flags.StringVar(&boot.ListenHost, "listen-host", "localhost", "host name or interface address for service listeners")
76 flags.StringVar(&boot.ControllerAddr, "controller-address", ":0", "desired controller address, `host:port` or `:port`")
77 flags.BoolVar(&boot.OwnTemporaryDatabase, "own-temporary-database", false, "bring up a postgres server and create a temporary database")
78 err = flags.Parse(args)
79 if err == flag.ErrHelp {
82 } else if err != nil {
84 } else if *versionFlag {
85 return cmd.Version.RunCommand(prog, args, stdin, stdout, stderr)
86 } else if boot.ClusterType != "development" && boot.ClusterType != "test" && boot.ClusterType != "production" {
87 err = fmt.Errorf("cluster type must be 'development', 'test', or 'production'")
91 loader.SkipAPICalls = true
92 cfg, err := loader.Load()
99 if url, ok := boot.WaitReady(); ok {
100 fmt.Fprintln(stdout, url)
101 // Wait for signal/crash + orderly shutdown
110 SourcePath string // e.g., /home/username/src/arvados
111 LibPath string // e.g., /var/lib/arvados
112 ClusterType string // e.g., production
113 ListenHost string // e.g., localhost
114 ControllerAddr string // e.g., 127.0.0.1:8000
115 OwnTemporaryDatabase bool
118 logger logrus.FieldLogger
119 cluster *arvados.Cluster
122 cancel context.CancelFunc
124 healthChecker *health.Aggregator
125 tasksReady map[string]chan bool
126 waitShutdown sync.WaitGroup
130 environ []string // for child processes
132 setupRubyOnce sync.Once
137 func (boot *Booter) Start(ctx context.Context, cfg *arvados.Config) {
138 boot.ctx, boot.cancel = context.WithCancel(ctx)
139 boot.done = make(chan struct{})
142 sigch := make(chan os.Signal)
143 signal.Notify(sigch, syscall.SIGINT, syscall.SIGTERM)
144 defer signal.Stop(sigch)
146 for sig := range sigch {
147 boot.logger.WithField("signal", sig).Info("caught signal")
154 fmt.Fprintln(boot.Stderr, err)
160 func (boot *Booter) run(cfg *arvados.Config) error {
161 cwd, err := os.Getwd()
165 if !strings.HasPrefix(boot.SourcePath, "/") {
166 boot.SourcePath = filepath.Join(cwd, boot.SourcePath)
168 boot.SourcePath, err = filepath.EvalSymlinks(boot.SourcePath)
173 boot.tempdir, err = ioutil.TempDir("", "arvados-server-boot-")
177 defer os.RemoveAll(boot.tempdir)
178 if err := os.Mkdir(filepath.Join(boot.tempdir, "bin"), 0777); err != nil {
182 // Fill in any missing config keys, and write the resulting
183 // config in the temp dir for child services to use.
184 err = boot.autofillConfig(cfg, boot.logger)
188 conffile, err := os.OpenFile(filepath.Join(boot.tempdir, "config.yml"), os.O_CREATE|os.O_WRONLY, 0777)
192 defer conffile.Close()
193 err = json.NewEncoder(conffile).Encode(cfg)
197 err = conffile.Close()
201 boot.configfile = conffile.Name()
203 boot.environ = os.Environ()
205 boot.setEnv("ARVADOS_CONFIG", boot.configfile)
206 boot.setEnv("RAILS_ENV", boot.ClusterType)
207 boot.setEnv("TMPDIR", boot.tempdir)
208 boot.prependEnv("PATH", filepath.Join(boot.tempdir, "bin")+":")
209 boot.prependEnv("PATH", filepath.Join(boot.LibPath, "bin")+":")
211 boot.cluster, err = cfg.GetCluster("")
215 // Now that we have the config, replace the bootstrap logger
216 // with a new one according to the logging config.
217 loglevel := boot.cluster.SystemLogs.LogLevel
218 if s := os.Getenv("ARVADOS_DEBUG"); s != "" && s != "0" {
221 boot.logger = ctxlog.New(boot.Stderr, boot.cluster.SystemLogs.Format, loglevel).WithFields(logrus.Fields{
225 for _, dir := range []string{boot.LibPath, filepath.Join(boot.LibPath, "bin")} {
226 if _, err = os.Stat(filepath.Join(dir, ".")); os.IsNotExist(err) {
227 err = os.Mkdir(dir, 0755)
231 } else if err != nil {
235 err = boot.installGoProgram(boot.ctx, "cmd/arvados-server")
239 err = boot.setupRubyEnv()
245 createCertificates{},
248 runServiceCommand{name: "controller", svc: boot.cluster.Services.Controller, depends: []bootTask{runPostgreSQL{}}},
249 runGoProgram{src: "services/arv-git-httpd"},
250 runGoProgram{src: "services/health"},
251 runGoProgram{src: "services/keepproxy", depends: []bootTask{runPassenger{src: "services/api"}}},
252 runGoProgram{src: "services/keepstore", svc: boot.cluster.Services.Keepstore},
253 runGoProgram{src: "services/keep-web"},
254 runGoProgram{src: "services/ws", depends: []bootTask{runPostgreSQL{}}},
255 installPassenger{src: "services/api"},
256 runPassenger{src: "services/api", svc: boot.cluster.Services.RailsAPI, depends: []bootTask{createCertificates{}, runPostgreSQL{}, installPassenger{src: "services/api"}}},
257 installPassenger{src: "apps/workbench", depends: []bootTask{installPassenger{src: "services/api"}}}, // dependency ensures workbench doesn't delay api startup
258 runPassenger{src: "apps/workbench", svc: boot.cluster.Services.Workbench1, depends: []bootTask{installPassenger{src: "apps/workbench"}}},
261 if boot.ClusterType != "test" {
262 tasks = append(tasks,
263 runServiceCommand{name: "dispatch-cloud", svc: boot.cluster.Services.Controller},
264 runGoProgram{src: "services/keep-balance"},
267 boot.tasksReady = map[string]chan bool{}
268 for _, task := range tasks {
269 boot.tasksReady[task.String()] = make(chan bool)
271 for _, task := range tasks {
273 fail := func(err error) {
274 if boot.ctx.Err() != nil {
278 boot.logger.WithField("task", task.String()).WithError(err).Error("task failed")
281 boot.logger.WithField("task", task.String()).Info("starting")
282 err := task.Run(boot.ctx, fail, boot)
287 close(boot.tasksReady[task.String()])
290 err = boot.wait(boot.ctx, tasks...)
294 boot.logger.Info("all startup tasks are complete; starting health checks")
295 boot.healthChecker = &health.Aggregator{Cluster: boot.cluster}
297 boot.logger.Info("shutting down")
298 boot.waitShutdown.Wait()
299 return boot.ctx.Err()
302 func (boot *Booter) wait(ctx context.Context, tasks ...bootTask) error {
303 for _, task := range tasks {
304 ch, ok := boot.tasksReady[task.String()]
306 return fmt.Errorf("no such task: %s", task)
308 boot.logger.WithField("task", task.String()).Info("waiting")
311 boot.logger.WithField("task", task.String()).Info("ready")
313 boot.logger.WithField("task", task.String()).Info("task was never ready")
320 func (boot *Booter) Stop() {
325 func (boot *Booter) WaitReady() (*arvados.URL, bool) {
326 ticker := time.NewTicker(time.Second)
328 for waiting := true; waiting; {
331 case <-boot.ctx.Done():
334 if boot.healthChecker == nil {
338 resp := boot.healthChecker.ClusterHealth()
339 // The overall health check (resp.Health=="OK") might
340 // never pass due to missing components (like
341 // arvados-dispatch-cloud in a test cluster), so
342 // instead we wait for all configured components to
345 for target, check := range resp.Checks {
346 if check.Health != "OK" {
348 boot.logger.WithField("target", target).Debug("waiting")
352 u := boot.cluster.Services.Controller.ExternalURL
356 func (boot *Booter) prependEnv(key, prepend string) {
357 for i, s := range boot.environ {
358 if strings.HasPrefix(s, key+"=") {
359 boot.environ[i] = key + "=" + prepend + s[len(key)+1:]
363 boot.environ = append(boot.environ, key+"="+prepend)
366 var cleanEnvPrefixes = []string{
372 func (boot *Booter) cleanEnv() {
374 for _, s := range boot.environ {
376 for _, p := range cleanEnvPrefixes {
377 if strings.HasPrefix(s, p) {
383 cleaned = append(cleaned, s)
386 boot.environ = cleaned
389 func (boot *Booter) setEnv(key, val string) {
390 for i, s := range boot.environ {
391 if strings.HasPrefix(s, key+"=") {
392 boot.environ[i] = key + "=" + val
396 boot.environ = append(boot.environ, key+"="+val)
399 // Remove all but the first occurrence of each env var.
400 func dedupEnv(in []string) []string {
401 saw := map[string]bool{}
403 for _, kv := range in {
404 if split := strings.Index(kv, "="); split < 1 {
405 panic("invalid environment var: " + kv)
406 } else if saw[kv[:split]] {
409 saw[kv[:split]] = true
410 out = append(out, kv)
416 func (boot *Booter) installGoProgram(ctx context.Context, srcpath string) error {
418 defer boot.goMutex.Unlock()
419 return boot.RunProgram(ctx, filepath.Join(boot.SourcePath, srcpath), nil, []string{"GOBIN=" + boot.tempdir + "/bin"}, "go", "install")
422 func (boot *Booter) setupRubyEnv() error {
423 cmd := exec.Command("gem", "env", "gempath")
424 cmd.Env = boot.environ
425 buf, err := cmd.Output() // /var/lib/arvados/.gem/ruby/2.5.0/bin:...
426 if err != nil || len(buf) == 0 {
427 return fmt.Errorf("gem env gempath: %v", err)
429 gempath := string(bytes.Split(buf, []byte{':'})[0])
430 boot.prependEnv("PATH", gempath+"/bin:")
431 boot.setEnv("GEM_HOME", gempath)
432 boot.setEnv("GEM_PATH", gempath)
433 // Passenger install doesn't work unless $HOME is ~user
434 u, err := user.Current()
438 boot.setEnv("HOME", u.HomeDir)
442 func (boot *Booter) lookPath(prog string) string {
443 for _, val := range boot.environ {
444 if strings.HasPrefix(val, "PATH=") {
445 for _, dir := range filepath.SplitList(val[5:]) {
446 path := filepath.Join(dir, prog)
447 if fi, err := os.Stat(path); err == nil && fi.Mode()&0111 != 0 {
456 // Run prog with args, using dir as working directory. If ctx is
457 // cancelled while the child is running, RunProgram terminates the
458 // child, waits for it to exit, then returns.
460 // Child's environment will have our env vars, plus any given in env.
462 // Child's stdout will be written to output if non-nil, otherwise the
463 // boot command's stderr.
464 func (boot *Booter) RunProgram(ctx context.Context, dir string, output io.Writer, env []string, prog string, args ...string) error {
465 cmdline := fmt.Sprintf("%s", append([]string{prog}, args...))
466 boot.logger.WithField("command", cmdline).WithField("dir", dir).Info("executing")
469 if prog == "bundle" && len(args) > 2 && args[0] == "exec" {
471 } else if prog == "arvados-server" && len(args) > 1 {
474 if !strings.HasPrefix(dir, "/") {
475 logprefix = dir + ": " + logprefix
478 cmd := exec.Command(boot.lookPath(prog), args...)
479 stdout, err := cmd.StdoutPipe()
483 stderr, err := cmd.StderrPipe()
487 logwriter := &service.LogPrefixer{Writer: boot.Stderr, Prefix: []byte("[" + logprefix + "] ")}
488 go io.Copy(logwriter, stderr)
490 go io.Copy(logwriter, stdout)
492 go io.Copy(output, stdout)
495 if strings.HasPrefix(dir, "/") {
498 cmd.Dir = filepath.Join(boot.SourcePath, dir)
500 env = append([]string(nil), env...)
501 env = append(env, boot.environ...)
502 cmd.Env = dedupEnv(env)
505 defer func() { exited = true }()
508 log := ctxlog.FromContext(ctx).WithFields(logrus.Fields{"dir": dir, "cmdline": cmdline})
510 if cmd.Process == nil {
511 log.Debug("waiting for child process to start")
512 time.Sleep(time.Second / 2)
514 log.WithField("PID", cmd.Process.Pid).Debug("sending SIGTERM")
515 cmd.Process.Signal(syscall.SIGTERM)
516 time.Sleep(5 * time.Second)
520 log.WithField("PID", cmd.Process.Pid).Warn("still waiting for child process to exit 5s after SIGTERM")
531 if err != nil && ctx.Err() == nil {
532 // Only report errors that happen before the context ends.
533 return fmt.Errorf("%s: error: %v", cmdline, err)
538 func (boot *Booter) autofillConfig(cfg *arvados.Config, log logrus.FieldLogger) error {
539 cluster, err := cfg.GetCluster("")
543 usedPort := map[string]bool{}
544 nextPort := func() string {
546 port, err := availablePort(":0")
553 usedPort[port] = true
557 if cluster.Services.Controller.ExternalURL.Host == "" {
558 h, p, err := net.SplitHostPort(boot.ControllerAddr)
566 p, err = availablePort(":0")
572 cluster.Services.Controller.ExternalURL = arvados.URL{Scheme: "https", Host: net.JoinHostPort(h, p)}
574 for _, svc := range []*arvados.Service{
575 &cluster.Services.Controller,
576 &cluster.Services.DispatchCloud,
577 &cluster.Services.GitHTTP,
578 &cluster.Services.Health,
579 &cluster.Services.Keepproxy,
580 &cluster.Services.Keepstore,
581 &cluster.Services.RailsAPI,
582 &cluster.Services.WebDAV,
583 &cluster.Services.WebDAVDownload,
584 &cluster.Services.Websocket,
585 &cluster.Services.Workbench1,
587 if svc == &cluster.Services.DispatchCloud && boot.ClusterType == "test" {
590 if svc.ExternalURL.Host == "" && (svc == &cluster.Services.Controller ||
591 svc == &cluster.Services.GitHTTP ||
592 svc == &cluster.Services.Keepproxy ||
593 svc == &cluster.Services.WebDAV ||
594 svc == &cluster.Services.WebDAVDownload ||
595 svc == &cluster.Services.Websocket ||
596 svc == &cluster.Services.Workbench1) {
597 svc.ExternalURL = arvados.URL{Scheme: "https", Host: fmt.Sprintf("%s:%s", boot.ListenHost, nextPort())}
599 if len(svc.InternalURLs) == 0 {
600 svc.InternalURLs = map[arvados.URL]arvados.ServiceInstance{
601 arvados.URL{Scheme: "http", Host: fmt.Sprintf("%s:%s", boot.ListenHost, nextPort())}: arvados.ServiceInstance{},
605 if cluster.SystemRootToken == "" {
606 cluster.SystemRootToken = randomHexString(64)
608 if cluster.ManagementToken == "" {
609 cluster.ManagementToken = randomHexString(64)
611 if cluster.API.RailsSessionSecretToken == "" {
612 cluster.API.RailsSessionSecretToken = randomHexString(64)
614 if cluster.Collections.BlobSigningKey == "" {
615 cluster.Collections.BlobSigningKey = randomHexString(64)
617 if boot.ClusterType != "production" && cluster.Containers.DispatchPrivateKey == "" {
618 buf, err := ioutil.ReadFile(filepath.Join(boot.SourcePath, "lib", "dispatchcloud", "test", "sshkey_dispatch"))
622 cluster.Containers.DispatchPrivateKey = string(buf)
624 if boot.ClusterType != "production" {
625 cluster.TLS.Insecure = true
627 if boot.ClusterType == "test" {
628 // Add a second keepstore process.
629 cluster.Services.Keepstore.InternalURLs[arvados.URL{Scheme: "http", Host: fmt.Sprintf("%s:%s", boot.ListenHost, nextPort())}] = arvados.ServiceInstance{}
631 // Create a directory-backed volume for each keepstore
633 cluster.Volumes = map[string]arvados.Volume{}
634 for url := range cluster.Services.Keepstore.InternalURLs {
635 volnum := len(cluster.Volumes)
636 datadir := fmt.Sprintf("%s/keep%d.data", boot.tempdir, volnum)
637 if _, err = os.Stat(datadir + "/."); err == nil {
638 } else if !os.IsNotExist(err) {
640 } else if err = os.Mkdir(datadir, 0777); err != nil {
643 cluster.Volumes[fmt.Sprintf(cluster.ClusterID+"-nyw5e-%015d", volnum)] = arvados.Volume{
645 DriverParameters: json.RawMessage(fmt.Sprintf(`{"Root":%q}`, datadir)),
646 AccessViaHosts: map[arvados.URL]arvados.VolumeAccess{
652 if boot.OwnTemporaryDatabase {
653 cluster.PostgreSQL.Connection = arvados.PostgreSQLConnection{
654 "client_encoding": "utf8",
657 "dbname": "arvados_test",
659 "password": "insecure_arvados_test",
663 cfg.Clusters[cluster.ClusterID] = *cluster
667 func randomHexString(chars int) string {
668 b := make([]byte, chars/2)
669 _, err := rand.Read(b)
673 return fmt.Sprintf("%x", b)
676 func internalPort(svc arvados.Service) (string, error) {
677 for u := range svc.InternalURLs {
678 if _, p, err := net.SplitHostPort(u.Host); err != nil {
682 } else if u.Scheme == "https" {
688 return "", fmt.Errorf("service has no InternalURLs")
691 func externalPort(svc arvados.Service) (string, error) {
692 if _, p, err := net.SplitHostPort(svc.ExternalURL.Host); err != nil {
696 } else if svc.ExternalURL.Scheme == "https" {
703 func availablePort(addr string) (string, error) {
704 ln, err := net.Listen("tcp", addr)
709 _, port, err := net.SplitHostPort(ln.Addr().String())
716 // Try to connect to addr until it works, then close ch. Give up if
718 func waitForConnect(ctx context.Context, addr string) error {
719 dialer := net.Dialer{Timeout: time.Second}
720 for ctx.Err() == nil {
721 conn, err := dialer.DialContext(ctx, "tcp", addr)
723 time.Sleep(time.Second / 10)