15954: Write controller URL to stdout when cluster is 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/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 bootCommand struct {
39         sourcePath  string // e.g., /home/username/src/arvados
40         libPath     string // e.g., /var/lib/arvados
41         clusterType string // e.g., production
42
43         cluster *arvados.Cluster
44         stdout  io.Writer
45         stderr  io.Writer
46
47         tempdir string
48
49         setupRubyOnce sync.Once
50         setupRubyErr  error
51         goMutex       sync.Mutex
52 }
53
54 func (boot *bootCommand) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
55         boot.stdout = stdout
56         boot.stderr = stderr
57         log := ctxlog.New(stderr, "json", "info")
58
59         var err error
60         defer func() {
61                 if err != nil {
62                         log.WithError(err).Info("exiting")
63                 }
64         }()
65
66         flags := flag.NewFlagSet(prog, flag.ContinueOnError)
67         flags.SetOutput(stderr)
68         loader := config.NewLoader(stdin, log)
69         loader.SetupFlags(flags)
70         versionFlag := flags.Bool("version", false, "Write version information to stdout and exit 0")
71         flags.StringVar(&boot.sourcePath, "source", ".", "arvados source tree `directory`")
72         flags.StringVar(&boot.libPath, "lib", "/var/lib/arvados", "`directory` to install dependencies and library files")
73         flags.StringVar(&boot.clusterType, "type", "production", "cluster `type`: development, test, or production")
74         err = flags.Parse(args)
75         if err == flag.ErrHelp {
76                 err = nil
77                 return 0
78         } else if err != nil {
79                 return 2
80         } else if *versionFlag {
81                 return cmd.Version.RunCommand(prog, args, stdin, stdout, stderr)
82         } else if boot.clusterType != "development" && boot.clusterType != "test" && boot.clusterType != "production" {
83                 err = fmt.Errorf("cluster type must be 'development', 'test', or 'production'")
84                 return 2
85         }
86
87         cwd, err := os.Getwd()
88         if err != nil {
89                 return 1
90         }
91         if !strings.HasPrefix(boot.sourcePath, "/") {
92                 boot.sourcePath = filepath.Join(cwd, boot.sourcePath)
93         }
94         boot.sourcePath, err = filepath.EvalSymlinks(boot.sourcePath)
95         if err != nil {
96                 return 1
97         }
98
99         loader.SkipAPICalls = true
100         cfg, err := loader.Load()
101         if err != nil {
102                 return 1
103         }
104
105         boot.tempdir, err = ioutil.TempDir("", "arvados-server-boot-")
106         if err != nil {
107                 return 1
108         }
109         defer os.RemoveAll(boot.tempdir)
110
111         // Fill in any missing config keys, and write the resulting
112         // config in the temp dir for child services to use.
113         err = boot.autofillConfig(cfg, log)
114         if err != nil {
115                 return 1
116         }
117         conffile, err := os.OpenFile(filepath.Join(boot.tempdir, "config.yml"), os.O_CREATE|os.O_WRONLY, 0777)
118         if err != nil {
119                 return 1
120         }
121         defer conffile.Close()
122         err = json.NewEncoder(conffile).Encode(cfg)
123         if err != nil {
124                 return 1
125         }
126         err = conffile.Close()
127         if err != nil {
128                 return 1
129         }
130         os.Setenv("ARVADOS_CONFIG", conffile.Name())
131         arvados.DefaultConfigFile = conffile.Name()
132         os.Setenv("RAILS_ENV", boot.clusterType)
133
134         // Now that we have the config, replace the bootstrap logger
135         // with a new one according to the logging config.
136         boot.cluster, err = cfg.GetCluster("")
137         if err != nil {
138                 return 1
139         }
140         log = ctxlog.New(stderr, boot.cluster.SystemLogs.Format, boot.cluster.SystemLogs.LogLevel)
141         logger := log.WithFields(logrus.Fields{
142                 "PID": os.Getpid(),
143         })
144         ctx := ctxlog.Context(context.Background(), logger)
145         ctx, cancel := context.WithCancel(ctx)
146         defer cancel()
147
148         ch := make(chan os.Signal)
149         signal.Notify(ch, syscall.SIGINT)
150         go func() {
151                 for sig := range ch {
152                         logger.WithField("signal", sig).Info("caught signal")
153                         cancel()
154                 }
155         }()
156
157         for _, dir := range []string{boot.libPath, filepath.Join(boot.libPath, "bin")} {
158                 if _, err = os.Stat(filepath.Join(dir, ".")); os.IsNotExist(err) {
159                         err = os.Mkdir(dir, 0755)
160                         if err != nil {
161                                 return 1
162                         }
163                 } else if err != nil {
164                         return 1
165                 }
166         }
167         os.Setenv("PATH", filepath.Join(boot.libPath, "bin")+":"+os.Getenv("PATH"))
168
169         err = boot.installGoProgram(ctx, "cmd/arvados-server")
170         if err != nil {
171                 return 1
172         }
173
174         var wg sync.WaitGroup
175         for _, cmpt := range []component{
176                 {name: "nginx", runFunc: runNginx},
177                 {name: "controller", cmdHandler: controller.Command},
178                 {name: "dispatchcloud", cmdHandler: dispatchcloud.Command, notIfTest: true},
179                 {name: "git-httpd", goProg: "services/arv-git-httpd"},
180                 {name: "health", goProg: "services/health"},
181                 {name: "keep-balance", goProg: "services/keep-balance", notIfTest: true},
182                 {name: "keepproxy", goProg: "services/keepproxy"},
183                 {name: "keepstore", goProg: "services/keepstore", svc: boot.cluster.Services.Keepstore},
184                 {name: "keep-web", goProg: "services/keep-web"},
185                 {name: "railsAPI", svc: boot.cluster.Services.RailsAPI, railsApp: "services/api"},
186                 {name: "ws", goProg: "services/ws"},
187         } {
188                 cmpt := cmpt
189                 wg.Add(1)
190                 go func() {
191                         defer wg.Done()
192                         defer cancel()
193                         logger.WithField("component", cmpt.name).Info("starting")
194                         err := cmpt.Run(ctx, boot, stdout, stderr)
195                         if err != nil {
196                                 logger.WithError(err).WithField("component", cmpt.name).Info("exited")
197                         }
198                 }()
199         }
200         if boot.waitUntilReady(ctx) {
201                 fmt.Fprintln(stdout, boot.cluster.Services.Controller.ExternalURL)
202         }
203         <-ctx.Done()
204         wg.Wait()
205         return 0
206 }
207
208 func (boot *bootCommand) waitUntilReady(ctx context.Context) bool {
209         agg := health.Aggregator{Cluster: boot.cluster}
210         for waiting := true; waiting; {
211                 time.Sleep(time.Second)
212                 if ctx.Err() != nil {
213                         return false
214                 }
215                 resp := agg.ClusterHealth()
216                 // The overall health check (resp.Health=="OK") might
217                 // never pass due to missing components (like
218                 // arvados-dispatch-cloud in a test cluster), so
219                 // instead we wait for all configured components to
220                 // pass.
221                 waiting = false
222                 for _, check := range resp.Checks {
223                         if check.Health != "OK" {
224                                 waiting = true
225                         }
226                 }
227         }
228         return true
229 }
230
231 func (boot *bootCommand) installGoProgram(ctx context.Context, srcpath string) error {
232         boot.goMutex.Lock()
233         defer boot.goMutex.Unlock()
234         return boot.RunProgram(ctx, filepath.Join(boot.sourcePath, srcpath), nil, []string{"GOPATH=" + boot.libPath}, "go", "install")
235 }
236
237 func (boot *bootCommand) setupRubyEnv() error {
238         boot.setupRubyOnce.Do(func() {
239                 buf, err := exec.Command("gem", "env", "gempath").Output() // /var/lib/arvados/.gem/ruby/2.5.0/bin:...
240                 if err != nil || len(buf) == 0 {
241                         boot.setupRubyErr = fmt.Errorf("gem env gempath: %v", err)
242                 }
243                 gempath := string(bytes.Split(buf, []byte{':'})[0])
244                 os.Setenv("PATH", gempath+"/bin:"+os.Getenv("PATH"))
245                 os.Setenv("GEM_HOME", gempath)
246                 os.Setenv("GEM_PATH", gempath)
247         })
248         return boot.setupRubyErr
249 }
250
251 // Run prog with args, using dir as working directory. If ctx is
252 // cancelled while the child is running, RunProgram terminates the
253 // child, waits for it to exit, then returns.
254 //
255 // Child's environment will have our env vars, plus any given in env.
256 //
257 // Child's stdout will be written to output if non-nil, otherwise the
258 // boot command's stderr.
259 func (boot *bootCommand) RunProgram(ctx context.Context, dir string, output io.Writer, env []string, prog string, args ...string) error {
260         cmdline := fmt.Sprintf("%s", append([]string{prog}, args...))
261         fmt.Fprintf(boot.stderr, "%s executing in %s\n", cmdline, dir)
262         cmd := exec.Command(prog, args...)
263         if output == nil {
264                 cmd.Stdout = boot.stderr
265         } else {
266                 cmd.Stdout = output
267         }
268         cmd.Stderr = boot.stderr
269         if strings.HasPrefix(dir, "/") {
270                 cmd.Dir = dir
271         } else {
272                 cmd.Dir = filepath.Join(boot.sourcePath, dir)
273         }
274         if env != nil {
275                 cmd.Env = append(env, os.Environ()...)
276         }
277         go func() {
278                 <-ctx.Done()
279                 log := ctxlog.FromContext(ctx).WithFields(logrus.Fields{"dir": dir, "cmdline": cmdline})
280                 for cmd.ProcessState == nil {
281                         // Child hasn't exited yet
282                         if cmd.Process == nil {
283                                 log.Infof("waiting for child process to start")
284                                 time.Sleep(time.Second)
285                         } else {
286                                 log.WithField("PID", cmd.Process.Pid).Info("sending SIGTERM")
287                                 cmd.Process.Signal(syscall.SIGTERM)
288                                 log.WithField("PID", cmd.Process.Pid).Info("waiting for child process to exit after SIGTERM")
289                                 time.Sleep(5 * time.Second)
290                         }
291                 }
292         }()
293         err := cmd.Run()
294         if err != nil {
295                 return fmt.Errorf("%s: error: %v", cmdline, err)
296         }
297         return nil
298 }
299
300 type component struct {
301         name       string
302         svc        arvados.Service
303         cmdHandler cmd.Handler
304         runFunc    func(ctx context.Context, boot *bootCommand, stdout, stderr io.Writer) error
305         railsApp   string // source dir in arvados tree, e.g., "services/api"
306         goProg     string // source dir in arvados tree, e.g., "services/keepstore"
307         notIfTest  bool   // don't run this component on a test cluster
308 }
309
310 func (cmpt *component) Run(ctx context.Context, boot *bootCommand, stdout, stderr io.Writer) error {
311         if cmpt.notIfTest && boot.clusterType == "test" {
312                 fmt.Fprintf(stderr, "skipping component %q in %s mode\n", cmpt.name, boot.clusterType)
313                 <-ctx.Done()
314                 return nil
315         }
316         fmt.Fprintf(stderr, "starting component %q\n", cmpt.name)
317         if cmpt.cmdHandler != nil {
318                 errs := make(chan error, 1)
319                 go func() {
320                         defer close(errs)
321                         exitcode := cmpt.cmdHandler.RunCommand(cmpt.name, nil, bytes.NewBuffer(nil), stdout, stderr)
322                         if exitcode != 0 {
323                                 errs <- fmt.Errorf("exit code %d", exitcode)
324                         }
325                 }()
326                 select {
327                 case err := <-errs:
328                         return err
329                 case <-ctx.Done():
330                         // cmpt.cmdHandler.RunCommand() doesn't have
331                         // access to our context, so it won't shut
332                         // down by itself. We just abandon it.
333                         return nil
334                 }
335         }
336         if cmpt.goProg != "" {
337                 boot.RunProgram(ctx, cmpt.goProg, nil, nil, "go", "install")
338                 if ctx.Err() != nil {
339                         return nil
340                 }
341                 _, basename := filepath.Split(cmpt.goProg)
342                 if len(cmpt.svc.InternalURLs) > 0 {
343                         // Run one for each URL
344                         var wg sync.WaitGroup
345                         for u := range cmpt.svc.InternalURLs {
346                                 u := u
347                                 wg.Add(1)
348                                 go func() {
349                                         defer wg.Done()
350                                         boot.RunProgram(ctx, boot.tempdir, nil, []string{"ARVADOS_SERVICE_INTERNAL_URL=" + u.String()}, basename)
351                                 }()
352                         }
353                         wg.Wait()
354                         return nil
355                 } else {
356                         // Just run one
357                         boot.RunProgram(ctx, boot.tempdir, nil, nil, basename)
358                 }
359         }
360         if cmpt.runFunc != nil {
361                 return cmpt.runFunc(ctx, boot, stdout, stderr)
362         }
363         if cmpt.railsApp != "" {
364                 port, err := internalPort(cmpt.svc)
365                 if err != nil {
366                         return fmt.Errorf("bug: no InternalURLs for component %q: %v", cmpt.name, cmpt.svc.InternalURLs)
367                 }
368                 err = boot.setupRubyEnv()
369                 if err != nil {
370                         return err
371                 }
372                 var buf bytes.Buffer
373                 err = boot.RunProgram(ctx, cmpt.railsApp, &buf, nil, "gem", "list", "--details", "bundler")
374                 if err != nil {
375                         return err
376                 }
377                 for _, version := range []string{"1.11.0", "1.17.3", "2.0.2"} {
378                         if !strings.Contains(buf.String(), "("+version+")") {
379                                 err = boot.RunProgram(ctx, cmpt.railsApp, nil, nil, "gem", "install", "--user", "bundler:1.11", "bundler:1.17.3", "bundler:2.0.2")
380                                 if err != nil {
381                                         return err
382                                 }
383                                 break
384                         }
385                 }
386                 err = boot.RunProgram(ctx, cmpt.railsApp, nil, nil, "bundle", "install", "--jobs", "4", "--path", filepath.Join(os.Getenv("HOME"), ".gem"))
387                 if err != nil {
388                         return err
389                 }
390                 err = boot.RunProgram(ctx, cmpt.railsApp, nil, nil, "bundle", "exec", "passenger-config", "build-native-support")
391                 if err != nil {
392                         return err
393                 }
394                 err = boot.RunProgram(ctx, cmpt.railsApp, nil, nil, "bundle", "exec", "passenger-config", "install-standalone-runtime")
395                 if err != nil {
396                         return err
397                 }
398                 err = boot.RunProgram(ctx, cmpt.railsApp, nil, nil, "bundle", "exec", "passenger-config", "validate-install")
399                 if err != nil {
400                         return err
401                 }
402                 err = boot.RunProgram(ctx, cmpt.railsApp, nil, nil, "bundle", "exec", "passenger", "start", "-p", port)
403                 if err != nil {
404                         return err
405                 }
406         }
407         return fmt.Errorf("bug: component %q has nothing to run", cmpt.name)
408 }
409
410 func (boot *bootCommand) autofillConfig(cfg *arvados.Config, log logrus.FieldLogger) error {
411         cluster, err := cfg.GetCluster("")
412         if err != nil {
413                 return err
414         }
415         port := 9000
416         for _, svc := range []*arvados.Service{
417                 &cluster.Services.Controller,
418                 &cluster.Services.DispatchCloud,
419                 &cluster.Services.GitHTTP,
420                 &cluster.Services.Health,
421                 &cluster.Services.Keepproxy,
422                 &cluster.Services.Keepstore,
423                 &cluster.Services.RailsAPI,
424                 &cluster.Services.WebDAV,
425                 &cluster.Services.WebDAVDownload,
426                 &cluster.Services.Websocket,
427         } {
428                 if svc == &cluster.Services.DispatchCloud && boot.clusterType == "test" {
429                         continue
430                 }
431                 if len(svc.InternalURLs) == 0 {
432                         port++
433                         svc.InternalURLs = map[arvados.URL]arvados.ServiceInstance{
434                                 arvados.URL{Scheme: "http", Host: fmt.Sprintf("localhost:%d", port)}: arvados.ServiceInstance{},
435                         }
436                 }
437                 if svc.ExternalURL.Host == "" && (svc == &cluster.Services.Controller ||
438                         svc == &cluster.Services.GitHTTP ||
439                         svc == &cluster.Services.Keepproxy ||
440                         svc == &cluster.Services.WebDAV ||
441                         svc == &cluster.Services.WebDAVDownload ||
442                         svc == &cluster.Services.Websocket) {
443                         port++
444                         svc.ExternalURL = arvados.URL{Scheme: "https", Host: fmt.Sprintf("localhost:%d", port)}
445                 }
446         }
447         if cluster.SystemRootToken == "" {
448                 cluster.SystemRootToken = randomHexString(64)
449         }
450         if cluster.ManagementToken == "" {
451                 cluster.ManagementToken = randomHexString(64)
452         }
453         if cluster.API.RailsSessionSecretToken == "" {
454                 cluster.API.RailsSessionSecretToken = randomHexString(64)
455         }
456         if cluster.Collections.BlobSigningKey == "" {
457                 cluster.Collections.BlobSigningKey = randomHexString(64)
458         }
459         if boot.clusterType != "production" && cluster.Containers.DispatchPrivateKey == "" {
460                 buf, err := ioutil.ReadFile(filepath.Join(boot.sourcePath, "lib", "dispatchcloud", "test", "sshkey_dispatch"))
461                 if err != nil {
462                         return err
463                 }
464                 cluster.Containers.DispatchPrivateKey = string(buf)
465         }
466         if boot.clusterType != "production" {
467                 cluster.TLS.Insecure = true
468         }
469         if boot.clusterType == "test" {
470                 // Add a second keepstore process.
471                 port++
472                 cluster.Services.Keepstore.InternalURLs[arvados.URL{Scheme: "http", Host: fmt.Sprintf("localhost:%d", port)}] = arvados.ServiceInstance{}
473
474                 // Create a directory-backed volume for each keepstore
475                 // process.
476                 cluster.Volumes = map[string]arvados.Volume{}
477                 for url := range cluster.Services.Keepstore.InternalURLs {
478                         volnum := len(cluster.Volumes)
479                         datadir := fmt.Sprintf("%s/keep%d.data", boot.tempdir, volnum)
480                         if _, err = os.Stat(datadir + "/."); err == nil {
481                         } else if !os.IsNotExist(err) {
482                                 return err
483                         } else if err = os.Mkdir(datadir, 0777); err != nil {
484                                 return err
485                         }
486                         cluster.Volumes[fmt.Sprintf("zzzzz-nyw5e-%015d", volnum)] = arvados.Volume{
487                                 Driver:           "Directory",
488                                 DriverParameters: json.RawMessage(fmt.Sprintf(`{"Root":%q}`, datadir)),
489                                 AccessViaHosts: map[arvados.URL]arvados.VolumeAccess{
490                                         url: {},
491                                 },
492                         }
493                 }
494         }
495         cfg.Clusters[cluster.ClusterID] = *cluster
496         return nil
497 }
498
499 func randomHexString(chars int) string {
500         b := make([]byte, chars/2)
501         _, err := rand.Read(b)
502         if err != nil {
503                 panic(err)
504         }
505         return fmt.Sprintf("%x", b)
506 }
507
508 func internalPort(svc arvados.Service) (string, error) {
509         for u := range svc.InternalURLs {
510                 if _, p, err := net.SplitHostPort(u.Host); err != nil {
511                         return "", err
512                 } else if p != "" {
513                         return p, nil
514                 } else if u.Scheme == "https" {
515                         return "443", nil
516                 } else {
517                         return "80", nil
518                 }
519         }
520         return "", fmt.Errorf("service has no InternalURLs")
521 }
522
523 func externalPort(svc arvados.Service) (string, error) {
524         if _, p, err := net.SplitHostPort(svc.ExternalURL.Host); err != nil {
525                 return "", err
526         } else if p != "" {
527                 return p, nil
528         } else if svc.ExternalURL.Scheme == "https" {
529                 return "443", nil
530         } else {
531                 return "80", nil
532         }
533 }