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