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
39 func (initcmd *initCommand) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
40 logger := ctxlog.New(stderr, "text", "info")
41 ctx := ctxlog.Context(context.Background(), logger)
42 ctx, cancel := context.WithCancel(ctx)
48 logger.WithError(err).Info("exiting")
52 hostname, err := os.Hostname()
54 err = fmt.Errorf("Hostname(): %w", err)
58 flags := flag.NewFlagSet(prog, flag.ContinueOnError)
59 flags.SetOutput(stderr)
60 versionFlag := flags.Bool("version", false, "Write version information to stdout and exit 0")
61 flags.StringVar(&initcmd.ClusterID, "cluster-id", "", "cluster `id`, like x1234 for a dev cluster")
62 flags.StringVar(&initcmd.Domain, "domain", hostname, "cluster public DNS `name`, like x1234.arvadosapi.com")
63 flags.StringVar(&initcmd.Login, "login", "", "login `backend`: test, pam, or ''")
64 if ok, code := cmd.ParseFlags(flags, prog, args, "", stderr); !ok {
66 } else if *versionFlag {
67 return cmd.Version.RunCommand(prog, args, stdin, stdout, stderr)
68 } else if !regexp.MustCompile(`^[a-z][a-z0-9]{4}`).MatchString(initcmd.ClusterID) {
69 err = fmt.Errorf("cluster ID %q is invalid; must be an ASCII letter followed by 4 alphanumerics (try -help)", initcmd.ClusterID)
73 wwwuser, err := user.Lookup("www-data")
75 err = fmt.Errorf("user.Lookup(%q): %w", "www-data", err)
78 wwwgid, err := strconv.Atoi(wwwuser.Gid)
82 initcmd.PostgreSQLPassword = initcmd.RandomHex(32)
84 err = os.Mkdir("/var/lib/arvados/keep", 0600)
85 if err != nil && !os.IsExist(err) {
86 err = fmt.Errorf("mkdir /var/lib/arvados/keep: %w", err)
89 fmt.Fprintln(stderr, "created /var/lib/arvados/keep")
91 err = os.Mkdir("/etc/arvados", 0750)
92 if err != nil && !os.IsExist(err) {
93 err = fmt.Errorf("mkdir /etc/arvados: %w", err)
96 err = os.Chown("/etc/arvados", 0, wwwgid)
97 f, err := os.OpenFile("/etc/arvados/config.yml", os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0644)
99 err = fmt.Errorf("open /etc/arvados/config.yml: %w", err)
102 tmpl, err := template.New("config").Parse(`Clusters:
107 "http://0.0.0.0:8003/": {}
108 ExternalURL: {{printf "%q" ( print "https://" .Domain ":4430/" ) }}
111 "http://0.0.0.0:8004/": {}
114 "http://0.0.0.0:8005/": {}
115 ExternalURL: {{printf "%q" ( print "wss://" .Domain ":4435/websocket" ) }}
118 "http://0.0.0.0:9005/": {}
121 "http://0.0.0.0:9001/": {}
122 ExternalURL: {{printf "%q" ( print "https://" .Domain ":4436/" ) }}
125 "http://0.0.0.0:9006/": {}
128 "http://0.0.0.0:25108/": {}
129 ExternalURL: {{printf "%q" ( print "https://" .Domain ":4437/" ) }}
132 "http://0.0.0.0:9002/": {}
133 ExternalURL: {{printf "%q" ( print "https://" .Domain ":4438/" ) }}
136 "http://0.0.0.0:8004/": {}
137 ExternalURL: {{printf "%q" ( print "https://" .Domain ":4439/" ) }}
140 "http://0.0.0.0:25107/": {}
142 ExternalURL: {{printf "%q" ( print "https://" .Domain ":4440/composer" ) }}
145 "http://0.0.0.0:8001/": {}
146 ExternalURL: {{printf "%q" ( print "https://" .Domain ":4441/" ) }}
148 ExternalURL: {{printf "%q" ( print "https://" .Domain ":4442/" ) }}
151 "http://0.0.0.0:9007/": {}
153 BlobSigningKey: {{printf "%q" ( .RandomHex 50 )}}
155 DispatchPrivateKey: {{printf "%q" .GenerateSSHPrivateKey}}
156 ManagementToken: {{printf "%q" ( .RandomHex 50 )}}
159 dbname: arvados_production
162 password: {{printf "%q" .PostgreSQLPassword}}
163 SystemRootToken: {{printf "%q" ( .RandomHex 50 )}}
167 {{.ClusterID}}-nyw5e-000000000000000:
170 Root: /var/lib/arvados/keep
173 SecretKeyBase: {{printf "%q" ( .RandomHex 50 )}}
175 {{if eq .Login "pam"}}
178 {{else if eq .Login "test"}}
183 Email: admin@example.com
189 {{if eq .Login "test"}}
190 AutoAdminUserWithEmail: admin@example.com
198 err = tmpl.Execute(f, initcmd)
200 err = fmt.Errorf("/etc/arvados/config.yml: tmpl.Execute: %w", err)
205 err = fmt.Errorf("/etc/arvados/config.yml: close: %w", err)
208 fmt.Fprintln(stderr, "created /etc/arvados/config.yml")
210 ldr := config.NewLoader(nil, logger)
211 ldr.SkipLegacy = true
212 cfg, err := ldr.Load()
214 err = fmt.Errorf("/etc/arvados/config.yml: %w", err)
217 cluster, err := cfg.GetCluster("")
222 err = initcmd.createDB(ctx, cluster.PostgreSQL.Connection, stderr)
227 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")
228 cmd.Dir = "/var/lib/arvados/railsapi"
233 err = fmt.Errorf("rake db:setup: %w", err)
236 fmt.Fprintln(stderr, "initialized database")
241 func (initcmd *initCommand) GenerateSSHPrivateKey() (string, error) {
242 privkey, err := rsa.GenerateKey(rand.Reader, 4096)
246 err = privkey.Validate()
250 return string(pem.EncodeToMemory(&pem.Block{
251 Type: "RSA PRIVATE KEY",
252 Bytes: x509.MarshalPKCS1PrivateKey(privkey),
256 func (initcmd *initCommand) RandomHex(chars int) string {
257 b := make([]byte, chars/2)
258 _, err := rand.Read(b)
262 return fmt.Sprintf("%x", b)
265 func (initcmd *initCommand) createDB(ctx context.Context, dbconn arvados.PostgreSQLConnection, stderr io.Writer) error {
266 for _, sql := range []string{
267 `CREATE USER ` + pq.QuoteIdentifier(dbconn["user"]) + ` WITH SUPERUSER ENCRYPTED PASSWORD ` + pq.QuoteLiteral(dbconn["password"]),
268 `CREATE DATABASE ` + pq.QuoteIdentifier(dbconn["dbname"]) + ` WITH TEMPLATE template0 ENCODING 'utf8'`,
269 `CREATE EXTENSION IF NOT EXISTS pg_trgm`,
271 cmd := exec.CommandContext(ctx, "sudo", "-u", "postgres", "psql", "-c", sql)
276 return fmt.Errorf("error setting up arvados user/database: %w", err)