Fix 2.4.1 release date refs #19017
[arvados.git] / lib / install / init.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package install
6
7 import (
8         "context"
9         "crypto/rand"
10         "crypto/rsa"
11         "crypto/x509"
12         "encoding/pem"
13         "flag"
14         "fmt"
15         "io"
16         "os"
17         "os/exec"
18         "os/user"
19         "regexp"
20         "strconv"
21         "text/template"
22
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"
27         "github.com/lib/pq"
28 )
29
30 var InitCommand cmd.Handler = &initCommand{}
31
32 type initCommand struct {
33         ClusterID          string
34         Domain             string
35         PostgreSQLPassword string
36         Login              string
37         Insecure           bool
38 }
39
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)
44         defer cancel()
45
46         var err error
47         defer func() {
48                 if err != nil {
49                         logger.WithError(err).Info("exiting")
50                 }
51         }()
52
53         hostname, err := os.Hostname()
54         if err != nil {
55                 err = fmt.Errorf("Hostname(): %w", err)
56                 return 1
57         }
58
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.BoolVar(&initcmd.Insecure, "insecure", false, "accept invalid TLS certificates and configure TrustAllContent (do not use in production!)")
66         if ok, code := cmd.ParseFlags(flags, prog, args, "", stderr); !ok {
67                 return code
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)
72                 return 1
73         }
74
75         wwwuser, err := user.Lookup("www-data")
76         if err != nil {
77                 err = fmt.Errorf("user.Lookup(%q): %w", "www-data", err)
78                 return 1
79         }
80         wwwgid, err := strconv.Atoi(wwwuser.Gid)
81         if err != nil {
82                 return 1
83         }
84         initcmd.PostgreSQLPassword = initcmd.RandomHex(32)
85
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)
89                 return 1
90         }
91         fmt.Fprintln(stderr, "created /var/lib/arvados/keep")
92
93         err = os.Mkdir("/etc/arvados", 0750)
94         if err != nil && !os.IsExist(err) {
95                 err = fmt.Errorf("mkdir /etc/arvados: %w", err)
96                 return 1
97         }
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)
100         if err != nil {
101                 err = fmt.Errorf("open /etc/arvados/config.yml: %w", err)
102                 return 1
103         }
104         tmpl, err := template.New("config").Parse(`Clusters:
105   {{.ClusterID}}:
106     Services:
107       Controller:
108         InternalURLs:
109           "http://0.0.0.0:9000/": {}
110         ExternalURL: {{printf "%q" ( print "https://" .Domain ":4440/" ) }}
111       RailsAPI:
112         InternalURLs:
113           "http://0.0.0.0:9001/": {}
114       Websocket:
115         InternalURLs:
116           "http://0.0.0.0:9004/": {}
117         ExternalURL: {{printf "%q" ( print "wss://" .Domain ":4444/websocket" ) }}
118       Keepbalance:
119         InternalURLs:
120           "http://0.0.0.0:9019/": {}
121       GitHTTP:
122         InternalURLs:
123           "http://0.0.0.0:9005/": {}
124         ExternalURL: {{printf "%q" ( print "https://" .Domain ":4445/" ) }}
125       DispatchCloud:
126         InternalURLs:
127           "http://0.0.0.0:9006/": {}
128       Keepproxy:
129         InternalURLs:
130           "http://0.0.0.0:9007/": {}
131         ExternalURL: {{printf "%q" ( print "https://" .Domain ":4447/" ) }}
132       WebDAV:
133         InternalURLs:
134           "http://0.0.0.0:9008/": {}
135         ExternalURL: {{printf "%q" ( print "https://" .Domain ":4448/" ) }}
136       WebDAVDownload:
137         InternalURLs:
138           "http://0.0.0.0:9009/": {}
139         ExternalURL: {{printf "%q" ( print "https://" .Domain ":4449/" ) }}
140       Keepstore:
141         InternalURLs:
142           "http://0.0.0.0:9010/": {}
143       Composer:
144         ExternalURL: {{printf "%q" ( print "https://" .Domain ":4459/composer" ) }}
145       Workbench1:
146         InternalURLs:
147           "http://0.0.0.0:9002/": {}
148         ExternalURL: {{printf "%q" ( print "https://" .Domain ":4442/" ) }}
149       Workbench2:
150         InternalURLs:
151           "http://0.0.0.0:9003/": {}
152         ExternalURL: {{printf "%q" ( print "https://" .Domain "/" ) }}
153       Health:
154         InternalURLs:
155           "http://0.0.0.0:9011/": {}
156     Collections:
157       BlobSigningKey: {{printf "%q" ( .RandomHex 50 )}}
158       {{if .Insecure}}
159       TrustAllContent: true
160       {{end}}
161     Containers:
162       DispatchPrivateKey: {{printf "%q" .GenerateSSHPrivateKey}}
163     ManagementToken: {{printf "%q" ( .RandomHex 50 )}}
164     PostgreSQL:
165       Connection:
166         dbname: arvados_production
167         host: localhost
168         user: arvados
169         password: {{printf "%q" .PostgreSQLPassword}}
170     SystemRootToken: {{printf "%q" ( .RandomHex 50 )}}
171     {{if .Insecure}}
172     TLS:
173       Insecure: true
174     {{end}}
175     Volumes:
176       {{.ClusterID}}-nyw5e-000000000000000:
177         Driver: Directory
178         DriverParameters:
179           Root: /var/lib/arvados/keep
180         Replication: 2
181     Workbench:
182       SecretKeyBase: {{printf "%q" ( .RandomHex 50 )}}
183     Login:
184       {{if eq .Login "pam"}}
185       PAM:
186         Enable: true
187       {{else if eq .Login "test"}}
188       Test:
189         Enable: true
190         Users:
191           admin:
192             Email: admin@example.com
193             Password: admin
194       {{else}}
195       {}
196       {{end}}
197     Users:
198       {{if eq .Login "test"}}
199       AutoAdminUserWithEmail: admin@example.com
200       {{else}}
201       {}
202       {{end}}
203 `)
204         if err != nil {
205                 return 1
206         }
207         err = tmpl.Execute(f, initcmd)
208         if err != nil {
209                 err = fmt.Errorf("/etc/arvados/config.yml: tmpl.Execute: %w", err)
210                 return 1
211         }
212         err = f.Close()
213         if err != nil {
214                 err = fmt.Errorf("/etc/arvados/config.yml: close: %w", err)
215                 return 1
216         }
217         fmt.Fprintln(stderr, "created /etc/arvados/config.yml")
218
219         ldr := config.NewLoader(nil, logger)
220         ldr.SkipLegacy = true
221         cfg, err := ldr.Load()
222         if err != nil {
223                 err = fmt.Errorf("/etc/arvados/config.yml: %w", err)
224                 return 1
225         }
226         cluster, err := cfg.GetCluster("")
227         if err != nil {
228                 return 1
229         }
230
231         err = initcmd.createDB(ctx, cluster.PostgreSQL.Connection, stderr)
232         if err != nil {
233                 return 1
234         }
235
236         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")
237         cmd.Dir = "/var/lib/arvados/railsapi"
238         cmd.Stdout = stderr
239         cmd.Stderr = stderr
240         err = cmd.Run()
241         if err != nil {
242                 err = fmt.Errorf("rake db:setup: %w", err)
243                 return 1
244         }
245         fmt.Fprintln(stderr, "initialized database")
246
247         return 0
248 }
249
250 func (initcmd *initCommand) GenerateSSHPrivateKey() (string, error) {
251         privkey, err := rsa.GenerateKey(rand.Reader, 4096)
252         if err != nil {
253                 return "", err
254         }
255         err = privkey.Validate()
256         if err != nil {
257                 return "", err
258         }
259         return string(pem.EncodeToMemory(&pem.Block{
260                 Type:  "RSA PRIVATE KEY",
261                 Bytes: x509.MarshalPKCS1PrivateKey(privkey),
262         })), nil
263 }
264
265 func (initcmd *initCommand) RandomHex(chars int) string {
266         b := make([]byte, chars/2)
267         _, err := rand.Read(b)
268         if err != nil {
269                 panic(err)
270         }
271         return fmt.Sprintf("%x", b)
272 }
273
274 func (initcmd *initCommand) createDB(ctx context.Context, dbconn arvados.PostgreSQLConnection, stderr io.Writer) error {
275         for _, sql := range []string{
276                 `CREATE USER ` + pq.QuoteIdentifier(dbconn["user"]) + ` WITH SUPERUSER ENCRYPTED PASSWORD ` + pq.QuoteLiteral(dbconn["password"]),
277                 `CREATE DATABASE ` + pq.QuoteIdentifier(dbconn["dbname"]) + ` WITH TEMPLATE template0 ENCODING 'utf8'`,
278                 `CREATE EXTENSION IF NOT EXISTS pg_trgm`,
279         } {
280                 cmd := exec.CommandContext(ctx, "sudo", "-u", "postgres", "psql", "-c", sql)
281                 cmd.Stdout = stderr
282                 cmd.Stderr = stderr
283                 err := cmd.Run()
284                 if err != nil {
285                         return fmt.Errorf("error setting up arvados user/database: %w", err)
286                 }
287         }
288         return nil
289 }