Merge branch '18696-rnaseq-training' refs #18696
[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         // Config file location like "/etc/arvados/config.yml", or "-"
41         // to read from Stdin (see below).
42         ConfigPath string
43         // Literal config file (useful for test suites). If non-empty,
44         // this is used instead of ConfigPath.
45         ConfigYAML string
46         // Path to arvados source tree. Only used for dev/test
47         // clusters.
48         SourcePath string
49         // Version number to build into binaries. Only used for
50         // dev/test clusters.
51         SourceVersion string
52         // "production", "development", or "test".
53         ClusterType string
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
58         // (0.0.0.0).
59         ListenHost string
60         // Default host:port for controller ExternalURL if not
61         // explicitly configured in config file. If blank, use a
62         // random port on ListenHost.
63         ControllerAddr string
64         // Path to arvados-workbench2 source tree checkout.
65         Workbench2Source     string
66         NoWorkbench1         bool
67         NoWorkbench2         bool
68         OwnTemporaryDatabase bool
69         Stdin                io.Reader
70         Stderr               io.Writer
71
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
75
76         ctx           context.Context
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
83
84         bindir     string
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
87         configfile string
88         environ    []string // for child processes
89 }
90
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
95         }
96         for id, super2 := range super.children {
97                 m[id] = super2.Cluster("")
98         }
99         return m
100 }
101
102 func (super *Supervisor) Cluster(id string) *arvados.Cluster {
103         if super.children != nil {
104                 return super.children[id].Cluster(id)
105         } else {
106                 return super.cluster
107         }
108 }
109
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{})
114
115         sigch := make(chan os.Signal)
116         signal.Notify(sigch, syscall.SIGINT, syscall.SIGTERM)
117         defer signal.Stop(sigch)
118         go func() {
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)
123                         }
124                         super.cancel()
125                 }
126         }()
127
128         hupch := make(chan os.Signal)
129         signal.Notify(hupch, syscall.SIGHUP)
130         defer signal.Stop(hupch)
131         go func() {
132                 for sig := range hupch {
133                         super.logger.WithField("signal", sig).Info("caught signal")
134                         if super.err == nil {
135                                 super.err = errNeedConfigReload
136                         }
137                         super.cancel()
138                 }
139         }()
140
141         loaderStdin := super.Stdin
142         if super.ConfigYAML != "" {
143                 loaderStdin = bytes.NewBufferString(super.ConfigYAML)
144         }
145         loader := config.NewLoader(loaderStdin, super.logger)
146         loader.SkipLegacy = true
147         loader.SkipAPICalls = true
148         loader.Path = super.ConfigPath
149         if super.ConfigYAML != "" {
150                 loader.Path = "-"
151         }
152         cfg, err := loader.Load()
153         if err != nil {
154                 super.err = err
155                 close(super.done)
156                 super.cancel()
157                 return
158         }
159
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
164                         }
165                         super.cancel()
166                 })
167         }
168
169         if len(cfg.Clusters) > 1 {
170                 super.startFederation(cfg)
171                 go func() {
172                         defer super.cancel()
173                         defer close(super.done)
174                         for _, super2 := range super.children {
175                                 err := super2.Wait()
176                                 if super.err == nil {
177                                         super.err = err
178                                 }
179                         }
180                 }()
181         } else {
182                 go func() {
183                         defer super.cancel()
184                         defer close(super.done)
185                         super.cluster, super.err = cfg.GetCluster("")
186                         if super.err != nil {
187                                 return
188                         }
189                         err := super.runCluster()
190                         if err != nil {
191                                 super.logger.WithError(err).Info("supervisor shut down")
192                                 if super.err == nil {
193                                         super.err = err
194                                 }
195                         }
196                 }()
197         }
198 }
199
200 // Wait returns when all child processes and goroutines have exited.
201 func (super *Supervisor) Wait() error {
202         <-super.done
203         return super.err
204 }
205
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 {
212                 super2 := *super
213                 yaml, err := json.Marshal(arvados.Config{Clusters: map[string]arvados.Cluster{id: cc}})
214                 if err != nil {
215                         panic(fmt.Sprintf("json.Marshal partial config: %s", err))
216                 }
217                 super2.ConfigYAML = string(yaml)
218                 super2.ConfigPath = "-"
219                 super2.children = nil
220
221                 if super2.ClusterType == "test" {
222                         super2.Stderr = &service.LogPrefixer{
223                                 Writer: super.Stderr,
224                                 Prefix: []byte("[" + id + "] "),
225                         }
226                 }
227                 super2.Start(super.ctx)
228                 super.children[id] = &super2
229         }
230 }
231
232 func (super *Supervisor) runCluster() error {
233         cwd, err := os.Getwd()
234         if err != nil {
235                 return err
236         }
237         if super.ClusterType == "test" && super.SourcePath == "" {
238                 // When invoked by test suite, default to current
239                 // source tree
240                 buf, err := exec.Command("git", "rev-parse", "--show-toplevel").CombinedOutput()
241                 if err != nil {
242                         return fmt.Errorf("git rev-parse: %w", err)
243                 }
244                 super.SourcePath = strings.TrimSuffix(string(buf), "\n")
245         } else if !strings.HasPrefix(super.SourcePath, "/") {
246                 super.SourcePath = filepath.Join(cwd, super.SourcePath)
247         }
248         super.SourcePath, err = filepath.EvalSymlinks(super.SourcePath)
249         if err != nil {
250                 return err
251         }
252
253         if super.ListenHost == "" {
254                 if urlhost := super.cluster.Services.Controller.ExternalURL.Host; urlhost != "" {
255                         if h, _, _ := net.SplitHostPort(urlhost); h != "" {
256                                 super.ListenHost = h
257                         } else {
258                                 super.ListenHost = urlhost
259                         }
260                 } else {
261                         super.ListenHost = "0.0.0.0"
262                 }
263         }
264
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
270                 // package).
271                 super.tempdir = "/var/lib/arvados/tmp"
272                 super.wwwtempdir = "/var/lib/arvados/wwwtmp"
273                 super.bindir = "/var/lib/arvados/bin"
274         } else {
275                 super.tempdir, err = ioutil.TempDir("", "arvados-server-boot-")
276                 if err != nil {
277                         return err
278                 }
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 {
283                         return err
284                 }
285         }
286
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()
290         if err != nil {
291                 return err
292         }
293         conffile, err := os.OpenFile(filepath.Join(super.wwwtempdir, "config.yml"), os.O_CREATE|os.O_WRONLY, 0644)
294         if err != nil {
295                 return err
296         }
297         defer conffile.Close()
298         err = json.NewEncoder(conffile).Encode(arvados.Config{
299                 Clusters: map[string]arvados.Cluster{
300                         super.cluster.ClusterID: *super.cluster}})
301         if err != nil {
302                 return err
303         }
304         err = conffile.Close()
305         if err != nil {
306                 return err
307         }
308         super.configfile = conffile.Name()
309
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:")
318         }
319
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" {
324                 loglevel = "debug"
325         }
326         super.logger = ctxlog.New(super.Stderr, super.cluster.SystemLogs.Format, loglevel).WithFields(logrus.Fields{
327                 "PID": os.Getpid(),
328         })
329
330         if super.SourceVersion == "" && super.ClusterType == "production" {
331                 // don't need SourceVersion
332         } else if super.SourceVersion == "" {
333                 // Find current source tree version.
334                 var buf bytes.Buffer
335                 err = super.RunProgram(super.ctx, ".", runOptions{output: &buf}, "git", "diff", "--shortstat")
336                 if err != nil {
337                         return err
338                 }
339                 dirty := buf.Len() > 0
340                 buf.Reset()
341                 err = super.RunProgram(super.ctx, ".", runOptions{output: &buf}, "git", "log", "-n1", "--format=%H")
342                 if err != nil {
343                         return err
344                 }
345                 super.SourceVersion = strings.TrimSpace(buf.String())
346                 if dirty {
347                         super.SourceVersion += "+uncommitted"
348                 }
349         } else {
350                 return errors.New("specifying a version to run is not yet supported")
351         }
352
353         _, err = super.installGoProgram(super.ctx, "cmd/arvados-server")
354         if err != nil {
355                 return err
356         }
357         err = super.setupRubyEnv()
358         if err != nil {
359                 return err
360         }
361
362         tasks := []supervisedTask{
363                 createCertificates{},
364                 runPostgreSQL{},
365                 runNginx{},
366                 runServiceCommand{name: "controller", svc: super.cluster.Services.Controller, depends: []supervisedTask{seedDatabase{}}},
367                 runGoProgram{src: "services/arv-git-httpd", svc: super.cluster.Services.GitHTTP},
368                 runGoProgram{src: "services/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                 runGoProgram{src: "services/keep-web", svc: super.cluster.Services.WebDAV},
372                 runServiceCommand{name: "ws", svc: super.cluster.Services.Websocket, depends: []supervisedTask{seedDatabase{}}},
373                 installPassenger{src: "services/api"},
374                 runPassenger{src: "services/api", varlibdir: "railsapi", svc: super.cluster.Services.RailsAPI, depends: []supervisedTask{createCertificates{}, seedDatabase{}, installPassenger{src: "services/api"}}},
375                 seedDatabase{},
376         }
377         if !super.NoWorkbench1 {
378                 tasks = append(tasks,
379                         installPassenger{src: "apps/workbench", 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"}}},
381                 )
382         }
383         if !super.NoWorkbench2 {
384                 tasks = append(tasks,
385                         runWorkbench2{svc: super.cluster.Services.Workbench2},
386                 )
387         }
388         if super.ClusterType != "test" {
389                 tasks = append(tasks,
390                         runServiceCommand{name: "dispatch-cloud", svc: super.cluster.Services.DispatchCloud},
391                         runGoProgram{src: "services/keep-balance", svc: super.cluster.Services.Keepbalance},
392                 )
393         }
394         super.tasksReady = map[string]chan bool{}
395         for _, task := range tasks {
396                 super.tasksReady[task.String()] = make(chan bool)
397         }
398         for _, task := range tasks {
399                 task := task
400                 fail := func(err error) {
401                         if super.ctx.Err() != nil {
402                                 return
403                         }
404                         super.cancel()
405                         super.logger.WithField("task", task.String()).WithError(err).Error("task failed")
406                 }
407                 go func() {
408                         super.logger.WithField("task", task.String()).Info("starting")
409                         err := task.Run(super.ctx, fail, super)
410                         if err != nil {
411                                 fail(err)
412                                 return
413                         }
414                         close(super.tasksReady[task.String()])
415                 }()
416         }
417         err = super.wait(super.ctx, tasks...)
418         if err != nil {
419                 return err
420         }
421         super.logger.Info("all startup tasks are complete; starting health checks")
422         super.healthChecker = &health.Aggregator{Cluster: super.cluster}
423         <-super.ctx.Done()
424         super.logger.Info("shutting down")
425         super.waitShutdown.Wait()
426         return super.ctx.Err()
427 }
428
429 func (super *Supervisor) wait(ctx context.Context, tasks ...supervisedTask) error {
430         ticker := time.NewTicker(15 * time.Second)
431         defer ticker.Stop()
432         for _, task := range tasks {
433                 ch, ok := super.tasksReady[task.String()]
434                 if !ok {
435                         return fmt.Errorf("no such task: %s", task)
436                 }
437                 super.logger.WithField("task", task.String()).Info("waiting")
438                 for {
439                         select {
440                         case <-ch:
441                                 super.logger.WithField("task", task.String()).Info("ready")
442                         case <-ctx.Done():
443                                 super.logger.WithField("task", task.String()).Info("task was never ready")
444                                 return ctx.Err()
445                         case <-ticker.C:
446                                 super.logger.WithField("task", task.String()).Info("still waiting...")
447                                 continue
448                         }
449                         break
450                 }
451         }
452         return nil
453 }
454
455 // Stop shuts down all child processes and goroutines, and returns
456 // when all of them have exited.
457 func (super *Supervisor) Stop() {
458         super.cancel()
459         <-super.done
460 }
461
462 // WaitReady waits for the cluster(s) to be ready to handle requests,
463 // then returns true. If startup fails, it returns false.
464 func (super *Supervisor) WaitReady() bool {
465         if super.children != nil {
466                 for id, super2 := range super.children {
467                         super.logger.Infof("waiting for %s to be ready", id)
468                         if !super2.WaitReady() {
469                                 super.logger.Infof("%s startup failed", id)
470                                 return false
471                         }
472                         super.logger.Infof("%s is ready", id)
473                 }
474                 super.logger.Info("all clusters are ready")
475                 return true
476         }
477         ticker := time.NewTicker(time.Second)
478         defer ticker.Stop()
479         for waiting := "all"; waiting != ""; {
480                 select {
481                 case <-ticker.C:
482                 case <-super.ctx.Done():
483                         return false
484                 }
485                 if super.healthChecker == nil {
486                         // not set up yet
487                         continue
488                 }
489                 resp := super.healthChecker.ClusterHealth()
490                 // The overall health check (resp.Health=="OK") might
491                 // never pass due to missing components (like
492                 // arvados-dispatch-cloud in a test cluster), so
493                 // instead we wait for all configured components to
494                 // pass.
495                 waiting = ""
496                 for target, check := range resp.Checks {
497                         if check.Health != "OK" {
498                                 waiting += " " + target
499                         }
500                 }
501                 if waiting != "" {
502                         super.logger.WithField("targets", waiting[1:]).Info("waiting")
503                 }
504         }
505         return true
506 }
507
508 func (super *Supervisor) prependEnv(key, prepend string) {
509         for i, s := range super.environ {
510                 if strings.HasPrefix(s, key+"=") {
511                         super.environ[i] = key + "=" + prepend + s[len(key)+1:]
512                         return
513                 }
514         }
515         super.environ = append(super.environ, key+"="+prepend)
516 }
517
518 func (super *Supervisor) cleanEnv(prefixes []string) {
519         var cleaned []string
520         for _, s := range super.environ {
521                 drop := false
522                 for _, p := range prefixes {
523                         if strings.HasPrefix(s, p) {
524                                 drop = true
525                                 break
526                         }
527                 }
528                 if !drop {
529                         cleaned = append(cleaned, s)
530                 }
531         }
532         super.environ = cleaned
533 }
534
535 func (super *Supervisor) setEnv(key, val string) {
536         for i, s := range super.environ {
537                 if strings.HasPrefix(s, key+"=") {
538                         super.environ[i] = key + "=" + val
539                         return
540                 }
541         }
542         super.environ = append(super.environ, key+"="+val)
543 }
544
545 // Remove all but the first occurrence of each env var.
546 func dedupEnv(in []string) []string {
547         saw := map[string]bool{}
548         var out []string
549         for _, kv := range in {
550                 if split := strings.Index(kv, "="); split < 1 {
551                         panic("invalid environment var: " + kv)
552                 } else if saw[kv[:split]] {
553                         continue
554                 } else {
555                         saw[kv[:split]] = true
556                         out = append(out, kv)
557                 }
558         }
559         return out
560 }
561
562 func (super *Supervisor) installGoProgram(ctx context.Context, srcpath string) (string, error) {
563         _, basename := filepath.Split(srcpath)
564         binfile := filepath.Join(super.bindir, basename)
565         if super.ClusterType == "production" {
566                 return binfile, nil
567         }
568         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)
569         return binfile, err
570 }
571
572 func (super *Supervisor) usingRVM() bool {
573         return os.Getenv("rvm_path") != ""
574 }
575
576 func (super *Supervisor) setupRubyEnv() error {
577         if !super.usingRVM() {
578                 // (If rvm is in use, assume the caller has everything
579                 // set up as desired)
580                 super.cleanEnv([]string{
581                         "GEM_HOME=",
582                         "GEM_PATH=",
583                 })
584                 gem := "gem"
585                 if _, err := os.Stat("/var/lib/arvados/bin/gem"); err == nil || super.ClusterType == "production" {
586                         gem = "/var/lib/arvados/bin/gem"
587                 }
588                 cmd := exec.Command(gem, "env", "gempath")
589                 if super.ClusterType == "production" {
590                         cmd.Args = append([]string{"sudo", "-u", "www-data", "-E", "HOME=/var/www"}, cmd.Args...)
591                         path, err := exec.LookPath("sudo")
592                         if err != nil {
593                                 return fmt.Errorf("LookPath(\"sudo\"): %w", err)
594                         }
595                         cmd.Path = path
596                 }
597                 cmd.Stderr = super.Stderr
598                 cmd.Env = super.environ
599                 buf, err := cmd.Output() // /var/lib/arvados/.gem/ruby/2.5.0/bin:...
600                 if err != nil || len(buf) == 0 {
601                         return fmt.Errorf("gem env gempath: %w", err)
602                 }
603                 gempath := string(bytes.Split(buf, []byte{':'})[0])
604                 super.prependEnv("PATH", gempath+"/bin:")
605                 super.setEnv("GEM_HOME", gempath)
606                 super.setEnv("GEM_PATH", gempath)
607         }
608         // Passenger install doesn't work unless $HOME is ~user
609         u, err := user.Current()
610         if err != nil {
611                 return err
612         }
613         super.setEnv("HOME", u.HomeDir)
614         return nil
615 }
616
617 func (super *Supervisor) lookPath(prog string) string {
618         for _, val := range super.environ {
619                 if strings.HasPrefix(val, "PATH=") {
620                         for _, dir := range filepath.SplitList(val[5:]) {
621                                 path := filepath.Join(dir, prog)
622                                 if fi, err := os.Stat(path); err == nil && fi.Mode()&0111 != 0 {
623                                         return path
624                                 }
625                         }
626                 }
627         }
628         return prog
629 }
630
631 type runOptions struct {
632         output io.Writer // attach stdout
633         env    []string  // add/replace environment variables
634         user   string    // run as specified user
635         stdin  io.Reader
636 }
637
638 // RunProgram runs prog with args, using dir as working directory. If ctx is
639 // cancelled while the child is running, RunProgram terminates the child, waits
640 // for it to exit, then returns.
641 //
642 // Child's environment will have our env vars, plus any given in env.
643 //
644 // Child's stdout will be written to output if non-nil, otherwise the
645 // boot command's stderr.
646 func (super *Supervisor) RunProgram(ctx context.Context, dir string, opts runOptions, prog string, args ...string) error {
647         cmdline := fmt.Sprintf("%s", append([]string{prog}, args...))
648         super.logger.WithField("command", cmdline).WithField("dir", dir).Info("executing")
649
650         logprefix := prog
651         {
652                 innerargs := args
653                 if logprefix == "sudo" {
654                         for i := 0; i < len(args); i++ {
655                                 if args[i] == "-u" {
656                                         i++
657                                 } else if args[i] == "-E" || strings.Contains(args[i], "=") {
658                                 } else {
659                                         logprefix = args[i]
660                                         innerargs = args[i+1:]
661                                         break
662                                 }
663                         }
664                 }
665                 logprefix = strings.TrimPrefix(logprefix, "/var/lib/arvados/bin/")
666                 logprefix = strings.TrimPrefix(logprefix, super.tempdir+"/bin/")
667                 if logprefix == "bundle" && len(innerargs) > 2 && innerargs[0] == "exec" {
668                         _, dirbase := filepath.Split(dir)
669                         logprefix = innerargs[1] + "@" + dirbase
670                 } else if logprefix == "arvados-server" && len(args) > 1 {
671                         logprefix = args[0]
672                 }
673                 if !strings.HasPrefix(dir, "/") {
674                         logprefix = dir + ": " + logprefix
675                 }
676         }
677
678         cmd := exec.Command(super.lookPath(prog), args...)
679         cmd.Stdin = opts.stdin
680         stdout, err := cmd.StdoutPipe()
681         if err != nil {
682                 return err
683         }
684         stderr, err := cmd.StderrPipe()
685         if err != nil {
686                 return err
687         }
688         logwriter := &service.LogPrefixer{Writer: super.Stderr, Prefix: []byte("[" + logprefix + "] ")}
689         var copiers sync.WaitGroup
690         copiers.Add(1)
691         go func() {
692                 io.Copy(logwriter, stderr)
693                 copiers.Done()
694         }()
695         copiers.Add(1)
696         go func() {
697                 if opts.output == nil {
698                         io.Copy(logwriter, stdout)
699                 } else {
700                         io.Copy(opts.output, stdout)
701                 }
702                 copiers.Done()
703         }()
704
705         if strings.HasPrefix(dir, "/") {
706                 cmd.Dir = dir
707         } else {
708                 cmd.Dir = filepath.Join(super.SourcePath, dir)
709         }
710         env := append([]string(nil), opts.env...)
711         env = append(env, super.environ...)
712         cmd.Env = dedupEnv(env)
713
714         if opts.user != "" {
715                 // Note: We use this approach instead of "sudo"
716                 // because in certain circumstances (we are pid 1 in a
717                 // docker container, and our passenger child process
718                 // changes to pgid 1) the intermediate sudo process
719                 // notices we have the same pgid as our child and
720                 // refuses to propagate signals from us to our child,
721                 // so we can't signal/shutdown our passenger/rails
722                 // apps. "chpst" or "setuidgid" would work, but these
723                 // few lines avoid depending on runit/daemontools.
724                 u, err := user.Lookup(opts.user)
725                 if err != nil {
726                         return fmt.Errorf("user.Lookup(%q): %w", opts.user, err)
727                 }
728                 uid, _ := strconv.Atoi(u.Uid)
729                 gid, _ := strconv.Atoi(u.Gid)
730                 cmd.SysProcAttr = &syscall.SysProcAttr{
731                         Credential: &syscall.Credential{
732                                 Uid: uint32(uid),
733                                 Gid: uint32(gid),
734                         },
735                 }
736         }
737
738         exited := false
739         defer func() { exited = true }()
740         go func() {
741                 <-ctx.Done()
742                 log := ctxlog.FromContext(ctx).WithFields(logrus.Fields{"dir": dir, "cmdline": cmdline})
743                 for !exited {
744                         if cmd.Process == nil {
745                                 log.Debug("waiting for child process to start")
746                                 time.Sleep(time.Second / 2)
747                         } else {
748                                 log.WithField("PID", cmd.Process.Pid).Debug("sending SIGTERM")
749                                 cmd.Process.Signal(syscall.SIGTERM)
750                                 time.Sleep(5 * time.Second)
751                                 if !exited {
752                                         stdout.Close()
753                                         stderr.Close()
754                                         log.WithField("PID", cmd.Process.Pid).Warn("still waiting for child process to exit 5s after SIGTERM")
755                                 }
756                         }
757                 }
758         }()
759
760         err = cmd.Start()
761         if err != nil {
762                 return err
763         }
764         copiers.Wait()
765         err = cmd.Wait()
766         if ctx.Err() != nil {
767                 // Return "context canceled", instead of the "killed"
768                 // error that was probably caused by the context being
769                 // canceled.
770                 return ctx.Err()
771         } else if err != nil {
772                 return fmt.Errorf("%s: error: %v", cmdline, err)
773         }
774         return nil
775 }
776
777 func (super *Supervisor) autofillConfig() error {
778         usedPort := map[string]bool{}
779         nextPort := func(host string) (string, error) {
780                 for {
781                         port, err := availablePort(host)
782                         if err != nil {
783                                 port, err = availablePort(super.ListenHost)
784                         }
785                         if err != nil {
786                                 return "", err
787                         }
788                         if usedPort[port] {
789                                 continue
790                         }
791                         usedPort[port] = true
792                         return port, nil
793                 }
794         }
795         if super.cluster.Services.Controller.ExternalURL.Host == "" {
796                 h, p, err := net.SplitHostPort(super.ControllerAddr)
797                 if err != nil && super.ControllerAddr != "" {
798                         return fmt.Errorf("SplitHostPort(ControllerAddr %q): %w", super.ControllerAddr, err)
799                 }
800                 if h == "" {
801                         h = super.ListenHost
802                 }
803                 if p == "0" || p == "" {
804                         p, err = nextPort(h)
805                         if err != nil {
806                                 return err
807                         }
808                 }
809                 super.cluster.Services.Controller.ExternalURL = arvados.URL{Scheme: "https", Host: net.JoinHostPort(h, p), Path: "/"}
810         }
811         u := url.URL(super.cluster.Services.Controller.ExternalURL)
812         defaultExtHost := u.Hostname()
813         for _, svc := range []*arvados.Service{
814                 &super.cluster.Services.Controller,
815                 &super.cluster.Services.DispatchCloud,
816                 &super.cluster.Services.GitHTTP,
817                 &super.cluster.Services.Health,
818                 &super.cluster.Services.Keepproxy,
819                 &super.cluster.Services.Keepstore,
820                 &super.cluster.Services.RailsAPI,
821                 &super.cluster.Services.WebDAV,
822                 &super.cluster.Services.WebDAVDownload,
823                 &super.cluster.Services.Websocket,
824                 &super.cluster.Services.Workbench1,
825                 &super.cluster.Services.Workbench2,
826         } {
827                 if svc == &super.cluster.Services.DispatchCloud && super.ClusterType == "test" {
828                         continue
829                 }
830                 if svc.ExternalURL.Host == "" {
831                         port, err := nextPort(defaultExtHost)
832                         if err != nil {
833                                 return err
834                         }
835                         host := net.JoinHostPort(defaultExtHost, port)
836                         if svc == &super.cluster.Services.Controller ||
837                                 svc == &super.cluster.Services.GitHTTP ||
838                                 svc == &super.cluster.Services.Health ||
839                                 svc == &super.cluster.Services.Keepproxy ||
840                                 svc == &super.cluster.Services.WebDAV ||
841                                 svc == &super.cluster.Services.WebDAVDownload ||
842                                 svc == &super.cluster.Services.Workbench1 ||
843                                 svc == &super.cluster.Services.Workbench2 {
844                                 svc.ExternalURL = arvados.URL{Scheme: "https", Host: host, Path: "/"}
845                         } else if svc == &super.cluster.Services.Websocket {
846                                 svc.ExternalURL = arvados.URL{Scheme: "wss", Host: host, Path: "/websocket"}
847                         }
848                 }
849                 if super.NoWorkbench1 && svc == &super.cluster.Services.Workbench1 ||
850                         super.NoWorkbench2 && svc == &super.cluster.Services.Workbench2 {
851                         // When workbench1 is disabled, it gets an
852                         // ExternalURL (so we have a valid listening
853                         // port to write in our Nginx config) but no
854                         // InternalURLs (so health checker doesn't
855                         // complain).
856                         continue
857                 }
858                 if len(svc.InternalURLs) == 0 {
859                         port, err := nextPort(super.ListenHost)
860                         if err != nil {
861                                 return err
862                         }
863                         host := net.JoinHostPort(super.ListenHost, port)
864                         svc.InternalURLs = map[arvados.URL]arvados.ServiceInstance{
865                                 {Scheme: "http", Host: host, Path: "/"}: {},
866                         }
867                 }
868         }
869         if super.ClusterType != "production" {
870                 if super.cluster.SystemRootToken == "" {
871                         super.cluster.SystemRootToken = randomHexString(64)
872                 }
873                 if super.cluster.ManagementToken == "" {
874                         super.cluster.ManagementToken = randomHexString(64)
875                 }
876                 if super.cluster.Collections.BlobSigningKey == "" {
877                         super.cluster.Collections.BlobSigningKey = randomHexString(64)
878                 }
879                 if super.cluster.Users.AnonymousUserToken == "" {
880                         super.cluster.Users.AnonymousUserToken = randomHexString(64)
881                 }
882                 if super.cluster.Containers.DispatchPrivateKey == "" {
883                         buf, err := ioutil.ReadFile(filepath.Join(super.SourcePath, "lib", "dispatchcloud", "test", "sshkey_dispatch"))
884                         if err != nil {
885                                 return err
886                         }
887                         super.cluster.Containers.DispatchPrivateKey = string(buf)
888                 }
889                 super.cluster.TLS.Insecure = true
890         }
891         if super.ClusterType == "test" {
892                 // Add a second keepstore process.
893                 port, err := nextPort(super.ListenHost)
894                 if err != nil {
895                         return err
896                 }
897                 host := net.JoinHostPort(super.ListenHost, port)
898                 super.cluster.Services.Keepstore.InternalURLs[arvados.URL{Scheme: "http", Host: host, Path: "/"}] = arvados.ServiceInstance{}
899
900                 // Create a directory-backed volume for each keepstore
901                 // process.
902                 super.cluster.Volumes = map[string]arvados.Volume{}
903                 for url := range super.cluster.Services.Keepstore.InternalURLs {
904                         volnum := len(super.cluster.Volumes)
905                         datadir := fmt.Sprintf("%s/keep%d.data", super.tempdir, volnum)
906                         if _, err = os.Stat(datadir + "/."); err == nil {
907                         } else if !os.IsNotExist(err) {
908                                 return err
909                         } else if err = os.Mkdir(datadir, 0755); err != nil {
910                                 return err
911                         }
912                         super.cluster.Volumes[fmt.Sprintf(super.cluster.ClusterID+"-nyw5e-%015d", volnum)] = arvados.Volume{
913                                 Driver:           "Directory",
914                                 DriverParameters: json.RawMessage(fmt.Sprintf(`{"Root":%q}`, datadir)),
915                                 AccessViaHosts: map[arvados.URL]arvados.VolumeAccess{
916                                         url: {},
917                                 },
918                                 StorageClasses: map[string]bool{
919                                         "default": true,
920                                         "foo":     true,
921                                         "bar":     true,
922                                 },
923                         }
924                 }
925                 super.cluster.StorageClasses = map[string]arvados.StorageClassConfig{
926                         "default": {Default: true},
927                         "foo":     {},
928                         "bar":     {},
929                 }
930         }
931         if super.OwnTemporaryDatabase {
932                 port, err := nextPort("localhost")
933                 if err != nil {
934                         return err
935                 }
936                 super.cluster.PostgreSQL.Connection = arvados.PostgreSQLConnection{
937                         "client_encoding": "utf8",
938                         "host":            "localhost",
939                         "port":            port,
940                         "dbname":          "arvados_test",
941                         "user":            "arvados",
942                         "password":        "insecure_arvados_test",
943                 }
944         }
945         return nil
946 }
947
948 func addrIsLocal(addr string) (bool, error) {
949         if h, _, err := net.SplitHostPort(addr); err != nil {
950                 return false, err
951         } else {
952                 addr = net.JoinHostPort(h, "0")
953         }
954         listener, err := net.Listen("tcp", addr)
955         if err == nil {
956                 listener.Close()
957                 return true, nil
958         } else if strings.Contains(err.Error(), "cannot assign requested address") {
959                 return false, nil
960         } else {
961                 return false, err
962         }
963 }
964
965 func randomHexString(chars int) string {
966         b := make([]byte, chars/2)
967         _, err := rand.Read(b)
968         if err != nil {
969                 panic(err)
970         }
971         return fmt.Sprintf("%x", b)
972 }
973
974 func internalPort(svc arvados.Service) (host, port string, err error) {
975         if len(svc.InternalURLs) > 1 {
976                 return "", "", errors.New("internalPort() doesn't work with multiple InternalURLs")
977         }
978         for u := range svc.InternalURLs {
979                 u := url.URL(u)
980                 host, port = u.Hostname(), u.Port()
981                 switch {
982                 case port != "":
983                 case u.Scheme == "https", u.Scheme == "ws":
984                         port = "443"
985                 default:
986                         port = "80"
987                 }
988                 return
989         }
990         return "", "", fmt.Errorf("service has no InternalURLs")
991 }
992
993 func externalPort(svc arvados.Service) (string, error) {
994         u := url.URL(svc.ExternalURL)
995         if p := u.Port(); p != "" {
996                 return p, nil
997         } else if u.Scheme == "https" || u.Scheme == "wss" {
998                 return "443", nil
999         } else {
1000                 return "80", nil
1001         }
1002 }
1003
1004 func availablePort(host string) (string, error) {
1005         ln, err := net.Listen("tcp", net.JoinHostPort(host, "0"))
1006         if err != nil {
1007                 return "", err
1008         }
1009         defer ln.Close()
1010         _, port, err := net.SplitHostPort(ln.Addr().String())
1011         if err != nil {
1012                 return "", err
1013         }
1014         return port, nil
1015 }
1016
1017 // Try to connect to addr until it works, then close ch. Give up if
1018 // ctx cancels.
1019 func waitForConnect(ctx context.Context, addr string) error {
1020         ctxlog.FromContext(ctx).WithField("addr", addr).Info("waitForConnect")
1021         dialer := net.Dialer{Timeout: time.Second}
1022         for ctx.Err() == nil {
1023                 conn, err := dialer.DialContext(ctx, "tcp", addr)
1024                 if err != nil {
1025                         time.Sleep(time.Second / 10)
1026                         continue
1027                 }
1028                 conn.Close()
1029                 return nil
1030         }
1031         return ctx.Err()
1032 }
1033
1034 func copyConfig(cfg *arvados.Config) *arvados.Config {
1035         pr, pw := io.Pipe()
1036         go func() {
1037                 err := json.NewEncoder(pw).Encode(cfg)
1038                 if err != nil {
1039                         panic(err)
1040                 }
1041                 pw.Close()
1042         }()
1043         cfg2 := new(arvados.Config)
1044         err := json.NewDecoder(pr).Decode(cfg2)
1045         if err != nil {
1046                 panic(err)
1047         }
1048         return cfg2
1049 }
1050
1051 func watchConfig(ctx context.Context, logger logrus.FieldLogger, cfgPath string, prevcfg *arvados.Config, fn func()) {
1052         watcher, err := fsnotify.NewWatcher()
1053         if err != nil {
1054                 logger.WithError(err).Error("fsnotify setup failed")
1055                 return
1056         }
1057         defer watcher.Close()
1058
1059         err = watcher.Add(cfgPath)
1060         if err != nil {
1061                 logger.WithError(err).Error("fsnotify watcher failed")
1062                 return
1063         }
1064
1065         for {
1066                 select {
1067                 case <-ctx.Done():
1068                         return
1069                 case err, ok := <-watcher.Errors:
1070                         if !ok {
1071                                 return
1072                         }
1073                         logger.WithError(err).Warn("fsnotify watcher reported error")
1074                 case _, ok := <-watcher.Events:
1075                         if !ok {
1076                                 return
1077                         }
1078                         for len(watcher.Events) > 0 {
1079                                 <-watcher.Events
1080                         }
1081                         loader := config.NewLoader(&bytes.Buffer{}, &logrus.Logger{Out: ioutil.Discard})
1082                         loader.Path = cfgPath
1083                         loader.SkipAPICalls = true
1084                         cfg, err := loader.Load()
1085                         if err != nil {
1086                                 logger.WithError(err).Warn("error reloading config file after change detected; ignoring new config for now")
1087                         } else if reflect.DeepEqual(cfg, prevcfg) {
1088                                 logger.Debug("config file changed but is still DeepEqual to the existing config")
1089                         } else {
1090                                 logger.Debug("config changed, notifying supervisor")
1091                                 fn()
1092                                 prevcfg = cfg
1093                         }
1094                 }
1095         }
1096 }