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
45 setupRubyOnce sync.Once
50 func (boot *bootCommand) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
53 log := ctxlog.New(stderr, "json", "info")
58 log.WithError(err).Info("exiting")
62 flags := flag.NewFlagSet(prog, flag.ContinueOnError)
63 flags.SetOutput(stderr)
64 loader := config.NewLoader(stdin, log)
65 loader.SetupFlags(flags)
66 versionFlag := flags.Bool("version", false, "Write version information to stdout and exit 0")
67 flags.StringVar(&boot.sourcePath, "source", ".", "arvados source tree `directory`")
68 flags.StringVar(&boot.libPath, "lib", "/var/lib/arvados", "`directory` to install dependencies and library files")
69 flags.StringVar(&boot.clusterType, "type", "production", "cluster `type`: development, test, or production")
70 err = flags.Parse(args)
71 if err == flag.ErrHelp {
74 } else if err != nil {
76 } else if *versionFlag {
77 return cmd.Version.RunCommand(prog, args, stdin, stdout, stderr)
78 } else if boot.clusterType != "development" && boot.clusterType != "test" && boot.clusterType != "production" {
79 err = fmt.Errorf("cluster type must be 'development', 'test', or 'production'")
83 cwd, err := os.Getwd()
87 if !strings.HasPrefix(boot.sourcePath, "/") {
88 boot.sourcePath = filepath.Join(cwd, boot.sourcePath)
90 boot.sourcePath, err = filepath.EvalSymlinks(boot.sourcePath)
95 loader.SkipAPICalls = true
96 cfg, err := loader.Load()
101 tempdir, err := ioutil.TempDir("", "arvados-server-boot-")
105 defer os.RemoveAll(tempdir)
107 // Fill in any missing config keys, and write the resulting
108 // config in the temp dir for child services to use.
109 err = boot.autofillConfig(cfg, log)
113 conffile, err := os.OpenFile(filepath.Join(tempdir, "config.yml"), os.O_CREATE|os.O_WRONLY, 0777)
117 defer conffile.Close()
118 err = json.NewEncoder(conffile).Encode(cfg)
122 err = conffile.Close()
126 os.Setenv("ARVADOS_CONFIG", conffile.Name())
128 os.Setenv("RAILS_ENV", boot.clusterType)
130 // Now that we have the config, replace the bootstrap logger
131 // with a new one according to the logging config.
132 cluster, err := cfg.GetCluster("")
136 log = ctxlog.New(stderr, cluster.SystemLogs.Format, cluster.SystemLogs.LogLevel)
137 logger := log.WithFields(logrus.Fields{
140 ctx := ctxlog.Context(context.Background(), logger)
141 ctx, cancel := context.WithCancel(ctx)
144 ch := make(chan os.Signal)
145 signal.Notify(ch, syscall.SIGINT)
147 for sig := range ch {
148 logger.WithField("signal", sig).Info("caught signal")
153 for _, dir := range []string{boot.libPath, filepath.Join(boot.libPath, "bin")} {
154 if _, err = os.Stat(filepath.Join(dir, ".")); os.IsNotExist(err) {
155 err = os.Mkdir(dir, 0755)
159 } else if err != nil {
163 os.Setenv("PATH", filepath.Join(boot.libPath, "bin")+":"+os.Getenv("PATH"))
165 err = boot.installGoProgram(ctx, "cmd/arvados-server")
170 var wg sync.WaitGroup
171 for _, cmpt := range []component{
172 {name: "controller", cmdHandler: controller.Command},
173 {name: "dispatchcloud", cmdHandler: dispatchcloud.Command, notIfTest: true},
174 {name: "keepproxy", goProg: "services/keepproxy"},
175 {name: "railsAPI", svc: cluster.Services.RailsAPI, railsApp: "services/api"},
182 logger.WithField("component", cmpt.name).Info("starting")
183 err := cmpt.Run(ctx, boot, stdout, stderr)
185 logger.WithError(err).WithField("component", cmpt.name).Info("exited")
194 func (boot *bootCommand) installGoProgram(ctx context.Context, srcpath string) error {
196 defer boot.goMutex.Unlock()
197 env := append([]string{"GOPATH=" + boot.libPath}, os.Environ()...)
198 return boot.RunProgram(ctx, filepath.Join(boot.sourcePath, srcpath), nil, env, "go", "install")
201 func (boot *bootCommand) setupRubyEnv() error {
202 boot.setupRubyOnce.Do(func() {
203 buf, err := exec.Command("gem", "env", "gempath").Output() // /var/lib/arvados/.gem/ruby/2.5.0/bin:...
204 if err != nil || len(buf) == 0 {
205 boot.setupRubyErr = fmt.Errorf("gem env gempath: %v", err)
207 gempath := string(bytes.Split(buf, []byte{':'})[0])
208 os.Setenv("PATH", gempath+"/bin:"+os.Getenv("PATH"))
209 os.Setenv("GEM_HOME", gempath)
210 os.Setenv("GEM_PATH", gempath)
212 return boot.setupRubyErr
215 func (boot *bootCommand) RunProgram(ctx context.Context, dir string, output io.Writer, env []string, prog string, args ...string) error {
216 cmdline := fmt.Sprintf("%s", append([]string{prog}, args...))
217 fmt.Fprintf(boot.stderr, "%s executing in %s\n", cmdline, dir)
218 cmd := exec.Command(prog, args...)
220 cmd.Stdout = boot.stderr
224 cmd.Stderr = boot.stderr
225 if strings.HasPrefix(dir, "/") {
228 cmd.Dir = filepath.Join(boot.sourcePath, dir)
235 log := ctxlog.FromContext(ctx).WithFields(logrus.Fields{"dir": dir, "cmdline": cmdline})
236 for cmd.ProcessState != nil {
237 if cmd.Process == nil {
238 log.Infof("waiting for child process to start")
239 time.Sleep(time.Second)
241 cmd.Process.Signal(syscall.SIGINT)
242 log.WithField("PID", cmd.Process.Pid).Infof("waiting for child process to exit after SIGINT")
243 time.Sleep(5 * time.Second)
249 return fmt.Errorf("%s: error: %v", cmdline, err)
254 type component struct {
257 cmdHandler cmd.Handler
258 railsApp string // source dir in arvados tree, e.g., "services/api"
259 goProg string // source dir in arvados tree, e.g., "services/keepstore"
260 notIfTest bool // don't run this component on a test cluster
263 func (cmpt *component) Run(ctx context.Context, boot *bootCommand, stdout, stderr io.Writer) error {
264 if cmpt.notIfTest && boot.clusterType == "test" {
265 fmt.Fprintf(stderr, "skipping component %q\n", cmpt.name)
269 fmt.Fprintf(stderr, "starting component %q\n", cmpt.name)
270 if cmpt.cmdHandler != nil {
271 errs := make(chan error, 1)
274 exitcode := cmpt.cmdHandler.RunCommand(cmpt.name, nil, bytes.NewBuffer(nil), stdout, stderr)
276 errs <- fmt.Errorf("exit code %d", exitcode)
283 // cmpt.cmdHandler.RunCommand() doesn't have
284 // access to our context, so it won't shut
285 // down by itself. We just abandon it.
289 if cmpt.goProg != "" {
290 return boot.RunProgram(ctx, cmpt.goProg, nil, nil, "go", "run", ".")
292 if cmpt.railsApp != "" {
294 for u := range cmpt.svc.InternalURLs {
295 if _, p, err := net.SplitHostPort(u.Host); err != nil {
299 } else if u.Scheme == "https" {
307 return fmt.Errorf("bug: no InternalURLs for component %q: %v", cmpt.name, cmpt.svc.InternalURLs)
310 err := boot.setupRubyEnv()
315 err = boot.RunProgram(ctx, cmpt.railsApp, &buf, nil, "gem", "list", "--details", "bundler")
319 for _, version := range []string{"1.11.0", "1.17.3", "2.0.2"} {
320 if !strings.Contains(buf.String(), "("+version+")") {
321 err = boot.RunProgram(ctx, cmpt.railsApp, nil, nil, "gem", "install", "--user", "bundler:1.11", "bundler:1.17.3", "bundler:2.0.2")
328 err = boot.RunProgram(ctx, cmpt.railsApp, nil, nil, "bundle", "install", "--jobs", "4", "--path", filepath.Join(os.Getenv("HOME"), ".gem"))
332 err = boot.RunProgram(ctx, cmpt.railsApp, nil, nil, "bundle", "exec", "passenger-config", "build-native-support")
336 err = boot.RunProgram(ctx, cmpt.railsApp, nil, nil, "bundle", "exec", "passenger-config", "install-standalone-runtime")
340 err = boot.RunProgram(ctx, cmpt.railsApp, nil, nil, "bundle", "exec", "passenger-config", "validate-install")
344 err = boot.RunProgram(ctx, cmpt.railsApp, nil, nil, "bundle", "exec", "passenger", "start", "-p", port)
349 return fmt.Errorf("bug: component %q has nothing to run", cmpt.name)
352 func (boot *bootCommand) autofillConfig(cfg *arvados.Config, log logrus.FieldLogger) error {
353 cluster, err := cfg.GetCluster("")
358 for _, svc := range []*arvados.Service{
359 &cluster.Services.Controller,
360 &cluster.Services.DispatchCloud,
361 &cluster.Services.RailsAPI,
363 if len(svc.InternalURLs) == 0 {
365 svc.InternalURLs = map[arvados.URL]arvados.ServiceInstance{
366 arvados.URL{Scheme: "http", Host: fmt.Sprintf("localhost:%d", port)}: arvados.ServiceInstance{},
370 if cluster.Services.Controller.ExternalURL.Host == "" {
371 for k := range cluster.Services.Controller.InternalURLs {
372 cluster.Services.Controller.ExternalURL = k
375 if cluster.SystemRootToken == "" {
376 cluster.SystemRootToken = randomHexString(64)
378 if cluster.API.RailsSessionSecretToken == "" {
379 cluster.API.RailsSessionSecretToken = randomHexString(64)
381 if cluster.Collections.BlobSigningKey == "" {
382 cluster.Collections.BlobSigningKey = randomHexString(64)
384 if boot.clusterType != "production" && cluster.Containers.DispatchPrivateKey == "" {
385 buf, err := ioutil.ReadFile(filepath.Join(boot.sourcePath, "lib", "dispatchcloud", "test", "sshkey_dispatch"))
389 cluster.Containers.DispatchPrivateKey = string(buf)
391 cfg.Clusters[cluster.ClusterID] = *cluster
395 func randomHexString(chars int) string {
396 b := make([]byte, chars/2)
397 _, err := rand.Read(b)
401 return fmt.Sprintf("%x", b)