1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
28 "git.arvados.org/arvados.git/lib/cmd"
29 "git.arvados.org/arvados.git/lib/config"
30 "git.arvados.org/arvados.git/lib/service"
31 "git.arvados.org/arvados.git/sdk/go/arvados"
32 "git.arvados.org/arvados.git/sdk/go/ctxlog"
33 "git.arvados.org/arvados.git/sdk/go/health"
34 "github.com/sirupsen/logrus"
37 var Command cmd.Handler = bootCommand{}
39 type bootTask interface {
40 // Execute the task. Run should return nil when the task is
41 // done enough to satisfy a dependency relationship (e.g., the
42 // service is running and ready). If the task starts a
43 // goroutine that fails after Run returns (e.g., the service
44 // shuts down), it should call cancel.
45 Run(ctx context.Context, fail func(error), boot *Booter) error
49 type bootCommand struct{}
51 func (bootCommand) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
54 logger: ctxlog.New(stderr, "json", "info"),
57 ctx := ctxlog.Context(context.Background(), boot.logger)
58 ctx, cancel := context.WithCancel(ctx)
64 boot.logger.WithError(err).Info("exiting")
68 flags := flag.NewFlagSet(prog, flag.ContinueOnError)
69 flags.SetOutput(stderr)
70 loader := config.NewLoader(stdin, boot.logger)
71 loader.SetupFlags(flags)
72 versionFlag := flags.Bool("version", false, "Write version information to stdout and exit 0")
73 flags.StringVar(&boot.SourcePath, "source", ".", "arvados source tree `directory`")
74 flags.StringVar(&boot.LibPath, "lib", "/var/lib/arvados", "`directory` to install dependencies and library files")
75 flags.StringVar(&boot.ClusterType, "type", "production", "cluster `type`: development, test, or production")
76 flags.StringVar(&boot.ListenHost, "listen-host", "localhost", "host name or interface address for service listeners")
77 flags.StringVar(&boot.ControllerAddr, "controller-address", ":0", "desired controller address, `host:port` or `:port`")
78 flags.BoolVar(&boot.OwnTemporaryDatabase, "own-temporary-database", false, "bring up a postgres server and create a temporary database")
79 err = flags.Parse(args)
80 if err == flag.ErrHelp {
83 } else if err != nil {
85 } else if *versionFlag {
86 return cmd.Version.RunCommand(prog, args, stdin, stdout, stderr)
87 } else if boot.ClusterType != "development" && boot.ClusterType != "test" && boot.ClusterType != "production" {
88 err = fmt.Errorf("cluster type must be 'development', 'test', or 'production'")
92 loader.SkipAPICalls = true
93 cfg, err := loader.Load()
100 if url, ok := boot.WaitReady(); ok {
101 fmt.Fprintln(stdout, url)
102 // Wait for signal/crash + orderly shutdown
111 SourcePath string // e.g., /home/username/src/arvados
112 SourceVersion string // e.g., acbd1324...
113 LibPath string // e.g., /var/lib/arvados
114 ClusterType string // e.g., production
115 ListenHost string // e.g., localhost
116 ControllerAddr string // e.g., 127.0.0.1:8000
117 OwnTemporaryDatabase bool
120 logger logrus.FieldLogger
121 cluster *arvados.Cluster
124 cancel context.CancelFunc
126 healthChecker *health.Aggregator
127 tasksReady map[string]chan bool
128 waitShutdown sync.WaitGroup
132 environ []string // for child processes
134 setupRubyOnce sync.Once
139 func (boot *Booter) Start(ctx context.Context, cfg *arvados.Config) {
140 boot.ctx, boot.cancel = context.WithCancel(ctx)
141 boot.done = make(chan struct{})
144 sigch := make(chan os.Signal)
145 signal.Notify(sigch, syscall.SIGINT, syscall.SIGTERM)
146 defer signal.Stop(sigch)
148 for sig := range sigch {
149 boot.logger.WithField("signal", sig).Info("caught signal")
156 fmt.Fprintln(boot.Stderr, err)
162 func (boot *Booter) run(cfg *arvados.Config) error {
163 cwd, err := os.Getwd()
167 if !strings.HasPrefix(boot.SourcePath, "/") {
168 boot.SourcePath = filepath.Join(cwd, boot.SourcePath)
170 boot.SourcePath, err = filepath.EvalSymlinks(boot.SourcePath)
175 boot.tempdir, err = ioutil.TempDir("", "arvados-server-boot-")
179 defer os.RemoveAll(boot.tempdir)
180 if err := os.Mkdir(filepath.Join(boot.tempdir, "bin"), 0777); err != nil {
184 // Fill in any missing config keys, and write the resulting
185 // config in the temp dir for child services to use.
186 err = boot.autofillConfig(cfg, boot.logger)
190 conffile, err := os.OpenFile(filepath.Join(boot.tempdir, "config.yml"), os.O_CREATE|os.O_WRONLY, 0777)
194 defer conffile.Close()
195 err = json.NewEncoder(conffile).Encode(cfg)
199 err = conffile.Close()
203 boot.configfile = conffile.Name()
205 boot.environ = os.Environ()
207 boot.setEnv("ARVADOS_CONFIG", boot.configfile)
208 boot.setEnv("RAILS_ENV", boot.ClusterType)
209 boot.setEnv("TMPDIR", boot.tempdir)
210 boot.prependEnv("PATH", filepath.Join(boot.tempdir, "bin")+":")
211 boot.prependEnv("PATH", filepath.Join(boot.LibPath, "bin")+":")
213 boot.cluster, err = cfg.GetCluster("")
217 // Now that we have the config, replace the bootstrap logger
218 // with a new one according to the logging config.
219 loglevel := boot.cluster.SystemLogs.LogLevel
220 if s := os.Getenv("ARVADOS_DEBUG"); s != "" && s != "0" {
223 boot.logger = ctxlog.New(boot.Stderr, boot.cluster.SystemLogs.Format, loglevel).WithFields(logrus.Fields{
227 if boot.SourceVersion == "" {
228 // Find current source tree version.
230 err = boot.RunProgram(boot.ctx, ".", &buf, nil, "git", "diff", "--shortstat")
234 dirty := buf.Len() > 0
236 err = boot.RunProgram(boot.ctx, ".", &buf, nil, "git", "log", "-n1", "--format=%H")
240 boot.SourceVersion = strings.TrimSpace(buf.String())
242 boot.SourceVersion += "+uncommitted"
245 return errors.New("specifying a version to run is not yet supported")
247 for _, dir := range []string{boot.LibPath, filepath.Join(boot.LibPath, "bin")} {
248 if _, err = os.Stat(filepath.Join(dir, ".")); os.IsNotExist(err) {
249 err = os.Mkdir(dir, 0755)
253 } else if err != nil {
257 _, err = boot.installGoProgram(boot.ctx, "cmd/arvados-server")
261 err = boot.setupRubyEnv()
267 createCertificates{},
270 runServiceCommand{name: "controller", svc: boot.cluster.Services.Controller, depends: []bootTask{runPostgreSQL{}}},
271 runGoProgram{src: "services/arv-git-httpd"},
272 runGoProgram{src: "services/health"},
273 runGoProgram{src: "services/keepproxy", depends: []bootTask{runPassenger{src: "services/api"}}},
274 runGoProgram{src: "services/keepstore", svc: boot.cluster.Services.Keepstore},
275 runGoProgram{src: "services/keep-web"},
276 runGoProgram{src: "services/ws", depends: []bootTask{runPostgreSQL{}}},
277 installPassenger{src: "services/api"},
278 runPassenger{src: "services/api", svc: boot.cluster.Services.RailsAPI, depends: []bootTask{createCertificates{}, runPostgreSQL{}, installPassenger{src: "services/api"}}},
279 installPassenger{src: "apps/workbench", depends: []bootTask{installPassenger{src: "services/api"}}}, // dependency ensures workbench doesn't delay api startup
280 runPassenger{src: "apps/workbench", svc: boot.cluster.Services.Workbench1, depends: []bootTask{installPassenger{src: "apps/workbench"}}},
283 if boot.ClusterType != "test" {
284 tasks = append(tasks,
285 runServiceCommand{name: "dispatch-cloud", svc: boot.cluster.Services.Controller},
286 runGoProgram{src: "services/keep-balance"},
289 boot.tasksReady = map[string]chan bool{}
290 for _, task := range tasks {
291 boot.tasksReady[task.String()] = make(chan bool)
293 for _, task := range tasks {
295 fail := func(err error) {
296 if boot.ctx.Err() != nil {
300 boot.logger.WithField("task", task.String()).WithError(err).Error("task failed")
303 boot.logger.WithField("task", task.String()).Info("starting")
304 err := task.Run(boot.ctx, fail, boot)
309 close(boot.tasksReady[task.String()])
312 err = boot.wait(boot.ctx, tasks...)
316 boot.logger.Info("all startup tasks are complete; starting health checks")
317 boot.healthChecker = &health.Aggregator{Cluster: boot.cluster}
319 boot.logger.Info("shutting down")
320 boot.waitShutdown.Wait()
321 return boot.ctx.Err()
324 func (boot *Booter) wait(ctx context.Context, tasks ...bootTask) error {
325 for _, task := range tasks {
326 ch, ok := boot.tasksReady[task.String()]
328 return fmt.Errorf("no such task: %s", task)
330 boot.logger.WithField("task", task.String()).Info("waiting")
333 boot.logger.WithField("task", task.String()).Info("ready")
335 boot.logger.WithField("task", task.String()).Info("task was never ready")
342 func (boot *Booter) Stop() {
347 func (boot *Booter) WaitReady() (*arvados.URL, bool) {
348 ticker := time.NewTicker(time.Second)
350 for waiting := true; waiting; {
353 case <-boot.ctx.Done():
356 if boot.healthChecker == nil {
360 resp := boot.healthChecker.ClusterHealth()
361 // The overall health check (resp.Health=="OK") might
362 // never pass due to missing components (like
363 // arvados-dispatch-cloud in a test cluster), so
364 // instead we wait for all configured components to
367 for target, check := range resp.Checks {
368 if check.Health != "OK" {
370 boot.logger.WithField("target", target).Debug("waiting")
374 u := boot.cluster.Services.Controller.ExternalURL
378 func (boot *Booter) prependEnv(key, prepend string) {
379 for i, s := range boot.environ {
380 if strings.HasPrefix(s, key+"=") {
381 boot.environ[i] = key + "=" + prepend + s[len(key)+1:]
385 boot.environ = append(boot.environ, key+"="+prepend)
388 var cleanEnvPrefixes = []string{
394 func (boot *Booter) cleanEnv() {
396 for _, s := range boot.environ {
398 for _, p := range cleanEnvPrefixes {
399 if strings.HasPrefix(s, p) {
405 cleaned = append(cleaned, s)
408 boot.environ = cleaned
411 func (boot *Booter) setEnv(key, val string) {
412 for i, s := range boot.environ {
413 if strings.HasPrefix(s, key+"=") {
414 boot.environ[i] = key + "=" + val
418 boot.environ = append(boot.environ, key+"="+val)
421 // Remove all but the first occurrence of each env var.
422 func dedupEnv(in []string) []string {
423 saw := map[string]bool{}
425 for _, kv := range in {
426 if split := strings.Index(kv, "="); split < 1 {
427 panic("invalid environment var: " + kv)
428 } else if saw[kv[:split]] {
431 saw[kv[:split]] = true
432 out = append(out, kv)
438 func (boot *Booter) installGoProgram(ctx context.Context, srcpath string) (string, error) {
439 _, basename := filepath.Split(srcpath)
440 bindir := filepath.Join(boot.tempdir, "bin")
441 binfile := filepath.Join(bindir, basename)
442 err := boot.RunProgram(ctx, filepath.Join(boot.SourcePath, srcpath), nil, []string{"GOBIN=" + bindir}, "go", "install", "-ldflags", "-X git.arvados.org/arvados.git/lib/cmd.version="+boot.SourceVersion+" -X main.version="+boot.SourceVersion)
446 func (boot *Booter) setupRubyEnv() error {
447 cmd := exec.Command("gem", "env", "gempath")
448 cmd.Env = boot.environ
449 buf, err := cmd.Output() // /var/lib/arvados/.gem/ruby/2.5.0/bin:...
450 if err != nil || len(buf) == 0 {
451 return fmt.Errorf("gem env gempath: %v", err)
453 gempath := string(bytes.Split(buf, []byte{':'})[0])
454 boot.prependEnv("PATH", gempath+"/bin:")
455 boot.setEnv("GEM_HOME", gempath)
456 boot.setEnv("GEM_PATH", gempath)
457 // Passenger install doesn't work unless $HOME is ~user
458 u, err := user.Current()
462 boot.setEnv("HOME", u.HomeDir)
466 func (boot *Booter) lookPath(prog string) string {
467 for _, val := range boot.environ {
468 if strings.HasPrefix(val, "PATH=") {
469 for _, dir := range filepath.SplitList(val[5:]) {
470 path := filepath.Join(dir, prog)
471 if fi, err := os.Stat(path); err == nil && fi.Mode()&0111 != 0 {
480 // Run prog with args, using dir as working directory. If ctx is
481 // cancelled while the child is running, RunProgram terminates the
482 // child, waits for it to exit, then returns.
484 // Child's environment will have our env vars, plus any given in env.
486 // Child's stdout will be written to output if non-nil, otherwise the
487 // boot command's stderr.
488 func (boot *Booter) RunProgram(ctx context.Context, dir string, output io.Writer, env []string, prog string, args ...string) error {
489 cmdline := fmt.Sprintf("%s", append([]string{prog}, args...))
490 boot.logger.WithField("command", cmdline).WithField("dir", dir).Info("executing")
492 logprefix := strings.TrimPrefix(prog, boot.tempdir+"/bin/")
493 if prog == "bundle" && len(args) > 2 && args[0] == "exec" {
495 } else if prog == "arvados-server" && len(args) > 1 {
498 if !strings.HasPrefix(dir, "/") {
499 logprefix = dir + ": " + logprefix
502 cmd := exec.Command(boot.lookPath(prog), args...)
503 stdout, err := cmd.StdoutPipe()
507 stderr, err := cmd.StderrPipe()
511 logwriter := &service.LogPrefixer{Writer: boot.Stderr, Prefix: []byte("[" + logprefix + "] ")}
512 var copiers sync.WaitGroup
515 io.Copy(logwriter, stderr)
521 io.Copy(logwriter, stdout)
523 io.Copy(output, stdout)
528 if strings.HasPrefix(dir, "/") {
531 cmd.Dir = filepath.Join(boot.SourcePath, dir)
533 env = append([]string(nil), env...)
534 env = append(env, boot.environ...)
535 cmd.Env = dedupEnv(env)
538 defer func() { exited = true }()
541 log := ctxlog.FromContext(ctx).WithFields(logrus.Fields{"dir": dir, "cmdline": cmdline})
543 if cmd.Process == nil {
544 log.Debug("waiting for child process to start")
545 time.Sleep(time.Second / 2)
547 log.WithField("PID", cmd.Process.Pid).Debug("sending SIGTERM")
548 cmd.Process.Signal(syscall.SIGTERM)
549 time.Sleep(5 * time.Second)
553 log.WithField("PID", cmd.Process.Pid).Warn("still waiting for child process to exit 5s after SIGTERM")
565 if ctx.Err() != nil {
566 // Return "context canceled", instead of the "killed"
567 // error that was probably caused by the context being
570 } else if err != nil {
571 return fmt.Errorf("%s: error: %v", cmdline, err)
576 func (boot *Booter) autofillConfig(cfg *arvados.Config, log logrus.FieldLogger) error {
577 cluster, err := cfg.GetCluster("")
581 usedPort := map[string]bool{}
582 nextPort := func() string {
584 port, err := availablePort(boot.ListenHost + ":0")
591 usedPort[port] = true
595 if cluster.Services.Controller.ExternalURL.Host == "" {
596 h, p, err := net.SplitHostPort(boot.ControllerAddr)
604 p, err = availablePort(":0")
610 cluster.Services.Controller.ExternalURL = arvados.URL{Scheme: "https", Host: net.JoinHostPort(h, p)}
612 for _, svc := range []*arvados.Service{
613 &cluster.Services.Controller,
614 &cluster.Services.DispatchCloud,
615 &cluster.Services.GitHTTP,
616 &cluster.Services.Health,
617 &cluster.Services.Keepproxy,
618 &cluster.Services.Keepstore,
619 &cluster.Services.RailsAPI,
620 &cluster.Services.WebDAV,
621 &cluster.Services.WebDAVDownload,
622 &cluster.Services.Websocket,
623 &cluster.Services.Workbench1,
625 if svc == &cluster.Services.DispatchCloud && boot.ClusterType == "test" {
628 if svc.ExternalURL.Host == "" && (svc == &cluster.Services.Controller ||
629 svc == &cluster.Services.GitHTTP ||
630 svc == &cluster.Services.Keepproxy ||
631 svc == &cluster.Services.WebDAV ||
632 svc == &cluster.Services.WebDAVDownload ||
633 svc == &cluster.Services.Websocket ||
634 svc == &cluster.Services.Workbench1) {
635 svc.ExternalURL = arvados.URL{Scheme: "https", Host: fmt.Sprintf("%s:%s", boot.ListenHost, nextPort())}
637 if len(svc.InternalURLs) == 0 {
638 svc.InternalURLs = map[arvados.URL]arvados.ServiceInstance{
639 arvados.URL{Scheme: "http", Host: fmt.Sprintf("%s:%s", boot.ListenHost, nextPort())}: arvados.ServiceInstance{},
643 if cluster.SystemRootToken == "" {
644 cluster.SystemRootToken = randomHexString(64)
646 if cluster.ManagementToken == "" {
647 cluster.ManagementToken = randomHexString(64)
649 if cluster.API.RailsSessionSecretToken == "" {
650 cluster.API.RailsSessionSecretToken = randomHexString(64)
652 if cluster.Collections.BlobSigningKey == "" {
653 cluster.Collections.BlobSigningKey = randomHexString(64)
655 if boot.ClusterType != "production" && cluster.Containers.DispatchPrivateKey == "" {
656 buf, err := ioutil.ReadFile(filepath.Join(boot.SourcePath, "lib", "dispatchcloud", "test", "sshkey_dispatch"))
660 cluster.Containers.DispatchPrivateKey = string(buf)
662 if boot.ClusterType != "production" {
663 cluster.TLS.Insecure = true
665 if boot.ClusterType == "test" {
666 // Add a second keepstore process.
667 cluster.Services.Keepstore.InternalURLs[arvados.URL{Scheme: "http", Host: fmt.Sprintf("%s:%s", boot.ListenHost, nextPort())}] = arvados.ServiceInstance{}
669 // Create a directory-backed volume for each keepstore
671 cluster.Volumes = map[string]arvados.Volume{}
672 for url := range cluster.Services.Keepstore.InternalURLs {
673 volnum := len(cluster.Volumes)
674 datadir := fmt.Sprintf("%s/keep%d.data", boot.tempdir, volnum)
675 if _, err = os.Stat(datadir + "/."); err == nil {
676 } else if !os.IsNotExist(err) {
678 } else if err = os.Mkdir(datadir, 0777); err != nil {
681 cluster.Volumes[fmt.Sprintf(cluster.ClusterID+"-nyw5e-%015d", volnum)] = arvados.Volume{
683 DriverParameters: json.RawMessage(fmt.Sprintf(`{"Root":%q}`, datadir)),
684 AccessViaHosts: map[arvados.URL]arvados.VolumeAccess{
690 if boot.OwnTemporaryDatabase {
691 cluster.PostgreSQL.Connection = arvados.PostgreSQLConnection{
692 "client_encoding": "utf8",
695 "dbname": "arvados_test",
697 "password": "insecure_arvados_test",
701 cfg.Clusters[cluster.ClusterID] = *cluster
705 func randomHexString(chars int) string {
706 b := make([]byte, chars/2)
707 _, err := rand.Read(b)
711 return fmt.Sprintf("%x", b)
714 func internalPort(svc arvados.Service) (string, error) {
715 for u := range svc.InternalURLs {
716 if _, p, err := net.SplitHostPort(u.Host); err != nil {
720 } else if u.Scheme == "https" {
726 return "", fmt.Errorf("service has no InternalURLs")
729 func externalPort(svc arvados.Service) (string, error) {
730 if _, p, err := net.SplitHostPort(svc.ExternalURL.Host); err != nil {
734 } else if svc.ExternalURL.Scheme == "https" {
741 func availablePort(addr string) (string, error) {
742 ln, err := net.Listen("tcp", addr)
747 _, port, err := net.SplitHostPort(ln.Addr().String())
754 // Try to connect to addr until it works, then close ch. Give up if
756 func waitForConnect(ctx context.Context, addr string) error {
757 dialer := net.Dialer{Timeout: time.Second}
758 for ctx.Err() == nil {
759 conn, err := dialer.DialContext(ctx, "tcp", addr)
761 time.Sleep(time.Second / 10)