16778: Setup federated users with VM and repo with LoginCluster set
[arvados.git] / lib / install / deps.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         "bufio"
9         "bytes"
10         "context"
11         "errors"
12         "flag"
13         "fmt"
14         "io"
15         "os"
16         "os/exec"
17         "strconv"
18         "strings"
19         "syscall"
20         "time"
21
22         "git.arvados.org/arvados.git/lib/cmd"
23         "git.arvados.org/arvados.git/sdk/go/ctxlog"
24         "github.com/lib/pq"
25 )
26
27 var Command cmd.Handler = installCommand{}
28
29 const devtestDatabasePassword = "insecure_arvados_test"
30
31 type installCommand struct{}
32
33 func (installCommand) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
34         logger := ctxlog.New(stderr, "text", "info")
35         ctx := ctxlog.Context(context.Background(), logger)
36         ctx, cancel := context.WithCancel(ctx)
37         defer cancel()
38
39         var err error
40         defer func() {
41                 if err != nil {
42                         logger.WithError(err).Info("exiting")
43                 }
44         }()
45
46         flags := flag.NewFlagSet(prog, flag.ContinueOnError)
47         flags.SetOutput(stderr)
48         versionFlag := flags.Bool("version", false, "Write version information to stdout and exit 0")
49         clusterType := flags.String("type", "production", "cluster `type`: development, test, or production")
50         err = flags.Parse(args)
51         if err == flag.ErrHelp {
52                 err = nil
53                 return 0
54         } else if err != nil {
55                 return 2
56         } else if *versionFlag {
57                 return cmd.Version.RunCommand(prog, args, stdin, stdout, stderr)
58         }
59
60         var dev, test, prod bool
61         switch *clusterType {
62         case "development":
63                 dev = true
64         case "test":
65                 test = true
66         case "production":
67                 prod = true
68         default:
69                 err = fmt.Errorf("invalid cluster type %q (must be 'development', 'test', or 'production')", *clusterType)
70                 return 2
71         }
72
73         if prod {
74                 err = errors.New("production install is not yet implemented")
75                 return 1
76         }
77
78         osv, err := identifyOS()
79         if err != nil {
80                 return 1
81         }
82
83         listdir, err := os.Open("/var/lib/apt/lists")
84         if err != nil {
85                 logger.Warnf("error while checking whether to run apt-get update: %s", err)
86         } else if names, _ := listdir.Readdirnames(1); len(names) == 0 {
87                 // Special case for a base docker image where the
88                 // package cache has been deleted and all "apt-get
89                 // install" commands will fail unless we fetch repos.
90                 cmd := exec.CommandContext(ctx, "apt-get", "update")
91                 cmd.Stdout = stdout
92                 cmd.Stderr = stderr
93                 err = cmd.Run()
94                 if err != nil {
95                         return 1
96                 }
97         }
98
99         if dev || test {
100                 debs := []string{
101                         "bison",
102                         "bsdmainutils",
103                         "build-essential",
104                         "ca-certificates",
105                         "cadaver",
106                         "curl",
107                         "cython",
108                         "daemontools", // lib/boot uses setuidgid to drop privileges when running as root
109                         "default-jdk-headless",
110                         "default-jre-headless",
111                         "fuse",
112                         "gettext",
113                         "git",
114                         "gitolite3",
115                         "graphviz",
116                         "haveged",
117                         "iceweasel",
118                         "libattr1-dev",
119                         "libcrypt-ssleay-perl",
120                         "libcrypt-ssleay-perl",
121                         "libcurl3-gnutls",
122                         "libcurl4-openssl-dev",
123                         "libfuse-dev",
124                         "libgnutls28-dev",
125                         "libjson-perl",
126                         "libjson-perl",
127                         "libpam-dev",
128                         "libpcre3-dev",
129                         "libpq-dev",
130                         "libpython2.7-dev",
131                         "libreadline-dev",
132                         "libssl-dev",
133                         "libwww-perl",
134                         "libxml2-dev",
135                         "libxslt1.1",
136                         "linkchecker",
137                         "lsof",
138                         "net-tools",
139                         "nginx",
140                         "pandoc",
141                         "perl-modules",
142                         "pkg-config",
143                         "postgresql",
144                         "postgresql-contrib",
145                         "python",
146                         "python3-dev",
147                         "python-epydoc",
148                         "r-base",
149                         "r-cran-testthat",
150                         "sudo",
151                         "virtualenv",
152                         "wget",
153                         "xvfb",
154                         "zlib1g-dev",
155                 }
156                 switch {
157                 case osv.Debian && osv.Major >= 10:
158                         debs = append(debs, "libcurl4")
159                 default:
160                         debs = append(debs, "libcurl3")
161                 }
162                 cmd := exec.CommandContext(ctx, "apt-get", "install", "--yes", "--no-install-recommends")
163                 cmd.Args = append(cmd.Args, debs...)
164                 cmd.Env = append(os.Environ(), "DEBIAN_FRONTEND=noninteractive")
165                 cmd.Stdout = stdout
166                 cmd.Stderr = stderr
167                 err = cmd.Run()
168                 if err != nil {
169                         return 1
170                 }
171         }
172
173         os.Mkdir("/var/lib/arvados", 0755)
174         rubyversion := "2.5.7"
175         if haverubyversion, err := exec.Command("/var/lib/arvados/bin/ruby", "-v").CombinedOutput(); err == nil && bytes.HasPrefix(haverubyversion, []byte("ruby "+rubyversion)) {
176                 logger.Print("ruby " + rubyversion + " already installed")
177         } else {
178                 err = runBash(`
179 mkdir -p /var/lib/arvados/tmp
180 tmp=/var/lib/arvados/tmp/ruby-`+rubyversion+`
181 trap "rm -r ${tmp}" ERR
182 wget --progress=dot:giga -O- https://cache.ruby-lang.org/pub/ruby/2.5/ruby-`+rubyversion+`.tar.gz | tar -C /var/lib/arvados/tmp -xzf -
183 cd ${tmp}
184 ./configure --disable-install-doc --prefix /var/lib/arvados
185 make -j4
186 make install
187 /var/lib/arvados/bin/gem install bundler
188 rm -r ${tmp}
189 `, stdout, stderr)
190                 if err != nil {
191                         return 1
192                 }
193         }
194
195         if !prod {
196                 goversion := "1.14"
197                 if havegoversion, err := exec.Command("/usr/local/bin/go", "version").CombinedOutput(); err == nil && bytes.HasPrefix(havegoversion, []byte("go version go"+goversion+" ")) {
198                         logger.Print("go " + goversion + " already installed")
199                 } else {
200                         err = runBash(`
201 cd /tmp
202 wget --progress=dot:giga -O- https://storage.googleapis.com/golang/go`+goversion+`.linux-amd64.tar.gz | tar -C /var/lib/arvados -xzf -
203 ln -sf /var/lib/arvados/go/bin/* /usr/local/bin/
204 `, stdout, stderr)
205                         if err != nil {
206                                 return 1
207                         }
208                 }
209
210                 pjsversion := "1.9.8"
211                 if havepjsversion, err := exec.Command("/usr/local/bin/phantomjs", "--version").CombinedOutput(); err == nil && string(havepjsversion) == "1.9.8\n" {
212                         logger.Print("phantomjs " + pjsversion + " already installed")
213                 } else {
214                         err = runBash(`
215 PJS=phantomjs-`+pjsversion+`-linux-x86_64
216 wget --progress=dot:giga -O- https://bitbucket.org/ariya/phantomjs/downloads/$PJS.tar.bz2 | tar -C /var/lib/arvados -xjf -
217 ln -sf /var/lib/arvados/$PJS/bin/phantomjs /usr/local/bin/
218 `, stdout, stderr)
219                         if err != nil {
220                                 return 1
221                         }
222                 }
223
224                 geckoversion := "0.24.0"
225                 if havegeckoversion, err := exec.Command("/usr/local/bin/geckodriver", "--version").CombinedOutput(); err == nil && strings.Contains(string(havegeckoversion), " "+geckoversion+" ") {
226                         logger.Print("geckodriver " + geckoversion + " already installed")
227                 } else {
228                         err = runBash(`
229 GD=v`+geckoversion+`
230 wget --progress=dot:giga -O- https://github.com/mozilla/geckodriver/releases/download/$GD/geckodriver-$GD-linux64.tar.gz | tar -C /var/lib/arvados/bin -xzf - geckodriver
231 ln -sf /var/lib/arvados/bin/geckodriver /usr/local/bin/
232 `, stdout, stderr)
233                         if err != nil {
234                                 return 1
235                         }
236                 }
237
238                 nodejsversion := "v8.15.1"
239                 if havenodejsversion, err := exec.Command("/usr/local/bin/node", "--version").CombinedOutput(); err == nil && string(havenodejsversion) == nodejsversion+"\n" {
240                         logger.Print("nodejs " + nodejsversion + " already installed")
241                 } else {
242                         err = runBash(`
243 NJS=`+nodejsversion+`
244 wget --progress=dot:giga -O- https://nodejs.org/dist/${NJS}/node-${NJS}-linux-x64.tar.xz | sudo tar -C /var/lib/arvados -xJf -
245 ln -sf /var/lib/arvados/node-${NJS}-linux-x64/bin/{node,npm} /usr/local/bin/
246 `, stdout, stderr)
247                         if err != nil {
248                                 return 1
249                         }
250                 }
251
252                 gradleversion := "5.3.1"
253                 if havegradleversion, err := exec.Command("/usr/local/bin/gradle", "--version").CombinedOutput(); err == nil && strings.Contains(string(havegradleversion), "Gradle "+gradleversion+"\n") {
254                         logger.Print("gradle " + gradleversion + " already installed")
255                 } else {
256                         err = runBash(`
257 G=`+gradleversion+`
258 mkdir -p /var/lib/arvados/tmp
259 zip=/var/lib/arvados/tmp/gradle-${G}-bin.zip
260 trap "rm ${zip}" ERR
261 wget --progress=dot:giga -O${zip} https://services.gradle.org/distributions/gradle-${G}-bin.zip
262 unzip -o -d /var/lib/arvados ${zip}
263 ln -sf /var/lib/arvados/gradle-${G}/bin/gradle /usr/local/bin/
264 rm ${zip}
265 `, stdout, stderr)
266                         if err != nil {
267                                 return 1
268                         }
269                 }
270
271                 // The entry in /etc/locale.gen is "en_US.UTF-8"; once
272                 // it's installed, locale -a reports it as
273                 // "en_US.utf8".
274                 wantlocale := "en_US.UTF-8"
275                 if havelocales, err := exec.Command("locale", "-a").CombinedOutput(); err == nil && bytes.Contains(havelocales, []byte(strings.Replace(wantlocale+"\n", "UTF-", "utf", 1))) {
276                         logger.Print("locale " + wantlocale + " already installed")
277                 } else {
278                         err = runBash(`sed -i 's/^# *\(`+wantlocale+`\)/\1/' /etc/locale.gen && locale-gen`, stdout, stderr)
279                         if err != nil {
280                                 return 1
281                         }
282                 }
283
284                 var pgc struct {
285                         Version       string
286                         Cluster       string
287                         Port          int
288                         Status        string
289                         Owner         string
290                         DataDirectory string
291                         LogFile       string
292                 }
293                 if pg_lsclusters, err2 := exec.Command("pg_lsclusters", "--no-header").CombinedOutput(); err2 != nil {
294                         err = fmt.Errorf("pg_lsclusters: %s", err2)
295                         return 1
296                 } else if pgclusters := strings.Split(strings.TrimSpace(string(pg_lsclusters)), "\n"); len(pgclusters) != 1 {
297                         logger.Warnf("pg_lsclusters returned %d postgresql clusters -- skipping postgresql initdb/startup, hope that's ok", len(pgclusters))
298                 } else if _, err = fmt.Sscanf(pgclusters[0], "%s %s %d %s %s %s %s", &pgc.Version, &pgc.Cluster, &pgc.Port, &pgc.Status, &pgc.Owner, &pgc.DataDirectory, &pgc.LogFile); err != nil {
299                         err = fmt.Errorf("error parsing pg_lsclusters output: %s", err)
300                         return 1
301                 } else if pgc.Status == "online" {
302                         logger.Infof("postgresql cluster %s-%s is online", pgc.Version, pgc.Cluster)
303                 } else {
304                         logger.Infof("postgresql cluster %s-%s is %s; trying to start", pgc.Version, pgc.Cluster, pgc.Status)
305                         cmd := exec.Command("pg_ctlcluster", "--foreground", pgc.Version, pgc.Cluster, "start")
306                         cmd.Stdout = stdout
307                         cmd.Stderr = stderr
308                         err = cmd.Start()
309                         if err != nil {
310                                 return 1
311                         }
312                         defer func() {
313                                 cmd.Process.Signal(syscall.SIGTERM)
314                                 logger.Info("sent SIGTERM; waiting for postgres to shut down")
315                                 cmd.Wait()
316                         }()
317                         err = waitPostgreSQLReady()
318                         if err != nil {
319                                 return 1
320                         }
321                 }
322
323                 if os.Getpid() == 1 {
324                         // We are the init process (presumably in a
325                         // docker container) so although postgresql is
326                         // installed, it's not running, and initdb
327                         // might never have been run.
328                 }
329
330                 var needcoll []string
331                 // If the en_US.UTF-8 locale wasn't installed when
332                 // postgresql initdb ran, it needs to be added
333                 // explicitly before we can use it in our test suite.
334                 for _, collname := range []string{"en_US", "en_US.UTF-8"} {
335                         cmd := exec.Command("sudo", "-u", "postgres", "psql", "-t", "-c", "SELECT 1 FROM pg_catalog.pg_collation WHERE collname='"+collname+"' AND collcollate IN ('en_US.UTF-8', 'en_US.utf8')")
336                         cmd.Dir = "/"
337                         out, err2 := cmd.CombinedOutput()
338                         if err != nil {
339                                 err = fmt.Errorf("error while checking postgresql collations: %s", err2)
340                                 return 1
341                         }
342                         if strings.Contains(string(out), "1") {
343                                 logger.Infof("postgresql supports collation %s", collname)
344                         } else {
345                                 needcoll = append(needcoll, collname)
346                         }
347                 }
348                 if len(needcoll) > 0 && os.Getpid() != 1 {
349                         // In order for the CREATE COLLATION statement
350                         // below to work, the locale must have existed
351                         // when PostgreSQL started up. If we're
352                         // running as init, we must have started
353                         // PostgreSQL ourselves after installing the
354                         // locales. Otherwise, it might need a
355                         // restart, so we attempt to restart it with
356                         // systemd.
357                         if err = runBash(`sudo systemctl restart postgresql`, stdout, stderr); err != nil {
358                                 logger.Warn("`systemctl restart postgresql` failed; hoping postgresql does not need to be restarted")
359                         } else if err = waitPostgreSQLReady(); err != nil {
360                                 return 1
361                         }
362                 }
363                 for _, collname := range needcoll {
364                         cmd := exec.Command("sudo", "-u", "postgres", "psql", "-c", "CREATE COLLATION \""+collname+"\" (LOCALE = \"en_US.UTF-8\")")
365                         cmd.Stdout = stdout
366                         cmd.Stderr = stderr
367                         cmd.Dir = "/"
368                         err = cmd.Run()
369                         if err != nil {
370                                 err = fmt.Errorf("error adding postgresql collation %s: %s", collname, err)
371                                 return 1
372                         }
373                 }
374
375                 withstuff := "WITH LOGIN SUPERUSER ENCRYPTED PASSWORD " + pq.QuoteLiteral(devtestDatabasePassword)
376                 cmd := exec.Command("sudo", "-u", "postgres", "psql", "-c", "ALTER ROLE arvados "+withstuff)
377                 cmd.Dir = "/"
378                 if err := cmd.Run(); err == nil {
379                         logger.Print("arvados role exists; superuser privileges added, password updated")
380                 } else {
381                         cmd := exec.Command("sudo", "-u", "postgres", "psql", "-c", "CREATE ROLE arvados "+withstuff)
382                         cmd.Dir = "/"
383                         cmd.Stdout = stdout
384                         cmd.Stderr = stderr
385                         err = cmd.Run()
386                         if err != nil {
387                                 return 1
388                         }
389                 }
390         }
391
392         return 0
393 }
394
395 type osversion struct {
396         Debian bool
397         Ubuntu bool
398         Major  int
399 }
400
401 func identifyOS() (osversion, error) {
402         var osv osversion
403         f, err := os.Open("/etc/os-release")
404         if err != nil {
405                 return osv, err
406         }
407         defer f.Close()
408
409         kv := map[string]string{}
410         scanner := bufio.NewScanner(f)
411         for scanner.Scan() {
412                 line := strings.TrimSpace(scanner.Text())
413                 if strings.HasPrefix(line, "#") {
414                         continue
415                 }
416                 toks := strings.SplitN(line, "=", 2)
417                 if len(toks) != 2 {
418                         return osv, fmt.Errorf("invalid line in /etc/os-release: %q", line)
419                 }
420                 k := toks[0]
421                 v := strings.Trim(toks[1], `"`)
422                 if v == toks[1] {
423                         v = strings.Trim(v, `'`)
424                 }
425                 kv[k] = v
426         }
427         if err = scanner.Err(); err != nil {
428                 return osv, err
429         }
430         switch kv["ID"] {
431         case "ubuntu":
432                 osv.Ubuntu = true
433         case "debian":
434                 osv.Debian = true
435         default:
436                 return osv, fmt.Errorf("unsupported ID in /etc/os-release: %q", kv["ID"])
437         }
438         vstr := kv["VERSION_ID"]
439         if i := strings.Index(vstr, "."); i > 0 {
440                 vstr = vstr[:i]
441         }
442         osv.Major, err = strconv.Atoi(vstr)
443         if err != nil {
444                 return osv, fmt.Errorf("incomprehensible VERSION_ID in /etc/os-release: %q", kv["VERSION_ID"])
445         }
446         return osv, nil
447 }
448
449 func waitPostgreSQLReady() error {
450         for deadline := time.Now().Add(10 * time.Second); ; {
451                 output, err := exec.Command("pg_isready").CombinedOutput()
452                 if err == nil {
453                         return nil
454                 } else if time.Now().After(deadline) {
455                         return fmt.Errorf("timed out waiting for pg_isready (%q)", output)
456                 } else {
457                         time.Sleep(time.Second)
458                 }
459         }
460 }
461
462 func runBash(script string, stdout, stderr io.Writer) error {
463         cmd := exec.Command("bash", "-")
464         cmd.Stdin = bytes.NewBufferString("set -ex -o pipefail\n" + script)
465         cmd.Stdout = stdout
466         cmd.Stderr = stderr
467         return cmd.Run()
468 }