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
50 func (initcmd *initCommand) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
51 logger := ctxlog.New(stderr, "text", "info")
52 ctx := ctxlog.Context(context.Background(), logger)
53 ctx, cancel := context.WithCancel(ctx)
59 logger.WithError(err).Info("exiting")
63 hostname, err := os.Hostname()
65 err = fmt.Errorf("Hostname(): %w", err)
69 flags := flag.NewFlagSet(prog, flag.ContinueOnError)
70 flags.SetOutput(stderr)
71 versionFlag := flags.Bool("version", false, "Write version information to stdout and exit 0")
72 flags.StringVar(&initcmd.ClusterID, "cluster-id", "", "cluster `id`, like x1234 for a dev cluster")
73 flags.StringVar(&initcmd.Domain, "domain", hostname, "cluster public DNS `name`, like x1234.arvadosapi.com")
74 flags.StringVar(&initcmd.Login, "login", "", "login `backend`: test, pam, 'google {client-id} {client-secret}', or ''")
75 flags.StringVar(&initcmd.AdminEmail, "admin-email", "", "give admin privileges to user with given `email`")
76 flags.StringVar(&initcmd.TLS, "tls", "none", "tls certificate `source`: acme, insecure, none, or /path/to/dir containing privkey and cert files")
77 flags.BoolVar(&initcmd.Start, "start", true, "start systemd service after creating config")
78 if ok, code := cmd.ParseFlags(flags, prog, args, "", stderr); !ok {
80 } else if *versionFlag {
81 return cmd.Version.RunCommand(prog, args, stdin, stdout, stderr)
82 } else if !regexp.MustCompile(`^[a-z][a-z0-9]{4}`).MatchString(initcmd.ClusterID) {
83 err = fmt.Errorf("cluster ID %q is invalid; must be an ASCII letter followed by 4 alphanumerics (try -help)", initcmd.ClusterID)
87 if fields := strings.Fields(initcmd.Login); len(fields) == 3 && fields[0] == "google" {
88 initcmd.LoginGoogle = true
89 initcmd.LoginGoogleClientID = fields[1]
90 initcmd.LoginGoogleClientSecret = fields[2]
91 } else if initcmd.Login == "test" {
92 initcmd.LoginTest = true
93 if initcmd.AdminEmail == "" {
94 initcmd.AdminEmail = "admin@example.com"
96 } else if initcmd.Login == "pam" {
97 initcmd.LoginPAM = true
98 } else if initcmd.Login == "" {
99 // none; login will show an error page
101 err = fmt.Errorf("invalid argument to -login: %q: should be 'test', 'pam', 'google {client-id} {client-secret}', or empty", initcmd.Login)
106 case "none", "acme", "insecure":
108 if !strings.HasPrefix(initcmd.TLS, "/") {
109 err = fmt.Errorf("invalid argument to -tls: %q; see %s -help", initcmd.TLS, prog)
112 initcmd.TLSDir = initcmd.TLS
115 confdir := "/etc/arvados"
116 conffile := confdir + "/config.yml"
117 if _, err = os.Stat(conffile); err == nil {
118 err = fmt.Errorf("config file %s already exists; delete it first if you really want to start over", conffile)
122 wwwuser, err := user.Lookup("www-data")
124 err = fmt.Errorf("user.Lookup(%q): %w", "www-data", err)
127 wwwgid, err := strconv.Atoi(wwwuser.Gid)
131 initcmd.PostgreSQLPassword = initcmd.RandomHex(32)
133 err = os.Mkdir("/var/lib/arvados/keep", 0600)
134 if err != nil && !os.IsExist(err) {
135 err = fmt.Errorf("mkdir /var/lib/arvados/keep: %w", err)
138 fmt.Fprintln(stderr, "created /var/lib/arvados/keep")
140 err = os.Mkdir(confdir, 0750)
141 if err != nil && !os.IsExist(err) {
142 err = fmt.Errorf("mkdir %s: %w", confdir, err)
145 err = os.Chown(confdir, 0, wwwgid)
147 err = fmt.Errorf("chown 0:%d %s: %w", wwwgid, confdir, err)
150 f, err := os.OpenFile(conffile, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0644)
152 err = fmt.Errorf("open %s: %w", conffile, err)
155 tmpl, err := template.New("config").Parse(`Clusters:
160 "http://0.0.0.0:9000/": {}
161 ExternalURL: {{printf "%q" ( print "https://" .Domain ":4440/" ) }}
164 "http://0.0.0.0:9001/": {}
167 "http://0.0.0.0:8005/": {}
168 ExternalURL: {{printf "%q" ( print "wss://" .Domain ":4446/" ) }}
171 "http://0.0.0.0:9019/": {}
174 "http://0.0.0.0:9005/": {}
175 ExternalURL: {{printf "%q" ( print "https://" .Domain ":4445/" ) }}
178 "http://0.0.0.0:9006/": {}
181 "http://0.0.0.0:9007/": {}
182 ExternalURL: {{printf "%q" ( print "https://" .Domain ":4447/" ) }}
185 "http://0.0.0.0:9008/": {}
186 ExternalURL: {{printf "%q" ( print "https://" .Domain ":4448/" ) }}
189 "http://0.0.0.0:9009/": {}
190 ExternalURL: {{printf "%q" ( print "https://" .Domain ":4449/" ) }}
193 "http://0.0.0.0:9010/": {}
195 ExternalURL: {{printf "%q" ( print "https://" .Domain ":4459/composer" ) }}
198 "http://0.0.0.0:9002/": {}
199 ExternalURL: {{printf "%q" ( print "https://" .Domain ":4442/" ) }}
202 "http://0.0.0.0:9003/": {}
203 ExternalURL: {{printf "%q" ( print "https://" .Domain "/" ) }}
206 "http://0.0.0.0:9011/": {}
208 BlobSigningKey: {{printf "%q" ( .RandomHex 50 )}}
209 {{if eq .TLS "insecure"}}
210 TrustAllContent: true
213 DispatchPrivateKey: {{printf "%q" .GenerateSSHPrivateKey}}
217 ManagementToken: {{printf "%q" ( .RandomHex 50 )}}
223 password: {{printf "%q" .PostgreSQLPassword}}
224 SystemRootToken: {{printf "%q" ( .RandomHex 50 )}}
226 {{if eq .TLS "insecure"}}
228 {{else if eq .TLS "acme"}}
231 {{else if ne .TLSDir ""}}
232 Certificate: {{printf "%q" (print .TLSDir "/cert")}}
233 Key: {{printf "%q" (print .TLSDir "/privkey")}}
238 {{.ClusterID}}-nyw5e-000000000000000:
241 Root: /var/lib/arvados/keep
244 SecretKeyBase: {{printf "%q" ( .RandomHex 50 )}}
249 {{else if .LoginTest}}
255 Email: {{printf "%q" .AdminEmail}}
257 {{else if .LoginGoogle}}
261 ClientID: {{printf "%q" .LoginGoogleClientID}}
262 ClientSecret: {{printf "%q" .LoginGoogleClientSecret}}
265 AutoAdminUserWithEmail: {{printf "%q" .AdminEmail}}
270 err = tmpl.Execute(f, initcmd)
272 err = fmt.Errorf("%s: tmpl.Execute: %w", conffile, err)
277 err = fmt.Errorf("%s: close: %w", conffile, err)
280 fmt.Fprintln(stderr, "created", conffile)
282 ldr := config.NewLoader(nil, logger)
283 ldr.SkipLegacy = true
284 cfg, err := ldr.Load()
286 err = fmt.Errorf("%s: %w", conffile, err)
289 cluster, err := cfg.GetCluster("")
294 err = initcmd.createDB(ctx, cluster.PostgreSQL.Connection, stderr)
299 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")
300 cmd.Dir = "/var/lib/arvados/railsapi"
305 err = fmt.Errorf("rake db:setup failed: %w", err)
308 fmt.Fprintln(stderr, "initialized database")
311 fmt.Fprintln(stderr, "starting systemd service")
312 cmd := exec.CommandContext(ctx, "systemctl", "start", "--no-block", "arvados")
318 err = fmt.Errorf("%v: %w", cmd.Args, err)
326 func (initcmd *initCommand) GenerateSSHPrivateKey() (string, error) {
327 privkey, err := rsa.GenerateKey(rand.Reader, 4096)
331 err = privkey.Validate()
335 return string(pem.EncodeToMemory(&pem.Block{
336 Type: "RSA PRIVATE KEY",
337 Bytes: x509.MarshalPKCS1PrivateKey(privkey),
341 func (initcmd *initCommand) RandomHex(chars int) string {
342 b := make([]byte, chars/2)
343 _, err := rand.Read(b)
347 return fmt.Sprintf("%x", b)
350 func (initcmd *initCommand) createDB(ctx context.Context, dbconn arvados.PostgreSQLConnection, stderr io.Writer) error {
351 for _, sql := range []string{
352 `CREATE USER ` + pq.QuoteIdentifier(dbconn["user"]) + ` WITH SUPERUSER ENCRYPTED PASSWORD ` + pq.QuoteLiteral(dbconn["password"]),
353 `CREATE DATABASE ` + pq.QuoteIdentifier(dbconn["dbname"]) + ` WITH TEMPLATE template0 ENCODING 'utf8'`,
354 `CREATE EXTENSION IF NOT EXISTS pg_trgm`,
356 cmd := exec.CommandContext(ctx, "sudo", "-u", "postgres", "psql", "-c", sql)
362 return fmt.Errorf("error setting up arvados user/database: %w", err)