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:9006/": {}
238 "http://0.0.0.0:9007/": {}
239 ExternalURL: {{printf "%q" ( print "https://" .Domain ":4447/" ) }}
242 "http://0.0.0.0:9008/": {}
243 ExternalURL: {{printf "%q" ( print "https://" .Domain ":4448/" ) }}
246 "http://0.0.0.0:9009/": {}
247 ExternalURL: {{printf "%q" ( print "https://" .Domain ":4449/" ) }}
250 "http://0.0.0.0:9010/": {}
252 ExternalURL: {{printf "%q" ( print "https://" .Domain ":4459/composer" ) }}
255 "http://0.0.0.0:9002/": {}
256 ExternalURL: {{printf "%q" ( print "https://" .Domain ":4442/" ) }}
259 "http://0.0.0.0:9003/": {}
260 ExternalURL: {{printf "%q" ( print "https://" .Domain "/" ) }}
263 "http://0.0.0.0:9011/": {}
265 BlobSigningKey: {{printf "%q" ( .RandomHex 50 )}}
266 {{if eq .TLS "insecure"}}
267 TrustAllContent: true
270 DispatchPrivateKey: {{printf "%q" .GenerateSSHPrivateKey}}
274 ManagementToken: {{printf "%q" ( .RandomHex 50 )}}
277 dbname: {{printf "%q" .PostgreSQL.DB}}
278 host: {{printf "%q" .PostgreSQL.Host}}
279 user: {{printf "%q" .PostgreSQL.User}}
280 password: {{printf "%q" .PostgreSQL.Password}}
281 SystemRootToken: {{printf "%q" ( .RandomHex 50 )}}
283 {{if eq .TLS "insecure"}}
285 {{else if eq .TLS "acme"}}
288 {{else if ne .TLSDir ""}}
289 Certificate: {{printf "%q" (print .TLSDir "/cert")}}
290 Key: {{printf "%q" (print .TLSDir "/privkey")}}
295 {{.ClusterID}}-nyw5e-000000000000000:
298 Root: /var/lib/arvados/keep
304 {{else if .LoginTest}}
310 Email: {{printf "%q" .AdminEmail}}
312 {{else if .LoginGoogle}}
316 ClientID: {{printf "%q" .LoginGoogleClientID}}
317 ClientSecret: {{printf "%q" .LoginGoogleClientSecret}}
320 AutoAdminUserWithEmail: {{printf "%q" .AdminEmail}}
325 err = tmpl.Execute(f, initcmd)
327 err = fmt.Errorf("%s: tmpl.Execute: %w", conffile+".tmp", err)
332 err = fmt.Errorf("%s: close: %w", conffile+".tmp", err)
335 err = os.Rename(conffile+".tmp", conffile)
337 err = fmt.Errorf("rename %s -> %s: %w", conffile+".tmp", conffile, err)
340 fmt.Fprintln(stderr, "...done")
342 ldr := config.NewLoader(nil, logger)
343 ldr.SkipLegacy = true
344 ldr.Path = conffile // load the file we just wrote, even if $ARVADOS_CONFIG is set
345 cfg, err := ldr.Load()
347 err = fmt.Errorf("%s: %w", conffile, err)
350 cluster, err := cfg.GetCluster("")
355 fmt.Fprintln(stderr, "creating postresql user and database...")
356 err = initcmd.createDB(ctx, cluster.PostgreSQL.Connection, stderr)
360 fmt.Fprintln(stderr, "...done")
362 fmt.Fprintln(stderr, "initializing database...")
363 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")
364 cmd.Dir = "/var/lib/arvados/railsapi"
369 err = fmt.Errorf("rake db:setup failed: %w", err)
372 fmt.Fprintln(stderr, "...done")
375 fmt.Fprintln(stderr, "starting systemd service...")
376 cmd := exec.CommandContext(ctx, "systemctl", "start", "arvados")
382 err = fmt.Errorf("%v: %w", cmd.Args, err)
385 fmt.Fprintln(stderr, "...done")
387 fmt.Fprintln(stderr, "checking controller API endpoint...")
388 u := url.URL(cluster.Services.Controller.ExternalURL)
389 conn := rpc.NewConn(cluster.ClusterID, &u, cluster.TLS.Insecure, rpc.PassthroughTokenProvider)
390 ctx := auth.NewContext(context.Background(), auth.NewCredentials(cluster.SystemRootToken))
391 _, err = conn.UserGetCurrent(ctx, arvados.GetOptions{})
393 err = fmt.Errorf("API request failed: %w", err)
396 fmt.Fprintln(stderr, "...looks good")
399 fmt.Fprintf(stderr, `
400 Setup complete. Next steps:
401 * run 'arv sudo diagnostics'
402 * log in to workbench2 at %s
403 * see documentation at https://doc.arvados.org/install/automatic.html
404 `, cluster.Services.Workbench2.ExternalURL.String())
409 func (initcmd *initCommand) GenerateSSHPrivateKey() (string, error) {
410 privkey, err := rsa.GenerateKey(rand.Reader, 4096)
414 err = privkey.Validate()
418 return string(pem.EncodeToMemory(&pem.Block{
419 Type: "RSA PRIVATE KEY",
420 Bytes: x509.MarshalPKCS1PrivateKey(privkey),
424 func (initcmd *initCommand) RandomHex(chars int) string {
425 b := make([]byte, chars/2)
426 _, err := rand.Read(b)
430 return fmt.Sprintf("%x", b)
433 func (initcmd *initCommand) createDB(ctx context.Context, dbconn arvados.PostgreSQLConnection, stderr io.Writer) error {
434 cmd := exec.CommandContext(ctx, "sudo", "-u", "postgres", "psql", "--quiet",
435 "-c", `CREATE USER `+pq.QuoteIdentifier(dbconn["user"])+` WITH SUPERUSER ENCRYPTED PASSWORD `+pq.QuoteLiteral(dbconn["password"]),
436 "-c", `CREATE DATABASE `+pq.QuoteIdentifier(dbconn["dbname"])+` WITH TEMPLATE template0 ENCODING 'utf8'`,
443 return fmt.Errorf("error setting up arvados user/database: %w", err)
448 // Confirm that http://{initcmd.Domain}:{port} reaches a server that
451 // If port is "80", listening fails, and Nginx appears to be using the
452 // debian-packaged default configuration that listens on port 80,
453 // disable that Nginx config and try again.
455 // (Typically, the reason Nginx is installed is so that Arvados can
456 // run an Nginx child process; the default Nginx service using config
457 // from /etc/nginx is just an unfortunate side effect of installing
458 // Nginx by way of the Debian package.)
459 func (initcmd *initCommand) checkPort(ctx context.Context, port string) error {
460 err := initcmd.checkPortOnce(ctx, port)
461 if err == nil || port != "80" {
462 // success, or poking Nginx in the eye won't help
465 d, err2 := os.Open("/etc/nginx/sites-enabled/.")
469 fis, err2 := d.Readdir(-1)
470 if err2 != nil || len(fis) != 1 {
473 if target, err2 := os.Readlink("/etc/nginx/sites-enabled/default"); err2 != nil || target != "/etc/nginx/sites-available/default" {
476 err2 = os.Remove("/etc/nginx/sites-enabled/default")
480 exec.CommandContext(ctx, "nginx", "-s", "reload").Run()
481 time.Sleep(time.Second)
482 return initcmd.checkPortOnce(ctx, port)
485 // Start an http server on 0.0.0.0:{port} and confirm that
486 // http://{initcmd.Domain}:{port} reaches that server.
487 func (initcmd *initCommand) checkPortOnce(ctx context.Context, port string) error {
488 b := make([]byte, 128)
489 _, err := rand.Read(b)
493 token := fmt.Sprintf("%x", b)
496 Addr: net.JoinHostPort("", port),
497 Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
500 var errServe atomic.Value
502 errServe.Store(srv.ListenAndServe())
505 url := "http://" + net.JoinHostPort(initcmd.Domain, port) + "/probe"
506 req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
510 resp, err := http.DefaultClient.Do(req)
512 defer resp.Body.Close()
514 if errServe, _ := errServe.Load().(error); errServe != nil {
515 // If server already exited, return that error
516 // (probably "can't listen"), not the request error.
522 buf := make([]byte, len(token))
523 n, err := io.ReadFull(resp.Body, buf)
524 if string(buf[:n]) != token {
525 return fmt.Errorf("listened on port %s but %s connected to something else, returned %q, err %v", port, url, buf[:n], err)