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