1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
30 "git.arvados.org/arvados.git/lib/config"
31 "git.arvados.org/arvados.git/lib/service"
32 "git.arvados.org/arvados.git/sdk/go/arvados"
33 "git.arvados.org/arvados.git/sdk/go/ctxlog"
34 "git.arvados.org/arvados.git/sdk/go/health"
35 "github.com/fsnotify/fsnotify"
36 "github.com/sirupsen/logrus"
39 type Supervisor struct {
40 SourcePath string // e.g., /home/username/src/arvados
41 SourceVersion string // e.g., acbd1324...
42 ClusterType string // e.g., production
43 ListenHost string // e.g., localhost
44 ControllerAddr string // e.g., 127.0.0.1:8000
46 OwnTemporaryDatabase bool
49 logger logrus.FieldLogger
50 cluster *arvados.Cluster
53 cancel context.CancelFunc
54 done chan struct{} // closed when child procs/services have shut down
55 err error // error that caused shutdown (valid when done is closed)
56 healthChecker *health.Aggregator
57 tasksReady map[string]chan bool
58 waitShutdown sync.WaitGroup
64 environ []string // for child processes
67 func (super *Supervisor) Cluster() *arvados.Cluster { return super.cluster }
69 func (super *Supervisor) Start(ctx context.Context, cfg *arvados.Config, cfgPath string) {
70 super.ctx, super.cancel = context.WithCancel(ctx)
71 super.done = make(chan struct{})
74 defer close(super.done)
76 sigch := make(chan os.Signal)
77 signal.Notify(sigch, syscall.SIGINT, syscall.SIGTERM)
78 defer signal.Stop(sigch)
80 for sig := range sigch {
81 super.logger.WithField("signal", sig).Info("caught signal")
83 super.err = fmt.Errorf("caught signal %s", sig)
89 hupch := make(chan os.Signal)
90 signal.Notify(hupch, syscall.SIGHUP)
91 defer signal.Stop(hupch)
93 for sig := range hupch {
94 super.logger.WithField("signal", sig).Info("caught signal")
96 super.err = errNeedConfigReload
102 if cfgPath != "" && cfgPath != "-" && cfg.AutoReloadConfig {
103 go watchConfig(super.ctx, super.logger, cfgPath, copyConfig(cfg), func() {
104 if super.err == nil {
105 super.err = errNeedConfigReload
111 err := super.run(cfg)
113 super.logger.WithError(err).Warn("supervisor shut down")
114 if super.err == nil {
121 func (super *Supervisor) Wait() error {
126 func (super *Supervisor) run(cfg *arvados.Config) error {
129 cwd, err := os.Getwd()
133 if !strings.HasPrefix(super.SourcePath, "/") {
134 super.SourcePath = filepath.Join(cwd, super.SourcePath)
136 super.SourcePath, err = filepath.EvalSymlinks(super.SourcePath)
141 // Choose bin and temp dirs: /var/lib/arvados/... in
142 // production, transient tempdir otherwise.
143 if super.ClusterType == "production" {
144 // These dirs have already been created by
145 // "arvados-server install" (or by extracting a
147 super.tempdir = "/var/lib/arvados/tmp"
148 super.wwwtempdir = "/var/lib/arvados/wwwtmp"
149 super.bindir = "/var/lib/arvados/bin"
151 super.tempdir, err = ioutil.TempDir("", "arvados-server-boot-")
155 defer os.RemoveAll(super.tempdir)
156 super.wwwtempdir = super.tempdir
157 super.bindir = filepath.Join(super.tempdir, "bin")
158 if err := os.Mkdir(super.bindir, 0755); err != nil {
163 // Fill in any missing config keys, and write the resulting
164 // config in the temp dir for child services to use.
165 err = super.autofillConfig(cfg)
169 conffile, err := os.OpenFile(filepath.Join(super.wwwtempdir, "config.yml"), os.O_CREATE|os.O_WRONLY, 0644)
173 defer conffile.Close()
174 err = json.NewEncoder(conffile).Encode(cfg)
178 err = conffile.Close()
182 super.configfile = conffile.Name()
184 super.environ = os.Environ()
185 super.cleanEnv([]string{"ARVADOS_"})
186 super.setEnv("ARVADOS_CONFIG", super.configfile)
187 super.setEnv("RAILS_ENV", super.ClusterType)
188 super.setEnv("TMPDIR", super.tempdir)
189 super.prependEnv("PATH", "/var/lib/arvados/bin:")
190 if super.ClusterType != "production" {
191 super.prependEnv("PATH", super.tempdir+"/bin:")
194 super.cluster, err = cfg.GetCluster("")
198 // Now that we have the config, replace the bootstrap logger
199 // with a new one according to the logging config.
200 loglevel := super.cluster.SystemLogs.LogLevel
201 if s := os.Getenv("ARVADOS_DEBUG"); s != "" && s != "0" {
204 super.logger = ctxlog.New(super.Stderr, super.cluster.SystemLogs.Format, loglevel).WithFields(logrus.Fields{
208 if super.SourceVersion == "" && super.ClusterType == "production" {
209 // don't need SourceVersion
210 } else if super.SourceVersion == "" {
211 // Find current source tree version.
213 err = super.RunProgram(super.ctx, ".", runOptions{output: &buf}, "git", "diff", "--shortstat")
217 dirty := buf.Len() > 0
219 err = super.RunProgram(super.ctx, ".", runOptions{output: &buf}, "git", "log", "-n1", "--format=%H")
223 super.SourceVersion = strings.TrimSpace(buf.String())
225 super.SourceVersion += "+uncommitted"
228 return errors.New("specifying a version to run is not yet supported")
231 _, err = super.installGoProgram(super.ctx, "cmd/arvados-server")
235 err = super.setupRubyEnv()
240 tasks := []supervisedTask{
241 createCertificates{},
244 runServiceCommand{name: "controller", svc: super.cluster.Services.Controller, depends: []supervisedTask{seedDatabase{}}},
245 runGoProgram{src: "services/arv-git-httpd", svc: super.cluster.Services.GitHTTP},
246 runGoProgram{src: "services/health", svc: super.cluster.Services.Health},
247 runGoProgram{src: "services/keepproxy", svc: super.cluster.Services.Keepproxy, depends: []supervisedTask{runPassenger{src: "services/api"}}},
248 runServiceCommand{name: "keepstore", svc: super.cluster.Services.Keepstore},
249 runGoProgram{src: "services/keep-web", svc: super.cluster.Services.WebDAV},
250 runServiceCommand{name: "ws", svc: super.cluster.Services.Websocket, depends: []supervisedTask{seedDatabase{}}},
251 installPassenger{src: "services/api"},
252 runPassenger{src: "services/api", varlibdir: "railsapi", svc: super.cluster.Services.RailsAPI, depends: []supervisedTask{createCertificates{}, seedDatabase{}, installPassenger{src: "services/api"}}},
255 if !super.NoWorkbench1 {
256 tasks = append(tasks,
257 installPassenger{src: "apps/workbench", depends: []supervisedTask{seedDatabase{}}}, // dependency ensures workbench doesn't delay api install/startup
258 runPassenger{src: "apps/workbench", varlibdir: "workbench1", svc: super.cluster.Services.Workbench1, depends: []supervisedTask{installPassenger{src: "apps/workbench"}}},
261 if super.ClusterType != "test" {
262 tasks = append(tasks,
263 runServiceCommand{name: "dispatch-cloud", svc: super.cluster.Services.DispatchCloud},
264 runGoProgram{src: "services/keep-balance", svc: super.cluster.Services.Keepbalance},
267 super.tasksReady = map[string]chan bool{}
268 for _, task := range tasks {
269 super.tasksReady[task.String()] = make(chan bool)
271 for _, task := range tasks {
273 fail := func(err error) {
274 if super.ctx.Err() != nil {
278 super.logger.WithField("task", task.String()).WithError(err).Error("task failed")
281 super.logger.WithField("task", task.String()).Info("starting")
282 err := task.Run(super.ctx, fail, super)
287 close(super.tasksReady[task.String()])
290 err = super.wait(super.ctx, tasks...)
294 super.logger.Info("all startup tasks are complete; starting health checks")
295 super.healthChecker = &health.Aggregator{Cluster: super.cluster}
297 super.logger.Info("shutting down")
298 super.waitShutdown.Wait()
299 return super.ctx.Err()
302 func (super *Supervisor) wait(ctx context.Context, tasks ...supervisedTask) error {
303 for _, task := range tasks {
304 ch, ok := super.tasksReady[task.String()]
306 return fmt.Errorf("no such task: %s", task)
308 super.logger.WithField("task", task.String()).Info("waiting")
311 super.logger.WithField("task", task.String()).Info("ready")
313 super.logger.WithField("task", task.String()).Info("task was never ready")
320 func (super *Supervisor) Stop() {
325 func (super *Supervisor) WaitReady() (*arvados.URL, bool) {
326 ticker := time.NewTicker(time.Second)
328 for waiting := "all"; waiting != ""; {
331 case <-super.ctx.Done():
334 if super.healthChecker == nil {
338 resp := super.healthChecker.ClusterHealth()
339 // The overall health check (resp.Health=="OK") might
340 // never pass due to missing components (like
341 // arvados-dispatch-cloud in a test cluster), so
342 // instead we wait for all configured components to
345 for target, check := range resp.Checks {
346 if check.Health != "OK" {
347 waiting += " " + target
351 super.logger.WithField("targets", waiting[1:]).Info("waiting")
354 u := super.cluster.Services.Controller.ExternalURL
358 func (super *Supervisor) prependEnv(key, prepend string) {
359 for i, s := range super.environ {
360 if strings.HasPrefix(s, key+"=") {
361 super.environ[i] = key + "=" + prepend + s[len(key)+1:]
365 super.environ = append(super.environ, key+"="+prepend)
368 func (super *Supervisor) cleanEnv(prefixes []string) {
370 for _, s := range super.environ {
372 for _, p := range prefixes {
373 if strings.HasPrefix(s, p) {
379 cleaned = append(cleaned, s)
382 super.environ = cleaned
385 func (super *Supervisor) setEnv(key, val string) {
386 for i, s := range super.environ {
387 if strings.HasPrefix(s, key+"=") {
388 super.environ[i] = key + "=" + val
392 super.environ = append(super.environ, key+"="+val)
395 // Remove all but the first occurrence of each env var.
396 func dedupEnv(in []string) []string {
397 saw := map[string]bool{}
399 for _, kv := range in {
400 if split := strings.Index(kv, "="); split < 1 {
401 panic("invalid environment var: " + kv)
402 } else if saw[kv[:split]] {
405 saw[kv[:split]] = true
406 out = append(out, kv)
412 func (super *Supervisor) installGoProgram(ctx context.Context, srcpath string) (string, error) {
413 _, basename := filepath.Split(srcpath)
414 binfile := filepath.Join(super.bindir, basename)
415 if super.ClusterType == "production" {
418 err := super.RunProgram(ctx, filepath.Join(super.SourcePath, srcpath), runOptions{env: []string{"GOBIN=" + super.bindir}}, "go", "install", "-ldflags", "-X git.arvados.org/arvados.git/lib/cmd.version="+super.SourceVersion+" -X main.version="+super.SourceVersion)
422 func (super *Supervisor) usingRVM() bool {
423 return os.Getenv("rvm_path") != ""
426 func (super *Supervisor) setupRubyEnv() error {
427 if !super.usingRVM() {
428 // (If rvm is in use, assume the caller has everything
429 // set up as desired)
430 super.cleanEnv([]string{
435 if _, err := os.Stat("/var/lib/arvados/bin/gem"); err == nil || super.ClusterType == "production" {
436 gem = "/var/lib/arvados/bin/gem"
438 cmd := exec.Command(gem, "env", "gempath")
439 if super.ClusterType == "production" {
440 cmd.Args = append([]string{"sudo", "-u", "www-data", "-E", "HOME=/var/www"}, cmd.Args...)
441 path, err := exec.LookPath("sudo")
443 return fmt.Errorf("LookPath(\"sudo\"): %w", err)
447 cmd.Stderr = super.Stderr
448 cmd.Env = super.environ
449 buf, err := cmd.Output() // /var/lib/arvados/.gem/ruby/2.5.0/bin:...
450 if err != nil || len(buf) == 0 {
451 return fmt.Errorf("gem env gempath: %w", err)
453 gempath := string(bytes.Split(buf, []byte{':'})[0])
454 super.prependEnv("PATH", gempath+"/bin:")
455 super.setEnv("GEM_HOME", gempath)
456 super.setEnv("GEM_PATH", gempath)
458 // Passenger install doesn't work unless $HOME is ~user
459 u, err := user.Current()
463 super.setEnv("HOME", u.HomeDir)
467 func (super *Supervisor) lookPath(prog string) string {
468 for _, val := range super.environ {
469 if strings.HasPrefix(val, "PATH=") {
470 for _, dir := range filepath.SplitList(val[5:]) {
471 path := filepath.Join(dir, prog)
472 if fi, err := os.Stat(path); err == nil && fi.Mode()&0111 != 0 {
481 type runOptions struct {
482 output io.Writer // attach stdout
483 env []string // add/replace environment variables
484 user string // run as specified user
487 // RunProgram runs prog with args, using dir as working directory. If ctx is
488 // cancelled while the child is running, RunProgram terminates the child, waits
489 // for it to exit, then returns.
491 // Child's environment will have our env vars, plus any given in env.
493 // Child's stdout will be written to output if non-nil, otherwise the
494 // boot command's stderr.
495 func (super *Supervisor) RunProgram(ctx context.Context, dir string, opts runOptions, prog string, args ...string) error {
496 cmdline := fmt.Sprintf("%s", append([]string{prog}, args...))
497 super.logger.WithField("command", cmdline).WithField("dir", dir).Info("executing")
502 if logprefix == "sudo" {
503 for i := 0; i < len(args); i++ {
506 } else if args[i] == "-E" || strings.Contains(args[i], "=") {
509 innerargs = args[i+1:]
514 logprefix = strings.TrimPrefix(logprefix, "/var/lib/arvados/bin/")
515 logprefix = strings.TrimPrefix(logprefix, super.tempdir+"/bin/")
516 if logprefix == "bundle" && len(innerargs) > 2 && innerargs[0] == "exec" {
517 _, dirbase := filepath.Split(dir)
518 logprefix = innerargs[1] + "@" + dirbase
519 } else if logprefix == "arvados-server" && len(args) > 1 {
522 if !strings.HasPrefix(dir, "/") {
523 logprefix = dir + ": " + logprefix
527 cmd := exec.Command(super.lookPath(prog), args...)
528 stdout, err := cmd.StdoutPipe()
532 stderr, err := cmd.StderrPipe()
536 logwriter := &service.LogPrefixer{Writer: super.Stderr, Prefix: []byte("[" + logprefix + "] ")}
537 var copiers sync.WaitGroup
540 io.Copy(logwriter, stderr)
545 if opts.output == nil {
546 io.Copy(logwriter, stdout)
548 io.Copy(opts.output, stdout)
553 if strings.HasPrefix(dir, "/") {
556 cmd.Dir = filepath.Join(super.SourcePath, dir)
558 env := append([]string(nil), opts.env...)
559 env = append(env, super.environ...)
560 cmd.Env = dedupEnv(env)
563 // Note: We use this approach instead of "sudo"
564 // because in certain circumstances (we are pid 1 in a
565 // docker container, and our passenger child process
566 // changes to pgid 1) the intermediate sudo process
567 // notices we have the same pgid as our child and
568 // refuses to propagate signals from us to our child,
569 // so we can't signal/shutdown our passenger/rails
570 // apps. "chpst" or "setuidgid" would work, but these
571 // few lines avoid depending on runit/daemontools.
572 u, err := user.Lookup(opts.user)
574 return fmt.Errorf("user.Lookup(%q): %w", opts.user, err)
576 uid, _ := strconv.Atoi(u.Uid)
577 gid, _ := strconv.Atoi(u.Gid)
578 cmd.SysProcAttr = &syscall.SysProcAttr{
579 Credential: &syscall.Credential{
587 defer func() { exited = true }()
590 log := ctxlog.FromContext(ctx).WithFields(logrus.Fields{"dir": dir, "cmdline": cmdline})
592 if cmd.Process == nil {
593 log.Debug("waiting for child process to start")
594 time.Sleep(time.Second / 2)
596 log.WithField("PID", cmd.Process.Pid).Debug("sending SIGTERM")
597 cmd.Process.Signal(syscall.SIGTERM)
598 time.Sleep(5 * time.Second)
602 log.WithField("PID", cmd.Process.Pid).Warn("still waiting for child process to exit 5s after SIGTERM")
614 if ctx.Err() != nil {
615 // Return "context canceled", instead of the "killed"
616 // error that was probably caused by the context being
619 } else if err != nil {
620 return fmt.Errorf("%s: error: %v", cmdline, err)
625 func (super *Supervisor) autofillConfig(cfg *arvados.Config) error {
626 cluster, err := cfg.GetCluster("")
630 usedPort := map[string]bool{}
631 nextPort := func(host string) string {
633 port, err := availablePort(host)
640 usedPort[port] = true
644 if cluster.Services.Controller.ExternalURL.Host == "" {
645 h, p, err := net.SplitHostPort(super.ControllerAddr)
655 cluster.Services.Controller.ExternalURL = arvados.URL{Scheme: "https", Host: net.JoinHostPort(h, p), Path: "/"}
657 for _, svc := range []*arvados.Service{
658 &cluster.Services.Controller,
659 &cluster.Services.DispatchCloud,
660 &cluster.Services.GitHTTP,
661 &cluster.Services.Health,
662 &cluster.Services.Keepproxy,
663 &cluster.Services.Keepstore,
664 &cluster.Services.RailsAPI,
665 &cluster.Services.WebDAV,
666 &cluster.Services.WebDAVDownload,
667 &cluster.Services.Websocket,
668 &cluster.Services.Workbench1,
670 if svc == &cluster.Services.DispatchCloud && super.ClusterType == "test" {
673 if svc.ExternalURL.Host == "" {
674 if svc == &cluster.Services.Controller ||
675 svc == &cluster.Services.GitHTTP ||
676 svc == &cluster.Services.Health ||
677 svc == &cluster.Services.Keepproxy ||
678 svc == &cluster.Services.WebDAV ||
679 svc == &cluster.Services.WebDAVDownload ||
680 svc == &cluster.Services.Workbench1 {
681 svc.ExternalURL = arvados.URL{Scheme: "https", Host: fmt.Sprintf("%s:%s", super.ListenHost, nextPort(super.ListenHost)), Path: "/"}
682 } else if svc == &cluster.Services.Websocket {
683 svc.ExternalURL = arvados.URL{Scheme: "wss", Host: fmt.Sprintf("%s:%s", super.ListenHost, nextPort(super.ListenHost)), Path: "/websocket"}
686 if super.NoWorkbench1 && svc == &cluster.Services.Workbench1 {
687 // When workbench1 is disabled, it gets an
688 // ExternalURL (so we have a valid listening
689 // port to write in our Nginx config) but no
690 // InternalURLs (so health checker doesn't
694 if len(svc.InternalURLs) == 0 {
695 svc.InternalURLs = map[arvados.URL]arvados.ServiceInstance{
696 {Scheme: "http", Host: fmt.Sprintf("%s:%s", super.ListenHost, nextPort(super.ListenHost)), Path: "/"}: {},
700 if super.ClusterType != "production" {
701 if cluster.SystemRootToken == "" {
702 cluster.SystemRootToken = randomHexString(64)
704 if cluster.ManagementToken == "" {
705 cluster.ManagementToken = randomHexString(64)
707 if cluster.Collections.BlobSigningKey == "" {
708 cluster.Collections.BlobSigningKey = randomHexString(64)
710 if cluster.Users.AnonymousUserToken == "" {
711 cluster.Users.AnonymousUserToken = randomHexString(64)
713 if cluster.Containers.DispatchPrivateKey == "" {
714 buf, err := ioutil.ReadFile(filepath.Join(super.SourcePath, "lib", "dispatchcloud", "test", "sshkey_dispatch"))
718 cluster.Containers.DispatchPrivateKey = string(buf)
720 cluster.TLS.Insecure = true
722 if super.ClusterType == "test" {
723 // Add a second keepstore process.
724 cluster.Services.Keepstore.InternalURLs[arvados.URL{Scheme: "http", Host: fmt.Sprintf("%s:%s", super.ListenHost, nextPort(super.ListenHost)), Path: "/"}] = arvados.ServiceInstance{}
726 // Create a directory-backed volume for each keepstore
728 cluster.Volumes = map[string]arvados.Volume{}
729 for url := range cluster.Services.Keepstore.InternalURLs {
730 volnum := len(cluster.Volumes)
731 datadir := fmt.Sprintf("%s/keep%d.data", super.tempdir, volnum)
732 if _, err = os.Stat(datadir + "/."); err == nil {
733 } else if !os.IsNotExist(err) {
735 } else if err = os.Mkdir(datadir, 0755); err != nil {
738 cluster.Volumes[fmt.Sprintf(cluster.ClusterID+"-nyw5e-%015d", volnum)] = arvados.Volume{
740 DriverParameters: json.RawMessage(fmt.Sprintf(`{"Root":%q}`, datadir)),
741 AccessViaHosts: map[arvados.URL]arvados.VolumeAccess{
744 StorageClasses: map[string]bool{
751 cluster.StorageClasses = map[string]arvados.StorageClassConfig{
752 "default": {Default: true},
757 if super.OwnTemporaryDatabase {
758 cluster.PostgreSQL.Connection = arvados.PostgreSQLConnection{
759 "client_encoding": "utf8",
760 "host": super.ListenHost,
761 "port": nextPort(super.ListenHost),
762 "dbname": "arvados_test",
764 "password": "insecure_arvados_test",
768 cfg.Clusters[cluster.ClusterID] = *cluster
772 func addrIsLocal(addr string) (bool, error) {
774 listener, err := net.Listen("tcp", addr)
778 } else if strings.Contains(err.Error(), "cannot assign requested address") {
785 func randomHexString(chars int) string {
786 b := make([]byte, chars/2)
787 _, err := rand.Read(b)
791 return fmt.Sprintf("%x", b)
794 func internalPort(svc arvados.Service) (host, port string, err error) {
795 if len(svc.InternalURLs) > 1 {
796 return "", "", errors.New("internalPort() doesn't work with multiple InternalURLs")
798 for u := range svc.InternalURLs {
800 host, port = u.Hostname(), u.Port()
803 case u.Scheme == "https", u.Scheme == "ws":
810 return "", "", fmt.Errorf("service has no InternalURLs")
813 func externalPort(svc arvados.Service) (string, error) {
814 u := url.URL(svc.ExternalURL)
815 if p := u.Port(); p != "" {
817 } else if u.Scheme == "https" || u.Scheme == "wss" {
824 func availablePort(host string) (string, error) {
825 ln, err := net.Listen("tcp", net.JoinHostPort(host, "0"))
830 _, port, err := net.SplitHostPort(ln.Addr().String())
837 // Try to connect to addr until it works, then close ch. Give up if
839 func waitForConnect(ctx context.Context, addr string) error {
840 dialer := net.Dialer{Timeout: time.Second}
841 for ctx.Err() == nil {
842 conn, err := dialer.DialContext(ctx, "tcp", addr)
844 time.Sleep(time.Second / 10)
853 func copyConfig(cfg *arvados.Config) *arvados.Config {
856 err := json.NewEncoder(pw).Encode(cfg)
862 cfg2 := new(arvados.Config)
863 err := json.NewDecoder(pr).Decode(cfg2)
870 func watchConfig(ctx context.Context, logger logrus.FieldLogger, cfgPath string, prevcfg *arvados.Config, fn func()) {
871 watcher, err := fsnotify.NewWatcher()
873 logger.WithError(err).Error("fsnotify setup failed")
876 defer watcher.Close()
878 err = watcher.Add(cfgPath)
880 logger.WithError(err).Error("fsnotify watcher failed")
888 case err, ok := <-watcher.Errors:
892 logger.WithError(err).Warn("fsnotify watcher reported error")
893 case _, ok := <-watcher.Events:
897 for len(watcher.Events) > 0 {
900 loader := config.NewLoader(&bytes.Buffer{}, &logrus.Logger{Out: ioutil.Discard})
901 loader.Path = cfgPath
902 loader.SkipAPICalls = true
903 cfg, err := loader.Load()
905 logger.WithError(err).Warn("error reloading config file after change detected; ignoring new config for now")
906 } else if reflect.DeepEqual(cfg, prevcfg) {
907 logger.Debug("config file changed but is still DeepEqual to the existing config")
909 logger.Debug("config changed, notifying supervisor")