15397: Move remaining Mail configs to Users section.
[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         "net"
17         "net/http"
18         "net/url"
19         "os"
20         "os/exec"
21         "os/user"
22         "regexp"
23         "strconv"
24         "strings"
25         "sync/atomic"
26         "text/template"
27         "time"
28
29         "git.arvados.org/arvados.git/lib/cmd"
30         "git.arvados.org/arvados.git/lib/config"
31         "git.arvados.org/arvados.git/lib/controller/rpc"
32         "git.arvados.org/arvados.git/sdk/go/arvados"
33         "git.arvados.org/arvados.git/sdk/go/auth"
34         "git.arvados.org/arvados.git/sdk/go/ctxlog"
35         "github.com/lib/pq"
36 )
37
38 var InitCommand cmd.Handler = &initCommand{}
39
40 type initCommand struct {
41         ClusterID  string
42         Domain     string
43         CreateDB   bool
44         Login      string
45         TLS        string
46         AdminEmail string
47         Start      bool
48
49         PostgreSQL struct {
50                 Host     string
51                 User     string
52                 Password string
53                 DB       string
54         }
55         LoginPAM                bool
56         LoginTest               bool
57         LoginGoogle             bool
58         LoginGoogleClientID     string
59         LoginGoogleClientSecret string
60         TLSDir                  string
61 }
62
63 func (initcmd *initCommand) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
64         logger := ctxlog.New(stderr, "text", "info")
65         ctx := ctxlog.Context(context.Background(), logger)
66         ctx, cancel := context.WithCancel(ctx)
67         defer cancel()
68
69         var err error
70         defer func() {
71                 if err != nil {
72                         logger.WithError(err).Info("exiting")
73                 }
74         }()
75
76         hostname, err := os.Hostname()
77         if err != nil {
78                 err = fmt.Errorf("Hostname(): %w", err)
79                 return 1
80         }
81
82         flags := flag.NewFlagSet(prog, flag.ContinueOnError)
83         flags.SetOutput(stderr)
84         versionFlag := flags.Bool("version", false, "Write version information to stdout and exit 0")
85         flags.StringVar(&initcmd.ClusterID, "cluster-id", "", "cluster `id`, like x1234 for a dev cluster")
86         flags.BoolVar(&initcmd.CreateDB, "create-db", true, "create an 'arvados' postgresql role and database using 'sudo -u postgres psql ...' (if false, use existing database specified by POSTGRES_HOST, POSTGRES_USER, POSTGRES_PASSWORD, and POSTGRES_DB env vars, and assume 'CREATE EXTENSION IF NOT EXISTS pg_trgm' has already been done)")
87         flags.StringVar(&initcmd.Domain, "domain", hostname, "cluster public DNS `name`, like x1234.arvadosapi.com")
88         flags.StringVar(&initcmd.Login, "login", "", "login `backend`: test, pam, 'google {client-id} {client-secret}', or ''")
89         flags.StringVar(&initcmd.AdminEmail, "admin-email", "", "give admin privileges to user with given `email`")
90         flags.StringVar(&initcmd.TLS, "tls", "none", "tls certificate `source`: acme, insecure, none, or /path/to/dir containing privkey and cert files")
91         flags.BoolVar(&initcmd.Start, "start", true, "start systemd service after creating config")
92         if ok, code := cmd.ParseFlags(flags, prog, args, "", stderr); !ok {
93                 return code
94         } else if *versionFlag {
95                 return cmd.Version.RunCommand(prog, args, stdin, stdout, stderr)
96         } else if !regexp.MustCompile(`^[a-z][a-z0-9]{4}`).MatchString(initcmd.ClusterID) {
97                 err = fmt.Errorf("cluster ID %q is invalid; must be an ASCII letter followed by 4 alphanumerics (try -help)", initcmd.ClusterID)
98                 return 1
99         }
100
101         if fields := strings.Fields(initcmd.Login); len(fields) == 3 && fields[0] == "google" {
102                 initcmd.LoginGoogle = true
103                 initcmd.LoginGoogleClientID = fields[1]
104                 initcmd.LoginGoogleClientSecret = fields[2]
105         } else if initcmd.Login == "test" {
106                 initcmd.LoginTest = true
107                 if initcmd.AdminEmail == "" {
108                         initcmd.AdminEmail = "admin@example.com"
109                 }
110         } else if initcmd.Login == "pam" {
111                 initcmd.LoginPAM = true
112         } else if initcmd.Login == "" {
113                 // none; login will show an error page
114         } else {
115                 err = fmt.Errorf("invalid argument to -login: %q: should be 'test', 'pam', 'google {client-id} {client-secret}', or empty", initcmd.Login)
116                 return 1
117         }
118
119         switch initcmd.TLS {
120         case "none", "acme", "insecure":
121         default:
122                 if !strings.HasPrefix(initcmd.TLS, "/") {
123                         err = fmt.Errorf("invalid argument to -tls: %q; see %s -help", initcmd.TLS, prog)
124                         return 1
125                 }
126                 initcmd.TLSDir = initcmd.TLS
127         }
128
129         confdir := "/etc/arvados"
130         conffile := confdir + "/config.yml"
131         if _, err = os.Stat(conffile); err == nil {
132                 err = fmt.Errorf("config file %s already exists; delete it first if you really want to start over", conffile)
133                 return 1
134         }
135
136         ports := []int{443}
137         for i := 4440; i < 4460; i++ {
138                 ports = append(ports, i)
139         }
140         if initcmd.TLS == "acme" {
141                 ports = append(ports, 80)
142         }
143         for _, port := range ports {
144                 err = initcmd.checkPort(ctx, fmt.Sprintf("%d", port))
145                 if err != nil {
146                         return 1
147                 }
148         }
149
150         if initcmd.CreateDB {
151                 // Do the "create extension" thing early. This way, if
152                 // there's no local postgresql server (a likely
153                 // failure mode), we can bail out without any side
154                 // effects, and the user can start over easily.
155                 fmt.Fprintln(stderr, "installing pg_trgm postgresql extension...")
156                 cmd := exec.CommandContext(ctx, "sudo", "-u", "postgres", "psql", "--quiet",
157                         "-c", `CREATE EXTENSION IF NOT EXISTS pg_trgm`)
158                 cmd.Dir = "/"
159                 cmd.Stdout = stdout
160                 cmd.Stderr = stderr
161                 err = cmd.Run()
162                 if err != nil {
163                         err = fmt.Errorf("error preparing postgresql server: %w", err)
164                         return 1
165                 }
166                 fmt.Fprintln(stderr, "...done")
167                 initcmd.PostgreSQL.Host = "localhost"
168                 initcmd.PostgreSQL.User = "arvados"
169                 initcmd.PostgreSQL.Password = initcmd.RandomHex(32)
170                 initcmd.PostgreSQL.DB = "arvados"
171         } else {
172                 initcmd.PostgreSQL.Host = os.Getenv("POSTGRES_HOST")
173                 initcmd.PostgreSQL.User = os.Getenv("POSTGRES_USER")
174                 initcmd.PostgreSQL.Password = os.Getenv("POSTGRES_PASSWORD")
175                 initcmd.PostgreSQL.DB = os.Getenv("POSTGRES_DB")
176                 if initcmd.PostgreSQL.Host == "" || initcmd.PostgreSQL.User == "" || initcmd.PostgreSQL.Password == "" || initcmd.PostgreSQL.DB == "" {
177                         err = fmt.Errorf("missing $POSTGRES_* env var(s) for -create-db=false; see %s -help", prog)
178                         return 1
179                 }
180         }
181
182         wwwuser, err := user.Lookup("www-data")
183         if err != nil {
184                 err = fmt.Errorf("user.Lookup(%q): %w", "www-data", err)
185                 return 1
186         }
187         wwwgid, err := strconv.Atoi(wwwuser.Gid)
188         if err != nil {
189                 return 1
190         }
191
192         fmt.Fprintln(stderr, "creating data storage directory /var/lib/arvados/keep ...")
193         err = os.Mkdir("/var/lib/arvados/keep", 0600)
194         if err != nil && !os.IsExist(err) {
195                 err = fmt.Errorf("mkdir /var/lib/arvados/keep: %w", err)
196                 return 1
197         }
198         fmt.Fprintln(stderr, "...done")
199
200         fmt.Fprintln(stderr, "creating config file", conffile, "...")
201         err = os.Mkdir(confdir, 0750)
202         if err != nil && !os.IsExist(err) {
203                 err = fmt.Errorf("mkdir %s: %w", confdir, err)
204                 return 1
205         }
206         err = os.Chown(confdir, 0, wwwgid)
207         if err != nil {
208                 err = fmt.Errorf("chown 0:%d %s: %w", wwwgid, confdir, err)
209                 return 1
210         }
211         f, err := os.OpenFile(conffile+".tmp", os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0644)
212         if err != nil {
213                 err = fmt.Errorf("open %s: %w", conffile+".tmp", err)
214                 return 1
215         }
216         tmpl, err := template.New("config").Parse(`Clusters:
217   {{.ClusterID}}:
218     Services:
219       Controller:
220         InternalURLs:
221           "http://0.0.0.0:9000/": {}
222         ExternalURL: {{printf "%q" ( print "https://" .Domain ":4440/" ) }}
223       RailsAPI:
224         InternalURLs:
225           "http://0.0.0.0:9001/": {}
226       Websocket:
227         InternalURLs:
228           "http://0.0.0.0:8005/": {}
229         ExternalURL: {{printf "%q" ( print "wss://" .Domain ":4446/" ) }}
230       Keepbalance:
231         InternalURLs:
232           "http://0.0.0.0:9019/": {}
233       DispatchCloud:
234         InternalURLs:
235           "http://0.0.0.0:9006/": {}
236       Keepproxy:
237         InternalURLs:
238           "http://0.0.0.0:9007/": {}
239         ExternalURL: {{printf "%q" ( print "https://" .Domain ":4447/" ) }}
240       WebDAV:
241         InternalURLs:
242           "http://0.0.0.0:9008/": {}
243         ExternalURL: {{printf "%q" ( print "https://" .Domain ":4448/" ) }}
244       WebDAVDownload:
245         InternalURLs:
246           "http://0.0.0.0:9009/": {}
247         ExternalURL: {{printf "%q" ( print "https://" .Domain ":4449/" ) }}
248       Keepstore:
249         InternalURLs:
250           "http://0.0.0.0:9010/": {}
251       Composer:
252         ExternalURL: {{printf "%q" ( print "https://" .Domain ":4459/composer" ) }}
253       Workbench1:
254         InternalURLs:
255           "http://0.0.0.0:9002/": {}
256         ExternalURL: {{printf "%q" ( print "https://" .Domain ":4442/" ) }}
257       Workbench2:
258         InternalURLs:
259           "http://0.0.0.0:9003/": {}
260         ExternalURL: {{printf "%q" ( print "https://" .Domain "/" ) }}
261       Health:
262         InternalURLs:
263           "http://0.0.0.0:9011/": {}
264     Collections:
265       BlobSigningKey: {{printf "%q" ( .RandomHex 50 )}}
266       {{if eq .TLS "insecure"}}
267       TrustAllContent: true
268       {{end}}
269     Containers:
270       DispatchPrivateKey: {{printf "%q" .GenerateSSHPrivateKey}}
271       CloudVMs:
272         Enable: true
273         Driver: loopback
274     ManagementToken: {{printf "%q" ( .RandomHex 50 )}}
275     PostgreSQL:
276       Connection:
277         dbname: {{printf "%q" .PostgreSQL.DB}}
278         host: {{printf "%q" .PostgreSQL.Host}}
279         user: {{printf "%q" .PostgreSQL.User}}
280         password: {{printf "%q" .PostgreSQL.Password}}
281     SystemRootToken: {{printf "%q" ( .RandomHex 50 )}}
282     TLS:
283       {{if eq .TLS "insecure"}}
284       Insecure: true
285       {{else if eq .TLS "acme"}}
286       ACME:
287         Server: LE
288       {{else if ne .TLSDir ""}}
289       Certificate: {{printf "%q" (print .TLSDir "/cert")}}
290       Key: {{printf "%q" (print .TLSDir "/privkey")}}
291       {{else}}
292       {}
293       {{end}}
294     Volumes:
295       {{.ClusterID}}-nyw5e-000000000000000:
296         Driver: Directory
297         DriverParameters:
298           Root: /var/lib/arvados/keep
299         Replication: 2
300     {{if .LoginPAM}}
301     Login:
302       PAM:
303         Enable: true
304     {{else if .LoginTest}}
305     Login:
306       Test:
307         Enable: true
308         Users:
309           admin:
310             Email: {{printf "%q" .AdminEmail}}
311             Password: admin
312     {{else if .LoginGoogle}}
313     Login:
314       Google:
315         Enable: true
316         ClientID: {{printf "%q" .LoginGoogleClientID}}
317         ClientSecret: {{printf "%q" .LoginGoogleClientSecret}}
318     {{end}}
319     Users:
320       AutoAdminUserWithEmail: {{printf "%q" .AdminEmail}}
321 `)
322         if err != nil {
323                 return 1
324         }
325         err = tmpl.Execute(f, initcmd)
326         if err != nil {
327                 err = fmt.Errorf("%s: tmpl.Execute: %w", conffile+".tmp", err)
328                 return 1
329         }
330         err = f.Close()
331         if err != nil {
332                 err = fmt.Errorf("%s: close: %w", conffile+".tmp", err)
333                 return 1
334         }
335         err = os.Rename(conffile+".tmp", conffile)
336         if err != nil {
337                 err = fmt.Errorf("rename %s -> %s: %w", conffile+".tmp", conffile, err)
338                 return 1
339         }
340         fmt.Fprintln(stderr, "...done")
341
342         ldr := config.NewLoader(nil, logger)
343         ldr.SkipLegacy = true
344         ldr.Path = conffile // load the file we just wrote, even if $ARVADOS_CONFIG is set
345         cfg, err := ldr.Load()
346         if err != nil {
347                 err = fmt.Errorf("%s: %w", conffile, err)
348                 return 1
349         }
350         cluster, err := cfg.GetCluster("")
351         if err != nil {
352                 return 1
353         }
354
355         fmt.Fprintln(stderr, "creating postresql user and database...")
356         err = initcmd.createDB(ctx, cluster.PostgreSQL.Connection, stderr)
357         if err != nil {
358                 return 1
359         }
360         fmt.Fprintln(stderr, "...done")
361
362         fmt.Fprintln(stderr, "initializing database...")
363         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")
364         cmd.Dir = "/var/lib/arvados/railsapi"
365         cmd.Stdout = stderr
366         cmd.Stderr = stderr
367         err = cmd.Run()
368         if err != nil {
369                 err = fmt.Errorf("rake db:setup failed: %w", err)
370                 return 1
371         }
372         fmt.Fprintln(stderr, "...done")
373
374         if initcmd.Start {
375                 fmt.Fprintln(stderr, "starting systemd service...")
376                 cmd := exec.CommandContext(ctx, "systemctl", "start", "arvados")
377                 cmd.Dir = "/"
378                 cmd.Stdout = stderr
379                 cmd.Stderr = stderr
380                 err = cmd.Run()
381                 if err != nil {
382                         err = fmt.Errorf("%v: %w", cmd.Args, err)
383                         return 1
384                 }
385                 fmt.Fprintln(stderr, "...done")
386
387                 fmt.Fprintln(stderr, "checking controller API endpoint...")
388                 u := url.URL(cluster.Services.Controller.ExternalURL)
389                 conn := rpc.NewConn(cluster.ClusterID, &u, cluster.TLS.Insecure, rpc.PassthroughTokenProvider)
390                 ctx := auth.NewContext(context.Background(), auth.NewCredentials(cluster.SystemRootToken))
391                 _, err = conn.UserGetCurrent(ctx, arvados.GetOptions{})
392                 if err != nil {
393                         err = fmt.Errorf("API request failed: %w", err)
394                         return 1
395                 }
396                 fmt.Fprintln(stderr, "...looks good")
397         }
398
399         fmt.Fprintf(stderr, `
400 Setup complete. Next steps:
401 * run 'arv sudo diagnostics'
402 * log in to workbench2 at %s
403 * see documentation at https://doc.arvados.org/install/automatic.html
404 `, cluster.Services.Workbench2.ExternalURL.String())
405
406         return 0
407 }
408
409 func (initcmd *initCommand) GenerateSSHPrivateKey() (string, error) {
410         privkey, err := rsa.GenerateKey(rand.Reader, 4096)
411         if err != nil {
412                 return "", err
413         }
414         err = privkey.Validate()
415         if err != nil {
416                 return "", err
417         }
418         return string(pem.EncodeToMemory(&pem.Block{
419                 Type:  "RSA PRIVATE KEY",
420                 Bytes: x509.MarshalPKCS1PrivateKey(privkey),
421         })), nil
422 }
423
424 func (initcmd *initCommand) RandomHex(chars int) string {
425         b := make([]byte, chars/2)
426         _, err := rand.Read(b)
427         if err != nil {
428                 panic(err)
429         }
430         return fmt.Sprintf("%x", b)
431 }
432
433 func (initcmd *initCommand) createDB(ctx context.Context, dbconn arvados.PostgreSQLConnection, stderr io.Writer) error {
434         cmd := exec.CommandContext(ctx, "sudo", "-u", "postgres", "psql", "--quiet",
435                 "-c", `CREATE USER `+pq.QuoteIdentifier(dbconn["user"])+` WITH SUPERUSER ENCRYPTED PASSWORD `+pq.QuoteLiteral(dbconn["password"]),
436                 "-c", `CREATE DATABASE `+pq.QuoteIdentifier(dbconn["dbname"])+` WITH TEMPLATE template0 ENCODING 'utf8'`,
437         )
438         cmd.Dir = "/"
439         cmd.Stdout = stderr
440         cmd.Stderr = stderr
441         err := cmd.Run()
442         if err != nil {
443                 return fmt.Errorf("error setting up arvados user/database: %w", err)
444         }
445         return nil
446 }
447
448 // Confirm that http://{initcmd.Domain}:{port} reaches a server that
449 // we run on {port}.
450 //
451 // If port is "80", listening fails, and Nginx appears to be using the
452 // debian-packaged default configuration that listens on port 80,
453 // disable that Nginx config and try again.
454 //
455 // (Typically, the reason Nginx is installed is so that Arvados can
456 // run an Nginx child process; the default Nginx service using config
457 // from /etc/nginx is just an unfortunate side effect of installing
458 // Nginx by way of the Debian package.)
459 func (initcmd *initCommand) checkPort(ctx context.Context, port string) error {
460         err := initcmd.checkPortOnce(ctx, port)
461         if err == nil || port != "80" {
462                 // success, or poking Nginx in the eye won't help
463                 return err
464         }
465         d, err2 := os.Open("/etc/nginx/sites-enabled/.")
466         if err2 != nil {
467                 return err
468         }
469         fis, err2 := d.Readdir(-1)
470         if err2 != nil || len(fis) != 1 {
471                 return err
472         }
473         if target, err2 := os.Readlink("/etc/nginx/sites-enabled/default"); err2 != nil || target != "/etc/nginx/sites-available/default" {
474                 return err
475         }
476         err2 = os.Remove("/etc/nginx/sites-enabled/default")
477         if err2 != nil {
478                 return err
479         }
480         exec.CommandContext(ctx, "nginx", "-s", "reload").Run()
481         time.Sleep(time.Second)
482         return initcmd.checkPortOnce(ctx, port)
483 }
484
485 // Start an http server on 0.0.0.0:{port} and confirm that
486 // http://{initcmd.Domain}:{port} reaches that server.
487 func (initcmd *initCommand) checkPortOnce(ctx context.Context, port string) error {
488         b := make([]byte, 128)
489         _, err := rand.Read(b)
490         if err != nil {
491                 return err
492         }
493         token := fmt.Sprintf("%x", b)
494
495         srv := http.Server{
496                 Addr: net.JoinHostPort("", port),
497                 Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
498                         fmt.Fprint(w, token)
499                 })}
500         var errServe atomic.Value
501         go func() {
502                 errServe.Store(srv.ListenAndServe())
503         }()
504         defer srv.Close()
505         url := "http://" + net.JoinHostPort(initcmd.Domain, port) + "/probe"
506         req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
507         if err != nil {
508                 return err
509         }
510         resp, err := http.DefaultClient.Do(req)
511         if err == nil {
512                 defer resp.Body.Close()
513         }
514         if errServe, _ := errServe.Load().(error); errServe != nil {
515                 // If server already exited, return that error
516                 // (probably "can't listen"), not the request error.
517                 return errServe
518         }
519         if err != nil {
520                 return err
521         }
522         buf := make([]byte, len(token))
523         n, err := io.ReadFull(resp.Body, buf)
524         if string(buf[:n]) != token {
525                 return fmt.Errorf("listened on port %s but %s connected to something else, returned %q, err %v", port, url, buf[:n], err)
526         }
527         return nil
528 }