19175: Merge branch 'main' into 19175-doc-refactor-multi-host-installation
[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       CloudVMs:
164         Enable: true
165         Driver: loopback
166     ManagementToken: {{printf "%q" ( .RandomHex 50 )}}
167     PostgreSQL:
168       Connection:
169         dbname: arvados_production
170         host: localhost
171         user: arvados
172         password: {{printf "%q" .PostgreSQLPassword}}
173     SystemRootToken: {{printf "%q" ( .RandomHex 50 )}}
174     {{if .Insecure}}
175     TLS:
176       Insecure: true
177     {{end}}
178     Volumes:
179       {{.ClusterID}}-nyw5e-000000000000000:
180         Driver: Directory
181         DriverParameters:
182           Root: /var/lib/arvados/keep
183         Replication: 2
184     Workbench:
185       SecretKeyBase: {{printf "%q" ( .RandomHex 50 )}}
186     Login:
187       {{if eq .Login "pam"}}
188       PAM:
189         Enable: true
190       {{else if eq .Login "test"}}
191       Test:
192         Enable: true
193         Users:
194           admin:
195             Email: admin@example.com
196             Password: admin
197       {{else}}
198       {}
199       {{end}}
200     Users:
201       {{if eq .Login "test"}}
202       AutoAdminUserWithEmail: admin@example.com
203       {{else}}
204       {}
205       {{end}}
206 `)
207         if err != nil {
208                 return 1
209         }
210         err = tmpl.Execute(f, initcmd)
211         if err != nil {
212                 err = fmt.Errorf("/etc/arvados/config.yml: tmpl.Execute: %w", err)
213                 return 1
214         }
215         err = f.Close()
216         if err != nil {
217                 err = fmt.Errorf("/etc/arvados/config.yml: close: %w", err)
218                 return 1
219         }
220         fmt.Fprintln(stderr, "created /etc/arvados/config.yml")
221
222         ldr := config.NewLoader(nil, logger)
223         ldr.SkipLegacy = true
224         cfg, err := ldr.Load()
225         if err != nil {
226                 err = fmt.Errorf("/etc/arvados/config.yml: %w", err)
227                 return 1
228         }
229         cluster, err := cfg.GetCluster("")
230         if err != nil {
231                 return 1
232         }
233
234         err = initcmd.createDB(ctx, cluster.PostgreSQL.Connection, stderr)
235         if err != nil {
236                 return 1
237         }
238
239         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")
240         cmd.Dir = "/var/lib/arvados/railsapi"
241         cmd.Stdout = stderr
242         cmd.Stderr = stderr
243         err = cmd.Run()
244         if err != nil {
245                 err = fmt.Errorf("rake db:setup: %w", err)
246                 return 1
247         }
248         fmt.Fprintln(stderr, "initialized database")
249
250         return 0
251 }
252
253 func (initcmd *initCommand) GenerateSSHPrivateKey() (string, error) {
254         privkey, err := rsa.GenerateKey(rand.Reader, 4096)
255         if err != nil {
256                 return "", err
257         }
258         err = privkey.Validate()
259         if err != nil {
260                 return "", err
261         }
262         return string(pem.EncodeToMemory(&pem.Block{
263                 Type:  "RSA PRIVATE KEY",
264                 Bytes: x509.MarshalPKCS1PrivateKey(privkey),
265         })), nil
266 }
267
268 func (initcmd *initCommand) RandomHex(chars int) string {
269         b := make([]byte, chars/2)
270         _, err := rand.Read(b)
271         if err != nil {
272                 panic(err)
273         }
274         return fmt.Sprintf("%x", b)
275 }
276
277 func (initcmd *initCommand) createDB(ctx context.Context, dbconn arvados.PostgreSQLConnection, stderr io.Writer) error {
278         for _, sql := range []string{
279                 `CREATE USER ` + pq.QuoteIdentifier(dbconn["user"]) + ` WITH SUPERUSER ENCRYPTED PASSWORD ` + pq.QuoteLiteral(dbconn["password"]),
280                 `CREATE DATABASE ` + pq.QuoteIdentifier(dbconn["dbname"]) + ` WITH TEMPLATE template0 ENCODING 'utf8'`,
281                 `CREATE EXTENSION IF NOT EXISTS pg_trgm`,
282         } {
283                 cmd := exec.CommandContext(ctx, "sudo", "-u", "postgres", "psql", "-c", sql)
284                 cmd.Stdout = stderr
285                 cmd.Stderr = stderr
286                 err := cmd.Run()
287                 if err != nil {
288                         return fmt.Errorf("error setting up arvados user/database: %w", err)
289                 }
290         }
291         return nil
292 }