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)
59 ch := make(chan os.Signal)
60 signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
63 boot.logger.WithField("signal", sig).Info("caught signal")
71 boot.logger.WithError(err).Info("exiting")
75 flags := flag.NewFlagSet(prog, flag.ContinueOnError)
76 flags.SetOutput(stderr)
77 loader := config.NewLoader(stdin, boot.logger)
78 loader.SetupFlags(flags)
79 versionFlag := flags.Bool("version", false, "Write version information to stdout and exit 0")
80 flags.StringVar(&boot.SourcePath, "source", ".", "arvados source tree `directory`")
81 flags.StringVar(&boot.LibPath, "lib", "/var/lib/arvados", "`directory` to install dependencies and library files")
82 flags.StringVar(&boot.ClusterType, "type", "production", "cluster `type`: development, test, or production")
83 flags.StringVar(&boot.ListenHost, "listen-host", "localhost", "host name or interface address for service listeners")
84 flags.StringVar(&boot.ControllerAddr, "controller-address", ":0", "desired controller address, `host:port` or `:port`")
85 flags.BoolVar(&boot.OwnTemporaryDatabase, "own-temporary-database", false, "bring up a postgres server and create a temporary database")
86 err = flags.Parse(args)
87 if err == flag.ErrHelp {
90 } else if err != nil {
92 } else if *versionFlag {
93 return cmd.Version.RunCommand(prog, args, stdin, stdout, stderr)
94 } else if boot.ClusterType != "development" && boot.ClusterType != "test" && boot.ClusterType != "production" {
95 err = fmt.Errorf("cluster type must be 'development', 'test', or 'production'")
99 loader.SkipAPICalls = true
100 cfg, err := loader.Load()
107 if url, ok := boot.WaitReady(); ok {
108 fmt.Fprintln(stdout, url)
109 <-ctx.Done() // wait for signal
117 SourcePath string // e.g., /home/username/src/arvados
118 LibPath string // e.g., /var/lib/arvados
119 ClusterType string // e.g., production
120 ListenHost string // e.g., localhost
121 ControllerAddr string // e.g., 127.0.0.1:8000
122 OwnTemporaryDatabase bool
125 logger logrus.FieldLogger
126 cluster *arvados.Cluster
129 cancel context.CancelFunc
131 healthChecker *health.Aggregator
132 tasksReady map[string]chan bool
136 environ []string // for child processes
138 setupRubyOnce sync.Once
143 func (boot *Booter) Start(ctx context.Context, cfg *arvados.Config) {
144 boot.ctx, boot.cancel = context.WithCancel(ctx)
145 boot.done = make(chan struct{})
149 fmt.Fprintln(boot.Stderr, err)
155 func (boot *Booter) run(cfg *arvados.Config) error {
156 cwd, err := os.Getwd()
160 if !strings.HasPrefix(boot.SourcePath, "/") {
161 boot.SourcePath = filepath.Join(cwd, boot.SourcePath)
163 boot.SourcePath, err = filepath.EvalSymlinks(boot.SourcePath)
168 boot.tempdir, err = ioutil.TempDir("", "arvados-server-boot-")
172 defer os.RemoveAll(boot.tempdir)
174 // Fill in any missing config keys, and write the resulting
175 // config in the temp dir for child services to use.
176 err = boot.autofillConfig(cfg, boot.logger)
180 conffile, err := os.OpenFile(filepath.Join(boot.tempdir, "config.yml"), os.O_CREATE|os.O_WRONLY, 0777)
184 defer conffile.Close()
185 err = json.NewEncoder(conffile).Encode(cfg)
189 err = conffile.Close()
193 boot.configfile = conffile.Name()
195 boot.environ = os.Environ()
197 boot.setEnv("ARVADOS_CONFIG", boot.configfile)
198 boot.setEnv("RAILS_ENV", boot.ClusterType)
199 boot.setEnv("TMPDIR", boot.tempdir)
200 boot.prependEnv("PATH", filepath.Join(boot.LibPath, "bin")+":")
202 boot.cluster, err = cfg.GetCluster("")
206 // Now that we have the config, replace the bootstrap logger
207 // with a new one according to the logging config.
208 loglevel := boot.cluster.SystemLogs.LogLevel
209 if s := os.Getenv("ARVADOS_DEBUG"); s != "" && s != "0" {
212 boot.logger = ctxlog.New(boot.Stderr, boot.cluster.SystemLogs.Format, loglevel).WithFields(logrus.Fields{
216 for _, dir := range []string{boot.LibPath, filepath.Join(boot.LibPath, "bin")} {
217 if _, err = os.Stat(filepath.Join(dir, ".")); os.IsNotExist(err) {
218 err = os.Mkdir(dir, 0755)
222 } else if err != nil {
226 err = boot.installGoProgram(boot.ctx, "cmd/arvados-server")
230 err = boot.setupRubyEnv()
236 createCertificates{},
239 runServiceCommand{name: "controller", svc: boot.cluster.Services.Controller, depends: []bootTask{runPostgreSQL{}}},
240 runGoProgram{src: "services/arv-git-httpd"},
241 runGoProgram{src: "services/health"},
242 runGoProgram{src: "services/keepproxy", depends: []bootTask{runPassenger{src: "services/api"}}},
243 runGoProgram{src: "services/keepstore", svc: boot.cluster.Services.Keepstore},
244 runGoProgram{src: "services/keep-web"},
245 runGoProgram{src: "services/ws", depends: []bootTask{runPostgreSQL{}}},
246 installPassenger{src: "services/api"},
247 runPassenger{src: "services/api", svc: boot.cluster.Services.RailsAPI, depends: []bootTask{createCertificates{}, runPostgreSQL{}, installPassenger{src: "services/api"}}},
248 installPassenger{src: "apps/workbench", depends: []bootTask{installPassenger{src: "services/api"}}}, // dependency ensures workbench doesn't delay api startup
249 runPassenger{src: "apps/workbench", svc: boot.cluster.Services.Workbench1, depends: []bootTask{installPassenger{src: "apps/workbench"}}},
252 if boot.ClusterType != "test" {
253 tasks = append(tasks,
254 runServiceCommand{name: "dispatch-cloud", svc: boot.cluster.Services.Controller},
255 runGoProgram{src: "services/keep-balance"},
258 boot.tasksReady = map[string]chan bool{}
259 for _, task := range tasks {
260 boot.tasksReady[task.String()] = make(chan bool)
262 for _, task := range tasks {
264 fail := func(err error) {
265 if boot.ctx.Err() != nil {
269 boot.logger.WithField("task", task.String()).WithError(err).Error("task failed")
272 boot.logger.WithField("task", task.String()).Info("starting")
273 err := task.Run(boot.ctx, fail, boot)
278 close(boot.tasksReady[task.String()])
281 err = boot.wait(boot.ctx, tasks...)
285 boot.logger.Info("all startup tasks are complete; starting health checks")
286 boot.healthChecker = &health.Aggregator{Cluster: boot.cluster}
288 boot.logger.Info("shutting down")
289 return boot.ctx.Err()
292 func (boot *Booter) wait(ctx context.Context, tasks ...bootTask) error {
293 for _, task := range tasks {
294 ch, ok := boot.tasksReady[task.String()]
296 return fmt.Errorf("no such task: %s", task)
298 boot.logger.WithField("task", task.String()).Info("waiting")
308 func (boot *Booter) Stop() {
313 func (boot *Booter) WaitReady() (*arvados.URL, bool) {
314 for waiting := true; waiting; {
315 time.Sleep(time.Second)
316 if boot.ctx.Err() != nil {
319 if boot.healthChecker == nil {
323 resp := boot.healthChecker.ClusterHealth()
324 // The overall health check (resp.Health=="OK") might
325 // never pass due to missing components (like
326 // arvados-dispatch-cloud in a test cluster), so
327 // instead we wait for all configured components to
330 for target, check := range resp.Checks {
331 if check.Health != "OK" {
333 boot.logger.WithField("target", target).Debug("waiting")
337 u := boot.cluster.Services.Controller.ExternalURL
341 func (boot *Booter) prependEnv(key, prepend string) {
342 for i, s := range boot.environ {
343 if strings.HasPrefix(s, key+"=") {
344 boot.environ[i] = key + "=" + prepend + s[len(key)+1:]
348 boot.environ = append(boot.environ, key+"="+prepend)
351 var cleanEnvPrefixes = []string{
357 func (boot *Booter) cleanEnv() {
359 for _, s := range boot.environ {
361 for _, p := range cleanEnvPrefixes {
362 if strings.HasPrefix(s, p) {
368 cleaned = append(cleaned, s)
371 boot.environ = cleaned
374 func (boot *Booter) setEnv(key, val string) {
375 for i, s := range boot.environ {
376 if strings.HasPrefix(s, key+"=") {
377 boot.environ[i] = key + "=" + val
381 boot.environ = append(boot.environ, key+"="+val)
384 func (boot *Booter) installGoProgram(ctx context.Context, srcpath string) error {
386 defer boot.goMutex.Unlock()
387 return boot.RunProgram(ctx, filepath.Join(boot.SourcePath, srcpath), nil, []string{"GOPATH=" + boot.LibPath}, "go", "install")
390 func (boot *Booter) setupRubyEnv() error {
391 cmd := exec.Command("gem", "env", "gempath")
392 cmd.Env = boot.environ
393 buf, err := cmd.Output() // /var/lib/arvados/.gem/ruby/2.5.0/bin:...
394 if err != nil || len(buf) == 0 {
395 return fmt.Errorf("gem env gempath: %v", err)
397 gempath := string(bytes.Split(buf, []byte{':'})[0])
398 boot.prependEnv("PATH", gempath+"/bin:")
399 boot.setEnv("GEM_HOME", gempath)
400 boot.setEnv("GEM_PATH", gempath)
401 // Passenger install doesn't work unless $HOME is ~user
402 u, err := user.Current()
406 boot.setEnv("HOME", u.HomeDir)
410 func (boot *Booter) lookPath(prog string) string {
411 for _, val := range boot.environ {
412 if strings.HasPrefix(val, "PATH=") {
413 for _, dir := range filepath.SplitList(val[5:]) {
414 path := filepath.Join(dir, prog)
415 if fi, err := os.Stat(path); err == nil && fi.Mode()&0111 != 0 {
424 // Run prog with args, using dir as working directory. If ctx is
425 // cancelled while the child is running, RunProgram terminates the
426 // child, waits for it to exit, then returns.
428 // Child's environment will have our env vars, plus any given in env.
430 // Child's stdout will be written to output if non-nil, otherwise the
431 // boot command's stderr.
432 func (boot *Booter) RunProgram(ctx context.Context, dir string, output io.Writer, env []string, prog string, args ...string) error {
433 cmdline := fmt.Sprintf("%s", append([]string{prog}, args...))
434 fmt.Fprintf(boot.Stderr, "%s executing in %s\n", cmdline, dir)
437 if prog == "bundle" && len(args) > 2 && args[0] == "exec" {
440 if !strings.HasPrefix(dir, "/") {
441 logprefix = dir + ": " + logprefix
443 stderr := &logPrefixer{Writer: boot.Stderr, Prefix: []byte("[" + logprefix + "] ")}
445 cmd := exec.Command(boot.lookPath(prog), args...)
452 if strings.HasPrefix(dir, "/") {
455 cmd.Dir = filepath.Join(boot.SourcePath, dir)
457 cmd.Env = append(env, boot.environ...)
460 defer func() { exited = true }()
463 log := ctxlog.FromContext(ctx).WithFields(logrus.Fields{"dir": dir, "cmdline": cmdline})
465 if cmd.Process == nil {
466 log.Debug("waiting for child process to start")
467 time.Sleep(time.Second / 2)
469 log.WithField("PID", cmd.Process.Pid).Debug("sending SIGTERM")
470 cmd.Process.Signal(syscall.SIGTERM)
471 time.Sleep(5 * time.Second)
473 log.WithField("PID", cmd.Process.Pid).Warn("still waiting for child process to exit 5s after SIGTERM")
480 if err != nil && ctx.Err() == nil {
481 // Only report errors that happen before the context ends.
482 return fmt.Errorf("%s: error: %v", cmdline, err)
487 func (boot *Booter) autofillConfig(cfg *arvados.Config, log logrus.FieldLogger) error {
488 cluster, err := cfg.GetCluster("")
492 usedPort := map[string]bool{}
493 nextPort := func() string {
495 port, err := availablePort(":0")
502 usedPort[port] = true
506 if cluster.Services.Controller.ExternalURL.Host == "" {
507 h, p, err := net.SplitHostPort(boot.ControllerAddr)
515 p, err = availablePort(":0")
521 cluster.Services.Controller.ExternalURL = arvados.URL{Scheme: "https", Host: net.JoinHostPort(h, p)}
523 for _, svc := range []*arvados.Service{
524 &cluster.Services.Controller,
525 &cluster.Services.DispatchCloud,
526 &cluster.Services.GitHTTP,
527 &cluster.Services.Health,
528 &cluster.Services.Keepproxy,
529 &cluster.Services.Keepstore,
530 &cluster.Services.RailsAPI,
531 &cluster.Services.WebDAV,
532 &cluster.Services.WebDAVDownload,
533 &cluster.Services.Websocket,
534 &cluster.Services.Workbench1,
536 if svc == &cluster.Services.DispatchCloud && boot.ClusterType == "test" {
539 if svc.ExternalURL.Host == "" && (svc == &cluster.Services.Controller ||
540 svc == &cluster.Services.GitHTTP ||
541 svc == &cluster.Services.Keepproxy ||
542 svc == &cluster.Services.WebDAV ||
543 svc == &cluster.Services.WebDAVDownload ||
544 svc == &cluster.Services.Websocket ||
545 svc == &cluster.Services.Workbench1) {
546 svc.ExternalURL = arvados.URL{Scheme: "https", Host: fmt.Sprintf("%s:%s", boot.ListenHost, nextPort())}
548 if len(svc.InternalURLs) == 0 {
549 svc.InternalURLs = map[arvados.URL]arvados.ServiceInstance{
550 arvados.URL{Scheme: "http", Host: fmt.Sprintf("%s:%s", boot.ListenHost, nextPort())}: arvados.ServiceInstance{},
554 if cluster.SystemRootToken == "" {
555 cluster.SystemRootToken = randomHexString(64)
557 if cluster.ManagementToken == "" {
558 cluster.ManagementToken = randomHexString(64)
560 if cluster.API.RailsSessionSecretToken == "" {
561 cluster.API.RailsSessionSecretToken = randomHexString(64)
563 if cluster.Collections.BlobSigningKey == "" {
564 cluster.Collections.BlobSigningKey = randomHexString(64)
566 if boot.ClusterType != "production" && cluster.Containers.DispatchPrivateKey == "" {
567 buf, err := ioutil.ReadFile(filepath.Join(boot.SourcePath, "lib", "dispatchcloud", "test", "sshkey_dispatch"))
571 cluster.Containers.DispatchPrivateKey = string(buf)
573 if boot.ClusterType != "production" {
574 cluster.TLS.Insecure = true
576 if boot.ClusterType == "test" {
577 // Add a second keepstore process.
578 cluster.Services.Keepstore.InternalURLs[arvados.URL{Scheme: "http", Host: fmt.Sprintf("%s:%s", boot.ListenHost, nextPort())}] = arvados.ServiceInstance{}
580 // Create a directory-backed volume for each keepstore
582 cluster.Volumes = map[string]arvados.Volume{}
583 for url := range cluster.Services.Keepstore.InternalURLs {
584 volnum := len(cluster.Volumes)
585 datadir := fmt.Sprintf("%s/keep%d.data", boot.tempdir, volnum)
586 if _, err = os.Stat(datadir + "/."); err == nil {
587 } else if !os.IsNotExist(err) {
589 } else if err = os.Mkdir(datadir, 0777); err != nil {
592 cluster.Volumes[fmt.Sprintf(cluster.ClusterID+"-nyw5e-%015d", volnum)] = arvados.Volume{
594 DriverParameters: json.RawMessage(fmt.Sprintf(`{"Root":%q}`, datadir)),
595 AccessViaHosts: map[arvados.URL]arvados.VolumeAccess{
601 if boot.OwnTemporaryDatabase {
602 cluster.PostgreSQL.Connection = arvados.PostgreSQLConnection{
603 "client_encoding": "utf8",
606 "dbname": "arvados_test",
608 "password": "insecure_arvados_test",
612 cfg.Clusters[cluster.ClusterID] = *cluster
616 func randomHexString(chars int) string {
617 b := make([]byte, chars/2)
618 _, err := rand.Read(b)
622 return fmt.Sprintf("%x", b)
625 func internalPort(svc arvados.Service) (string, error) {
626 for u := range svc.InternalURLs {
627 if _, p, err := net.SplitHostPort(u.Host); err != nil {
631 } else if u.Scheme == "https" {
637 return "", fmt.Errorf("service has no InternalURLs")
640 func externalPort(svc arvados.Service) (string, error) {
641 if _, p, err := net.SplitHostPort(svc.ExternalURL.Host); err != nil {
645 } else if svc.ExternalURL.Scheme == "https" {
652 func availablePort(addr string) (string, error) {
653 ln, err := net.Listen("tcp", addr)
658 _, port, err := net.SplitHostPort(ln.Addr().String())
665 // Try to connect to addr until it works, then close ch. Give up if
667 func waitForConnect(ctx context.Context, addr string) error {
668 dialer := net.Dialer{Timeout: time.Second}
669 for ctx.Err() == nil {
670 conn, err := dialer.DialContext(ctx, "tcp", addr)
672 time.Sleep(time.Second / 10)