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 bootCommand struct{}
40 func (bootCommand) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
43 logger: ctxlog.New(stderr, "json", "info"),
46 ctx := ctxlog.Context(context.Background(), boot.logger)
47 ctx, cancel := context.WithCancel(ctx)
50 ch := make(chan os.Signal)
51 signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
54 boot.logger.WithField("signal", sig).Info("caught signal")
62 boot.logger.WithError(err).Info("exiting")
66 flags := flag.NewFlagSet(prog, flag.ContinueOnError)
67 flags.SetOutput(stderr)
68 loader := config.NewLoader(stdin, boot.logger)
69 loader.SetupFlags(flags)
70 versionFlag := flags.Bool("version", false, "Write version information to stdout and exit 0")
71 flags.StringVar(&boot.SourcePath, "source", ".", "arvados source tree `directory`")
72 flags.StringVar(&boot.LibPath, "lib", "/var/lib/arvados", "`directory` to install dependencies and library files")
73 flags.StringVar(&boot.ClusterType, "type", "production", "cluster `type`: development, test, or production")
74 err = flags.Parse(args)
75 if err == flag.ErrHelp {
78 } else if err != nil {
80 } else if *versionFlag {
81 return cmd.Version.RunCommand(prog, args, stdin, stdout, stderr)
82 } else if boot.ClusterType != "development" && boot.ClusterType != "test" && boot.ClusterType != "production" {
83 err = fmt.Errorf("cluster type must be 'development', 'test', or 'production'")
87 boot.Start(ctx, loader)
90 fmt.Fprintln(stdout, boot.cluster.Services.Controller.ExternalURL)
91 <-ctx.Done() // wait for signal
99 SourcePath string // e.g., /home/username/src/arvados
100 LibPath string // e.g., /var/lib/arvados
101 ClusterType string // e.g., production
104 logger logrus.FieldLogger
105 cluster *arvados.Cluster
108 cancel context.CancelFunc
110 healthChecker *health.Aggregator
114 environ []string // for child processes
116 setupRubyOnce sync.Once
121 func (boot *Booter) Start(ctx context.Context, loader *config.Loader) {
122 boot.ctx, boot.cancel = context.WithCancel(ctx)
123 boot.done = make(chan struct{})
125 err := boot.run(loader)
127 fmt.Fprintln(boot.Stderr, err)
133 func (boot *Booter) run(loader *config.Loader) error {
134 cwd, err := os.Getwd()
138 if !strings.HasPrefix(boot.SourcePath, "/") {
139 boot.SourcePath = filepath.Join(cwd, boot.SourcePath)
141 boot.SourcePath, err = filepath.EvalSymlinks(boot.SourcePath)
146 boot.tempdir, err = ioutil.TempDir("", "arvados-server-boot-")
150 defer os.RemoveAll(boot.tempdir)
152 loader.SkipAPICalls = true
153 cfg, err := loader.Load()
158 // Fill in any missing config keys, and write the resulting
159 // config in the temp dir for child services to use.
160 err = boot.autofillConfig(cfg, boot.logger)
164 conffile, err := os.OpenFile(filepath.Join(boot.tempdir, "config.yml"), os.O_CREATE|os.O_WRONLY, 0777)
168 defer conffile.Close()
169 err = json.NewEncoder(conffile).Encode(cfg)
173 err = conffile.Close()
177 boot.configfile = conffile.Name()
179 boot.environ = os.Environ()
180 boot.setEnv("ARVADOS_CONFIG", boot.configfile)
181 boot.setEnv("RAILS_ENV", boot.ClusterType)
182 boot.prependEnv("PATH", filepath.Join(boot.LibPath, "bin")+":")
184 boot.cluster, err = cfg.GetCluster("")
188 // Now that we have the config, replace the bootstrap logger
189 // with a new one according to the logging config.
190 boot.logger = ctxlog.New(boot.Stderr, boot.cluster.SystemLogs.Format, boot.cluster.SystemLogs.LogLevel).WithFields(logrus.Fields{
193 boot.healthChecker = &health.Aggregator{Cluster: boot.cluster}
195 for _, dir := range []string{boot.LibPath, filepath.Join(boot.LibPath, "bin")} {
196 if _, err = os.Stat(filepath.Join(dir, ".")); os.IsNotExist(err) {
197 err = os.Mkdir(dir, 0755)
201 } else if err != nil {
205 err = boot.installGoProgram(boot.ctx, "cmd/arvados-server")
209 err = boot.setupRubyEnv()
214 var wg sync.WaitGroup
215 for _, cmpt := range []component{
216 {name: "nginx", runFunc: runNginx},
217 {name: "controller", cmdHandler: controller.Command},
218 {name: "dispatchcloud", cmdHandler: dispatchcloud.Command, notIfTest: true},
219 {name: "git-httpd", goProg: "services/arv-git-httpd"},
220 {name: "health", goProg: "services/health"},
221 {name: "keep-balance", goProg: "services/keep-balance", notIfTest: true},
222 {name: "keepproxy", goProg: "services/keepproxy"},
223 {name: "keepstore", goProg: "services/keepstore", svc: boot.cluster.Services.Keepstore},
224 {name: "keep-web", goProg: "services/keep-web"},
225 {name: "railsAPI", svc: boot.cluster.Services.RailsAPI, railsApp: "services/api"},
226 {name: "workbench1", svc: boot.cluster.Services.Workbench1, railsApp: "apps/workbench"},
227 {name: "ws", goProg: "services/ws"},
234 boot.logger.WithField("component", cmpt.name).Info("starting")
235 err := cmpt.Run(boot.ctx, boot)
236 if err != nil && err != context.Canceled {
237 boot.logger.WithError(err).WithField("component", cmpt.name).Error("exited")
245 func (boot *Booter) Stop() {
250 func (boot *Booter) WaitReady() bool {
251 for waiting := true; waiting; {
252 time.Sleep(time.Second)
253 if boot.ctx.Err() != nil {
256 if boot.healthChecker == nil {
260 resp := boot.healthChecker.ClusterHealth()
261 // The overall health check (resp.Health=="OK") might
262 // never pass due to missing components (like
263 // arvados-dispatch-cloud in a test cluster), so
264 // instead we wait for all configured components to
267 for _, check := range resp.Checks {
268 if check.Health != "OK" {
276 func (boot *Booter) prependEnv(key, prepend string) {
277 for i, s := range boot.environ {
278 if strings.HasPrefix(s, key+"=") {
279 boot.environ[i] = key + "=" + prepend + s[len(key)+1:]
283 boot.environ = append(boot.environ, key+"="+prepend)
286 func (boot *Booter) setEnv(key, val string) {
287 for i, s := range boot.environ {
288 if strings.HasPrefix(s, key+"=") {
289 boot.environ[i] = key + "=" + val
293 boot.environ = append(boot.environ, key+"="+val)
296 func (boot *Booter) installGoProgram(ctx context.Context, srcpath string) error {
298 defer boot.goMutex.Unlock()
299 return boot.RunProgram(ctx, filepath.Join(boot.SourcePath, srcpath), nil, []string{"GOPATH=" + boot.LibPath}, "go", "install")
302 func (boot *Booter) setupRubyEnv() error {
303 buf, err := exec.Command("gem", "env", "gempath").Output() // /var/lib/arvados/.gem/ruby/2.5.0/bin:...
304 if err != nil || len(buf) == 0 {
305 return fmt.Errorf("gem env gempath: %v", err)
307 gempath := string(bytes.Split(buf, []byte{':'})[0])
308 boot.prependEnv("PATH", gempath+"/bin:")
309 boot.setEnv("GEM_HOME", gempath)
310 boot.setEnv("GEM_PATH", gempath)
314 func (boot *Booter) lookPath(prog string) string {
315 for _, val := range boot.environ {
316 if strings.HasPrefix(val, "PATH=") {
317 for _, dir := range filepath.SplitList(val[5:]) {
318 path := filepath.Join(dir, prog)
319 if fi, err := os.Stat(path); err == nil && fi.Mode()&0111 != 0 {
328 // Run prog with args, using dir as working directory. If ctx is
329 // cancelled while the child is running, RunProgram terminates the
330 // child, waits for it to exit, then returns.
332 // Child's environment will have our env vars, plus any given in env.
334 // Child's stdout will be written to output if non-nil, otherwise the
335 // boot command's stderr.
336 func (boot *Booter) RunProgram(ctx context.Context, dir string, output io.Writer, env []string, prog string, args ...string) error {
337 cmdline := fmt.Sprintf("%s", append([]string{prog}, args...))
338 fmt.Fprintf(boot.Stderr, "%s executing in %s\n", cmdline, dir)
339 cmd := exec.Command(boot.lookPath(prog), args...)
341 cmd.Stdout = boot.Stderr
345 cmd.Stderr = boot.Stderr
346 if strings.HasPrefix(dir, "/") {
349 cmd.Dir = filepath.Join(boot.SourcePath, dir)
351 cmd.Env = append(env, boot.environ...)
354 defer func() { exited = true }()
357 log := ctxlog.FromContext(ctx).WithFields(logrus.Fields{"dir": dir, "cmdline": cmdline})
359 if cmd.Process == nil {
360 log.Debug("waiting for child process to start")
361 time.Sleep(time.Second / 2)
363 log.WithField("PID", cmd.Process.Pid).Debug("sending SIGTERM")
364 cmd.Process.Signal(syscall.SIGTERM)
365 time.Sleep(5 * time.Second)
367 log.WithField("PID", cmd.Process.Pid).Warn("still waiting for child process to exit 5s after SIGTERM")
374 if err != nil && ctx.Err() == nil {
375 // Only report errors that happen before the context ends.
376 return fmt.Errorf("%s: error: %v", cmdline, err)
381 type component struct {
384 cmdHandler cmd.Handler
385 runFunc func(ctx context.Context, boot *Booter) error
386 railsApp string // source dir in arvados tree, e.g., "services/api"
387 goProg string // source dir in arvados tree, e.g., "services/keepstore"
388 notIfTest bool // don't run this component on a test cluster
391 func (cmpt *component) Run(ctx context.Context, boot *Booter) error {
392 if cmpt.notIfTest && boot.ClusterType == "test" {
393 fmt.Fprintf(boot.Stderr, "skipping component %q in %s mode\n", cmpt.name, boot.ClusterType)
397 fmt.Fprintf(boot.Stderr, "starting component %q\n", cmpt.name)
398 if cmpt.cmdHandler != nil {
399 errs := make(chan error, 1)
402 exitcode := cmpt.cmdHandler.RunCommand(cmpt.name, []string{"-config", boot.configfile}, bytes.NewBuffer(nil), boot.Stderr, boot.Stderr)
404 errs <- fmt.Errorf("exit code %d", exitcode)
411 // cmpt.cmdHandler.RunCommand() doesn't have
412 // access to our context, so it won't shut
413 // down by itself. We just abandon it.
417 if cmpt.goProg != "" {
418 boot.RunProgram(ctx, cmpt.goProg, nil, nil, "go", "install")
419 if ctx.Err() != nil {
422 _, basename := filepath.Split(cmpt.goProg)
423 if len(cmpt.svc.InternalURLs) > 0 {
424 // Run one for each URL
425 var wg sync.WaitGroup
426 for u := range cmpt.svc.InternalURLs {
431 boot.RunProgram(ctx, boot.tempdir, nil, []string{"ARVADOS_SERVICE_INTERNAL_URL=" + u.String()}, basename)
437 boot.RunProgram(ctx, boot.tempdir, nil, nil, basename)
441 if cmpt.runFunc != nil {
442 return cmpt.runFunc(ctx, boot)
444 if cmpt.railsApp != "" {
445 port, err := internalPort(cmpt.svc)
447 return fmt.Errorf("bug: no InternalURLs for component %q: %v", cmpt.name, cmpt.svc.InternalURLs)
450 err = boot.RunProgram(ctx, cmpt.railsApp, &buf, nil, "gem", "list", "--details", "bundler")
454 for _, version := range []string{"1.11.0", "1.17.3", "2.0.2"} {
455 if !strings.Contains(buf.String(), "("+version+")") {
456 err = boot.RunProgram(ctx, cmpt.railsApp, nil, nil, "gem", "install", "--user", "bundler:1.11", "bundler:1.17.3", "bundler:2.0.2")
463 err = boot.RunProgram(ctx, cmpt.railsApp, nil, nil, "bundle", "install", "--jobs", "4", "--path", filepath.Join(os.Getenv("HOME"), ".gem"))
467 err = boot.RunProgram(ctx, cmpt.railsApp, nil, nil, "bundle", "exec", "passenger-config", "build-native-support")
471 err = boot.RunProgram(ctx, cmpt.railsApp, nil, nil, "bundle", "exec", "passenger-config", "install-standalone-runtime")
475 err = boot.RunProgram(ctx, cmpt.railsApp, nil, nil, "bundle", "exec", "passenger-config", "validate-install")
479 err = boot.RunProgram(ctx, cmpt.railsApp, nil, nil, "bundle", "exec", "passenger", "start", "-p", port)
485 return fmt.Errorf("bug: component %q has nothing to run", cmpt.name)
488 func (boot *Booter) autofillConfig(cfg *arvados.Config, log logrus.FieldLogger) error {
489 cluster, err := cfg.GetCluster("")
494 for _, svc := range []*arvados.Service{
495 &cluster.Services.Controller,
496 &cluster.Services.DispatchCloud,
497 &cluster.Services.GitHTTP,
498 &cluster.Services.Health,
499 &cluster.Services.Keepproxy,
500 &cluster.Services.Keepstore,
501 &cluster.Services.RailsAPI,
502 &cluster.Services.WebDAV,
503 &cluster.Services.WebDAVDownload,
504 &cluster.Services.Websocket,
505 &cluster.Services.Workbench1,
507 if svc == &cluster.Services.DispatchCloud && boot.ClusterType == "test" {
510 if len(svc.InternalURLs) == 0 {
512 svc.InternalURLs = map[arvados.URL]arvados.ServiceInstance{
513 arvados.URL{Scheme: "http", Host: fmt.Sprintf("localhost:%d", port)}: arvados.ServiceInstance{},
516 if svc.ExternalURL.Host == "" && (svc == &cluster.Services.Controller ||
517 svc == &cluster.Services.GitHTTP ||
518 svc == &cluster.Services.Keepproxy ||
519 svc == &cluster.Services.WebDAV ||
520 svc == &cluster.Services.WebDAVDownload ||
521 svc == &cluster.Services.Websocket ||
522 svc == &cluster.Services.Workbench1) {
524 svc.ExternalURL = arvados.URL{Scheme: "https", Host: fmt.Sprintf("localhost:%d", port)}
527 if cluster.SystemRootToken == "" {
528 cluster.SystemRootToken = randomHexString(64)
530 if cluster.ManagementToken == "" {
531 cluster.ManagementToken = randomHexString(64)
533 if cluster.API.RailsSessionSecretToken == "" {
534 cluster.API.RailsSessionSecretToken = randomHexString(64)
536 if cluster.Collections.BlobSigningKey == "" {
537 cluster.Collections.BlobSigningKey = randomHexString(64)
539 if boot.ClusterType != "production" && cluster.Containers.DispatchPrivateKey == "" {
540 buf, err := ioutil.ReadFile(filepath.Join(boot.SourcePath, "lib", "dispatchcloud", "test", "sshkey_dispatch"))
544 cluster.Containers.DispatchPrivateKey = string(buf)
546 if boot.ClusterType != "production" {
547 cluster.TLS.Insecure = true
549 if boot.ClusterType == "test" {
550 // Add a second keepstore process.
552 cluster.Services.Keepstore.InternalURLs[arvados.URL{Scheme: "http", Host: fmt.Sprintf("localhost:%d", port)}] = arvados.ServiceInstance{}
554 // Create a directory-backed volume for each keepstore
556 cluster.Volumes = map[string]arvados.Volume{}
557 for url := range cluster.Services.Keepstore.InternalURLs {
558 volnum := len(cluster.Volumes)
559 datadir := fmt.Sprintf("%s/keep%d.data", boot.tempdir, volnum)
560 if _, err = os.Stat(datadir + "/."); err == nil {
561 } else if !os.IsNotExist(err) {
563 } else if err = os.Mkdir(datadir, 0777); err != nil {
566 cluster.Volumes[fmt.Sprintf("zzzzz-nyw5e-%015d", volnum)] = arvados.Volume{
568 DriverParameters: json.RawMessage(fmt.Sprintf(`{"Root":%q}`, datadir)),
569 AccessViaHosts: map[arvados.URL]arvados.VolumeAccess{
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" {