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)
179 // Fill in any missing config keys, and write the resulting
180 // config in the temp dir for child services to use.
181 err = boot.autofillConfig(cfg, boot.logger)
185 conffile, err := os.OpenFile(filepath.Join(boot.tempdir, "config.yml"), os.O_CREATE|os.O_WRONLY, 0777)
189 defer conffile.Close()
190 err = json.NewEncoder(conffile).Encode(cfg)
194 err = conffile.Close()
198 boot.configfile = conffile.Name()
200 boot.environ = os.Environ()
202 boot.setEnv("ARVADOS_CONFIG", boot.configfile)
203 boot.setEnv("RAILS_ENV", boot.ClusterType)
204 boot.setEnv("TMPDIR", boot.tempdir)
205 boot.prependEnv("PATH", filepath.Join(boot.LibPath, "bin")+":")
207 boot.cluster, err = cfg.GetCluster("")
211 // Now that we have the config, replace the bootstrap logger
212 // with a new one according to the logging config.
213 loglevel := boot.cluster.SystemLogs.LogLevel
214 if s := os.Getenv("ARVADOS_DEBUG"); s != "" && s != "0" {
217 boot.logger = ctxlog.New(boot.Stderr, boot.cluster.SystemLogs.Format, loglevel).WithFields(logrus.Fields{
221 for _, dir := range []string{boot.LibPath, filepath.Join(boot.LibPath, "bin")} {
222 if _, err = os.Stat(filepath.Join(dir, ".")); os.IsNotExist(err) {
223 err = os.Mkdir(dir, 0755)
227 } else if err != nil {
231 err = boot.installGoProgram(boot.ctx, "cmd/arvados-server")
235 err = boot.setupRubyEnv()
241 createCertificates{},
244 runServiceCommand{name: "controller", svc: boot.cluster.Services.Controller, depends: []bootTask{runPostgreSQL{}}},
245 runGoProgram{src: "services/arv-git-httpd"},
246 runGoProgram{src: "services/health"},
247 runGoProgram{src: "services/keepproxy", depends: []bootTask{runPassenger{src: "services/api"}}},
248 runGoProgram{src: "services/keepstore", svc: boot.cluster.Services.Keepstore},
249 runGoProgram{src: "services/keep-web"},
250 runGoProgram{src: "services/ws", depends: []bootTask{runPostgreSQL{}}},
251 installPassenger{src: "services/api"},
252 runPassenger{src: "services/api", svc: boot.cluster.Services.RailsAPI, depends: []bootTask{createCertificates{}, runPostgreSQL{}, installPassenger{src: "services/api"}}},
253 installPassenger{src: "apps/workbench", depends: []bootTask{installPassenger{src: "services/api"}}}, // dependency ensures workbench doesn't delay api startup
254 runPassenger{src: "apps/workbench", svc: boot.cluster.Services.Workbench1, depends: []bootTask{installPassenger{src: "apps/workbench"}}},
257 if boot.ClusterType != "test" {
258 tasks = append(tasks,
259 runServiceCommand{name: "dispatch-cloud", svc: boot.cluster.Services.Controller},
260 runGoProgram{src: "services/keep-balance"},
263 boot.tasksReady = map[string]chan bool{}
264 for _, task := range tasks {
265 boot.tasksReady[task.String()] = make(chan bool)
267 for _, task := range tasks {
269 fail := func(err error) {
270 if boot.ctx.Err() != nil {
274 boot.logger.WithField("task", task.String()).WithError(err).Error("task failed")
277 boot.logger.WithField("task", task.String()).Info("starting")
278 err := task.Run(boot.ctx, fail, boot)
283 close(boot.tasksReady[task.String()])
286 err = boot.wait(boot.ctx, tasks...)
290 boot.logger.Info("all startup tasks are complete; starting health checks")
291 boot.healthChecker = &health.Aggregator{Cluster: boot.cluster}
293 boot.logger.Info("shutting down")
294 boot.waitShutdown.Wait()
295 return boot.ctx.Err()
298 func (boot *Booter) wait(ctx context.Context, tasks ...bootTask) error {
299 for _, task := range tasks {
300 ch, ok := boot.tasksReady[task.String()]
302 return fmt.Errorf("no such task: %s", task)
304 boot.logger.WithField("task", task.String()).Info("waiting")
307 boot.logger.WithField("task", task.String()).Info("ready")
309 boot.logger.WithField("task", task.String()).Info("task was never ready")
316 func (boot *Booter) Stop() {
321 func (boot *Booter) WaitReady() (*arvados.URL, bool) {
322 ticker := time.NewTicker(time.Second)
324 for waiting := true; waiting; {
327 case <-boot.ctx.Done():
330 if boot.healthChecker == nil {
334 resp := boot.healthChecker.ClusterHealth()
335 // The overall health check (resp.Health=="OK") might
336 // never pass due to missing components (like
337 // arvados-dispatch-cloud in a test cluster), so
338 // instead we wait for all configured components to
341 for target, check := range resp.Checks {
342 if check.Health != "OK" {
344 boot.logger.WithField("target", target).Debug("waiting")
348 u := boot.cluster.Services.Controller.ExternalURL
352 func (boot *Booter) prependEnv(key, prepend string) {
353 for i, s := range boot.environ {
354 if strings.HasPrefix(s, key+"=") {
355 boot.environ[i] = key + "=" + prepend + s[len(key)+1:]
359 boot.environ = append(boot.environ, key+"="+prepend)
362 var cleanEnvPrefixes = []string{
368 func (boot *Booter) cleanEnv() {
370 for _, s := range boot.environ {
372 for _, p := range cleanEnvPrefixes {
373 if strings.HasPrefix(s, p) {
379 cleaned = append(cleaned, s)
382 boot.environ = cleaned
385 func (boot *Booter) setEnv(key, val string) {
386 for i, s := range boot.environ {
387 if strings.HasPrefix(s, key+"=") {
388 boot.environ[i] = key + "=" + val
392 boot.environ = append(boot.environ, key+"="+val)
395 // Remove all but the first occurrence of each env var.
396 func dedupEnv(in []string) []string {
397 saw := map[string]bool{}
399 for _, kv := range in {
400 if split := strings.Index(kv, "="); split < 1 {
401 panic("invalid environment var: " + kv)
402 } else if saw[kv[:split]] {
405 saw[kv[:split]] = true
406 out = append(out, kv)
412 func (boot *Booter) installGoProgram(ctx context.Context, srcpath string) error {
414 defer boot.goMutex.Unlock()
415 return boot.RunProgram(ctx, filepath.Join(boot.SourcePath, srcpath), nil, []string{"GOPATH=" + boot.LibPath}, "go", "install")
418 func (boot *Booter) setupRubyEnv() error {
419 cmd := exec.Command("gem", "env", "gempath")
420 cmd.Env = boot.environ
421 buf, err := cmd.Output() // /var/lib/arvados/.gem/ruby/2.5.0/bin:...
422 if err != nil || len(buf) == 0 {
423 return fmt.Errorf("gem env gempath: %v", err)
425 gempath := string(bytes.Split(buf, []byte{':'})[0])
426 boot.prependEnv("PATH", gempath+"/bin:")
427 boot.setEnv("GEM_HOME", gempath)
428 boot.setEnv("GEM_PATH", gempath)
429 // Passenger install doesn't work unless $HOME is ~user
430 u, err := user.Current()
434 boot.setEnv("HOME", u.HomeDir)
438 func (boot *Booter) lookPath(prog string) string {
439 for _, val := range boot.environ {
440 if strings.HasPrefix(val, "PATH=") {
441 for _, dir := range filepath.SplitList(val[5:]) {
442 path := filepath.Join(dir, prog)
443 if fi, err := os.Stat(path); err == nil && fi.Mode()&0111 != 0 {
452 // Run prog with args, using dir as working directory. If ctx is
453 // cancelled while the child is running, RunProgram terminates the
454 // child, waits for it to exit, then returns.
456 // Child's environment will have our env vars, plus any given in env.
458 // Child's stdout will be written to output if non-nil, otherwise the
459 // boot command's stderr.
460 func (boot *Booter) RunProgram(ctx context.Context, dir string, output io.Writer, env []string, prog string, args ...string) error {
461 cmdline := fmt.Sprintf("%s", append([]string{prog}, args...))
462 boot.logger.WithField("command", cmdline).WithField("dir", dir).Info("executing")
465 if prog == "bundle" && len(args) > 2 && args[0] == "exec" {
467 } else if prog == "arvados-server" && len(args) > 1 {
470 if !strings.HasPrefix(dir, "/") {
471 logprefix = dir + ": " + logprefix
474 cmd := exec.Command(boot.lookPath(prog), args...)
475 stdout, err := cmd.StdoutPipe()
479 stderr, err := cmd.StderrPipe()
483 logwriter := &service.LogPrefixer{Writer: boot.Stderr, Prefix: []byte("[" + logprefix + "] ")}
484 go io.Copy(logwriter, stderr)
486 go io.Copy(logwriter, stdout)
488 go io.Copy(output, stdout)
491 if strings.HasPrefix(dir, "/") {
494 cmd.Dir = filepath.Join(boot.SourcePath, dir)
496 env = append([]string(nil), env...)
497 env = append(env, boot.environ...)
498 cmd.Env = dedupEnv(env)
501 defer func() { exited = true }()
504 log := ctxlog.FromContext(ctx).WithFields(logrus.Fields{"dir": dir, "cmdline": cmdline})
506 if cmd.Process == nil {
507 log.Debug("waiting for child process to start")
508 time.Sleep(time.Second / 2)
510 log.WithField("PID", cmd.Process.Pid).Debug("sending SIGTERM")
511 cmd.Process.Signal(syscall.SIGTERM)
512 time.Sleep(5 * time.Second)
516 log.WithField("PID", cmd.Process.Pid).Warn("still waiting for child process to exit 5s after SIGTERM")
527 if err != nil && ctx.Err() == nil {
528 // Only report errors that happen before the context ends.
529 return fmt.Errorf("%s: error: %v", cmdline, err)
534 func (boot *Booter) autofillConfig(cfg *arvados.Config, log logrus.FieldLogger) error {
535 cluster, err := cfg.GetCluster("")
539 usedPort := map[string]bool{}
540 nextPort := func() string {
542 port, err := availablePort(":0")
549 usedPort[port] = true
553 if cluster.Services.Controller.ExternalURL.Host == "" {
554 h, p, err := net.SplitHostPort(boot.ControllerAddr)
562 p, err = availablePort(":0")
568 cluster.Services.Controller.ExternalURL = arvados.URL{Scheme: "https", Host: net.JoinHostPort(h, p)}
570 for _, svc := range []*arvados.Service{
571 &cluster.Services.Controller,
572 &cluster.Services.DispatchCloud,
573 &cluster.Services.GitHTTP,
574 &cluster.Services.Health,
575 &cluster.Services.Keepproxy,
576 &cluster.Services.Keepstore,
577 &cluster.Services.RailsAPI,
578 &cluster.Services.WebDAV,
579 &cluster.Services.WebDAVDownload,
580 &cluster.Services.Websocket,
581 &cluster.Services.Workbench1,
583 if svc == &cluster.Services.DispatchCloud && boot.ClusterType == "test" {
586 if svc.ExternalURL.Host == "" && (svc == &cluster.Services.Controller ||
587 svc == &cluster.Services.GitHTTP ||
588 svc == &cluster.Services.Keepproxy ||
589 svc == &cluster.Services.WebDAV ||
590 svc == &cluster.Services.WebDAVDownload ||
591 svc == &cluster.Services.Websocket ||
592 svc == &cluster.Services.Workbench1) {
593 svc.ExternalURL = arvados.URL{Scheme: "https", Host: fmt.Sprintf("%s:%s", boot.ListenHost, nextPort())}
595 if len(svc.InternalURLs) == 0 {
596 svc.InternalURLs = map[arvados.URL]arvados.ServiceInstance{
597 arvados.URL{Scheme: "http", Host: fmt.Sprintf("%s:%s", boot.ListenHost, nextPort())}: arvados.ServiceInstance{},
601 if cluster.SystemRootToken == "" {
602 cluster.SystemRootToken = randomHexString(64)
604 if cluster.ManagementToken == "" {
605 cluster.ManagementToken = randomHexString(64)
607 if cluster.API.RailsSessionSecretToken == "" {
608 cluster.API.RailsSessionSecretToken = randomHexString(64)
610 if cluster.Collections.BlobSigningKey == "" {
611 cluster.Collections.BlobSigningKey = randomHexString(64)
613 if boot.ClusterType != "production" && cluster.Containers.DispatchPrivateKey == "" {
614 buf, err := ioutil.ReadFile(filepath.Join(boot.SourcePath, "lib", "dispatchcloud", "test", "sshkey_dispatch"))
618 cluster.Containers.DispatchPrivateKey = string(buf)
620 if boot.ClusterType != "production" {
621 cluster.TLS.Insecure = true
623 if boot.ClusterType == "test" {
624 // Add a second keepstore process.
625 cluster.Services.Keepstore.InternalURLs[arvados.URL{Scheme: "http", Host: fmt.Sprintf("%s:%s", boot.ListenHost, nextPort())}] = arvados.ServiceInstance{}
627 // Create a directory-backed volume for each keepstore
629 cluster.Volumes = map[string]arvados.Volume{}
630 for url := range cluster.Services.Keepstore.InternalURLs {
631 volnum := len(cluster.Volumes)
632 datadir := fmt.Sprintf("%s/keep%d.data", boot.tempdir, volnum)
633 if _, err = os.Stat(datadir + "/."); err == nil {
634 } else if !os.IsNotExist(err) {
636 } else if err = os.Mkdir(datadir, 0777); err != nil {
639 cluster.Volumes[fmt.Sprintf(cluster.ClusterID+"-nyw5e-%015d", volnum)] = arvados.Volume{
641 DriverParameters: json.RawMessage(fmt.Sprintf(`{"Root":%q}`, datadir)),
642 AccessViaHosts: map[arvados.URL]arvados.VolumeAccess{
648 if boot.OwnTemporaryDatabase {
649 cluster.PostgreSQL.Connection = arvados.PostgreSQLConnection{
650 "client_encoding": "utf8",
653 "dbname": "arvados_test",
655 "password": "insecure_arvados_test",
659 cfg.Clusters[cluster.ClusterID] = *cluster
663 func randomHexString(chars int) string {
664 b := make([]byte, chars/2)
665 _, err := rand.Read(b)
669 return fmt.Sprintf("%x", b)
672 func internalPort(svc arvados.Service) (string, error) {
673 for u := range svc.InternalURLs {
674 if _, p, err := net.SplitHostPort(u.Host); err != nil {
678 } else if u.Scheme == "https" {
684 return "", fmt.Errorf("service has no InternalURLs")
687 func externalPort(svc arvados.Service) (string, error) {
688 if _, p, err := net.SplitHostPort(svc.ExternalURL.Host); err != nil {
692 } else if svc.ExternalURL.Scheme == "https" {
699 func availablePort(addr string) (string, error) {
700 ln, err := net.Listen("tcp", addr)
705 _, port, err := net.SplitHostPort(ln.Addr().String())
712 // Try to connect to addr until it works, then close ch. Give up if
714 func waitForConnect(ctx context.Context, addr string) error {
715 dialer := net.Dialer{Timeout: time.Second}
716 for ctx.Err() == nil {
717 conn, err := dialer.DialContext(ctx, "tcp", addr)
719 time.Sleep(time.Second / 10)