1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
23 "git.arvados.org/arvados.git/lib/cmd"
24 "git.arvados.org/arvados.git/lib/config"
25 "git.arvados.org/arvados.git/sdk/go/arvados"
26 "git.arvados.org/arvados.git/sdk/go/ctxlog"
30 var InitCommand cmd.Handler = &initCommand{}
32 type initCommand struct {
35 PostgreSQLPassword string
41 func (initcmd *initCommand) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
42 logger := ctxlog.New(stderr, "text", "info")
43 ctx := ctxlog.Context(context.Background(), logger)
44 ctx, cancel := context.WithCancel(ctx)
50 logger.WithError(err).Info("exiting")
54 hostname, err := os.Hostname()
56 err = fmt.Errorf("Hostname(): %w", err)
60 flags := flag.NewFlagSet(prog, flag.ContinueOnError)
61 flags.SetOutput(stderr)
62 versionFlag := flags.Bool("version", false, "Write version information to stdout and exit 0")
63 flags.StringVar(&initcmd.ClusterID, "cluster-id", "", "cluster `id`, like x1234 for a dev cluster")
64 flags.StringVar(&initcmd.Domain, "domain", hostname, "cluster public DNS `name`, like x1234.arvadosapi.com")
65 flags.StringVar(&initcmd.Login, "login", "", "login `backend`: test, pam, or ''")
66 flags.StringVar(&initcmd.TLS, "tls", "none", "tls certificate `source`: acme, auto, insecure, or none")
67 flags.BoolVar(&initcmd.Start, "start", true, "start systemd service after creating config")
68 if ok, code := cmd.ParseFlags(flags, prog, args, "", stderr); !ok {
70 } else if *versionFlag {
71 return cmd.Version.RunCommand(prog, args, stdin, stdout, stderr)
72 } else if !regexp.MustCompile(`^[a-z][a-z0-9]{4}`).MatchString(initcmd.ClusterID) {
73 err = fmt.Errorf("cluster ID %q is invalid; must be an ASCII letter followed by 4 alphanumerics (try -help)", initcmd.ClusterID)
77 confdir := "/etc/arvados"
78 conffile := confdir + "/config.yml"
79 if _, err = os.Stat(conffile); err == nil {
80 err = fmt.Errorf("config file %s already exists; delete it first if you really want to start over", conffile)
84 wwwuser, err := user.Lookup("www-data")
86 err = fmt.Errorf("user.Lookup(%q): %w", "www-data", err)
89 wwwgid, err := strconv.Atoi(wwwuser.Gid)
93 initcmd.PostgreSQLPassword = initcmd.RandomHex(32)
95 err = os.Mkdir("/var/lib/arvados/keep", 0600)
96 if err != nil && !os.IsExist(err) {
97 err = fmt.Errorf("mkdir /var/lib/arvados/keep: %w", err)
100 fmt.Fprintln(stderr, "created /var/lib/arvados/keep")
102 err = os.Mkdir(confdir, 0750)
103 if err != nil && !os.IsExist(err) {
104 err = fmt.Errorf("mkdir %s: %w", confdir, err)
107 err = os.Chown(confdir, 0, wwwgid)
109 err = fmt.Errorf("chown 0:%d %s: %w", wwwgid, confdir, err)
112 f, err := os.OpenFile(conffile, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0644)
114 err = fmt.Errorf("open %s: %w", conffile, err)
117 tmpl, err := template.New("config").Parse(`Clusters:
122 "http://0.0.0.0:9000/": {}
123 ExternalURL: {{printf "%q" ( print "https://" .Domain ":4440/" ) }}
126 "http://0.0.0.0:9001/": {}
129 "http://0.0.0.0:8005/": {}
130 ExternalURL: {{printf "%q" ( print "wss://" .Domain ":4436/" ) }}
133 "http://0.0.0.0:9019/": {}
136 "http://0.0.0.0:9005/": {}
137 ExternalURL: {{printf "%q" ( print "https://" .Domain ":4445/" ) }}
140 "http://0.0.0.0:9006/": {}
143 "http://0.0.0.0:9007/": {}
144 ExternalURL: {{printf "%q" ( print "https://" .Domain ":4447/" ) }}
147 "http://0.0.0.0:9008/": {}
148 ExternalURL: {{printf "%q" ( print "https://" .Domain ":4448/" ) }}
151 "http://0.0.0.0:9009/": {}
152 ExternalURL: {{printf "%q" ( print "https://" .Domain ":4449/" ) }}
155 "http://0.0.0.0:9010/": {}
157 ExternalURL: {{printf "%q" ( print "https://" .Domain ":4459/composer" ) }}
160 "http://0.0.0.0:9002/": {}
161 ExternalURL: {{printf "%q" ( print "https://" .Domain ":4442/" ) }}
164 "http://0.0.0.0:9003/": {}
165 ExternalURL: {{printf "%q" ( print "https://" .Domain "/" ) }}
168 "http://0.0.0.0:9011/": {}
170 BlobSigningKey: {{printf "%q" ( .RandomHex 50 )}}
171 {{if eq .TLS "insecure"}}
172 TrustAllContent: true
175 DispatchPrivateKey: {{printf "%q" .GenerateSSHPrivateKey}}
179 ManagementToken: {{printf "%q" ( .RandomHex 50 )}}
182 dbname: arvados_production
185 password: {{printf "%q" .PostgreSQLPassword}}
186 SystemRootToken: {{printf "%q" ( .RandomHex 50 )}}
188 {{if eq .TLS "insecure"}}
190 {{else if eq .TLS "auto"}}
192 {{else if eq .TLS "acme"}}
193 Certificate: {{printf "%q" (print "/var/lib/acme/live/" .Domain "/cert")}}
194 Key: {{printf "%q" (print "/var/lib/acme/live/" .Domain "/privkey")}}
199 {{.ClusterID}}-nyw5e-000000000000000:
202 Root: /var/lib/arvados/keep
205 SecretKeyBase: {{printf "%q" ( .RandomHex 50 )}}
207 {{if eq .Login "pam"}}
210 {{else if eq .Login "test"}}
215 Email: admin@example.com
221 {{if eq .Login "test"}}
222 AutoAdminUserWithEmail: admin@example.com
230 err = tmpl.Execute(f, initcmd)
232 err = fmt.Errorf("%s: tmpl.Execute: %w", conffile, err)
237 err = fmt.Errorf("%s: close: %w", conffile, err)
240 fmt.Fprintln(stderr, "created", conffile)
242 ldr := config.NewLoader(nil, logger)
243 ldr.SkipLegacy = true
244 cfg, err := ldr.Load()
246 err = fmt.Errorf("%s: %w", conffile, err)
249 cluster, err := cfg.GetCluster("")
254 err = initcmd.createDB(ctx, cluster.PostgreSQL.Connection, stderr)
259 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")
260 cmd.Dir = "/var/lib/arvados/railsapi"
265 err = fmt.Errorf("rake db:setup failed: %w", err)
268 fmt.Fprintln(stderr, "initialized database")
271 fmt.Fprintln(stderr, "starting systemd service")
272 cmd := exec.CommandContext(ctx, "systemctl", "start", "--no-block", "arvados")
278 err = fmt.Errorf("%v: %w", cmd.Args, err)
286 func (initcmd *initCommand) GenerateSSHPrivateKey() (string, error) {
287 privkey, err := rsa.GenerateKey(rand.Reader, 4096)
291 err = privkey.Validate()
295 return string(pem.EncodeToMemory(&pem.Block{
296 Type: "RSA PRIVATE KEY",
297 Bytes: x509.MarshalPKCS1PrivateKey(privkey),
301 func (initcmd *initCommand) RandomHex(chars int) string {
302 b := make([]byte, chars/2)
303 _, err := rand.Read(b)
307 return fmt.Sprintf("%x", b)
310 func (initcmd *initCommand) createDB(ctx context.Context, dbconn arvados.PostgreSQLConnection, stderr io.Writer) error {
311 for _, sql := range []string{
312 `CREATE USER ` + pq.QuoteIdentifier(dbconn["user"]) + ` WITH SUPERUSER ENCRYPTED PASSWORD ` + pq.QuoteLiteral(dbconn["password"]),
313 `CREATE DATABASE ` + pq.QuoteIdentifier(dbconn["dbname"]) + ` WITH TEMPLATE template0 ENCODING 'utf8'`,
314 `CREATE EXTENSION IF NOT EXISTS pg_trgm`,
316 cmd := exec.CommandContext(ctx, "sudo", "-u", "postgres", "psql", "-c", sql)
321 return fmt.Errorf("error setting up arvados user/database: %w", err)