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 "github.com/sirupsen/logrus"
35 var Command cmd.Handler = &bootCommand{}
37 type bootCommand struct {
38 sourcePath string // e.g., /home/username/src/arvados
39 libPath string // e.g., /var/lib/arvados
40 clusterType string // e.g., production
42 cluster *arvados.Cluster
48 setupRubyOnce sync.Once
53 func (boot *bootCommand) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
56 log := ctxlog.New(stderr, "json", "info")
61 log.WithError(err).Info("exiting")
65 flags := flag.NewFlagSet(prog, flag.ContinueOnError)
66 flags.SetOutput(stderr)
67 loader := config.NewLoader(stdin, log)
68 loader.SetupFlags(flags)
69 versionFlag := flags.Bool("version", false, "Write version information to stdout and exit 0")
70 flags.StringVar(&boot.sourcePath, "source", ".", "arvados source tree `directory`")
71 flags.StringVar(&boot.libPath, "lib", "/var/lib/arvados", "`directory` to install dependencies and library files")
72 flags.StringVar(&boot.clusterType, "type", "production", "cluster `type`: development, test, or production")
73 err = flags.Parse(args)
74 if err == flag.ErrHelp {
77 } else if err != nil {
79 } else if *versionFlag {
80 return cmd.Version.RunCommand(prog, args, stdin, stdout, stderr)
81 } else if boot.clusterType != "development" && boot.clusterType != "test" && boot.clusterType != "production" {
82 err = fmt.Errorf("cluster type must be 'development', 'test', or 'production'")
86 cwd, err := os.Getwd()
90 if !strings.HasPrefix(boot.sourcePath, "/") {
91 boot.sourcePath = filepath.Join(cwd, boot.sourcePath)
93 boot.sourcePath, err = filepath.EvalSymlinks(boot.sourcePath)
98 loader.SkipAPICalls = true
99 cfg, err := loader.Load()
104 boot.tempdir, err = ioutil.TempDir("", "arvados-server-boot-")
108 defer os.RemoveAll(boot.tempdir)
110 // Fill in any missing config keys, and write the resulting
111 // config in the temp dir for child services to use.
112 err = boot.autofillConfig(cfg, log)
116 conffile, err := os.OpenFile(filepath.Join(boot.tempdir, "config.yml"), os.O_CREATE|os.O_WRONLY, 0777)
120 defer conffile.Close()
121 err = json.NewEncoder(conffile).Encode(cfg)
125 err = conffile.Close()
129 os.Setenv("ARVADOS_CONFIG", conffile.Name())
130 arvados.DefaultConfigFile = conffile.Name()
131 os.Setenv("RAILS_ENV", boot.clusterType)
133 // Now that we have the config, replace the bootstrap logger
134 // with a new one according to the logging config.
135 boot.cluster, err = cfg.GetCluster("")
139 log = ctxlog.New(stderr, boot.cluster.SystemLogs.Format, boot.cluster.SystemLogs.LogLevel)
140 logger := log.WithFields(logrus.Fields{
143 ctx := ctxlog.Context(context.Background(), logger)
144 ctx, cancel := context.WithCancel(ctx)
147 ch := make(chan os.Signal)
148 signal.Notify(ch, syscall.SIGINT)
150 for sig := range ch {
151 logger.WithField("signal", sig).Info("caught signal")
156 for _, dir := range []string{boot.libPath, filepath.Join(boot.libPath, "bin")} {
157 if _, err = os.Stat(filepath.Join(dir, ".")); os.IsNotExist(err) {
158 err = os.Mkdir(dir, 0755)
162 } else if err != nil {
166 os.Setenv("PATH", filepath.Join(boot.libPath, "bin")+":"+os.Getenv("PATH"))
168 err = boot.installGoProgram(ctx, "cmd/arvados-server")
173 var wg sync.WaitGroup
174 for _, cmpt := range []component{
175 {name: "nginx", runFunc: runNginx},
176 {name: "controller", cmdHandler: controller.Command},
177 {name: "dispatchcloud", cmdHandler: dispatchcloud.Command, notIfTest: true},
178 {name: "git-httpd", goProg: "services/arv-git-httpd"},
179 {name: "health", goProg: "services/health"},
180 {name: "keep-balance", goProg: "services/keep-balance", notIfTest: true},
181 {name: "keepproxy", goProg: "services/keepproxy"},
182 {name: "keepstore", goProg: "services/keepstore", svc: boot.cluster.Services.Keepstore},
183 {name: "keep-web", goProg: "services/keep-web"},
184 {name: "railsAPI", svc: boot.cluster.Services.RailsAPI, railsApp: "services/api"},
185 {name: "ws", goProg: "services/ws"},
192 logger.WithField("component", cmpt.name).Info("starting")
193 err := cmpt.Run(ctx, boot, stdout, stderr)
195 logger.WithError(err).WithField("component", cmpt.name).Info("exited")
204 func (boot *bootCommand) installGoProgram(ctx context.Context, srcpath string) error {
206 defer boot.goMutex.Unlock()
207 return boot.RunProgram(ctx, filepath.Join(boot.sourcePath, srcpath), nil, []string{"GOPATH=" + boot.libPath}, "go", "install")
210 func (boot *bootCommand) setupRubyEnv() error {
211 boot.setupRubyOnce.Do(func() {
212 buf, err := exec.Command("gem", "env", "gempath").Output() // /var/lib/arvados/.gem/ruby/2.5.0/bin:...
213 if err != nil || len(buf) == 0 {
214 boot.setupRubyErr = fmt.Errorf("gem env gempath: %v", err)
216 gempath := string(bytes.Split(buf, []byte{':'})[0])
217 os.Setenv("PATH", gempath+"/bin:"+os.Getenv("PATH"))
218 os.Setenv("GEM_HOME", gempath)
219 os.Setenv("GEM_PATH", gempath)
221 return boot.setupRubyErr
224 func (boot *bootCommand) RunProgram(ctx context.Context, dir string, output io.Writer, env []string, prog string, args ...string) error {
225 cmdline := fmt.Sprintf("%s", append([]string{prog}, args...))
226 fmt.Fprintf(boot.stderr, "%s executing in %s\n", cmdline, dir)
227 cmd := exec.Command(prog, args...)
229 cmd.Stdout = boot.stderr
233 cmd.Stderr = boot.stderr
234 if strings.HasPrefix(dir, "/") {
237 cmd.Dir = filepath.Join(boot.sourcePath, dir)
240 cmd.Env = append(env, os.Environ()...)
244 log := ctxlog.FromContext(ctx).WithFields(logrus.Fields{"dir": dir, "cmdline": cmdline})
245 for cmd.ProcessState == nil {
246 if cmd.Process == nil {
247 log.Infof("waiting for child process to start")
248 time.Sleep(time.Second)
250 cmd.Process.Signal(syscall.SIGTERM)
251 log.WithField("PID", cmd.Process.Pid).Infof("waiting for child process to exit after SIGTERM")
252 time.Sleep(5 * time.Second)
258 return fmt.Errorf("%s: error: %v", cmdline, err)
263 type component struct {
266 cmdHandler cmd.Handler
267 runFunc func(ctx context.Context, boot *bootCommand, stdout, stderr io.Writer) error
268 railsApp string // source dir in arvados tree, e.g., "services/api"
269 goProg string // source dir in arvados tree, e.g., "services/keepstore"
270 notIfTest bool // don't run this component on a test cluster
273 func (cmpt *component) Run(ctx context.Context, boot *bootCommand, stdout, stderr io.Writer) error {
274 if cmpt.notIfTest && boot.clusterType == "test" {
275 fmt.Fprintf(stderr, "skipping component %q in %s mode\n", cmpt.name, boot.clusterType)
279 fmt.Fprintf(stderr, "starting component %q\n", cmpt.name)
280 if cmpt.cmdHandler != nil {
281 errs := make(chan error, 1)
284 exitcode := cmpt.cmdHandler.RunCommand(cmpt.name, nil, bytes.NewBuffer(nil), stdout, stderr)
286 errs <- fmt.Errorf("exit code %d", exitcode)
293 // cmpt.cmdHandler.RunCommand() doesn't have
294 // access to our context, so it won't shut
295 // down by itself. We just abandon it.
299 if cmpt.goProg != "" {
300 if len(cmpt.svc.InternalURLs) > 0 {
301 // Run one for each URL
302 var wg sync.WaitGroup
303 for u := range cmpt.svc.InternalURLs {
308 boot.RunProgram(ctx, cmpt.goProg, nil, []string{"ARVADOS_SERVICE_INTERNAL_URL=" + u.String()}, "go", "run", ".")
315 return boot.RunProgram(ctx, cmpt.goProg, nil, nil, "go", "run", ".")
318 if cmpt.runFunc != nil {
319 return cmpt.runFunc(ctx, boot, stdout, stderr)
321 if cmpt.railsApp != "" {
322 port, err := internalPort(cmpt.svc)
324 return fmt.Errorf("bug: no InternalURLs for component %q: %v", cmpt.name, cmpt.svc.InternalURLs)
326 err = boot.setupRubyEnv()
331 err = boot.RunProgram(ctx, cmpt.railsApp, &buf, nil, "gem", "list", "--details", "bundler")
335 for _, version := range []string{"1.11.0", "1.17.3", "2.0.2"} {
336 if !strings.Contains(buf.String(), "("+version+")") {
337 err = boot.RunProgram(ctx, cmpt.railsApp, nil, nil, "gem", "install", "--user", "bundler:1.11", "bundler:1.17.3", "bundler:2.0.2")
344 err = boot.RunProgram(ctx, cmpt.railsApp, nil, nil, "bundle", "install", "--jobs", "4", "--path", filepath.Join(os.Getenv("HOME"), ".gem"))
348 err = boot.RunProgram(ctx, cmpt.railsApp, nil, nil, "bundle", "exec", "passenger-config", "build-native-support")
352 err = boot.RunProgram(ctx, cmpt.railsApp, nil, nil, "bundle", "exec", "passenger-config", "install-standalone-runtime")
356 err = boot.RunProgram(ctx, cmpt.railsApp, nil, nil, "bundle", "exec", "passenger-config", "validate-install")
360 err = boot.RunProgram(ctx, cmpt.railsApp, nil, nil, "bundle", "exec", "passenger", "start", "-p", port)
365 return fmt.Errorf("bug: component %q has nothing to run", cmpt.name)
368 func (boot *bootCommand) autofillConfig(cfg *arvados.Config, log logrus.FieldLogger) error {
369 cluster, err := cfg.GetCluster("")
374 for _, svc := range []*arvados.Service{
375 &cluster.Services.Controller,
376 &cluster.Services.DispatchCloud,
377 &cluster.Services.GitHTTP,
378 &cluster.Services.Health,
379 &cluster.Services.Keepproxy,
380 &cluster.Services.Keepstore,
381 &cluster.Services.RailsAPI,
382 &cluster.Services.WebDAV,
383 &cluster.Services.WebDAVDownload,
384 &cluster.Services.Websocket,
386 if svc == &cluster.Services.DispatchCloud && boot.clusterType == "test" {
389 if len(svc.InternalURLs) == 0 {
391 svc.InternalURLs = map[arvados.URL]arvados.ServiceInstance{
392 arvados.URL{Scheme: "http", Host: fmt.Sprintf("localhost:%d", port)}: arvados.ServiceInstance{},
395 if svc.ExternalURL.Host == "" && (svc == &cluster.Services.Controller ||
396 svc == &cluster.Services.GitHTTP ||
397 svc == &cluster.Services.Keepproxy ||
398 svc == &cluster.Services.WebDAV ||
399 svc == &cluster.Services.WebDAVDownload ||
400 svc == &cluster.Services.Websocket) {
402 svc.ExternalURL = arvados.URL{Scheme: "https", Host: fmt.Sprintf("localhost:%d", port)}
405 if cluster.SystemRootToken == "" {
406 cluster.SystemRootToken = randomHexString(64)
408 if cluster.ManagementToken == "" {
409 cluster.ManagementToken = randomHexString(64)
411 if cluster.API.RailsSessionSecretToken == "" {
412 cluster.API.RailsSessionSecretToken = randomHexString(64)
414 if cluster.Collections.BlobSigningKey == "" {
415 cluster.Collections.BlobSigningKey = randomHexString(64)
417 if boot.clusterType != "production" && cluster.Containers.DispatchPrivateKey == "" {
418 buf, err := ioutil.ReadFile(filepath.Join(boot.sourcePath, "lib", "dispatchcloud", "test", "sshkey_dispatch"))
422 cluster.Containers.DispatchPrivateKey = string(buf)
424 if boot.clusterType != "production" {
425 cluster.TLS.Insecure = true
427 if boot.clusterType == "test" {
429 cluster.Services.Keepstore.InternalURLs[arvados.URL{Scheme: "http", Host: fmt.Sprintf("localhost:%d", port)}] = arvados.ServiceInstance{}
432 for url := range cluster.Services.Keepstore.InternalURLs {
434 datadir := fmt.Sprintf("%s/keep%d.data", boot.tempdir, n)
435 if _, err = os.Stat(datadir + "/."); err == nil {
436 } else if !os.IsNotExist(err) {
438 } else if err = os.Mkdir(datadir, 0777); err != nil {
441 cluster.Volumes = map[string]arvados.Volume{
442 fmt.Sprintf("zzzzz-nyw5e-%015d", n): arvados.Volume{
444 DriverParameters: json.RawMessage(fmt.Sprintf(`{"Root":%q}`, datadir)),
445 AccessViaHosts: map[arvados.URL]arvados.VolumeAccess{
452 cfg.Clusters[cluster.ClusterID] = *cluster
456 func randomHexString(chars int) string {
457 b := make([]byte, chars/2)
458 _, err := rand.Read(b)
462 return fmt.Sprintf("%x", b)
465 func internalPort(svc arvados.Service) (string, error) {
466 for u := range svc.InternalURLs {
467 if _, p, err := net.SplitHostPort(u.Host); err != nil {
471 } else if u.Scheme == "https" {
477 return "", fmt.Errorf("service has no InternalURLs")
480 func externalPort(svc arvados.Service) (string, error) {
481 if _, p, err := net.SplitHostPort(svc.ExternalURL.Host); err != nil {
485 } else if svc.ExternalURL.Scheme == "https" {