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