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 {
58 LoginGoogleClientID string
59 LoginGoogleClientSecret string
63 func (initcmd *initCommand) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
64 logger := ctxlog.New(stderr, "text", "info")
65 ctx := ctxlog.Context(context.Background(), logger)
66 ctx, cancel := context.WithCancel(ctx)
72 logger.WithError(err).Info("exiting")
76 hostname, err := os.Hostname()
78 err = fmt.Errorf("Hostname(): %w", err)
82 flags := flag.NewFlagSet(prog, flag.ContinueOnError)
83 flags.SetOutput(stderr)
84 versionFlag := flags.Bool("version", false, "Write version information to stdout and exit 0")
85 flags.StringVar(&initcmd.ClusterID, "cluster-id", "", "cluster `id`, like x1234 for a dev cluster")
86 flags.BoolVar(&initcmd.CreateDB, "create-db", true, "create an 'arvados' postgresql role and database using 'sudo -u postgres psql ...' (if false, use existing database specified by POSTGRES_HOST, POSTGRES_USER, POSTGRES_PASSWORD, and POSTGRES_DB env vars, and assume 'CREATE EXTENSION IF NOT EXISTS pg_trgm' has already been done)")
87 flags.StringVar(&initcmd.Domain, "domain", hostname, "cluster public DNS `name`, like x1234.arvadosapi.com")
88 flags.StringVar(&initcmd.Login, "login", "", "login `backend`: test, pam, 'google {client-id} {client-secret}', or ''")
89 flags.StringVar(&initcmd.AdminEmail, "admin-email", "", "give admin privileges to user with given `email`")
90 flags.StringVar(&initcmd.TLS, "tls", "none", "tls certificate `source`: acme, insecure, none, or /path/to/dir containing privkey and cert files")
91 flags.BoolVar(&initcmd.Start, "start", true, "start systemd service after creating config")
92 if ok, code := cmd.ParseFlags(flags, prog, args, "", stderr); !ok {
94 } else if *versionFlag {
95 return cmd.Version.RunCommand(prog, args, stdin, stdout, stderr)
96 } else if !regexp.MustCompile(`^[a-z][a-z0-9]{4}`).MatchString(initcmd.ClusterID) {
97 err = fmt.Errorf("cluster ID %q is invalid; must be an ASCII letter followed by 4 alphanumerics (try -help)", initcmd.ClusterID)
101 if fields := strings.Fields(initcmd.Login); len(fields) == 3 && fields[0] == "google" {
102 initcmd.LoginGoogle = true
103 initcmd.LoginGoogleClientID = fields[1]
104 initcmd.LoginGoogleClientSecret = fields[2]
105 } else if initcmd.Login == "test" {
106 initcmd.LoginTest = true
107 if initcmd.AdminEmail == "" {
108 initcmd.AdminEmail = "admin@example.com"
110 } else if initcmd.Login == "pam" {
111 initcmd.LoginPAM = true
112 } else if initcmd.Login == "" {
113 // none; login will show an error page
115 err = fmt.Errorf("invalid argument to -login: %q: should be 'test', 'pam', 'google {client-id} {client-secret}', or empty", initcmd.Login)
120 case "none", "acme", "insecure":
122 if !strings.HasPrefix(initcmd.TLS, "/") {
123 err = fmt.Errorf("invalid argument to -tls: %q; see %s -help", initcmd.TLS, prog)
126 initcmd.TLSDir = initcmd.TLS
129 confdir := "/etc/arvados"
130 conffile := confdir + "/config.yml"
131 if _, err = os.Stat(conffile); err == nil {
132 err = fmt.Errorf("config file %s already exists; delete it first if you really want to start over", conffile)
137 for i := 4440; i < 4460; i++ {
138 ports = append(ports, i)
140 if initcmd.TLS == "acme" {
141 ports = append(ports, 80)
143 for _, port := range ports {
144 err = initcmd.checkPort(ctx, fmt.Sprintf("%d", port))
150 if initcmd.CreateDB {
151 // Do the "create extension" thing early. This way, if
152 // there's no local postgresql server (a likely
153 // failure mode), we can bail out without any side
154 // effects, and the user can start over easily.
155 fmt.Fprintln(stderr, "installing pg_trgm postgresql extension...")
156 cmd := exec.CommandContext(ctx, "sudo", "-u", "postgres", "psql", "--quiet",
157 "-c", `CREATE EXTENSION IF NOT EXISTS pg_trgm`)
163 err = fmt.Errorf("error preparing postgresql server: %w", err)
166 fmt.Fprintln(stderr, "...done")
167 initcmd.PostgreSQL.Host = "localhost"
168 initcmd.PostgreSQL.User = "arvados"
169 initcmd.PostgreSQL.Password = initcmd.RandomHex(32)
170 initcmd.PostgreSQL.DB = "arvados"
172 initcmd.PostgreSQL.Host = os.Getenv("POSTGRES_HOST")
173 initcmd.PostgreSQL.User = os.Getenv("POSTGRES_USER")
174 initcmd.PostgreSQL.Password = os.Getenv("POSTGRES_PASSWORD")
175 initcmd.PostgreSQL.DB = os.Getenv("POSTGRES_DB")
176 if initcmd.PostgreSQL.Host == "" || initcmd.PostgreSQL.User == "" || initcmd.PostgreSQL.Password == "" || initcmd.PostgreSQL.DB == "" {
177 err = fmt.Errorf("missing $POSTGRES_* env var(s) for -create-db=false; see %s -help", prog)
182 wwwuser, err := user.Lookup("www-data")
184 err = fmt.Errorf("user.Lookup(%q): %w", "www-data", err)
187 wwwgid, err := strconv.Atoi(wwwuser.Gid)
192 fmt.Fprintln(stderr, "creating data storage directory /var/lib/arvados/keep ...")
193 err = os.Mkdir("/var/lib/arvados/keep", 0600)
194 if err != nil && !os.IsExist(err) {
195 err = fmt.Errorf("mkdir /var/lib/arvados/keep: %w", err)
198 fmt.Fprintln(stderr, "...done")
200 fmt.Fprintln(stderr, "creating config file", conffile, "...")
201 err = os.Mkdir(confdir, 0750)
202 if err != nil && !os.IsExist(err) {
203 err = fmt.Errorf("mkdir %s: %w", confdir, err)
206 err = os.Chown(confdir, 0, wwwgid)
208 err = fmt.Errorf("chown 0:%d %s: %w", wwwgid, confdir, err)
211 f, err := os.OpenFile(conffile+".tmp", os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0644)
213 err = fmt.Errorf("open %s: %w", conffile+".tmp", err)
216 tmpl, err := template.New("config").Parse(`Clusters:
221 "http://0.0.0.0:9000/": {}
222 ExternalURL: {{printf "%q" ( print "https://" .Domain ":4440/" ) }}
225 "http://0.0.0.0:9001/": {}
228 "http://0.0.0.0:8005/": {}
229 ExternalURL: {{printf "%q" ( print "wss://" .Domain ":4446/" ) }}
232 "http://0.0.0.0:9019/": {}
235 "http://0.0.0.0:9005/": {}
236 ExternalURL: {{printf "%q" ( print "https://" .Domain ":4445/" ) }}
239 "http://0.0.0.0:9006/": {}
242 "http://0.0.0.0:9007/": {}
243 ExternalURL: {{printf "%q" ( print "https://" .Domain ":4447/" ) }}
246 "http://0.0.0.0:9008/": {}
247 ExternalURL: {{printf "%q" ( print "https://" .Domain ":4448/" ) }}
250 "http://0.0.0.0:9009/": {}
251 ExternalURL: {{printf "%q" ( print "https://" .Domain ":4449/" ) }}
254 "http://0.0.0.0:9010/": {}
256 ExternalURL: {{printf "%q" ( print "https://" .Domain ":4459/composer" ) }}
259 "http://0.0.0.0:9002/": {}
260 ExternalURL: {{printf "%q" ( print "https://" .Domain ":4442/" ) }}
263 "http://0.0.0.0:9003/": {}
264 ExternalURL: {{printf "%q" ( print "https://" .Domain "/" ) }}
267 "http://0.0.0.0:9011/": {}
269 BlobSigningKey: {{printf "%q" ( .RandomHex 50 )}}
270 {{if eq .TLS "insecure"}}
271 TrustAllContent: true
274 DispatchPrivateKey: {{printf "%q" .GenerateSSHPrivateKey}}
278 ManagementToken: {{printf "%q" ( .RandomHex 50 )}}
281 dbname: {{printf "%q" .PostgreSQL.DB}}
282 host: {{printf "%q" .PostgreSQL.Host}}
283 user: {{printf "%q" .PostgreSQL.User}}
284 password: {{printf "%q" .PostgreSQL.Password}}
285 SystemRootToken: {{printf "%q" ( .RandomHex 50 )}}
287 {{if eq .TLS "insecure"}}
289 {{else if eq .TLS "acme"}}
292 {{else if ne .TLSDir ""}}
293 Certificate: {{printf "%q" (print .TLSDir "/cert")}}
294 Key: {{printf "%q" (print .TLSDir "/privkey")}}
299 {{.ClusterID}}-nyw5e-000000000000000:
302 Root: /var/lib/arvados/keep
305 SecretKeyBase: {{printf "%q" ( .RandomHex 50 )}}
310 {{else if .LoginTest}}
316 Email: {{printf "%q" .AdminEmail}}
318 {{else if .LoginGoogle}}
322 ClientID: {{printf "%q" .LoginGoogleClientID}}
323 ClientSecret: {{printf "%q" .LoginGoogleClientSecret}}
326 AutoAdminUserWithEmail: {{printf "%q" .AdminEmail}}
331 err = tmpl.Execute(f, initcmd)
333 err = fmt.Errorf("%s: tmpl.Execute: %w", conffile+".tmp", err)
338 err = fmt.Errorf("%s: close: %w", conffile+".tmp", err)
341 err = os.Rename(conffile+".tmp", conffile)
343 err = fmt.Errorf("rename %s -> %s: %w", conffile+".tmp", conffile, err)
346 fmt.Fprintln(stderr, "...done")
348 ldr := config.NewLoader(nil, logger)
349 ldr.SkipLegacy = true
350 ldr.Path = conffile // load the file we just wrote, even if $ARVADOS_CONFIG is set
351 cfg, err := ldr.Load()
353 err = fmt.Errorf("%s: %w", conffile, err)
356 cluster, err := cfg.GetCluster("")
361 fmt.Fprintln(stderr, "creating postresql user and database...")
362 err = initcmd.createDB(ctx, cluster.PostgreSQL.Connection, stderr)
366 fmt.Fprintln(stderr, "...done")
368 fmt.Fprintln(stderr, "initializing database...")
369 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")
370 cmd.Dir = "/var/lib/arvados/railsapi"
375 err = fmt.Errorf("rake db:setup failed: %w", err)
378 fmt.Fprintln(stderr, "...done")
381 fmt.Fprintln(stderr, "starting systemd service...")
382 cmd := exec.CommandContext(ctx, "systemctl", "start", "arvados")
388 err = fmt.Errorf("%v: %w", cmd.Args, err)
391 fmt.Fprintln(stderr, "...done")
393 fmt.Fprintln(stderr, "checking controller API endpoint...")
394 u := url.URL(cluster.Services.Controller.ExternalURL)
395 conn := rpc.NewConn(cluster.ClusterID, &u, cluster.TLS.Insecure, rpc.PassthroughTokenProvider)
396 ctx := auth.NewContext(context.Background(), auth.NewCredentials(cluster.SystemRootToken))
397 _, err = conn.UserGetCurrent(ctx, arvados.GetOptions{})
399 err = fmt.Errorf("API request failed: %w", err)
402 fmt.Fprintln(stderr, "...looks good")
405 fmt.Fprintf(stderr, `
406 Setup complete. Next steps:
407 * run 'arv sudo diagnostics'
408 * log in to workbench2 at %s
409 * see documentation at https://doc.arvados.org/install/automatic.html
410 `, cluster.Services.Workbench2.ExternalURL.String())
415 func (initcmd *initCommand) GenerateSSHPrivateKey() (string, error) {
416 privkey, err := rsa.GenerateKey(rand.Reader, 4096)
420 err = privkey.Validate()
424 return string(pem.EncodeToMemory(&pem.Block{
425 Type: "RSA PRIVATE KEY",
426 Bytes: x509.MarshalPKCS1PrivateKey(privkey),
430 func (initcmd *initCommand) RandomHex(chars int) string {
431 b := make([]byte, chars/2)
432 _, err := rand.Read(b)
436 return fmt.Sprintf("%x", b)
439 func (initcmd *initCommand) createDB(ctx context.Context, dbconn arvados.PostgreSQLConnection, stderr io.Writer) error {
440 cmd := exec.CommandContext(ctx, "sudo", "-u", "postgres", "psql", "--quiet",
441 "-c", `CREATE USER `+pq.QuoteIdentifier(dbconn["user"])+` WITH SUPERUSER ENCRYPTED PASSWORD `+pq.QuoteLiteral(dbconn["password"]),
442 "-c", `CREATE DATABASE `+pq.QuoteIdentifier(dbconn["dbname"])+` WITH TEMPLATE template0 ENCODING 'utf8'`,
449 return fmt.Errorf("error setting up arvados user/database: %w", err)
454 // Confirm that http://{initcmd.Domain}:{port} reaches a server that
457 // If port is "80", listening fails, and Nginx appears to be using the
458 // debian-packaged default configuration that listens on port 80,
459 // disable that Nginx config and try again.
461 // (Typically, the reason Nginx is installed is so that Arvados can
462 // run an Nginx child process; the default Nginx service using config
463 // from /etc/nginx is just an unfortunate side effect of installing
464 // Nginx by way of the Debian package.)
465 func (initcmd *initCommand) checkPort(ctx context.Context, port string) error {
466 err := initcmd.checkPortOnce(ctx, port)
467 if err == nil || port != "80" {
468 // success, or poking Nginx in the eye won't help
471 d, err2 := os.Open("/etc/nginx/sites-enabled/.")
475 fis, err2 := d.Readdir(-1)
476 if err2 != nil || len(fis) != 1 {
479 if target, err2 := os.Readlink("/etc/nginx/sites-enabled/default"); err2 != nil || target != "/etc/nginx/sites-available/default" {
482 err2 = os.Remove("/etc/nginx/sites-enabled/default")
486 exec.CommandContext(ctx, "nginx", "-s", "reload").Run()
487 time.Sleep(time.Second)
488 return initcmd.checkPortOnce(ctx, port)
491 // Start an http server on 0.0.0.0:{port} and confirm that
492 // http://{initcmd.Domain}:{port} reaches that server.
493 func (initcmd *initCommand) checkPortOnce(ctx context.Context, port string) error {
494 b := make([]byte, 128)
495 _, err := rand.Read(b)
499 token := fmt.Sprintf("%x", b)
502 Addr: net.JoinHostPort("", port),
503 Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
506 var errServe atomic.Value
508 errServe.Store(srv.ListenAndServe())
511 url := "http://" + net.JoinHostPort(initcmd.Domain, port) + "/probe"
512 req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
516 resp, err := http.DefaultClient.Do(req)
518 defer resp.Body.Close()
520 if errServe, _ := errServe.Load().(error); errServe != nil {
521 // If server already exited, return that error
522 // (probably "can't listen"), not the request error.
528 buf := make([]byte, len(token))
529 n, err := io.ReadFull(resp.Body, buf)
530 if string(buf[:n]) != token {
531 return fmt.Errorf("listened on port %s but %s connected to something else, returned %q, err %v", port, url, buf[:n], err)