1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
26 "git.arvados.org/arvados.git/lib/cmd"
27 "git.arvados.org/arvados.git/lib/config"
28 "git.arvados.org/arvados.git/sdk/go/arvados"
29 "git.arvados.org/arvados.git/sdk/go/ctxlog"
30 "git.arvados.org/arvados.git/sdk/go/health"
31 "github.com/sirupsen/logrus"
34 var Command cmd.Handler = bootCommand{}
36 type bootTask interface {
37 // Execute the task. Run should return nil when the task is
38 // done enough to satisfy a dependency relationship (e.g., the
39 // service is running and ready). If the task starts a
40 // goroutine that fails after Run returns (e.g., the service
41 // shuts down), it should call cancel.
42 Run(ctx context.Context, fail func(error), boot *Booter) error
46 type bootCommand struct{}
48 func (bootCommand) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
51 logger: ctxlog.New(stderr, "json", "info"),
54 ctx := ctxlog.Context(context.Background(), boot.logger)
55 ctx, cancel := context.WithCancel(ctx)
58 ch := make(chan os.Signal)
59 signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
62 boot.logger.WithField("signal", sig).Info("caught signal")
70 boot.logger.WithError(err).Info("exiting")
74 flags := flag.NewFlagSet(prog, flag.ContinueOnError)
75 flags.SetOutput(stderr)
76 loader := config.NewLoader(stdin, boot.logger)
77 loader.SetupFlags(flags)
78 versionFlag := flags.Bool("version", false, "Write version information to stdout and exit 0")
79 flags.StringVar(&boot.SourcePath, "source", ".", "arvados source tree `directory`")
80 flags.StringVar(&boot.LibPath, "lib", "/var/lib/arvados", "`directory` to install dependencies and library files")
81 flags.StringVar(&boot.ClusterType, "type", "production", "cluster `type`: development, test, or production")
82 flags.StringVar(&boot.ListenHost, "listen-host", "localhost", "host name or interface address for service listeners")
83 flags.StringVar(&boot.ControllerAddr, "controller-address", ":0", "desired controller address, `host:port` or `:port`")
84 flags.BoolVar(&boot.OwnTemporaryDatabase, "own-temporary-database", false, "bring up a postgres server and create a temporary database")
85 err = flags.Parse(args)
86 if err == flag.ErrHelp {
89 } else if err != nil {
91 } else if *versionFlag {
92 return cmd.Version.RunCommand(prog, args, stdin, stdout, stderr)
93 } else if boot.ClusterType != "development" && boot.ClusterType != "test" && boot.ClusterType != "production" {
94 err = fmt.Errorf("cluster type must be 'development', 'test', or 'production'")
98 boot.Start(ctx, loader)
100 if boot.WaitReady() {
101 fmt.Fprintln(stdout, boot.cluster.Services.Controller.ExternalURL)
102 <-ctx.Done() // wait for signal
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
129 environ []string // for child processes
131 setupRubyOnce sync.Once
136 func (boot *Booter) Start(ctx context.Context, loader *config.Loader) {
137 boot.ctx, boot.cancel = context.WithCancel(ctx)
138 boot.done = make(chan struct{})
140 err := boot.run(loader)
142 fmt.Fprintln(boot.Stderr, err)
148 func (boot *Booter) run(loader *config.Loader) error {
149 cwd, err := os.Getwd()
153 if !strings.HasPrefix(boot.SourcePath, "/") {
154 boot.SourcePath = filepath.Join(cwd, boot.SourcePath)
156 boot.SourcePath, err = filepath.EvalSymlinks(boot.SourcePath)
161 boot.tempdir, err = ioutil.TempDir("", "arvados-server-boot-")
165 defer os.RemoveAll(boot.tempdir)
167 loader.SkipAPICalls = true
168 cfg, err := loader.Load()
173 // Fill in any missing config keys, and write the resulting
174 // config in the temp dir for child services to use.
175 err = boot.autofillConfig(cfg, boot.logger)
179 conffile, err := os.OpenFile(filepath.Join(boot.tempdir, "config.yml"), os.O_CREATE|os.O_WRONLY, 0777)
183 defer conffile.Close()
184 err = json.NewEncoder(conffile).Encode(cfg)
188 err = conffile.Close()
192 boot.configfile = conffile.Name()
194 boot.environ = os.Environ()
195 boot.setEnv("ARVADOS_CONFIG", boot.configfile)
196 boot.setEnv("RAILS_ENV", boot.ClusterType)
197 boot.prependEnv("PATH", filepath.Join(boot.LibPath, "bin")+":")
199 boot.cluster, err = cfg.GetCluster("")
203 // Now that we have the config, replace the bootstrap logger
204 // with a new one according to the logging config.
205 loglevel := boot.cluster.SystemLogs.LogLevel
206 if s := os.Getenv("ARVADOS_DEBUG"); s != "" && s != "0" {
209 boot.logger = ctxlog.New(boot.Stderr, boot.cluster.SystemLogs.Format, loglevel).WithFields(logrus.Fields{
212 boot.healthChecker = &health.Aggregator{Cluster: boot.cluster}
214 for _, dir := range []string{boot.LibPath, filepath.Join(boot.LibPath, "bin")} {
215 if _, err = os.Stat(filepath.Join(dir, ".")); os.IsNotExist(err) {
216 err = os.Mkdir(dir, 0755)
220 } else if err != nil {
224 err = boot.installGoProgram(boot.ctx, "cmd/arvados-server")
228 err = boot.setupRubyEnv()
234 createCertificates{},
237 runServiceCommand{name: "controller", svc: boot.cluster.Services.Controller, depends: []bootTask{runPostgreSQL{}}},
238 runGoProgram{src: "services/arv-git-httpd"},
239 runGoProgram{src: "services/health"},
240 runGoProgram{src: "services/keepproxy", depends: []bootTask{runPassenger{src: "services/api"}}},
241 runGoProgram{src: "services/keepstore", svc: boot.cluster.Services.Keepstore},
242 runGoProgram{src: "services/keep-web"},
243 runGoProgram{src: "services/ws", depends: []bootTask{runPostgreSQL{}}},
244 installPassenger{src: "services/api"},
245 runPassenger{src: "services/api", svc: boot.cluster.Services.RailsAPI, depends: []bootTask{createCertificates{}, runPostgreSQL{}, installPassenger{src: "services/api"}}},
246 installPassenger{src: "apps/workbench", depends: []bootTask{installPassenger{src: "services/api"}}}, // dependency ensures workbench doesn't delay api startup
247 runPassenger{src: "apps/workbench", svc: boot.cluster.Services.Workbench1, depends: []bootTask{installPassenger{src: "apps/workbench"}}},
250 if boot.ClusterType != "test" {
251 tasks = append(tasks,
252 runServiceCommand{name: "dispatch-cloud", svc: boot.cluster.Services.Controller},
253 runGoProgram{src: "services/keep-balance"},
256 boot.tasksReady = map[string]chan bool{}
257 for _, task := range tasks {
258 boot.tasksReady[task.String()] = make(chan bool)
260 for _, task := range tasks {
262 fail := func(err error) {
263 if boot.ctx.Err() != nil {
267 boot.logger.WithField("task", task.String()).WithError(err).Error("task failed")
270 boot.logger.WithField("task", task.String()).Info("starting")
271 err := task.Run(boot.ctx, fail, boot)
276 close(boot.tasksReady[task.String()])
279 err = boot.wait(boot.ctx, tasks...)
284 return boot.ctx.Err()
287 func (boot *Booter) wait(ctx context.Context, tasks ...bootTask) error {
288 for _, task := range tasks {
289 ch, ok := boot.tasksReady[task.String()]
291 return fmt.Errorf("no such task: %s", task)
293 boot.logger.WithField("task", task.String()).Info("waiting")
303 func (boot *Booter) Stop() {
308 func (boot *Booter) WaitReady() bool {
309 for waiting := true; waiting; {
310 time.Sleep(time.Second)
311 if boot.ctx.Err() != nil {
314 if boot.healthChecker == nil {
318 resp := boot.healthChecker.ClusterHealth()
319 // The overall health check (resp.Health=="OK") might
320 // never pass due to missing components (like
321 // arvados-dispatch-cloud in a test cluster), so
322 // instead we wait for all configured components to
325 for target, check := range resp.Checks {
326 if check.Health != "OK" {
328 boot.logger.WithField("target", target).Debug("waiting")
335 func (boot *Booter) prependEnv(key, prepend string) {
336 for i, s := range boot.environ {
337 if strings.HasPrefix(s, key+"=") {
338 boot.environ[i] = key + "=" + prepend + s[len(key)+1:]
342 boot.environ = append(boot.environ, key+"="+prepend)
345 func (boot *Booter) setEnv(key, val string) {
346 for i, s := range boot.environ {
347 if strings.HasPrefix(s, key+"=") {
348 boot.environ[i] = key + "=" + val
352 boot.environ = append(boot.environ, key+"="+val)
355 func (boot *Booter) installGoProgram(ctx context.Context, srcpath string) error {
357 defer boot.goMutex.Unlock()
358 return boot.RunProgram(ctx, filepath.Join(boot.SourcePath, srcpath), nil, []string{"GOPATH=" + boot.LibPath}, "go", "install")
361 func (boot *Booter) setupRubyEnv() error {
362 buf, err := exec.Command("gem", "env", "gempath").Output() // /var/lib/arvados/.gem/ruby/2.5.0/bin:...
363 if err != nil || len(buf) == 0 {
364 return fmt.Errorf("gem env gempath: %v", err)
366 gempath := string(bytes.Split(buf, []byte{':'})[0])
367 boot.prependEnv("PATH", gempath+"/bin:")
368 boot.setEnv("GEM_HOME", gempath)
369 boot.setEnv("GEM_PATH", gempath)
373 func (boot *Booter) lookPath(prog string) string {
374 for _, val := range boot.environ {
375 if strings.HasPrefix(val, "PATH=") {
376 for _, dir := range filepath.SplitList(val[5:]) {
377 path := filepath.Join(dir, prog)
378 if fi, err := os.Stat(path); err == nil && fi.Mode()&0111 != 0 {
387 // Run prog with args, using dir as working directory. If ctx is
388 // cancelled while the child is running, RunProgram terminates the
389 // child, waits for it to exit, then returns.
391 // Child's environment will have our env vars, plus any given in env.
393 // Child's stdout will be written to output if non-nil, otherwise the
394 // boot command's stderr.
395 func (boot *Booter) RunProgram(ctx context.Context, dir string, output io.Writer, env []string, prog string, args ...string) error {
396 cmdline := fmt.Sprintf("%s", append([]string{prog}, args...))
397 fmt.Fprintf(boot.Stderr, "%s executing in %s\n", cmdline, dir)
400 if prog == "bundle" && len(args) > 2 && args[0] == "exec" {
403 if !strings.HasPrefix(dir, "/") {
404 logprefix = dir + ": " + logprefix
406 stderr := &logPrefixer{Writer: boot.Stderr, Prefix: []byte("[" + logprefix + "] ")}
408 cmd := exec.Command(boot.lookPath(prog), args...)
415 if strings.HasPrefix(dir, "/") {
418 cmd.Dir = filepath.Join(boot.SourcePath, dir)
420 cmd.Env = append(env, boot.environ...)
423 defer func() { exited = true }()
426 log := ctxlog.FromContext(ctx).WithFields(logrus.Fields{"dir": dir, "cmdline": cmdline})
428 if cmd.Process == nil {
429 log.Debug("waiting for child process to start")
430 time.Sleep(time.Second / 2)
432 log.WithField("PID", cmd.Process.Pid).Debug("sending SIGTERM")
433 cmd.Process.Signal(syscall.SIGTERM)
434 time.Sleep(5 * time.Second)
436 log.WithField("PID", cmd.Process.Pid).Warn("still waiting for child process to exit 5s after SIGTERM")
443 if err != nil && ctx.Err() == nil {
444 // Only report errors that happen before the context ends.
445 return fmt.Errorf("%s: error: %v", cmdline, err)
450 func (boot *Booter) autofillConfig(cfg *arvados.Config, log logrus.FieldLogger) error {
451 cluster, err := cfg.GetCluster("")
455 usedPort := map[string]bool{}
456 nextPort := func() string {
458 port, err := availablePort(":0")
465 usedPort[port] = true
469 if cluster.Services.Controller.ExternalURL.Host == "" {
470 h, p, err := net.SplitHostPort(boot.ControllerAddr)
478 p, err = availablePort(":0")
484 cluster.Services.Controller.ExternalURL = arvados.URL{Scheme: "https", Host: net.JoinHostPort(h, p)}
486 for _, svc := range []*arvados.Service{
487 &cluster.Services.Controller,
488 &cluster.Services.DispatchCloud,
489 &cluster.Services.GitHTTP,
490 &cluster.Services.Health,
491 &cluster.Services.Keepproxy,
492 &cluster.Services.Keepstore,
493 &cluster.Services.RailsAPI,
494 &cluster.Services.WebDAV,
495 &cluster.Services.WebDAVDownload,
496 &cluster.Services.Websocket,
497 &cluster.Services.Workbench1,
499 if svc == &cluster.Services.DispatchCloud && boot.ClusterType == "test" {
502 if svc.ExternalURL.Host == "" && (svc == &cluster.Services.Controller ||
503 svc == &cluster.Services.GitHTTP ||
504 svc == &cluster.Services.Keepproxy ||
505 svc == &cluster.Services.WebDAV ||
506 svc == &cluster.Services.WebDAVDownload ||
507 svc == &cluster.Services.Websocket ||
508 svc == &cluster.Services.Workbench1) {
509 svc.ExternalURL = arvados.URL{Scheme: "https", Host: fmt.Sprintf("%s:%s", boot.ListenHost, nextPort())}
511 if len(svc.InternalURLs) == 0 {
512 svc.InternalURLs = map[arvados.URL]arvados.ServiceInstance{
513 arvados.URL{Scheme: "http", Host: fmt.Sprintf("%s:%s", boot.ListenHost, nextPort())}: arvados.ServiceInstance{},
517 if cluster.SystemRootToken == "" {
518 cluster.SystemRootToken = randomHexString(64)
520 if cluster.ManagementToken == "" {
521 cluster.ManagementToken = randomHexString(64)
523 if cluster.API.RailsSessionSecretToken == "" {
524 cluster.API.RailsSessionSecretToken = randomHexString(64)
526 if cluster.Collections.BlobSigningKey == "" {
527 cluster.Collections.BlobSigningKey = randomHexString(64)
529 if boot.ClusterType != "production" && cluster.Containers.DispatchPrivateKey == "" {
530 buf, err := ioutil.ReadFile(filepath.Join(boot.SourcePath, "lib", "dispatchcloud", "test", "sshkey_dispatch"))
534 cluster.Containers.DispatchPrivateKey = string(buf)
536 if boot.ClusterType != "production" {
537 cluster.TLS.Insecure = true
539 if boot.ClusterType == "test" {
540 // Add a second keepstore process.
541 cluster.Services.Keepstore.InternalURLs[arvados.URL{Scheme: "http", Host: fmt.Sprintf("%s:%s", boot.ListenHost, nextPort())}] = arvados.ServiceInstance{}
543 // Create a directory-backed volume for each keepstore
545 cluster.Volumes = map[string]arvados.Volume{}
546 for url := range cluster.Services.Keepstore.InternalURLs {
547 volnum := len(cluster.Volumes)
548 datadir := fmt.Sprintf("%s/keep%d.data", boot.tempdir, volnum)
549 if _, err = os.Stat(datadir + "/."); err == nil {
550 } else if !os.IsNotExist(err) {
552 } else if err = os.Mkdir(datadir, 0777); err != nil {
555 cluster.Volumes[fmt.Sprintf(cluster.ClusterID+"-nyw5e-%015d", volnum)] = arvados.Volume{
557 DriverParameters: json.RawMessage(fmt.Sprintf(`{"Root":%q}`, datadir)),
558 AccessViaHosts: map[arvados.URL]arvados.VolumeAccess{
564 if boot.OwnTemporaryDatabase {
565 cluster.PostgreSQL.Connection = arvados.PostgreSQLConnection{
566 "client_encoding": "utf8",
569 "dbname": "arvados_test",
571 "password": "insecure_arvados_test",
575 cfg.Clusters[cluster.ClusterID] = *cluster
579 func randomHexString(chars int) string {
580 b := make([]byte, chars/2)
581 _, err := rand.Read(b)
585 return fmt.Sprintf("%x", b)
588 func internalPort(svc arvados.Service) (string, error) {
589 for u := range svc.InternalURLs {
590 if _, p, err := net.SplitHostPort(u.Host); err != nil {
594 } else if u.Scheme == "https" {
600 return "", fmt.Errorf("service has no InternalURLs")
603 func externalPort(svc arvados.Service) (string, error) {
604 if _, p, err := net.SplitHostPort(svc.ExternalURL.Host); err != nil {
608 } else if svc.ExternalURL.Scheme == "https" {
615 func availablePort(addr string) (string, error) {
616 ln, err := net.Listen("tcp", addr)
621 _, port, err := net.SplitHostPort(ln.Addr().String())
628 // Try to connect to addr until it works, then close ch. Give up if
630 func waitForConnect(ctx context.Context, addr string) error {
631 dialer := net.Dialer{Timeout: time.Second}
632 for ctx.Err() == nil {
633 conn, err := dialer.DialContext(ctx, "tcp", addr)
635 time.Sleep(time.Second / 10)