1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
25 "git.arvados.org/arvados.git/lib/cmd"
26 "git.arvados.org/arvados.git/lib/config"
27 "git.arvados.org/arvados.git/lib/controller/rpc"
28 "git.arvados.org/arvados.git/sdk/go/arvados"
29 "git.arvados.org/arvados.git/sdk/go/auth"
30 "git.arvados.org/arvados.git/sdk/go/ctxlog"
34 var InitCommand cmd.Handler = &initCommand{}
36 type initCommand struct {
39 PostgreSQLPassword string
48 LoginGoogleClientID string
49 LoginGoogleClientSecret string
52 func (initcmd *initCommand) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
53 logger := ctxlog.New(stderr, "text", "info")
54 ctx := ctxlog.Context(context.Background(), logger)
55 ctx, cancel := context.WithCancel(ctx)
61 logger.WithError(err).Info("exiting")
65 hostname, err := os.Hostname()
67 err = fmt.Errorf("Hostname(): %w", err)
71 flags := flag.NewFlagSet(prog, flag.ContinueOnError)
72 flags.SetOutput(stderr)
73 versionFlag := flags.Bool("version", false, "Write version information to stdout and exit 0")
74 flags.StringVar(&initcmd.ClusterID, "cluster-id", "", "cluster `id`, like x1234 for a dev cluster")
75 flags.StringVar(&initcmd.Domain, "domain", hostname, "cluster public DNS `name`, like x1234.arvadosapi.com")
76 flags.StringVar(&initcmd.Login, "login", "", "login `backend`: test, pam, 'google {client-id} {client-secret}', or ''")
77 flags.StringVar(&initcmd.AdminEmail, "admin-email", "", "give admin privileges to user with given `email`")
78 flags.StringVar(&initcmd.TLS, "tls", "none", "tls certificate `source`: acme, auto, insecure, or none")
79 flags.BoolVar(&initcmd.Start, "start", true, "start systemd service after creating config")
80 if ok, code := cmd.ParseFlags(flags, prog, args, "", stderr); !ok {
82 } else if *versionFlag {
83 return cmd.Version.RunCommand(prog, args, stdin, stdout, stderr)
84 } else if !regexp.MustCompile(`^[a-z][a-z0-9]{4}`).MatchString(initcmd.ClusterID) {
85 err = fmt.Errorf("cluster ID %q is invalid; must be an ASCII letter followed by 4 alphanumerics (try -help)", initcmd.ClusterID)
89 if fields := strings.Fields(initcmd.Login); len(fields) == 3 && fields[0] == "google" {
90 initcmd.LoginGoogle = true
91 initcmd.LoginGoogleClientID = fields[1]
92 initcmd.LoginGoogleClientSecret = fields[2]
93 } else if initcmd.Login == "test" {
94 initcmd.LoginTest = true
95 if initcmd.AdminEmail == "" {
96 initcmd.AdminEmail = "admin@example.com"
98 } else if initcmd.Login == "pam" {
99 initcmd.LoginPAM = true
100 } else if initcmd.Login == "" {
101 // none; login will show an error page
103 err = fmt.Errorf("invalid argument to -login: %q: should be 'test', 'pam', 'google {client-id} {client-secret}', or empty", initcmd.Login)
107 confdir := "/etc/arvados"
108 conffile := confdir + "/config.yml"
109 if _, err = os.Stat(conffile); err == nil {
110 err = fmt.Errorf("config file %s already exists; delete it first if you really want to start over", conffile)
114 wwwuser, err := user.Lookup("www-data")
116 err = fmt.Errorf("user.Lookup(%q): %w", "www-data", err)
119 wwwgid, err := strconv.Atoi(wwwuser.Gid)
123 initcmd.PostgreSQLPassword = initcmd.RandomHex(32)
125 fmt.Fprintln(stderr, "creating data storage directory /var/lib/arvados/keep ...")
126 err = os.Mkdir("/var/lib/arvados/keep", 0600)
127 if err != nil && !os.IsExist(err) {
128 err = fmt.Errorf("mkdir /var/lib/arvados/keep: %w", err)
131 fmt.Fprintln(stderr, "...done")
133 fmt.Fprintln(stderr, "creating config file", conffile, "...")
134 err = os.Mkdir(confdir, 0750)
135 if err != nil && !os.IsExist(err) {
136 err = fmt.Errorf("mkdir %s: %w", confdir, err)
139 err = os.Chown(confdir, 0, wwwgid)
141 err = fmt.Errorf("chown 0:%d %s: %w", wwwgid, confdir, err)
144 f, err := os.OpenFile(conffile+".tmp", os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0644)
146 err = fmt.Errorf("open %s: %w", conffile+".tmp", err)
149 tmpl, err := template.New("config").Parse(`Clusters:
154 "http://0.0.0.0:9000/": {}
155 ExternalURL: {{printf "%q" ( print "https://" .Domain ":4440/" ) }}
158 "http://0.0.0.0:9001/": {}
161 "http://0.0.0.0:8005/": {}
162 ExternalURL: {{printf "%q" ( print "wss://" .Domain ":4446/" ) }}
165 "http://0.0.0.0:9019/": {}
168 "http://0.0.0.0:9005/": {}
169 ExternalURL: {{printf "%q" ( print "https://" .Domain ":4445/" ) }}
172 "http://0.0.0.0:9006/": {}
175 "http://0.0.0.0:9007/": {}
176 ExternalURL: {{printf "%q" ( print "https://" .Domain ":4447/" ) }}
179 "http://0.0.0.0:9008/": {}
180 ExternalURL: {{printf "%q" ( print "https://" .Domain ":4448/" ) }}
183 "http://0.0.0.0:9009/": {}
184 ExternalURL: {{printf "%q" ( print "https://" .Domain ":4449/" ) }}
187 "http://0.0.0.0:9010/": {}
189 ExternalURL: {{printf "%q" ( print "https://" .Domain ":4459/composer" ) }}
192 "http://0.0.0.0:9002/": {}
193 ExternalURL: {{printf "%q" ( print "https://" .Domain ":4442/" ) }}
196 "http://0.0.0.0:9003/": {}
197 ExternalURL: {{printf "%q" ( print "https://" .Domain "/" ) }}
200 "http://0.0.0.0:9011/": {}
202 BlobSigningKey: {{printf "%q" ( .RandomHex 50 )}}
203 {{if eq .TLS "insecure"}}
204 TrustAllContent: true
207 DispatchPrivateKey: {{printf "%q" .GenerateSSHPrivateKey}}
211 ManagementToken: {{printf "%q" ( .RandomHex 50 )}}
217 password: {{printf "%q" .PostgreSQLPassword}}
218 SystemRootToken: {{printf "%q" ( .RandomHex 50 )}}
220 {{if eq .TLS "insecure"}}
222 {{else if eq .TLS "auto"}}
224 {{else if eq .TLS "acme"}}
225 Certificate: {{printf "%q" (print "/var/lib/acme/live/" .Domain "/cert")}}
226 Key: {{printf "%q" (print "/var/lib/acme/live/" .Domain "/privkey")}}
231 {{.ClusterID}}-nyw5e-000000000000000:
234 Root: /var/lib/arvados/keep
237 SecretKeyBase: {{printf "%q" ( .RandomHex 50 )}}
242 {{else if .LoginTest}}
248 Email: {{printf "%q" .AdminEmail}}
250 {{else if .LoginGoogle}}
254 ClientID: {{printf "%q" .LoginGoogleClientID}}
255 ClientSecret: {{printf "%q" .LoginGoogleClientSecret}}
258 AutoAdminUserWithEmail: {{printf "%q" .AdminEmail}}
263 err = tmpl.Execute(f, initcmd)
265 err = fmt.Errorf("%s: tmpl.Execute: %w", conffile+".tmp", err)
270 err = fmt.Errorf("%s: close: %w", conffile+".tmp", err)
273 err = os.Rename(conffile+".tmp", conffile)
275 err = fmt.Errorf("rename %s -> %s: %w", conffile+".tmp", conffile, err)
278 fmt.Fprintln(stderr, "...done")
280 ldr := config.NewLoader(nil, logger)
281 ldr.SkipLegacy = true
282 cfg, err := ldr.Load()
284 err = fmt.Errorf("%s: %w", conffile, err)
287 cluster, err := cfg.GetCluster("")
292 fmt.Fprintln(stderr, "creating postresql user and database...")
293 err = initcmd.createDB(ctx, cluster.PostgreSQL.Connection, stderr)
297 fmt.Fprintln(stderr, "...done")
299 fmt.Fprintln(stderr, "initializing database...")
300 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")
301 cmd.Dir = "/var/lib/arvados/railsapi"
306 err = fmt.Errorf("rake db:setup failed: %w", err)
309 fmt.Fprintln(stderr, "...done")
312 fmt.Fprintln(stderr, "starting systemd service...")
313 cmd := exec.CommandContext(ctx, "systemctl", "start", "arvados")
319 err = fmt.Errorf("%v: %w", cmd.Args, err)
323 fmt.Fprintln(stderr, "checking controller API endpoint...")
324 u := url.URL(cluster.Services.Controller.ExternalURL)
325 conn := rpc.NewConn(cluster.ClusterID, &u, cluster.TLS.Insecure, rpc.PassthroughTokenProvider)
326 ctx := auth.NewContext(context.Background(), auth.NewCredentials(cluster.SystemRootToken))
327 _, err = conn.UserGetCurrent(ctx, arvados.GetOptions{})
329 err = fmt.Errorf("API request failed: %w", err)
332 fmt.Fprintln(stderr, "...looks good")
335 fmt.Fprintln(stderr, "Setup complete. You should now be able to log in to workbench2 at", cluster.Services.Workbench2.ExternalURL.String())
340 func (initcmd *initCommand) GenerateSSHPrivateKey() (string, error) {
341 privkey, err := rsa.GenerateKey(rand.Reader, 4096)
345 err = privkey.Validate()
349 return string(pem.EncodeToMemory(&pem.Block{
350 Type: "RSA PRIVATE KEY",
351 Bytes: x509.MarshalPKCS1PrivateKey(privkey),
355 func (initcmd *initCommand) RandomHex(chars int) string {
356 b := make([]byte, chars/2)
357 _, err := rand.Read(b)
361 return fmt.Sprintf("%x", b)
364 func (initcmd *initCommand) createDB(ctx context.Context, dbconn arvados.PostgreSQLConnection, stderr io.Writer) error {
365 cmd := exec.CommandContext(ctx, "sudo", "-u", "postgres", "psql", "--quiet",
366 "-c", `CREATE USER `+pq.QuoteIdentifier(dbconn["user"])+` WITH SUPERUSER ENCRYPTED PASSWORD `+pq.QuoteLiteral(dbconn["password"]),
367 "-c", `CREATE DATABASE `+pq.QuoteIdentifier(dbconn["dbname"])+` WITH TEMPLATE template0 ENCODING 'utf8'`,
368 "-c", `CREATE EXTENSION IF NOT EXISTS pg_trgm`,
375 return fmt.Errorf("error setting up arvados user/database: %w", err)