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
40 func (initcmd *initCommand) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
41 logger := ctxlog.New(stderr, "text", "info")
42 ctx := ctxlog.Context(context.Background(), logger)
43 ctx, cancel := context.WithCancel(ctx)
49 logger.WithError(err).Info("exiting")
53 hostname, err := os.Hostname()
55 err = fmt.Errorf("Hostname(): %w", err)
59 flags := flag.NewFlagSet(prog, flag.ContinueOnError)
60 flags.SetOutput(stderr)
61 versionFlag := flags.Bool("version", false, "Write version information to stdout and exit 0")
62 flags.StringVar(&initcmd.ClusterID, "cluster-id", "", "cluster `id`, like x1234 for a dev cluster")
63 flags.StringVar(&initcmd.Domain, "domain", hostname, "cluster public DNS `name`, like x1234.arvadosapi.com")
64 flags.StringVar(&initcmd.Login, "login", "", "login `backend`: test, pam, or ''")
65 flags.StringVar(&initcmd.TLS, "tls", "none", "tls certificate `source`: acme, auto, insecure, or none")
66 if ok, code := cmd.ParseFlags(flags, prog, args, "", stderr); !ok {
68 } else if *versionFlag {
69 return cmd.Version.RunCommand(prog, args, stdin, stdout, stderr)
70 } else if !regexp.MustCompile(`^[a-z][a-z0-9]{4}`).MatchString(initcmd.ClusterID) {
71 err = fmt.Errorf("cluster ID %q is invalid; must be an ASCII letter followed by 4 alphanumerics (try -help)", initcmd.ClusterID)
75 wwwuser, err := user.Lookup("www-data")
77 err = fmt.Errorf("user.Lookup(%q): %w", "www-data", err)
80 wwwgid, err := strconv.Atoi(wwwuser.Gid)
84 initcmd.PostgreSQLPassword = initcmd.RandomHex(32)
86 err = os.Mkdir("/var/lib/arvados/keep", 0600)
87 if err != nil && !os.IsExist(err) {
88 err = fmt.Errorf("mkdir /var/lib/arvados/keep: %w", err)
91 fmt.Fprintln(stderr, "created /var/lib/arvados/keep")
93 err = os.Mkdir("/etc/arvados", 0750)
94 if err != nil && !os.IsExist(err) {
95 err = fmt.Errorf("mkdir /etc/arvados: %w", err)
98 err = os.Chown("/etc/arvados", 0, wwwgid)
99 f, err := os.OpenFile("/etc/arvados/config.yml", os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0644)
101 err = fmt.Errorf("open /etc/arvados/config.yml: %w", err)
104 tmpl, err := template.New("config").Parse(`Clusters:
109 "http://0.0.0.0:9000/": {}
110 ExternalURL: {{printf "%q" ( print "https://" .Domain ":4440/" ) }}
113 "http://0.0.0.0:9001/": {}
116 "http://0.0.0.0:8005/": {}
117 ExternalURL: {{printf "%q" ( print "wss://" .Domain ":4436/" ) }}
120 "http://0.0.0.0:9019/": {}
123 "http://0.0.0.0:9005/": {}
124 ExternalURL: {{printf "%q" ( print "https://" .Domain ":4445/" ) }}
127 "http://0.0.0.0:9006/": {}
130 "http://0.0.0.0:9007/": {}
131 ExternalURL: {{printf "%q" ( print "https://" .Domain ":4447/" ) }}
134 "http://0.0.0.0:9008/": {}
135 ExternalURL: {{printf "%q" ( print "https://" .Domain ":4448/" ) }}
138 "http://0.0.0.0:9009/": {}
139 ExternalURL: {{printf "%q" ( print "https://" .Domain ":4449/" ) }}
142 "http://0.0.0.0:9010/": {}
144 ExternalURL: {{printf "%q" ( print "https://" .Domain ":4459/composer" ) }}
147 "http://0.0.0.0:9002/": {}
148 ExternalURL: {{printf "%q" ( print "https://" .Domain ":4442/" ) }}
151 "http://0.0.0.0:9003/": {}
152 ExternalURL: {{printf "%q" ( print "https://" .Domain "/" ) }}
155 "http://0.0.0.0:9011/": {}
157 BlobSigningKey: {{printf "%q" ( .RandomHex 50 )}}
158 {{if eq .TLS "insecure"}}
159 TrustAllContent: true
162 DispatchPrivateKey: {{printf "%q" .GenerateSSHPrivateKey}}
166 ManagementToken: {{printf "%q" ( .RandomHex 50 )}}
169 dbname: arvados_production
172 password: {{printf "%q" .PostgreSQLPassword}}
173 SystemRootToken: {{printf "%q" ( .RandomHex 50 )}}
175 {{if eq .TLS "insecure"}}
177 {{else if eq .TLS "auto"}}
179 {{else if eq .TLS "acme"}}
180 Certificate: {{printf "%q" (print "/var/lib/acme/live/" .Domain "/cert")}}
181 Key: {{printf "%q" (print "/var/lib/acme/live/" .Domain "/privkey")}}
186 {{.ClusterID}}-nyw5e-000000000000000:
189 Root: /var/lib/arvados/keep
192 SecretKeyBase: {{printf "%q" ( .RandomHex 50 )}}
194 {{if eq .Login "pam"}}
197 {{else if eq .Login "test"}}
202 Email: admin@example.com
208 {{if eq .Login "test"}}
209 AutoAdminUserWithEmail: admin@example.com
217 err = tmpl.Execute(f, initcmd)
219 err = fmt.Errorf("/etc/arvados/config.yml: tmpl.Execute: %w", err)
224 err = fmt.Errorf("/etc/arvados/config.yml: close: %w", err)
227 fmt.Fprintln(stderr, "created /etc/arvados/config.yml")
229 ldr := config.NewLoader(nil, logger)
230 ldr.SkipLegacy = true
231 cfg, err := ldr.Load()
233 err = fmt.Errorf("/etc/arvados/config.yml: %w", err)
236 cluster, err := cfg.GetCluster("")
241 err = initcmd.createDB(ctx, cluster.PostgreSQL.Connection, stderr)
246 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")
247 cmd.Dir = "/var/lib/arvados/railsapi"
252 err = fmt.Errorf("rake db:setup: %w", err)
255 fmt.Fprintln(stderr, "initialized database")
260 func (initcmd *initCommand) GenerateSSHPrivateKey() (string, error) {
261 privkey, err := rsa.GenerateKey(rand.Reader, 4096)
265 err = privkey.Validate()
269 return string(pem.EncodeToMemory(&pem.Block{
270 Type: "RSA PRIVATE KEY",
271 Bytes: x509.MarshalPKCS1PrivateKey(privkey),
275 func (initcmd *initCommand) RandomHex(chars int) string {
276 b := make([]byte, chars/2)
277 _, err := rand.Read(b)
281 return fmt.Sprintf("%x", b)
284 func (initcmd *initCommand) createDB(ctx context.Context, dbconn arvados.PostgreSQLConnection, stderr io.Writer) error {
285 for _, sql := range []string{
286 `CREATE USER ` + pq.QuoteIdentifier(dbconn["user"]) + ` WITH SUPERUSER ENCRYPTED PASSWORD ` + pq.QuoteLiteral(dbconn["password"]),
287 `CREATE DATABASE ` + pq.QuoteIdentifier(dbconn["dbname"]) + ` WITH TEMPLATE template0 ENCODING 'utf8'`,
288 `CREATE EXTENSION IF NOT EXISTS pg_trgm`,
290 cmd := exec.CommandContext(ctx, "sudo", "-u", "postgres", "psql", "-c", sql)
295 return fmt.Errorf("error setting up arvados user/database: %w", err)