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 // Config file location like "/etc/arvados/config.yml", or "-"
41 // to read from Stdin (see below).
43 // Literal config file (useful for test suites). If non-empty,
44 // this is used instead of ConfigPath.
46 // Path to arvados source tree. Only used for dev/test
49 // Version number to build into binaries. Only used for
52 // "production", "development", or "test".
54 // Listening address for external services, and internal
55 // services whose InternalURLs are not explicitly configured.
56 // If blank, listen on the configured controller ExternalURL
57 // host; if that is also blank, listen on all addresses
60 // Default host:port for controller ExternalURL if not
61 // explicitly configured in config file. If blank, use a
62 // random port on ListenHost.
64 // Path to arvados-workbench2 source tree checkout.
65 Workbench2Source string
68 OwnTemporaryDatabase bool
72 logger logrus.FieldLogger
73 cluster *arvados.Cluster // nil if this is a multi-cluster supervisor
74 children map[string]*Supervisor // nil if this is a single-cluster supervisor
77 cancel context.CancelFunc
78 done chan struct{} // closed when child procs/services have shut down
79 err error // error that caused shutdown (valid when done is closed)
80 healthChecker *health.Aggregator // nil if this is a multi-cluster supervisor, or still booting
81 tasksReady map[string]chan bool
82 waitShutdown sync.WaitGroup
85 tempdir string // in production mode, this is accessible only to root
86 wwwtempdir string // in production mode, this is accessible only to www-data
88 environ []string // for child processes
91 func (super *Supervisor) Clusters() map[string]*arvados.Cluster {
92 m := map[string]*arvados.Cluster{}
93 if super.cluster != nil {
94 m[super.cluster.ClusterID] = super.cluster
96 for id, super2 := range super.children {
97 m[id] = super2.Cluster("")
102 func (super *Supervisor) Cluster(id string) *arvados.Cluster {
103 if super.children != nil {
104 return super.children[id].Cluster(id)
110 func (super *Supervisor) Start(ctx context.Context) {
111 super.logger = ctxlog.FromContext(ctx)
112 super.ctx, super.cancel = context.WithCancel(ctx)
113 super.done = make(chan struct{})
115 sigch := make(chan os.Signal)
116 signal.Notify(sigch, syscall.SIGINT, syscall.SIGTERM)
117 defer signal.Stop(sigch)
119 for sig := range sigch {
120 super.logger.WithField("signal", sig).Info("caught signal")
121 if super.err == nil {
122 super.err = fmt.Errorf("caught signal %s", sig)
128 hupch := make(chan os.Signal)
129 signal.Notify(hupch, syscall.SIGHUP)
130 defer signal.Stop(hupch)
132 for sig := range hupch {
133 super.logger.WithField("signal", sig).Info("caught signal")
134 if super.err == nil {
135 super.err = errNeedConfigReload
141 loaderStdin := super.Stdin
142 if super.ConfigYAML != "" {
143 loaderStdin = bytes.NewBufferString(super.ConfigYAML)
145 loader := config.NewLoader(loaderStdin, super.logger)
146 loader.SkipLegacy = true
147 loader.SkipAPICalls = true
148 loader.Path = super.ConfigPath
149 if super.ConfigYAML != "" {
152 cfg, err := loader.Load()
160 if super.ConfigPath != "" && super.ConfigPath != "-" && cfg.AutoReloadConfig {
161 go watchConfig(super.ctx, super.logger, super.ConfigPath, copyConfig(cfg), func() {
162 if super.err == nil {
163 super.err = errNeedConfigReload
169 if len(cfg.Clusters) > 1 {
170 super.startFederation(cfg)
173 defer close(super.done)
174 for _, super2 := range super.children {
176 if super.err == nil {
184 defer close(super.done)
185 super.cluster, super.err = cfg.GetCluster("")
186 if super.err != nil {
189 err := super.runCluster()
191 super.logger.WithError(err).Info("supervisor shut down")
192 if super.err == nil {
200 // Wait returns when all child processes and goroutines have exited.
201 func (super *Supervisor) Wait() error {
206 // startFederation starts a child Supervisor for each cluster in the
207 // given config. Each is a copy of the original/parent with the
208 // original config reduced to a single cluster.
209 func (super *Supervisor) startFederation(cfg *arvados.Config) {
210 super.children = map[string]*Supervisor{}
211 for id, cc := range cfg.Clusters {
213 yaml, err := json.Marshal(arvados.Config{Clusters: map[string]arvados.Cluster{id: cc}})
215 panic(fmt.Sprintf("json.Marshal partial config: %s", err))
217 super2.ConfigYAML = string(yaml)
218 super2.ConfigPath = "-"
219 super2.children = nil
221 if super2.ClusterType == "test" {
222 super2.Stderr = &service.LogPrefixer{
223 Writer: super.Stderr,
224 Prefix: []byte("[" + id + "] "),
227 super2.Start(super.ctx)
228 super.children[id] = &super2
232 func (super *Supervisor) runCluster() error {
233 cwd, err := os.Getwd()
237 if super.ClusterType == "test" && super.SourcePath == "" {
238 // When invoked by test suite, default to current
240 buf, err := exec.Command("git", "rev-parse", "--show-toplevel").CombinedOutput()
242 return fmt.Errorf("git rev-parse: %w", err)
244 super.SourcePath = strings.TrimSuffix(string(buf), "\n")
245 } else if !strings.HasPrefix(super.SourcePath, "/") {
246 super.SourcePath = filepath.Join(cwd, super.SourcePath)
248 super.SourcePath, err = filepath.EvalSymlinks(super.SourcePath)
253 if super.ListenHost == "" {
254 if urlhost := super.cluster.Services.Controller.ExternalURL.Host; urlhost != "" {
255 if h, _, _ := net.SplitHostPort(urlhost); h != "" {
258 super.ListenHost = urlhost
261 super.ListenHost = "0.0.0.0"
265 // Choose bin and temp dirs: /var/lib/arvados/... in
266 // production, transient tempdir otherwise.
267 if super.ClusterType == "production" {
268 // These dirs have already been created by
269 // "arvados-server install" (or by extracting a
271 super.tempdir = "/var/lib/arvados/tmp"
272 super.wwwtempdir = "/var/lib/arvados/wwwtmp"
273 super.bindir = "/var/lib/arvados/bin"
275 super.tempdir, err = ioutil.TempDir("", "arvados-server-boot-")
279 defer os.RemoveAll(super.tempdir)
280 super.wwwtempdir = super.tempdir
281 super.bindir = filepath.Join(super.tempdir, "bin")
282 if err := os.Mkdir(super.bindir, 0755); err != nil {
287 // Fill in any missing config keys, and write the resulting
288 // config in the temp dir for child services to use.
289 err = super.autofillConfig()
293 conffile, err := os.OpenFile(filepath.Join(super.wwwtempdir, "config.yml"), os.O_CREATE|os.O_WRONLY, 0644)
297 defer conffile.Close()
298 err = json.NewEncoder(conffile).Encode(arvados.Config{
299 Clusters: map[string]arvados.Cluster{
300 super.cluster.ClusterID: *super.cluster}})
304 err = conffile.Close()
308 super.configfile = conffile.Name()
310 super.environ = os.Environ()
311 super.cleanEnv([]string{"ARVADOS_"})
312 super.setEnv("ARVADOS_CONFIG", super.configfile)
313 super.setEnv("RAILS_ENV", super.ClusterType)
314 super.setEnv("TMPDIR", super.tempdir)
315 super.prependEnv("PATH", "/var/lib/arvados/bin:")
316 if super.ClusterType != "production" {
317 super.prependEnv("PATH", super.tempdir+"/bin:")
320 // Now that we have the config, replace the bootstrap logger
321 // with a new one according to the logging config.
322 loglevel := super.cluster.SystemLogs.LogLevel
323 if s := os.Getenv("ARVADOS_DEBUG"); s != "" && s != "0" {
326 super.logger = ctxlog.New(super.Stderr, super.cluster.SystemLogs.Format, loglevel).WithFields(logrus.Fields{
330 if super.SourceVersion == "" && super.ClusterType == "production" {
331 // don't need SourceVersion
332 } else if super.SourceVersion == "" {
333 // Find current source tree version.
335 err = super.RunProgram(super.ctx, ".", runOptions{output: &buf}, "git", "diff", "--shortstat")
339 dirty := buf.Len() > 0
341 err = super.RunProgram(super.ctx, ".", runOptions{output: &buf}, "git", "log", "-n1", "--format=%H")
345 super.SourceVersion = strings.TrimSpace(buf.String())
347 super.SourceVersion += "+uncommitted"
350 return errors.New("specifying a version to run is not yet supported")
353 _, err = super.installGoProgram(super.ctx, "cmd/arvados-server")
357 err = super.setupRubyEnv()
362 tasks := []supervisedTask{
363 createCertificates{},
366 runServiceCommand{name: "controller", svc: super.cluster.Services.Controller, depends: []supervisedTask{seedDatabase{}}},
367 runServiceCommand{name: "git-httpd", svc: super.cluster.Services.GitHTTP},
368 runServiceCommand{name: "health", svc: super.cluster.Services.Health},
369 runServiceCommand{name: "keepproxy", svc: super.cluster.Services.Keepproxy, depends: []supervisedTask{runPassenger{src: "services/api"}}},
370 runServiceCommand{name: "keepstore", svc: super.cluster.Services.Keepstore},
371 runServiceCommand{name: "keep-web", svc: super.cluster.Services.WebDAV},
372 runServiceCommand{name: "ws", svc: super.cluster.Services.Websocket, depends: []supervisedTask{seedDatabase{}}},
373 installPassenger{src: "services/api", varlibdir: "railsapi"},
374 runPassenger{src: "services/api", varlibdir: "railsapi", svc: super.cluster.Services.RailsAPI, depends: []supervisedTask{createCertificates{}, seedDatabase{}, installPassenger{src: "services/api", varlibdir: "railsapi"}}},
377 if !super.NoWorkbench1 {
378 tasks = append(tasks,
379 installPassenger{src: "apps/workbench", varlibdir: "workbench1", depends: []supervisedTask{seedDatabase{}}}, // dependency ensures workbench doesn't delay api install/startup
380 runPassenger{src: "apps/workbench", varlibdir: "workbench1", svc: super.cluster.Services.Workbench1, depends: []supervisedTask{installPassenger{src: "apps/workbench", varlibdir: "workbench1"}}},
383 if !super.NoWorkbench2 {
384 tasks = append(tasks,
385 runWorkbench2{svc: super.cluster.Services.Workbench2},
388 if super.ClusterType != "test" {
389 tasks = append(tasks,
390 runServiceCommand{name: "keep-balance", svc: super.cluster.Services.Keepbalance},
393 if super.cluster.Containers.CloudVMs.Enable {
394 tasks = append(tasks,
395 runServiceCommand{name: "dispatch-cloud", svc: super.cluster.Services.DispatchCloud},
398 super.tasksReady = map[string]chan bool{}
399 for _, task := range tasks {
400 super.tasksReady[task.String()] = make(chan bool)
402 for _, task := range tasks {
404 fail := func(err error) {
405 if super.ctx.Err() != nil {
409 super.logger.WithField("task", task.String()).WithError(err).Error("task failed")
412 super.logger.WithField("task", task.String()).Info("starting")
413 err := task.Run(super.ctx, fail, super)
418 close(super.tasksReady[task.String()])
421 err = super.wait(super.ctx, tasks...)
425 super.logger.Info("all startup tasks are complete; starting health checks")
426 super.healthChecker = &health.Aggregator{Cluster: super.cluster}
428 super.logger.Info("shutting down")
429 super.waitShutdown.Wait()
430 return super.ctx.Err()
433 func (super *Supervisor) wait(ctx context.Context, tasks ...supervisedTask) error {
434 ticker := time.NewTicker(15 * time.Second)
436 for _, task := range tasks {
437 ch, ok := super.tasksReady[task.String()]
439 return fmt.Errorf("no such task: %s", task)
441 super.logger.WithField("task", task.String()).Info("waiting")
445 super.logger.WithField("task", task.String()).Info("ready")
447 super.logger.WithField("task", task.String()).Info("task was never ready")
450 super.logger.WithField("task", task.String()).Info("still waiting...")
459 // Stop shuts down all child processes and goroutines, and returns
460 // when all of them have exited.
461 func (super *Supervisor) Stop() {
466 // WaitReady waits for the cluster(s) to be ready to handle requests,
467 // then returns true. If startup fails, it returns false.
468 func (super *Supervisor) WaitReady() bool {
469 if super.children != nil {
470 for id, super2 := range super.children {
471 super.logger.Infof("waiting for %s to be ready", id)
472 if !super2.WaitReady() {
473 super.logger.Infof("%s startup failed", id)
476 super.logger.Infof("%s is ready", id)
478 super.logger.Info("all clusters are ready")
481 ticker := time.NewTicker(time.Second)
483 for waiting := "all"; waiting != ""; {
486 case <-super.ctx.Done():
489 if super.healthChecker == nil {
493 resp := super.healthChecker.ClusterHealth()
494 // The overall health check (resp.Health=="OK") might
495 // never pass due to missing components (like
496 // arvados-dispatch-cloud in a test cluster), so
497 // instead we wait for all configured components to
500 for target, check := range resp.Checks {
501 if check.Health != "OK" {
502 waiting += " " + target
506 super.logger.WithField("targets", waiting[1:]).Info("waiting")
512 func (super *Supervisor) prependEnv(key, prepend string) {
513 for i, s := range super.environ {
514 if strings.HasPrefix(s, key+"=") {
515 super.environ[i] = key + "=" + prepend + s[len(key)+1:]
519 super.environ = append(super.environ, key+"="+prepend)
522 func (super *Supervisor) cleanEnv(prefixes []string) {
524 for _, s := range super.environ {
526 for _, p := range prefixes {
527 if strings.HasPrefix(s, p) {
533 cleaned = append(cleaned, s)
536 super.environ = cleaned
539 func (super *Supervisor) setEnv(key, val string) {
540 for i, s := range super.environ {
541 if strings.HasPrefix(s, key+"=") {
542 super.environ[i] = key + "=" + val
546 super.environ = append(super.environ, key+"="+val)
549 // Remove all but the first occurrence of each env var.
550 func dedupEnv(in []string) []string {
551 saw := map[string]bool{}
553 for _, kv := range in {
554 if split := strings.Index(kv, "="); split < 1 {
555 panic("invalid environment var: " + kv)
556 } else if saw[kv[:split]] {
559 saw[kv[:split]] = true
560 out = append(out, kv)
566 func (super *Supervisor) installGoProgram(ctx context.Context, srcpath string) (string, error) {
567 _, basename := filepath.Split(srcpath)
568 binfile := filepath.Join(super.bindir, basename)
569 if super.ClusterType == "production" {
572 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)
576 func (super *Supervisor) usingRVM() bool {
577 return os.Getenv("rvm_path") != ""
580 func (super *Supervisor) setupRubyEnv() error {
581 if !super.usingRVM() {
582 // (If rvm is in use, assume the caller has everything
583 // set up as desired)
584 super.cleanEnv([]string{
589 if _, err := os.Stat("/var/lib/arvados/bin/gem"); err == nil || super.ClusterType == "production" {
590 gem = "/var/lib/arvados/bin/gem"
592 cmd := exec.Command(gem, "env", "gempath")
593 if super.ClusterType == "production" {
594 cmd.Args = append([]string{"sudo", "-u", "www-data", "-E", "HOME=/var/www"}, cmd.Args...)
595 path, err := exec.LookPath("sudo")
597 return fmt.Errorf("LookPath(\"sudo\"): %w", err)
601 cmd.Stderr = super.Stderr
602 cmd.Env = super.environ
603 buf, err := cmd.Output() // /var/lib/arvados/.gem/ruby/2.5.0/bin:...
604 if err != nil || len(buf) == 0 {
605 return fmt.Errorf("gem env gempath: %w", err)
607 gempath := string(bytes.Split(buf, []byte{':'})[0])
608 super.prependEnv("PATH", gempath+"/bin:")
609 super.setEnv("GEM_HOME", gempath)
610 super.setEnv("GEM_PATH", gempath)
612 // Passenger install doesn't work unless $HOME is ~user
613 u, err := user.Current()
617 super.setEnv("HOME", u.HomeDir)
621 func (super *Supervisor) lookPath(prog string) string {
622 for _, val := range super.environ {
623 if strings.HasPrefix(val, "PATH=") {
624 for _, dir := range filepath.SplitList(val[5:]) {
625 path := filepath.Join(dir, prog)
626 if fi, err := os.Stat(path); err == nil && fi.Mode()&0111 != 0 {
635 type runOptions struct {
636 output io.Writer // attach stdout
637 env []string // add/replace environment variables
638 user string // run as specified user
642 // RunProgram runs prog with args, using dir as working directory. If ctx is
643 // cancelled while the child is running, RunProgram terminates the child, waits
644 // for it to exit, then returns.
646 // Child's environment will have our env vars, plus any given in env.
648 // Child's stdout will be written to output if non-nil, otherwise the
649 // boot command's stderr.
650 func (super *Supervisor) RunProgram(ctx context.Context, dir string, opts runOptions, prog string, args ...string) error {
651 cmdline := fmt.Sprintf("%s", append([]string{prog}, args...))
652 super.logger.WithField("command", cmdline).WithField("dir", dir).Info("executing")
657 if logprefix == "sudo" {
658 for i := 0; i < len(args); i++ {
661 } else if args[i] == "-E" || strings.Contains(args[i], "=") {
664 innerargs = args[i+1:]
669 logprefix = strings.TrimPrefix(logprefix, "/var/lib/arvados/bin/")
670 logprefix = strings.TrimPrefix(logprefix, super.tempdir+"/bin/")
671 if logprefix == "bundle" && len(innerargs) > 2 && innerargs[0] == "exec" {
672 _, dirbase := filepath.Split(dir)
673 logprefix = innerargs[1] + "@" + dirbase
674 } else if logprefix == "arvados-server" && len(args) > 1 {
677 if !strings.HasPrefix(dir, "/") {
678 logprefix = dir + ": " + logprefix
682 cmd := exec.Command(super.lookPath(prog), args...)
683 cmd.Stdin = opts.stdin
684 stdout, err := cmd.StdoutPipe()
688 stderr, err := cmd.StderrPipe()
692 logwriter := &service.LogPrefixer{Writer: super.Stderr, Prefix: []byte("[" + logprefix + "] ")}
693 var copiers sync.WaitGroup
696 io.Copy(logwriter, stderr)
701 if opts.output == nil {
702 io.Copy(logwriter, stdout)
704 io.Copy(opts.output, stdout)
709 if strings.HasPrefix(dir, "/") {
712 cmd.Dir = filepath.Join(super.SourcePath, dir)
714 env := append([]string(nil), opts.env...)
715 env = append(env, super.environ...)
716 cmd.Env = dedupEnv(env)
719 // Note: We use this approach instead of "sudo"
720 // because in certain circumstances (we are pid 1 in a
721 // docker container, and our passenger child process
722 // changes to pgid 1) the intermediate sudo process
723 // notices we have the same pgid as our child and
724 // refuses to propagate signals from us to our child,
725 // so we can't signal/shutdown our passenger/rails
726 // apps. "chpst" or "setuidgid" would work, but these
727 // few lines avoid depending on runit/daemontools.
728 u, err := user.Lookup(opts.user)
730 return fmt.Errorf("user.Lookup(%q): %w", opts.user, err)
732 uid, _ := strconv.Atoi(u.Uid)
733 gid, _ := strconv.Atoi(u.Gid)
734 cmd.SysProcAttr = &syscall.SysProcAttr{
735 Credential: &syscall.Credential{
743 defer func() { exited = true }()
746 log := ctxlog.FromContext(ctx).WithFields(logrus.Fields{"dir": dir, "cmdline": cmdline})
748 if cmd.Process == nil {
749 log.Debug("waiting for child process to start")
750 time.Sleep(time.Second / 2)
752 log.WithField("PID", cmd.Process.Pid).Debug("sending SIGTERM")
753 cmd.Process.Signal(syscall.SIGTERM)
754 time.Sleep(5 * time.Second)
758 log.WithField("PID", cmd.Process.Pid).Warn("still waiting for child process to exit 5s after SIGTERM")
770 if ctx.Err() != nil {
771 // Return "context canceled", instead of the "killed"
772 // error that was probably caused by the context being
775 } else if err != nil {
776 return fmt.Errorf("%s: error: %v", cmdline, err)
781 func (super *Supervisor) autofillConfig() error {
782 usedPort := map[string]bool{}
783 nextPort := func(host string) (string, error) {
785 port, err := availablePort(host)
787 port, err = availablePort(super.ListenHost)
795 usedPort[port] = true
799 if super.cluster.Services.Controller.ExternalURL.Host == "" {
800 h, p, err := net.SplitHostPort(super.ControllerAddr)
801 if err != nil && super.ControllerAddr != "" {
802 return fmt.Errorf("SplitHostPort(ControllerAddr %q): %w", super.ControllerAddr, err)
807 if p == "0" || p == "" {
813 super.cluster.Services.Controller.ExternalURL = arvados.URL{Scheme: "https", Host: net.JoinHostPort(h, p), Path: "/"}
815 u := url.URL(super.cluster.Services.Controller.ExternalURL)
816 defaultExtHost := u.Hostname()
817 for _, svc := range []*arvados.Service{
818 &super.cluster.Services.Controller,
819 &super.cluster.Services.DispatchCloud,
820 &super.cluster.Services.GitHTTP,
821 &super.cluster.Services.Health,
822 &super.cluster.Services.Keepproxy,
823 &super.cluster.Services.Keepstore,
824 &super.cluster.Services.RailsAPI,
825 &super.cluster.Services.WebDAV,
826 &super.cluster.Services.WebDAVDownload,
827 &super.cluster.Services.Websocket,
828 &super.cluster.Services.Workbench1,
829 &super.cluster.Services.Workbench2,
831 if svc.ExternalURL.Host == "" {
832 port, err := nextPort(defaultExtHost)
836 host := net.JoinHostPort(defaultExtHost, port)
837 if svc == &super.cluster.Services.Controller ||
838 svc == &super.cluster.Services.GitHTTP ||
839 svc == &super.cluster.Services.Health ||
840 svc == &super.cluster.Services.Keepproxy ||
841 svc == &super.cluster.Services.WebDAV ||
842 svc == &super.cluster.Services.WebDAVDownload ||
843 svc == &super.cluster.Services.Workbench1 ||
844 svc == &super.cluster.Services.Workbench2 {
845 svc.ExternalURL = arvados.URL{Scheme: "https", Host: host, Path: "/"}
846 } else if svc == &super.cluster.Services.Websocket {
847 svc.ExternalURL = arvados.URL{Scheme: "wss", Host: host, Path: "/websocket"}
850 if super.NoWorkbench1 && svc == &super.cluster.Services.Workbench1 ||
851 super.NoWorkbench2 && svc == &super.cluster.Services.Workbench2 {
852 // When workbench1 is disabled, it gets an
853 // ExternalURL (so we have a valid listening
854 // port to write in our Nginx config) but no
855 // InternalURLs (so health checker doesn't
859 if len(svc.InternalURLs) == 0 {
860 port, err := nextPort(super.ListenHost)
864 host := net.JoinHostPort(super.ListenHost, port)
865 svc.InternalURLs = map[arvados.URL]arvados.ServiceInstance{
866 {Scheme: "http", Host: host, Path: "/"}: {},
870 if super.ClusterType != "production" {
871 if super.cluster.SystemRootToken == "" {
872 super.cluster.SystemRootToken = randomHexString(64)
874 if super.cluster.ManagementToken == "" {
875 super.cluster.ManagementToken = randomHexString(64)
877 if super.cluster.Collections.BlobSigningKey == "" {
878 super.cluster.Collections.BlobSigningKey = randomHexString(64)
880 if super.cluster.Users.AnonymousUserToken == "" {
881 super.cluster.Users.AnonymousUserToken = randomHexString(64)
883 if super.cluster.Containers.DispatchPrivateKey == "" {
884 buf, err := ioutil.ReadFile(filepath.Join(super.SourcePath, "lib", "dispatchcloud", "test", "sshkey_dispatch"))
888 super.cluster.Containers.DispatchPrivateKey = string(buf)
890 super.cluster.TLS.Insecure = true
892 if super.ClusterType == "test" {
893 // Add a second keepstore process.
894 port, err := nextPort(super.ListenHost)
898 host := net.JoinHostPort(super.ListenHost, port)
899 super.cluster.Services.Keepstore.InternalURLs[arvados.URL{Scheme: "http", Host: host, Path: "/"}] = arvados.ServiceInstance{}
901 // Create a directory-backed volume for each keepstore
903 super.cluster.Volumes = map[string]arvados.Volume{}
904 for url := range super.cluster.Services.Keepstore.InternalURLs {
905 volnum := len(super.cluster.Volumes)
906 datadir := fmt.Sprintf("%s/keep%d.data", super.tempdir, volnum)
907 if _, err = os.Stat(datadir + "/."); err == nil {
908 } else if !os.IsNotExist(err) {
910 } else if err = os.Mkdir(datadir, 0755); err != nil {
913 super.cluster.Volumes[fmt.Sprintf(super.cluster.ClusterID+"-nyw5e-%015d", volnum)] = arvados.Volume{
915 DriverParameters: json.RawMessage(fmt.Sprintf(`{"Root":%q}`, datadir)),
916 AccessViaHosts: map[arvados.URL]arvados.VolumeAccess{
919 StorageClasses: map[string]bool{
926 super.cluster.StorageClasses = map[string]arvados.StorageClassConfig{
927 "default": {Default: true},
932 if super.OwnTemporaryDatabase {
933 port, err := nextPort("localhost")
937 super.cluster.PostgreSQL.Connection = arvados.PostgreSQLConnection{
938 "client_encoding": "utf8",
941 "dbname": "arvados_test",
943 "password": "insecure_arvados_test",
949 func addrIsLocal(addr string) (bool, error) {
950 if h, _, err := net.SplitHostPort(addr); err != nil {
953 addr = net.JoinHostPort(h, "0")
955 listener, err := net.Listen("tcp", addr)
959 } else if strings.Contains(err.Error(), "cannot assign requested address") {
966 func randomHexString(chars int) string {
967 b := make([]byte, chars/2)
968 _, err := rand.Read(b)
972 return fmt.Sprintf("%x", b)
975 func internalPort(svc arvados.Service) (host, port string, err error) {
976 if len(svc.InternalURLs) > 1 {
977 return "", "", errors.New("internalPort() doesn't work with multiple InternalURLs")
979 for u := range svc.InternalURLs {
981 host, port = u.Hostname(), u.Port()
984 case u.Scheme == "https", u.Scheme == "ws":
991 return "", "", fmt.Errorf("service has no InternalURLs")
994 func externalPort(svc arvados.Service) (string, error) {
995 u := url.URL(svc.ExternalURL)
996 if p := u.Port(); p != "" {
998 } else if u.Scheme == "https" || u.Scheme == "wss" {
1005 func availablePort(host string) (string, error) {
1006 ln, err := net.Listen("tcp", net.JoinHostPort(host, "0"))
1011 _, port, err := net.SplitHostPort(ln.Addr().String())
1018 // Try to connect to addr until it works, then close ch. Give up if
1020 func waitForConnect(ctx context.Context, addr string) error {
1021 ctxlog.FromContext(ctx).WithField("addr", addr).Info("waitForConnect")
1022 dialer := net.Dialer{Timeout: time.Second}
1023 for ctx.Err() == nil {
1024 conn, err := dialer.DialContext(ctx, "tcp", addr)
1026 time.Sleep(time.Second / 10)
1035 func copyConfig(cfg *arvados.Config) *arvados.Config {
1038 err := json.NewEncoder(pw).Encode(cfg)
1044 cfg2 := new(arvados.Config)
1045 err := json.NewDecoder(pr).Decode(cfg2)
1052 func watchConfig(ctx context.Context, logger logrus.FieldLogger, cfgPath string, prevcfg *arvados.Config, fn func()) {
1053 watcher, err := fsnotify.NewWatcher()
1055 logger.WithError(err).Error("fsnotify setup failed")
1058 defer watcher.Close()
1060 err = watcher.Add(cfgPath)
1062 logger.WithError(err).Error("fsnotify watcher failed")
1070 case err, ok := <-watcher.Errors:
1074 logger.WithError(err).Warn("fsnotify watcher reported error")
1075 case _, ok := <-watcher.Events:
1079 for len(watcher.Events) > 0 {
1082 loader := config.NewLoader(&bytes.Buffer{}, &logrus.Logger{Out: ioutil.Discard})
1083 loader.Path = cfgPath
1084 loader.SkipAPICalls = true
1085 cfg, err := loader.Load()
1087 logger.WithError(err).Warn("error reloading config file after change detected; ignoring new config for now")
1088 } else if reflect.DeepEqual(cfg, prevcfg) {
1089 logger.Debug("config file changed but is still DeepEqual to the existing config")
1091 logger.Debug("config changed, notifying supervisor")