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