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 loader.SkipAPICalls = true
99 cfg, err := loader.Load()
106 if url, ok := boot.WaitReady(); ok {
107 fmt.Fprintln(stdout, url)
108 <-ctx.Done() // wait for signal
116 SourcePath string // e.g., /home/username/src/arvados
117 LibPath string // e.g., /var/lib/arvados
118 ClusterType string // e.g., production
119 ListenHost string // e.g., localhost
120 ControllerAddr string // e.g., 127.0.0.1:8000
121 OwnTemporaryDatabase bool
124 logger logrus.FieldLogger
125 cluster *arvados.Cluster
128 cancel context.CancelFunc
130 healthChecker *health.Aggregator
131 tasksReady map[string]chan bool
135 environ []string // for child processes
137 setupRubyOnce sync.Once
142 func (boot *Booter) Start(ctx context.Context, cfg *arvados.Config) {
143 boot.ctx, boot.cancel = context.WithCancel(ctx)
144 boot.done = make(chan struct{})
148 fmt.Fprintln(boot.Stderr, err)
154 func (boot *Booter) run(cfg *arvados.Config) error {
155 cwd, err := os.Getwd()
159 if !strings.HasPrefix(boot.SourcePath, "/") {
160 boot.SourcePath = filepath.Join(cwd, boot.SourcePath)
162 boot.SourcePath, err = filepath.EvalSymlinks(boot.SourcePath)
167 boot.tempdir, err = ioutil.TempDir("", "arvados-server-boot-")
171 defer os.RemoveAll(boot.tempdir)
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() (*arvados.URL, 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")
332 u := boot.cluster.Services.Controller.ExternalURL
336 func (boot *Booter) prependEnv(key, prepend string) {
337 for i, s := range boot.environ {
338 if strings.HasPrefix(s, key+"=") {
339 boot.environ[i] = key + "=" + prepend + s[len(key)+1:]
343 boot.environ = append(boot.environ, key+"="+prepend)
346 func (boot *Booter) setEnv(key, val string) {
347 for i, s := range boot.environ {
348 if strings.HasPrefix(s, key+"=") {
349 boot.environ[i] = key + "=" + val
353 boot.environ = append(boot.environ, key+"="+val)
356 func (boot *Booter) installGoProgram(ctx context.Context, srcpath string) error {
358 defer boot.goMutex.Unlock()
359 return boot.RunProgram(ctx, filepath.Join(boot.SourcePath, srcpath), nil, []string{"GOPATH=" + boot.LibPath}, "go", "install")
362 func (boot *Booter) setupRubyEnv() error {
363 buf, err := exec.Command("gem", "env", "gempath").Output() // /var/lib/arvados/.gem/ruby/2.5.0/bin:...
364 if err != nil || len(buf) == 0 {
365 return fmt.Errorf("gem env gempath: %v", err)
367 gempath := string(bytes.Split(buf, []byte{':'})[0])
368 boot.prependEnv("PATH", gempath+"/bin:")
369 boot.setEnv("GEM_HOME", gempath)
370 boot.setEnv("GEM_PATH", gempath)
374 func (boot *Booter) lookPath(prog string) string {
375 for _, val := range boot.environ {
376 if strings.HasPrefix(val, "PATH=") {
377 for _, dir := range filepath.SplitList(val[5:]) {
378 path := filepath.Join(dir, prog)
379 if fi, err := os.Stat(path); err == nil && fi.Mode()&0111 != 0 {
388 // Run prog with args, using dir as working directory. If ctx is
389 // cancelled while the child is running, RunProgram terminates the
390 // child, waits for it to exit, then returns.
392 // Child's environment will have our env vars, plus any given in env.
394 // Child's stdout will be written to output if non-nil, otherwise the
395 // boot command's stderr.
396 func (boot *Booter) RunProgram(ctx context.Context, dir string, output io.Writer, env []string, prog string, args ...string) error {
397 cmdline := fmt.Sprintf("%s", append([]string{prog}, args...))
398 fmt.Fprintf(boot.Stderr, "%s executing in %s\n", cmdline, dir)
401 if prog == "bundle" && len(args) > 2 && args[0] == "exec" {
404 if !strings.HasPrefix(dir, "/") {
405 logprefix = dir + ": " + logprefix
407 stderr := &logPrefixer{Writer: boot.Stderr, Prefix: []byte("[" + logprefix + "] ")}
409 cmd := exec.Command(boot.lookPath(prog), args...)
416 if strings.HasPrefix(dir, "/") {
419 cmd.Dir = filepath.Join(boot.SourcePath, dir)
421 cmd.Env = append(env, boot.environ...)
424 defer func() { exited = true }()
427 log := ctxlog.FromContext(ctx).WithFields(logrus.Fields{"dir": dir, "cmdline": cmdline})
429 if cmd.Process == nil {
430 log.Debug("waiting for child process to start")
431 time.Sleep(time.Second / 2)
433 log.WithField("PID", cmd.Process.Pid).Debug("sending SIGTERM")
434 cmd.Process.Signal(syscall.SIGTERM)
435 time.Sleep(5 * time.Second)
437 log.WithField("PID", cmd.Process.Pid).Warn("still waiting for child process to exit 5s after SIGTERM")
444 if err != nil && ctx.Err() == nil {
445 // Only report errors that happen before the context ends.
446 return fmt.Errorf("%s: error: %v", cmdline, err)
451 func (boot *Booter) autofillConfig(cfg *arvados.Config, log logrus.FieldLogger) error {
452 cluster, err := cfg.GetCluster("")
456 usedPort := map[string]bool{}
457 nextPort := func() string {
459 port, err := availablePort(":0")
466 usedPort[port] = true
470 if cluster.Services.Controller.ExternalURL.Host == "" {
471 h, p, err := net.SplitHostPort(boot.ControllerAddr)
479 p, err = availablePort(":0")
485 cluster.Services.Controller.ExternalURL = arvados.URL{Scheme: "https", Host: net.JoinHostPort(h, p)}
487 for _, svc := range []*arvados.Service{
488 &cluster.Services.Controller,
489 &cluster.Services.DispatchCloud,
490 &cluster.Services.GitHTTP,
491 &cluster.Services.Health,
492 &cluster.Services.Keepproxy,
493 &cluster.Services.Keepstore,
494 &cluster.Services.RailsAPI,
495 &cluster.Services.WebDAV,
496 &cluster.Services.WebDAVDownload,
497 &cluster.Services.Websocket,
498 &cluster.Services.Workbench1,
500 if svc == &cluster.Services.DispatchCloud && boot.ClusterType == "test" {
503 if svc.ExternalURL.Host == "" && (svc == &cluster.Services.Controller ||
504 svc == &cluster.Services.GitHTTP ||
505 svc == &cluster.Services.Keepproxy ||
506 svc == &cluster.Services.WebDAV ||
507 svc == &cluster.Services.WebDAVDownload ||
508 svc == &cluster.Services.Websocket ||
509 svc == &cluster.Services.Workbench1) {
510 svc.ExternalURL = arvados.URL{Scheme: "https", Host: fmt.Sprintf("%s:%s", boot.ListenHost, nextPort())}
512 if len(svc.InternalURLs) == 0 {
513 svc.InternalURLs = map[arvados.URL]arvados.ServiceInstance{
514 arvados.URL{Scheme: "http", Host: fmt.Sprintf("%s:%s", boot.ListenHost, nextPort())}: arvados.ServiceInstance{},
518 if cluster.SystemRootToken == "" {
519 cluster.SystemRootToken = randomHexString(64)
521 if cluster.ManagementToken == "" {
522 cluster.ManagementToken = randomHexString(64)
524 if cluster.API.RailsSessionSecretToken == "" {
525 cluster.API.RailsSessionSecretToken = randomHexString(64)
527 if cluster.Collections.BlobSigningKey == "" {
528 cluster.Collections.BlobSigningKey = randomHexString(64)
530 if boot.ClusterType != "production" && cluster.Containers.DispatchPrivateKey == "" {
531 buf, err := ioutil.ReadFile(filepath.Join(boot.SourcePath, "lib", "dispatchcloud", "test", "sshkey_dispatch"))
535 cluster.Containers.DispatchPrivateKey = string(buf)
537 if boot.ClusterType != "production" {
538 cluster.TLS.Insecure = true
540 if boot.ClusterType == "test" {
541 // Add a second keepstore process.
542 cluster.Services.Keepstore.InternalURLs[arvados.URL{Scheme: "http", Host: fmt.Sprintf("%s:%s", boot.ListenHost, nextPort())}] = arvados.ServiceInstance{}
544 // Create a directory-backed volume for each keepstore
546 cluster.Volumes = map[string]arvados.Volume{}
547 for url := range cluster.Services.Keepstore.InternalURLs {
548 volnum := len(cluster.Volumes)
549 datadir := fmt.Sprintf("%s/keep%d.data", boot.tempdir, volnum)
550 if _, err = os.Stat(datadir + "/."); err == nil {
551 } else if !os.IsNotExist(err) {
553 } else if err = os.Mkdir(datadir, 0777); err != nil {
556 cluster.Volumes[fmt.Sprintf(cluster.ClusterID+"-nyw5e-%015d", volnum)] = arvados.Volume{
558 DriverParameters: json.RawMessage(fmt.Sprintf(`{"Root":%q}`, datadir)),
559 AccessViaHosts: map[arvados.URL]arvados.VolumeAccess{
565 if boot.OwnTemporaryDatabase {
566 cluster.PostgreSQL.Connection = arvados.PostgreSQLConnection{
567 "client_encoding": "utf8",
570 "dbname": "arvados_test",
572 "password": "insecure_arvados_test",
576 cfg.Clusters[cluster.ClusterID] = *cluster
580 func randomHexString(chars int) string {
581 b := make([]byte, chars/2)
582 _, err := rand.Read(b)
586 return fmt.Sprintf("%x", b)
589 func internalPort(svc arvados.Service) (string, error) {
590 for u := range svc.InternalURLs {
591 if _, p, err := net.SplitHostPort(u.Host); err != nil {
595 } else if u.Scheme == "https" {
601 return "", fmt.Errorf("service has no InternalURLs")
604 func externalPort(svc arvados.Service) (string, error) {
605 if _, p, err := net.SplitHostPort(svc.ExternalURL.Host); err != nil {
609 } else if svc.ExternalURL.Scheme == "https" {
616 func availablePort(addr string) (string, error) {
617 ln, err := net.Listen("tcp", addr)
622 _, port, err := net.SplitHostPort(ln.Addr().String())
629 // Try to connect to addr until it works, then close ch. Give up if
631 func waitForConnect(ctx context.Context, addr string) error {
632 dialer := net.Dialer{Timeout: time.Second}
633 for ctx.Err() == nil {
634 conn, err := dialer.DialContext(ctx, "tcp", addr)
636 time.Sleep(time.Second / 10)