2d76972336ae238d0025e5bbfeb77a2a46c651e8
[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         "strings"
25         "sync"
26         "syscall"
27         "time"
28
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"
36 )
37
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
45         Stderr               io.Writer
46
47         logger  logrus.FieldLogger
48         cluster *arvados.Cluster
49
50         ctx           context.Context
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
57
58         bindir     string
59         tempdir    string
60         wwwtempdir string
61         configfile string
62         environ    []string // for child processes
63 }
64
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{})
68
69         go func() {
70                 defer close(super.done)
71
72                 sigch := make(chan os.Signal)
73                 signal.Notify(sigch, syscall.SIGINT, syscall.SIGTERM)
74                 defer signal.Stop(sigch)
75                 go func() {
76                         for sig := range sigch {
77                                 super.logger.WithField("signal", sig).Info("caught signal")
78                                 if super.err == nil {
79                                         super.err = fmt.Errorf("caught signal %s", sig)
80                                 }
81                                 super.cancel()
82                         }
83                 }()
84
85                 hupch := make(chan os.Signal)
86                 signal.Notify(hupch, syscall.SIGHUP)
87                 defer signal.Stop(hupch)
88                 go func() {
89                         for sig := range hupch {
90                                 super.logger.WithField("signal", sig).Info("caught signal")
91                                 if super.err == nil {
92                                         super.err = errNeedConfigReload
93                                 }
94                                 super.cancel()
95                         }
96                 }()
97
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
102                                 }
103                                 super.cancel()
104                         })
105                 }
106
107                 err := super.run(cfg)
108                 if err != nil {
109                         super.logger.WithError(err).Warn("supervisor shut down")
110                         if super.err == nil {
111                                 super.err = err
112                         }
113                 }
114         }()
115 }
116
117 func (super *Supervisor) Wait() error {
118         <-super.done
119         return super.err
120 }
121
122 func (super *Supervisor) run(cfg *arvados.Config) error {
123         defer super.cancel()
124
125         cwd, err := os.Getwd()
126         if err != nil {
127                 return err
128         }
129         if !strings.HasPrefix(super.SourcePath, "/") {
130                 super.SourcePath = filepath.Join(cwd, super.SourcePath)
131         }
132         super.SourcePath, err = filepath.EvalSymlinks(super.SourcePath)
133         if err != nil {
134                 return err
135         }
136
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
142                 // package).
143                 super.tempdir = "/var/lib/arvados/tmp"
144                 super.wwwtempdir = "/var/lib/arvados/wwwtmp"
145                 super.bindir = "/var/lib/arvados/bin"
146         } else {
147                 super.tempdir, err = ioutil.TempDir("", "arvados-server-boot-")
148                 if err != nil {
149                         return err
150                 }
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 {
155                         return err
156                 }
157         }
158
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)
162         if err != nil {
163                 return err
164         }
165         conffile, err := os.OpenFile(filepath.Join(super.tempdir, "config.yml"), os.O_CREATE|os.O_WRONLY, 0644)
166         if err != nil {
167                 return err
168         }
169         defer conffile.Close()
170         err = json.NewEncoder(conffile).Encode(cfg)
171         if err != nil {
172                 return err
173         }
174         err = conffile.Close()
175         if err != nil {
176                 return err
177         }
178         super.configfile = conffile.Name()
179
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:")
188         }
189
190         super.cluster, err = cfg.GetCluster("")
191         if err != nil {
192                 return err
193         }
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" {
198                 loglevel = "debug"
199         }
200         super.logger = ctxlog.New(super.Stderr, super.cluster.SystemLogs.Format, loglevel).WithFields(logrus.Fields{
201                 "PID": os.Getpid(),
202         })
203
204         if super.SourceVersion == "" && super.ClusterType == "production" {
205                 // don't need SourceVersion
206         } else if super.SourceVersion == "" {
207                 // Find current source tree version.
208                 var buf bytes.Buffer
209                 err = super.RunProgram(super.ctx, ".", &buf, nil, "git", "diff", "--shortstat")
210                 if err != nil {
211                         return err
212                 }
213                 dirty := buf.Len() > 0
214                 buf.Reset()
215                 err = super.RunProgram(super.ctx, ".", &buf, nil, "git", "log", "-n1", "--format=%H")
216                 if err != nil {
217                         return err
218                 }
219                 super.SourceVersion = strings.TrimSpace(buf.String())
220                 if dirty {
221                         super.SourceVersion += "+uncommitted"
222                 }
223         } else {
224                 return errors.New("specifying a version to run is not yet supported")
225         }
226
227         _, err = super.installGoProgram(super.ctx, "cmd/arvados-server")
228         if err != nil {
229                 return err
230         }
231         err = super.setupRubyEnv()
232         if err != nil {
233                 return err
234         }
235
236         tasks := []supervisedTask{
237                 createCertificates{},
238                 runPostgreSQL{},
239                 runNginx{},
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"}}},
251                 seedDatabase{},
252         }
253         if super.ClusterType != "test" {
254                 tasks = append(tasks,
255                         runServiceCommand{name: "dispatch-cloud", svc: super.cluster.Services.Controller},
256                         runGoProgram{src: "services/keep-balance", svc: super.cluster.Services.Keepbalance},
257                 )
258         }
259         super.tasksReady = map[string]chan bool{}
260         for _, task := range tasks {
261                 super.tasksReady[task.String()] = make(chan bool)
262         }
263         for _, task := range tasks {
264                 task := task
265                 fail := func(err error) {
266                         if super.ctx.Err() != nil {
267                                 return
268                         }
269                         super.cancel()
270                         super.logger.WithField("task", task.String()).WithError(err).Error("task failed")
271                 }
272                 go func() {
273                         super.logger.WithField("task", task.String()).Info("starting")
274                         err := task.Run(super.ctx, fail, super)
275                         if err != nil {
276                                 fail(err)
277                                 return
278                         }
279                         close(super.tasksReady[task.String()])
280                 }()
281         }
282         err = super.wait(super.ctx, tasks...)
283         if err != nil {
284                 return err
285         }
286         super.logger.Info("all startup tasks are complete; starting health checks")
287         super.healthChecker = &health.Aggregator{Cluster: super.cluster}
288         <-super.ctx.Done()
289         super.logger.Info("shutting down")
290         super.waitShutdown.Wait()
291         return super.ctx.Err()
292 }
293
294 func (super *Supervisor) wait(ctx context.Context, tasks ...supervisedTask) error {
295         for _, task := range tasks {
296                 ch, ok := super.tasksReady[task.String()]
297                 if !ok {
298                         return fmt.Errorf("no such task: %s", task)
299                 }
300                 super.logger.WithField("task", task.String()).Info("waiting")
301                 select {
302                 case <-ch:
303                         super.logger.WithField("task", task.String()).Info("ready")
304                 case <-ctx.Done():
305                         super.logger.WithField("task", task.String()).Info("task was never ready")
306                         return ctx.Err()
307                 }
308         }
309         return nil
310 }
311
312 func (super *Supervisor) Stop() {
313         super.cancel()
314         <-super.done
315 }
316
317 func (super *Supervisor) WaitReady() (*arvados.URL, bool) {
318         ticker := time.NewTicker(time.Second)
319         defer ticker.Stop()
320         for waiting := "all"; waiting != ""; {
321                 select {
322                 case <-ticker.C:
323                 case <-super.ctx.Done():
324                         return nil, false
325                 }
326                 if super.healthChecker == nil {
327                         // not set up yet
328                         continue
329                 }
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
335                 // pass.
336                 waiting = ""
337                 for target, check := range resp.Checks {
338                         if check.Health != "OK" {
339                                 waiting += " " + target
340                         }
341                 }
342                 if waiting != "" {
343                         super.logger.WithField("targets", waiting[1:]).Info("waiting")
344                 }
345         }
346         u := super.cluster.Services.Controller.ExternalURL
347         return &u, true
348 }
349
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:]
354                         return
355                 }
356         }
357         super.environ = append(super.environ, key+"="+prepend)
358 }
359
360 func (super *Supervisor) cleanEnv(prefixes []string) {
361         var cleaned []string
362         for _, s := range super.environ {
363                 drop := false
364                 for _, p := range prefixes {
365                         if strings.HasPrefix(s, p) {
366                                 drop = true
367                                 break
368                         }
369                 }
370                 if !drop {
371                         cleaned = append(cleaned, s)
372                 }
373         }
374         super.environ = cleaned
375 }
376
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
381                         return
382                 }
383         }
384         super.environ = append(super.environ, key+"="+val)
385 }
386
387 // Remove all but the first occurrence of each env var.
388 func dedupEnv(in []string) []string {
389         saw := map[string]bool{}
390         var out []string
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]] {
395                         continue
396                 } else {
397                         saw[kv[:split]] = true
398                         out = append(out, kv)
399                 }
400         }
401         return out
402 }
403
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" {
408                 return binfile, nil
409         }
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)
411         return binfile, err
412 }
413
414 func (super *Supervisor) usingRVM() bool {
415         return os.Getenv("rvm_path") != ""
416 }
417
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{
423                         "GEM_HOME=",
424                         "GEM_PATH=",
425                 })
426                 gem := "gem"
427                 if _, err := os.Stat("/var/lib/arvados/bin/gem"); err == nil || super.ClusterType == "production" {
428                         gem = "/var/lib/arvados/bin/gem"
429                 }
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")
434                         if err != nil {
435                                 return fmt.Errorf("LookPath(\"sudo\"): %w", err)
436                         }
437                         cmd.Path = path
438                 }
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)
444                 }
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)
449         }
450         // Passenger install doesn't work unless $HOME is ~user
451         u, err := user.Current()
452         if err != nil {
453                 return err
454         }
455         super.setEnv("HOME", u.HomeDir)
456         return nil
457 }
458
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 {
465                                         return path
466                                 }
467                         }
468                 }
469         }
470         return prog
471 }
472
473 // Run prog with args, using dir as working directory. If ctx is
474 // cancelled while the child is running, RunProgram terminates the
475 // child, waits for it to exit, then returns.
476 //
477 // Child's environment will have our env vars, plus any given in env.
478 //
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")
484
485         logprefix := prog
486         if logprefix == "setuidgid" && len(args) >= 3 {
487                 logprefix = args[2]
488         }
489         logprefix = strings.TrimPrefix(logprefix, super.tempdir+"/bin/")
490         if logprefix == "bundle" && len(args) > 2 && args[0] == "exec" {
491                 logprefix = args[1]
492         } else if logprefix == "arvados-server" && len(args) > 1 {
493                 logprefix = args[0]
494         }
495         if !strings.HasPrefix(dir, "/") {
496                 logprefix = dir + ": " + logprefix
497         }
498
499         cmd := exec.Command(super.lookPath(prog), args...)
500         stdout, err := cmd.StdoutPipe()
501         if err != nil {
502                 return err
503         }
504         stderr, err := cmd.StderrPipe()
505         if err != nil {
506                 return err
507         }
508         logwriter := &service.LogPrefixer{Writer: super.Stderr, Prefix: []byte("[" + logprefix + "] ")}
509         var copiers sync.WaitGroup
510         copiers.Add(1)
511         go func() {
512                 io.Copy(logwriter, stderr)
513                 copiers.Done()
514         }()
515         copiers.Add(1)
516         go func() {
517                 if output == nil {
518                         io.Copy(logwriter, stdout)
519                 } else {
520                         io.Copy(output, stdout)
521                 }
522                 copiers.Done()
523         }()
524
525         if strings.HasPrefix(dir, "/") {
526                 cmd.Dir = dir
527         } else {
528                 cmd.Dir = filepath.Join(super.SourcePath, dir)
529         }
530         env = append([]string(nil), env...)
531         env = append(env, super.environ...)
532         cmd.Env = dedupEnv(env)
533
534         exited := false
535         defer func() { exited = true }()
536         go func() {
537                 <-ctx.Done()
538                 log := ctxlog.FromContext(ctx).WithFields(logrus.Fields{"dir": dir, "cmdline": cmdline})
539                 for !exited {
540                         if cmd.Process == nil {
541                                 log.Debug("waiting for child process to start")
542                                 time.Sleep(time.Second / 2)
543                         } else {
544                                 log.WithField("PID", cmd.Process.Pid).Debug("sending SIGTERM")
545                                 cmd.Process.Signal(syscall.SIGTERM)
546                                 time.Sleep(5 * time.Second)
547                                 if !exited {
548                                         stdout.Close()
549                                         stderr.Close()
550                                         log.WithField("PID", cmd.Process.Pid).Warn("still waiting for child process to exit 5s after SIGTERM")
551                                 }
552                         }
553                 }
554         }()
555
556         err = cmd.Start()
557         if err != nil {
558                 return err
559         }
560         copiers.Wait()
561         err = cmd.Wait()
562         if ctx.Err() != nil {
563                 // Return "context canceled", instead of the "killed"
564                 // error that was probably caused by the context being
565                 // canceled.
566                 return ctx.Err()
567         } else if err != nil {
568                 return fmt.Errorf("%s: error: %v", cmdline, err)
569         }
570         return nil
571 }
572
573 func (super *Supervisor) autofillConfig(cfg *arvados.Config) error {
574         cluster, err := cfg.GetCluster("")
575         if err != nil {
576                 return err
577         }
578         usedPort := map[string]bool{}
579         nextPort := func(host string) string {
580                 for {
581                         port, err := availablePort(host)
582                         if err != nil {
583                                 panic(err)
584                         }
585                         if usedPort[port] {
586                                 continue
587                         }
588                         usedPort[port] = true
589                         return port
590                 }
591         }
592         if cluster.Services.Controller.ExternalURL.Host == "" {
593                 h, p, err := net.SplitHostPort(super.ControllerAddr)
594                 if err != nil {
595                         return err
596                 }
597                 if h == "" {
598                         h = super.ListenHost
599                 }
600                 if p == "0" {
601                         p = nextPort(h)
602                 }
603                 cluster.Services.Controller.ExternalURL = arvados.URL{Scheme: "https", Host: net.JoinHostPort(h, p), Path: "/"}
604         }
605         for _, svc := range []*arvados.Service{
606                 &cluster.Services.Controller,
607                 &cluster.Services.DispatchCloud,
608                 &cluster.Services.GitHTTP,
609                 &cluster.Services.Health,
610                 &cluster.Services.Keepproxy,
611                 &cluster.Services.Keepstore,
612                 &cluster.Services.RailsAPI,
613                 &cluster.Services.WebDAV,
614                 &cluster.Services.WebDAVDownload,
615                 &cluster.Services.Websocket,
616                 &cluster.Services.Workbench1,
617         } {
618                 if svc == &cluster.Services.DispatchCloud && super.ClusterType == "test" {
619                         continue
620                 }
621                 if svc.ExternalURL.Host == "" {
622                         if svc == &cluster.Services.Controller ||
623                                 svc == &cluster.Services.GitHTTP ||
624                                 svc == &cluster.Services.Health ||
625                                 svc == &cluster.Services.Keepproxy ||
626                                 svc == &cluster.Services.WebDAV ||
627                                 svc == &cluster.Services.WebDAVDownload ||
628                                 svc == &cluster.Services.Workbench1 {
629                                 svc.ExternalURL = arvados.URL{Scheme: "https", Host: fmt.Sprintf("%s:%s", super.ListenHost, nextPort(super.ListenHost)), Path: "/"}
630                         } else if svc == &cluster.Services.Websocket {
631                                 svc.ExternalURL = arvados.URL{Scheme: "wss", Host: fmt.Sprintf("%s:%s", super.ListenHost, nextPort(super.ListenHost)), Path: "/websocket"}
632                         }
633                 }
634                 if len(svc.InternalURLs) == 0 {
635                         svc.InternalURLs = map[arvados.URL]arvados.ServiceInstance{
636                                 arvados.URL{Scheme: "http", Host: fmt.Sprintf("%s:%s", super.ListenHost, nextPort(super.ListenHost)), Path: "/"}: arvados.ServiceInstance{},
637                         }
638                 }
639         }
640         if cluster.SystemRootToken == "" {
641                 cluster.SystemRootToken = randomHexString(64)
642         }
643         if cluster.ManagementToken == "" {
644                 cluster.ManagementToken = randomHexString(64)
645         }
646         if cluster.API.RailsSessionSecretToken == "" {
647                 cluster.API.RailsSessionSecretToken = randomHexString(64)
648         }
649         if cluster.Collections.BlobSigningKey == "" {
650                 cluster.Collections.BlobSigningKey = randomHexString(64)
651         }
652         if super.ClusterType != "production" && cluster.Containers.DispatchPrivateKey == "" {
653                 buf, err := ioutil.ReadFile(filepath.Join(super.SourcePath, "lib", "dispatchcloud", "test", "sshkey_dispatch"))
654                 if err != nil {
655                         return err
656                 }
657                 cluster.Containers.DispatchPrivateKey = string(buf)
658         }
659         if super.ClusterType != "production" {
660                 cluster.TLS.Insecure = true
661         }
662         if super.ClusterType == "test" {
663                 // Add a second keepstore process.
664                 cluster.Services.Keepstore.InternalURLs[arvados.URL{Scheme: "http", Host: fmt.Sprintf("%s:%s", super.ListenHost, nextPort(super.ListenHost)), Path: "/"}] = arvados.ServiceInstance{}
665
666                 // Create a directory-backed volume for each keepstore
667                 // process.
668                 cluster.Volumes = map[string]arvados.Volume{}
669                 for url := range cluster.Services.Keepstore.InternalURLs {
670                         volnum := len(cluster.Volumes)
671                         datadir := fmt.Sprintf("%s/keep%d.data", super.tempdir, volnum)
672                         if _, err = os.Stat(datadir + "/."); err == nil {
673                         } else if !os.IsNotExist(err) {
674                                 return err
675                         } else if err = os.Mkdir(datadir, 0755); err != nil {
676                                 return err
677                         }
678                         cluster.Volumes[fmt.Sprintf(cluster.ClusterID+"-nyw5e-%015d", volnum)] = arvados.Volume{
679                                 Driver:           "Directory",
680                                 DriverParameters: json.RawMessage(fmt.Sprintf(`{"Root":%q}`, datadir)),
681                                 AccessViaHosts: map[arvados.URL]arvados.VolumeAccess{
682                                         url: {},
683                                 },
684                         }
685                 }
686         }
687         if super.OwnTemporaryDatabase {
688                 cluster.PostgreSQL.Connection = arvados.PostgreSQLConnection{
689                         "client_encoding": "utf8",
690                         "host":            "localhost",
691                         "port":            nextPort(super.ListenHost),
692                         "dbname":          "arvados_test",
693                         "user":            "arvados",
694                         "password":        "insecure_arvados_test",
695                 }
696         }
697
698         cfg.Clusters[cluster.ClusterID] = *cluster
699         return nil
700 }
701
702 func addrIsLocal(addr string) (bool, error) {
703         return true, nil
704         listener, err := net.Listen("tcp", addr)
705         if err == nil {
706                 listener.Close()
707                 return true, nil
708         } else if strings.Contains(err.Error(), "cannot assign requested address") {
709                 return false, nil
710         } else {
711                 return false, err
712         }
713 }
714
715 func randomHexString(chars int) string {
716         b := make([]byte, chars/2)
717         _, err := rand.Read(b)
718         if err != nil {
719                 panic(err)
720         }
721         return fmt.Sprintf("%x", b)
722 }
723
724 func internalPort(svc arvados.Service) (string, error) {
725         if len(svc.InternalURLs) > 1 {
726                 return "", errors.New("internalPort() doesn't work with multiple InternalURLs")
727         }
728         for u := range svc.InternalURLs {
729                 u := url.URL(u)
730                 if p := u.Port(); p != "" {
731                         return p, nil
732                 } else if u.Scheme == "https" || u.Scheme == "ws" {
733                         return "443", nil
734                 } else {
735                         return "80", nil
736                 }
737         }
738         return "", fmt.Errorf("service has no InternalURLs")
739 }
740
741 func externalPort(svc arvados.Service) (string, error) {
742         u := url.URL(svc.ExternalURL)
743         if p := u.Port(); p != "" {
744                 return p, nil
745         } else if u.Scheme == "https" || u.Scheme == "wss" {
746                 return "443", nil
747         } else {
748                 return "80", nil
749         }
750 }
751
752 func availablePort(host string) (string, error) {
753         ln, err := net.Listen("tcp", net.JoinHostPort(host, "0"))
754         if err != nil {
755                 return "", err
756         }
757         defer ln.Close()
758         _, port, err := net.SplitHostPort(ln.Addr().String())
759         if err != nil {
760                 return "", err
761         }
762         return port, nil
763 }
764
765 // Try to connect to addr until it works, then close ch. Give up if
766 // ctx cancels.
767 func waitForConnect(ctx context.Context, addr string) error {
768         dialer := net.Dialer{Timeout: time.Second}
769         for ctx.Err() == nil {
770                 conn, err := dialer.DialContext(ctx, "tcp", addr)
771                 if err != nil {
772                         time.Sleep(time.Second / 10)
773                         continue
774                 }
775                 conn.Close()
776                 return nil
777         }
778         return ctx.Err()
779 }
780
781 func copyConfig(cfg *arvados.Config) *arvados.Config {
782         pr, pw := io.Pipe()
783         go func() {
784                 err := json.NewEncoder(pw).Encode(cfg)
785                 if err != nil {
786                         panic(err)
787                 }
788                 pw.Close()
789         }()
790         cfg2 := new(arvados.Config)
791         err := json.NewDecoder(pr).Decode(cfg2)
792         if err != nil {
793                 panic(err)
794         }
795         return cfg2
796 }
797
798 func watchConfig(ctx context.Context, logger logrus.FieldLogger, cfgPath string, prevcfg *arvados.Config, fn func()) {
799         watcher, err := fsnotify.NewWatcher()
800         if err != nil {
801                 logger.WithError(err).Error("fsnotify setup failed")
802                 return
803         }
804         defer watcher.Close()
805
806         err = watcher.Add(cfgPath)
807         if err != nil {
808                 logger.WithError(err).Error("fsnotify watcher failed")
809                 return
810         }
811
812         for {
813                 select {
814                 case <-ctx.Done():
815                         return
816                 case err, ok := <-watcher.Errors:
817                         if !ok {
818                                 return
819                         }
820                         logger.WithError(err).Warn("fsnotify watcher reported error")
821                 case _, ok := <-watcher.Events:
822                         if !ok {
823                                 return
824                         }
825                         for len(watcher.Events) > 0 {
826                                 <-watcher.Events
827                         }
828                         loader := config.NewLoader(&bytes.Buffer{}, &logrus.Logger{Out: ioutil.Discard})
829                         loader.Path = cfgPath
830                         loader.SkipAPICalls = true
831                         cfg, err := loader.Load()
832                         if err != nil {
833                                 logger.WithError(err).Warn("error reloading config file after change detected; ignoring new config for now")
834                         } else if reflect.DeepEqual(cfg, prevcfg) {
835                                 logger.Debug("config file changed but is still DeepEqual to the existing config")
836                         } else {
837                                 logger.Debug("config changed, notifying supervisor")
838                                 fn()
839                                 prevcfg = cfg
840                         }
841                 }
842         }
843 }