1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
24 "git.arvados.org/arvados.git/lib/cmd"
25 "git.arvados.org/arvados.git/lib/config"
26 "git.arvados.org/arvados.git/sdk/go/arvados"
27 "git.arvados.org/arvados.git/sdk/go/ctxlog"
31 var InitCommand cmd.Handler = &initCommand{}
33 type initCommand struct {
36 PostgreSQLPassword string
45 LoginGoogleClientID string
46 LoginGoogleClientSecret string
49 func (initcmd *initCommand) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
50 logger := ctxlog.New(stderr, "text", "info")
51 ctx := ctxlog.Context(context.Background(), logger)
52 ctx, cancel := context.WithCancel(ctx)
58 logger.WithError(err).Info("exiting")
62 hostname, err := os.Hostname()
64 err = fmt.Errorf("Hostname(): %w", err)
68 flags := flag.NewFlagSet(prog, flag.ContinueOnError)
69 flags.SetOutput(stderr)
70 versionFlag := flags.Bool("version", false, "Write version information to stdout and exit 0")
71 flags.StringVar(&initcmd.ClusterID, "cluster-id", "", "cluster `id`, like x1234 for a dev cluster")
72 flags.StringVar(&initcmd.Domain, "domain", hostname, "cluster public DNS `name`, like x1234.arvadosapi.com")
73 flags.StringVar(&initcmd.Login, "login", "", "login `backend`: test, pam, 'google {client-id} {client-secret}', or ''")
74 flags.StringVar(&initcmd.AdminEmail, "admin-email", "", "give admin privileges to user with given `email`")
75 flags.StringVar(&initcmd.TLS, "tls", "none", "tls certificate `source`: acme, auto, insecure, or none")
76 flags.BoolVar(&initcmd.Start, "start", true, "start systemd service after creating config")
77 if ok, code := cmd.ParseFlags(flags, prog, args, "", stderr); !ok {
79 } else if *versionFlag {
80 return cmd.Version.RunCommand(prog, args, stdin, stdout, stderr)
81 } else if !regexp.MustCompile(`^[a-z][a-z0-9]{4}`).MatchString(initcmd.ClusterID) {
82 err = fmt.Errorf("cluster ID %q is invalid; must be an ASCII letter followed by 4 alphanumerics (try -help)", initcmd.ClusterID)
86 if fields := strings.Fields(initcmd.Login); len(fields) == 3 && fields[0] == "google" {
87 initcmd.LoginGoogle = true
88 initcmd.LoginGoogleClientID = fields[1]
89 initcmd.LoginGoogleClientSecret = fields[2]
90 } else if initcmd.Login == "test" {
91 initcmd.LoginTest = true
92 if initcmd.AdminEmail == "" {
93 initcmd.AdminEmail = "admin@example.com"
95 } else if initcmd.Login == "pam" {
96 initcmd.LoginPAM = true
97 } else if initcmd.Login == "" {
98 // none; login will show an error page
100 err = fmt.Errorf("invalid argument to -login: %q: should be 'test', 'pam', 'google {client-id} {client-secret}', or empty")
104 confdir := "/etc/arvados"
105 conffile := confdir + "/config.yml"
106 if _, err = os.Stat(conffile); err == nil {
107 err = fmt.Errorf("config file %s already exists; delete it first if you really want to start over", conffile)
111 wwwuser, err := user.Lookup("www-data")
113 err = fmt.Errorf("user.Lookup(%q): %w", "www-data", err)
116 wwwgid, err := strconv.Atoi(wwwuser.Gid)
120 initcmd.PostgreSQLPassword = initcmd.RandomHex(32)
122 err = os.Mkdir("/var/lib/arvados/keep", 0600)
123 if err != nil && !os.IsExist(err) {
124 err = fmt.Errorf("mkdir /var/lib/arvados/keep: %w", err)
127 fmt.Fprintln(stderr, "created /var/lib/arvados/keep")
129 err = os.Mkdir(confdir, 0750)
130 if err != nil && !os.IsExist(err) {
131 err = fmt.Errorf("mkdir %s: %w", confdir, err)
134 err = os.Chown(confdir, 0, wwwgid)
136 err = fmt.Errorf("chown 0:%d %s: %w", wwwgid, confdir, err)
139 f, err := os.OpenFile(conffile, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0644)
141 err = fmt.Errorf("open %s: %w", conffile, err)
144 tmpl, err := template.New("config").Parse(`Clusters:
149 "http://0.0.0.0:9000/": {}
150 ExternalURL: {{printf "%q" ( print "https://" .Domain ":4440/" ) }}
153 "http://0.0.0.0:9001/": {}
156 "http://0.0.0.0:8005/": {}
157 ExternalURL: {{printf "%q" ( print "wss://" .Domain ":4436/" ) }}
160 "http://0.0.0.0:9019/": {}
163 "http://0.0.0.0:9005/": {}
164 ExternalURL: {{printf "%q" ( print "https://" .Domain ":4445/" ) }}
167 "http://0.0.0.0:9006/": {}
170 "http://0.0.0.0:9007/": {}
171 ExternalURL: {{printf "%q" ( print "https://" .Domain ":4447/" ) }}
174 "http://0.0.0.0:9008/": {}
175 ExternalURL: {{printf "%q" ( print "https://" .Domain ":4448/" ) }}
178 "http://0.0.0.0:9009/": {}
179 ExternalURL: {{printf "%q" ( print "https://" .Domain ":4449/" ) }}
182 "http://0.0.0.0:9010/": {}
184 ExternalURL: {{printf "%q" ( print "https://" .Domain ":4459/composer" ) }}
187 "http://0.0.0.0:9002/": {}
188 ExternalURL: {{printf "%q" ( print "https://" .Domain ":4442/" ) }}
191 "http://0.0.0.0:9003/": {}
192 ExternalURL: {{printf "%q" ( print "https://" .Domain "/" ) }}
195 "http://0.0.0.0:9011/": {}
197 BlobSigningKey: {{printf "%q" ( .RandomHex 50 )}}
198 {{if eq .TLS "insecure"}}
199 TrustAllContent: true
202 DispatchPrivateKey: {{printf "%q" .GenerateSSHPrivateKey}}
206 ManagementToken: {{printf "%q" ( .RandomHex 50 )}}
212 password: {{printf "%q" .PostgreSQLPassword}}
213 SystemRootToken: {{printf "%q" ( .RandomHex 50 )}}
215 {{if eq .TLS "insecure"}}
217 {{else if eq .TLS "auto"}}
219 {{else if eq .TLS "acme"}}
220 Certificate: {{printf "%q" (print "/var/lib/acme/live/" .Domain "/cert")}}
221 Key: {{printf "%q" (print "/var/lib/acme/live/" .Domain "/privkey")}}
226 {{.ClusterID}}-nyw5e-000000000000000:
229 Root: /var/lib/arvados/keep
232 SecretKeyBase: {{printf "%q" ( .RandomHex 50 )}}
237 {{else if .LoginTest}}
243 Email: {{printf "%q" .AdminEmail}}
245 {{else if .LoginGoogle}}
249 ClientID: {{printf "%q" .LoginGoogleClientID}}
250 ClientSecret: {{printf "%q" .LoginGoogleClientSecret}}
253 AutoAdminUserWithEmail: {{printf "%q" .AdminEmail}}
258 err = tmpl.Execute(f, initcmd)
260 err = fmt.Errorf("%s: tmpl.Execute: %w", conffile, err)
265 err = fmt.Errorf("%s: close: %w", conffile, err)
268 fmt.Fprintln(stderr, "created", conffile)
270 ldr := config.NewLoader(nil, logger)
271 ldr.SkipLegacy = true
272 cfg, err := ldr.Load()
274 err = fmt.Errorf("%s: %w", conffile, err)
277 cluster, err := cfg.GetCluster("")
282 err = initcmd.createDB(ctx, cluster.PostgreSQL.Connection, stderr)
287 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")
288 cmd.Dir = "/var/lib/arvados/railsapi"
293 err = fmt.Errorf("rake db:setup failed: %w", err)
296 fmt.Fprintln(stderr, "initialized database")
299 fmt.Fprintln(stderr, "starting systemd service")
300 cmd := exec.CommandContext(ctx, "systemctl", "start", "--no-block", "arvados")
306 err = fmt.Errorf("%v: %w", cmd.Args, err)
314 func (initcmd *initCommand) GenerateSSHPrivateKey() (string, error) {
315 privkey, err := rsa.GenerateKey(rand.Reader, 4096)
319 err = privkey.Validate()
323 return string(pem.EncodeToMemory(&pem.Block{
324 Type: "RSA PRIVATE KEY",
325 Bytes: x509.MarshalPKCS1PrivateKey(privkey),
329 func (initcmd *initCommand) RandomHex(chars int) string {
330 b := make([]byte, chars/2)
331 _, err := rand.Read(b)
335 return fmt.Sprintf("%x", b)
338 func (initcmd *initCommand) createDB(ctx context.Context, dbconn arvados.PostgreSQLConnection, stderr io.Writer) error {
339 for _, sql := range []string{
340 `CREATE USER ` + pq.QuoteIdentifier(dbconn["user"]) + ` WITH SUPERUSER ENCRYPTED PASSWORD ` + pq.QuoteLiteral(dbconn["password"]),
341 `CREATE DATABASE ` + pq.QuoteIdentifier(dbconn["dbname"]) + ` WITH TEMPLATE template0 ENCODING 'utf8'`,
342 `CREATE EXTENSION IF NOT EXISTS pg_trgm`,
344 cmd := exec.CommandContext(ctx, "sudo", "-u", "postgres", "psql", "-c", sql)
350 return fmt.Errorf("error setting up arvados user/database: %w", err)