- // Fill in any missing config keys, and write the resulting
- // config in the temp dir for child services to use.
- err = boot.autofillConfig(cfg, boot.logger)
- if err != nil {
- return err
- }
- conffile, err := os.OpenFile(filepath.Join(boot.tempdir, "config.yml"), os.O_CREATE|os.O_WRONLY, 0777)
- if err != nil {
- return err
- }
- defer conffile.Close()
- err = json.NewEncoder(conffile).Encode(cfg)
- if err != nil {
- return err
- }
- err = conffile.Close()
- if err != nil {
- return err
- }
- boot.configfile = conffile.Name()
-
- boot.environ = os.Environ()
- boot.setEnv("ARVADOS_CONFIG", boot.configfile)
- boot.setEnv("RAILS_ENV", boot.ClusterType)
- boot.prependEnv("PATH", filepath.Join(boot.LibPath, "bin")+":")
-
- boot.cluster, err = cfg.GetCluster("")
- if err != nil {
- return err
- }
- // Now that we have the config, replace the bootstrap logger
- // with a new one according to the logging config.
- boot.logger = ctxlog.New(boot.Stderr, boot.cluster.SystemLogs.Format, boot.cluster.SystemLogs.LogLevel).WithFields(logrus.Fields{
- "PID": os.Getpid(),
- })
- boot.healthChecker = &health.Aggregator{Cluster: boot.cluster}
-
- for _, dir := range []string{boot.LibPath, filepath.Join(boot.LibPath, "bin")} {
- if _, err = os.Stat(filepath.Join(dir, ".")); os.IsNotExist(err) {
- err = os.Mkdir(dir, 0755)
- if err != nil {
- return err
- }
- } else if err != nil {
- return err
- }
- }
- err = boot.installGoProgram(boot.ctx, "cmd/arvados-server")
- if err != nil {
- return err
- }
- err = boot.setupRubyEnv()
- if err != nil {
- return err
- }
-
- tasks := []bootTask{
- createCertificates{},
- runPostgreSQL{},
- runNginx{},
- runServiceCommand{name: "controller", command: controller.Command, depends: []bootTask{runPostgreSQL{}}},
- runGoProgram{src: "services/arv-git-httpd"},
- runGoProgram{src: "services/health"},
- runGoProgram{src: "services/keepproxy"},
- runGoProgram{src: "services/keepstore", svc: boot.cluster.Services.Keepstore},
- runGoProgram{src: "services/keep-web"},
- runGoProgram{src: "services/ws", depends: []bootTask{runPostgreSQL{}}},
- installPassenger{src: "services/api"},
- runPassenger{src: "services/api", svc: boot.cluster.Services.RailsAPI, depends: []bootTask{createCertificates{}, runPostgreSQL{}, installPassenger{src: "services/api"}}},
- installPassenger{src: "apps/workbench"},
- runPassenger{src: "apps/workbench", svc: boot.cluster.Services.Workbench1, depends: []bootTask{installPassenger{src: "apps/workbench"}}},
- seedDatabase{},
- }
- if boot.ClusterType != "test" {
- tasks = append(tasks,
- runServiceCommand{name: "dispatchcloud", command: dispatchcloud.Command},
- runGoProgram{src: "services/keep-balance"},
- )
- }
- boot.tasksReady = map[string]chan bool{}
- for _, task := range tasks {
- boot.tasksReady[task.String()] = make(chan bool)
- }
- for _, task := range tasks {
- task := task
- fail := func(err error) {
- if boot.ctx.Err() != nil {
- return
- }
- boot.cancel()
- boot.logger.WithField("task", task).WithError(err).Error("task failed")
- }
- go func() {
- boot.logger.WithField("task", task).Info("starting")
- err := task.Run(boot.ctx, fail, boot)
- if err != nil {
- fail(err)
- return
- }
- close(boot.tasksReady[task.String()])
- }()
- }
- return boot.wait(boot.ctx, tasks...)
-}
-
-func (boot *Booter) wait(ctx context.Context, tasks ...bootTask) error {
- for _, task := range tasks {
- ch, ok := boot.tasksReady[task.String()]
- if !ok {
- return fmt.Errorf("no such task: %s", task)
- }
- boot.logger.WithField("task", task).Info("waiting")
- select {
- case <-ch:
- case <-ctx.Done():
- return ctx.Err()
- }
- }
- return nil
-}
-
-func (boot *Booter) Stop() {
- boot.cancel()
- <-boot.done
-}
-
-func (boot *Booter) WaitReady() bool {
- for waiting := true; waiting; {
- time.Sleep(time.Second)
- if boot.ctx.Err() != nil {
- return false
- }
- if boot.healthChecker == nil {
- // not set up yet
- continue
- }
- resp := boot.healthChecker.ClusterHealth()
- // The overall health check (resp.Health=="OK") might
- // never pass due to missing components (like
- // arvados-dispatch-cloud in a test cluster), so
- // instead we wait for all configured components to
- // pass.
- waiting = false
- for _, check := range resp.Checks {
- if check.Health != "OK" {
- waiting = true
- }
- }
- }
- return true
-}
-
-func (boot *Booter) prependEnv(key, prepend string) {
- for i, s := range boot.environ {
- if strings.HasPrefix(s, key+"=") {
- boot.environ[i] = key + "=" + prepend + s[len(key)+1:]
- return
- }
- }
- boot.environ = append(boot.environ, key+"="+prepend)
-}
-
-func (boot *Booter) setEnv(key, val string) {
- for i, s := range boot.environ {
- if strings.HasPrefix(s, key+"=") {
- boot.environ[i] = key + "=" + val
- return
- }
- }
- boot.environ = append(boot.environ, key+"="+val)
-}
-
-func (boot *Booter) installGoProgram(ctx context.Context, srcpath string) error {
- boot.goMutex.Lock()
- defer boot.goMutex.Unlock()
- return boot.RunProgram(ctx, filepath.Join(boot.SourcePath, srcpath), nil, []string{"GOPATH=" + boot.LibPath}, "go", "install")
-}
-
-func (boot *Booter) setupRubyEnv() error {
- buf, err := exec.Command("gem", "env", "gempath").Output() // /var/lib/arvados/.gem/ruby/2.5.0/bin:...
- if err != nil || len(buf) == 0 {
- return fmt.Errorf("gem env gempath: %v", err)
- }
- gempath := string(bytes.Split(buf, []byte{':'})[0])
- boot.prependEnv("PATH", gempath+"/bin:")
- boot.setEnv("GEM_HOME", gempath)
- boot.setEnv("GEM_PATH", gempath)
- return nil
-}
-
-func (boot *Booter) lookPath(prog string) string {
- for _, val := range boot.environ {
- if strings.HasPrefix(val, "PATH=") {
- for _, dir := range filepath.SplitList(val[5:]) {
- path := filepath.Join(dir, prog)
- if fi, err := os.Stat(path); err == nil && fi.Mode()&0111 != 0 {
- return path
- }
- }
- }
- }
- return prog
-}
-
-// Run prog with args, using dir as working directory. If ctx is
-// cancelled while the child is running, RunProgram terminates the
-// child, waits for it to exit, then returns.
-//
-// Child's environment will have our env vars, plus any given in env.
-//
-// Child's stdout will be written to output if non-nil, otherwise the
-// boot command's stderr.
-func (boot *Booter) RunProgram(ctx context.Context, dir string, output io.Writer, env []string, prog string, args ...string) error {
- cmdline := fmt.Sprintf("%s", append([]string{prog}, args...))
- fmt.Fprintf(boot.Stderr, "%s executing in %s\n", cmdline, dir)
- cmd := exec.Command(boot.lookPath(prog), args...)
- if output == nil {
- cmd.Stdout = boot.Stderr
- } else {
- cmd.Stdout = output
- }
- cmd.Stderr = boot.Stderr
- if strings.HasPrefix(dir, "/") {
- cmd.Dir = dir
- } else {
- cmd.Dir = filepath.Join(boot.SourcePath, dir)
- }
- cmd.Env = append(env, boot.environ...)
-
- exited := false
- defer func() { exited = true }()
- go func() {
- <-ctx.Done()
- log := ctxlog.FromContext(ctx).WithFields(logrus.Fields{"dir": dir, "cmdline": cmdline})
- for !exited {
- if cmd.Process == nil {
- log.Debug("waiting for child process to start")
- time.Sleep(time.Second / 2)
- } else {
- log.WithField("PID", cmd.Process.Pid).Debug("sending SIGTERM")
- cmd.Process.Signal(syscall.SIGTERM)
- time.Sleep(5 * time.Second)
- if !exited {
- log.WithField("PID", cmd.Process.Pid).Warn("still waiting for child process to exit 5s after SIGTERM")
- }
- }
- }
- }()
-
- err := cmd.Run()
- if err != nil && ctx.Err() == nil {
- // Only report errors that happen before the context ends.
- return fmt.Errorf("%s: error: %v", cmdline, err)
- }
- return nil
-}
-
-func (boot *Booter) autofillConfig(cfg *arvados.Config, log logrus.FieldLogger) error {
- cluster, err := cfg.GetCluster("")
- if err != nil {
- return err
- }
- port := 9000
- for _, svc := range []*arvados.Service{
- &cluster.Services.Controller,
- &cluster.Services.DispatchCloud,
- &cluster.Services.GitHTTP,
- &cluster.Services.Health,
- &cluster.Services.Keepproxy,
- &cluster.Services.Keepstore,
- &cluster.Services.RailsAPI,
- &cluster.Services.WebDAV,
- &cluster.Services.WebDAVDownload,
- &cluster.Services.Websocket,
- &cluster.Services.Workbench1,
- } {
- if svc == &cluster.Services.DispatchCloud && boot.ClusterType == "test" {
- continue
- }
- if len(svc.InternalURLs) == 0 {
- port++
- svc.InternalURLs = map[arvados.URL]arvados.ServiceInstance{
- arvados.URL{Scheme: "http", Host: fmt.Sprintf("localhost:%d", port)}: arvados.ServiceInstance{},
- }
- }
- if svc.ExternalURL.Host == "" && (svc == &cluster.Services.Controller ||
- svc == &cluster.Services.GitHTTP ||
- svc == &cluster.Services.Keepproxy ||
- svc == &cluster.Services.WebDAV ||
- svc == &cluster.Services.WebDAVDownload ||
- svc == &cluster.Services.Websocket ||
- svc == &cluster.Services.Workbench1) {
- port++
- svc.ExternalURL = arvados.URL{Scheme: "https", Host: fmt.Sprintf("localhost:%d", port)}
- }
- }
- if cluster.SystemRootToken == "" {
- cluster.SystemRootToken = randomHexString(64)
- }
- if cluster.ManagementToken == "" {
- cluster.ManagementToken = randomHexString(64)
- }
- if cluster.API.RailsSessionSecretToken == "" {
- cluster.API.RailsSessionSecretToken = randomHexString(64)
- }
- if cluster.Collections.BlobSigningKey == "" {
- cluster.Collections.BlobSigningKey = randomHexString(64)
- }
- if boot.ClusterType != "production" && cluster.Containers.DispatchPrivateKey == "" {
- buf, err := ioutil.ReadFile(filepath.Join(boot.SourcePath, "lib", "dispatchcloud", "test", "sshkey_dispatch"))
- if err != nil {
- return err
- }
- cluster.Containers.DispatchPrivateKey = string(buf)
- }
- if boot.ClusterType != "production" {
- cluster.TLS.Insecure = true
- }
- if boot.ClusterType == "test" {
- // Add a second keepstore process.
- port++
- cluster.Services.Keepstore.InternalURLs[arvados.URL{Scheme: "http", Host: fmt.Sprintf("localhost:%d", port)}] = arvados.ServiceInstance{}
-
- // Create a directory-backed volume for each keepstore
- // process.
- cluster.Volumes = map[string]arvados.Volume{}
- for url := range cluster.Services.Keepstore.InternalURLs {
- volnum := len(cluster.Volumes)
- datadir := fmt.Sprintf("%s/keep%d.data", boot.tempdir, volnum)
- if _, err = os.Stat(datadir + "/."); err == nil {
- } else if !os.IsNotExist(err) {
- return err
- } else if err = os.Mkdir(datadir, 0777); err != nil {
- return err
- }
- cluster.Volumes[fmt.Sprintf("zzzzz-nyw5e-%015d", volnum)] = arvados.Volume{
- Driver: "Directory",
- DriverParameters: json.RawMessage(fmt.Sprintf(`{"Root":%q}`, datadir)),
- AccessViaHosts: map[arvados.URL]arvados.VolumeAccess{
- url: {},
- },
- }
- }
- }
- if boot.OwnTemporaryDatabase {
- p, err := availablePort()
- if err != nil {
- return err
- }
- cluster.PostgreSQL.Connection = arvados.PostgreSQLConnection{
- "client_encoding": "utf8",
- "host": "localhost",
- "port": strconv.Itoa(p),
- "dbname": "arvados_test",
- "user": "arvados",
- "password": "insecure_arvados_test",
- }
- }
-
- cfg.Clusters[cluster.ClusterID] = *cluster
- return nil
-}
-
-func randomHexString(chars int) string {
- b := make([]byte, chars/2)
- _, err := rand.Read(b)
- if err != nil {
- panic(err)
- }
- return fmt.Sprintf("%x", b)
-}