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