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 err = os.Mkdir("/var/lib/arvados/keep", 0600)
126 if err != nil && !os.IsExist(err) {
127 err = fmt.Errorf("mkdir /var/lib/arvados/keep: %w", err)
130 fmt.Fprintln(stderr, "created /var/lib/arvados/keep")
132 err = os.Mkdir(confdir, 0750)
133 if err != nil && !os.IsExist(err) {
134 err = fmt.Errorf("mkdir %s: %w", confdir, err)
137 err = os.Chown(confdir, 0, wwwgid)
139 err = fmt.Errorf("chown 0:%d %s: %w", wwwgid, confdir, err)
142 f, err := os.OpenFile(conffile, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0644)
144 err = fmt.Errorf("open %s: %w", conffile, err)
147 tmpl, err := template.New("config").Parse(`Clusters:
152 "http://0.0.0.0:9000/": {}
153 ExternalURL: {{printf "%q" ( print "https://" .Domain ":4440/" ) }}
156 "http://0.0.0.0:9001/": {}
159 "http://0.0.0.0:8005/": {}
160 ExternalURL: {{printf "%q" ( print "wss://" .Domain ":4446/" ) }}
163 "http://0.0.0.0:9019/": {}
166 "http://0.0.0.0:9005/": {}
167 ExternalURL: {{printf "%q" ( print "https://" .Domain ":4445/" ) }}
170 "http://0.0.0.0:9006/": {}
173 "http://0.0.0.0:9007/": {}
174 ExternalURL: {{printf "%q" ( print "https://" .Domain ":4447/" ) }}
177 "http://0.0.0.0:9008/": {}
178 ExternalURL: {{printf "%q" ( print "https://" .Domain ":4448/" ) }}
181 "http://0.0.0.0:9009/": {}
182 ExternalURL: {{printf "%q" ( print "https://" .Domain ":4449/" ) }}
185 "http://0.0.0.0:9010/": {}
187 ExternalURL: {{printf "%q" ( print "https://" .Domain ":4459/composer" ) }}
190 "http://0.0.0.0:9002/": {}
191 ExternalURL: {{printf "%q" ( print "https://" .Domain ":4442/" ) }}
194 "http://0.0.0.0:9003/": {}
195 ExternalURL: {{printf "%q" ( print "https://" .Domain "/" ) }}
198 "http://0.0.0.0:9011/": {}
200 BlobSigningKey: {{printf "%q" ( .RandomHex 50 )}}
201 {{if eq .TLS "insecure"}}
202 TrustAllContent: true
205 DispatchPrivateKey: {{printf "%q" .GenerateSSHPrivateKey}}
209 ManagementToken: {{printf "%q" ( .RandomHex 50 )}}
215 password: {{printf "%q" .PostgreSQLPassword}}
216 SystemRootToken: {{printf "%q" ( .RandomHex 50 )}}
218 {{if eq .TLS "insecure"}}
220 {{else if eq .TLS "auto"}}
222 {{else if eq .TLS "acme"}}
223 Certificate: {{printf "%q" (print "/var/lib/acme/live/" .Domain "/cert")}}
224 Key: {{printf "%q" (print "/var/lib/acme/live/" .Domain "/privkey")}}
229 {{.ClusterID}}-nyw5e-000000000000000:
232 Root: /var/lib/arvados/keep
235 SecretKeyBase: {{printf "%q" ( .RandomHex 50 )}}
240 {{else if .LoginTest}}
246 Email: {{printf "%q" .AdminEmail}}
248 {{else if .LoginGoogle}}
252 ClientID: {{printf "%q" .LoginGoogleClientID}}
253 ClientSecret: {{printf "%q" .LoginGoogleClientSecret}}
256 AutoAdminUserWithEmail: {{printf "%q" .AdminEmail}}
261 err = tmpl.Execute(f, initcmd)
263 err = fmt.Errorf("%s: tmpl.Execute: %w", conffile, err)
268 err = fmt.Errorf("%s: close: %w", conffile, err)
271 fmt.Fprintln(stderr, "created", conffile)
273 ldr := config.NewLoader(nil, logger)
274 ldr.SkipLegacy = true
275 cfg, err := ldr.Load()
277 err = fmt.Errorf("%s: %w", conffile, err)
280 cluster, err := cfg.GetCluster("")
285 err = initcmd.createDB(ctx, cluster.PostgreSQL.Connection, stderr)
290 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")
291 cmd.Dir = "/var/lib/arvados/railsapi"
296 err = fmt.Errorf("rake db:setup failed: %w", err)
299 fmt.Fprintln(stderr, "initialized database")
302 fmt.Fprintln(stderr, "starting systemd service")
303 cmd := exec.CommandContext(ctx, "systemctl", "start", "arvados")
309 err = fmt.Errorf("%v: %w", cmd.Args, err)
313 fmt.Fprintln(stderr, "checking controller API endpoint")
314 u := url.URL(cluster.Services.Controller.ExternalURL)
315 conn := rpc.NewConn(cluster.ClusterID, &u, cluster.TLS.Insecure, rpc.PassthroughTokenProvider)
316 ctx := auth.NewContext(context.Background(), auth.NewCredentials(cluster.SystemRootToken))
317 _, err = conn.UserGetCurrent(ctx, arvados.GetOptions{})
319 err = fmt.Errorf("API request failed: %w", err)
324 fmt.Fprintln(stderr, "Log in to workbench2 at", cluster.Services.Workbench2.ExternalURL.String())
329 func (initcmd *initCommand) GenerateSSHPrivateKey() (string, error) {
330 privkey, err := rsa.GenerateKey(rand.Reader, 4096)
334 err = privkey.Validate()
338 return string(pem.EncodeToMemory(&pem.Block{
339 Type: "RSA PRIVATE KEY",
340 Bytes: x509.MarshalPKCS1PrivateKey(privkey),
344 func (initcmd *initCommand) RandomHex(chars int) string {
345 b := make([]byte, chars/2)
346 _, err := rand.Read(b)
350 return fmt.Sprintf("%x", b)
353 func (initcmd *initCommand) createDB(ctx context.Context, dbconn arvados.PostgreSQLConnection, stderr io.Writer) error {
354 for _, sql := range []string{
355 `CREATE USER ` + pq.QuoteIdentifier(dbconn["user"]) + ` WITH SUPERUSER ENCRYPTED PASSWORD ` + pq.QuoteLiteral(dbconn["password"]),
356 `CREATE DATABASE ` + pq.QuoteIdentifier(dbconn["dbname"]) + ` WITH TEMPLATE template0 ENCODING 'utf8'`,
357 `CREATE EXTENSION IF NOT EXISTS pg_trgm`,
359 cmd := exec.CommandContext(ctx, "sudo", "-u", "postgres", "psql", "-c", sql)
365 return fmt.Errorf("error setting up arvados user/database: %w", err)