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