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