15954: Add -controller-address flag.
[arvados.git] / lib / boot / cmd.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         "flag"
13         "fmt"
14         "io"
15         "io/ioutil"
16         "net"
17         "os"
18         "os/exec"
19         "os/signal"
20         "path/filepath"
21         "strings"
22         "sync"
23         "syscall"
24         "time"
25
26         "git.arvados.org/arvados.git/lib/cmd"
27         "git.arvados.org/arvados.git/lib/config"
28         "git.arvados.org/arvados.git/lib/controller"
29         "git.arvados.org/arvados.git/lib/dispatchcloud"
30         "git.arvados.org/arvados.git/sdk/go/arvados"
31         "git.arvados.org/arvados.git/sdk/go/ctxlog"
32         "git.arvados.org/arvados.git/sdk/go/health"
33         "github.com/sirupsen/logrus"
34 )
35
36 var Command cmd.Handler = bootCommand{}
37
38 type bootTask interface {
39         // Execute the task. Run should return nil when the task is
40         // done enough to satisfy a dependency relationship (e.g., the
41         // service is running and ready). If the task starts a
42         // goroutine that fails after Run returns (e.g., the service
43         // shuts down), it should call cancel.
44         Run(ctx context.Context, fail func(error), boot *Booter) error
45         String() string
46 }
47
48 type bootCommand struct{}
49
50 func (bootCommand) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
51         boot := &Booter{
52                 Stderr: stderr,
53                 logger: ctxlog.New(stderr, "json", "info"),
54         }
55
56         ctx := ctxlog.Context(context.Background(), boot.logger)
57         ctx, cancel := context.WithCancel(ctx)
58         defer cancel()
59
60         ch := make(chan os.Signal)
61         signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
62         go func() {
63                 for sig := range ch {
64                         boot.logger.WithField("signal", sig).Info("caught signal")
65                         cancel()
66                 }
67         }()
68
69         var err error
70         defer func() {
71                 if err != nil {
72                         boot.logger.WithError(err).Info("exiting")
73                 }
74         }()
75
76         flags := flag.NewFlagSet(prog, flag.ContinueOnError)
77         flags.SetOutput(stderr)
78         loader := config.NewLoader(stdin, boot.logger)
79         loader.SetupFlags(flags)
80         versionFlag := flags.Bool("version", false, "Write version information to stdout and exit 0")
81         flags.StringVar(&boot.SourcePath, "source", ".", "arvados source tree `directory`")
82         flags.StringVar(&boot.LibPath, "lib", "/var/lib/arvados", "`directory` to install dependencies and library files")
83         flags.StringVar(&boot.ClusterType, "type", "production", "cluster `type`: development, test, or production")
84         flags.StringVar(&boot.ControllerAddr, "controller-address", ":0", "desired controller address, `host:port` or `:port`")
85         flags.BoolVar(&boot.OwnTemporaryDatabase, "own-temporary-database", false, "bring up a postgres server and create a temporary database")
86         err = flags.Parse(args)
87         if err == flag.ErrHelp {
88                 err = nil
89                 return 0
90         } else if err != nil {
91                 return 2
92         } else if *versionFlag {
93                 return cmd.Version.RunCommand(prog, args, stdin, stdout, stderr)
94         } else if boot.ClusterType != "development" && boot.ClusterType != "test" && boot.ClusterType != "production" {
95                 err = fmt.Errorf("cluster type must be 'development', 'test', or 'production'")
96                 return 2
97         }
98
99         boot.Start(ctx, loader)
100         defer boot.Stop()
101         if boot.WaitReady() {
102                 fmt.Fprintln(stdout, boot.cluster.Services.Controller.ExternalURL)
103                 <-ctx.Done() // wait for signal
104                 return 0
105         } else {
106                 return 1
107         }
108 }
109
110 type Booter struct {
111         SourcePath           string // e.g., /home/username/src/arvados
112         LibPath              string // e.g., /var/lib/arvados
113         ClusterType          string // e.g., production
114         ControllerAddr       string // e.g., 127.0.0.1:8000
115         OwnTemporaryDatabase bool
116         Stderr               io.Writer
117
118         logger  logrus.FieldLogger
119         cluster *arvados.Cluster
120
121         ctx           context.Context
122         cancel        context.CancelFunc
123         done          chan struct{}
124         healthChecker *health.Aggregator
125         tasksReady    map[string]chan bool
126
127         tempdir    string
128         configfile string
129         environ    []string // for child processes
130
131         setupRubyOnce sync.Once
132         setupRubyErr  error
133         goMutex       sync.Mutex
134 }
135
136 func (boot *Booter) Start(ctx context.Context, loader *config.Loader) {
137         boot.ctx, boot.cancel = context.WithCancel(ctx)
138         boot.done = make(chan struct{})
139         go func() {
140                 err := boot.run(loader)
141                 if err != nil {
142                         fmt.Fprintln(boot.Stderr, err)
143                 }
144                 close(boot.done)
145         }()
146 }
147
148 func (boot *Booter) run(loader *config.Loader) error {
149         cwd, err := os.Getwd()
150         if err != nil {
151                 return err
152         }
153         if !strings.HasPrefix(boot.SourcePath, "/") {
154                 boot.SourcePath = filepath.Join(cwd, boot.SourcePath)
155         }
156         boot.SourcePath, err = filepath.EvalSymlinks(boot.SourcePath)
157         if err != nil {
158                 return err
159         }
160
161         boot.tempdir, err = ioutil.TempDir("", "arvados-server-boot-")
162         if err != nil {
163                 return err
164         }
165         defer os.RemoveAll(boot.tempdir)
166
167         loader.SkipAPICalls = true
168         cfg, err := loader.Load()
169         if err != nil {
170                 return err
171         }
172
173         // Fill in any missing config keys, and write the resulting
174         // config in the temp dir for child services to use.
175         err = boot.autofillConfig(cfg, boot.logger)
176         if err != nil {
177                 return err
178         }
179         conffile, err := os.OpenFile(filepath.Join(boot.tempdir, "config.yml"), os.O_CREATE|os.O_WRONLY, 0777)
180         if err != nil {
181                 return err
182         }
183         defer conffile.Close()
184         err = json.NewEncoder(conffile).Encode(cfg)
185         if err != nil {
186                 return err
187         }
188         err = conffile.Close()
189         if err != nil {
190                 return err
191         }
192         boot.configfile = conffile.Name()
193
194         boot.environ = os.Environ()
195         boot.setEnv("ARVADOS_CONFIG", boot.configfile)
196         boot.setEnv("RAILS_ENV", boot.ClusterType)
197         boot.prependEnv("PATH", filepath.Join(boot.LibPath, "bin")+":")
198
199         boot.cluster, err = cfg.GetCluster("")
200         if err != nil {
201                 return err
202         }
203         // Now that we have the config, replace the bootstrap logger
204         // with a new one according to the logging config.
205         boot.logger = ctxlog.New(boot.Stderr, boot.cluster.SystemLogs.Format, boot.cluster.SystemLogs.LogLevel).WithFields(logrus.Fields{
206                 "PID": os.Getpid(),
207         })
208         boot.healthChecker = &health.Aggregator{Cluster: boot.cluster}
209
210         for _, dir := range []string{boot.LibPath, filepath.Join(boot.LibPath, "bin")} {
211                 if _, err = os.Stat(filepath.Join(dir, ".")); os.IsNotExist(err) {
212                         err = os.Mkdir(dir, 0755)
213                         if err != nil {
214                                 return err
215                         }
216                 } else if err != nil {
217                         return err
218                 }
219         }
220         err = boot.installGoProgram(boot.ctx, "cmd/arvados-server")
221         if err != nil {
222                 return err
223         }
224         err = boot.setupRubyEnv()
225         if err != nil {
226                 return err
227         }
228
229         tasks := []bootTask{
230                 createCertificates{},
231                 runPostgreSQL{},
232                 runNginx{},
233                 runServiceCommand{name: "controller", command: controller.Command, depends: []bootTask{runPostgreSQL{}}},
234                 runGoProgram{src: "services/arv-git-httpd"},
235                 runGoProgram{src: "services/health"},
236                 runGoProgram{src: "services/keepproxy"},
237                 runGoProgram{src: "services/keepstore", svc: boot.cluster.Services.Keepstore},
238                 runGoProgram{src: "services/keep-web"},
239                 runGoProgram{src: "services/ws", depends: []bootTask{runPostgreSQL{}}},
240                 installPassenger{src: "services/api"},
241                 runPassenger{src: "services/api", svc: boot.cluster.Services.RailsAPI, depends: []bootTask{createCertificates{}, runPostgreSQL{}, installPassenger{src: "services/api"}}},
242                 installPassenger{src: "apps/workbench"},
243                 runPassenger{src: "apps/workbench", svc: boot.cluster.Services.Workbench1, depends: []bootTask{installPassenger{src: "apps/workbench"}}},
244                 seedDatabase{},
245         }
246         if boot.ClusterType != "test" {
247                 tasks = append(tasks,
248                         runServiceCommand{name: "dispatchcloud", command: dispatchcloud.Command},
249                         runGoProgram{src: "services/keep-balance"},
250                 )
251         }
252         boot.tasksReady = map[string]chan bool{}
253         for _, task := range tasks {
254                 boot.tasksReady[task.String()] = make(chan bool)
255         }
256         for _, task := range tasks {
257                 task := task
258                 fail := func(err error) {
259                         if boot.ctx.Err() != nil {
260                                 return
261                         }
262                         boot.cancel()
263                         boot.logger.WithField("task", task).WithError(err).Error("task failed")
264                 }
265                 go func() {
266                         boot.logger.WithField("task", task).Info("starting")
267                         err := task.Run(boot.ctx, fail, boot)
268                         if err != nil {
269                                 fail(err)
270                                 return
271                         }
272                         close(boot.tasksReady[task.String()])
273                 }()
274         }
275         return boot.wait(boot.ctx, tasks...)
276 }
277
278 func (boot *Booter) wait(ctx context.Context, tasks ...bootTask) error {
279         for _, task := range tasks {
280                 ch, ok := boot.tasksReady[task.String()]
281                 if !ok {
282                         return fmt.Errorf("no such task: %s", task)
283                 }
284                 boot.logger.WithField("task", task).Info("waiting")
285                 select {
286                 case <-ch:
287                 case <-ctx.Done():
288                         return ctx.Err()
289                 }
290         }
291         return nil
292 }
293
294 func (boot *Booter) Stop() {
295         boot.cancel()
296         <-boot.done
297 }
298
299 func (boot *Booter) WaitReady() bool {
300         for waiting := true; waiting; {
301                 time.Sleep(time.Second)
302                 if boot.ctx.Err() != nil {
303                         return false
304                 }
305                 if boot.healthChecker == nil {
306                         // not set up yet
307                         continue
308                 }
309                 resp := boot.healthChecker.ClusterHealth()
310                 // The overall health check (resp.Health=="OK") might
311                 // never pass due to missing components (like
312                 // arvados-dispatch-cloud in a test cluster), so
313                 // instead we wait for all configured components to
314                 // pass.
315                 waiting = false
316                 for _, check := range resp.Checks {
317                         if check.Health != "OK" {
318                                 waiting = true
319                         }
320                 }
321         }
322         return true
323 }
324
325 func (boot *Booter) prependEnv(key, prepend string) {
326         for i, s := range boot.environ {
327                 if strings.HasPrefix(s, key+"=") {
328                         boot.environ[i] = key + "=" + prepend + s[len(key)+1:]
329                         return
330                 }
331         }
332         boot.environ = append(boot.environ, key+"="+prepend)
333 }
334
335 func (boot *Booter) setEnv(key, val string) {
336         for i, s := range boot.environ {
337                 if strings.HasPrefix(s, key+"=") {
338                         boot.environ[i] = key + "=" + val
339                         return
340                 }
341         }
342         boot.environ = append(boot.environ, key+"="+val)
343 }
344
345 func (boot *Booter) installGoProgram(ctx context.Context, srcpath string) error {
346         boot.goMutex.Lock()
347         defer boot.goMutex.Unlock()
348         return boot.RunProgram(ctx, filepath.Join(boot.SourcePath, srcpath), nil, []string{"GOPATH=" + boot.LibPath}, "go", "install")
349 }
350
351 func (boot *Booter) setupRubyEnv() error {
352         buf, err := exec.Command("gem", "env", "gempath").Output() // /var/lib/arvados/.gem/ruby/2.5.0/bin:...
353         if err != nil || len(buf) == 0 {
354                 return fmt.Errorf("gem env gempath: %v", err)
355         }
356         gempath := string(bytes.Split(buf, []byte{':'})[0])
357         boot.prependEnv("PATH", gempath+"/bin:")
358         boot.setEnv("GEM_HOME", gempath)
359         boot.setEnv("GEM_PATH", gempath)
360         return nil
361 }
362
363 func (boot *Booter) lookPath(prog string) string {
364         for _, val := range boot.environ {
365                 if strings.HasPrefix(val, "PATH=") {
366                         for _, dir := range filepath.SplitList(val[5:]) {
367                                 path := filepath.Join(dir, prog)
368                                 if fi, err := os.Stat(path); err == nil && fi.Mode()&0111 != 0 {
369                                         return path
370                                 }
371                         }
372                 }
373         }
374         return prog
375 }
376
377 // Run prog with args, using dir as working directory. If ctx is
378 // cancelled while the child is running, RunProgram terminates the
379 // child, waits for it to exit, then returns.
380 //
381 // Child's environment will have our env vars, plus any given in env.
382 //
383 // Child's stdout will be written to output if non-nil, otherwise the
384 // boot command's stderr.
385 func (boot *Booter) RunProgram(ctx context.Context, dir string, output io.Writer, env []string, prog string, args ...string) error {
386         cmdline := fmt.Sprintf("%s", append([]string{prog}, args...))
387         fmt.Fprintf(boot.Stderr, "%s executing in %s\n", cmdline, dir)
388         cmd := exec.Command(boot.lookPath(prog), args...)
389         if output == nil {
390                 cmd.Stdout = boot.Stderr
391         } else {
392                 cmd.Stdout = output
393         }
394         cmd.Stderr = boot.Stderr
395         if strings.HasPrefix(dir, "/") {
396                 cmd.Dir = dir
397         } else {
398                 cmd.Dir = filepath.Join(boot.SourcePath, dir)
399         }
400         cmd.Env = append(env, boot.environ...)
401
402         exited := false
403         defer func() { exited = true }()
404         go func() {
405                 <-ctx.Done()
406                 log := ctxlog.FromContext(ctx).WithFields(logrus.Fields{"dir": dir, "cmdline": cmdline})
407                 for !exited {
408                         if cmd.Process == nil {
409                                 log.Debug("waiting for child process to start")
410                                 time.Sleep(time.Second / 2)
411                         } else {
412                                 log.WithField("PID", cmd.Process.Pid).Debug("sending SIGTERM")
413                                 cmd.Process.Signal(syscall.SIGTERM)
414                                 time.Sleep(5 * time.Second)
415                                 if !exited {
416                                         log.WithField("PID", cmd.Process.Pid).Warn("still waiting for child process to exit 5s after SIGTERM")
417                                 }
418                         }
419                 }
420         }()
421
422         err := cmd.Run()
423         if err != nil && ctx.Err() == nil {
424                 // Only report errors that happen before the context ends.
425                 return fmt.Errorf("%s: error: %v", cmdline, err)
426         }
427         return nil
428 }
429
430 func (boot *Booter) autofillConfig(cfg *arvados.Config, log logrus.FieldLogger) error {
431         cluster, err := cfg.GetCluster("")
432         if err != nil {
433                 return err
434         }
435         usedPort := map[string]bool{}
436         nextPort := func() string {
437                 for {
438                         port, err := availablePort(":0")
439                         if err != nil {
440                                 panic(err)
441                         }
442                         if usedPort[port] {
443                                 continue
444                         }
445                         usedPort[port] = true
446                         return port
447                 }
448         }
449         if cluster.Services.Controller.ExternalURL.Host == "" {
450                 h, p, err := net.SplitHostPort(boot.ControllerAddr)
451                 if err != nil {
452                         return err
453                 }
454                 if h == "" {
455                         h = "localhost"
456                 }
457                 if p == "0" {
458                         p, err = availablePort(":0")
459                         if err != nil {
460                                 return err
461                         }
462                         usedPort[p] = true
463                 }
464                 cluster.Services.Controller.ExternalURL = arvados.URL{Scheme: "https", Host: net.JoinHostPort(h, p)}
465         }
466         for _, svc := range []*arvados.Service{
467                 &cluster.Services.Controller,
468                 &cluster.Services.DispatchCloud,
469                 &cluster.Services.GitHTTP,
470                 &cluster.Services.Health,
471                 &cluster.Services.Keepproxy,
472                 &cluster.Services.Keepstore,
473                 &cluster.Services.RailsAPI,
474                 &cluster.Services.WebDAV,
475                 &cluster.Services.WebDAVDownload,
476                 &cluster.Services.Websocket,
477                 &cluster.Services.Workbench1,
478         } {
479                 if svc == &cluster.Services.DispatchCloud && boot.ClusterType == "test" {
480                         continue
481                 }
482                 if svc.ExternalURL.Host == "" && (svc == &cluster.Services.Controller ||
483                         svc == &cluster.Services.GitHTTP ||
484                         svc == &cluster.Services.Keepproxy ||
485                         svc == &cluster.Services.WebDAV ||
486                         svc == &cluster.Services.WebDAVDownload ||
487                         svc == &cluster.Services.Websocket ||
488                         svc == &cluster.Services.Workbench1) {
489                         svc.ExternalURL = arvados.URL{Scheme: "https", Host: fmt.Sprintf("localhost:%s", nextPort())}
490                 }
491                 if len(svc.InternalURLs) == 0 {
492                         svc.InternalURLs = map[arvados.URL]arvados.ServiceInstance{
493                                 arvados.URL{Scheme: "http", Host: fmt.Sprintf("localhost:%s", nextPort())}: arvados.ServiceInstance{},
494                         }
495                 }
496         }
497         if cluster.SystemRootToken == "" {
498                 cluster.SystemRootToken = randomHexString(64)
499         }
500         if cluster.ManagementToken == "" {
501                 cluster.ManagementToken = randomHexString(64)
502         }
503         if cluster.API.RailsSessionSecretToken == "" {
504                 cluster.API.RailsSessionSecretToken = randomHexString(64)
505         }
506         if cluster.Collections.BlobSigningKey == "" {
507                 cluster.Collections.BlobSigningKey = randomHexString(64)
508         }
509         if boot.ClusterType != "production" && cluster.Containers.DispatchPrivateKey == "" {
510                 buf, err := ioutil.ReadFile(filepath.Join(boot.SourcePath, "lib", "dispatchcloud", "test", "sshkey_dispatch"))
511                 if err != nil {
512                         return err
513                 }
514                 cluster.Containers.DispatchPrivateKey = string(buf)
515         }
516         if boot.ClusterType != "production" {
517                 cluster.TLS.Insecure = true
518         }
519         if boot.ClusterType == "test" {
520                 // Add a second keepstore process.
521                 cluster.Services.Keepstore.InternalURLs[arvados.URL{Scheme: "http", Host: fmt.Sprintf("localhost:%s", nextPort())}] = arvados.ServiceInstance{}
522
523                 // Create a directory-backed volume for each keepstore
524                 // process.
525                 cluster.Volumes = map[string]arvados.Volume{}
526                 for url := range cluster.Services.Keepstore.InternalURLs {
527                         volnum := len(cluster.Volumes)
528                         datadir := fmt.Sprintf("%s/keep%d.data", boot.tempdir, volnum)
529                         if _, err = os.Stat(datadir + "/."); err == nil {
530                         } else if !os.IsNotExist(err) {
531                                 return err
532                         } else if err = os.Mkdir(datadir, 0777); err != nil {
533                                 return err
534                         }
535                         cluster.Volumes[fmt.Sprintf("zzzzz-nyw5e-%015d", volnum)] = arvados.Volume{
536                                 Driver:           "Directory",
537                                 DriverParameters: json.RawMessage(fmt.Sprintf(`{"Root":%q}`, datadir)),
538                                 AccessViaHosts: map[arvados.URL]arvados.VolumeAccess{
539                                         url: {},
540                                 },
541                         }
542                 }
543         }
544         if boot.OwnTemporaryDatabase {
545                 cluster.PostgreSQL.Connection = arvados.PostgreSQLConnection{
546                         "client_encoding": "utf8",
547                         "host":            "localhost",
548                         "port":            nextPort(),
549                         "dbname":          "arvados_test",
550                         "user":            "arvados",
551                         "password":        "insecure_arvados_test",
552                 }
553         }
554
555         cfg.Clusters[cluster.ClusterID] = *cluster
556         return nil
557 }
558
559 func randomHexString(chars int) string {
560         b := make([]byte, chars/2)
561         _, err := rand.Read(b)
562         if err != nil {
563                 panic(err)
564         }
565         return fmt.Sprintf("%x", b)
566 }
567
568 func internalPort(svc arvados.Service) (string, error) {
569         for u := range svc.InternalURLs {
570                 if _, p, err := net.SplitHostPort(u.Host); err != nil {
571                         return "", err
572                 } else if p != "" {
573                         return p, nil
574                 } else if u.Scheme == "https" {
575                         return "443", nil
576                 } else {
577                         return "80", nil
578                 }
579         }
580         return "", fmt.Errorf("service has no InternalURLs")
581 }
582
583 func externalPort(svc arvados.Service) (string, error) {
584         if _, p, err := net.SplitHostPort(svc.ExternalURL.Host); err != nil {
585                 return "", err
586         } else if p != "" {
587                 return p, nil
588         } else if svc.ExternalURL.Scheme == "https" {
589                 return "443", nil
590         } else {
591                 return "80", nil
592         }
593 }
594
595 func availablePort(addr string) (string, error) {
596         ln, err := net.Listen("tcp", addr)
597         if err != nil {
598                 return "", err
599         }
600         defer ln.Close()
601         _, port, err := net.SplitHostPort(ln.Addr().String())
602         if err != nil {
603                 return "", err
604         }
605         return port, nil
606 }
607
608 // Try to connect to addr until it works, then close ch. Give up if
609 // ctx cancels.
610 func waitForConnect(ctx context.Context, addr string) error {
611         dialer := net.Dialer{Timeout: time.Second}
612         for ctx.Err() == nil {
613                 conn, err := dialer.DialContext(ctx, "tcp", addr)
614                 if err != nil {
615                         time.Sleep(time.Second / 10)
616                         continue
617                 }
618                 conn.Close()
619                 return nil
620         }
621         return ctx.Err()
622 }