Merge branch '17782-nodejs-update' into main
[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                         "uuid-dev",
182                         "wget",
183                         "xvfb",
184                 )
185                 if dev || test {
186                         pkgs = append(pkgs,
187                                 "squashfs-tools", // for singularity
188                         )
189                 }
190                 switch {
191                 case osv.Debian && osv.Major >= 10:
192                         pkgs = append(pkgs, "libcurl4")
193                 default:
194                         pkgs = append(pkgs, "libcurl3")
195                 }
196                 cmd := exec.CommandContext(ctx, "apt-get")
197                 if inst.EatMyData {
198                         cmd = exec.CommandContext(ctx, "eatmydata", "apt-get")
199                 }
200                 cmd.Args = append(cmd.Args, "install", "--yes", "--no-install-recommends")
201                 cmd.Args = append(cmd.Args, pkgs...)
202                 cmd.Env = append(os.Environ(), "DEBIAN_FRONTEND=noninteractive")
203                 cmd.Stdout = stdout
204                 cmd.Stderr = stderr
205                 err = cmd.Run()
206                 if err != nil {
207                         return 1
208                 }
209         }
210
211         os.Mkdir("/var/lib/arvados", 0755)
212         os.Mkdir("/var/lib/arvados/tmp", 0700)
213         if prod || pkg {
214                 os.Mkdir("/var/lib/arvados/wwwtmp", 0700)
215                 u, er := user.Lookup("www-data")
216                 if er != nil {
217                         err = fmt.Errorf("user.Lookup(%q): %w", "www-data", er)
218                         return 1
219                 }
220                 uid, _ := strconv.Atoi(u.Uid)
221                 gid, _ := strconv.Atoi(u.Gid)
222                 err = os.Chown("/var/lib/arvados/wwwtmp", uid, gid)
223                 if err != nil {
224                         return 1
225                 }
226         }
227         rubyversion := "2.7.2"
228         rubymajorversion := rubyversion[:strings.LastIndex(rubyversion, ".")]
229         if haverubyversion, err := exec.Command("/var/lib/arvados/bin/ruby", "-v").CombinedOutput(); err == nil && bytes.HasPrefix(haverubyversion, []byte("ruby "+rubyversion)) {
230                 logger.Print("ruby " + rubyversion + " already installed")
231         } else {
232                 err = inst.runBash(`
233 tmp="$(mktemp -d)"
234 trap 'rm -r "${tmp}"' ERR EXIT
235 wget --progress=dot:giga -O- https://cache.ruby-lang.org/pub/ruby/`+rubymajorversion+`/ruby-`+rubyversion+`.tar.gz | tar -C "${tmp}" -xzf -
236 cd "${tmp}/ruby-`+rubyversion+`"
237 ./configure --disable-install-static-library --enable-shared --disable-install-doc --prefix /var/lib/arvados
238 make -j8
239 make install
240 /var/lib/arvados/bin/gem install bundler --no-document
241 `, stdout, stderr)
242                 if err != nil {
243                         return 1
244                 }
245         }
246
247         if !prod {
248                 goversion := "1.16.3"
249                 if havegoversion, err := exec.Command("/usr/local/bin/go", "version").CombinedOutput(); err == nil && bytes.HasPrefix(havegoversion, []byte("go version go"+goversion+" ")) {
250                         logger.Print("go " + goversion + " already installed")
251                 } else {
252                         err = inst.runBash(`
253 cd /tmp
254 rm -rf /var/lib/arvados/go/
255 wget --progress=dot:giga -O- https://storage.googleapis.com/golang/go`+goversion+`.linux-amd64.tar.gz | tar -C /var/lib/arvados -xzf -
256 ln -sf /var/lib/arvados/go/bin/* /usr/local/bin/
257 `, stdout, stderr)
258                         if err != nil {
259                                 return 1
260                         }
261                 }
262         }
263
264         if !prod && !pkg {
265                 pjsversion := "1.9.8"
266                 if havepjsversion, err := exec.Command("/usr/local/bin/phantomjs", "--version").CombinedOutput(); err == nil && string(havepjsversion) == "1.9.8\n" {
267                         logger.Print("phantomjs " + pjsversion + " already installed")
268                 } else {
269                         err = inst.runBash(`
270 PJS=phantomjs-`+pjsversion+`-linux-x86_64
271 wget --progress=dot:giga -O- https://bitbucket.org/ariya/phantomjs/downloads/$PJS.tar.bz2 | tar -C /var/lib/arvados -xjf -
272 ln -sf /var/lib/arvados/$PJS/bin/phantomjs /usr/local/bin/
273 `, stdout, stderr)
274                         if err != nil {
275                                 return 1
276                         }
277                 }
278
279                 geckoversion := "0.24.0"
280                 if havegeckoversion, err := exec.Command("/usr/local/bin/geckodriver", "--version").CombinedOutput(); err == nil && strings.Contains(string(havegeckoversion), " "+geckoversion+" ") {
281                         logger.Print("geckodriver " + geckoversion + " already installed")
282                 } else {
283                         err = inst.runBash(`
284 GD=v`+geckoversion+`
285 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
286 ln -sf /var/lib/arvados/bin/geckodriver /usr/local/bin/
287 `, stdout, stderr)
288                         if err != nil {
289                                 return 1
290                         }
291                 }
292
293                 nodejsversion := "v12.22.2"
294                 if havenodejsversion, err := exec.Command("/usr/local/bin/node", "--version").CombinedOutput(); err == nil && string(havenodejsversion) == nodejsversion+"\n" {
295                         logger.Print("nodejs " + nodejsversion + " already installed")
296                 } else {
297                         err = inst.runBash(`
298 NJS=`+nodejsversion+`
299 wget --progress=dot:giga -O- https://nodejs.org/dist/${NJS}/node-${NJS}-linux-x64.tar.xz | sudo tar -C /var/lib/arvados -xJf -
300 ln -sf /var/lib/arvados/node-${NJS}-linux-x64/bin/{node,npm} /usr/local/bin/
301 `, stdout, stderr)
302                         if err != nil {
303                                 return 1
304                         }
305                 }
306
307                 gradleversion := "5.3.1"
308                 if havegradleversion, err := exec.Command("/usr/local/bin/gradle", "--version").CombinedOutput(); err == nil && strings.Contains(string(havegradleversion), "Gradle "+gradleversion+"\n") {
309                         logger.Print("gradle " + gradleversion + " already installed")
310                 } else {
311                         err = inst.runBash(`
312 G=`+gradleversion+`
313 zip=/var/lib/arvados/tmp/gradle-${G}-bin.zip
314 trap "rm ${zip}" ERR
315 wget --progress=dot:giga -O${zip} https://services.gradle.org/distributions/gradle-${G}-bin.zip
316 unzip -o -d /var/lib/arvados ${zip}
317 ln -sf /var/lib/arvados/gradle-${G}/bin/gradle /usr/local/bin/
318 rm ${zip}
319 `, stdout, stderr)
320                         if err != nil {
321                                 return 1
322                         }
323                 }
324
325                 singularityversion := "3.5.2"
326                 if havesingularityversion, err := exec.Command("/var/lib/arvados/bin/singularity", "--version").CombinedOutput(); err == nil && strings.Contains(string(havesingularityversion), singularityversion) {
327                         logger.Print("singularity " + singularityversion + " already installed")
328                 } else if dev || test {
329                         err = inst.runBash(`
330 S=`+singularityversion+`
331 tmp=/var/lib/arvados/tmp/singularity
332 trap "rm -r ${tmp}" ERR EXIT
333 cd /var/lib/arvados/tmp
334 git clone https://github.com/sylabs/singularity
335 cd singularity
336 git checkout v${S}
337 ./mconfig --prefix=/var/lib/arvados
338 make -C ./builddir
339 make -C ./builddir install
340 `, stdout, stderr)
341                         if err != nil {
342                                 return 1
343                         }
344                 }
345
346                 // The entry in /etc/locale.gen is "en_US.UTF-8"; once
347                 // it's installed, locale -a reports it as
348                 // "en_US.utf8".
349                 wantlocale := "en_US.UTF-8"
350                 if havelocales, err := exec.Command("locale", "-a").CombinedOutput(); err == nil && bytes.Contains(havelocales, []byte(strings.Replace(wantlocale+"\n", "UTF-", "utf", 1))) {
351                         logger.Print("locale " + wantlocale + " already installed")
352                 } else {
353                         err = inst.runBash(`sed -i 's/^# *\(`+wantlocale+`\)/\1/' /etc/locale.gen && locale-gen`, stdout, stderr)
354                         if err != nil {
355                                 return 1
356                         }
357                 }
358
359                 var pgc struct {
360                         Version       string
361                         Cluster       string
362                         Port          int
363                         Status        string
364                         Owner         string
365                         DataDirectory string
366                         LogFile       string
367                 }
368                 if pgLsclusters, err2 := exec.Command("pg_lsclusters", "--no-header").CombinedOutput(); err2 != nil {
369                         err = fmt.Errorf("pg_lsclusters: %s", err2)
370                         return 1
371                 } else if pgclusters := strings.Split(strings.TrimSpace(string(pgLsclusters)), "\n"); len(pgclusters) != 1 {
372                         logger.Warnf("pg_lsclusters returned %d postgresql clusters -- skipping postgresql initdb/startup, hope that's ok", len(pgclusters))
373                 } 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 {
374                         err = fmt.Errorf("error parsing pg_lsclusters output: %s", err)
375                         return 1
376                 } else if pgc.Status == "online" {
377                         logger.Infof("postgresql cluster %s-%s is online", pgc.Version, pgc.Cluster)
378                 } else {
379                         logger.Infof("postgresql cluster %s-%s is %s; trying to start", pgc.Version, pgc.Cluster, pgc.Status)
380                         cmd := exec.Command("pg_ctlcluster", "--foreground", pgc.Version, pgc.Cluster, "start")
381                         cmd.Stdout = stdout
382                         cmd.Stderr = stderr
383                         err = cmd.Start()
384                         if err != nil {
385                                 return 1
386                         }
387                         defer func() {
388                                 cmd.Process.Signal(syscall.SIGTERM)
389                                 logger.Info("sent SIGTERM; waiting for postgres to shut down")
390                                 cmd.Wait()
391                         }()
392                         err = waitPostgreSQLReady()
393                         if err != nil {
394                                 return 1
395                         }
396                 }
397
398                 if os.Getpid() == 1 {
399                         // We are the init process (presumably in a
400                         // docker container) so although postgresql is
401                         // installed, it's not running, and initdb
402                         // might never have been run.
403                 }
404
405                 var needcoll []string
406                 // If the en_US.UTF-8 locale wasn't installed when
407                 // postgresql initdb ran, it needs to be added
408                 // explicitly before we can use it in our test suite.
409                 for _, collname := range []string{"en_US", "en_US.UTF-8"} {
410                         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')")
411                         cmd.Dir = "/"
412                         out, err2 := cmd.CombinedOutput()
413                         if err != nil {
414                                 err = fmt.Errorf("error while checking postgresql collations: %s", err2)
415                                 return 1
416                         }
417                         if strings.Contains(string(out), "1") {
418                                 logger.Infof("postgresql supports collation %s", collname)
419                         } else {
420                                 needcoll = append(needcoll, collname)
421                         }
422                 }
423                 if len(needcoll) > 0 && os.Getpid() != 1 {
424                         // In order for the CREATE COLLATION statement
425                         // below to work, the locale must have existed
426                         // when PostgreSQL started up. If we're
427                         // running as init, we must have started
428                         // PostgreSQL ourselves after installing the
429                         // locales. Otherwise, it might need a
430                         // restart, so we attempt to restart it with
431                         // systemd.
432                         if err = inst.runBash(`sudo systemctl restart postgresql`, stdout, stderr); err != nil {
433                                 logger.Warn("`systemctl restart postgresql` failed; hoping postgresql does not need to be restarted")
434                         } else if err = waitPostgreSQLReady(); err != nil {
435                                 return 1
436                         }
437                 }
438                 for _, collname := range needcoll {
439                         cmd := exec.Command("sudo", "-u", "postgres", "psql", "-c", "CREATE COLLATION \""+collname+"\" (LOCALE = \"en_US.UTF-8\")")
440                         cmd.Stdout = stdout
441                         cmd.Stderr = stderr
442                         cmd.Dir = "/"
443                         err = cmd.Run()
444                         if err != nil {
445                                 err = fmt.Errorf("error adding postgresql collation %s: %s", collname, err)
446                                 return 1
447                         }
448                 }
449
450                 withstuff := "WITH LOGIN SUPERUSER ENCRYPTED PASSWORD " + pq.QuoteLiteral(devtestDatabasePassword)
451                 cmd := exec.Command("sudo", "-u", "postgres", "psql", "-c", "ALTER ROLE arvados "+withstuff)
452                 cmd.Dir = "/"
453                 if err := cmd.Run(); err == nil {
454                         logger.Print("arvados role exists; superuser privileges added, password updated")
455                 } else {
456                         cmd := exec.Command("sudo", "-u", "postgres", "psql", "-c", "CREATE ROLE arvados "+withstuff)
457                         cmd.Dir = "/"
458                         cmd.Stdout = stdout
459                         cmd.Stderr = stderr
460                         err = cmd.Run()
461                         if err != nil {
462                                 return 1
463                         }
464                 }
465         }
466
467         if prod || pkg {
468                 // Install Rails apps to /var/lib/arvados/{railsapi,workbench1}/
469                 for dstdir, srcdir := range map[string]string{
470                         "railsapi":   "services/api",
471                         "workbench1": "apps/workbench",
472                 } {
473                         fmt.Fprintf(stderr, "building %s...\n", srcdir)
474                         cmd := exec.Command("rsync",
475                                 "-a", "--no-owner", "--no-group", "--delete-after", "--delete-excluded",
476                                 "--exclude", "/coverage",
477                                 "--exclude", "/log",
478                                 "--exclude", "/tmp",
479                                 "--exclude", "/vendor",
480                                 "--exclude", "/config/environments",
481                                 "./", "/var/lib/arvados/"+dstdir+"/")
482                         cmd.Dir = filepath.Join(inst.SourcePath, srcdir)
483                         cmd.Stdout = stdout
484                         cmd.Stderr = stderr
485                         err = cmd.Run()
486                         if err != nil {
487                                 return 1
488                         }
489                         for _, cmdline := range [][]string{
490                                 {"mkdir", "-p", "log", "tmp", ".bundle", "/var/www/.gem", "/var/www/.bundle", "/var/www/.passenger"},
491                                 {"touch", "log/production.log"},
492                                 {"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"},
493                                 {"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"},
494                                 {"sudo", "-u", "www-data", "/var/lib/arvados/bin/bundle", "install", "--deployment", "--jobs", "8", "--path", "/var/www/.gem"},
495                                 {"sudo", "-u", "www-data", "/var/lib/arvados/bin/bundle", "exec", "passenger-config", "build-native-support"},
496                                 {"sudo", "-u", "www-data", "/var/lib/arvados/bin/bundle", "exec", "passenger-config", "install-standalone-runtime"},
497                         } {
498                                 cmd = exec.Command(cmdline[0], cmdline[1:]...)
499                                 cmd.Dir = "/var/lib/arvados/" + dstdir
500                                 cmd.Stdout = stdout
501                                 cmd.Stderr = stderr
502                                 fmt.Fprintf(stderr, "... %s\n", cmd.Args)
503                                 err = cmd.Run()
504                                 if err != nil {
505                                         return 1
506                                 }
507                         }
508                         cmd = exec.Command("sudo", "-u", "www-data", "/var/lib/arvados/bin/bundle", "exec", "passenger-config", "validate-install")
509                         cmd.Dir = "/var/lib/arvados/" + dstdir
510                         cmd.Stdout = stdout
511                         cmd.Stderr = stderr
512                         err = cmd.Run()
513                         if err != nil && !strings.Contains(err.Error(), "exit status 2") {
514                                 // Exit code 2 indicates there were warnings (like
515                                 // "other passenger installations have been detected",
516                                 // which we can't expect to avoid) but no errors.
517                                 // Other non-zero exit codes (1, 9) indicate errors.
518                                 return 1
519                         }
520                 }
521
522                 // Install Go programs to /var/lib/arvados/bin/
523                 for _, srcdir := range []string{
524                         "cmd/arvados-client",
525                         "cmd/arvados-server",
526                         "services/arv-git-httpd",
527                         "services/crunch-dispatch-local",
528                         "services/crunch-dispatch-slurm",
529                         "services/health",
530                         "services/keep-balance",
531                         "services/keep-web",
532                         "services/keepproxy",
533                         "services/keepstore",
534                         "services/ws",
535                 } {
536                         fmt.Fprintf(stderr, "building %s...\n", srcdir)
537                         cmd := exec.Command("go", "install", "-ldflags", "-X git.arvados.org/arvados.git/lib/cmd.version="+inst.PackageVersion+" -X main.version="+inst.PackageVersion)
538                         cmd.Env = append(cmd.Env, os.Environ()...)
539                         cmd.Env = append(cmd.Env, "GOBIN=/var/lib/arvados/bin")
540                         cmd.Dir = filepath.Join(inst.SourcePath, srcdir)
541                         cmd.Stdout = stdout
542                         cmd.Stderr = stderr
543                         err = cmd.Run()
544                         if err != nil {
545                                 return 1
546                         }
547                 }
548
549                 // Copy assets from source tree to /var/lib/arvados/share
550                 cmd := exec.Command("install", "-v", "-t", "/var/lib/arvados/share", filepath.Join(inst.SourcePath, "sdk/python/tests/nginx.conf"))
551                 cmd.Stdout = stdout
552                 cmd.Stderr = stderr
553                 err = cmd.Run()
554                 if err != nil {
555                         return 1
556                 }
557         }
558
559         return 0
560 }
561
562 type osversion struct {
563         Debian bool
564         Ubuntu bool
565         Centos bool
566         Major  int
567 }
568
569 func identifyOS() (osversion, error) {
570         var osv osversion
571         f, err := os.Open("/etc/os-release")
572         if err != nil {
573                 return osv, err
574         }
575         defer f.Close()
576
577         kv := map[string]string{}
578         scanner := bufio.NewScanner(f)
579         for scanner.Scan() {
580                 line := strings.TrimSpace(scanner.Text())
581                 if strings.HasPrefix(line, "#") {
582                         continue
583                 }
584                 toks := strings.SplitN(line, "=", 2)
585                 if len(toks) != 2 {
586                         return osv, fmt.Errorf("invalid line in /etc/os-release: %q", line)
587                 }
588                 k := toks[0]
589                 v := strings.Trim(toks[1], `"`)
590                 if v == toks[1] {
591                         v = strings.Trim(v, `'`)
592                 }
593                 kv[k] = v
594         }
595         if err = scanner.Err(); err != nil {
596                 return osv, err
597         }
598         switch kv["ID"] {
599         case "ubuntu":
600                 osv.Ubuntu = true
601         case "debian":
602                 osv.Debian = true
603         case "centos":
604                 osv.Centos = true
605         default:
606                 return osv, fmt.Errorf("unsupported ID in /etc/os-release: %q", kv["ID"])
607         }
608         vstr := kv["VERSION_ID"]
609         if i := strings.Index(vstr, "."); i > 0 {
610                 vstr = vstr[:i]
611         }
612         osv.Major, err = strconv.Atoi(vstr)
613         if err != nil {
614                 return osv, fmt.Errorf("incomprehensible VERSION_ID in /etc/os-release: %q", kv["VERSION_ID"])
615         }
616         return osv, nil
617 }
618
619 func waitPostgreSQLReady() error {
620         for deadline := time.Now().Add(10 * time.Second); ; {
621                 output, err := exec.Command("pg_isready").CombinedOutput()
622                 if err == nil {
623                         return nil
624                 } else if time.Now().After(deadline) {
625                         return fmt.Errorf("timed out waiting for pg_isready (%q)", output)
626                 } else {
627                         time.Sleep(time.Second)
628                 }
629         }
630 }
631
632 func (inst *installCommand) runBash(script string, stdout, stderr io.Writer) error {
633         cmd := exec.Command("bash", "-")
634         if inst.EatMyData {
635                 cmd = exec.Command("eatmydata", "bash", "-")
636         }
637         cmd.Stdin = bytes.NewBufferString("set -ex -o pipefail\n" + script)
638         cmd.Stdout = stdout
639         cmd.Stderr = stderr
640         return cmd.Run()
641 }
642
643 func prodpkgs(osv osversion) []string {
644         pkgs := []string{
645                 "ca-certificates",
646                 "curl",
647                 "fuse",
648                 "git",
649                 "gitolite3",
650                 "graphviz",
651                 "haveged",
652                 "libcurl3-gnutls",
653                 "libxslt1.1",
654                 "nginx",
655                 "python",
656                 "sudo",
657         }
658         if osv.Debian || osv.Ubuntu {
659                 if osv.Debian && osv.Major == 8 {
660                         pkgs = append(pkgs, "libgnutls-deb0-28") // sdk/cwl
661                 } else if osv.Debian && osv.Major >= 10 || osv.Ubuntu && osv.Major >= 16 {
662                         pkgs = append(pkgs, "python3-distutils") // sdk/cwl
663                 }
664                 return append(pkgs,
665                         "g++",
666                         "libcurl4-openssl-dev", // services/api
667                         "libpq-dev",
668                         "libpython2.7", // services/fuse
669                         "mime-support", // keep-web
670                         "zlib1g-dev",   // services/api
671                 )
672         } else if osv.Centos {
673                 return append(pkgs,
674                         "fuse-libs", // services/fuse
675                         "gcc",
676                         "gcc-c++",
677                         "libcurl-devel",    // services/api
678                         "mailcap",          // keep-web
679                         "postgresql-devel", // services/api
680                 )
681         } else {
682                 panic("os version not supported")
683         }
684 }
685
686 func ProductionDependencies() ([]string, error) {
687         osv, err := identifyOS()
688         if err != nil {
689                 return nil, err
690         }
691         return prodpkgs(osv), nil
692 }