1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
29 "git.arvados.org/arvados.git/lib/config"
30 "git.arvados.org/arvados.git/lib/service"
31 "git.arvados.org/arvados.git/sdk/go/arvados"
32 "git.arvados.org/arvados.git/sdk/go/ctxlog"
33 "git.arvados.org/arvados.git/sdk/go/health"
34 "github.com/fsnotify/fsnotify"
35 "github.com/sirupsen/logrus"
38 type Supervisor struct {
39 SourcePath string // e.g., /home/username/src/arvados
40 SourceVersion string // e.g., acbd1324...
41 ClusterType string // e.g., production
42 ListenHost string // e.g., localhost
43 ControllerAddr string // e.g., 127.0.0.1:8000
44 OwnTemporaryDatabase bool
47 logger logrus.FieldLogger
48 cluster *arvados.Cluster
51 cancel context.CancelFunc
52 done chan struct{} // closed when child procs/services have shut down
53 err error // error that caused shutdown (valid when done is closed)
54 healthChecker *health.Aggregator
55 tasksReady map[string]chan bool
56 waitShutdown sync.WaitGroup
62 environ []string // for child processes
65 func (super *Supervisor) Start(ctx context.Context, cfg *arvados.Config, cfgPath string) {
66 super.ctx, super.cancel = context.WithCancel(ctx)
67 super.done = make(chan struct{})
70 defer close(super.done)
72 sigch := make(chan os.Signal)
73 signal.Notify(sigch, syscall.SIGINT, syscall.SIGTERM)
74 defer signal.Stop(sigch)
76 for sig := range sigch {
77 super.logger.WithField("signal", sig).Info("caught signal")
79 super.err = fmt.Errorf("caught signal %s", sig)
85 hupch := make(chan os.Signal)
86 signal.Notify(hupch, syscall.SIGHUP)
87 defer signal.Stop(hupch)
89 for sig := range hupch {
90 super.logger.WithField("signal", sig).Info("caught signal")
92 super.err = errNeedConfigReload
98 if cfgPath != "" && cfgPath != "-" && cfg.AutoReloadConfig {
99 go watchConfig(super.ctx, super.logger, cfgPath, copyConfig(cfg), func() {
100 if super.err == nil {
101 super.err = errNeedConfigReload
107 err := super.run(cfg)
109 super.logger.WithError(err).Warn("supervisor shut down")
110 if super.err == nil {
117 func (super *Supervisor) Wait() error {
122 func (super *Supervisor) run(cfg *arvados.Config) error {
125 cwd, err := os.Getwd()
129 if !strings.HasPrefix(super.SourcePath, "/") {
130 super.SourcePath = filepath.Join(cwd, super.SourcePath)
132 super.SourcePath, err = filepath.EvalSymlinks(super.SourcePath)
137 // Choose bin and temp dirs: /var/lib/arvados/... in
138 // production, transient tempdir otherwise.
139 if super.ClusterType == "production" {
140 // These dirs have already been created by
141 // "arvados-server install" (or by extracting a
143 super.tempdir = "/var/lib/arvados/tmp"
144 super.wwwtempdir = "/var/lib/arvados/wwwtmp"
145 super.bindir = "/var/lib/arvados/bin"
147 super.tempdir, err = ioutil.TempDir("", "arvados-server-boot-")
151 defer os.RemoveAll(super.tempdir)
152 super.wwwtempdir = super.tempdir
153 super.bindir = filepath.Join(super.tempdir, "bin")
154 if err := os.Mkdir(super.bindir, 0755); err != nil {
159 // Fill in any missing config keys, and write the resulting
160 // config in the temp dir for child services to use.
161 err = super.autofillConfig(cfg)
165 conffile, err := os.OpenFile(filepath.Join(super.wwwtempdir, "config.yml"), os.O_CREATE|os.O_WRONLY, 0644)
169 defer conffile.Close()
170 err = json.NewEncoder(conffile).Encode(cfg)
174 err = conffile.Close()
178 super.configfile = conffile.Name()
180 super.environ = os.Environ()
181 super.cleanEnv([]string{"ARVADOS_"})
182 super.setEnv("ARVADOS_CONFIG", super.configfile)
183 super.setEnv("RAILS_ENV", super.ClusterType)
184 super.setEnv("TMPDIR", super.tempdir)
185 super.prependEnv("PATH", "/var/lib/arvados/bin:")
186 if super.ClusterType != "production" {
187 super.prependEnv("PATH", super.tempdir+"/bin:")
190 super.cluster, err = cfg.GetCluster("")
194 // Now that we have the config, replace the bootstrap logger
195 // with a new one according to the logging config.
196 loglevel := super.cluster.SystemLogs.LogLevel
197 if s := os.Getenv("ARVADOS_DEBUG"); s != "" && s != "0" {
200 super.logger = ctxlog.New(super.Stderr, super.cluster.SystemLogs.Format, loglevel).WithFields(logrus.Fields{
204 if super.SourceVersion == "" && super.ClusterType == "production" {
205 // don't need SourceVersion
206 } else if super.SourceVersion == "" {
207 // Find current source tree version.
209 err = super.RunProgram(super.ctx, ".", &buf, nil, "git", "diff", "--shortstat")
213 dirty := buf.Len() > 0
215 err = super.RunProgram(super.ctx, ".", &buf, nil, "git", "log", "-n1", "--format=%H")
219 super.SourceVersion = strings.TrimSpace(buf.String())
221 super.SourceVersion += "+uncommitted"
224 return errors.New("specifying a version to run is not yet supported")
227 _, err = super.installGoProgram(super.ctx, "cmd/arvados-server")
231 err = super.setupRubyEnv()
236 tasks := []supervisedTask{
237 createCertificates{},
240 runServiceCommand{name: "controller", svc: super.cluster.Services.Controller, depends: []supervisedTask{runPostgreSQL{}}},
241 runGoProgram{src: "services/arv-git-httpd", svc: super.cluster.Services.GitHTTP},
242 runGoProgram{src: "services/health", svc: super.cluster.Services.Health},
243 runGoProgram{src: "services/keepproxy", svc: super.cluster.Services.Keepproxy, depends: []supervisedTask{runPassenger{src: "services/api"}}},
244 runGoProgram{src: "services/keepstore", svc: super.cluster.Services.Keepstore},
245 runGoProgram{src: "services/keep-web", svc: super.cluster.Services.WebDAV},
246 runServiceCommand{name: "ws", svc: super.cluster.Services.Websocket, depends: []supervisedTask{runPostgreSQL{}}},
247 installPassenger{src: "services/api"},
248 runPassenger{src: "services/api", varlibdir: "railsapi", svc: super.cluster.Services.RailsAPI, depends: []supervisedTask{createCertificates{}, runPostgreSQL{}, installPassenger{src: "services/api"}}},
249 installPassenger{src: "apps/workbench", depends: []supervisedTask{installPassenger{src: "services/api"}}}, // dependency ensures workbench doesn't delay api startup
250 runPassenger{src: "apps/workbench", varlibdir: "workbench1", svc: super.cluster.Services.Workbench1, depends: []supervisedTask{installPassenger{src: "apps/workbench"}}},
253 if super.ClusterType != "test" {
254 tasks = append(tasks,
255 runServiceCommand{name: "dispatch-cloud", svc: super.cluster.Services.DispatchCloud},
256 runGoProgram{src: "services/keep-balance", svc: super.cluster.Services.Keepbalance},
259 super.tasksReady = map[string]chan bool{}
260 for _, task := range tasks {
261 super.tasksReady[task.String()] = make(chan bool)
263 for _, task := range tasks {
265 fail := func(err error) {
266 if super.ctx.Err() != nil {
270 super.logger.WithField("task", task.String()).WithError(err).Error("task failed")
273 super.logger.WithField("task", task.String()).Info("starting")
274 err := task.Run(super.ctx, fail, super)
279 close(super.tasksReady[task.String()])
282 err = super.wait(super.ctx, tasks...)
286 super.logger.Info("all startup tasks are complete; starting health checks")
287 super.healthChecker = &health.Aggregator{Cluster: super.cluster}
289 super.logger.Info("shutting down")
290 super.waitShutdown.Wait()
291 return super.ctx.Err()
294 func (super *Supervisor) wait(ctx context.Context, tasks ...supervisedTask) error {
295 for _, task := range tasks {
296 ch, ok := super.tasksReady[task.String()]
298 return fmt.Errorf("no such task: %s", task)
300 super.logger.WithField("task", task.String()).Info("waiting")
303 super.logger.WithField("task", task.String()).Info("ready")
305 super.logger.WithField("task", task.String()).Info("task was never ready")
312 func (super *Supervisor) Stop() {
317 func (super *Supervisor) WaitReady() (*arvados.URL, bool) {
318 ticker := time.NewTicker(time.Second)
320 for waiting := "all"; waiting != ""; {
323 case <-super.ctx.Done():
326 if super.healthChecker == nil {
330 resp := super.healthChecker.ClusterHealth()
331 // The overall health check (resp.Health=="OK") might
332 // never pass due to missing components (like
333 // arvados-dispatch-cloud in a test cluster), so
334 // instead we wait for all configured components to
337 for target, check := range resp.Checks {
338 if check.Health != "OK" {
339 waiting += " " + target
343 super.logger.WithField("targets", waiting[1:]).Info("waiting")
346 u := super.cluster.Services.Controller.ExternalURL
350 func (super *Supervisor) prependEnv(key, prepend string) {
351 for i, s := range super.environ {
352 if strings.HasPrefix(s, key+"=") {
353 super.environ[i] = key + "=" + prepend + s[len(key)+1:]
357 super.environ = append(super.environ, key+"="+prepend)
360 func (super *Supervisor) cleanEnv(prefixes []string) {
362 for _, s := range super.environ {
364 for _, p := range prefixes {
365 if strings.HasPrefix(s, p) {
371 cleaned = append(cleaned, s)
374 super.environ = cleaned
377 func (super *Supervisor) setEnv(key, val string) {
378 for i, s := range super.environ {
379 if strings.HasPrefix(s, key+"=") {
380 super.environ[i] = key + "=" + val
384 super.environ = append(super.environ, key+"="+val)
387 // Remove all but the first occurrence of each env var.
388 func dedupEnv(in []string) []string {
389 saw := map[string]bool{}
391 for _, kv := range in {
392 if split := strings.Index(kv, "="); split < 1 {
393 panic("invalid environment var: " + kv)
394 } else if saw[kv[:split]] {
397 saw[kv[:split]] = true
398 out = append(out, kv)
404 func (super *Supervisor) installGoProgram(ctx context.Context, srcpath string) (string, error) {
405 _, basename := filepath.Split(srcpath)
406 binfile := filepath.Join(super.bindir, basename)
407 if super.ClusterType == "production" {
410 err := super.RunProgram(ctx, filepath.Join(super.SourcePath, srcpath), nil, []string{"GOBIN=" + super.bindir}, "go", "install", "-ldflags", "-X git.arvados.org/arvados.git/lib/cmd.version="+super.SourceVersion+" -X main.version="+super.SourceVersion)
414 func (super *Supervisor) usingRVM() bool {
415 return os.Getenv("rvm_path") != ""
418 func (super *Supervisor) setupRubyEnv() error {
419 if !super.usingRVM() {
420 // (If rvm is in use, assume the caller has everything
421 // set up as desired)
422 super.cleanEnv([]string{
427 if _, err := os.Stat("/var/lib/arvados/bin/gem"); err == nil || super.ClusterType == "production" {
428 gem = "/var/lib/arvados/bin/gem"
430 cmd := exec.Command(gem, "env", "gempath")
431 if super.ClusterType == "production" {
432 cmd.Args = append([]string{"sudo", "-u", "www-data", "-E", "HOME=/var/www"}, cmd.Args...)
433 path, err := exec.LookPath("sudo")
435 return fmt.Errorf("LookPath(\"sudo\"): %w", err)
439 cmd.Stderr = super.Stderr
440 cmd.Env = super.environ
441 buf, err := cmd.Output() // /var/lib/arvados/.gem/ruby/2.5.0/bin:...
442 if err != nil || len(buf) == 0 {
443 return fmt.Errorf("gem env gempath: %v", err)
445 gempath := string(bytes.Split(buf, []byte{':'})[0])
446 super.prependEnv("PATH", gempath+"/bin:")
447 super.setEnv("GEM_HOME", gempath)
448 super.setEnv("GEM_PATH", gempath)
450 // Passenger install doesn't work unless $HOME is ~user
451 u, err := user.Current()
455 super.setEnv("HOME", u.HomeDir)
459 func (super *Supervisor) lookPath(prog string) string {
460 for _, val := range super.environ {
461 if strings.HasPrefix(val, "PATH=") {
462 for _, dir := range filepath.SplitList(val[5:]) {
463 path := filepath.Join(dir, prog)
464 if fi, err := os.Stat(path); err == nil && fi.Mode()&0111 != 0 {
473 // RunProgram runs prog with args, using dir as working directory. If ctx is
474 // cancelled while the child is running, RunProgram terminates the child, waits
475 // for it to exit, then returns.
477 // Child's environment will have our env vars, plus any given in env.
479 // Child's stdout will be written to output if non-nil, otherwise the
480 // boot command's stderr.
481 func (super *Supervisor) RunProgram(ctx context.Context, dir string, output io.Writer, env []string, prog string, args ...string) error {
482 cmdline := fmt.Sprintf("%s", append([]string{prog}, args...))
483 super.logger.WithField("command", cmdline).WithField("dir", dir).Info("executing")
487 if logprefix == "setuidgid" && len(args) >= 3 {
491 if logprefix == "sudo" {
492 for i := 0; i < len(args); i++ {
495 } else if args[i] == "-E" || strings.Contains(args[i], "=") {
498 innerargs = args[i+1:]
503 logprefix = strings.TrimPrefix(logprefix, "/var/lib/arvados/bin/")
504 logprefix = strings.TrimPrefix(logprefix, super.tempdir+"/bin/")
505 if logprefix == "bundle" && len(innerargs) > 2 && innerargs[0] == "exec" {
506 _, dirbase := filepath.Split(dir)
507 logprefix = innerargs[1] + "@" + dirbase
508 } else if logprefix == "arvados-server" && len(args) > 1 {
511 if !strings.HasPrefix(dir, "/") {
512 logprefix = dir + ": " + logprefix
516 cmd := exec.Command(super.lookPath(prog), args...)
517 stdout, err := cmd.StdoutPipe()
521 stderr, err := cmd.StderrPipe()
525 logwriter := &service.LogPrefixer{Writer: super.Stderr, Prefix: []byte("[" + logprefix + "] ")}
526 var copiers sync.WaitGroup
529 io.Copy(logwriter, stderr)
535 io.Copy(logwriter, stdout)
537 io.Copy(output, stdout)
542 if strings.HasPrefix(dir, "/") {
545 cmd.Dir = filepath.Join(super.SourcePath, dir)
547 env = append([]string(nil), env...)
548 env = append(env, super.environ...)
549 cmd.Env = dedupEnv(env)
552 defer func() { exited = true }()
555 log := ctxlog.FromContext(ctx).WithFields(logrus.Fields{"dir": dir, "cmdline": cmdline})
557 if cmd.Process == nil {
558 log.Debug("waiting for child process to start")
559 time.Sleep(time.Second / 2)
561 log.WithField("PID", cmd.Process.Pid).Debug("sending SIGTERM")
562 cmd.Process.Signal(syscall.SIGTERM)
563 time.Sleep(5 * time.Second)
567 log.WithField("PID", cmd.Process.Pid).Warn("still waiting for child process to exit 5s after SIGTERM")
579 if ctx.Err() != nil {
580 // Return "context canceled", instead of the "killed"
581 // error that was probably caused by the context being
584 } else if err != nil {
585 return fmt.Errorf("%s: error: %v", cmdline, err)
590 func (super *Supervisor) autofillConfig(cfg *arvados.Config) error {
591 cluster, err := cfg.GetCluster("")
595 usedPort := map[string]bool{}
596 nextPort := func(host string) string {
598 port, err := availablePort(host)
605 usedPort[port] = true
609 if cluster.Services.Controller.ExternalURL.Host == "" {
610 h, p, err := net.SplitHostPort(super.ControllerAddr)
620 cluster.Services.Controller.ExternalURL = arvados.URL{Scheme: "https", Host: net.JoinHostPort(h, p), Path: "/"}
622 for _, svc := range []*arvados.Service{
623 &cluster.Services.Controller,
624 &cluster.Services.DispatchCloud,
625 &cluster.Services.GitHTTP,
626 &cluster.Services.Health,
627 &cluster.Services.Keepproxy,
628 &cluster.Services.Keepstore,
629 &cluster.Services.RailsAPI,
630 &cluster.Services.WebDAV,
631 &cluster.Services.WebDAVDownload,
632 &cluster.Services.Websocket,
633 &cluster.Services.Workbench1,
635 if svc == &cluster.Services.DispatchCloud && super.ClusterType == "test" {
638 if svc.ExternalURL.Host == "" {
639 if svc == &cluster.Services.Controller ||
640 svc == &cluster.Services.GitHTTP ||
641 svc == &cluster.Services.Health ||
642 svc == &cluster.Services.Keepproxy ||
643 svc == &cluster.Services.WebDAV ||
644 svc == &cluster.Services.WebDAVDownload ||
645 svc == &cluster.Services.Workbench1 {
646 svc.ExternalURL = arvados.URL{Scheme: "https", Host: fmt.Sprintf("%s:%s", super.ListenHost, nextPort(super.ListenHost)), Path: "/"}
647 } else if svc == &cluster.Services.Websocket {
648 svc.ExternalURL = arvados.URL{Scheme: "wss", Host: fmt.Sprintf("%s:%s", super.ListenHost, nextPort(super.ListenHost)), Path: "/websocket"}
651 if len(svc.InternalURLs) == 0 {
652 svc.InternalURLs = map[arvados.URL]arvados.ServiceInstance{
653 {Scheme: "http", Host: fmt.Sprintf("%s:%s", super.ListenHost, nextPort(super.ListenHost)), Path: "/"}: {},
657 if super.ClusterType != "production" {
658 if cluster.SystemRootToken == "" {
659 cluster.SystemRootToken = randomHexString(64)
661 if cluster.ManagementToken == "" {
662 cluster.ManagementToken = randomHexString(64)
664 if cluster.API.RailsSessionSecretToken == "" {
665 cluster.API.RailsSessionSecretToken = randomHexString(64)
667 if cluster.Collections.BlobSigningKey == "" {
668 cluster.Collections.BlobSigningKey = randomHexString(64)
670 if cluster.Containers.DispatchPrivateKey == "" {
671 buf, err := ioutil.ReadFile(filepath.Join(super.SourcePath, "lib", "dispatchcloud", "test", "sshkey_dispatch"))
675 cluster.Containers.DispatchPrivateKey = string(buf)
677 cluster.TLS.Insecure = true
679 if super.ClusterType == "test" {
680 // Add a second keepstore process.
681 cluster.Services.Keepstore.InternalURLs[arvados.URL{Scheme: "http", Host: fmt.Sprintf("%s:%s", super.ListenHost, nextPort(super.ListenHost)), Path: "/"}] = arvados.ServiceInstance{}
683 // Create a directory-backed volume for each keepstore
685 cluster.Volumes = map[string]arvados.Volume{}
686 for url := range cluster.Services.Keepstore.InternalURLs {
687 volnum := len(cluster.Volumes)
688 datadir := fmt.Sprintf("%s/keep%d.data", super.tempdir, volnum)
689 if _, err = os.Stat(datadir + "/."); err == nil {
690 } else if !os.IsNotExist(err) {
692 } else if err = os.Mkdir(datadir, 0755); err != nil {
695 cluster.Volumes[fmt.Sprintf(cluster.ClusterID+"-nyw5e-%015d", volnum)] = arvados.Volume{
697 DriverParameters: json.RawMessage(fmt.Sprintf(`{"Root":%q}`, datadir)),
698 AccessViaHosts: map[arvados.URL]arvados.VolumeAccess{
704 if super.OwnTemporaryDatabase {
705 cluster.PostgreSQL.Connection = arvados.PostgreSQLConnection{
706 "client_encoding": "utf8",
708 "port": nextPort(super.ListenHost),
709 "dbname": "arvados_test",
711 "password": "insecure_arvados_test",
715 cfg.Clusters[cluster.ClusterID] = *cluster
719 func addrIsLocal(addr string) (bool, error) {
721 listener, err := net.Listen("tcp", addr)
725 } else if strings.Contains(err.Error(), "cannot assign requested address") {
732 func randomHexString(chars int) string {
733 b := make([]byte, chars/2)
734 _, err := rand.Read(b)
738 return fmt.Sprintf("%x", b)
741 func internalPort(svc arvados.Service) (string, error) {
742 if len(svc.InternalURLs) > 1 {
743 return "", errors.New("internalPort() doesn't work with multiple InternalURLs")
745 for u := range svc.InternalURLs {
747 if p := u.Port(); p != "" {
749 } else if u.Scheme == "https" || u.Scheme == "ws" {
755 return "", fmt.Errorf("service has no InternalURLs")
758 func externalPort(svc arvados.Service) (string, error) {
759 u := url.URL(svc.ExternalURL)
760 if p := u.Port(); p != "" {
762 } else if u.Scheme == "https" || u.Scheme == "wss" {
769 func availablePort(host string) (string, error) {
770 ln, err := net.Listen("tcp", net.JoinHostPort(host, "0"))
775 _, port, err := net.SplitHostPort(ln.Addr().String())
782 // Try to connect to addr until it works, then close ch. Give up if
784 func waitForConnect(ctx context.Context, addr string) error {
785 dialer := net.Dialer{Timeout: time.Second}
786 for ctx.Err() == nil {
787 conn, err := dialer.DialContext(ctx, "tcp", addr)
789 time.Sleep(time.Second / 10)
798 func copyConfig(cfg *arvados.Config) *arvados.Config {
801 err := json.NewEncoder(pw).Encode(cfg)
807 cfg2 := new(arvados.Config)
808 err := json.NewDecoder(pr).Decode(cfg2)
815 func watchConfig(ctx context.Context, logger logrus.FieldLogger, cfgPath string, prevcfg *arvados.Config, fn func()) {
816 watcher, err := fsnotify.NewWatcher()
818 logger.WithError(err).Error("fsnotify setup failed")
821 defer watcher.Close()
823 err = watcher.Add(cfgPath)
825 logger.WithError(err).Error("fsnotify watcher failed")
833 case err, ok := <-watcher.Errors:
837 logger.WithError(err).Warn("fsnotify watcher reported error")
838 case _, ok := <-watcher.Events:
842 for len(watcher.Events) > 0 {
845 loader := config.NewLoader(&bytes.Buffer{}, &logrus.Logger{Out: ioutil.Discard})
846 loader.Path = cfgPath
847 loader.SkipAPICalls = true
848 cfg, err := loader.Load()
850 logger.WithError(err).Warn("error reloading config file after change detected; ignoring new config for now")
851 } else if reflect.DeepEqual(cfg, prevcfg) {
852 logger.Debug("config file changed but is still DeepEqual to the existing config")
854 logger.Debug("config changed, notifying supervisor")