12630: Report errors from nvidia-modprobe & use Getenv
[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         "os/user"
18         "path/filepath"
19         "strconv"
20         "strings"
21         "syscall"
22         "time"
23
24         "git.arvados.org/arvados.git/lib/cmd"
25         "git.arvados.org/arvados.git/sdk/go/ctxlog"
26         "github.com/lib/pq"
27 )
28
29 var Command cmd.Handler = &installCommand{}
30
31 const devtestDatabasePassword = "insecure_arvados_test"
32 const goversion = "1.17.1"
33
34 type installCommand struct {
35         ClusterType    string
36         SourcePath     string
37         PackageVersion string
38         EatMyData      bool
39 }
40
41 func (inst *installCommand) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
42         logger := ctxlog.New(stderr, "text", "info")
43         ctx := ctxlog.Context(context.Background(), logger)
44         ctx, cancel := context.WithCancel(ctx)
45         defer cancel()
46
47         var err error
48         defer func() {
49                 if err != nil {
50                         logger.WithError(err).Info("exiting")
51                 }
52         }()
53
54         flags := flag.NewFlagSet(prog, flag.ContinueOnError)
55         flags.SetOutput(stderr)
56         versionFlag := flags.Bool("version", false, "Write version information to stdout and exit 0")
57         flags.StringVar(&inst.ClusterType, "type", "production", "cluster `type`: development, test, production, or package")
58         flags.StringVar(&inst.SourcePath, "source", "/arvados", "source tree location (required for -type=package)")
59         flags.StringVar(&inst.PackageVersion, "package-version", "0.0.0", "version string to embed in executable files")
60         flags.BoolVar(&inst.EatMyData, "eatmydata", false, "use eatmydata to speed up install")
61
62         if ok, code := cmd.ParseFlags(flags, prog, args, "", stderr); !ok {
63                 return code
64         } else if *versionFlag {
65                 return cmd.Version.RunCommand(prog, args, stdin, stdout, stderr)
66         }
67
68         var dev, test, prod, pkg bool
69         switch inst.ClusterType {
70         case "development":
71                 dev = true
72         case "test":
73                 test = true
74         case "production":
75                 prod = true
76         case "package":
77                 pkg = true
78         default:
79                 err = fmt.Errorf("invalid cluster type %q (must be 'development', 'test', 'production', or 'package')", inst.ClusterType)
80                 return 2
81         }
82
83         if prod {
84                 err = errors.New("production install is not yet implemented")
85                 return 1
86         }
87
88         osv, err := identifyOS()
89         if err != nil {
90                 return 1
91         }
92
93         listdir, err := os.Open("/var/lib/apt/lists")
94         if err != nil {
95                 logger.Warnf("error while checking whether to run apt-get update: %s", err)
96         } else if names, _ := listdir.Readdirnames(1); len(names) == 0 {
97                 // Special case for a base docker image where the
98                 // package cache has been deleted and all "apt-get
99                 // install" commands will fail unless we fetch repos.
100                 cmd := exec.CommandContext(ctx, "apt-get", "update")
101                 cmd.Stdout = stdout
102                 cmd.Stderr = stderr
103                 err = cmd.Run()
104                 if err != nil {
105                         return 1
106                 }
107         }
108
109         if inst.EatMyData {
110                 cmd := exec.CommandContext(ctx, "apt-get", "install", "--yes", "--no-install-recommends", "eatmydata")
111                 cmd.Env = append(os.Environ(), "DEBIAN_FRONTEND=noninteractive")
112                 cmd.Stdout = stdout
113                 cmd.Stderr = stderr
114                 err = cmd.Run()
115                 if err != nil {
116                         return 1
117                 }
118         }
119
120         pkgs := prodpkgs(osv)
121
122         if pkg {
123                 pkgs = append(pkgs,
124                         "dpkg-dev",
125                         "eatmydata", // install it for later steps, even if we're not using it now
126                         "rsync",
127                 )
128         }
129
130         if dev || test || pkg {
131                 pkgs = append(pkgs,
132                         "automake",
133                         "bison",
134                         "bsdmainutils",
135                         "build-essential",
136                         "cadaver",
137                         "curl",
138                         "cython3",
139                         "default-jdk-headless",
140                         "default-jre-headless",
141                         "gettext",
142                         "iceweasel",
143                         "libattr1-dev",
144                         "libcrypt-ssleay-perl",
145                         "libfuse-dev",
146                         "libgnutls28-dev",
147                         "libjson-perl",
148                         "libpam-dev",
149                         "libpcre3-dev",
150                         "libpq-dev",
151                         "libreadline-dev",
152                         "libssl-dev",
153                         "libwww-perl",
154                         "libxml2-dev",
155                         "libxslt1-dev",
156                         "linkchecker",
157                         "lsof",
158                         "make",
159                         "net-tools",
160                         "pandoc",
161                         "perl-modules",
162                         "pkg-config",
163                         "postgresql",
164                         "postgresql-contrib",
165                         "python3-dev",
166                         "python3-venv",
167                         "python3-virtualenv",
168                         "r-base",
169                         "r-cran-testthat",
170                         "r-cran-devtools",
171                         "r-cran-knitr",
172                         "r-cran-markdown",
173                         "r-cran-roxygen2",
174                         "r-cran-xml",
175                         "sudo",
176                         "uuid-dev",
177                         "wget",
178                         "xvfb",
179                 )
180                 if dev || test {
181                         pkgs = append(pkgs,
182                                 "squashfs-tools", // for singularity
183                         )
184                 }
185                 switch {
186                 case osv.Debian && osv.Major >= 10:
187                         pkgs = append(pkgs, "libcurl4")
188                 default:
189                         pkgs = append(pkgs, "libcurl3")
190                 }
191                 cmd := exec.CommandContext(ctx, "apt-get")
192                 if inst.EatMyData {
193                         cmd = exec.CommandContext(ctx, "eatmydata", "apt-get")
194                 }
195                 cmd.Args = append(cmd.Args, "install", "--yes", "--no-install-recommends")
196                 cmd.Args = append(cmd.Args, pkgs...)
197                 cmd.Env = append(os.Environ(), "DEBIAN_FRONTEND=noninteractive")
198                 cmd.Stdout = stdout
199                 cmd.Stderr = stderr
200                 err = cmd.Run()
201                 if err != nil {
202                         return 1
203                 }
204         }
205
206         os.Mkdir("/var/lib/arvados", 0755)
207         os.Mkdir("/var/lib/arvados/tmp", 0700)
208         if prod || pkg {
209                 os.Mkdir("/var/lib/arvados/wwwtmp", 0700)
210                 u, er := user.Lookup("www-data")
211                 if er != nil {
212                         err = fmt.Errorf("user.Lookup(%q): %w", "www-data", er)
213                         return 1
214                 }
215                 uid, _ := strconv.Atoi(u.Uid)
216                 gid, _ := strconv.Atoi(u.Gid)
217                 err = os.Chown("/var/lib/arvados/wwwtmp", uid, gid)
218                 if err != nil {
219                         return 1
220                 }
221         }
222         rubyversion := "2.7.2"
223         rubymajorversion := rubyversion[:strings.LastIndex(rubyversion, ".")]
224         if haverubyversion, err := exec.Command("/var/lib/arvados/bin/ruby", "-v").CombinedOutput(); err == nil && bytes.HasPrefix(haverubyversion, []byte("ruby "+rubyversion)) {
225                 logger.Print("ruby " + rubyversion + " already installed")
226         } else {
227                 err = inst.runBash(`
228 tmp="$(mktemp -d)"
229 trap 'rm -r "${tmp}"' ERR EXIT
230 wget --progress=dot:giga -O- https://cache.ruby-lang.org/pub/ruby/`+rubymajorversion+`/ruby-`+rubyversion+`.tar.gz | tar -C "${tmp}" -xzf -
231 cd "${tmp}/ruby-`+rubyversion+`"
232 ./configure --disable-install-static-library --enable-shared --disable-install-doc --prefix /var/lib/arvados
233 make -j8
234 make install
235 /var/lib/arvados/bin/gem install bundler --no-document
236 `, stdout, stderr)
237                 if err != nil {
238                         return 1
239                 }
240         }
241
242         if !prod {
243                 if havegoversion, err := exec.Command("/usr/local/bin/go", "version").CombinedOutput(); err == nil && bytes.HasPrefix(havegoversion, []byte("go version go"+goversion+" ")) {
244                         logger.Print("go " + goversion + " already installed")
245                 } else {
246                         err = inst.runBash(`
247 cd /tmp
248 rm -rf /var/lib/arvados/go/
249 wget --progress=dot:giga -O- https://storage.googleapis.com/golang/go`+goversion+`.linux-amd64.tar.gz | tar -C /var/lib/arvados -xzf -
250 ln -sf /var/lib/arvados/go/bin/* /usr/local/bin/
251 `, stdout, stderr)
252                         if err != nil {
253                                 return 1
254                         }
255                 }
256         }
257
258         if !prod && !pkg {
259                 pjsversion := "1.9.8"
260                 if havepjsversion, err := exec.Command("/usr/local/bin/phantomjs", "--version").CombinedOutput(); err == nil && string(havepjsversion) == "1.9.8\n" {
261                         logger.Print("phantomjs " + pjsversion + " already installed")
262                 } else {
263                         err = inst.runBash(`
264 PJS=phantomjs-`+pjsversion+`-linux-x86_64
265 wget --progress=dot:giga -O- https://bitbucket.org/ariya/phantomjs/downloads/$PJS.tar.bz2 | tar -C /var/lib/arvados -xjf -
266 ln -sf /var/lib/arvados/$PJS/bin/phantomjs /usr/local/bin/
267 `, stdout, stderr)
268                         if err != nil {
269                                 return 1
270                         }
271                 }
272
273                 geckoversion := "0.24.0"
274                 if havegeckoversion, err := exec.Command("/usr/local/bin/geckodriver", "--version").CombinedOutput(); err == nil && strings.Contains(string(havegeckoversion), " "+geckoversion+" ") {
275                         logger.Print("geckodriver " + geckoversion + " already installed")
276                 } else {
277                         err = inst.runBash(`
278 GD=v`+geckoversion+`
279 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
280 ln -sf /var/lib/arvados/bin/geckodriver /usr/local/bin/
281 `, stdout, stderr)
282                         if err != nil {
283                                 return 1
284                         }
285                 }
286
287                 nodejsversion := "v12.22.2"
288                 if havenodejsversion, err := exec.Command("/usr/local/bin/node", "--version").CombinedOutput(); err == nil && string(havenodejsversion) == nodejsversion+"\n" {
289                         logger.Print("nodejs " + nodejsversion + " already installed")
290                 } else {
291                         err = inst.runBash(`
292 NJS=`+nodejsversion+`
293 wget --progress=dot:giga -O- https://nodejs.org/dist/${NJS}/node-${NJS}-linux-x64.tar.xz | sudo tar -C /var/lib/arvados -xJf -
294 ln -sf /var/lib/arvados/node-${NJS}-linux-x64/bin/{node,npm} /usr/local/bin/
295 `, stdout, stderr)
296                         if err != nil {
297                                 return 1
298                         }
299                 }
300
301                 gradleversion := "5.3.1"
302                 if havegradleversion, err := exec.Command("/usr/local/bin/gradle", "--version").CombinedOutput(); err == nil && strings.Contains(string(havegradleversion), "Gradle "+gradleversion+"\n") {
303                         logger.Print("gradle " + gradleversion + " already installed")
304                 } else {
305                         err = inst.runBash(`
306 G=`+gradleversion+`
307 zip=/var/lib/arvados/tmp/gradle-${G}-bin.zip
308 trap "rm ${zip}" ERR
309 wget --progress=dot:giga -O${zip} https://services.gradle.org/distributions/gradle-${G}-bin.zip
310 unzip -o -d /var/lib/arvados ${zip}
311 ln -sf /var/lib/arvados/gradle-${G}/bin/gradle /usr/local/bin/
312 rm ${zip}
313 `, stdout, stderr)
314                         if err != nil {
315                                 return 1
316                         }
317                 }
318
319                 singularityversion := "3.7.4"
320                 if havesingularityversion, err := exec.Command("/var/lib/arvados/bin/singularity", "--version").CombinedOutput(); err == nil && strings.Contains(string(havesingularityversion), singularityversion) {
321                         logger.Print("singularity " + singularityversion + " already installed")
322                 } else if dev || test {
323                         err = inst.runBash(`
324 S=`+singularityversion+`
325 tmp=/var/lib/arvados/tmp/singularity
326 trap "rm -r ${tmp}" ERR EXIT
327 cd /var/lib/arvados/tmp
328 git clone https://github.com/sylabs/singularity
329 cd singularity
330 git checkout v${S}
331 ./mconfig --prefix=/var/lib/arvados
332 make -C ./builddir
333 make -C ./builddir install
334 `, stdout, stderr)
335                         if err != nil {
336                                 return 1
337                         }
338                 }
339
340                 // The entry in /etc/locale.gen is "en_US.UTF-8"; once
341                 // it's installed, locale -a reports it as
342                 // "en_US.utf8".
343                 wantlocale := "en_US.UTF-8"
344                 if havelocales, err := exec.Command("locale", "-a").CombinedOutput(); err == nil && bytes.Contains(havelocales, []byte(strings.Replace(wantlocale+"\n", "UTF-", "utf", 1))) {
345                         logger.Print("locale " + wantlocale + " already installed")
346                 } else {
347                         err = inst.runBash(`sed -i 's/^# *\(`+wantlocale+`\)/\1/' /etc/locale.gen && locale-gen`, stdout, stderr)
348                         if err != nil {
349                                 return 1
350                         }
351                 }
352
353                 var pgc struct {
354                         Version       string
355                         Cluster       string
356                         Port          int
357                         Status        string
358                         Owner         string
359                         DataDirectory string
360                         LogFile       string
361                 }
362                 if pgLsclusters, err2 := exec.Command("pg_lsclusters", "--no-header").CombinedOutput(); err2 != nil {
363                         err = fmt.Errorf("pg_lsclusters: %s", err2)
364                         return 1
365                 } else if pgclusters := strings.Split(strings.TrimSpace(string(pgLsclusters)), "\n"); len(pgclusters) != 1 {
366                         logger.Warnf("pg_lsclusters returned %d postgresql clusters -- skipping postgresql initdb/startup, hope that's ok", len(pgclusters))
367                 } 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 {
368                         err = fmt.Errorf("error parsing pg_lsclusters output: %s", err)
369                         return 1
370                 } else if pgc.Status == "online" {
371                         logger.Infof("postgresql cluster %s-%s is online", pgc.Version, pgc.Cluster)
372                 } else {
373                         logger.Infof("postgresql cluster %s-%s is %s; trying to start", pgc.Version, pgc.Cluster, pgc.Status)
374                         cmd := exec.Command("pg_ctlcluster", "--foreground", pgc.Version, pgc.Cluster, "start")
375                         cmd.Stdout = stdout
376                         cmd.Stderr = stderr
377                         err = cmd.Start()
378                         if err != nil {
379                                 return 1
380                         }
381                         defer func() {
382                                 cmd.Process.Signal(syscall.SIGTERM)
383                                 logger.Info("sent SIGTERM; waiting for postgres to shut down")
384                                 cmd.Wait()
385                         }()
386                         err = waitPostgreSQLReady()
387                         if err != nil {
388                                 return 1
389                         }
390                 }
391
392                 if os.Getpid() == 1 {
393                         // We are the init process (presumably in a
394                         // docker container) so although postgresql is
395                         // installed, it's not running, and initdb
396                         // might never have been run.
397                 }
398
399                 var needcoll []string
400                 // If the en_US.UTF-8 locale wasn't installed when
401                 // postgresql initdb ran, it needs to be added
402                 // explicitly before we can use it in our test suite.
403                 for _, collname := range []string{"en_US", "en_US.UTF-8"} {
404                         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')")
405                         cmd.Dir = "/"
406                         out, err2 := cmd.CombinedOutput()
407                         if err != nil {
408                                 err = fmt.Errorf("error while checking postgresql collations: %s", err2)
409                                 return 1
410                         }
411                         if strings.Contains(string(out), "1") {
412                                 logger.Infof("postgresql supports collation %s", collname)
413                         } else {
414                                 needcoll = append(needcoll, collname)
415                         }
416                 }
417                 if len(needcoll) > 0 && os.Getpid() != 1 {
418                         // In order for the CREATE COLLATION statement
419                         // below to work, the locale must have existed
420                         // when PostgreSQL started up. If we're
421                         // running as init, we must have started
422                         // PostgreSQL ourselves after installing the
423                         // locales. Otherwise, it might need a
424                         // restart, so we attempt to restart it with
425                         // systemd.
426                         if err = inst.runBash(`sudo systemctl restart postgresql`, stdout, stderr); err != nil {
427                                 logger.Warn("`systemctl restart postgresql` failed; hoping postgresql does not need to be restarted")
428                         } else if err = waitPostgreSQLReady(); err != nil {
429                                 return 1
430                         }
431                 }
432                 for _, collname := range needcoll {
433                         cmd := exec.Command("sudo", "-u", "postgres", "psql", "-c", "CREATE COLLATION \""+collname+"\" (LOCALE = \"en_US.UTF-8\")")
434                         cmd.Stdout = stdout
435                         cmd.Stderr = stderr
436                         cmd.Dir = "/"
437                         err = cmd.Run()
438                         if err != nil {
439                                 err = fmt.Errorf("error adding postgresql collation %s: %s", collname, err)
440                                 return 1
441                         }
442                 }
443
444                 withstuff := "WITH LOGIN SUPERUSER ENCRYPTED PASSWORD " + pq.QuoteLiteral(devtestDatabasePassword)
445                 cmd := exec.Command("sudo", "-u", "postgres", "psql", "-c", "ALTER ROLE arvados "+withstuff)
446                 cmd.Dir = "/"
447                 if err := cmd.Run(); err == nil {
448                         logger.Print("arvados role exists; superuser privileges added, password updated")
449                 } else {
450                         cmd := exec.Command("sudo", "-u", "postgres", "psql", "-c", "CREATE ROLE arvados "+withstuff)
451                         cmd.Dir = "/"
452                         cmd.Stdout = stdout
453                         cmd.Stderr = stderr
454                         err = cmd.Run()
455                         if err != nil {
456                                 return 1
457                         }
458                 }
459         }
460
461         if prod || pkg {
462                 // Install Rails apps to /var/lib/arvados/{railsapi,workbench1}/
463                 for dstdir, srcdir := range map[string]string{
464                         "railsapi":   "services/api",
465                         "workbench1": "apps/workbench",
466                 } {
467                         fmt.Fprintf(stderr, "building %s...\n", srcdir)
468                         cmd := exec.Command("rsync",
469                                 "-a", "--no-owner", "--no-group", "--delete-after", "--delete-excluded",
470                                 "--exclude", "/coverage",
471                                 "--exclude", "/log",
472                                 "--exclude", "/tmp",
473                                 "--exclude", "/vendor",
474                                 "--exclude", "/config/environments",
475                                 "./", "/var/lib/arvados/"+dstdir+"/")
476                         cmd.Dir = filepath.Join(inst.SourcePath, srcdir)
477                         cmd.Stdout = stdout
478                         cmd.Stderr = stderr
479                         err = cmd.Run()
480                         if err != nil {
481                                 return 1
482                         }
483                         for _, cmdline := range [][]string{
484                                 {"mkdir", "-p", "log", "tmp", ".bundle", "/var/www/.gem", "/var/www/.bundle", "/var/www/.passenger"},
485                                 {"touch", "log/production.log"},
486                                 {"chown", "-R", "--from=root", "www-data:www-data", "/var/www/.gem", "/var/www/.bundle", "/var/www/.passenger", "log", "tmp", ".bundle", "Gemfile.lock", "config.ru", "config/environment.rb"},
487                                 {"sudo", "-u", "www-data", "/var/lib/arvados/bin/gem", "install", "--user", "--conservative", "--no-document", "bundler:2.2.19"},
488                                 {"sudo", "-u", "www-data", "/var/lib/arvados/bin/bundle", "install", "--deployment", "--jobs", "8", "--path", "/var/www/.gem"},
489                                 {"sudo", "-u", "www-data", "/var/lib/arvados/bin/bundle", "exec", "passenger-config", "build-native-support"},
490                                 {"sudo", "-u", "www-data", "/var/lib/arvados/bin/bundle", "exec", "passenger-config", "install-standalone-runtime"},
491                         } {
492                                 cmd = exec.Command(cmdline[0], cmdline[1:]...)
493                                 cmd.Dir = "/var/lib/arvados/" + dstdir
494                                 cmd.Stdout = stdout
495                                 cmd.Stderr = stderr
496                                 fmt.Fprintf(stderr, "... %s\n", cmd.Args)
497                                 err = cmd.Run()
498                                 if err != nil {
499                                         return 1
500                                 }
501                         }
502                         cmd = exec.Command("sudo", "-u", "www-data", "/var/lib/arvados/bin/bundle", "exec", "passenger-config", "validate-install")
503                         cmd.Dir = "/var/lib/arvados/" + dstdir
504                         cmd.Stdout = stdout
505                         cmd.Stderr = stderr
506                         err = cmd.Run()
507                         if err != nil && !strings.Contains(err.Error(), "exit status 2") {
508                                 // Exit code 2 indicates there were warnings (like
509                                 // "other passenger installations have been detected",
510                                 // which we can't expect to avoid) but no errors.
511                                 // Other non-zero exit codes (1, 9) indicate errors.
512                                 return 1
513                         }
514                 }
515
516                 // Install Go programs to /var/lib/arvados/bin/
517                 for _, srcdir := range []string{
518                         "cmd/arvados-client",
519                         "cmd/arvados-server",
520                         "services/arv-git-httpd",
521                         "services/crunch-dispatch-local",
522                         "services/crunch-dispatch-slurm",
523                         "services/health",
524                         "services/keep-balance",
525                         "services/keep-web",
526                         "services/keepproxy",
527                         "services/keepstore",
528                         "services/ws",
529                 } {
530                         fmt.Fprintf(stderr, "building %s...\n", srcdir)
531                         cmd := exec.Command("go", "install", "-ldflags", "-X git.arvados.org/arvados.git/lib/cmd.version="+inst.PackageVersion+" -X main.version="+inst.PackageVersion)
532                         cmd.Env = append(cmd.Env, os.Environ()...)
533                         cmd.Env = append(cmd.Env, "GOBIN=/var/lib/arvados/bin")
534                         cmd.Dir = filepath.Join(inst.SourcePath, srcdir)
535                         cmd.Stdout = stdout
536                         cmd.Stderr = stderr
537                         err = cmd.Run()
538                         if err != nil {
539                                 return 1
540                         }
541                 }
542
543                 // Copy assets from source tree to /var/lib/arvados/share
544                 cmd := exec.Command("install", "-v", "-t", "/var/lib/arvados/share", filepath.Join(inst.SourcePath, "sdk/python/tests/nginx.conf"))
545                 cmd.Stdout = stdout
546                 cmd.Stderr = stderr
547                 err = cmd.Run()
548                 if err != nil {
549                         return 1
550                 }
551         }
552
553         return 0
554 }
555
556 type osversion struct {
557         Debian bool
558         Ubuntu bool
559         Centos bool
560         Major  int
561 }
562
563 func identifyOS() (osversion, error) {
564         var osv osversion
565         f, err := os.Open("/etc/os-release")
566         if err != nil {
567                 return osv, err
568         }
569         defer f.Close()
570
571         kv := map[string]string{}
572         scanner := bufio.NewScanner(f)
573         for scanner.Scan() {
574                 line := strings.TrimSpace(scanner.Text())
575                 if strings.HasPrefix(line, "#") {
576                         continue
577                 }
578                 toks := strings.SplitN(line, "=", 2)
579                 if len(toks) != 2 {
580                         return osv, fmt.Errorf("invalid line in /etc/os-release: %q", line)
581                 }
582                 k := toks[0]
583                 v := strings.Trim(toks[1], `"`)
584                 if v == toks[1] {
585                         v = strings.Trim(v, `'`)
586                 }
587                 kv[k] = v
588         }
589         if err = scanner.Err(); err != nil {
590                 return osv, err
591         }
592         switch kv["ID"] {
593         case "ubuntu":
594                 osv.Ubuntu = true
595         case "debian":
596                 osv.Debian = true
597         case "centos":
598                 osv.Centos = true
599         default:
600                 return osv, fmt.Errorf("unsupported ID in /etc/os-release: %q", kv["ID"])
601         }
602         vstr := kv["VERSION_ID"]
603         if i := strings.Index(vstr, "."); i > 0 {
604                 vstr = vstr[:i]
605         }
606         osv.Major, err = strconv.Atoi(vstr)
607         if err != nil {
608                 return osv, fmt.Errorf("incomprehensible VERSION_ID in /etc/os-release: %q", kv["VERSION_ID"])
609         }
610         return osv, nil
611 }
612
613 func waitPostgreSQLReady() error {
614         for deadline := time.Now().Add(10 * time.Second); ; {
615                 output, err := exec.Command("pg_isready").CombinedOutput()
616                 if err == nil {
617                         return nil
618                 } else if time.Now().After(deadline) {
619                         return fmt.Errorf("timed out waiting for pg_isready (%q)", output)
620                 } else {
621                         time.Sleep(time.Second)
622                 }
623         }
624 }
625
626 func (inst *installCommand) runBash(script string, stdout, stderr io.Writer) error {
627         cmd := exec.Command("bash", "-")
628         if inst.EatMyData {
629                 cmd = exec.Command("eatmydata", "bash", "-")
630         }
631         cmd.Stdin = bytes.NewBufferString("set -ex -o pipefail\n" + script)
632         cmd.Stdout = stdout
633         cmd.Stderr = stderr
634         return cmd.Run()
635 }
636
637 func prodpkgs(osv osversion) []string {
638         pkgs := []string{
639                 "ca-certificates",
640                 "curl",
641                 "fuse",
642                 "git",
643                 "gitolite3",
644                 "graphviz",
645                 "haveged",
646                 "libcurl3-gnutls",
647                 "libxslt1.1",
648                 "nginx",
649                 "python",
650                 "sudo",
651         }
652         if osv.Debian || osv.Ubuntu {
653                 if osv.Debian && osv.Major == 8 {
654                         pkgs = append(pkgs, "libgnutls-deb0-28") // sdk/cwl
655                 } else if osv.Debian && osv.Major >= 10 || osv.Ubuntu && osv.Major >= 16 {
656                         pkgs = append(pkgs, "python3-distutils") // sdk/cwl
657                 }
658                 return append(pkgs,
659                         "g++",
660                         "libcurl4-openssl-dev", // services/api
661                         "libpq-dev",
662                         "libpython2.7", // services/fuse
663                         "mime-support", // keep-web
664                         "zlib1g-dev",   // services/api
665                 )
666         } else if osv.Centos {
667                 return append(pkgs,
668                         "fuse-libs", // services/fuse
669                         "gcc",
670                         "gcc-c++",
671                         "libcurl-devel",    // services/api
672                         "mailcap",          // keep-web
673                         "postgresql-devel", // services/api
674                 )
675         } else {
676                 panic("os version not supported")
677         }
678 }
679
680 func ProductionDependencies() ([]string, error) {
681         osv, err := identifyOS()
682         if err != nil {
683                 return nil, err
684         }
685         return prodpkgs(osv), nil
686 }