15954: Don't assign ports for dispatchcloud in test mode.
[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: "keep-web", goProg: "services/keep-web"},
183                 {name: "railsAPI", svc: boot.cluster.Services.RailsAPI, railsApp: "services/api"},
184         } {
185                 cmpt := cmpt
186                 wg.Add(1)
187                 go func() {
188                         defer wg.Done()
189                         defer cancel()
190                         logger.WithField("component", cmpt.name).Info("starting")
191                         err := cmpt.Run(ctx, boot, stdout, stderr)
192                         if err != nil {
193                                 logger.WithError(err).WithField("component", cmpt.name).Info("exited")
194                         }
195                 }()
196         }
197         <-ctx.Done()
198         wg.Wait()
199         return 0
200 }
201
202 func (boot *bootCommand) installGoProgram(ctx context.Context, srcpath string) error {
203         boot.goMutex.Lock()
204         defer boot.goMutex.Unlock()
205         env := append([]string{"GOPATH=" + boot.libPath}, os.Environ()...)
206         return boot.RunProgram(ctx, filepath.Join(boot.sourcePath, srcpath), nil, env, "go", "install")
207 }
208
209 func (boot *bootCommand) setupRubyEnv() error {
210         boot.setupRubyOnce.Do(func() {
211                 buf, err := exec.Command("gem", "env", "gempath").Output() // /var/lib/arvados/.gem/ruby/2.5.0/bin:...
212                 if err != nil || len(buf) == 0 {
213                         boot.setupRubyErr = fmt.Errorf("gem env gempath: %v", err)
214                 }
215                 gempath := string(bytes.Split(buf, []byte{':'})[0])
216                 os.Setenv("PATH", gempath+"/bin:"+os.Getenv("PATH"))
217                 os.Setenv("GEM_HOME", gempath)
218                 os.Setenv("GEM_PATH", gempath)
219         })
220         return boot.setupRubyErr
221 }
222
223 func (boot *bootCommand) RunProgram(ctx context.Context, dir string, output io.Writer, env []string, prog string, args ...string) error {
224         cmdline := fmt.Sprintf("%s", append([]string{prog}, args...))
225         fmt.Fprintf(boot.stderr, "%s executing in %s\n", cmdline, dir)
226         cmd := exec.Command(prog, args...)
227         if output == nil {
228                 cmd.Stdout = boot.stderr
229         } else {
230                 cmd.Stdout = output
231         }
232         cmd.Stderr = boot.stderr
233         if strings.HasPrefix(dir, "/") {
234                 cmd.Dir = dir
235         } else {
236                 cmd.Dir = filepath.Join(boot.sourcePath, dir)
237         }
238         if env != nil {
239                 cmd.Env = env
240         }
241         go func() {
242                 <-ctx.Done()
243                 log := ctxlog.FromContext(ctx).WithFields(logrus.Fields{"dir": dir, "cmdline": cmdline})
244                 for cmd.ProcessState == nil {
245                         if cmd.Process == nil {
246                                 log.Infof("waiting for child process to start")
247                                 time.Sleep(time.Second)
248                         } else {
249                                 cmd.Process.Signal(syscall.SIGTERM)
250                                 log.WithField("PID", cmd.Process.Pid).Infof("waiting for child process to exit after SIGTERM")
251                                 time.Sleep(5 * time.Second)
252                         }
253                 }
254         }()
255         err := cmd.Run()
256         if err != nil {
257                 return fmt.Errorf("%s: error: %v", cmdline, err)
258         }
259         return nil
260 }
261
262 type component struct {
263         name       string
264         svc        arvados.Service
265         cmdHandler cmd.Handler
266         runFunc    func(ctx context.Context, boot *bootCommand, stdout, stderr io.Writer) error
267         railsApp   string // source dir in arvados tree, e.g., "services/api"
268         goProg     string // source dir in arvados tree, e.g., "services/keepstore"
269         notIfTest  bool   // don't run this component on a test cluster
270 }
271
272 func (cmpt *component) Run(ctx context.Context, boot *bootCommand, stdout, stderr io.Writer) error {
273         if cmpt.notIfTest && boot.clusterType == "test" {
274                 fmt.Fprintf(stderr, "skipping component %q in %s mode\n", cmpt.name, boot.clusterType)
275                 <-ctx.Done()
276                 return nil
277         }
278         fmt.Fprintf(stderr, "starting component %q\n", cmpt.name)
279         if cmpt.cmdHandler != nil {
280                 errs := make(chan error, 1)
281                 go func() {
282                         defer close(errs)
283                         exitcode := cmpt.cmdHandler.RunCommand(cmpt.name, nil, bytes.NewBuffer(nil), stdout, stderr)
284                         if exitcode != 0 {
285                                 errs <- fmt.Errorf("exit code %d", exitcode)
286                         }
287                 }()
288                 select {
289                 case err := <-errs:
290                         return err
291                 case <-ctx.Done():
292                         // cmpt.cmdHandler.RunCommand() doesn't have
293                         // access to our context, so it won't shut
294                         // down by itself. We just abandon it.
295                         return nil
296                 }
297         }
298         if cmpt.goProg != "" {
299                 return boot.RunProgram(ctx, cmpt.goProg, nil, nil, "go", "run", ".")
300         }
301         if cmpt.runFunc != nil {
302                 return cmpt.runFunc(ctx, boot, stdout, stderr)
303         }
304         if cmpt.railsApp != "" {
305                 port, err := internalPort(cmpt.svc)
306                 if err != nil {
307                         return fmt.Errorf("bug: no InternalURLs for component %q: %v", cmpt.name, cmpt.svc.InternalURLs)
308                 }
309                 err = boot.setupRubyEnv()
310                 if err != nil {
311                         return err
312                 }
313                 var buf bytes.Buffer
314                 err = boot.RunProgram(ctx, cmpt.railsApp, &buf, nil, "gem", "list", "--details", "bundler")
315                 if err != nil {
316                         return err
317                 }
318                 for _, version := range []string{"1.11.0", "1.17.3", "2.0.2"} {
319                         if !strings.Contains(buf.String(), "("+version+")") {
320                                 err = boot.RunProgram(ctx, cmpt.railsApp, nil, nil, "gem", "install", "--user", "bundler:1.11", "bundler:1.17.3", "bundler:2.0.2")
321                                 if err != nil {
322                                         return err
323                                 }
324                                 break
325                         }
326                 }
327                 err = boot.RunProgram(ctx, cmpt.railsApp, nil, nil, "bundle", "install", "--jobs", "4", "--path", filepath.Join(os.Getenv("HOME"), ".gem"))
328                 if err != nil {
329                         return err
330                 }
331                 err = boot.RunProgram(ctx, cmpt.railsApp, nil, nil, "bundle", "exec", "passenger-config", "build-native-support")
332                 if err != nil {
333                         return err
334                 }
335                 err = boot.RunProgram(ctx, cmpt.railsApp, nil, nil, "bundle", "exec", "passenger-config", "install-standalone-runtime")
336                 if err != nil {
337                         return err
338                 }
339                 err = boot.RunProgram(ctx, cmpt.railsApp, nil, nil, "bundle", "exec", "passenger-config", "validate-install")
340                 if err != nil {
341                         return err
342                 }
343                 err = boot.RunProgram(ctx, cmpt.railsApp, nil, nil, "bundle", "exec", "passenger", "start", "-p", port)
344                 if err != nil {
345                         return err
346                 }
347         }
348         return fmt.Errorf("bug: component %q has nothing to run", cmpt.name)
349 }
350
351 func (boot *bootCommand) autofillConfig(cfg *arvados.Config, log logrus.FieldLogger) error {
352         cluster, err := cfg.GetCluster("")
353         if err != nil {
354                 return err
355         }
356         port := 9000
357         for _, svc := range []*arvados.Service{
358                 &cluster.Services.Controller,
359                 &cluster.Services.DispatchCloud,
360                 &cluster.Services.GitHTTP,
361                 &cluster.Services.Health,
362                 &cluster.Services.Keepproxy,
363                 &cluster.Services.Keepstore,
364                 &cluster.Services.RailsAPI,
365                 &cluster.Services.WebDAV,
366                 &cluster.Services.WebDAVDownload,
367                 &cluster.Services.Websocket,
368         } {
369                 if svc == &cluster.Services.DispatchCloud && boot.clusterType == "test" {
370                         continue
371                 }
372                 if len(svc.InternalURLs) == 0 {
373                         port++
374                         svc.InternalURLs = map[arvados.URL]arvados.ServiceInstance{
375                                 arvados.URL{Scheme: "http", Host: fmt.Sprintf("localhost:%d", port)}: arvados.ServiceInstance{},
376                         }
377                 }
378                 if svc.ExternalURL.Host == "" && (svc == &cluster.Services.Controller ||
379                         svc == &cluster.Services.GitHTTP ||
380                         svc == &cluster.Services.Keepproxy ||
381                         svc == &cluster.Services.WebDAV ||
382                         svc == &cluster.Services.WebDAVDownload ||
383                         svc == &cluster.Services.Websocket) {
384                         port++
385                         svc.ExternalURL = arvados.URL{Scheme: "https", Host: fmt.Sprintf("localhost:%d", port)}
386                 }
387         }
388         if cluster.SystemRootToken == "" {
389                 cluster.SystemRootToken = randomHexString(64)
390         }
391         if cluster.ManagementToken == "" {
392                 cluster.ManagementToken = randomHexString(64)
393         }
394         if cluster.API.RailsSessionSecretToken == "" {
395                 cluster.API.RailsSessionSecretToken = randomHexString(64)
396         }
397         if cluster.Collections.BlobSigningKey == "" {
398                 cluster.Collections.BlobSigningKey = randomHexString(64)
399         }
400         if boot.clusterType != "production" && cluster.Containers.DispatchPrivateKey == "" {
401                 buf, err := ioutil.ReadFile(filepath.Join(boot.sourcePath, "lib", "dispatchcloud", "test", "sshkey_dispatch"))
402                 if err != nil {
403                         return err
404                 }
405                 cluster.Containers.DispatchPrivateKey = string(buf)
406         }
407         if boot.clusterType != "production" {
408                 cluster.TLS.Insecure = true
409         }
410         if boot.clusterType == "test" && len(cluster.Volumes) == 0 {
411                 cluster.Volumes = map[string]arvados.Volume{
412                         "zzzzz-nyw5e-000000000000000": arvados.Volume{
413                                 Driver:           "Directory",
414                                 DriverParameters: json.RawMessage(fmt.Sprintf(`{"Root":%q}`, boot.tempdir+"/keep0")),
415                         },
416                 }
417         }
418         cfg.Clusters[cluster.ClusterID] = *cluster
419         return nil
420 }
421
422 func randomHexString(chars int) string {
423         b := make([]byte, chars/2)
424         _, err := rand.Read(b)
425         if err != nil {
426                 panic(err)
427         }
428         return fmt.Sprintf("%x", b)
429 }
430
431 func internalPort(svc arvados.Service) (string, error) {
432         for u := range svc.InternalURLs {
433                 if _, p, err := net.SplitHostPort(u.Host); err != nil {
434                         return "", err
435                 } else if p != "" {
436                         return p, nil
437                 } else if u.Scheme == "https" {
438                         return "443", nil
439                 } else {
440                         return "80", nil
441                 }
442         }
443         return "", fmt.Errorf("service has no InternalURLs")
444 }
445
446 func externalPort(svc arvados.Service) (string, error) {
447         if _, p, err := net.SplitHostPort(svc.ExternalURL.Host); err != nil {
448                 return "", err
449         } else if p != "" {
450                 return p, nil
451         } else if svc.ExternalURL.Scheme == "https" {
452                 return "443", nil
453         } else {
454                 return "80", nil
455         }
456 }