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 wwwuser, err := user.Lookup("www-data")
79 err = fmt.Errorf("user.Lookup(%q): %w", "www-data", err)
82 wwwgid, err := strconv.Atoi(wwwuser.Gid)
86 initcmd.PostgreSQLPassword = initcmd.RandomHex(32)
88 err = os.Mkdir("/var/lib/arvados/keep", 0600)
89 if err != nil && !os.IsExist(err) {
90 err = fmt.Errorf("mkdir /var/lib/arvados/keep: %w", err)
93 fmt.Fprintln(stderr, "created /var/lib/arvados/keep")
95 err = os.Mkdir("/etc/arvados", 0750)
96 if err != nil && !os.IsExist(err) {
97 err = fmt.Errorf("mkdir /etc/arvados: %w", err)
100 err = os.Chown("/etc/arvados", 0, wwwgid)
101 f, err := os.OpenFile("/etc/arvados/config.yml", os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0644)
103 err = fmt.Errorf("open /etc/arvados/config.yml: %w", err)
106 tmpl, err := template.New("config").Parse(`Clusters:
111 "http://0.0.0.0:9000/": {}
112 ExternalURL: {{printf "%q" ( print "https://" .Domain ":4440/" ) }}
115 "http://0.0.0.0:9001/": {}
118 "http://0.0.0.0:8005/": {}
119 ExternalURL: {{printf "%q" ( print "wss://" .Domain ":4436/" ) }}
122 "http://0.0.0.0:9019/": {}
125 "http://0.0.0.0:9005/": {}
126 ExternalURL: {{printf "%q" ( print "https://" .Domain ":4445/" ) }}
129 "http://0.0.0.0:9006/": {}
132 "http://0.0.0.0:9007/": {}
133 ExternalURL: {{printf "%q" ( print "https://" .Domain ":4447/" ) }}
136 "http://0.0.0.0:9008/": {}
137 ExternalURL: {{printf "%q" ( print "https://" .Domain ":4448/" ) }}
140 "http://0.0.0.0:9009/": {}
141 ExternalURL: {{printf "%q" ( print "https://" .Domain ":4449/" ) }}
144 "http://0.0.0.0:9010/": {}
146 ExternalURL: {{printf "%q" ( print "https://" .Domain ":4459/composer" ) }}
149 "http://0.0.0.0:9002/": {}
150 ExternalURL: {{printf "%q" ( print "https://" .Domain ":4442/" ) }}
153 "http://0.0.0.0:9003/": {}
154 ExternalURL: {{printf "%q" ( print "https://" .Domain "/" ) }}
157 "http://0.0.0.0:9011/": {}
159 BlobSigningKey: {{printf "%q" ( .RandomHex 50 )}}
160 {{if eq .TLS "insecure"}}
161 TrustAllContent: true
164 DispatchPrivateKey: {{printf "%q" .GenerateSSHPrivateKey}}
168 ManagementToken: {{printf "%q" ( .RandomHex 50 )}}
171 dbname: arvados_production
174 password: {{printf "%q" .PostgreSQLPassword}}
175 SystemRootToken: {{printf "%q" ( .RandomHex 50 )}}
177 {{if eq .TLS "insecure"}}
179 {{else if eq .TLS "auto"}}
181 {{else if eq .TLS "acme"}}
182 Certificate: {{printf "%q" (print "/var/lib/acme/live/" .Domain "/cert")}}
183 Key: {{printf "%q" (print "/var/lib/acme/live/" .Domain "/privkey")}}
188 {{.ClusterID}}-nyw5e-000000000000000:
191 Root: /var/lib/arvados/keep
194 SecretKeyBase: {{printf "%q" ( .RandomHex 50 )}}
196 {{if eq .Login "pam"}}
199 {{else if eq .Login "test"}}
204 Email: admin@example.com
210 {{if eq .Login "test"}}
211 AutoAdminUserWithEmail: admin@example.com
219 err = tmpl.Execute(f, initcmd)
221 err = fmt.Errorf("/etc/arvados/config.yml: tmpl.Execute: %w", err)
226 err = fmt.Errorf("/etc/arvados/config.yml: close: %w", err)
229 fmt.Fprintln(stderr, "created /etc/arvados/config.yml")
231 ldr := config.NewLoader(nil, logger)
232 ldr.SkipLegacy = true
233 cfg, err := ldr.Load()
235 err = fmt.Errorf("/etc/arvados/config.yml: %w", err)
238 cluster, err := cfg.GetCluster("")
243 err = initcmd.createDB(ctx, cluster.PostgreSQL.Connection, stderr)
248 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")
249 cmd.Dir = "/var/lib/arvados/railsapi"
254 err = fmt.Errorf("rake db:setup: %w", err)
257 fmt.Fprintln(stderr, "initialized database")
260 fmt.Fprintln(stderr, "starting systemd service")
261 cmd := exec.CommandContext(ctx, "systemctl", "start", "--no-block", "arvados")
267 err = fmt.Errorf("%v: %w", cmd.Args, err)
275 func (initcmd *initCommand) GenerateSSHPrivateKey() (string, error) {
276 privkey, err := rsa.GenerateKey(rand.Reader, 4096)
280 err = privkey.Validate()
284 return string(pem.EncodeToMemory(&pem.Block{
285 Type: "RSA PRIVATE KEY",
286 Bytes: x509.MarshalPKCS1PrivateKey(privkey),
290 func (initcmd *initCommand) RandomHex(chars int) string {
291 b := make([]byte, chars/2)
292 _, err := rand.Read(b)
296 return fmt.Sprintf("%x", b)
299 func (initcmd *initCommand) createDB(ctx context.Context, dbconn arvados.PostgreSQLConnection, stderr io.Writer) error {
300 for _, sql := range []string{
301 `CREATE USER ` + pq.QuoteIdentifier(dbconn["user"]) + ` WITH SUPERUSER ENCRYPTED PASSWORD ` + pq.QuoteLiteral(dbconn["password"]),
302 `CREATE DATABASE ` + pq.QuoteIdentifier(dbconn["dbname"]) + ` WITH TEMPLATE template0 ENCODING 'utf8'`,
303 `CREATE EXTENSION IF NOT EXISTS pg_trgm`,
305 cmd := exec.CommandContext(ctx, "sudo", "-u", "postgres", "psql", "-c", sql)
310 return fmt.Errorf("error setting up arvados user/database: %w", err)