16306: Merge branch 'master'
[arvados.git] / lib / boot / supervisor.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package boot
6
7 import (
8         "bytes"
9         "context"
10         "crypto/rand"
11         "encoding/json"
12         "errors"
13         "fmt"
14         "io"
15         "io/ioutil"
16         "net"
17         "net/url"
18         "os"
19         "os/exec"
20         "os/signal"
21         "os/user"
22         "path/filepath"
23         "reflect"
24         "strconv"
25         "strings"
26         "sync"
27         "syscall"
28         "time"
29
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"
37 )
38
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
45         OwnTemporaryDatabase bool
46         Stderr               io.Writer
47
48         logger  logrus.FieldLogger
49         cluster *arvados.Cluster
50
51         ctx           context.Context
52         cancel        context.CancelFunc
53         done          chan struct{} // closed when child procs/services have shut down
54         err           error         // error that caused shutdown (valid when done is closed)
55         healthChecker *health.Aggregator
56         tasksReady    map[string]chan bool
57         waitShutdown  sync.WaitGroup
58
59         bindir     string
60         tempdir    string
61         wwwtempdir string
62         configfile string
63         environ    []string // for child processes
64 }
65
66 func (super *Supervisor) Start(ctx context.Context, cfg *arvados.Config, cfgPath string) {
67         super.ctx, super.cancel = context.WithCancel(ctx)
68         super.done = make(chan struct{})
69
70         go func() {
71                 defer close(super.done)
72
73                 sigch := make(chan os.Signal)
74                 signal.Notify(sigch, syscall.SIGINT, syscall.SIGTERM)
75                 defer signal.Stop(sigch)
76                 go func() {
77                         for sig := range sigch {
78                                 super.logger.WithField("signal", sig).Info("caught signal")
79                                 if super.err == nil {
80                                         super.err = fmt.Errorf("caught signal %s", sig)
81                                 }
82                                 super.cancel()
83                         }
84                 }()
85
86                 hupch := make(chan os.Signal)
87                 signal.Notify(hupch, syscall.SIGHUP)
88                 defer signal.Stop(hupch)
89                 go func() {
90                         for sig := range hupch {
91                                 super.logger.WithField("signal", sig).Info("caught signal")
92                                 if super.err == nil {
93                                         super.err = errNeedConfigReload
94                                 }
95                                 super.cancel()
96                         }
97                 }()
98
99                 if cfgPath != "" && cfgPath != "-" && cfg.AutoReloadConfig {
100                         go watchConfig(super.ctx, super.logger, cfgPath, copyConfig(cfg), func() {
101                                 if super.err == nil {
102                                         super.err = errNeedConfigReload
103                                 }
104                                 super.cancel()
105                         })
106                 }
107
108                 err := super.run(cfg)
109                 if err != nil {
110                         super.logger.WithError(err).Warn("supervisor shut down")
111                         if super.err == nil {
112                                 super.err = err
113                         }
114                 }
115         }()
116 }
117
118 func (super *Supervisor) Wait() error {
119         <-super.done
120         return super.err
121 }
122
123 func (super *Supervisor) run(cfg *arvados.Config) error {
124         defer super.cancel()
125
126         cwd, err := os.Getwd()
127         if err != nil {
128                 return err
129         }
130         if !strings.HasPrefix(super.SourcePath, "/") {
131                 super.SourcePath = filepath.Join(cwd, super.SourcePath)
132         }
133         super.SourcePath, err = filepath.EvalSymlinks(super.SourcePath)
134         if err != nil {
135                 return err
136         }
137
138         // Choose bin and temp dirs: /var/lib/arvados/... in
139         // production, transient tempdir otherwise.
140         if super.ClusterType == "production" {
141                 // These dirs have already been created by
142                 // "arvados-server install" (or by extracting a
143                 // package).
144                 super.tempdir = "/var/lib/arvados/tmp"
145                 super.wwwtempdir = "/var/lib/arvados/wwwtmp"
146                 super.bindir = "/var/lib/arvados/bin"
147         } else {
148                 super.tempdir, err = ioutil.TempDir("", "arvados-server-boot-")
149                 if err != nil {
150                         return err
151                 }
152                 defer os.RemoveAll(super.tempdir)
153                 super.wwwtempdir = super.tempdir
154                 super.bindir = filepath.Join(super.tempdir, "bin")
155                 if err := os.Mkdir(super.bindir, 0755); err != nil {
156                         return err
157                 }
158         }
159
160         // Fill in any missing config keys, and write the resulting
161         // config in the temp dir for child services to use.
162         err = super.autofillConfig(cfg)
163         if err != nil {
164                 return err
165         }
166         conffile, err := os.OpenFile(filepath.Join(super.wwwtempdir, "config.yml"), os.O_CREATE|os.O_WRONLY, 0644)
167         if err != nil {
168                 return err
169         }
170         defer conffile.Close()
171         err = json.NewEncoder(conffile).Encode(cfg)
172         if err != nil {
173                 return err
174         }
175         err = conffile.Close()
176         if err != nil {
177                 return err
178         }
179         super.configfile = conffile.Name()
180
181         super.environ = os.Environ()
182         super.cleanEnv([]string{"ARVADOS_"})
183         super.setEnv("ARVADOS_CONFIG", super.configfile)
184         super.setEnv("RAILS_ENV", super.ClusterType)
185         super.setEnv("TMPDIR", super.tempdir)
186         super.prependEnv("PATH", "/var/lib/arvados/bin:")
187         if super.ClusterType != "production" {
188                 super.prependEnv("PATH", super.tempdir+"/bin:")
189         }
190
191         super.cluster, err = cfg.GetCluster("")
192         if err != nil {
193                 return err
194         }
195         // Now that we have the config, replace the bootstrap logger
196         // with a new one according to the logging config.
197         loglevel := super.cluster.SystemLogs.LogLevel
198         if s := os.Getenv("ARVADOS_DEBUG"); s != "" && s != "0" {
199                 loglevel = "debug"
200         }
201         super.logger = ctxlog.New(super.Stderr, super.cluster.SystemLogs.Format, loglevel).WithFields(logrus.Fields{
202                 "PID": os.Getpid(),
203         })
204
205         if super.SourceVersion == "" && super.ClusterType == "production" {
206                 // don't need SourceVersion
207         } else if super.SourceVersion == "" {
208                 // Find current source tree version.
209                 var buf bytes.Buffer
210                 err = super.RunProgram(super.ctx, ".", runOptions{output: &buf}, "git", "diff", "--shortstat")
211                 if err != nil {
212                         return err
213                 }
214                 dirty := buf.Len() > 0
215                 buf.Reset()
216                 err = super.RunProgram(super.ctx, ".", runOptions{output: &buf}, "git", "log", "-n1", "--format=%H")
217                 if err != nil {
218                         return err
219                 }
220                 super.SourceVersion = strings.TrimSpace(buf.String())
221                 if dirty {
222                         super.SourceVersion += "+uncommitted"
223                 }
224         } else {
225                 return errors.New("specifying a version to run is not yet supported")
226         }
227
228         _, err = super.installGoProgram(super.ctx, "cmd/arvados-server")
229         if err != nil {
230                 return err
231         }
232         err = super.setupRubyEnv()
233         if err != nil {
234                 return err
235         }
236
237         tasks := []supervisedTask{
238                 createCertificates{},
239                 runPostgreSQL{},
240                 runNginx{},
241                 runServiceCommand{name: "controller", svc: super.cluster.Services.Controller, depends: []supervisedTask{seedDatabase{}}},
242                 runGoProgram{src: "services/arv-git-httpd", svc: super.cluster.Services.GitHTTP},
243                 runGoProgram{src: "services/health", svc: super.cluster.Services.Health},
244                 runGoProgram{src: "services/keepproxy", svc: super.cluster.Services.Keepproxy, depends: []supervisedTask{runPassenger{src: "services/api"}}},
245                 runGoProgram{src: "services/keepstore", svc: super.cluster.Services.Keepstore},
246                 runGoProgram{src: "services/keep-web", svc: super.cluster.Services.WebDAV},
247                 runServiceCommand{name: "ws", svc: super.cluster.Services.Websocket, depends: []supervisedTask{seedDatabase{}}},
248                 installPassenger{src: "services/api"},
249                 runPassenger{src: "services/api", varlibdir: "railsapi", svc: super.cluster.Services.RailsAPI, depends: []supervisedTask{createCertificates{}, seedDatabase{}, installPassenger{src: "services/api"}}},
250                 installPassenger{src: "apps/workbench", depends: []supervisedTask{seedDatabase{}}}, // dependency ensures workbench doesn't delay api install/startup
251                 runPassenger{src: "apps/workbench", varlibdir: "workbench1", svc: super.cluster.Services.Workbench1, depends: []supervisedTask{installPassenger{src: "apps/workbench"}}},
252                 seedDatabase{},
253         }
254         if super.ClusterType != "test" {
255                 tasks = append(tasks,
256                         runServiceCommand{name: "dispatch-cloud", svc: super.cluster.Services.DispatchCloud},
257                         runGoProgram{src: "services/keep-balance", svc: super.cluster.Services.Keepbalance},
258                 )
259         }
260         super.tasksReady = map[string]chan bool{}
261         for _, task := range tasks {
262                 super.tasksReady[task.String()] = make(chan bool)
263         }
264         for _, task := range tasks {
265                 task := task
266                 fail := func(err error) {
267                         if super.ctx.Err() != nil {
268                                 return
269                         }
270                         super.cancel()
271                         super.logger.WithField("task", task.String()).WithError(err).Error("task failed")
272                 }
273                 go func() {
274                         super.logger.WithField("task", task.String()).Info("starting")
275                         err := task.Run(super.ctx, fail, super)
276                         if err != nil {
277                                 fail(err)
278                                 return
279                         }
280                         close(super.tasksReady[task.String()])
281                 }()
282         }
283         err = super.wait(super.ctx, tasks...)
284         if err != nil {
285                 return err
286         }
287         super.logger.Info("all startup tasks are complete; starting health checks")
288         super.healthChecker = &health.Aggregator{Cluster: super.cluster}
289         <-super.ctx.Done()
290         super.logger.Info("shutting down")
291         super.waitShutdown.Wait()
292         return super.ctx.Err()
293 }
294
295 func (super *Supervisor) wait(ctx context.Context, tasks ...supervisedTask) error {
296         for _, task := range tasks {
297                 ch, ok := super.tasksReady[task.String()]
298                 if !ok {
299                         return fmt.Errorf("no such task: %s", task)
300                 }
301                 super.logger.WithField("task", task.String()).Info("waiting")
302                 select {
303                 case <-ch:
304                         super.logger.WithField("task", task.String()).Info("ready")
305                 case <-ctx.Done():
306                         super.logger.WithField("task", task.String()).Info("task was never ready")
307                         return ctx.Err()
308                 }
309         }
310         return nil
311 }
312
313 func (super *Supervisor) Stop() {
314         super.cancel()
315         <-super.done
316 }
317
318 func (super *Supervisor) WaitReady() (*arvados.URL, bool) {
319         ticker := time.NewTicker(time.Second)
320         defer ticker.Stop()
321         for waiting := "all"; waiting != ""; {
322                 select {
323                 case <-ticker.C:
324                 case <-super.ctx.Done():
325                         return nil, false
326                 }
327                 if super.healthChecker == nil {
328                         // not set up yet
329                         continue
330                 }
331                 resp := super.healthChecker.ClusterHealth()
332                 // The overall health check (resp.Health=="OK") might
333                 // never pass due to missing components (like
334                 // arvados-dispatch-cloud in a test cluster), so
335                 // instead we wait for all configured components to
336                 // pass.
337                 waiting = ""
338                 for target, check := range resp.Checks {
339                         if check.Health != "OK" {
340                                 waiting += " " + target
341                         }
342                 }
343                 if waiting != "" {
344                         super.logger.WithField("targets", waiting[1:]).Info("waiting")
345                 }
346         }
347         u := super.cluster.Services.Controller.ExternalURL
348         return &u, true
349 }
350
351 func (super *Supervisor) prependEnv(key, prepend string) {
352         for i, s := range super.environ {
353                 if strings.HasPrefix(s, key+"=") {
354                         super.environ[i] = key + "=" + prepend + s[len(key)+1:]
355                         return
356                 }
357         }
358         super.environ = append(super.environ, key+"="+prepend)
359 }
360
361 func (super *Supervisor) cleanEnv(prefixes []string) {
362         var cleaned []string
363         for _, s := range super.environ {
364                 drop := false
365                 for _, p := range prefixes {
366                         if strings.HasPrefix(s, p) {
367                                 drop = true
368                                 break
369                         }
370                 }
371                 if !drop {
372                         cleaned = append(cleaned, s)
373                 }
374         }
375         super.environ = cleaned
376 }
377
378 func (super *Supervisor) setEnv(key, val string) {
379         for i, s := range super.environ {
380                 if strings.HasPrefix(s, key+"=") {
381                         super.environ[i] = key + "=" + val
382                         return
383                 }
384         }
385         super.environ = append(super.environ, key+"="+val)
386 }
387
388 // Remove all but the first occurrence of each env var.
389 func dedupEnv(in []string) []string {
390         saw := map[string]bool{}
391         var out []string
392         for _, kv := range in {
393                 if split := strings.Index(kv, "="); split < 1 {
394                         panic("invalid environment var: " + kv)
395                 } else if saw[kv[:split]] {
396                         continue
397                 } else {
398                         saw[kv[:split]] = true
399                         out = append(out, kv)
400                 }
401         }
402         return out
403 }
404
405 func (super *Supervisor) installGoProgram(ctx context.Context, srcpath string) (string, error) {
406         _, basename := filepath.Split(srcpath)
407         binfile := filepath.Join(super.bindir, basename)
408         if super.ClusterType == "production" {
409                 return binfile, nil
410         }
411         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)
412         return binfile, err
413 }
414
415 func (super *Supervisor) usingRVM() bool {
416         return os.Getenv("rvm_path") != ""
417 }
418
419 func (super *Supervisor) setupRubyEnv() error {
420         if !super.usingRVM() {
421                 // (If rvm is in use, assume the caller has everything
422                 // set up as desired)
423                 super.cleanEnv([]string{
424                         "GEM_HOME=",
425                         "GEM_PATH=",
426                 })
427                 gem := "gem"
428                 if _, err := os.Stat("/var/lib/arvados/bin/gem"); err == nil || super.ClusterType == "production" {
429                         gem = "/var/lib/arvados/bin/gem"
430                 }
431                 cmd := exec.Command(gem, "env", "gempath")
432                 if super.ClusterType == "production" {
433                         cmd.Args = append([]string{"sudo", "-u", "www-data", "-E", "HOME=/var/www"}, cmd.Args...)
434                         path, err := exec.LookPath("sudo")
435                         if err != nil {
436                                 return fmt.Errorf("LookPath(\"sudo\"): %w", err)
437                         }
438                         cmd.Path = path
439                 }
440                 cmd.Stderr = super.Stderr
441                 cmd.Env = super.environ
442                 buf, err := cmd.Output() // /var/lib/arvados/.gem/ruby/2.5.0/bin:...
443                 if err != nil || len(buf) == 0 {
444                         return fmt.Errorf("gem env gempath: %v", err)
445                 }
446                 gempath := string(bytes.Split(buf, []byte{':'})[0])
447                 super.prependEnv("PATH", gempath+"/bin:")
448                 super.setEnv("GEM_HOME", gempath)
449                 super.setEnv("GEM_PATH", gempath)
450         }
451         // Passenger install doesn't work unless $HOME is ~user
452         u, err := user.Current()
453         if err != nil {
454                 return err
455         }
456         super.setEnv("HOME", u.HomeDir)
457         return nil
458 }
459
460 func (super *Supervisor) lookPath(prog string) string {
461         for _, val := range super.environ {
462                 if strings.HasPrefix(val, "PATH=") {
463                         for _, dir := range filepath.SplitList(val[5:]) {
464                                 path := filepath.Join(dir, prog)
465                                 if fi, err := os.Stat(path); err == nil && fi.Mode()&0111 != 0 {
466                                         return path
467                                 }
468                         }
469                 }
470         }
471         return prog
472 }
473
474 type runOptions struct {
475         output io.Writer // attach stdout
476         env    []string  // add/replace environment variables
477         user   string    // run as specified user
478 }
479
480 // RunProgram runs prog with args, using dir as working directory. If ctx is
481 // cancelled while the child is running, RunProgram terminates the child, waits
482 // for it to exit, then returns.
483 //
484 // Child's environment will have our env vars, plus any given in env.
485 //
486 // Child's stdout will be written to output if non-nil, otherwise the
487 // boot command's stderr.
488 func (super *Supervisor) RunProgram(ctx context.Context, dir string, opts runOptions, prog string, args ...string) error {
489         cmdline := fmt.Sprintf("%s", append([]string{prog}, args...))
490         super.logger.WithField("command", cmdline).WithField("dir", dir).Info("executing")
491
492         logprefix := prog
493         {
494                 innerargs := args
495                 if logprefix == "sudo" {
496                         for i := 0; i < len(args); i++ {
497                                 if args[i] == "-u" {
498                                         i++
499                                 } else if args[i] == "-E" || strings.Contains(args[i], "=") {
500                                 } else {
501                                         logprefix = args[i]
502                                         innerargs = args[i+1:]
503                                         break
504                                 }
505                         }
506                 }
507                 logprefix = strings.TrimPrefix(logprefix, "/var/lib/arvados/bin/")
508                 logprefix = strings.TrimPrefix(logprefix, super.tempdir+"/bin/")
509                 if logprefix == "bundle" && len(innerargs) > 2 && innerargs[0] == "exec" {
510                         _, dirbase := filepath.Split(dir)
511                         logprefix = innerargs[1] + "@" + dirbase
512                 } else if logprefix == "arvados-server" && len(args) > 1 {
513                         logprefix = args[0]
514                 }
515                 if !strings.HasPrefix(dir, "/") {
516                         logprefix = dir + ": " + logprefix
517                 }
518         }
519
520         cmd := exec.Command(super.lookPath(prog), args...)
521         stdout, err := cmd.StdoutPipe()
522         if err != nil {
523                 return err
524         }
525         stderr, err := cmd.StderrPipe()
526         if err != nil {
527                 return err
528         }
529         logwriter := &service.LogPrefixer{Writer: super.Stderr, Prefix: []byte("[" + logprefix + "] ")}
530         var copiers sync.WaitGroup
531         copiers.Add(1)
532         go func() {
533                 io.Copy(logwriter, stderr)
534                 copiers.Done()
535         }()
536         copiers.Add(1)
537         go func() {
538                 if opts.output == nil {
539                         io.Copy(logwriter, stdout)
540                 } else {
541                         io.Copy(opts.output, stdout)
542                 }
543                 copiers.Done()
544         }()
545
546         if strings.HasPrefix(dir, "/") {
547                 cmd.Dir = dir
548         } else {
549                 cmd.Dir = filepath.Join(super.SourcePath, dir)
550         }
551         env := append([]string(nil), opts.env...)
552         env = append(env, super.environ...)
553         cmd.Env = dedupEnv(env)
554
555         if opts.user != "" {
556                 // Note: We use this approach instead of "sudo"
557                 // because in certain circumstances (we are pid 1 in a
558                 // docker container, and our passenger child process
559                 // changes to pgid 1) the intermediate sudo process
560                 // notices we have the same pgid as our child and
561                 // refuses to propagate signals from us to our child,
562                 // so we can't signal/shutdown our passenger/rails
563                 // apps. "chpst" or "setuidgid" would work, but these
564                 // few lines avoid depending on runit/daemontools.
565                 u, err := user.Lookup(opts.user)
566                 if err != nil {
567                         return fmt.Errorf("user.Lookup(%q): %w", opts.user, err)
568                 }
569                 uid, _ := strconv.Atoi(u.Uid)
570                 gid, _ := strconv.Atoi(u.Gid)
571                 cmd.SysProcAttr = &syscall.SysProcAttr{
572                         Credential: &syscall.Credential{
573                                 Uid: uint32(uid),
574                                 Gid: uint32(gid),
575                         },
576                 }
577         }
578
579         exited := false
580         defer func() { exited = true }()
581         go func() {
582                 <-ctx.Done()
583                 log := ctxlog.FromContext(ctx).WithFields(logrus.Fields{"dir": dir, "cmdline": cmdline})
584                 for !exited {
585                         if cmd.Process == nil {
586                                 log.Debug("waiting for child process to start")
587                                 time.Sleep(time.Second / 2)
588                         } else {
589                                 log.WithField("PID", cmd.Process.Pid).Debug("sending SIGTERM")
590                                 cmd.Process.Signal(syscall.SIGTERM)
591                                 time.Sleep(5 * time.Second)
592                                 if !exited {
593                                         stdout.Close()
594                                         stderr.Close()
595                                         log.WithField("PID", cmd.Process.Pid).Warn("still waiting for child process to exit 5s after SIGTERM")
596                                 }
597                         }
598                 }
599         }()
600
601         err = cmd.Start()
602         if err != nil {
603                 return err
604         }
605         copiers.Wait()
606         err = cmd.Wait()
607         if ctx.Err() != nil {
608                 // Return "context canceled", instead of the "killed"
609                 // error that was probably caused by the context being
610                 // canceled.
611                 return ctx.Err()
612         } else if err != nil {
613                 return fmt.Errorf("%s: error: %v", cmdline, err)
614         }
615         return nil
616 }
617
618 func (super *Supervisor) autofillConfig(cfg *arvados.Config) error {
619         cluster, err := cfg.GetCluster("")
620         if err != nil {
621                 return err
622         }
623         usedPort := map[string]bool{}
624         nextPort := func(host string) string {
625                 for {
626                         port, err := availablePort(host)
627                         if err != nil {
628                                 panic(err)
629                         }
630                         if usedPort[port] {
631                                 continue
632                         }
633                         usedPort[port] = true
634                         return port
635                 }
636         }
637         if cluster.Services.Controller.ExternalURL.Host == "" {
638                 h, p, err := net.SplitHostPort(super.ControllerAddr)
639                 if err != nil {
640                         return err
641                 }
642                 if h == "" {
643                         h = super.ListenHost
644                 }
645                 if p == "0" {
646                         p = nextPort(h)
647                 }
648                 cluster.Services.Controller.ExternalURL = arvados.URL{Scheme: "https", Host: net.JoinHostPort(h, p), Path: "/"}
649         }
650         for _, svc := range []*arvados.Service{
651                 &cluster.Services.Controller,
652                 &cluster.Services.DispatchCloud,
653                 &cluster.Services.GitHTTP,
654                 &cluster.Services.Health,
655                 &cluster.Services.Keepproxy,
656                 &cluster.Services.Keepstore,
657                 &cluster.Services.RailsAPI,
658                 &cluster.Services.WebDAV,
659                 &cluster.Services.WebDAVDownload,
660                 &cluster.Services.Websocket,
661                 &cluster.Services.Workbench1,
662         } {
663                 if svc == &cluster.Services.DispatchCloud && super.ClusterType == "test" {
664                         continue
665                 }
666                 if svc.ExternalURL.Host == "" {
667                         if svc == &cluster.Services.Controller ||
668                                 svc == &cluster.Services.GitHTTP ||
669                                 svc == &cluster.Services.Health ||
670                                 svc == &cluster.Services.Keepproxy ||
671                                 svc == &cluster.Services.WebDAV ||
672                                 svc == &cluster.Services.WebDAVDownload ||
673                                 svc == &cluster.Services.Workbench1 {
674                                 svc.ExternalURL = arvados.URL{Scheme: "https", Host: fmt.Sprintf("%s:%s", super.ListenHost, nextPort(super.ListenHost)), Path: "/"}
675                         } else if svc == &cluster.Services.Websocket {
676                                 svc.ExternalURL = arvados.URL{Scheme: "wss", Host: fmt.Sprintf("%s:%s", super.ListenHost, nextPort(super.ListenHost)), Path: "/websocket"}
677                         }
678                 }
679                 if len(svc.InternalURLs) == 0 {
680                         svc.InternalURLs = map[arvados.URL]arvados.ServiceInstance{
681                                 {Scheme: "http", Host: fmt.Sprintf("%s:%s", super.ListenHost, nextPort(super.ListenHost)), Path: "/"}: {},
682                         }
683                 }
684         }
685         if super.ClusterType != "production" {
686                 if cluster.SystemRootToken == "" {
687                         cluster.SystemRootToken = randomHexString(64)
688                 }
689                 if cluster.ManagementToken == "" {
690                         cluster.ManagementToken = randomHexString(64)
691                 }
692                 if cluster.Collections.BlobSigningKey == "" {
693                         cluster.Collections.BlobSigningKey = randomHexString(64)
694                 }
695                 if cluster.Users.AnonymousUserToken == "" {
696                         cluster.Users.AnonymousUserToken = randomHexString(64)
697                 }
698                 if cluster.Containers.DispatchPrivateKey == "" {
699                         buf, err := ioutil.ReadFile(filepath.Join(super.SourcePath, "lib", "dispatchcloud", "test", "sshkey_dispatch"))
700                         if err != nil {
701                                 return err
702                         }
703                         cluster.Containers.DispatchPrivateKey = string(buf)
704                 }
705                 cluster.TLS.Insecure = true
706         }
707         if super.ClusterType == "test" {
708                 // Add a second keepstore process.
709                 cluster.Services.Keepstore.InternalURLs[arvados.URL{Scheme: "http", Host: fmt.Sprintf("%s:%s", super.ListenHost, nextPort(super.ListenHost)), Path: "/"}] = arvados.ServiceInstance{}
710
711                 // Create a directory-backed volume for each keepstore
712                 // process.
713                 cluster.Volumes = map[string]arvados.Volume{}
714                 for url := range cluster.Services.Keepstore.InternalURLs {
715                         volnum := len(cluster.Volumes)
716                         datadir := fmt.Sprintf("%s/keep%d.data", super.tempdir, volnum)
717                         if _, err = os.Stat(datadir + "/."); err == nil {
718                         } else if !os.IsNotExist(err) {
719                                 return err
720                         } else if err = os.Mkdir(datadir, 0755); err != nil {
721                                 return err
722                         }
723                         cluster.Volumes[fmt.Sprintf(cluster.ClusterID+"-nyw5e-%015d", volnum)] = arvados.Volume{
724                                 Driver:           "Directory",
725                                 DriverParameters: json.RawMessage(fmt.Sprintf(`{"Root":%q}`, datadir)),
726                                 AccessViaHosts: map[arvados.URL]arvados.VolumeAccess{
727                                         url: {},
728                                 },
729                         }
730                 }
731         }
732         if super.OwnTemporaryDatabase {
733                 cluster.PostgreSQL.Connection = arvados.PostgreSQLConnection{
734                         "client_encoding": "utf8",
735                         "host":            "localhost",
736                         "port":            nextPort(super.ListenHost),
737                         "dbname":          "arvados_test",
738                         "user":            "arvados",
739                         "password":        "insecure_arvados_test",
740                 }
741         }
742
743         cfg.Clusters[cluster.ClusterID] = *cluster
744         return nil
745 }
746
747 func addrIsLocal(addr string) (bool, error) {
748         return true, nil
749         listener, err := net.Listen("tcp", addr)
750         if err == nil {
751                 listener.Close()
752                 return true, nil
753         } else if strings.Contains(err.Error(), "cannot assign requested address") {
754                 return false, nil
755         } else {
756                 return false, err
757         }
758 }
759
760 func randomHexString(chars int) string {
761         b := make([]byte, chars/2)
762         _, err := rand.Read(b)
763         if err != nil {
764                 panic(err)
765         }
766         return fmt.Sprintf("%x", b)
767 }
768
769 func internalPort(svc arvados.Service) (string, error) {
770         if len(svc.InternalURLs) > 1 {
771                 return "", errors.New("internalPort() doesn't work with multiple InternalURLs")
772         }
773         for u := range svc.InternalURLs {
774                 u := url.URL(u)
775                 if p := u.Port(); p != "" {
776                         return p, nil
777                 } else if u.Scheme == "https" || u.Scheme == "ws" {
778                         return "443", nil
779                 } else {
780                         return "80", nil
781                 }
782         }
783         return "", fmt.Errorf("service has no InternalURLs")
784 }
785
786 func externalPort(svc arvados.Service) (string, error) {
787         u := url.URL(svc.ExternalURL)
788         if p := u.Port(); p != "" {
789                 return p, nil
790         } else if u.Scheme == "https" || u.Scheme == "wss" {
791                 return "443", nil
792         } else {
793                 return "80", nil
794         }
795 }
796
797 func availablePort(host string) (string, error) {
798         ln, err := net.Listen("tcp", net.JoinHostPort(host, "0"))
799         if err != nil {
800                 return "", err
801         }
802         defer ln.Close()
803         _, port, err := net.SplitHostPort(ln.Addr().String())
804         if err != nil {
805                 return "", err
806         }
807         return port, nil
808 }
809
810 // Try to connect to addr until it works, then close ch. Give up if
811 // ctx cancels.
812 func waitForConnect(ctx context.Context, addr string) error {
813         dialer := net.Dialer{Timeout: time.Second}
814         for ctx.Err() == nil {
815                 conn, err := dialer.DialContext(ctx, "tcp", addr)
816                 if err != nil {
817                         time.Sleep(time.Second / 10)
818                         continue
819                 }
820                 conn.Close()
821                 return nil
822         }
823         return ctx.Err()
824 }
825
826 func copyConfig(cfg *arvados.Config) *arvados.Config {
827         pr, pw := io.Pipe()
828         go func() {
829                 err := json.NewEncoder(pw).Encode(cfg)
830                 if err != nil {
831                         panic(err)
832                 }
833                 pw.Close()
834         }()
835         cfg2 := new(arvados.Config)
836         err := json.NewDecoder(pr).Decode(cfg2)
837         if err != nil {
838                 panic(err)
839         }
840         return cfg2
841 }
842
843 func watchConfig(ctx context.Context, logger logrus.FieldLogger, cfgPath string, prevcfg *arvados.Config, fn func()) {
844         watcher, err := fsnotify.NewWatcher()
845         if err != nil {
846                 logger.WithError(err).Error("fsnotify setup failed")
847                 return
848         }
849         defer watcher.Close()
850
851         err = watcher.Add(cfgPath)
852         if err != nil {
853                 logger.WithError(err).Error("fsnotify watcher failed")
854                 return
855         }
856
857         for {
858                 select {
859                 case <-ctx.Done():
860                         return
861                 case err, ok := <-watcher.Errors:
862                         if !ok {
863                                 return
864                         }
865                         logger.WithError(err).Warn("fsnotify watcher reported error")
866                 case _, ok := <-watcher.Events:
867                         if !ok {
868                                 return
869                         }
870                         for len(watcher.Events) > 0 {
871                                 <-watcher.Events
872                         }
873                         loader := config.NewLoader(&bytes.Buffer{}, &logrus.Logger{Out: ioutil.Discard})
874                         loader.Path = cfgPath
875                         loader.SkipAPICalls = true
876                         cfg, err := loader.Load()
877                         if err != nil {
878                                 logger.WithError(err).Warn("error reloading config file after change detected; ignoring new config for now")
879                         } else if reflect.DeepEqual(cfg, prevcfg) {
880                                 logger.Debug("config file changed but is still DeepEqual to the existing config")
881                         } else {
882                                 logger.Debug("config changed, notifying supervisor")
883                                 fn()
884                                 prevcfg = cfg
885                         }
886                 }
887         }
888 }