16809: Test keep-web with s3cmd if available.
[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                         "cython3",
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                         "libreadline-dev",
131                         "libssl-dev",
132                         "libwww-perl",
133                         "libxml2-dev",
134                         "libxslt1.1",
135                         "linkchecker",
136                         "lsof",
137                         "net-tools",
138                         "nginx",
139                         "pandoc",
140                         "perl-modules",
141                         "pkg-config",
142                         "postgresql",
143                         "postgresql-contrib",
144                         "python3-dev",
145                         "python3-venv",
146                         "python3-virtualenv",
147                         "r-base",
148                         "r-cran-testthat",
149                         "s3cmd",
150                         "sudo",
151                         "wget",
152                         "xvfb",
153                         "zlib1g-dev",
154                 }
155                 switch {
156                 case osv.Debian && osv.Major >= 10:
157                         debs = append(debs, "libcurl4")
158                 default:
159                         debs = append(debs, "libcurl3")
160                 }
161                 cmd := exec.CommandContext(ctx, "apt-get", "install", "--yes", "--no-install-recommends")
162                 cmd.Args = append(cmd.Args, debs...)
163                 cmd.Env = append(os.Environ(), "DEBIAN_FRONTEND=noninteractive")
164                 cmd.Stdout = stdout
165                 cmd.Stderr = stderr
166                 err = cmd.Run()
167                 if err != nil {
168                         return 1
169                 }
170         }
171
172         os.Mkdir("/var/lib/arvados", 0755)
173         rubyversion := "2.5.7"
174         if haverubyversion, err := exec.Command("/var/lib/arvados/bin/ruby", "-v").CombinedOutput(); err == nil && bytes.HasPrefix(haverubyversion, []byte("ruby "+rubyversion)) {
175                 logger.Print("ruby " + rubyversion + " already installed")
176         } else {
177                 err = runBash(`
178 mkdir -p /var/lib/arvados/tmp
179 tmp=/var/lib/arvados/tmp/ruby-`+rubyversion+`
180 trap "rm -r ${tmp}" ERR
181 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 -
182 cd ${tmp}
183 ./configure --disable-install-doc --prefix /var/lib/arvados
184 make -j4
185 make install
186 /var/lib/arvados/bin/gem install bundler
187 rm -r ${tmp}
188 `, stdout, stderr)
189                 if err != nil {
190                         return 1
191                 }
192         }
193
194         if !prod {
195                 goversion := "1.14"
196                 if havegoversion, err := exec.Command("/usr/local/bin/go", "version").CombinedOutput(); err == nil && bytes.HasPrefix(havegoversion, []byte("go version go"+goversion+" ")) {
197                         logger.Print("go " + goversion + " already installed")
198                 } else {
199                         err = runBash(`
200 cd /tmp
201 wget --progress=dot:giga -O- https://storage.googleapis.com/golang/go`+goversion+`.linux-amd64.tar.gz | tar -C /var/lib/arvados -xzf -
202 ln -sf /var/lib/arvados/go/bin/* /usr/local/bin/
203 `, stdout, stderr)
204                         if err != nil {
205                                 return 1
206                         }
207                 }
208
209                 pjsversion := "1.9.8"
210                 if havepjsversion, err := exec.Command("/usr/local/bin/phantomjs", "--version").CombinedOutput(); err == nil && string(havepjsversion) == "1.9.8\n" {
211                         logger.Print("phantomjs " + pjsversion + " already installed")
212                 } else {
213                         err = runBash(`
214 PJS=phantomjs-`+pjsversion+`-linux-x86_64
215 wget --progress=dot:giga -O- https://bitbucket.org/ariya/phantomjs/downloads/$PJS.tar.bz2 | tar -C /var/lib/arvados -xjf -
216 ln -sf /var/lib/arvados/$PJS/bin/phantomjs /usr/local/bin/
217 `, stdout, stderr)
218                         if err != nil {
219                                 return 1
220                         }
221                 }
222
223                 geckoversion := "0.24.0"
224                 if havegeckoversion, err := exec.Command("/usr/local/bin/geckodriver", "--version").CombinedOutput(); err == nil && strings.Contains(string(havegeckoversion), " "+geckoversion+" ") {
225                         logger.Print("geckodriver " + geckoversion + " already installed")
226                 } else {
227                         err = runBash(`
228 GD=v`+geckoversion+`
229 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
230 ln -sf /var/lib/arvados/bin/geckodriver /usr/local/bin/
231 `, stdout, stderr)
232                         if err != nil {
233                                 return 1
234                         }
235                 }
236
237                 nodejsversion := "v8.15.1"
238                 if havenodejsversion, err := exec.Command("/usr/local/bin/node", "--version").CombinedOutput(); err == nil && string(havenodejsversion) == nodejsversion+"\n" {
239                         logger.Print("nodejs " + nodejsversion + " already installed")
240                 } else {
241                         err = runBash(`
242 NJS=`+nodejsversion+`
243 wget --progress=dot:giga -O- https://nodejs.org/dist/${NJS}/node-${NJS}-linux-x64.tar.xz | sudo tar -C /var/lib/arvados -xJf -
244 ln -sf /var/lib/arvados/node-${NJS}-linux-x64/bin/{node,npm} /usr/local/bin/
245 `, stdout, stderr)
246                         if err != nil {
247                                 return 1
248                         }
249                 }
250
251                 gradleversion := "5.3.1"
252                 if havegradleversion, err := exec.Command("/usr/local/bin/gradle", "--version").CombinedOutput(); err == nil && strings.Contains(string(havegradleversion), "Gradle "+gradleversion+"\n") {
253                         logger.Print("gradle " + gradleversion + " already installed")
254                 } else {
255                         err = runBash(`
256 G=`+gradleversion+`
257 mkdir -p /var/lib/arvados/tmp
258 zip=/var/lib/arvados/tmp/gradle-${G}-bin.zip
259 trap "rm ${zip}" ERR
260 wget --progress=dot:giga -O${zip} https://services.gradle.org/distributions/gradle-${G}-bin.zip
261 unzip -o -d /var/lib/arvados ${zip}
262 ln -sf /var/lib/arvados/gradle-${G}/bin/gradle /usr/local/bin/
263 rm ${zip}
264 `, stdout, stderr)
265                         if err != nil {
266                                 return 1
267                         }
268                 }
269
270                 // The entry in /etc/locale.gen is "en_US.UTF-8"; once
271                 // it's installed, locale -a reports it as
272                 // "en_US.utf8".
273                 wantlocale := "en_US.UTF-8"
274                 if havelocales, err := exec.Command("locale", "-a").CombinedOutput(); err == nil && bytes.Contains(havelocales, []byte(strings.Replace(wantlocale+"\n", "UTF-", "utf", 1))) {
275                         logger.Print("locale " + wantlocale + " already installed")
276                 } else {
277                         err = runBash(`sed -i 's/^# *\(`+wantlocale+`\)/\1/' /etc/locale.gen && locale-gen`, stdout, stderr)
278                         if err != nil {
279                                 return 1
280                         }
281                 }
282
283                 var pgc struct {
284                         Version       string
285                         Cluster       string
286                         Port          int
287                         Status        string
288                         Owner         string
289                         DataDirectory string
290                         LogFile       string
291                 }
292                 if pg_lsclusters, err2 := exec.Command("pg_lsclusters", "--no-header").CombinedOutput(); err2 != nil {
293                         err = fmt.Errorf("pg_lsclusters: %s", err2)
294                         return 1
295                 } else if pgclusters := strings.Split(strings.TrimSpace(string(pg_lsclusters)), "\n"); len(pgclusters) != 1 {
296                         logger.Warnf("pg_lsclusters returned %d postgresql clusters -- skipping postgresql initdb/startup, hope that's ok", len(pgclusters))
297                 } 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 {
298                         err = fmt.Errorf("error parsing pg_lsclusters output: %s", err)
299                         return 1
300                 } else if pgc.Status == "online" {
301                         logger.Infof("postgresql cluster %s-%s is online", pgc.Version, pgc.Cluster)
302                 } else {
303                         logger.Infof("postgresql cluster %s-%s is %s; trying to start", pgc.Version, pgc.Cluster, pgc.Status)
304                         cmd := exec.Command("pg_ctlcluster", "--foreground", pgc.Version, pgc.Cluster, "start")
305                         cmd.Stdout = stdout
306                         cmd.Stderr = stderr
307                         err = cmd.Start()
308                         if err != nil {
309                                 return 1
310                         }
311                         defer func() {
312                                 cmd.Process.Signal(syscall.SIGTERM)
313                                 logger.Info("sent SIGTERM; waiting for postgres to shut down")
314                                 cmd.Wait()
315                         }()
316                         err = waitPostgreSQLReady()
317                         if err != nil {
318                                 return 1
319                         }
320                 }
321
322                 if os.Getpid() == 1 {
323                         // We are the init process (presumably in a
324                         // docker container) so although postgresql is
325                         // installed, it's not running, and initdb
326                         // might never have been run.
327                 }
328
329                 var needcoll []string
330                 // If the en_US.UTF-8 locale wasn't installed when
331                 // postgresql initdb ran, it needs to be added
332                 // explicitly before we can use it in our test suite.
333                 for _, collname := range []string{"en_US", "en_US.UTF-8"} {
334                         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')")
335                         cmd.Dir = "/"
336                         out, err2 := cmd.CombinedOutput()
337                         if err != nil {
338                                 err = fmt.Errorf("error while checking postgresql collations: %s", err2)
339                                 return 1
340                         }
341                         if strings.Contains(string(out), "1") {
342                                 logger.Infof("postgresql supports collation %s", collname)
343                         } else {
344                                 needcoll = append(needcoll, collname)
345                         }
346                 }
347                 if len(needcoll) > 0 && os.Getpid() != 1 {
348                         // In order for the CREATE COLLATION statement
349                         // below to work, the locale must have existed
350                         // when PostgreSQL started up. If we're
351                         // running as init, we must have started
352                         // PostgreSQL ourselves after installing the
353                         // locales. Otherwise, it might need a
354                         // restart, so we attempt to restart it with
355                         // systemd.
356                         if err = runBash(`sudo systemctl restart postgresql`, stdout, stderr); err != nil {
357                                 logger.Warn("`systemctl restart postgresql` failed; hoping postgresql does not need to be restarted")
358                         } else if err = waitPostgreSQLReady(); err != nil {
359                                 return 1
360                         }
361                 }
362                 for _, collname := range needcoll {
363                         cmd := exec.Command("sudo", "-u", "postgres", "psql", "-c", "CREATE COLLATION \""+collname+"\" (LOCALE = \"en_US.UTF-8\")")
364                         cmd.Stdout = stdout
365                         cmd.Stderr = stderr
366                         cmd.Dir = "/"
367                         err = cmd.Run()
368                         if err != nil {
369                                 err = fmt.Errorf("error adding postgresql collation %s: %s", collname, err)
370                                 return 1
371                         }
372                 }
373
374                 withstuff := "WITH LOGIN SUPERUSER ENCRYPTED PASSWORD " + pq.QuoteLiteral(devtestDatabasePassword)
375                 cmd := exec.Command("sudo", "-u", "postgres", "psql", "-c", "ALTER ROLE arvados "+withstuff)
376                 cmd.Dir = "/"
377                 if err := cmd.Run(); err == nil {
378                         logger.Print("arvados role exists; superuser privileges added, password updated")
379                 } else {
380                         cmd := exec.Command("sudo", "-u", "postgres", "psql", "-c", "CREATE ROLE arvados "+withstuff)
381                         cmd.Dir = "/"
382                         cmd.Stdout = stdout
383                         cmd.Stderr = stderr
384                         err = cmd.Run()
385                         if err != nil {
386                                 return 1
387                         }
388                 }
389         }
390
391         return 0
392 }
393
394 type osversion struct {
395         Debian bool
396         Ubuntu bool
397         Major  int
398 }
399
400 func identifyOS() (osversion, error) {
401         var osv osversion
402         f, err := os.Open("/etc/os-release")
403         if err != nil {
404                 return osv, err
405         }
406         defer f.Close()
407
408         kv := map[string]string{}
409         scanner := bufio.NewScanner(f)
410         for scanner.Scan() {
411                 line := strings.TrimSpace(scanner.Text())
412                 if strings.HasPrefix(line, "#") {
413                         continue
414                 }
415                 toks := strings.SplitN(line, "=", 2)
416                 if len(toks) != 2 {
417                         return osv, fmt.Errorf("invalid line in /etc/os-release: %q", line)
418                 }
419                 k := toks[0]
420                 v := strings.Trim(toks[1], `"`)
421                 if v == toks[1] {
422                         v = strings.Trim(v, `'`)
423                 }
424                 kv[k] = v
425         }
426         if err = scanner.Err(); err != nil {
427                 return osv, err
428         }
429         switch kv["ID"] {
430         case "ubuntu":
431                 osv.Ubuntu = true
432         case "debian":
433                 osv.Debian = true
434         default:
435                 return osv, fmt.Errorf("unsupported ID in /etc/os-release: %q", kv["ID"])
436         }
437         vstr := kv["VERSION_ID"]
438         if i := strings.Index(vstr, "."); i > 0 {
439                 vstr = vstr[:i]
440         }
441         osv.Major, err = strconv.Atoi(vstr)
442         if err != nil {
443                 return osv, fmt.Errorf("incomprehensible VERSION_ID in /etc/os-release: %q", kv["VERSION_ID"])
444         }
445         return osv, nil
446 }
447
448 func waitPostgreSQLReady() error {
449         for deadline := time.Now().Add(10 * time.Second); ; {
450                 output, err := exec.Command("pg_isready").CombinedOutput()
451                 if err == nil {
452                         return nil
453                 } else if time.Now().After(deadline) {
454                         return fmt.Errorf("timed out waiting for pg_isready (%q)", output)
455                 } else {
456                         time.Sleep(time.Second)
457                 }
458         }
459 }
460
461 func runBash(script string, stdout, stderr io.Writer) error {
462         cmd := exec.Command("bash", "-")
463         cmd.Stdin = bytes.NewBufferString("set -ex -o pipefail\n" + script)
464         cmd.Stdout = stdout
465         cmd.Stderr = stderr
466         return cmd.Run()
467 }