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/lib/controller"
29 "git.arvados.org/arvados.git/lib/dispatchcloud"
30 "git.arvados.org/arvados.git/sdk/go/arvados"
31 "git.arvados.org/arvados.git/sdk/go/ctxlog"
32 "git.arvados.org/arvados.git/sdk/go/health"
33 "github.com/sirupsen/logrus"
36 var Command cmd.Handler = bootCommand{}
38 type bootTask interface {
39 // Execute the task. Run should return nil when the task is
40 // done enough to satisfy a dependency relationship (e.g., the
41 // service is running and ready). If the task starts a
42 // goroutine that fails after Run returns (e.g., the service
43 // shuts down), it should call cancel.
44 Run(ctx context.Context, fail func(error), boot *Booter) error
48 type bootCommand struct{}
50 func (bootCommand) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
53 logger: ctxlog.New(stderr, "json", "info"),
56 ctx := ctxlog.Context(context.Background(), boot.logger)
57 ctx, cancel := context.WithCancel(ctx)
60 ch := make(chan os.Signal)
61 signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
64 boot.logger.WithField("signal", sig).Info("caught signal")
72 boot.logger.WithError(err).Info("exiting")
76 flags := flag.NewFlagSet(prog, flag.ContinueOnError)
77 flags.SetOutput(stderr)
78 loader := config.NewLoader(stdin, boot.logger)
79 loader.SetupFlags(flags)
80 versionFlag := flags.Bool("version", false, "Write version information to stdout and exit 0")
81 flags.StringVar(&boot.SourcePath, "source", ".", "arvados source tree `directory`")
82 flags.StringVar(&boot.LibPath, "lib", "/var/lib/arvados", "`directory` to install dependencies and library files")
83 flags.StringVar(&boot.ClusterType, "type", "production", "cluster `type`: development, test, or production")
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 boot.Start(ctx, loader)
101 if boot.WaitReady() {
102 fmt.Fprintln(stdout, boot.cluster.Services.Controller.ExternalURL)
103 <-ctx.Done() // wait for signal
111 SourcePath string // e.g., /home/username/src/arvados
112 LibPath string // e.g., /var/lib/arvados
113 ClusterType string // e.g., production
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 boot.logger = ctxlog.New(boot.Stderr, boot.cluster.SystemLogs.Format, boot.cluster.SystemLogs.LogLevel).WithFields(logrus.Fields{
208 boot.healthChecker = &health.Aggregator{Cluster: boot.cluster}
210 for _, dir := range []string{boot.LibPath, filepath.Join(boot.LibPath, "bin")} {
211 if _, err = os.Stat(filepath.Join(dir, ".")); os.IsNotExist(err) {
212 err = os.Mkdir(dir, 0755)
216 } else if err != nil {
220 err = boot.installGoProgram(boot.ctx, "cmd/arvados-server")
224 err = boot.setupRubyEnv()
230 createCertificates{},
233 runServiceCommand{name: "controller", command: controller.Command, depends: []bootTask{runPostgreSQL{}}},
234 runGoProgram{src: "services/arv-git-httpd"},
235 runGoProgram{src: "services/health"},
236 runGoProgram{src: "services/keepproxy"},
237 runGoProgram{src: "services/keepstore", svc: boot.cluster.Services.Keepstore},
238 runGoProgram{src: "services/keep-web"},
239 runGoProgram{src: "services/ws", depends: []bootTask{runPostgreSQL{}}},
240 installPassenger{src: "services/api"},
241 runPassenger{src: "services/api", svc: boot.cluster.Services.RailsAPI, depends: []bootTask{createCertificates{}, runPostgreSQL{}, installPassenger{src: "services/api"}}},
242 installPassenger{src: "apps/workbench"},
243 runPassenger{src: "apps/workbench", svc: boot.cluster.Services.Workbench1, depends: []bootTask{installPassenger{src: "apps/workbench"}}},
246 if boot.ClusterType != "test" {
247 tasks = append(tasks,
248 runServiceCommand{name: "dispatchcloud", command: dispatchcloud.Command},
249 runGoProgram{src: "services/keep-balance"},
252 boot.tasksReady = map[string]chan bool{}
253 for _, task := range tasks {
254 boot.tasksReady[task.String()] = make(chan bool)
256 for _, task := range tasks {
258 fail := func(err error) {
259 if boot.ctx.Err() != nil {
263 boot.logger.WithField("task", task).WithError(err).Error("task failed")
266 boot.logger.WithField("task", task).Info("starting")
267 err := task.Run(boot.ctx, fail, boot)
272 close(boot.tasksReady[task.String()])
275 return boot.wait(boot.ctx, tasks...)
278 func (boot *Booter) wait(ctx context.Context, tasks ...bootTask) error {
279 for _, task := range tasks {
280 ch, ok := boot.tasksReady[task.String()]
282 return fmt.Errorf("no such task: %s", task)
284 boot.logger.WithField("task", task).Info("waiting")
294 func (boot *Booter) Stop() {
299 func (boot *Booter) WaitReady() bool {
300 for waiting := true; waiting; {
301 time.Sleep(time.Second)
302 if boot.ctx.Err() != nil {
305 if boot.healthChecker == nil {
309 resp := boot.healthChecker.ClusterHealth()
310 // The overall health check (resp.Health=="OK") might
311 // never pass due to missing components (like
312 // arvados-dispatch-cloud in a test cluster), so
313 // instead we wait for all configured components to
316 for _, check := range resp.Checks {
317 if check.Health != "OK" {
325 func (boot *Booter) prependEnv(key, prepend string) {
326 for i, s := range boot.environ {
327 if strings.HasPrefix(s, key+"=") {
328 boot.environ[i] = key + "=" + prepend + s[len(key)+1:]
332 boot.environ = append(boot.environ, key+"="+prepend)
335 func (boot *Booter) setEnv(key, val string) {
336 for i, s := range boot.environ {
337 if strings.HasPrefix(s, key+"=") {
338 boot.environ[i] = key + "=" + val
342 boot.environ = append(boot.environ, key+"="+val)
345 func (boot *Booter) installGoProgram(ctx context.Context, srcpath string) error {
347 defer boot.goMutex.Unlock()
348 return boot.RunProgram(ctx, filepath.Join(boot.SourcePath, srcpath), nil, []string{"GOPATH=" + boot.LibPath}, "go", "install")
351 func (boot *Booter) setupRubyEnv() error {
352 buf, err := exec.Command("gem", "env", "gempath").Output() // /var/lib/arvados/.gem/ruby/2.5.0/bin:...
353 if err != nil || len(buf) == 0 {
354 return fmt.Errorf("gem env gempath: %v", err)
356 gempath := string(bytes.Split(buf, []byte{':'})[0])
357 boot.prependEnv("PATH", gempath+"/bin:")
358 boot.setEnv("GEM_HOME", gempath)
359 boot.setEnv("GEM_PATH", gempath)
363 func (boot *Booter) lookPath(prog string) string {
364 for _, val := range boot.environ {
365 if strings.HasPrefix(val, "PATH=") {
366 for _, dir := range filepath.SplitList(val[5:]) {
367 path := filepath.Join(dir, prog)
368 if fi, err := os.Stat(path); err == nil && fi.Mode()&0111 != 0 {
377 // Run prog with args, using dir as working directory. If ctx is
378 // cancelled while the child is running, RunProgram terminates the
379 // child, waits for it to exit, then returns.
381 // Child's environment will have our env vars, plus any given in env.
383 // Child's stdout will be written to output if non-nil, otherwise the
384 // boot command's stderr.
385 func (boot *Booter) RunProgram(ctx context.Context, dir string, output io.Writer, env []string, prog string, args ...string) error {
386 cmdline := fmt.Sprintf("%s", append([]string{prog}, args...))
387 fmt.Fprintf(boot.Stderr, "%s executing in %s\n", cmdline, dir)
388 cmd := exec.Command(boot.lookPath(prog), args...)
390 cmd.Stdout = boot.Stderr
394 cmd.Stderr = boot.Stderr
395 if strings.HasPrefix(dir, "/") {
398 cmd.Dir = filepath.Join(boot.SourcePath, dir)
400 cmd.Env = append(env, boot.environ...)
403 defer func() { exited = true }()
406 log := ctxlog.FromContext(ctx).WithFields(logrus.Fields{"dir": dir, "cmdline": cmdline})
408 if cmd.Process == nil {
409 log.Debug("waiting for child process to start")
410 time.Sleep(time.Second / 2)
412 log.WithField("PID", cmd.Process.Pid).Debug("sending SIGTERM")
413 cmd.Process.Signal(syscall.SIGTERM)
414 time.Sleep(5 * time.Second)
416 log.WithField("PID", cmd.Process.Pid).Warn("still waiting for child process to exit 5s after SIGTERM")
423 if err != nil && ctx.Err() == nil {
424 // Only report errors that happen before the context ends.
425 return fmt.Errorf("%s: error: %v", cmdline, err)
430 func (boot *Booter) autofillConfig(cfg *arvados.Config, log logrus.FieldLogger) error {
431 cluster, err := cfg.GetCluster("")
435 usedPort := map[string]bool{}
436 nextPort := func() string {
438 port, err := availablePort(":0")
445 usedPort[port] = true
449 if cluster.Services.Controller.ExternalURL.Host == "" {
450 h, p, err := net.SplitHostPort(boot.ControllerAddr)
458 p, err = availablePort(":0")
464 cluster.Services.Controller.ExternalURL = arvados.URL{Scheme: "https", Host: net.JoinHostPort(h, p)}
466 for _, svc := range []*arvados.Service{
467 &cluster.Services.Controller,
468 &cluster.Services.DispatchCloud,
469 &cluster.Services.GitHTTP,
470 &cluster.Services.Health,
471 &cluster.Services.Keepproxy,
472 &cluster.Services.Keepstore,
473 &cluster.Services.RailsAPI,
474 &cluster.Services.WebDAV,
475 &cluster.Services.WebDAVDownload,
476 &cluster.Services.Websocket,
477 &cluster.Services.Workbench1,
479 if svc == &cluster.Services.DispatchCloud && boot.ClusterType == "test" {
482 if svc.ExternalURL.Host == "" && (svc == &cluster.Services.Controller ||
483 svc == &cluster.Services.GitHTTP ||
484 svc == &cluster.Services.Keepproxy ||
485 svc == &cluster.Services.WebDAV ||
486 svc == &cluster.Services.WebDAVDownload ||
487 svc == &cluster.Services.Websocket ||
488 svc == &cluster.Services.Workbench1) {
489 svc.ExternalURL = arvados.URL{Scheme: "https", Host: fmt.Sprintf("localhost:%s", nextPort())}
491 if len(svc.InternalURLs) == 0 {
492 svc.InternalURLs = map[arvados.URL]arvados.ServiceInstance{
493 arvados.URL{Scheme: "http", Host: fmt.Sprintf("localhost:%s", nextPort())}: arvados.ServiceInstance{},
497 if cluster.SystemRootToken == "" {
498 cluster.SystemRootToken = randomHexString(64)
500 if cluster.ManagementToken == "" {
501 cluster.ManagementToken = randomHexString(64)
503 if cluster.API.RailsSessionSecretToken == "" {
504 cluster.API.RailsSessionSecretToken = randomHexString(64)
506 if cluster.Collections.BlobSigningKey == "" {
507 cluster.Collections.BlobSigningKey = randomHexString(64)
509 if boot.ClusterType != "production" && cluster.Containers.DispatchPrivateKey == "" {
510 buf, err := ioutil.ReadFile(filepath.Join(boot.SourcePath, "lib", "dispatchcloud", "test", "sshkey_dispatch"))
514 cluster.Containers.DispatchPrivateKey = string(buf)
516 if boot.ClusterType != "production" {
517 cluster.TLS.Insecure = true
519 if boot.ClusterType == "test" {
520 // Add a second keepstore process.
521 cluster.Services.Keepstore.InternalURLs[arvados.URL{Scheme: "http", Host: fmt.Sprintf("localhost:%s", nextPort())}] = arvados.ServiceInstance{}
523 // Create a directory-backed volume for each keepstore
525 cluster.Volumes = map[string]arvados.Volume{}
526 for url := range cluster.Services.Keepstore.InternalURLs {
527 volnum := len(cluster.Volumes)
528 datadir := fmt.Sprintf("%s/keep%d.data", boot.tempdir, volnum)
529 if _, err = os.Stat(datadir + "/."); err == nil {
530 } else if !os.IsNotExist(err) {
532 } else if err = os.Mkdir(datadir, 0777); err != nil {
535 cluster.Volumes[fmt.Sprintf("zzzzz-nyw5e-%015d", volnum)] = arvados.Volume{
537 DriverParameters: json.RawMessage(fmt.Sprintf(`{"Root":%q}`, datadir)),
538 AccessViaHosts: map[arvados.URL]arvados.VolumeAccess{
544 if boot.OwnTemporaryDatabase {
545 cluster.PostgreSQL.Connection = arvados.PostgreSQLConnection{
546 "client_encoding": "utf8",
549 "dbname": "arvados_test",
551 "password": "insecure_arvados_test",
555 cfg.Clusters[cluster.ClusterID] = *cluster
559 func randomHexString(chars int) string {
560 b := make([]byte, chars/2)
561 _, err := rand.Read(b)
565 return fmt.Sprintf("%x", b)
568 func internalPort(svc arvados.Service) (string, error) {
569 for u := range svc.InternalURLs {
570 if _, p, err := net.SplitHostPort(u.Host); err != nil {
574 } else if u.Scheme == "https" {
580 return "", fmt.Errorf("service has no InternalURLs")
583 func externalPort(svc arvados.Service) (string, error) {
584 if _, p, err := net.SplitHostPort(svc.ExternalURL.Host); err != nil {
588 } else if svc.ExternalURL.Scheme == "https" {
595 func availablePort(addr string) (string, error) {
596 ln, err := net.Listen("tcp", addr)
601 _, port, err := net.SplitHostPort(ln.Addr().String())
608 // Try to connect to addr until it works, then close ch. Give up if
610 func waitForConnect(ctx context.Context, addr string) error {
611 dialer := net.Dialer{Timeout: time.Second}
612 for ctx.Err() == nil {
613 conn, err := dialer.DialContext(ctx, "tcp", addr)
615 time.Sleep(time.Second / 10)