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 environ []string // for child processes
51 setupRubyOnce sync.Once
56 func (boot *bootCommand) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
59 log := ctxlog.New(stderr, "json", "info")
64 log.WithError(err).Info("exiting")
68 flags := flag.NewFlagSet(prog, flag.ContinueOnError)
69 flags.SetOutput(stderr)
70 loader := config.NewLoader(stdin, log)
71 loader.SetupFlags(flags)
72 versionFlag := flags.Bool("version", false, "Write version information to stdout and exit 0")
73 flags.StringVar(&boot.sourcePath, "source", ".", "arvados source tree `directory`")
74 flags.StringVar(&boot.libPath, "lib", "/var/lib/arvados", "`directory` to install dependencies and library files")
75 flags.StringVar(&boot.clusterType, "type", "production", "cluster `type`: development, test, or production")
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 cwd, err := os.Getwd()
93 if !strings.HasPrefix(boot.sourcePath, "/") {
94 boot.sourcePath = filepath.Join(cwd, boot.sourcePath)
96 boot.sourcePath, err = filepath.EvalSymlinks(boot.sourcePath)
101 loader.SkipAPICalls = true
102 cfg, err := loader.Load()
107 boot.tempdir, err = ioutil.TempDir("", "arvados-server-boot-")
111 defer os.RemoveAll(boot.tempdir)
113 // Fill in any missing config keys, and write the resulting
114 // config in the temp dir for child services to use.
115 err = boot.autofillConfig(cfg, log)
119 conffile, err := os.OpenFile(filepath.Join(boot.tempdir, "config.yml"), os.O_CREATE|os.O_WRONLY, 0777)
123 defer conffile.Close()
124 err = json.NewEncoder(conffile).Encode(cfg)
128 err = conffile.Close()
132 boot.configfile = conffile.Name()
134 boot.environ = os.Environ()
135 boot.setEnv("ARVADOS_CONFIG", boot.configfile)
136 boot.setEnv("RAILS_ENV", boot.clusterType)
137 boot.prependEnv("PATH", filepath.Join(boot.libPath, "bin")+":")
139 // Now that we have the config, replace the bootstrap logger
140 // with a new one according to the logging config.
141 boot.cluster, err = cfg.GetCluster("")
145 log = ctxlog.New(stderr, boot.cluster.SystemLogs.Format, boot.cluster.SystemLogs.LogLevel)
146 logger := log.WithFields(logrus.Fields{
149 ctx := ctxlog.Context(context.Background(), logger)
150 ctx, cancel := context.WithCancel(ctx)
153 ch := make(chan os.Signal)
154 signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
156 for sig := range ch {
157 logger.WithField("signal", sig).Info("caught signal")
162 for _, dir := range []string{boot.libPath, filepath.Join(boot.libPath, "bin")} {
163 if _, err = os.Stat(filepath.Join(dir, ".")); os.IsNotExist(err) {
164 err = os.Mkdir(dir, 0755)
168 } else if err != nil {
172 err = boot.installGoProgram(ctx, "cmd/arvados-server")
176 err = boot.setupRubyEnv()
181 var wg sync.WaitGroup
182 for _, cmpt := range []component{
183 {name: "nginx", runFunc: runNginx},
184 {name: "controller", cmdHandler: controller.Command},
185 {name: "dispatchcloud", cmdHandler: dispatchcloud.Command, notIfTest: true},
186 {name: "git-httpd", goProg: "services/arv-git-httpd"},
187 {name: "health", goProg: "services/health"},
188 {name: "keep-balance", goProg: "services/keep-balance", notIfTest: true},
189 {name: "keepproxy", goProg: "services/keepproxy"},
190 {name: "keepstore", goProg: "services/keepstore", svc: boot.cluster.Services.Keepstore},
191 {name: "keep-web", goProg: "services/keep-web"},
192 {name: "railsAPI", svc: boot.cluster.Services.RailsAPI, railsApp: "services/api"},
193 {name: "ws", goProg: "services/ws"},
200 logger.WithField("component", cmpt.name).Info("starting")
201 err := cmpt.Run(ctx, boot, stdout, stderr)
203 logger.WithError(err).WithField("component", cmpt.name).Info("exited")
207 if boot.waitUntilReady(ctx) {
208 fmt.Fprintln(stdout, boot.cluster.Services.Controller.ExternalURL)
215 func (boot *bootCommand) waitUntilReady(ctx context.Context) bool {
216 agg := health.Aggregator{Cluster: boot.cluster}
217 for waiting := true; waiting; {
218 time.Sleep(time.Second)
219 if ctx.Err() != nil {
222 resp := agg.ClusterHealth()
223 // The overall health check (resp.Health=="OK") might
224 // never pass due to missing components (like
225 // arvados-dispatch-cloud in a test cluster), so
226 // instead we wait for all configured components to
229 for _, check := range resp.Checks {
230 if check.Health != "OK" {
238 func (boot *bootCommand) prependEnv(key, prepend string) {
239 for i, s := range boot.environ {
240 if strings.HasPrefix(s, key+"=") {
241 boot.environ[i] = key + "=" + prepend + s[len(key)+1:]
245 boot.environ = append(boot.environ, key+"="+prepend)
248 func (boot *bootCommand) setEnv(key, val string) {
249 for i, s := range boot.environ {
250 if strings.HasPrefix(s, key+"=") {
251 boot.environ[i] = key + "=" + val
255 boot.environ = append(boot.environ, key+"="+val)
258 func (boot *bootCommand) installGoProgram(ctx context.Context, srcpath string) error {
260 defer boot.goMutex.Unlock()
261 return boot.RunProgram(ctx, filepath.Join(boot.sourcePath, srcpath), nil, []string{"GOPATH=" + boot.libPath}, "go", "install")
264 func (boot *bootCommand) setupRubyEnv() error {
265 buf, err := exec.Command("gem", "env", "gempath").Output() // /var/lib/arvados/.gem/ruby/2.5.0/bin:...
266 if err != nil || len(buf) == 0 {
267 return fmt.Errorf("gem env gempath: %v", err)
269 gempath := string(bytes.Split(buf, []byte{':'})[0])
270 boot.prependEnv("PATH", gempath+"/bin:")
271 boot.setEnv("GEM_HOME", gempath)
272 boot.setEnv("GEM_PATH", gempath)
276 func (boot *bootCommand) lookPath(prog string) string {
277 for _, val := range boot.environ {
278 if strings.HasPrefix(val, "PATH=") {
279 for _, dir := range filepath.SplitList(val[5:]) {
280 path := filepath.Join(dir, prog)
281 if fi, err := os.Stat(path); err == nil && fi.Mode()&0111 != 0 {
290 // Run prog with args, using dir as working directory. If ctx is
291 // cancelled while the child is running, RunProgram terminates the
292 // child, waits for it to exit, then returns.
294 // Child's environment will have our env vars, plus any given in env.
296 // Child's stdout will be written to output if non-nil, otherwise the
297 // boot command's stderr.
298 func (boot *bootCommand) RunProgram(ctx context.Context, dir string, output io.Writer, env []string, prog string, args ...string) error {
299 cmdline := fmt.Sprintf("%s", append([]string{prog}, args...))
300 fmt.Fprintf(boot.stderr, "%s executing in %s\n", cmdline, dir)
301 cmd := exec.Command(boot.lookPath(prog), args...)
303 cmd.Stdout = boot.stderr
307 cmd.Stderr = boot.stderr
308 if strings.HasPrefix(dir, "/") {
311 cmd.Dir = filepath.Join(boot.sourcePath, dir)
313 cmd.Env = append(env, boot.environ...)
316 log := ctxlog.FromContext(ctx).WithFields(logrus.Fields{"dir": dir, "cmdline": cmdline})
317 for cmd.ProcessState == nil {
318 // Child hasn't exited yet
319 if cmd.Process == nil {
320 log.Infof("waiting for child process to start")
321 time.Sleep(time.Second)
323 log.WithField("PID", cmd.Process.Pid).Info("sending SIGTERM")
324 cmd.Process.Signal(syscall.SIGTERM)
325 log.WithField("PID", cmd.Process.Pid).Info("waiting for child process to exit after SIGTERM")
326 time.Sleep(5 * time.Second)
332 return fmt.Errorf("%s: error: %v", cmdline, err)
337 type component struct {
340 cmdHandler cmd.Handler
341 runFunc func(ctx context.Context, boot *bootCommand, stdout, stderr io.Writer) error
342 railsApp string // source dir in arvados tree, e.g., "services/api"
343 goProg string // source dir in arvados tree, e.g., "services/keepstore"
344 notIfTest bool // don't run this component on a test cluster
347 func (cmpt *component) Run(ctx context.Context, boot *bootCommand, stdout, stderr io.Writer) error {
348 if cmpt.notIfTest && boot.clusterType == "test" {
349 fmt.Fprintf(stderr, "skipping component %q in %s mode\n", cmpt.name, boot.clusterType)
353 fmt.Fprintf(stderr, "starting component %q\n", cmpt.name)
354 if cmpt.cmdHandler != nil {
355 errs := make(chan error, 1)
358 exitcode := cmpt.cmdHandler.RunCommand(cmpt.name, []string{"-config", boot.configfile}, bytes.NewBuffer(nil), stdout, stderr)
360 errs <- fmt.Errorf("exit code %d", exitcode)
367 // cmpt.cmdHandler.RunCommand() doesn't have
368 // access to our context, so it won't shut
369 // down by itself. We just abandon it.
373 if cmpt.goProg != "" {
374 boot.RunProgram(ctx, cmpt.goProg, nil, nil, "go", "install")
375 if ctx.Err() != nil {
378 _, basename := filepath.Split(cmpt.goProg)
379 if len(cmpt.svc.InternalURLs) > 0 {
380 // Run one for each URL
381 var wg sync.WaitGroup
382 for u := range cmpt.svc.InternalURLs {
387 boot.RunProgram(ctx, boot.tempdir, nil, []string{"ARVADOS_SERVICE_INTERNAL_URL=" + u.String()}, basename)
393 boot.RunProgram(ctx, boot.tempdir, nil, nil, basename)
397 if cmpt.runFunc != nil {
398 return cmpt.runFunc(ctx, boot, stdout, stderr)
400 if cmpt.railsApp != "" {
401 port, err := internalPort(cmpt.svc)
403 return fmt.Errorf("bug: no InternalURLs for component %q: %v", cmpt.name, cmpt.svc.InternalURLs)
406 err = boot.RunProgram(ctx, cmpt.railsApp, &buf, nil, "gem", "list", "--details", "bundler")
410 for _, version := range []string{"1.11.0", "1.17.3", "2.0.2"} {
411 if !strings.Contains(buf.String(), "("+version+")") {
412 err = boot.RunProgram(ctx, cmpt.railsApp, nil, nil, "gem", "install", "--user", "bundler:1.11", "bundler:1.17.3", "bundler:2.0.2")
419 err = boot.RunProgram(ctx, cmpt.railsApp, nil, nil, "bundle", "install", "--jobs", "4", "--path", filepath.Join(os.Getenv("HOME"), ".gem"))
423 err = boot.RunProgram(ctx, cmpt.railsApp, nil, nil, "bundle", "exec", "passenger-config", "build-native-support")
427 err = boot.RunProgram(ctx, cmpt.railsApp, nil, nil, "bundle", "exec", "passenger-config", "install-standalone-runtime")
431 err = boot.RunProgram(ctx, cmpt.railsApp, nil, nil, "bundle", "exec", "passenger-config", "validate-install")
435 err = boot.RunProgram(ctx, cmpt.railsApp, nil, nil, "bundle", "exec", "passenger", "start", "-p", port)
440 return fmt.Errorf("bug: component %q has nothing to run", cmpt.name)
443 func (boot *bootCommand) autofillConfig(cfg *arvados.Config, log logrus.FieldLogger) error {
444 cluster, err := cfg.GetCluster("")
449 for _, svc := range []*arvados.Service{
450 &cluster.Services.Controller,
451 &cluster.Services.DispatchCloud,
452 &cluster.Services.GitHTTP,
453 &cluster.Services.Health,
454 &cluster.Services.Keepproxy,
455 &cluster.Services.Keepstore,
456 &cluster.Services.RailsAPI,
457 &cluster.Services.WebDAV,
458 &cluster.Services.WebDAVDownload,
459 &cluster.Services.Websocket,
461 if svc == &cluster.Services.DispatchCloud && boot.clusterType == "test" {
464 if len(svc.InternalURLs) == 0 {
466 svc.InternalURLs = map[arvados.URL]arvados.ServiceInstance{
467 arvados.URL{Scheme: "http", Host: fmt.Sprintf("localhost:%d", port)}: arvados.ServiceInstance{},
470 if svc.ExternalURL.Host == "" && (svc == &cluster.Services.Controller ||
471 svc == &cluster.Services.GitHTTP ||
472 svc == &cluster.Services.Keepproxy ||
473 svc == &cluster.Services.WebDAV ||
474 svc == &cluster.Services.WebDAVDownload ||
475 svc == &cluster.Services.Websocket) {
477 svc.ExternalURL = arvados.URL{Scheme: "https", Host: fmt.Sprintf("localhost:%d", port)}
480 if cluster.SystemRootToken == "" {
481 cluster.SystemRootToken = randomHexString(64)
483 if cluster.ManagementToken == "" {
484 cluster.ManagementToken = randomHexString(64)
486 if cluster.API.RailsSessionSecretToken == "" {
487 cluster.API.RailsSessionSecretToken = randomHexString(64)
489 if cluster.Collections.BlobSigningKey == "" {
490 cluster.Collections.BlobSigningKey = randomHexString(64)
492 if boot.clusterType != "production" && cluster.Containers.DispatchPrivateKey == "" {
493 buf, err := ioutil.ReadFile(filepath.Join(boot.sourcePath, "lib", "dispatchcloud", "test", "sshkey_dispatch"))
497 cluster.Containers.DispatchPrivateKey = string(buf)
499 if boot.clusterType != "production" {
500 cluster.TLS.Insecure = true
502 if boot.clusterType == "test" {
503 // Add a second keepstore process.
505 cluster.Services.Keepstore.InternalURLs[arvados.URL{Scheme: "http", Host: fmt.Sprintf("localhost:%d", port)}] = arvados.ServiceInstance{}
507 // Create a directory-backed volume for each keepstore
509 cluster.Volumes = map[string]arvados.Volume{}
510 for url := range cluster.Services.Keepstore.InternalURLs {
511 volnum := len(cluster.Volumes)
512 datadir := fmt.Sprintf("%s/keep%d.data", boot.tempdir, volnum)
513 if _, err = os.Stat(datadir + "/."); err == nil {
514 } else if !os.IsNotExist(err) {
516 } else if err = os.Mkdir(datadir, 0777); err != nil {
519 cluster.Volumes[fmt.Sprintf("zzzzz-nyw5e-%015d", volnum)] = arvados.Volume{
521 DriverParameters: json.RawMessage(fmt.Sprintf(`{"Root":%q}`, datadir)),
522 AccessViaHosts: map[arvados.URL]arvados.VolumeAccess{
528 cfg.Clusters[cluster.ClusterID] = *cluster
532 func randomHexString(chars int) string {
533 b := make([]byte, chars/2)
534 _, err := rand.Read(b)
538 return fmt.Sprintf("%x", b)
541 func internalPort(svc arvados.Service) (string, error) {
542 for u := range svc.InternalURLs {
543 if _, p, err := net.SplitHostPort(u.Host); err != nil {
547 } else if u.Scheme == "https" {
553 return "", fmt.Errorf("service has no InternalURLs")
556 func externalPort(svc arvados.Service) (string, error) {
557 if _, p, err := net.SplitHostPort(svc.ExternalURL.Host); err != nil {
561 } else if svc.ExternalURL.Scheme == "https" {