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