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 // Wait for signal/crash + orderly shutdown
109 SourcePath string // e.g., /home/username/src/arvados
110 LibPath string // e.g., /var/lib/arvados
111 ClusterType string // e.g., production
112 ListenHost string // e.g., localhost
113 ControllerAddr string // e.g., 127.0.0.1:8000
114 OwnTemporaryDatabase bool
117 logger logrus.FieldLogger
118 cluster *arvados.Cluster
121 cancel context.CancelFunc
123 healthChecker *health.Aggregator
124 tasksReady map[string]chan bool
125 waitShutdown sync.WaitGroup
129 environ []string // for child processes
131 setupRubyOnce sync.Once
136 func (boot *Booter) Start(ctx context.Context, cfg *arvados.Config) {
137 boot.ctx, boot.cancel = context.WithCancel(ctx)
138 boot.done = make(chan struct{})
141 sigch := make(chan os.Signal)
142 signal.Notify(sigch, syscall.SIGINT, syscall.SIGTERM)
143 defer signal.Stop(sigch)
145 for sig := range sigch {
146 boot.logger.WithField("signal", sig).Info("caught signal")
153 fmt.Fprintln(boot.Stderr, err)
159 func (boot *Booter) run(cfg *arvados.Config) error {
160 cwd, err := os.Getwd()
164 if !strings.HasPrefix(boot.SourcePath, "/") {
165 boot.SourcePath = filepath.Join(cwd, boot.SourcePath)
167 boot.SourcePath, err = filepath.EvalSymlinks(boot.SourcePath)
172 boot.tempdir, err = ioutil.TempDir("", "arvados-server-boot-")
176 defer os.RemoveAll(boot.tempdir)
178 // Fill in any missing config keys, and write the resulting
179 // config in the temp dir for child services to use.
180 err = boot.autofillConfig(cfg, boot.logger)
184 conffile, err := os.OpenFile(filepath.Join(boot.tempdir, "config.yml"), os.O_CREATE|os.O_WRONLY, 0777)
188 defer conffile.Close()
189 err = json.NewEncoder(conffile).Encode(cfg)
193 err = conffile.Close()
197 boot.configfile = conffile.Name()
199 boot.environ = os.Environ()
201 boot.setEnv("ARVADOS_CONFIG", boot.configfile)
202 boot.setEnv("RAILS_ENV", boot.ClusterType)
203 boot.setEnv("TMPDIR", boot.tempdir)
204 boot.prependEnv("PATH", filepath.Join(boot.LibPath, "bin")+":")
206 boot.cluster, err = cfg.GetCluster("")
210 // Now that we have the config, replace the bootstrap logger
211 // with a new one according to the logging config.
212 loglevel := boot.cluster.SystemLogs.LogLevel
213 if s := os.Getenv("ARVADOS_DEBUG"); s != "" && s != "0" {
216 boot.logger = ctxlog.New(boot.Stderr, boot.cluster.SystemLogs.Format, loglevel).WithFields(logrus.Fields{
220 for _, dir := range []string{boot.LibPath, filepath.Join(boot.LibPath, "bin")} {
221 if _, err = os.Stat(filepath.Join(dir, ".")); os.IsNotExist(err) {
222 err = os.Mkdir(dir, 0755)
226 } else if err != nil {
230 err = boot.installGoProgram(boot.ctx, "cmd/arvados-server")
234 err = boot.setupRubyEnv()
240 createCertificates{},
243 runServiceCommand{name: "controller", svc: boot.cluster.Services.Controller, depends: []bootTask{runPostgreSQL{}}},
244 runGoProgram{src: "services/arv-git-httpd"},
245 runGoProgram{src: "services/health"},
246 runGoProgram{src: "services/keepproxy", depends: []bootTask{runPassenger{src: "services/api"}}},
247 runGoProgram{src: "services/keepstore", svc: boot.cluster.Services.Keepstore},
248 runGoProgram{src: "services/keep-web"},
249 runGoProgram{src: "services/ws", depends: []bootTask{runPostgreSQL{}}},
250 installPassenger{src: "services/api"},
251 runPassenger{src: "services/api", svc: boot.cluster.Services.RailsAPI, depends: []bootTask{createCertificates{}, runPostgreSQL{}, installPassenger{src: "services/api"}}},
252 installPassenger{src: "apps/workbench", depends: []bootTask{installPassenger{src: "services/api"}}}, // dependency ensures workbench doesn't delay api startup
253 runPassenger{src: "apps/workbench", svc: boot.cluster.Services.Workbench1, depends: []bootTask{installPassenger{src: "apps/workbench"}}},
256 if boot.ClusterType != "test" {
257 tasks = append(tasks,
258 runServiceCommand{name: "dispatch-cloud", svc: boot.cluster.Services.Controller},
259 runGoProgram{src: "services/keep-balance"},
262 boot.tasksReady = map[string]chan bool{}
263 for _, task := range tasks {
264 boot.tasksReady[task.String()] = make(chan bool)
266 for _, task := range tasks {
268 fail := func(err error) {
269 if boot.ctx.Err() != nil {
273 boot.logger.WithField("task", task.String()).WithError(err).Error("task failed")
276 boot.logger.WithField("task", task.String()).Info("starting")
277 err := task.Run(boot.ctx, fail, boot)
282 close(boot.tasksReady[task.String()])
285 err = boot.wait(boot.ctx, tasks...)
289 boot.logger.Info("all startup tasks are complete; starting health checks")
290 boot.healthChecker = &health.Aggregator{Cluster: boot.cluster}
292 boot.logger.Info("shutting down")
293 boot.waitShutdown.Wait()
294 return boot.ctx.Err()
297 func (boot *Booter) wait(ctx context.Context, tasks ...bootTask) error {
298 for _, task := range tasks {
299 ch, ok := boot.tasksReady[task.String()]
301 return fmt.Errorf("no such task: %s", task)
303 boot.logger.WithField("task", task.String()).Info("waiting")
306 boot.logger.WithField("task", task.String()).Info("ready")
308 boot.logger.WithField("task", task.String()).Info("task was never ready")
315 func (boot *Booter) Stop() {
320 func (boot *Booter) WaitReady() (*arvados.URL, bool) {
321 ticker := time.NewTicker(time.Second)
323 for waiting := true; waiting; {
326 case <-boot.ctx.Done():
329 if boot.healthChecker == nil {
333 resp := boot.healthChecker.ClusterHealth()
334 // The overall health check (resp.Health=="OK") might
335 // never pass due to missing components (like
336 // arvados-dispatch-cloud in a test cluster), so
337 // instead we wait for all configured components to
340 for target, check := range resp.Checks {
341 if check.Health != "OK" {
343 boot.logger.WithField("target", target).Debug("waiting")
347 u := boot.cluster.Services.Controller.ExternalURL
351 func (boot *Booter) prependEnv(key, prepend string) {
352 for i, s := range boot.environ {
353 if strings.HasPrefix(s, key+"=") {
354 boot.environ[i] = key + "=" + prepend + s[len(key)+1:]
358 boot.environ = append(boot.environ, key+"="+prepend)
361 var cleanEnvPrefixes = []string{
367 func (boot *Booter) cleanEnv() {
369 for _, s := range boot.environ {
371 for _, p := range cleanEnvPrefixes {
372 if strings.HasPrefix(s, p) {
378 cleaned = append(cleaned, s)
381 boot.environ = cleaned
384 func (boot *Booter) setEnv(key, val string) {
385 for i, s := range boot.environ {
386 if strings.HasPrefix(s, key+"=") {
387 boot.environ[i] = key + "=" + val
391 boot.environ = append(boot.environ, key+"="+val)
394 func (boot *Booter) installGoProgram(ctx context.Context, srcpath string) error {
396 defer boot.goMutex.Unlock()
397 return boot.RunProgram(ctx, filepath.Join(boot.SourcePath, srcpath), nil, []string{"GOPATH=" + boot.LibPath}, "go", "install")
400 func (boot *Booter) setupRubyEnv() error {
401 cmd := exec.Command("gem", "env", "gempath")
402 cmd.Env = boot.environ
403 buf, err := cmd.Output() // /var/lib/arvados/.gem/ruby/2.5.0/bin:...
404 if err != nil || len(buf) == 0 {
405 return fmt.Errorf("gem env gempath: %v", err)
407 gempath := string(bytes.Split(buf, []byte{':'})[0])
408 boot.prependEnv("PATH", gempath+"/bin:")
409 boot.setEnv("GEM_HOME", gempath)
410 boot.setEnv("GEM_PATH", gempath)
411 // Passenger install doesn't work unless $HOME is ~user
412 u, err := user.Current()
416 boot.setEnv("HOME", u.HomeDir)
420 func (boot *Booter) lookPath(prog string) string {
421 for _, val := range boot.environ {
422 if strings.HasPrefix(val, "PATH=") {
423 for _, dir := range filepath.SplitList(val[5:]) {
424 path := filepath.Join(dir, prog)
425 if fi, err := os.Stat(path); err == nil && fi.Mode()&0111 != 0 {
434 // Run prog with args, using dir as working directory. If ctx is
435 // cancelled while the child is running, RunProgram terminates the
436 // child, waits for it to exit, then returns.
438 // Child's environment will have our env vars, plus any given in env.
440 // Child's stdout will be written to output if non-nil, otherwise the
441 // boot command's stderr.
442 func (boot *Booter) RunProgram(ctx context.Context, dir string, output io.Writer, env []string, prog string, args ...string) error {
443 cmdline := fmt.Sprintf("%s", append([]string{prog}, args...))
444 fmt.Fprintf(boot.Stderr, "%s executing in %s\n", cmdline, dir)
447 if prog == "bundle" && len(args) > 2 && args[0] == "exec" {
450 if !strings.HasPrefix(dir, "/") {
451 logprefix = dir + ": " + logprefix
454 cmd := exec.Command(boot.lookPath(prog), args...)
455 stdout, err := cmd.StdoutPipe()
459 stderr, err := cmd.StderrPipe()
463 logwriter := &logPrefixer{Writer: boot.Stderr, Prefix: []byte("[" + logprefix + "] ")}
464 go io.Copy(logwriter, stderr)
466 go io.Copy(logwriter, stdout)
468 go io.Copy(output, stdout)
471 if strings.HasPrefix(dir, "/") {
474 cmd.Dir = filepath.Join(boot.SourcePath, dir)
476 cmd.Env = append(env, boot.environ...)
479 defer func() { exited = true }()
482 log := ctxlog.FromContext(ctx).WithFields(logrus.Fields{"dir": dir, "cmdline": cmdline})
484 if cmd.Process == nil {
485 log.Debug("waiting for child process to start")
486 time.Sleep(time.Second / 2)
488 log.WithField("PID", cmd.Process.Pid).Debug("sending SIGTERM")
489 cmd.Process.Signal(syscall.SIGTERM)
490 time.Sleep(5 * time.Second)
494 log.WithField("PID", cmd.Process.Pid).Warn("still waiting for child process to exit 5s after SIGTERM")
505 if err != nil && ctx.Err() == nil {
506 // Only report errors that happen before the context ends.
507 return fmt.Errorf("%s: error: %v", cmdline, err)
512 func (boot *Booter) autofillConfig(cfg *arvados.Config, log logrus.FieldLogger) error {
513 cluster, err := cfg.GetCluster("")
517 usedPort := map[string]bool{}
518 nextPort := func() string {
520 port, err := availablePort(":0")
527 usedPort[port] = true
531 if cluster.Services.Controller.ExternalURL.Host == "" {
532 h, p, err := net.SplitHostPort(boot.ControllerAddr)
540 p, err = availablePort(":0")
546 cluster.Services.Controller.ExternalURL = arvados.URL{Scheme: "https", Host: net.JoinHostPort(h, p)}
548 for _, svc := range []*arvados.Service{
549 &cluster.Services.Controller,
550 &cluster.Services.DispatchCloud,
551 &cluster.Services.GitHTTP,
552 &cluster.Services.Health,
553 &cluster.Services.Keepproxy,
554 &cluster.Services.Keepstore,
555 &cluster.Services.RailsAPI,
556 &cluster.Services.WebDAV,
557 &cluster.Services.WebDAVDownload,
558 &cluster.Services.Websocket,
559 &cluster.Services.Workbench1,
561 if svc == &cluster.Services.DispatchCloud && boot.ClusterType == "test" {
564 if svc.ExternalURL.Host == "" && (svc == &cluster.Services.Controller ||
565 svc == &cluster.Services.GitHTTP ||
566 svc == &cluster.Services.Keepproxy ||
567 svc == &cluster.Services.WebDAV ||
568 svc == &cluster.Services.WebDAVDownload ||
569 svc == &cluster.Services.Websocket ||
570 svc == &cluster.Services.Workbench1) {
571 svc.ExternalURL = arvados.URL{Scheme: "https", Host: fmt.Sprintf("%s:%s", boot.ListenHost, nextPort())}
573 if len(svc.InternalURLs) == 0 {
574 svc.InternalURLs = map[arvados.URL]arvados.ServiceInstance{
575 arvados.URL{Scheme: "http", Host: fmt.Sprintf("%s:%s", boot.ListenHost, nextPort())}: arvados.ServiceInstance{},
579 if cluster.SystemRootToken == "" {
580 cluster.SystemRootToken = randomHexString(64)
582 if cluster.ManagementToken == "" {
583 cluster.ManagementToken = randomHexString(64)
585 if cluster.API.RailsSessionSecretToken == "" {
586 cluster.API.RailsSessionSecretToken = randomHexString(64)
588 if cluster.Collections.BlobSigningKey == "" {
589 cluster.Collections.BlobSigningKey = randomHexString(64)
591 if boot.ClusterType != "production" && cluster.Containers.DispatchPrivateKey == "" {
592 buf, err := ioutil.ReadFile(filepath.Join(boot.SourcePath, "lib", "dispatchcloud", "test", "sshkey_dispatch"))
596 cluster.Containers.DispatchPrivateKey = string(buf)
598 if boot.ClusterType != "production" {
599 cluster.TLS.Insecure = true
601 if boot.ClusterType == "test" {
602 // Add a second keepstore process.
603 cluster.Services.Keepstore.InternalURLs[arvados.URL{Scheme: "http", Host: fmt.Sprintf("%s:%s", boot.ListenHost, nextPort())}] = arvados.ServiceInstance{}
605 // Create a directory-backed volume for each keepstore
607 cluster.Volumes = map[string]arvados.Volume{}
608 for url := range cluster.Services.Keepstore.InternalURLs {
609 volnum := len(cluster.Volumes)
610 datadir := fmt.Sprintf("%s/keep%d.data", boot.tempdir, volnum)
611 if _, err = os.Stat(datadir + "/."); err == nil {
612 } else if !os.IsNotExist(err) {
614 } else if err = os.Mkdir(datadir, 0777); err != nil {
617 cluster.Volumes[fmt.Sprintf(cluster.ClusterID+"-nyw5e-%015d", volnum)] = arvados.Volume{
619 DriverParameters: json.RawMessage(fmt.Sprintf(`{"Root":%q}`, datadir)),
620 AccessViaHosts: map[arvados.URL]arvados.VolumeAccess{
626 if boot.OwnTemporaryDatabase {
627 cluster.PostgreSQL.Connection = arvados.PostgreSQLConnection{
628 "client_encoding": "utf8",
631 "dbname": "arvados_test",
633 "password": "insecure_arvados_test",
637 cfg.Clusters[cluster.ClusterID] = *cluster
641 func randomHexString(chars int) string {
642 b := make([]byte, chars/2)
643 _, err := rand.Read(b)
647 return fmt.Sprintf("%x", b)
650 func internalPort(svc arvados.Service) (string, error) {
651 for u := range svc.InternalURLs {
652 if _, p, err := net.SplitHostPort(u.Host); err != nil {
656 } else if u.Scheme == "https" {
662 return "", fmt.Errorf("service has no InternalURLs")
665 func externalPort(svc arvados.Service) (string, error) {
666 if _, p, err := net.SplitHostPort(svc.ExternalURL.Host); err != nil {
670 } else if svc.ExternalURL.Scheme == "https" {
677 func availablePort(addr string) (string, error) {
678 ln, err := net.Listen("tcp", addr)
683 _, port, err := net.SplitHostPort(ln.Addr().String())
690 // Try to connect to addr until it works, then close ch. Give up if
692 func waitForConnect(ctx context.Context, addr string) error {
693 dialer := net.Dialer{Timeout: time.Second}
694 for ctx.Err() == nil {
695 conn, err := dialer.DialContext(ctx, "tcp", addr)
697 time.Sleep(time.Second / 10)