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/lib/controller"
30 "git.arvados.org/arvados.git/lib/dispatchcloud"
31 "git.arvados.org/arvados.git/sdk/go/arvados"
32 "git.arvados.org/arvados.git/sdk/go/ctxlog"
33 "git.arvados.org/arvados.git/sdk/go/health"
34 "github.com/sirupsen/logrus"
37 var Command cmd.Handler = bootCommand{}
39 type bootCommand struct{}
41 func (bootCommand) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
44 logger: ctxlog.New(stderr, "json", "info"),
47 ctx := ctxlog.Context(context.Background(), boot.logger)
48 ctx, cancel := context.WithCancel(ctx)
51 ch := make(chan os.Signal)
52 signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
55 boot.logger.WithField("signal", sig).Info("caught signal")
63 boot.logger.WithError(err).Info("exiting")
67 flags := flag.NewFlagSet(prog, flag.ContinueOnError)
68 flags.SetOutput(stderr)
69 loader := config.NewLoader(stdin, boot.logger)
70 loader.SetupFlags(flags)
71 versionFlag := flags.Bool("version", false, "Write version information to stdout and exit 0")
72 flags.StringVar(&boot.SourcePath, "source", ".", "arvados source tree `directory`")
73 flags.StringVar(&boot.LibPath, "lib", "/var/lib/arvados", "`directory` to install dependencies and library files")
74 flags.StringVar(&boot.ClusterType, "type", "production", "cluster `type`: development, test, or production")
75 flags.BoolVar(&boot.OwnTemporaryDatabase, "own-temporary-database", false, "bring up a postgres server and create a temporary database")
76 err = flags.Parse(args)
77 if err == flag.ErrHelp {
80 } else if err != nil {
82 } else if *versionFlag {
83 return cmd.Version.RunCommand(prog, args, stdin, stdout, stderr)
84 } else if boot.ClusterType != "development" && boot.ClusterType != "test" && boot.ClusterType != "production" {
85 err = fmt.Errorf("cluster type must be 'development', 'test', or 'production'")
89 boot.Start(ctx, loader)
92 fmt.Fprintln(stdout, boot.cluster.Services.Controller.ExternalURL)
93 <-ctx.Done() // wait for signal
101 SourcePath string // e.g., /home/username/src/arvados
102 LibPath string // e.g., /var/lib/arvados
103 ClusterType string // e.g., production
104 OwnTemporaryDatabase bool
107 logger logrus.FieldLogger
108 cluster *arvados.Cluster
111 cancel context.CancelFunc
113 healthChecker *health.Aggregator
117 environ []string // for child processes
119 setupRubyOnce sync.Once
124 func (boot *Booter) Start(ctx context.Context, loader *config.Loader) {
125 boot.ctx, boot.cancel = context.WithCancel(ctx)
126 boot.done = make(chan struct{})
128 err := boot.run(loader)
130 fmt.Fprintln(boot.Stderr, err)
136 func (boot *Booter) run(loader *config.Loader) error {
137 cwd, err := os.Getwd()
141 if !strings.HasPrefix(boot.SourcePath, "/") {
142 boot.SourcePath = filepath.Join(cwd, boot.SourcePath)
144 boot.SourcePath, err = filepath.EvalSymlinks(boot.SourcePath)
149 boot.tempdir, err = ioutil.TempDir("", "arvados-server-boot-")
153 defer os.RemoveAll(boot.tempdir)
155 loader.SkipAPICalls = true
156 cfg, err := loader.Load()
161 // Fill in any missing config keys, and write the resulting
162 // config in the temp dir for child services to use.
163 err = boot.autofillConfig(cfg, boot.logger)
167 conffile, err := os.OpenFile(filepath.Join(boot.tempdir, "config.yml"), os.O_CREATE|os.O_WRONLY, 0777)
171 defer conffile.Close()
172 err = json.NewEncoder(conffile).Encode(cfg)
176 err = conffile.Close()
180 boot.configfile = conffile.Name()
182 boot.environ = os.Environ()
183 boot.setEnv("ARVADOS_CONFIG", boot.configfile)
184 boot.setEnv("RAILS_ENV", boot.ClusterType)
185 boot.prependEnv("PATH", filepath.Join(boot.LibPath, "bin")+":")
187 boot.cluster, err = cfg.GetCluster("")
191 // Now that we have the config, replace the bootstrap logger
192 // with a new one according to the logging config.
193 boot.logger = ctxlog.New(boot.Stderr, boot.cluster.SystemLogs.Format, boot.cluster.SystemLogs.LogLevel).WithFields(logrus.Fields{
196 boot.healthChecker = &health.Aggregator{Cluster: boot.cluster}
198 for _, dir := range []string{boot.LibPath, filepath.Join(boot.LibPath, "bin")} {
199 if _, err = os.Stat(filepath.Join(dir, ".")); os.IsNotExist(err) {
200 err = os.Mkdir(dir, 0755)
204 } else if err != nil {
208 err = boot.installGoProgram(boot.ctx, "cmd/arvados-server")
212 err = boot.setupRubyEnv()
217 var wg sync.WaitGroup
218 components := map[string]*component{
219 "certificates": &component{runFunc: createCertificates},
220 "database": &component{runFunc: runPostgres, depends: []string{"certificates"}},
221 "nginx": &component{runFunc: runNginx},
222 "controller": &component{cmdHandler: controller.Command, depends: []string{"database"}},
223 "dispatchcloud": &component{cmdHandler: dispatchcloud.Command, notIfTest: true},
224 "git-httpd": &component{goProg: "services/arv-git-httpd"},
225 "health": &component{goProg: "services/health"},
226 "keep-balance": &component{goProg: "services/keep-balance", notIfTest: true},
227 "keepproxy": &component{goProg: "services/keepproxy"},
228 "keepstore": &component{goProg: "services/keepstore", svc: boot.cluster.Services.Keepstore},
229 "keep-web": &component{goProg: "services/keep-web"},
230 "railsAPI": &component{svc: boot.cluster.Services.RailsAPI, railsApp: "services/api", depends: []string{"database"}},
231 "workbench1": &component{svc: boot.cluster.Services.Workbench1, railsApp: "apps/workbench"},
232 "ws": &component{goProg: "services/ws", depends: []string{"database"}},
234 for _, cmpt := range components {
235 cmpt.ready = make(chan bool)
237 for name, cmpt := range components {
238 name, cmpt := name, cmpt
243 for _, dep := range cmpt.depends {
244 boot.logger.WithField("component", name).WithField("dependency", dep).Info("waiting")
246 case <-components[dep].ready:
247 case <-boot.ctx.Done():
251 boot.logger.WithField("component", name).Info("starting")
252 err := cmpt.Run(boot.ctx, name, boot)
253 if err != nil && err != context.Canceled {
254 boot.logger.WithError(err).WithField("component", name).Error("exited")
262 func (boot *Booter) Stop() {
267 func (boot *Booter) WaitReady() bool {
268 for waiting := true; waiting; {
269 time.Sleep(time.Second)
270 if boot.ctx.Err() != nil {
273 if boot.healthChecker == nil {
277 resp := boot.healthChecker.ClusterHealth()
278 // The overall health check (resp.Health=="OK") might
279 // never pass due to missing components (like
280 // arvados-dispatch-cloud in a test cluster), so
281 // instead we wait for all configured components to
284 for _, check := range resp.Checks {
285 if check.Health != "OK" {
293 func (boot *Booter) prependEnv(key, prepend string) {
294 for i, s := range boot.environ {
295 if strings.HasPrefix(s, key+"=") {
296 boot.environ[i] = key + "=" + prepend + s[len(key)+1:]
300 boot.environ = append(boot.environ, key+"="+prepend)
303 func (boot *Booter) setEnv(key, val string) {
304 for i, s := range boot.environ {
305 if strings.HasPrefix(s, key+"=") {
306 boot.environ[i] = key + "=" + val
310 boot.environ = append(boot.environ, key+"="+val)
313 func (boot *Booter) installGoProgram(ctx context.Context, srcpath string) error {
315 defer boot.goMutex.Unlock()
316 return boot.RunProgram(ctx, filepath.Join(boot.SourcePath, srcpath), nil, []string{"GOPATH=" + boot.LibPath}, "go", "install")
319 func (boot *Booter) setupRubyEnv() error {
320 buf, err := exec.Command("gem", "env", "gempath").Output() // /var/lib/arvados/.gem/ruby/2.5.0/bin:...
321 if err != nil || len(buf) == 0 {
322 return fmt.Errorf("gem env gempath: %v", err)
324 gempath := string(bytes.Split(buf, []byte{':'})[0])
325 boot.prependEnv("PATH", gempath+"/bin:")
326 boot.setEnv("GEM_HOME", gempath)
327 boot.setEnv("GEM_PATH", gempath)
331 func (boot *Booter) lookPath(prog string) string {
332 for _, val := range boot.environ {
333 if strings.HasPrefix(val, "PATH=") {
334 for _, dir := range filepath.SplitList(val[5:]) {
335 path := filepath.Join(dir, prog)
336 if fi, err := os.Stat(path); err == nil && fi.Mode()&0111 != 0 {
345 // Run prog with args, using dir as working directory. If ctx is
346 // cancelled while the child is running, RunProgram terminates the
347 // child, waits for it to exit, then returns.
349 // Child's environment will have our env vars, plus any given in env.
351 // Child's stdout will be written to output if non-nil, otherwise the
352 // boot command's stderr.
353 func (boot *Booter) RunProgram(ctx context.Context, dir string, output io.Writer, env []string, prog string, args ...string) error {
354 cmdline := fmt.Sprintf("%s", append([]string{prog}, args...))
355 fmt.Fprintf(boot.Stderr, "%s executing in %s\n", cmdline, dir)
356 cmd := exec.Command(boot.lookPath(prog), args...)
358 cmd.Stdout = boot.Stderr
362 cmd.Stderr = boot.Stderr
363 if strings.HasPrefix(dir, "/") {
366 cmd.Dir = filepath.Join(boot.SourcePath, dir)
368 cmd.Env = append(env, boot.environ...)
371 defer func() { exited = true }()
374 log := ctxlog.FromContext(ctx).WithFields(logrus.Fields{"dir": dir, "cmdline": cmdline})
376 if cmd.Process == nil {
377 log.Debug("waiting for child process to start")
378 time.Sleep(time.Second / 2)
380 log.WithField("PID", cmd.Process.Pid).Debug("sending SIGTERM")
381 cmd.Process.Signal(syscall.SIGTERM)
382 time.Sleep(5 * time.Second)
384 log.WithField("PID", cmd.Process.Pid).Warn("still waiting for child process to exit 5s after SIGTERM")
391 if err != nil && ctx.Err() == nil {
392 // Only report errors that happen before the context ends.
393 return fmt.Errorf("%s: error: %v", cmdline, err)
398 type component struct {
401 cmdHandler cmd.Handler
402 runFunc func(ctx context.Context, boot *Booter, ready chan<- bool) error
403 railsApp string // source dir in arvados tree, e.g., "services/api"
404 goProg string // source dir in arvados tree, e.g., "services/keepstore"
405 notIfTest bool // don't run this component on a test cluster
406 depends []string // don't start until all of these components are ready
411 func (cmpt *component) Run(ctx context.Context, name string, boot *Booter) error {
412 if cmpt.notIfTest && boot.ClusterType == "test" {
413 fmt.Fprintf(boot.Stderr, "skipping component %q in %s mode\n", name, boot.ClusterType)
417 fmt.Fprintf(boot.Stderr, "starting component %q\n", name)
418 if cmpt.cmdHandler != nil {
419 errs := make(chan error, 1)
422 exitcode := cmpt.cmdHandler.RunCommand(name, []string{"-config", boot.configfile}, bytes.NewBuffer(nil), boot.Stderr, boot.Stderr)
424 errs <- fmt.Errorf("exit code %d", exitcode)
431 // cmpt.cmdHandler.RunCommand() doesn't have
432 // access to our context, so it won't shut
433 // down by itself. We just abandon it.
437 if cmpt.goProg != "" {
438 boot.RunProgram(ctx, cmpt.goProg, nil, nil, "go", "install")
439 if ctx.Err() != nil {
442 _, basename := filepath.Split(cmpt.goProg)
443 if len(cmpt.svc.InternalURLs) > 0 {
444 // Run one for each URL
445 var wg sync.WaitGroup
446 for u := range cmpt.svc.InternalURLs {
451 boot.RunProgram(ctx, boot.tempdir, nil, []string{"ARVADOS_SERVICE_INTERNAL_URL=" + u.String()}, basename)
457 boot.RunProgram(ctx, boot.tempdir, nil, nil, basename)
461 if cmpt.runFunc != nil {
462 return cmpt.runFunc(ctx, boot, cmpt.ready)
464 if cmpt.railsApp != "" {
465 port, err := internalPort(cmpt.svc)
467 return fmt.Errorf("bug: no InternalURLs for component %q: %v", name, cmpt.svc.InternalURLs)
470 err = boot.RunProgram(ctx, cmpt.railsApp, &buf, nil, "gem", "list", "--details", "bundler")
474 for _, version := range []string{"1.11.0", "1.17.3", "2.0.2"} {
475 if !strings.Contains(buf.String(), "("+version+")") {
476 err = boot.RunProgram(ctx, cmpt.railsApp, nil, nil, "gem", "install", "--user", "bundler:1.11", "bundler:1.17.3", "bundler:2.0.2")
483 err = boot.RunProgram(ctx, cmpt.railsApp, nil, nil, "bundle", "install", "--jobs", "4", "--path", filepath.Join(os.Getenv("HOME"), ".gem"))
487 err = boot.RunProgram(ctx, cmpt.railsApp, nil, nil, "bundle", "exec", "passenger-config", "build-native-support")
491 err = boot.RunProgram(ctx, cmpt.railsApp, nil, nil, "bundle", "exec", "passenger-config", "install-standalone-runtime")
495 err = boot.RunProgram(ctx, cmpt.railsApp, nil, nil, "bundle", "exec", "passenger-config", "validate-install")
499 err = boot.RunProgram(ctx, cmpt.railsApp, nil, nil, "bundle", "exec", "passenger", "start", "-p", port)
505 return fmt.Errorf("bug: component %q has nothing to run", name)
508 func (boot *Booter) autofillConfig(cfg *arvados.Config, log logrus.FieldLogger) error {
509 cluster, err := cfg.GetCluster("")
514 for _, svc := range []*arvados.Service{
515 &cluster.Services.Controller,
516 &cluster.Services.DispatchCloud,
517 &cluster.Services.GitHTTP,
518 &cluster.Services.Health,
519 &cluster.Services.Keepproxy,
520 &cluster.Services.Keepstore,
521 &cluster.Services.RailsAPI,
522 &cluster.Services.WebDAV,
523 &cluster.Services.WebDAVDownload,
524 &cluster.Services.Websocket,
525 &cluster.Services.Workbench1,
527 if svc == &cluster.Services.DispatchCloud && boot.ClusterType == "test" {
530 if len(svc.InternalURLs) == 0 {
532 svc.InternalURLs = map[arvados.URL]arvados.ServiceInstance{
533 arvados.URL{Scheme: "http", Host: fmt.Sprintf("localhost:%d", port)}: arvados.ServiceInstance{},
536 if svc.ExternalURL.Host == "" && (svc == &cluster.Services.Controller ||
537 svc == &cluster.Services.GitHTTP ||
538 svc == &cluster.Services.Keepproxy ||
539 svc == &cluster.Services.WebDAV ||
540 svc == &cluster.Services.WebDAVDownload ||
541 svc == &cluster.Services.Websocket ||
542 svc == &cluster.Services.Workbench1) {
544 svc.ExternalURL = arvados.URL{Scheme: "https", Host: fmt.Sprintf("localhost:%d", port)}
547 if cluster.SystemRootToken == "" {
548 cluster.SystemRootToken = randomHexString(64)
550 if cluster.ManagementToken == "" {
551 cluster.ManagementToken = randomHexString(64)
553 if cluster.API.RailsSessionSecretToken == "" {
554 cluster.API.RailsSessionSecretToken = randomHexString(64)
556 if cluster.Collections.BlobSigningKey == "" {
557 cluster.Collections.BlobSigningKey = randomHexString(64)
559 if boot.ClusterType != "production" && cluster.Containers.DispatchPrivateKey == "" {
560 buf, err := ioutil.ReadFile(filepath.Join(boot.SourcePath, "lib", "dispatchcloud", "test", "sshkey_dispatch"))
564 cluster.Containers.DispatchPrivateKey = string(buf)
566 if boot.ClusterType != "production" {
567 cluster.TLS.Insecure = true
569 if boot.ClusterType == "test" {
570 // Add a second keepstore process.
572 cluster.Services.Keepstore.InternalURLs[arvados.URL{Scheme: "http", Host: fmt.Sprintf("localhost:%d", port)}] = arvados.ServiceInstance{}
574 // Create a directory-backed volume for each keepstore
576 cluster.Volumes = map[string]arvados.Volume{}
577 for url := range cluster.Services.Keepstore.InternalURLs {
578 volnum := len(cluster.Volumes)
579 datadir := fmt.Sprintf("%s/keep%d.data", boot.tempdir, volnum)
580 if _, err = os.Stat(datadir + "/."); err == nil {
581 } else if !os.IsNotExist(err) {
583 } else if err = os.Mkdir(datadir, 0777); err != nil {
586 cluster.Volumes[fmt.Sprintf("zzzzz-nyw5e-%015d", volnum)] = arvados.Volume{
588 DriverParameters: json.RawMessage(fmt.Sprintf(`{"Root":%q}`, datadir)),
589 AccessViaHosts: map[arvados.URL]arvados.VolumeAccess{
595 if boot.OwnTemporaryDatabase {
596 p, err := availablePort()
600 cluster.PostgreSQL.Connection = arvados.PostgreSQLConnection{
601 "client_encoding": "utf8",
603 "port": strconv.Itoa(p),
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() (int, error) {
651 ln, err := net.Listen("tcp", ":0")
656 _, p, err := net.SplitHostPort(ln.Addr().String())
660 return strconv.Atoi(p)
663 // Try to connect to addr until it works, then close ch. Give up if
665 func connectAndClose(ctx context.Context, addr string, ch chan<- bool) {
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)