16552: boot: wait for child proc cleanup when shutting down.
[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                 runServiceCommand{name: "git-httpd", svc: super.cluster.Services.GitHTTP},
368                 runServiceCommand{name: "health", svc: super.cluster.Services.Health},
369                 runServiceCommand{name: "keepproxy", svc: super.cluster.Services.Keepproxy, depends: []supervisedTask{runPassenger{src: "services/api"}}},
370                 runServiceCommand{name: "keepstore", svc: super.cluster.Services.Keepstore},
371                 runServiceCommand{name: "keep-web", svc: super.cluster.Services.WebDAV},
372                 runServiceCommand{name: "ws", svc: super.cluster.Services.Websocket, depends: []supervisedTask{seedDatabase{}}},
373                 installPassenger{src: "services/api", varlibdir: "railsapi"},
374                 runPassenger{src: "services/api", varlibdir: "railsapi", svc: super.cluster.Services.RailsAPI, depends: []supervisedTask{createCertificates{}, seedDatabase{}, installPassenger{src: "services/api", varlibdir: "railsapi"}}},
375                 seedDatabase{},
376         }
377         if !super.NoWorkbench1 {
378                 tasks = append(tasks,
379                         installPassenger{src: "apps/workbench", varlibdir: "workbench1", depends: []supervisedTask{seedDatabase{}}}, // dependency ensures workbench doesn't delay api install/startup
380                         runPassenger{src: "apps/workbench", varlibdir: "workbench1", svc: super.cluster.Services.Workbench1, depends: []supervisedTask{installPassenger{src: "apps/workbench", varlibdir: "workbench1"}}},
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: "keep-balance", svc: super.cluster.Services.Keepbalance},
391                 )
392         }
393         if super.cluster.Containers.CloudVMs.Enable {
394                 tasks = append(tasks,
395                         runServiceCommand{name: "dispatch-cloud", svc: super.cluster.Services.DispatchCloud},
396                 )
397         }
398         super.tasksReady = map[string]chan bool{}
399         for _, task := range tasks {
400                 super.tasksReady[task.String()] = make(chan bool)
401         }
402         for _, task := range tasks {
403                 task := task
404                 fail := func(err error) {
405                         if super.ctx.Err() != nil {
406                                 return
407                         }
408                         super.cancel()
409                         super.logger.WithField("task", task.String()).WithError(err).Error("task failed")
410                 }
411                 go func() {
412                         super.logger.WithField("task", task.String()).Info("starting")
413                         err := task.Run(super.ctx, fail, super)
414                         if err != nil {
415                                 fail(err)
416                                 return
417                         }
418                         close(super.tasksReady[task.String()])
419                 }()
420         }
421         err = super.wait(super.ctx, tasks...)
422         if err != nil {
423                 return err
424         }
425         super.logger.Info("all startup tasks are complete; starting health checks")
426         super.healthChecker = &health.Aggregator{Cluster: super.cluster}
427         <-super.ctx.Done()
428         super.logger.Info("shutting down")
429         super.waitShutdown.Wait()
430         return super.ctx.Err()
431 }
432
433 func (super *Supervisor) wait(ctx context.Context, tasks ...supervisedTask) error {
434         ticker := time.NewTicker(15 * time.Second)
435         defer ticker.Stop()
436         for _, task := range tasks {
437                 ch, ok := super.tasksReady[task.String()]
438                 if !ok {
439                         return fmt.Errorf("no such task: %s", task)
440                 }
441                 super.logger.WithField("task", task.String()).Info("waiting")
442                 for {
443                         select {
444                         case <-ch:
445                                 super.logger.WithField("task", task.String()).Info("ready")
446                         case <-ctx.Done():
447                                 super.logger.WithField("task", task.String()).Info("task was never ready")
448                                 return ctx.Err()
449                         case <-ticker.C:
450                                 super.logger.WithField("task", task.String()).Info("still waiting...")
451                                 continue
452                         }
453                         break
454                 }
455         }
456         return nil
457 }
458
459 // Stop shuts down all child processes and goroutines, and returns
460 // when all of them have exited.
461 func (super *Supervisor) Stop() {
462         super.cancel()
463         <-super.done
464 }
465
466 // WaitReady waits for the cluster(s) to be ready to handle requests,
467 // then returns true. If startup fails, it returns false.
468 func (super *Supervisor) WaitReady() bool {
469         if super.children != nil {
470                 for id, super2 := range super.children {
471                         super.logger.Infof("waiting for %s to be ready", id)
472                         if !super2.WaitReady() {
473                                 super.logger.Infof("%s startup failed", id)
474                                 super.Stop()
475                                 return false
476                         }
477                         super.logger.Infof("%s is ready", id)
478                 }
479                 super.logger.Info("all clusters are ready")
480                 return true
481         }
482         ticker := time.NewTicker(time.Second)
483         defer ticker.Stop()
484         for waiting := "all"; waiting != ""; {
485                 select {
486                 case <-ticker.C:
487                 case <-super.ctx.Done():
488                         super.Stop()
489                         return false
490                 }
491                 if super.healthChecker == nil {
492                         // not set up yet
493                         continue
494                 }
495                 resp := super.healthChecker.ClusterHealth()
496                 // The overall health check (resp.Health=="OK") might
497                 // never pass due to missing components (like
498                 // arvados-dispatch-cloud in a test cluster), so
499                 // instead we wait for all configured components to
500                 // pass.
501                 waiting = ""
502                 for target, check := range resp.Checks {
503                         if check.Health != "OK" {
504                                 waiting += " " + target
505                         }
506                 }
507                 if waiting != "" {
508                         super.logger.WithField("targets", waiting[1:]).Info("waiting")
509                 }
510         }
511         return true
512 }
513
514 func (super *Supervisor) prependEnv(key, prepend string) {
515         for i, s := range super.environ {
516                 if strings.HasPrefix(s, key+"=") {
517                         super.environ[i] = key + "=" + prepend + s[len(key)+1:]
518                         return
519                 }
520         }
521         super.environ = append(super.environ, key+"="+prepend)
522 }
523
524 func (super *Supervisor) cleanEnv(prefixes []string) {
525         var cleaned []string
526         for _, s := range super.environ {
527                 drop := false
528                 for _, p := range prefixes {
529                         if strings.HasPrefix(s, p) {
530                                 drop = true
531                                 break
532                         }
533                 }
534                 if !drop {
535                         cleaned = append(cleaned, s)
536                 }
537         }
538         super.environ = cleaned
539 }
540
541 func (super *Supervisor) setEnv(key, val string) {
542         for i, s := range super.environ {
543                 if strings.HasPrefix(s, key+"=") {
544                         super.environ[i] = key + "=" + val
545                         return
546                 }
547         }
548         super.environ = append(super.environ, key+"="+val)
549 }
550
551 // Remove all but the first occurrence of each env var.
552 func dedupEnv(in []string) []string {
553         saw := map[string]bool{}
554         var out []string
555         for _, kv := range in {
556                 if split := strings.Index(kv, "="); split < 1 {
557                         panic("invalid environment var: " + kv)
558                 } else if saw[kv[:split]] {
559                         continue
560                 } else {
561                         saw[kv[:split]] = true
562                         out = append(out, kv)
563                 }
564         }
565         return out
566 }
567
568 func (super *Supervisor) installGoProgram(ctx context.Context, srcpath string) (string, error) {
569         _, basename := filepath.Split(srcpath)
570         binfile := filepath.Join(super.bindir, basename)
571         if super.ClusterType == "production" {
572                 return binfile, nil
573         }
574         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)
575         return binfile, err
576 }
577
578 func (super *Supervisor) usingRVM() bool {
579         return os.Getenv("rvm_path") != ""
580 }
581
582 func (super *Supervisor) setupRubyEnv() error {
583         if !super.usingRVM() {
584                 // (If rvm is in use, assume the caller has everything
585                 // set up as desired)
586                 super.cleanEnv([]string{
587                         "GEM_HOME=",
588                         "GEM_PATH=",
589                 })
590                 gem := "gem"
591                 if _, err := os.Stat("/var/lib/arvados/bin/gem"); err == nil || super.ClusterType == "production" {
592                         gem = "/var/lib/arvados/bin/gem"
593                 }
594                 cmd := exec.Command(gem, "env", "gempath")
595                 if super.ClusterType == "production" {
596                         cmd.Args = append([]string{"sudo", "-u", "www-data", "-E", "HOME=/var/www"}, cmd.Args...)
597                         path, err := exec.LookPath("sudo")
598                         if err != nil {
599                                 return fmt.Errorf("LookPath(\"sudo\"): %w", err)
600                         }
601                         cmd.Path = path
602                 }
603                 cmd.Stderr = super.Stderr
604                 cmd.Env = super.environ
605                 buf, err := cmd.Output() // /var/lib/arvados/.gem/ruby/2.5.0/bin:...
606                 if err != nil || len(buf) == 0 {
607                         return fmt.Errorf("gem env gempath: %w", err)
608                 }
609                 gempath := string(bytes.Split(buf, []byte{':'})[0])
610                 super.prependEnv("PATH", gempath+"/bin:")
611                 super.setEnv("GEM_HOME", gempath)
612                 super.setEnv("GEM_PATH", gempath)
613         }
614         // Passenger install doesn't work unless $HOME is ~user
615         u, err := user.Current()
616         if err != nil {
617                 return err
618         }
619         super.setEnv("HOME", u.HomeDir)
620         return nil
621 }
622
623 func (super *Supervisor) lookPath(prog string) string {
624         for _, val := range super.environ {
625                 if strings.HasPrefix(val, "PATH=") {
626                         for _, dir := range filepath.SplitList(val[5:]) {
627                                 path := filepath.Join(dir, prog)
628                                 if fi, err := os.Stat(path); err == nil && fi.Mode()&0111 != 0 {
629                                         return path
630                                 }
631                         }
632                 }
633         }
634         return prog
635 }
636
637 type runOptions struct {
638         output io.Writer // attach stdout
639         env    []string  // add/replace environment variables
640         user   string    // run as specified user
641         stdin  io.Reader
642 }
643
644 // RunProgram runs prog with args, using dir as working directory. If ctx is
645 // cancelled while the child is running, RunProgram terminates the child, waits
646 // for it to exit, then returns.
647 //
648 // Child's environment will have our env vars, plus any given in env.
649 //
650 // Child's stdout will be written to output if non-nil, otherwise the
651 // boot command's stderr.
652 func (super *Supervisor) RunProgram(ctx context.Context, dir string, opts runOptions, prog string, args ...string) error {
653         cmdline := fmt.Sprintf("%s", append([]string{prog}, args...))
654         super.logger.WithField("command", cmdline).WithField("dir", dir).Info("executing")
655
656         logprefix := prog
657         {
658                 innerargs := args
659                 if logprefix == "sudo" {
660                         for i := 0; i < len(args); i++ {
661                                 if args[i] == "-u" {
662                                         i++
663                                 } else if args[i] == "-E" || strings.Contains(args[i], "=") {
664                                 } else {
665                                         logprefix = args[i]
666                                         innerargs = args[i+1:]
667                                         break
668                                 }
669                         }
670                 }
671                 logprefix = strings.TrimPrefix(logprefix, "/var/lib/arvados/bin/")
672                 logprefix = strings.TrimPrefix(logprefix, super.tempdir+"/bin/")
673                 if logprefix == "bundle" && len(innerargs) > 2 && innerargs[0] == "exec" {
674                         _, dirbase := filepath.Split(dir)
675                         logprefix = innerargs[1] + "@" + dirbase
676                 } else if logprefix == "arvados-server" && len(args) > 1 {
677                         logprefix = args[0]
678                 }
679                 if !strings.HasPrefix(dir, "/") {
680                         logprefix = dir + ": " + logprefix
681                 }
682         }
683
684         cmd := exec.Command(super.lookPath(prog), args...)
685         cmd.Stdin = opts.stdin
686         stdout, err := cmd.StdoutPipe()
687         if err != nil {
688                 return err
689         }
690         stderr, err := cmd.StderrPipe()
691         if err != nil {
692                 return err
693         }
694         logwriter := &service.LogPrefixer{Writer: super.Stderr, Prefix: []byte("[" + logprefix + "] ")}
695         var copiers sync.WaitGroup
696         copiers.Add(1)
697         go func() {
698                 io.Copy(logwriter, stderr)
699                 copiers.Done()
700         }()
701         copiers.Add(1)
702         go func() {
703                 if opts.output == nil {
704                         io.Copy(logwriter, stdout)
705                 } else {
706                         io.Copy(opts.output, stdout)
707                 }
708                 copiers.Done()
709         }()
710
711         if strings.HasPrefix(dir, "/") {
712                 cmd.Dir = dir
713         } else {
714                 cmd.Dir = filepath.Join(super.SourcePath, dir)
715         }
716         env := append([]string(nil), opts.env...)
717         env = append(env, super.environ...)
718         cmd.Env = dedupEnv(env)
719
720         if opts.user != "" {
721                 // Note: We use this approach instead of "sudo"
722                 // because in certain circumstances (we are pid 1 in a
723                 // docker container, and our passenger child process
724                 // changes to pgid 1) the intermediate sudo process
725                 // notices we have the same pgid as our child and
726                 // refuses to propagate signals from us to our child,
727                 // so we can't signal/shutdown our passenger/rails
728                 // apps. "chpst" or "setuidgid" would work, but these
729                 // few lines avoid depending on runit/daemontools.
730                 u, err := user.Lookup(opts.user)
731                 if err != nil {
732                         return fmt.Errorf("user.Lookup(%q): %w", opts.user, err)
733                 }
734                 uid, _ := strconv.Atoi(u.Uid)
735                 gid, _ := strconv.Atoi(u.Gid)
736                 cmd.SysProcAttr = &syscall.SysProcAttr{
737                         Credential: &syscall.Credential{
738                                 Uid: uint32(uid),
739                                 Gid: uint32(gid),
740                         },
741                 }
742         }
743
744         exited := false
745         defer func() { exited = true }()
746         go func() {
747                 <-ctx.Done()
748                 log := ctxlog.FromContext(ctx).WithFields(logrus.Fields{"dir": dir, "cmdline": cmdline})
749                 for !exited {
750                         if cmd.Process == nil {
751                                 log.Debug("waiting for child process to start")
752                                 time.Sleep(time.Second / 2)
753                         } else {
754                                 log.WithField("PID", cmd.Process.Pid).Debug("sending SIGTERM")
755                                 cmd.Process.Signal(syscall.SIGTERM)
756                                 time.Sleep(5 * time.Second)
757                                 if !exited {
758                                         stdout.Close()
759                                         stderr.Close()
760                                         log.WithField("PID", cmd.Process.Pid).Warn("still waiting for child process to exit 5s after SIGTERM")
761                                 }
762                         }
763                 }
764         }()
765
766         err = cmd.Start()
767         if err != nil {
768                 return err
769         }
770         copiers.Wait()
771         err = cmd.Wait()
772         if ctx.Err() != nil {
773                 // Return "context canceled", instead of the "killed"
774                 // error that was probably caused by the context being
775                 // canceled.
776                 return ctx.Err()
777         } else if err != nil {
778                 return fmt.Errorf("%s: error: %v", cmdline, err)
779         }
780         return nil
781 }
782
783 func (super *Supervisor) autofillConfig() error {
784         usedPort := map[string]bool{}
785         nextPort := func(host string) (string, error) {
786                 for {
787                         port, err := availablePort(host)
788                         if err != nil {
789                                 port, err = availablePort(super.ListenHost)
790                         }
791                         if err != nil {
792                                 return "", err
793                         }
794                         if usedPort[port] {
795                                 continue
796                         }
797                         usedPort[port] = true
798                         return port, nil
799                 }
800         }
801         if super.cluster.Services.Controller.ExternalURL.Host == "" {
802                 h, p, err := net.SplitHostPort(super.ControllerAddr)
803                 if err != nil && super.ControllerAddr != "" {
804                         return fmt.Errorf("SplitHostPort(ControllerAddr %q): %w", super.ControllerAddr, err)
805                 }
806                 if h == "" {
807                         h = super.ListenHost
808                 }
809                 if p == "0" || p == "" {
810                         p, err = nextPort(h)
811                         if err != nil {
812                                 return err
813                         }
814                 }
815                 super.cluster.Services.Controller.ExternalURL = arvados.URL{Scheme: "https", Host: net.JoinHostPort(h, p), Path: "/"}
816         }
817         u := url.URL(super.cluster.Services.Controller.ExternalURL)
818         defaultExtHost := u.Hostname()
819         for _, svc := range []*arvados.Service{
820                 &super.cluster.Services.Controller,
821                 &super.cluster.Services.DispatchCloud,
822                 &super.cluster.Services.GitHTTP,
823                 &super.cluster.Services.Health,
824                 &super.cluster.Services.Keepproxy,
825                 &super.cluster.Services.Keepstore,
826                 &super.cluster.Services.RailsAPI,
827                 &super.cluster.Services.WebDAV,
828                 &super.cluster.Services.WebDAVDownload,
829                 &super.cluster.Services.Websocket,
830                 &super.cluster.Services.Workbench1,
831                 &super.cluster.Services.Workbench2,
832         } {
833                 if svc.ExternalURL.Host == "" {
834                         port, err := nextPort(defaultExtHost)
835                         if err != nil {
836                                 return err
837                         }
838                         host := net.JoinHostPort(defaultExtHost, port)
839                         if svc == &super.cluster.Services.Controller ||
840                                 svc == &super.cluster.Services.GitHTTP ||
841                                 svc == &super.cluster.Services.Health ||
842                                 svc == &super.cluster.Services.Keepproxy ||
843                                 svc == &super.cluster.Services.WebDAV ||
844                                 svc == &super.cluster.Services.WebDAVDownload ||
845                                 svc == &super.cluster.Services.Workbench1 ||
846                                 svc == &super.cluster.Services.Workbench2 {
847                                 svc.ExternalURL = arvados.URL{Scheme: "https", Host: host, Path: "/"}
848                         } else if svc == &super.cluster.Services.Websocket {
849                                 svc.ExternalURL = arvados.URL{Scheme: "wss", Host: host, Path: "/websocket"}
850                         }
851                 }
852                 if super.NoWorkbench1 && svc == &super.cluster.Services.Workbench1 ||
853                         super.NoWorkbench2 && svc == &super.cluster.Services.Workbench2 ||
854                         !super.cluster.Containers.CloudVMs.Enable && svc == &super.cluster.Services.DispatchCloud {
855                         // When workbench1 is disabled, it gets an
856                         // ExternalURL (so we have a valid listening
857                         // port to write in our Nginx config) but no
858                         // InternalURLs (so health checker doesn't
859                         // complain).
860                         continue
861                 }
862                 if len(svc.InternalURLs) == 0 {
863                         port, err := nextPort(super.ListenHost)
864                         if err != nil {
865                                 return err
866                         }
867                         host := net.JoinHostPort(super.ListenHost, port)
868                         svc.InternalURLs = map[arvados.URL]arvados.ServiceInstance{
869                                 {Scheme: "http", Host: host, Path: "/"}: {},
870                         }
871                 }
872         }
873         if super.ClusterType != "production" {
874                 if super.cluster.SystemRootToken == "" {
875                         super.cluster.SystemRootToken = randomHexString(64)
876                 }
877                 if super.cluster.ManagementToken == "" {
878                         super.cluster.ManagementToken = randomHexString(64)
879                 }
880                 if super.cluster.Collections.BlobSigningKey == "" {
881                         super.cluster.Collections.BlobSigningKey = randomHexString(64)
882                 }
883                 if super.cluster.Users.AnonymousUserToken == "" {
884                         super.cluster.Users.AnonymousUserToken = randomHexString(64)
885                 }
886                 if super.cluster.Containers.DispatchPrivateKey == "" {
887                         buf, err := ioutil.ReadFile(filepath.Join(super.SourcePath, "lib", "dispatchcloud", "test", "sshkey_dispatch"))
888                         if err != nil {
889                                 return err
890                         }
891                         super.cluster.Containers.DispatchPrivateKey = string(buf)
892                 }
893                 super.cluster.TLS.Insecure = true
894         }
895         if super.ClusterType == "test" {
896                 // Add a second keepstore process.
897                 port, err := nextPort(super.ListenHost)
898                 if err != nil {
899                         return err
900                 }
901                 host := net.JoinHostPort(super.ListenHost, port)
902                 super.cluster.Services.Keepstore.InternalURLs[arvados.URL{Scheme: "http", Host: host, Path: "/"}] = arvados.ServiceInstance{}
903
904                 // Create a directory-backed volume for each keepstore
905                 // process.
906                 super.cluster.Volumes = map[string]arvados.Volume{}
907                 for url := range super.cluster.Services.Keepstore.InternalURLs {
908                         volnum := len(super.cluster.Volumes)
909                         datadir := fmt.Sprintf("%s/keep%d.data", super.tempdir, volnum)
910                         if _, err = os.Stat(datadir + "/."); err == nil {
911                         } else if !os.IsNotExist(err) {
912                                 return err
913                         } else if err = os.Mkdir(datadir, 0755); err != nil {
914                                 return err
915                         }
916                         super.cluster.Volumes[fmt.Sprintf(super.cluster.ClusterID+"-nyw5e-%015d", volnum)] = arvados.Volume{
917                                 Driver:           "Directory",
918                                 DriverParameters: json.RawMessage(fmt.Sprintf(`{"Root":%q}`, datadir)),
919                                 AccessViaHosts: map[arvados.URL]arvados.VolumeAccess{
920                                         url: {},
921                                 },
922                                 StorageClasses: map[string]bool{
923                                         "default": true,
924                                         "foo":     true,
925                                         "bar":     true,
926                                 },
927                         }
928                 }
929                 super.cluster.StorageClasses = map[string]arvados.StorageClassConfig{
930                         "default": {Default: true},
931                         "foo":     {},
932                         "bar":     {},
933                 }
934         }
935         if super.OwnTemporaryDatabase {
936                 port, err := nextPort("localhost")
937                 if err != nil {
938                         return err
939                 }
940                 super.cluster.PostgreSQL.Connection = arvados.PostgreSQLConnection{
941                         "client_encoding": "utf8",
942                         "host":            "localhost",
943                         "port":            port,
944                         "dbname":          "arvados_test",
945                         "user":            "arvados",
946                         "password":        "insecure_arvados_test",
947                 }
948         }
949         return nil
950 }
951
952 func addrIsLocal(addr string) (bool, error) {
953         if h, _, err := net.SplitHostPort(addr); err != nil {
954                 return false, err
955         } else {
956                 addr = net.JoinHostPort(h, "0")
957         }
958         listener, err := net.Listen("tcp", addr)
959         if err == nil {
960                 listener.Close()
961                 return true, nil
962         } else if strings.Contains(err.Error(), "cannot assign requested address") {
963                 return false, nil
964         } else {
965                 return false, err
966         }
967 }
968
969 func randomHexString(chars int) string {
970         b := make([]byte, chars/2)
971         _, err := rand.Read(b)
972         if err != nil {
973                 panic(err)
974         }
975         return fmt.Sprintf("%x", b)
976 }
977
978 func internalPort(svc arvados.Service) (host, port string, err error) {
979         if len(svc.InternalURLs) > 1 {
980                 return "", "", errors.New("internalPort() doesn't work with multiple InternalURLs")
981         }
982         for u := range svc.InternalURLs {
983                 u := url.URL(u)
984                 host, port = u.Hostname(), u.Port()
985                 switch {
986                 case port != "":
987                 case u.Scheme == "https", u.Scheme == "ws":
988                         port = "443"
989                 default:
990                         port = "80"
991                 }
992                 return
993         }
994         return "", "", fmt.Errorf("service has no InternalURLs")
995 }
996
997 func externalPort(svc arvados.Service) (string, error) {
998         u := url.URL(svc.ExternalURL)
999         if p := u.Port(); p != "" {
1000                 return p, nil
1001         } else if u.Scheme == "https" || u.Scheme == "wss" {
1002                 return "443", nil
1003         } else {
1004                 return "80", nil
1005         }
1006 }
1007
1008 func availablePort(host string) (string, error) {
1009         ln, err := net.Listen("tcp", net.JoinHostPort(host, "0"))
1010         if err != nil {
1011                 return "", err
1012         }
1013         defer ln.Close()
1014         _, port, err := net.SplitHostPort(ln.Addr().String())
1015         if err != nil {
1016                 return "", err
1017         }
1018         return port, nil
1019 }
1020
1021 // Try to connect to addr until it works, then close ch. Give up if
1022 // ctx cancels.
1023 func waitForConnect(ctx context.Context, addr string) error {
1024         ctxlog.FromContext(ctx).WithField("addr", addr).Info("waitForConnect")
1025         dialer := net.Dialer{Timeout: time.Second}
1026         for ctx.Err() == nil {
1027                 conn, err := dialer.DialContext(ctx, "tcp", addr)
1028                 if err != nil {
1029                         time.Sleep(time.Second / 10)
1030                         continue
1031                 }
1032                 conn.Close()
1033                 return nil
1034         }
1035         return ctx.Err()
1036 }
1037
1038 func copyConfig(cfg *arvados.Config) *arvados.Config {
1039         pr, pw := io.Pipe()
1040         go func() {
1041                 err := json.NewEncoder(pw).Encode(cfg)
1042                 if err != nil {
1043                         panic(err)
1044                 }
1045                 pw.Close()
1046         }()
1047         cfg2 := new(arvados.Config)
1048         err := json.NewDecoder(pr).Decode(cfg2)
1049         if err != nil {
1050                 panic(err)
1051         }
1052         return cfg2
1053 }
1054
1055 func watchConfig(ctx context.Context, logger logrus.FieldLogger, cfgPath string, prevcfg *arvados.Config, fn func()) {
1056         watcher, err := fsnotify.NewWatcher()
1057         if err != nil {
1058                 logger.WithError(err).Error("fsnotify setup failed")
1059                 return
1060         }
1061         defer watcher.Close()
1062
1063         err = watcher.Add(cfgPath)
1064         if err != nil {
1065                 logger.WithError(err).Error("fsnotify watcher failed")
1066                 return
1067         }
1068
1069         for {
1070                 select {
1071                 case <-ctx.Done():
1072                         return
1073                 case err, ok := <-watcher.Errors:
1074                         if !ok {
1075                                 return
1076                         }
1077                         logger.WithError(err).Warn("fsnotify watcher reported error")
1078                 case _, ok := <-watcher.Events:
1079                         if !ok {
1080                                 return
1081                         }
1082                         for len(watcher.Events) > 0 {
1083                                 <-watcher.Events
1084                         }
1085                         loader := config.NewLoader(&bytes.Buffer{}, &logrus.Logger{Out: ioutil.Discard})
1086                         loader.Path = cfgPath
1087                         loader.SkipAPICalls = true
1088                         cfg, err := loader.Load()
1089                         if err != nil {
1090                                 logger.WithError(err).Warn("error reloading config file after change detected; ignoring new config for now")
1091                         } else if reflect.DeepEqual(cfg, prevcfg) {
1092                                 logger.Debug("config file changed but is still DeepEqual to the existing config")
1093                         } else {
1094                                 logger.Debug("config changed, notifying supervisor")
1095                                 fn()
1096                                 prevcfg = cfg
1097                         }
1098                 }
1099         }
1100 }