15954: Start websocket and keepstore.
[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                                 cmd.Process.Signal(syscall.SIGTERM)
251                                 log.WithField("PID", cmd.Process.Pid).Infof("waiting for child process to exit after SIGTERM")
252                                 time.Sleep(5 * time.Second)
253                         }
254                 }
255         }()
256         err := cmd.Run()
257         if err != nil {
258                 return fmt.Errorf("%s: error: %v", cmdline, err)
259         }
260         return nil
261 }
262
263 type component struct {
264         name       string
265         svc        arvados.Service
266         cmdHandler cmd.Handler
267         runFunc    func(ctx context.Context, boot *bootCommand, stdout, stderr io.Writer) error
268         railsApp   string // source dir in arvados tree, e.g., "services/api"
269         goProg     string // source dir in arvados tree, e.g., "services/keepstore"
270         notIfTest  bool   // don't run this component on a test cluster
271 }
272
273 func (cmpt *component) Run(ctx context.Context, boot *bootCommand, stdout, stderr io.Writer) error {
274         if cmpt.notIfTest && boot.clusterType == "test" {
275                 fmt.Fprintf(stderr, "skipping component %q in %s mode\n", cmpt.name, boot.clusterType)
276                 <-ctx.Done()
277                 return nil
278         }
279         fmt.Fprintf(stderr, "starting component %q\n", cmpt.name)
280         if cmpt.cmdHandler != nil {
281                 errs := make(chan error, 1)
282                 go func() {
283                         defer close(errs)
284                         exitcode := cmpt.cmdHandler.RunCommand(cmpt.name, nil, bytes.NewBuffer(nil), stdout, stderr)
285                         if exitcode != 0 {
286                                 errs <- fmt.Errorf("exit code %d", exitcode)
287                         }
288                 }()
289                 select {
290                 case err := <-errs:
291                         return err
292                 case <-ctx.Done():
293                         // cmpt.cmdHandler.RunCommand() doesn't have
294                         // access to our context, so it won't shut
295                         // down by itself. We just abandon it.
296                         return nil
297                 }
298         }
299         if cmpt.goProg != "" {
300                 if len(cmpt.svc.InternalURLs) > 0 {
301                         // Run one for each URL
302                         var wg sync.WaitGroup
303                         for u := range cmpt.svc.InternalURLs {
304                                 u := u
305                                 wg.Add(1)
306                                 go func() {
307                                         defer wg.Done()
308                                         boot.RunProgram(ctx, cmpt.goProg, nil, []string{"ARVADOS_SERVICE_INTERNAL_URL=" + u.String()}, "go", "run", ".")
309                                 }()
310                         }
311                         wg.Wait()
312                         return nil
313                 } else {
314                         // Just run one
315                         return boot.RunProgram(ctx, cmpt.goProg, nil, nil, "go", "run", ".")
316                 }
317         }
318         if cmpt.runFunc != nil {
319                 return cmpt.runFunc(ctx, boot, stdout, stderr)
320         }
321         if cmpt.railsApp != "" {
322                 port, err := internalPort(cmpt.svc)
323                 if err != nil {
324                         return fmt.Errorf("bug: no InternalURLs for component %q: %v", cmpt.name, cmpt.svc.InternalURLs)
325                 }
326                 err = boot.setupRubyEnv()
327                 if err != nil {
328                         return err
329                 }
330                 var buf bytes.Buffer
331                 err = boot.RunProgram(ctx, cmpt.railsApp, &buf, nil, "gem", "list", "--details", "bundler")
332                 if err != nil {
333                         return err
334                 }
335                 for _, version := range []string{"1.11.0", "1.17.3", "2.0.2"} {
336                         if !strings.Contains(buf.String(), "("+version+")") {
337                                 err = boot.RunProgram(ctx, cmpt.railsApp, nil, nil, "gem", "install", "--user", "bundler:1.11", "bundler:1.17.3", "bundler:2.0.2")
338                                 if err != nil {
339                                         return err
340                                 }
341                                 break
342                         }
343                 }
344                 err = boot.RunProgram(ctx, cmpt.railsApp, nil, nil, "bundle", "install", "--jobs", "4", "--path", filepath.Join(os.Getenv("HOME"), ".gem"))
345                 if err != nil {
346                         return err
347                 }
348                 err = boot.RunProgram(ctx, cmpt.railsApp, nil, nil, "bundle", "exec", "passenger-config", "build-native-support")
349                 if err != nil {
350                         return err
351                 }
352                 err = boot.RunProgram(ctx, cmpt.railsApp, nil, nil, "bundle", "exec", "passenger-config", "install-standalone-runtime")
353                 if err != nil {
354                         return err
355                 }
356                 err = boot.RunProgram(ctx, cmpt.railsApp, nil, nil, "bundle", "exec", "passenger-config", "validate-install")
357                 if err != nil {
358                         return err
359                 }
360                 err = boot.RunProgram(ctx, cmpt.railsApp, nil, nil, "bundle", "exec", "passenger", "start", "-p", port)
361                 if err != nil {
362                         return err
363                 }
364         }
365         return fmt.Errorf("bug: component %q has nothing to run", cmpt.name)
366 }
367
368 func (boot *bootCommand) autofillConfig(cfg *arvados.Config, log logrus.FieldLogger) error {
369         cluster, err := cfg.GetCluster("")
370         if err != nil {
371                 return err
372         }
373         port := 9000
374         for _, svc := range []*arvados.Service{
375                 &cluster.Services.Controller,
376                 &cluster.Services.DispatchCloud,
377                 &cluster.Services.GitHTTP,
378                 &cluster.Services.Health,
379                 &cluster.Services.Keepproxy,
380                 &cluster.Services.Keepstore,
381                 &cluster.Services.RailsAPI,
382                 &cluster.Services.WebDAV,
383                 &cluster.Services.WebDAVDownload,
384                 &cluster.Services.Websocket,
385         } {
386                 if svc == &cluster.Services.DispatchCloud && boot.clusterType == "test" {
387                         continue
388                 }
389                 if len(svc.InternalURLs) == 0 {
390                         port++
391                         svc.InternalURLs = map[arvados.URL]arvados.ServiceInstance{
392                                 arvados.URL{Scheme: "http", Host: fmt.Sprintf("localhost:%d", port)}: arvados.ServiceInstance{},
393                         }
394                 }
395                 if svc.ExternalURL.Host == "" && (svc == &cluster.Services.Controller ||
396                         svc == &cluster.Services.GitHTTP ||
397                         svc == &cluster.Services.Keepproxy ||
398                         svc == &cluster.Services.WebDAV ||
399                         svc == &cluster.Services.WebDAVDownload ||
400                         svc == &cluster.Services.Websocket) {
401                         port++
402                         svc.ExternalURL = arvados.URL{Scheme: "https", Host: fmt.Sprintf("localhost:%d", port)}
403                 }
404         }
405         if cluster.SystemRootToken == "" {
406                 cluster.SystemRootToken = randomHexString(64)
407         }
408         if cluster.ManagementToken == "" {
409                 cluster.ManagementToken = randomHexString(64)
410         }
411         if cluster.API.RailsSessionSecretToken == "" {
412                 cluster.API.RailsSessionSecretToken = randomHexString(64)
413         }
414         if cluster.Collections.BlobSigningKey == "" {
415                 cluster.Collections.BlobSigningKey = randomHexString(64)
416         }
417         if boot.clusterType != "production" && cluster.Containers.DispatchPrivateKey == "" {
418                 buf, err := ioutil.ReadFile(filepath.Join(boot.sourcePath, "lib", "dispatchcloud", "test", "sshkey_dispatch"))
419                 if err != nil {
420                         return err
421                 }
422                 cluster.Containers.DispatchPrivateKey = string(buf)
423         }
424         if boot.clusterType != "production" {
425                 cluster.TLS.Insecure = true
426         }
427         if boot.clusterType == "test" {
428                 port++
429                 cluster.Services.Keepstore.InternalURLs[arvados.URL{Scheme: "http", Host: fmt.Sprintf("localhost:%d", port)}] = arvados.ServiceInstance{}
430
431                 n := -1
432                 for url := range cluster.Services.Keepstore.InternalURLs {
433                         n++
434                         datadir := fmt.Sprintf("%s/keep%d.data", boot.tempdir, n)
435                         if _, err = os.Stat(datadir + "/."); err == nil {
436                         } else if !os.IsNotExist(err) {
437                                 return err
438                         } else if err = os.Mkdir(datadir, 0777); err != nil {
439                                 return err
440                         }
441                         cluster.Volumes = map[string]arvados.Volume{
442                                 fmt.Sprintf("zzzzz-nyw5e-%015d", n): arvados.Volume{
443                                         Driver:           "Directory",
444                                         DriverParameters: json.RawMessage(fmt.Sprintf(`{"Root":%q}`, datadir)),
445                                         AccessViaHosts: map[arvados.URL]arvados.VolumeAccess{
446                                                 url: {},
447                                         },
448                                 },
449                         }
450                 }
451         }
452         cfg.Clusters[cluster.ClusterID] = *cluster
453         return nil
454 }
455
456 func randomHexString(chars int) string {
457         b := make([]byte, chars/2)
458         _, err := rand.Read(b)
459         if err != nil {
460                 panic(err)
461         }
462         return fmt.Sprintf("%x", b)
463 }
464
465 func internalPort(svc arvados.Service) (string, error) {
466         for u := range svc.InternalURLs {
467                 if _, p, err := net.SplitHostPort(u.Host); err != nil {
468                         return "", err
469                 } else if p != "" {
470                         return p, nil
471                 } else if u.Scheme == "https" {
472                         return "443", nil
473                 } else {
474                         return "80", nil
475                 }
476         }
477         return "", fmt.Errorf("service has no InternalURLs")
478 }
479
480 func externalPort(svc arvados.Service) (string, error) {
481         if _, p, err := net.SplitHostPort(svc.ExternalURL.Host); err != nil {
482                 return "", err
483         } else if p != "" {
484                 return p, nil
485         } else if svc.ExternalURL.Scheme == "https" {
486                 return "443", nil
487         } else {
488                 return "80", nil
489         }
490 }