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