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{
215 boot.healthChecker = &health.Aggregator{Cluster: boot.cluster}
217 for _, dir := range []string{boot.LibPath, filepath.Join(boot.LibPath, "bin")} {
218 if _, err = os.Stat(filepath.Join(dir, ".")); os.IsNotExist(err) {
219 err = os.Mkdir(dir, 0755)
223 } else if err != nil {
227 err = boot.installGoProgram(boot.ctx, "cmd/arvados-server")
231 err = boot.setupRubyEnv()
237 createCertificates{},
240 runServiceCommand{name: "controller", svc: boot.cluster.Services.Controller, depends: []bootTask{runPostgreSQL{}}},
241 runGoProgram{src: "services/arv-git-httpd"},
242 runGoProgram{src: "services/health"},
243 runGoProgram{src: "services/keepproxy", depends: []bootTask{runPassenger{src: "services/api"}}},
244 runGoProgram{src: "services/keepstore", svc: boot.cluster.Services.Keepstore},
245 runGoProgram{src: "services/keep-web"},
246 runGoProgram{src: "services/ws", depends: []bootTask{runPostgreSQL{}}},
247 installPassenger{src: "services/api"},
248 runPassenger{src: "services/api", svc: boot.cluster.Services.RailsAPI, depends: []bootTask{createCertificates{}, runPostgreSQL{}, installPassenger{src: "services/api"}}},
249 installPassenger{src: "apps/workbench", depends: []bootTask{installPassenger{src: "services/api"}}}, // dependency ensures workbench doesn't delay api startup
250 runPassenger{src: "apps/workbench", svc: boot.cluster.Services.Workbench1, depends: []bootTask{installPassenger{src: "apps/workbench"}}},
253 if boot.ClusterType != "test" {
254 tasks = append(tasks,
255 runServiceCommand{name: "dispatch-cloud", svc: boot.cluster.Services.Controller},
256 runGoProgram{src: "services/keep-balance"},
259 boot.tasksReady = map[string]chan bool{}
260 for _, task := range tasks {
261 boot.tasksReady[task.String()] = make(chan bool)
263 for _, task := range tasks {
265 fail := func(err error) {
266 if boot.ctx.Err() != nil {
270 boot.logger.WithField("task", task.String()).WithError(err).Error("task failed")
273 boot.logger.WithField("task", task.String()).Info("starting")
274 err := task.Run(boot.ctx, fail, boot)
279 close(boot.tasksReady[task.String()])
282 err = boot.wait(boot.ctx, tasks...)
287 return boot.ctx.Err()
290 func (boot *Booter) wait(ctx context.Context, tasks ...bootTask) error {
291 for _, task := range tasks {
292 ch, ok := boot.tasksReady[task.String()]
294 return fmt.Errorf("no such task: %s", task)
296 boot.logger.WithField("task", task.String()).Info("waiting")
306 func (boot *Booter) Stop() {
311 func (boot *Booter) WaitReady() (*arvados.URL, bool) {
312 for waiting := true; waiting; {
313 time.Sleep(time.Second)
314 if boot.ctx.Err() != nil {
317 if boot.healthChecker == nil {
321 resp := boot.healthChecker.ClusterHealth()
322 // The overall health check (resp.Health=="OK") might
323 // never pass due to missing components (like
324 // arvados-dispatch-cloud in a test cluster), so
325 // instead we wait for all configured components to
328 for target, check := range resp.Checks {
329 if check.Health != "OK" {
331 boot.logger.WithField("target", target).Debug("waiting")
335 u := boot.cluster.Services.Controller.ExternalURL
339 func (boot *Booter) prependEnv(key, prepend string) {
340 for i, s := range boot.environ {
341 if strings.HasPrefix(s, key+"=") {
342 boot.environ[i] = key + "=" + prepend + s[len(key)+1:]
346 boot.environ = append(boot.environ, key+"="+prepend)
349 var cleanEnvPrefixes = []string{
355 func (boot *Booter) cleanEnv() {
357 for _, s := range boot.environ {
359 for _, p := range cleanEnvPrefixes {
360 if strings.HasPrefix(s, p) {
366 cleaned = append(cleaned, s)
369 boot.environ = cleaned
372 func (boot *Booter) setEnv(key, val string) {
373 for i, s := range boot.environ {
374 if strings.HasPrefix(s, key+"=") {
375 boot.environ[i] = key + "=" + val
379 boot.environ = append(boot.environ, key+"="+val)
382 func (boot *Booter) installGoProgram(ctx context.Context, srcpath string) error {
384 defer boot.goMutex.Unlock()
385 return boot.RunProgram(ctx, filepath.Join(boot.SourcePath, srcpath), nil, []string{"GOPATH=" + boot.LibPath}, "go", "install")
388 func (boot *Booter) setupRubyEnv() error {
389 cmd := exec.Command("gem", "env", "gempath")
390 cmd.Env = boot.environ
391 buf, err := cmd.Output() // /var/lib/arvados/.gem/ruby/2.5.0/bin:...
392 if err != nil || len(buf) == 0 {
393 return fmt.Errorf("gem env gempath: %v", err)
395 gempath := string(bytes.Split(buf, []byte{':'})[0])
396 boot.prependEnv("PATH", gempath+"/bin:")
397 boot.setEnv("GEM_HOME", gempath)
398 boot.setEnv("GEM_PATH", gempath)
399 // Passenger install doesn't work unless $HOME is ~user
400 u, err := user.Current()
404 boot.setEnv("HOME", u.HomeDir)
408 func (boot *Booter) lookPath(prog string) string {
409 for _, val := range boot.environ {
410 if strings.HasPrefix(val, "PATH=") {
411 for _, dir := range filepath.SplitList(val[5:]) {
412 path := filepath.Join(dir, prog)
413 if fi, err := os.Stat(path); err == nil && fi.Mode()&0111 != 0 {
422 // Run prog with args, using dir as working directory. If ctx is
423 // cancelled while the child is running, RunProgram terminates the
424 // child, waits for it to exit, then returns.
426 // Child's environment will have our env vars, plus any given in env.
428 // Child's stdout will be written to output if non-nil, otherwise the
429 // boot command's stderr.
430 func (boot *Booter) RunProgram(ctx context.Context, dir string, output io.Writer, env []string, prog string, args ...string) error {
431 cmdline := fmt.Sprintf("%s", append([]string{prog}, args...))
432 fmt.Fprintf(boot.Stderr, "%s executing in %s\n", cmdline, dir)
435 if prog == "bundle" && len(args) > 2 && args[0] == "exec" {
438 if !strings.HasPrefix(dir, "/") {
439 logprefix = dir + ": " + logprefix
441 stderr := &logPrefixer{Writer: boot.Stderr, Prefix: []byte("[" + logprefix + "] ")}
443 cmd := exec.Command(boot.lookPath(prog), args...)
450 if strings.HasPrefix(dir, "/") {
453 cmd.Dir = filepath.Join(boot.SourcePath, dir)
455 cmd.Env = append(env, boot.environ...)
458 defer func() { exited = true }()
461 log := ctxlog.FromContext(ctx).WithFields(logrus.Fields{"dir": dir, "cmdline": cmdline})
463 if cmd.Process == nil {
464 log.Debug("waiting for child process to start")
465 time.Sleep(time.Second / 2)
467 log.WithField("PID", cmd.Process.Pid).Debug("sending SIGTERM")
468 cmd.Process.Signal(syscall.SIGTERM)
469 time.Sleep(5 * time.Second)
471 log.WithField("PID", cmd.Process.Pid).Warn("still waiting for child process to exit 5s after SIGTERM")
478 if err != nil && ctx.Err() == nil {
479 // Only report errors that happen before the context ends.
480 return fmt.Errorf("%s: error: %v", cmdline, err)
485 func (boot *Booter) autofillConfig(cfg *arvados.Config, log logrus.FieldLogger) error {
486 cluster, err := cfg.GetCluster("")
490 usedPort := map[string]bool{}
491 nextPort := func() string {
493 port, err := availablePort(":0")
500 usedPort[port] = true
504 if cluster.Services.Controller.ExternalURL.Host == "" {
505 h, p, err := net.SplitHostPort(boot.ControllerAddr)
513 p, err = availablePort(":0")
519 cluster.Services.Controller.ExternalURL = arvados.URL{Scheme: "https", Host: net.JoinHostPort(h, p)}
521 for _, svc := range []*arvados.Service{
522 &cluster.Services.Controller,
523 &cluster.Services.DispatchCloud,
524 &cluster.Services.GitHTTP,
525 &cluster.Services.Health,
526 &cluster.Services.Keepproxy,
527 &cluster.Services.Keepstore,
528 &cluster.Services.RailsAPI,
529 &cluster.Services.WebDAV,
530 &cluster.Services.WebDAVDownload,
531 &cluster.Services.Websocket,
532 &cluster.Services.Workbench1,
534 if svc == &cluster.Services.DispatchCloud && boot.ClusterType == "test" {
537 if svc.ExternalURL.Host == "" && (svc == &cluster.Services.Controller ||
538 svc == &cluster.Services.GitHTTP ||
539 svc == &cluster.Services.Keepproxy ||
540 svc == &cluster.Services.WebDAV ||
541 svc == &cluster.Services.WebDAVDownload ||
542 svc == &cluster.Services.Websocket ||
543 svc == &cluster.Services.Workbench1) {
544 svc.ExternalURL = arvados.URL{Scheme: "https", Host: fmt.Sprintf("%s:%s", boot.ListenHost, nextPort())}
546 if len(svc.InternalURLs) == 0 {
547 svc.InternalURLs = map[arvados.URL]arvados.ServiceInstance{
548 arvados.URL{Scheme: "http", Host: fmt.Sprintf("%s:%s", boot.ListenHost, nextPort())}: arvados.ServiceInstance{},
552 if cluster.SystemRootToken == "" {
553 cluster.SystemRootToken = randomHexString(64)
555 if cluster.ManagementToken == "" {
556 cluster.ManagementToken = randomHexString(64)
558 if cluster.API.RailsSessionSecretToken == "" {
559 cluster.API.RailsSessionSecretToken = randomHexString(64)
561 if cluster.Collections.BlobSigningKey == "" {
562 cluster.Collections.BlobSigningKey = randomHexString(64)
564 if boot.ClusterType != "production" && cluster.Containers.DispatchPrivateKey == "" {
565 buf, err := ioutil.ReadFile(filepath.Join(boot.SourcePath, "lib", "dispatchcloud", "test", "sshkey_dispatch"))
569 cluster.Containers.DispatchPrivateKey = string(buf)
571 if boot.ClusterType != "production" {
572 cluster.TLS.Insecure = true
574 if boot.ClusterType == "test" {
575 // Add a second keepstore process.
576 cluster.Services.Keepstore.InternalURLs[arvados.URL{Scheme: "http", Host: fmt.Sprintf("%s:%s", boot.ListenHost, nextPort())}] = arvados.ServiceInstance{}
578 // Create a directory-backed volume for each keepstore
580 cluster.Volumes = map[string]arvados.Volume{}
581 for url := range cluster.Services.Keepstore.InternalURLs {
582 volnum := len(cluster.Volumes)
583 datadir := fmt.Sprintf("%s/keep%d.data", boot.tempdir, volnum)
584 if _, err = os.Stat(datadir + "/."); err == nil {
585 } else if !os.IsNotExist(err) {
587 } else if err = os.Mkdir(datadir, 0777); err != nil {
590 cluster.Volumes[fmt.Sprintf(cluster.ClusterID+"-nyw5e-%015d", volnum)] = arvados.Volume{
592 DriverParameters: json.RawMessage(fmt.Sprintf(`{"Root":%q}`, datadir)),
593 AccessViaHosts: map[arvados.URL]arvados.VolumeAccess{
599 if boot.OwnTemporaryDatabase {
600 cluster.PostgreSQL.Connection = arvados.PostgreSQLConnection{
601 "client_encoding": "utf8",
604 "dbname": "arvados_test",
606 "password": "insecure_arvados_test",
610 cfg.Clusters[cluster.ClusterID] = *cluster
614 func randomHexString(chars int) string {
615 b := make([]byte, chars/2)
616 _, err := rand.Read(b)
620 return fmt.Sprintf("%x", b)
623 func internalPort(svc arvados.Service) (string, error) {
624 for u := range svc.InternalURLs {
625 if _, p, err := net.SplitHostPort(u.Host); err != nil {
629 } else if u.Scheme == "https" {
635 return "", fmt.Errorf("service has no InternalURLs")
638 func externalPort(svc arvados.Service) (string, error) {
639 if _, p, err := net.SplitHostPort(svc.ExternalURL.Host); err != nil {
643 } else if svc.ExternalURL.Scheme == "https" {
650 func availablePort(addr string) (string, error) {
651 ln, err := net.Listen("tcp", addr)
656 _, port, err := net.SplitHostPort(ln.Addr().String())
663 // Try to connect to addr until it works, then close ch. Give up if
665 func waitForConnect(ctx context.Context, addr string) error {
666 dialer := net.Dialer{Timeout: time.Second}
667 for ctx.Err() == nil {
668 conn, err := dialer.DialContext(ctx, "tcp", addr)
670 time.Sleep(time.Second / 10)