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