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 {
39 sourcePath string // e.g., /home/username/src/arvados
40 libPath string // e.g., /var/lib/arvados
41 clusterType string // e.g., production
43 cluster *arvados.Cluster
49 setupRubyOnce sync.Once
54 func (boot *bootCommand) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
57 log := ctxlog.New(stderr, "json", "info")
62 log.WithError(err).Info("exiting")
66 flags := flag.NewFlagSet(prog, flag.ContinueOnError)
67 flags.SetOutput(stderr)
68 loader := config.NewLoader(stdin, log)
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 cwd, err := os.Getwd()
91 if !strings.HasPrefix(boot.sourcePath, "/") {
92 boot.sourcePath = filepath.Join(cwd, boot.sourcePath)
94 boot.sourcePath, err = filepath.EvalSymlinks(boot.sourcePath)
99 loader.SkipAPICalls = true
100 cfg, err := loader.Load()
105 boot.tempdir, err = ioutil.TempDir("", "arvados-server-boot-")
109 defer os.RemoveAll(boot.tempdir)
111 // Fill in any missing config keys, and write the resulting
112 // config in the temp dir for child services to use.
113 err = boot.autofillConfig(cfg, log)
117 conffile, err := os.OpenFile(filepath.Join(boot.tempdir, "config.yml"), os.O_CREATE|os.O_WRONLY, 0777)
121 defer conffile.Close()
122 err = json.NewEncoder(conffile).Encode(cfg)
126 err = conffile.Close()
130 os.Setenv("ARVADOS_CONFIG", conffile.Name())
131 arvados.DefaultConfigFile = conffile.Name()
132 os.Setenv("RAILS_ENV", boot.clusterType)
134 // Now that we have the config, replace the bootstrap logger
135 // with a new one according to the logging config.
136 boot.cluster, err = cfg.GetCluster("")
140 log = ctxlog.New(stderr, boot.cluster.SystemLogs.Format, boot.cluster.SystemLogs.LogLevel)
141 logger := log.WithFields(logrus.Fields{
144 ctx := ctxlog.Context(context.Background(), logger)
145 ctx, cancel := context.WithCancel(ctx)
148 ch := make(chan os.Signal)
149 signal.Notify(ch, syscall.SIGINT)
151 for sig := range ch {
152 logger.WithField("signal", sig).Info("caught signal")
157 for _, dir := range []string{boot.libPath, filepath.Join(boot.libPath, "bin")} {
158 if _, err = os.Stat(filepath.Join(dir, ".")); os.IsNotExist(err) {
159 err = os.Mkdir(dir, 0755)
163 } else if err != nil {
167 os.Setenv("PATH", filepath.Join(boot.libPath, "bin")+":"+os.Getenv("PATH"))
169 err = boot.installGoProgram(ctx, "cmd/arvados-server")
174 var wg sync.WaitGroup
175 for _, cmpt := range []component{
176 {name: "nginx", runFunc: runNginx},
177 {name: "controller", cmdHandler: controller.Command},
178 {name: "dispatchcloud", cmdHandler: dispatchcloud.Command, notIfTest: true},
179 {name: "git-httpd", goProg: "services/arv-git-httpd"},
180 {name: "health", goProg: "services/health"},
181 {name: "keep-balance", goProg: "services/keep-balance", notIfTest: true},
182 {name: "keepproxy", goProg: "services/keepproxy"},
183 {name: "keepstore", goProg: "services/keepstore", svc: boot.cluster.Services.Keepstore},
184 {name: "keep-web", goProg: "services/keep-web"},
185 {name: "railsAPI", svc: boot.cluster.Services.RailsAPI, railsApp: "services/api"},
186 {name: "ws", goProg: "services/ws"},
193 logger.WithField("component", cmpt.name).Info("starting")
194 err := cmpt.Run(ctx, boot, stdout, stderr)
196 logger.WithError(err).WithField("component", cmpt.name).Info("exited")
200 if boot.waitUntilReady(ctx) {
201 fmt.Fprintln(stdout, boot.cluster.Services.Controller.ExternalURL)
208 func (boot *bootCommand) waitUntilReady(ctx context.Context) bool {
209 agg := health.Aggregator{Cluster: boot.cluster}
210 for waiting := true; waiting; {
211 time.Sleep(time.Second)
212 if ctx.Err() != nil {
215 resp := agg.ClusterHealth()
216 // The overall health check (resp.Health=="OK") might
217 // never pass due to missing components (like
218 // arvados-dispatch-cloud in a test cluster), so
219 // instead we wait for all configured components to
222 for _, check := range resp.Checks {
223 if check.Health != "OK" {
231 func (boot *bootCommand) installGoProgram(ctx context.Context, srcpath string) error {
233 defer boot.goMutex.Unlock()
234 return boot.RunProgram(ctx, filepath.Join(boot.sourcePath, srcpath), nil, []string{"GOPATH=" + boot.libPath}, "go", "install")
237 func (boot *bootCommand) setupRubyEnv() error {
238 boot.setupRubyOnce.Do(func() {
239 buf, err := exec.Command("gem", "env", "gempath").Output() // /var/lib/arvados/.gem/ruby/2.5.0/bin:...
240 if err != nil || len(buf) == 0 {
241 boot.setupRubyErr = fmt.Errorf("gem env gempath: %v", err)
243 gempath := string(bytes.Split(buf, []byte{':'})[0])
244 os.Setenv("PATH", gempath+"/bin:"+os.Getenv("PATH"))
245 os.Setenv("GEM_HOME", gempath)
246 os.Setenv("GEM_PATH", gempath)
248 return boot.setupRubyErr
251 // Run prog with args, using dir as working directory. If ctx is
252 // cancelled while the child is running, RunProgram terminates the
253 // child, waits for it to exit, then returns.
255 // Child's environment will have our env vars, plus any given in env.
257 // Child's stdout will be written to output if non-nil, otherwise the
258 // boot command's stderr.
259 func (boot *bootCommand) RunProgram(ctx context.Context, dir string, output io.Writer, env []string, prog string, args ...string) error {
260 cmdline := fmt.Sprintf("%s", append([]string{prog}, args...))
261 fmt.Fprintf(boot.stderr, "%s executing in %s\n", cmdline, dir)
262 cmd := exec.Command(prog, args...)
264 cmd.Stdout = boot.stderr
268 cmd.Stderr = boot.stderr
269 if strings.HasPrefix(dir, "/") {
272 cmd.Dir = filepath.Join(boot.sourcePath, dir)
275 cmd.Env = append(env, os.Environ()...)
279 log := ctxlog.FromContext(ctx).WithFields(logrus.Fields{"dir": dir, "cmdline": cmdline})
280 for cmd.ProcessState == nil {
281 // Child hasn't exited yet
282 if cmd.Process == nil {
283 log.Infof("waiting for child process to start")
284 time.Sleep(time.Second)
286 log.WithField("PID", cmd.Process.Pid).Info("sending SIGTERM")
287 cmd.Process.Signal(syscall.SIGTERM)
288 log.WithField("PID", cmd.Process.Pid).Info("waiting for child process to exit after SIGTERM")
289 time.Sleep(5 * time.Second)
295 return fmt.Errorf("%s: error: %v", cmdline, err)
300 type component struct {
303 cmdHandler cmd.Handler
304 runFunc func(ctx context.Context, boot *bootCommand, stdout, stderr io.Writer) error
305 railsApp string // source dir in arvados tree, e.g., "services/api"
306 goProg string // source dir in arvados tree, e.g., "services/keepstore"
307 notIfTest bool // don't run this component on a test cluster
310 func (cmpt *component) Run(ctx context.Context, boot *bootCommand, stdout, stderr io.Writer) error {
311 if cmpt.notIfTest && boot.clusterType == "test" {
312 fmt.Fprintf(stderr, "skipping component %q in %s mode\n", cmpt.name, boot.clusterType)
316 fmt.Fprintf(stderr, "starting component %q\n", cmpt.name)
317 if cmpt.cmdHandler != nil {
318 errs := make(chan error, 1)
321 exitcode := cmpt.cmdHandler.RunCommand(cmpt.name, nil, bytes.NewBuffer(nil), stdout, stderr)
323 errs <- fmt.Errorf("exit code %d", exitcode)
330 // cmpt.cmdHandler.RunCommand() doesn't have
331 // access to our context, so it won't shut
332 // down by itself. We just abandon it.
336 if cmpt.goProg != "" {
337 boot.RunProgram(ctx, cmpt.goProg, nil, nil, "go", "install")
338 if ctx.Err() != nil {
341 _, basename := filepath.Split(cmpt.goProg)
342 if len(cmpt.svc.InternalURLs) > 0 {
343 // Run one for each URL
344 var wg sync.WaitGroup
345 for u := range cmpt.svc.InternalURLs {
350 boot.RunProgram(ctx, boot.tempdir, nil, []string{"ARVADOS_SERVICE_INTERNAL_URL=" + u.String()}, basename)
357 boot.RunProgram(ctx, boot.tempdir, nil, nil, basename)
360 if cmpt.runFunc != nil {
361 return cmpt.runFunc(ctx, boot, stdout, stderr)
363 if cmpt.railsApp != "" {
364 port, err := internalPort(cmpt.svc)
366 return fmt.Errorf("bug: no InternalURLs for component %q: %v", cmpt.name, cmpt.svc.InternalURLs)
368 err = boot.setupRubyEnv()
373 err = boot.RunProgram(ctx, cmpt.railsApp, &buf, nil, "gem", "list", "--details", "bundler")
377 for _, version := range []string{"1.11.0", "1.17.3", "2.0.2"} {
378 if !strings.Contains(buf.String(), "("+version+")") {
379 err = boot.RunProgram(ctx, cmpt.railsApp, nil, nil, "gem", "install", "--user", "bundler:1.11", "bundler:1.17.3", "bundler:2.0.2")
386 err = boot.RunProgram(ctx, cmpt.railsApp, nil, nil, "bundle", "install", "--jobs", "4", "--path", filepath.Join(os.Getenv("HOME"), ".gem"))
390 err = boot.RunProgram(ctx, cmpt.railsApp, nil, nil, "bundle", "exec", "passenger-config", "build-native-support")
394 err = boot.RunProgram(ctx, cmpt.railsApp, nil, nil, "bundle", "exec", "passenger-config", "install-standalone-runtime")
398 err = boot.RunProgram(ctx, cmpt.railsApp, nil, nil, "bundle", "exec", "passenger-config", "validate-install")
402 err = boot.RunProgram(ctx, cmpt.railsApp, nil, nil, "bundle", "exec", "passenger", "start", "-p", port)
407 return fmt.Errorf("bug: component %q has nothing to run", cmpt.name)
410 func (boot *bootCommand) autofillConfig(cfg *arvados.Config, log logrus.FieldLogger) error {
411 cluster, err := cfg.GetCluster("")
416 for _, svc := range []*arvados.Service{
417 &cluster.Services.Controller,
418 &cluster.Services.DispatchCloud,
419 &cluster.Services.GitHTTP,
420 &cluster.Services.Health,
421 &cluster.Services.Keepproxy,
422 &cluster.Services.Keepstore,
423 &cluster.Services.RailsAPI,
424 &cluster.Services.WebDAV,
425 &cluster.Services.WebDAVDownload,
426 &cluster.Services.Websocket,
428 if svc == &cluster.Services.DispatchCloud && boot.clusterType == "test" {
431 if len(svc.InternalURLs) == 0 {
433 svc.InternalURLs = map[arvados.URL]arvados.ServiceInstance{
434 arvados.URL{Scheme: "http", Host: fmt.Sprintf("localhost:%d", port)}: arvados.ServiceInstance{},
437 if svc.ExternalURL.Host == "" && (svc == &cluster.Services.Controller ||
438 svc == &cluster.Services.GitHTTP ||
439 svc == &cluster.Services.Keepproxy ||
440 svc == &cluster.Services.WebDAV ||
441 svc == &cluster.Services.WebDAVDownload ||
442 svc == &cluster.Services.Websocket) {
444 svc.ExternalURL = arvados.URL{Scheme: "https", Host: fmt.Sprintf("localhost:%d", port)}
447 if cluster.SystemRootToken == "" {
448 cluster.SystemRootToken = randomHexString(64)
450 if cluster.ManagementToken == "" {
451 cluster.ManagementToken = randomHexString(64)
453 if cluster.API.RailsSessionSecretToken == "" {
454 cluster.API.RailsSessionSecretToken = randomHexString(64)
456 if cluster.Collections.BlobSigningKey == "" {
457 cluster.Collections.BlobSigningKey = randomHexString(64)
459 if boot.clusterType != "production" && cluster.Containers.DispatchPrivateKey == "" {
460 buf, err := ioutil.ReadFile(filepath.Join(boot.sourcePath, "lib", "dispatchcloud", "test", "sshkey_dispatch"))
464 cluster.Containers.DispatchPrivateKey = string(buf)
466 if boot.clusterType != "production" {
467 cluster.TLS.Insecure = true
469 if boot.clusterType == "test" {
470 // Add a second keepstore process.
472 cluster.Services.Keepstore.InternalURLs[arvados.URL{Scheme: "http", Host: fmt.Sprintf("localhost:%d", port)}] = arvados.ServiceInstance{}
474 // Create a directory-backed volume for each keepstore
476 cluster.Volumes = map[string]arvados.Volume{}
477 for url := range cluster.Services.Keepstore.InternalURLs {
478 volnum := len(cluster.Volumes)
479 datadir := fmt.Sprintf("%s/keep%d.data", boot.tempdir, volnum)
480 if _, err = os.Stat(datadir + "/."); err == nil {
481 } else if !os.IsNotExist(err) {
483 } else if err = os.Mkdir(datadir, 0777); err != nil {
486 cluster.Volumes[fmt.Sprintf("zzzzz-nyw5e-%015d", volnum)] = arvados.Volume{
488 DriverParameters: json.RawMessage(fmt.Sprintf(`{"Root":%q}`, datadir)),
489 AccessViaHosts: map[arvados.URL]arvados.VolumeAccess{
495 cfg.Clusters[cluster.ClusterID] = *cluster
499 func randomHexString(chars int) string {
500 b := make([]byte, chars/2)
501 _, err := rand.Read(b)
505 return fmt.Sprintf("%x", b)
508 func internalPort(svc arvados.Service) (string, error) {
509 for u := range svc.InternalURLs {
510 if _, p, err := net.SplitHostPort(u.Host); err != nil {
514 } else if u.Scheme == "https" {
520 return "", fmt.Errorf("service has no InternalURLs")
523 func externalPort(svc arvados.Service) (string, error) {
524 if _, p, err := net.SplitHostPort(svc.ExternalURL.Host); err != nil {
528 } else if svc.ExternalURL.Scheme == "https" {