15954: Try harder to shut down children before exiting.
[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/sdk/go/arvados"
30         "git.arvados.org/arvados.git/sdk/go/ctxlog"
31         "github.com/sirupsen/logrus"
32 )
33
34 var Command cmd.Handler = &bootCommand{}
35
36 type bootCommand struct {
37         sourcePath  string // e.g., /home/username/src/arvados
38         libPath     string // e.g., /var/lib/arvados
39         clusterType string // e.g., production
40
41         stdout io.Writer
42         stderr io.Writer
43
44         setupRubyOnce sync.Once
45         setupRubyErr  error
46         goMutex       sync.Mutex
47 }
48
49 func (boot *bootCommand) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
50         boot.stdout = stdout
51         boot.stderr = stderr
52         log := ctxlog.New(stderr, "json", "info")
53
54         var err error
55         defer func() {
56                 if err != nil {
57                         log.WithError(err).Info("exiting")
58                 }
59         }()
60
61         flags := flag.NewFlagSet(prog, flag.ContinueOnError)
62         flags.SetOutput(stderr)
63         loader := config.NewLoader(stdin, log)
64         loader.SetupFlags(flags)
65         versionFlag := flags.Bool("version", false, "Write version information to stdout and exit 0")
66         flags.StringVar(&boot.sourcePath, "source", ".", "arvados source tree `directory`")
67         flags.StringVar(&boot.libPath, "lib", "/var/lib/arvados", "`directory` to install dependencies and library files")
68         flags.StringVar(&boot.clusterType, "type", "production", "cluster `type`: development, test, or production")
69         err = flags.Parse(args)
70         if err == flag.ErrHelp {
71                 err = nil
72                 return 0
73         } else if err != nil {
74                 return 2
75         } else if *versionFlag {
76                 return cmd.Version.RunCommand(prog, args, stdin, stdout, stderr)
77         } else if boot.clusterType != "development" && boot.clusterType != "test" && boot.clusterType != "production" {
78                 err = fmt.Errorf("cluster type must be 'development', 'test', or 'production'")
79                 return 2
80         }
81
82         cwd, err := os.Getwd()
83         if err != nil {
84                 return 1
85         }
86         if !strings.HasPrefix(boot.sourcePath, "/") {
87                 boot.sourcePath = filepath.Join(cwd, boot.sourcePath)
88         }
89         boot.sourcePath, err = filepath.EvalSymlinks(boot.sourcePath)
90         if err != nil {
91                 return 1
92         }
93
94         loader.SkipAPICalls = true
95         cfg, err := loader.Load()
96         if err != nil {
97                 return 1
98         }
99
100         tempdir, err := ioutil.TempDir("", "arvados-server-boot-")
101         if err != nil {
102                 return 1
103         }
104         defer os.RemoveAll(tempdir)
105
106         // Fill in any missing config keys, and write the resulting
107         // config in the temp dir for child services to use.
108         autofillConfig(cfg, log)
109         conffile, err := os.OpenFile(filepath.Join(tempdir, "config.yml"), os.O_CREATE|os.O_WRONLY, 0777)
110         if err != nil {
111                 return 1
112         }
113         defer conffile.Close()
114         err = json.NewEncoder(conffile).Encode(cfg)
115         if err != nil {
116                 return 1
117         }
118         err = conffile.Close()
119         if err != nil {
120                 return 1
121         }
122         os.Setenv("ARVADOS_CONFIG", conffile.Name())
123
124         os.Setenv("RAILS_ENV", boot.clusterType)
125
126         // Now that we have the config, replace the bootstrap logger
127         // with a new one according to the logging config.
128         cluster, err := cfg.GetCluster("")
129         if err != nil {
130                 return 1
131         }
132         log = ctxlog.New(stderr, cluster.SystemLogs.Format, cluster.SystemLogs.LogLevel)
133         logger := log.WithFields(logrus.Fields{
134                 "PID": os.Getpid(),
135         })
136         ctx := ctxlog.Context(context.Background(), logger)
137         ctx, cancel := context.WithCancel(ctx)
138         defer cancel()
139
140         ch := make(chan os.Signal)
141         signal.Notify(ch, syscall.SIGINT)
142         go func() {
143                 for sig := range ch {
144                         logger.WithField("signal", sig).Info("caught signal")
145                         cancel()
146                 }
147         }()
148
149         for _, dir := range []string{boot.libPath, filepath.Join(boot.libPath, "bin")} {
150                 if _, err = os.Stat(filepath.Join(dir, ".")); os.IsNotExist(err) {
151                         err = os.Mkdir(dir, 0755)
152                         if err != nil {
153                                 return 1
154                         }
155                 } else if err != nil {
156                         return 1
157                 }
158         }
159         os.Setenv("PATH", filepath.Join(boot.libPath, "bin")+":"+os.Getenv("PATH"))
160
161         err = boot.installGoProgram(ctx, "cmd/arvados-server")
162         if err != nil {
163                 return 1
164         }
165
166         var wg sync.WaitGroup
167         for _, cmpt := range []component{
168                 {name: "controller", svc: cluster.Services.Controller, cmdArgs: []string{"-config", conffile.Name()}, cmdHandler: controller.Command},
169                 // {name: "dispatchcloud", cmdArgs: []string{"-config", conffile.Name()}, cmdHandler: dispatchcloud.Command},
170                 {name: "railsAPI", svc: cluster.Services.RailsAPI, src: "services/api"},
171         } {
172                 cmpt := cmpt
173                 wg.Add(1)
174                 go func() {
175                         defer wg.Done()
176                         defer cancel()
177                         logger.WithField("component", cmpt.name).Info("starting")
178                         err := cmpt.Run(ctx, boot, stdout, stderr)
179                         if err != nil {
180                                 logger.WithError(err).WithField("component", cmpt.name).Info("exited")
181                         }
182                 }()
183         }
184         <-ctx.Done()
185         wg.Wait()
186         return 0
187 }
188
189 func (boot *bootCommand) installGoProgram(ctx context.Context, srcpath string) error {
190         boot.goMutex.Lock()
191         defer boot.goMutex.Unlock()
192         env := append([]string{"GOPATH=" + boot.libPath}, os.Environ()...)
193         return boot.RunProgram(ctx, filepath.Join(boot.sourcePath, srcpath), nil, env, "go", "install")
194 }
195
196 func (boot *bootCommand) setupRubyEnv() error {
197         boot.setupRubyOnce.Do(func() {
198                 buf, err := exec.Command("gem", "env", "gempath").Output() // /var/lib/arvados/.gem/ruby/2.5.0/bin:...
199                 if err != nil || len(buf) == 0 {
200                         boot.setupRubyErr = fmt.Errorf("gem env gempath: %v", err)
201                 }
202                 gempath := string(bytes.Split(buf, []byte{':'})[0])
203                 os.Setenv("PATH", gempath+"/bin:"+os.Getenv("PATH"))
204                 os.Setenv("GEM_HOME", gempath)
205                 os.Setenv("GEM_PATH", gempath)
206         })
207         return boot.setupRubyErr
208 }
209
210 func (boot *bootCommand) RunProgram(ctx context.Context, dir string, output io.Writer, env []string, prog string, args ...string) error {
211         cmdline := fmt.Sprintf("%s", append([]string{prog}, args...))
212         fmt.Fprintf(boot.stderr, "%s executing in %s\n", cmdline, dir)
213         cmd := exec.Command(prog, args...)
214         if output == nil {
215                 cmd.Stdout = boot.stderr
216         } else {
217                 cmd.Stdout = output
218         }
219         cmd.Stderr = boot.stderr
220         if strings.HasPrefix(dir, "/") {
221                 cmd.Dir = dir
222         } else {
223                 cmd.Dir = filepath.Join(boot.sourcePath, dir)
224         }
225         if env != nil {
226                 cmd.Env = env
227         }
228         go func() {
229                 <-ctx.Done()
230                 cmd.Process.Signal(syscall.SIGINT)
231                 for range time.Tick(5 * time.Second) {
232                         if cmd.ProcessState != nil {
233                                 break
234                         }
235                         ctxlog.FromContext(ctx).WithField("process", cmd.Process).Infof("waiting for child process to exit after SIGINT")
236                         cmd.Process.Signal(syscall.SIGINT)
237                 }
238         }()
239         err := cmd.Run()
240         if err != nil {
241                 return fmt.Errorf("%s: error: %v", cmdline, err)
242         }
243         return nil
244 }
245
246 type component struct {
247         name       string
248         svc        arvados.Service
249         cmdHandler cmd.Handler
250         cmdArgs    []string
251         src        string // source dir in arvados tree, e.g., "services/keepstore"
252 }
253
254 func (cmpt *component) Run(ctx context.Context, boot *bootCommand, stdout, stderr io.Writer) error {
255         fmt.Fprintf(stderr, "starting component %q\n", cmpt.name)
256         if cmpt.cmdHandler != nil {
257                 errs := make(chan error, 1)
258                 go func() {
259                         defer close(errs)
260                         exitcode := cmpt.cmdHandler.RunCommand(cmpt.name, cmpt.cmdArgs, bytes.NewBuffer(nil), stdout, stderr)
261                         if exitcode != 0 {
262                                 errs <- fmt.Errorf("exit code %d", exitcode)
263                         }
264                 }()
265                 select {
266                 case err := <-errs:
267                         return err
268                 case <-ctx.Done():
269                         // cmpt.cmdHandler.RunCommand() doesn't have
270                         // access to our context, so it won't shut
271                         // down by itself. We just abandon it.
272                         return nil
273                 }
274         }
275         if cmpt.src != "" {
276                 port := "-"
277                 for u := range cmpt.svc.InternalURLs {
278                         if _, p, err := net.SplitHostPort(u.Host); err != nil {
279                                 return err
280                         } else if p != "" {
281                                 port = p
282                         } else if u.Scheme == "https" {
283                                 port = "443"
284                         } else {
285                                 port = "80"
286                         }
287                         break
288                 }
289                 if port == "-" {
290                         return fmt.Errorf("bug: no InternalURLs for component %q: %v", cmpt.name, cmpt.svc.InternalURLs)
291                 }
292
293                 err := boot.setupRubyEnv()
294                 if err != nil {
295                         return err
296                 }
297                 var buf bytes.Buffer
298                 err = boot.RunProgram(ctx, cmpt.src, &buf, nil, "gem", "list", "--details", "bundler")
299                 if err != nil {
300                         return err
301                 }
302                 for _, version := range []string{"1.11.0", "1.17.3", "2.0.2"} {
303                         if !strings.Contains(buf.String(), "("+version+")") {
304                                 err = boot.RunProgram(ctx, cmpt.src, nil, nil, "gem", "install", "--user", "bundler:1.11", "bundler:1.17.3", "bundler:2.0.2")
305                                 if err != nil {
306                                         return err
307                                 }
308                                 break
309                         }
310                 }
311                 err = boot.RunProgram(ctx, cmpt.src, nil, nil, "bundle", "install", "--jobs", "4", "--path", filepath.Join(os.Getenv("HOME"), ".gem"))
312                 if err != nil {
313                         return err
314                 }
315                 err = boot.RunProgram(ctx, cmpt.src, nil, nil, "bundle", "exec", "passenger-config", "build-native-support")
316                 if err != nil {
317                         return err
318                 }
319                 err = boot.RunProgram(ctx, cmpt.src, nil, nil, "bundle", "exec", "passenger-config", "install-standalone-runtime")
320                 if err != nil {
321                         return err
322                 }
323                 err = boot.RunProgram(ctx, cmpt.src, nil, nil, "bundle", "exec", "passenger-config", "validate-install")
324                 if err != nil {
325                         return err
326                 }
327                 err = boot.RunProgram(ctx, cmpt.src, nil, nil, "bundle", "exec", "passenger", "start", "-p", port)
328                 if err != nil {
329                         return err
330                 }
331         }
332         return fmt.Errorf("bug: component %q has nothing to run", cmpt.name)
333 }
334
335 func autofillConfig(cfg *arvados.Config, log logrus.FieldLogger) {
336         cluster, err := cfg.GetCluster("")
337         if err != nil {
338                 panic(err)
339         }
340         port := 9000
341         for _, svc := range []*arvados.Service{
342                 &cluster.Services.Controller,
343                 &cluster.Services.DispatchCloud,
344                 &cluster.Services.RailsAPI,
345         } {
346                 if len(svc.InternalURLs) == 0 {
347                         port++
348                         svc.InternalURLs = map[arvados.URL]arvados.ServiceInstance{
349                                 arvados.URL{Scheme: "http", Host: fmt.Sprintf("localhost:%d", port)}: arvados.ServiceInstance{},
350                         }
351                 }
352         }
353         if cluster.Services.Controller.ExternalURL.Host == "" {
354                 for k := range cluster.Services.Controller.InternalURLs {
355                         cluster.Services.Controller.ExternalURL = k
356                 }
357         }
358         if cluster.SystemRootToken == "" {
359                 cluster.SystemRootToken = randomHexString(64)
360         }
361         if cluster.API.RailsSessionSecretToken == "" {
362                 cluster.API.RailsSessionSecretToken = randomHexString(64)
363         }
364         if cluster.Collections.BlobSigningKey == "" {
365                 cluster.Collections.BlobSigningKey = randomHexString(64)
366         }
367         cfg.Clusters[cluster.ClusterID] = *cluster
368 }
369
370 func randomHexString(chars int) string {
371         b := make([]byte, chars/2)
372         _, err := rand.Read(b)
373         if err != nil {
374                 panic(err)
375         }
376         return fmt.Sprintf("%x", b)
377 }