16053: Error out on unimplemented install in production mode.
[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.Infof("sent SIGTERM; waiting for postgres to shut down")
315                                 cmd.Wait()
316                         }()
317                         for deadline := time.Now().Add(10 * time.Second); ; {
318                                 output, err2 := exec.Command("pg_isready").CombinedOutput()
319                                 if err2 == nil {
320                                         break
321                                 } else if time.Now().After(deadline) {
322                                         err = fmt.Errorf("timed out waiting for pg_isready (%q)", output)
323                                         return 1
324                                 } else {
325                                         time.Sleep(time.Second)
326                                 }
327                         }
328                 }
329
330                 if os.Getpid() == 1 {
331                         // We are the init process (presumably in a
332                         // docker container) so although postgresql is
333                         // installed, it's not running, and initdb
334                         // might never have been run.
335                 }
336
337                 withstuff := "WITH LOGIN SUPERUSER ENCRYPTED PASSWORD " + pq.QuoteLiteral(devtestDatabasePassword)
338                 cmd := exec.Command("sudo", "-u", "postgres", "psql", "-c", "ALTER ROLE arvados "+withstuff)
339                 cmd.Dir = "/"
340                 if err := cmd.Run(); err == nil {
341                         logger.Print("arvados role exists; superuser privileges added, password updated")
342                 } else {
343                         cmd := exec.Command("sudo", "-u", "postgres", "psql", "-c", "CREATE ROLE arvados "+withstuff)
344                         cmd.Dir = "/"
345                         cmd.Stdout = stdout
346                         cmd.Stderr = stderr
347                         err = cmd.Run()
348                         if err != nil {
349                                 return 1
350                         }
351                 }
352         }
353
354         return 0
355 }
356
357 type osversion struct {
358         Debian bool
359         Ubuntu bool
360         Major  int
361 }
362
363 func identifyOS() (osversion, error) {
364         var osv osversion
365         f, err := os.Open("/etc/os-release")
366         if err != nil {
367                 return osv, err
368         }
369         defer f.Close()
370
371         kv := map[string]string{}
372         scanner := bufio.NewScanner(f)
373         for scanner.Scan() {
374                 line := strings.TrimSpace(scanner.Text())
375                 if strings.HasPrefix(line, "#") {
376                         continue
377                 }
378                 toks := strings.SplitN(line, "=", 2)
379                 if len(toks) != 2 {
380                         return osv, fmt.Errorf("invalid line in /etc/os-release: %q", line)
381                 }
382                 k := toks[0]
383                 v := strings.Trim(toks[1], `"`)
384                 if v == toks[1] {
385                         v = strings.Trim(v, `'`)
386                 }
387                 kv[k] = v
388         }
389         if err = scanner.Err(); err != nil {
390                 return osv, err
391         }
392         switch kv["ID"] {
393         case "ubuntu":
394                 osv.Ubuntu = true
395         case "debian":
396                 osv.Debian = true
397         default:
398                 return osv, fmt.Errorf("unsupported ID in /etc/os-release: %q", kv["ID"])
399         }
400         vstr := kv["VERSION_ID"]
401         if i := strings.Index(vstr, "."); i > 0 {
402                 vstr = vstr[:i]
403         }
404         osv.Major, err = strconv.Atoi(vstr)
405         if err != nil {
406                 return osv, fmt.Errorf("incomprehensible VERSION_ID in /etc/os/release: %q", kv["VERSION_ID"])
407         }
408         return osv, nil
409 }
410
411 func runBash(script string, stdout, stderr io.Writer) error {
412         cmd := exec.Command("bash", "-")
413         cmd.Stdin = bytes.NewBufferString("set -ex -o pipefail\n" + script)
414         cmd.Stdout = stdout
415         cmd.Stderr = stderr
416         return cmd.Run()
417 }