1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
29 "git.arvados.org/arvados.git/lib/cmd"
30 "git.arvados.org/arvados.git/lib/config"
31 "git.arvados.org/arvados.git/lib/controller/rpc"
32 "git.arvados.org/arvados.git/sdk/go/arvados"
33 "git.arvados.org/arvados.git/sdk/go/auth"
34 "git.arvados.org/arvados.git/sdk/go/ctxlog"
38 var InitCommand cmd.Handler = &initCommand{}
40 type initCommand struct {
43 PostgreSQLPassword string
52 LoginGoogleClientID string
53 LoginGoogleClientSecret string
56 func (initcmd *initCommand) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
57 logger := ctxlog.New(stderr, "text", "info")
58 ctx := ctxlog.Context(context.Background(), logger)
59 ctx, cancel := context.WithCancel(ctx)
65 logger.WithError(err).Info("exiting")
69 hostname, err := os.Hostname()
71 err = fmt.Errorf("Hostname(): %w", err)
75 flags := flag.NewFlagSet(prog, flag.ContinueOnError)
76 flags.SetOutput(stderr)
77 versionFlag := flags.Bool("version", false, "Write version information to stdout and exit 0")
78 flags.StringVar(&initcmd.ClusterID, "cluster-id", "", "cluster `id`, like x1234 for a dev cluster")
79 flags.StringVar(&initcmd.Domain, "domain", hostname, "cluster public DNS `name`, like x1234.arvadosapi.com")
80 flags.StringVar(&initcmd.Login, "login", "", "login `backend`: test, pam, 'google {client-id} {client-secret}', or ''")
81 flags.StringVar(&initcmd.AdminEmail, "admin-email", "", "give admin privileges to user with given `email`")
82 flags.StringVar(&initcmd.TLS, "tls", "none", "tls certificate `source`: acme, auto, insecure, or none")
83 flags.BoolVar(&initcmd.Start, "start", true, "start systemd service after creating config")
84 if ok, code := cmd.ParseFlags(flags, prog, args, "", stderr); !ok {
86 } else if *versionFlag {
87 return cmd.Version.RunCommand(prog, args, stdin, stdout, stderr)
88 } else if !regexp.MustCompile(`^[a-z][a-z0-9]{4}`).MatchString(initcmd.ClusterID) {
89 err = fmt.Errorf("cluster ID %q is invalid; must be an ASCII letter followed by 4 alphanumerics (try -help)", initcmd.ClusterID)
93 if fields := strings.Fields(initcmd.Login); len(fields) == 3 && fields[0] == "google" {
94 initcmd.LoginGoogle = true
95 initcmd.LoginGoogleClientID = fields[1]
96 initcmd.LoginGoogleClientSecret = fields[2]
97 } else if initcmd.Login == "test" {
98 initcmd.LoginTest = true
99 if initcmd.AdminEmail == "" {
100 initcmd.AdminEmail = "admin@example.com"
102 } else if initcmd.Login == "pam" {
103 initcmd.LoginPAM = true
104 } else if initcmd.Login == "" {
105 // none; login will show an error page
107 err = fmt.Errorf("invalid argument to -login: %q: should be 'test', 'pam', 'google {client-id} {client-secret}', or empty", initcmd.Login)
111 confdir := "/etc/arvados"
112 conffile := confdir + "/config.yml"
113 if _, err = os.Stat(conffile); err == nil {
114 err = fmt.Errorf("config file %s already exists; delete it first if you really want to start over", conffile)
118 err = initcmd.checkPort(ctx, "4440")
119 err = initcmd.checkPort(ctx, "443")
120 if initcmd.TLS == "auto" {
121 err = initcmd.checkPort(ctx, "80")
127 // Do the "create extension" thing early. This way, if there's
128 // no local postgresql server (a likely failure mode), we can
129 // bail out without any side effects, and the user can start
131 fmt.Fprintln(stderr, "installing pg_trgm postgresql extension...")
132 cmd := exec.CommandContext(ctx, "sudo", "-u", "postgres", "psql", "--quiet",
133 "-c", `CREATE EXTENSION IF NOT EXISTS pg_trgm`)
139 err = fmt.Errorf("error preparing postgresql server: %w", err)
142 fmt.Fprintln(stderr, "...done")
144 wwwuser, err := user.Lookup("www-data")
146 err = fmt.Errorf("user.Lookup(%q): %w", "www-data", err)
149 wwwgid, err := strconv.Atoi(wwwuser.Gid)
153 initcmd.PostgreSQLPassword = initcmd.RandomHex(32)
155 fmt.Fprintln(stderr, "creating data storage directory /var/lib/arvados/keep ...")
156 err = os.Mkdir("/var/lib/arvados/keep", 0600)
157 if err != nil && !os.IsExist(err) {
158 err = fmt.Errorf("mkdir /var/lib/arvados/keep: %w", err)
161 fmt.Fprintln(stderr, "...done")
163 fmt.Fprintln(stderr, "creating config file", conffile, "...")
164 err = os.Mkdir(confdir, 0750)
165 if err != nil && !os.IsExist(err) {
166 err = fmt.Errorf("mkdir %s: %w", confdir, err)
169 err = os.Chown(confdir, 0, wwwgid)
171 err = fmt.Errorf("chown 0:%d %s: %w", wwwgid, confdir, err)
174 f, err := os.OpenFile(conffile+".tmp", os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0644)
176 err = fmt.Errorf("open %s: %w", conffile+".tmp", err)
179 tmpl, err := template.New("config").Parse(`Clusters:
184 "http://0.0.0.0:9000/": {}
185 ExternalURL: {{printf "%q" ( print "https://" .Domain ":4440/" ) }}
188 "http://0.0.0.0:9001/": {}
191 "http://0.0.0.0:8005/": {}
192 ExternalURL: {{printf "%q" ( print "wss://" .Domain ":4446/" ) }}
195 "http://0.0.0.0:9019/": {}
198 "http://0.0.0.0:9005/": {}
199 ExternalURL: {{printf "%q" ( print "https://" .Domain ":4445/" ) }}
202 "http://0.0.0.0:9006/": {}
205 "http://0.0.0.0:9007/": {}
206 ExternalURL: {{printf "%q" ( print "https://" .Domain ":4447/" ) }}
209 "http://0.0.0.0:9008/": {}
210 ExternalURL: {{printf "%q" ( print "https://" .Domain ":4448/" ) }}
213 "http://0.0.0.0:9009/": {}
214 ExternalURL: {{printf "%q" ( print "https://" .Domain ":4449/" ) }}
217 "http://0.0.0.0:9010/": {}
219 ExternalURL: {{printf "%q" ( print "https://" .Domain ":4459/composer" ) }}
222 "http://0.0.0.0:9002/": {}
223 ExternalURL: {{printf "%q" ( print "https://" .Domain ":4442/" ) }}
226 "http://0.0.0.0:9003/": {}
227 ExternalURL: {{printf "%q" ( print "https://" .Domain "/" ) }}
230 "http://0.0.0.0:9011/": {}
232 BlobSigningKey: {{printf "%q" ( .RandomHex 50 )}}
233 {{if eq .TLS "insecure"}}
234 TrustAllContent: true
237 DispatchPrivateKey: {{printf "%q" .GenerateSSHPrivateKey}}
241 ManagementToken: {{printf "%q" ( .RandomHex 50 )}}
247 password: {{printf "%q" .PostgreSQLPassword}}
248 SystemRootToken: {{printf "%q" ( .RandomHex 50 )}}
250 {{if eq .TLS "insecure"}}
252 {{else if eq .TLS "auto"}}
254 {{else if eq .TLS "acme"}}
255 Certificate: {{printf "%q" (print "/var/lib/acme/live/" .Domain "/cert")}}
256 Key: {{printf "%q" (print "/var/lib/acme/live/" .Domain "/privkey")}}
261 {{.ClusterID}}-nyw5e-000000000000000:
264 Root: /var/lib/arvados/keep
267 SecretKeyBase: {{printf "%q" ( .RandomHex 50 )}}
272 {{else if .LoginTest}}
278 Email: {{printf "%q" .AdminEmail}}
280 {{else if .LoginGoogle}}
284 ClientID: {{printf "%q" .LoginGoogleClientID}}
285 ClientSecret: {{printf "%q" .LoginGoogleClientSecret}}
288 AutoAdminUserWithEmail: {{printf "%q" .AdminEmail}}
293 err = tmpl.Execute(f, initcmd)
295 err = fmt.Errorf("%s: tmpl.Execute: %w", conffile+".tmp", err)
300 err = fmt.Errorf("%s: close: %w", conffile+".tmp", err)
303 err = os.Rename(conffile+".tmp", conffile)
305 err = fmt.Errorf("rename %s -> %s: %w", conffile+".tmp", conffile, err)
308 fmt.Fprintln(stderr, "...done")
310 ldr := config.NewLoader(nil, logger)
311 ldr.SkipLegacy = true
312 ldr.Path = conffile // load the file we just wrote, even if $ARVADOS_CONFIG is set
313 cfg, err := ldr.Load()
315 err = fmt.Errorf("%s: %w", conffile, err)
318 cluster, err := cfg.GetCluster("")
323 fmt.Fprintln(stderr, "creating postresql user and database...")
324 err = initcmd.createDB(ctx, cluster.PostgreSQL.Connection, stderr)
328 fmt.Fprintln(stderr, "...done")
330 fmt.Fprintln(stderr, "initializing database...")
331 cmd = exec.CommandContext(ctx, "sudo", "-u", "www-data", "-E", "HOME=/var/www", "PATH=/var/lib/arvados/bin:"+os.Getenv("PATH"), "/var/lib/arvados/bin/bundle", "exec", "rake", "db:setup")
332 cmd.Dir = "/var/lib/arvados/railsapi"
337 err = fmt.Errorf("rake db:setup failed: %w", err)
340 fmt.Fprintln(stderr, "...done")
343 fmt.Fprintln(stderr, "starting systemd service...")
344 cmd := exec.CommandContext(ctx, "systemctl", "start", "arvados")
350 err = fmt.Errorf("%v: %w", cmd.Args, err)
353 fmt.Fprintln(stderr, "...done")
355 fmt.Fprintln(stderr, "checking controller API endpoint...")
356 u := url.URL(cluster.Services.Controller.ExternalURL)
357 conn := rpc.NewConn(cluster.ClusterID, &u, cluster.TLS.Insecure, rpc.PassthroughTokenProvider)
358 ctx := auth.NewContext(context.Background(), auth.NewCredentials(cluster.SystemRootToken))
359 _, err = conn.UserGetCurrent(ctx, arvados.GetOptions{})
361 err = fmt.Errorf("API request failed: %w", err)
364 fmt.Fprintln(stderr, "...looks good")
367 if out, err := exec.CommandContext(ctx, "docker", "version").CombinedOutput(); err == nil && strings.Contains(string(out), "\nServer:\n") {
368 fmt.Fprintln(stderr, "loading alpine docker image for diagnostics...")
369 cmd := exec.CommandContext(ctx, "docker", "pull", "alpine")
374 err = fmt.Errorf("%v: %w", cmd.Args, err)
377 cmd = exec.CommandContext(ctx, "arv", "sudo", "keep", "docker", "alpine")
382 err = fmt.Errorf("%v: %w", cmd.Args, err)
385 fmt.Fprintln(stderr, "...done")
387 fmt.Fprintln(stderr, "docker is not installed -- skipping step of downloading 'alpine' image")
390 fmt.Fprintln(stderr, "Setup complete. You should now be able to log in to workbench2 at", cluster.Services.Workbench2.ExternalURL.String())
395 func (initcmd *initCommand) GenerateSSHPrivateKey() (string, error) {
396 privkey, err := rsa.GenerateKey(rand.Reader, 4096)
400 err = privkey.Validate()
404 return string(pem.EncodeToMemory(&pem.Block{
405 Type: "RSA PRIVATE KEY",
406 Bytes: x509.MarshalPKCS1PrivateKey(privkey),
410 func (initcmd *initCommand) RandomHex(chars int) string {
411 b := make([]byte, chars/2)
412 _, err := rand.Read(b)
416 return fmt.Sprintf("%x", b)
419 func (initcmd *initCommand) createDB(ctx context.Context, dbconn arvados.PostgreSQLConnection, stderr io.Writer) error {
420 cmd := exec.CommandContext(ctx, "sudo", "-u", "postgres", "psql", "--quiet",
421 "-c", `CREATE USER `+pq.QuoteIdentifier(dbconn["user"])+` WITH SUPERUSER ENCRYPTED PASSWORD `+pq.QuoteLiteral(dbconn["password"]),
422 "-c", `CREATE DATABASE `+pq.QuoteIdentifier(dbconn["dbname"])+` WITH TEMPLATE template0 ENCODING 'utf8'`,
429 return fmt.Errorf("error setting up arvados user/database: %w", err)
434 // Confirm that http://{initcmd.Domain}:{port} reaches a server that
437 // If port is "80", listening fails, and Nginx appears to be using the
438 // debian-packaged default configuration that listens on port 80,
439 // disable that Nginx config and try again.
441 // (Typically, the reason Nginx is installed is so that Arvados can
442 // run an Nginx child process; the default Nginx service using config
443 // from /etc/nginx is just an unfortunate side effect of installing
444 // Nginx by way of the Debian package.)
445 func (initcmd *initCommand) checkPort(ctx context.Context, port string) error {
446 err := initcmd.checkPortOnce(ctx, port)
447 if err == nil || port != "80" {
448 // success, or poking Nginx in the eye won't help
451 d, err2 := os.Open("/etc/nginx/sites-enabled/.")
455 fis, err2 := d.Readdir(-1)
456 if err2 != nil || len(fis) != 1 {
459 if target, err2 := os.Readlink("/etc/nginx/sites-enabled/default"); err2 != nil || target != "/etc/nginx/sites-available/default" {
462 err2 = os.Remove("/etc/nginx/sites-enabled/default")
466 exec.CommandContext(ctx, "nginx", "-s", "reload").Run()
467 time.Sleep(time.Second)
468 return initcmd.checkPortOnce(ctx, port)
471 // Start an http server on 0.0.0.0:{port} and confirm that
472 // http://{initcmd.Domain}:{port} reaches that server.
473 func (initcmd *initCommand) checkPortOnce(ctx context.Context, port string) error {
474 b := make([]byte, 128)
475 _, err := rand.Read(b)
479 token := fmt.Sprintf("%x", b)
482 Addr: net.JoinHostPort("", port),
483 Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
486 var errServe atomic.Value
488 errServe.Store(srv.ListenAndServe())
491 url := "http://" + net.JoinHostPort(initcmd.Domain, port) + "/probe"
492 req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
496 resp, err := http.DefaultClient.Do(req)
497 if errServe, _ := errServe.Load().(error); errServe != nil {
498 // If server already exited, return that error
499 // (probably "can't listen"), not the request error.
505 buf := make([]byte, len(token))
506 n, err := io.ReadFull(resp.Body, buf)
507 if string(buf[:n]) != token {
508 return fmt.Errorf("listened on port %s but %s connected to something else, returned %q, err %v", port, url, buf[:n], err)