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
38 func (initcmd *initCommand) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
39 logger := ctxlog.New(stderr, "text", "info")
40 ctx := ctxlog.Context(context.Background(), logger)
41 ctx, cancel := context.WithCancel(ctx)
47 logger.WithError(err).Info("exiting")
51 hostname, err := os.Hostname()
53 err = fmt.Errorf("Hostname(): %w", err)
57 flags := flag.NewFlagSet(prog, flag.ContinueOnError)
58 flags.SetOutput(stderr)
59 versionFlag := flags.Bool("version", false, "Write version information to stdout and exit 0")
60 flags.StringVar(&initcmd.ClusterID, "cluster-id", "", "cluster `id`, like x1234 for a dev cluster")
61 flags.StringVar(&initcmd.Domain, "domain", hostname, "cluster public DNS `name`, like x1234.arvadosapi.com")
62 err = flags.Parse(args)
63 if err == flag.ErrHelp {
66 } else if err != nil {
68 } else if *versionFlag {
69 return cmd.Version.RunCommand(prog, args, stdin, stdout, stderr)
70 } else if len(flags.Args()) > 0 {
71 err = fmt.Errorf("unrecognized command line arguments: %v", flags.Args())
73 } else if !regexp.MustCompile(`^[a-z][a-z0-9]{4}`).MatchString(initcmd.ClusterID) {
74 err = fmt.Errorf("cluster ID %q is invalid; must be an ASCII letter followed by 4 alphanumerics (try -help)", initcmd.ClusterID)
78 wwwuser, err := user.Lookup("www-data")
80 err = fmt.Errorf("user.Lookup(%q): %w", "www-data", err)
83 wwwgid, err := strconv.Atoi(wwwuser.Gid)
87 initcmd.PostgreSQLPassword = initcmd.RandomHex(32)
89 err = os.Mkdir("/var/lib/arvados/keep", 0600)
90 if err != nil && !os.IsExist(err) {
91 err = fmt.Errorf("mkdir /var/lib/arvados/keep: %w", err)
94 fmt.Fprintln(stderr, "created /var/lib/arvados/keep")
96 err = os.Mkdir("/etc/arvados", 0750)
97 if err != nil && !os.IsExist(err) {
98 err = fmt.Errorf("mkdir /etc/arvados: %w", err)
101 err = os.Chown("/etc/arvados", 0, wwwgid)
102 f, err := os.OpenFile("/etc/arvados/config.yml", os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0644)
104 err = fmt.Errorf("open /etc/arvados/config.yml: %w", err)
107 tmpl, err := template.New("config").Parse(`Clusters:
112 "http://0.0.0.0:8003/": {}
113 ExternalURL: {{printf "%q" ( print "https://" .Domain "/" ) }}
116 "http://0.0.0.0:8004/": {}
119 "http://0.0.0.0:8005/": {}
120 ExternalURL: {{printf "%q" ( print "wss://ws." .Domain "/" ) }}
123 "http://0.0.0.0:9005/": {}
126 "http://0.0.0.0:9001/": {}
127 ExternalURL: {{printf "%q" ( print "https://git." .Domain "/" ) }}
130 "http://0.0.0.0:9006/": {}
133 "http://0.0.0.0:25108/": {}
134 ExternalURL: {{printf "%q" ( print "https://keep." .Domain "/" ) }}
137 "http://0.0.0.0:9002/": {}
138 ExternalURL: {{printf "%q" ( print "https://*.collections." .Domain "/" ) }}
141 "http://0.0.0.0:8004/": {}
142 ExternalURL: {{printf "%q" ( print "https://download." .Domain "/" ) }}
145 "http://0.0.0.0:25107/": {}
147 ExternalURL: {{printf "%q" ( print "https://workbench." .Domain "/composer" ) }}
150 "http://0.0.0.0:8001/": {}
151 ExternalURL: {{printf "%q" ( print "https://workbench." .Domain "/" ) }}
154 # "http://0.0.0.0:8002/": {}
155 # ExternalURL: {{printf "%q" ( print "https://workbench2." .Domain "/" ) }}
158 "http://0.0.0.0:9007/": {}
160 BlobSigningKey: {{printf "%q" ( .RandomHex 50 )}}
162 DispatchPrivateKey: {{printf "%q" .GenerateSSHPrivateKey}}
163 ManagementToken: {{printf "%q" ( .RandomHex 50 )}}
166 dbname: arvados_production
169 password: {{printf "%q" .PostgreSQLPassword}}
170 SystemRootToken: {{printf "%q" ( .RandomHex 50 )}}
174 {{.ClusterID}}-nyw5e-000000000000000:
177 Root: /var/lib/arvados/keep
180 SecretKeyBase: {{printf "%q" ( .RandomHex 50 )}}
185 err = tmpl.Execute(f, initcmd)
187 err = fmt.Errorf("/etc/arvados/config.yml: tmpl.Execute: %w", err)
192 err = fmt.Errorf("/etc/arvados/config.yml: close: %w", err)
195 fmt.Fprintln(stderr, "created /etc/arvados/config.yml")
197 ldr := config.NewLoader(nil, logger)
198 ldr.SkipLegacy = true
199 cfg, err := ldr.Load()
201 err = fmt.Errorf("/etc/arvados/config.yml: %w", err)
204 cluster, err := cfg.GetCluster("")
209 err = initcmd.createDB(ctx, cluster.PostgreSQL.Connection, stderr)
214 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")
215 cmd.Dir = "/var/lib/arvados/railsapi"
220 err = fmt.Errorf("rake db:setup: %w", err)
223 fmt.Fprintln(stderr, "initialized database")
228 func (initcmd *initCommand) GenerateSSHPrivateKey() (string, error) {
229 privkey, err := rsa.GenerateKey(rand.Reader, 4096)
233 err = privkey.Validate()
237 return string(pem.EncodeToMemory(&pem.Block{
238 Type: "RSA PRIVATE KEY",
239 Bytes: x509.MarshalPKCS1PrivateKey(privkey),
243 func (initcmd *initCommand) RandomHex(chars int) string {
244 b := make([]byte, chars/2)
245 _, err := rand.Read(b)
249 return fmt.Sprintf("%x", b)
252 func (initcmd *initCommand) createDB(ctx context.Context, dbconn arvados.PostgreSQLConnection, stderr io.Writer) error {
253 for _, sql := range []string{
254 `CREATE USER ` + pq.QuoteIdentifier(dbconn["user"]) + ` WITH SUPERUSER ENCRYPTED PASSWORD ` + pq.QuoteLiteral(dbconn["password"]),
255 `CREATE DATABASE ` + pq.QuoteIdentifier(dbconn["dbname"]) + ` WITH TEMPLATE template0 ENCODING 'utf8'`,
256 `CREATE EXTENSION IF NOT EXISTS pg_trgm`,
258 cmd := exec.CommandContext(ctx, "sudo", "-u", "postgres", "psql", "-c", sql)
263 return fmt.Errorf("error setting up arvados user/database: %w", err)