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