Merge branch '20825-cwl-separate-runner' refs #20825
[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         _ "embed"
12         "errors"
13         "flag"
14         "fmt"
15         "io"
16         "os"
17         "os/exec"
18         "os/user"
19         "path/filepath"
20         "runtime"
21         "strconv"
22         "strings"
23         "syscall"
24         "time"
25
26         "git.arvados.org/arvados.git/lib/cmd"
27         "git.arvados.org/arvados.git/sdk/go/ctxlog"
28         "github.com/lib/pq"
29 )
30
31 var Command cmd.Handler = &installCommand{}
32
33 const goversion = "1.20.6"
34
35 const (
36         rubyversion             = "2.7.7"
37         bundlerversion          = "2.2.19"
38         singularityversion      = "3.10.4"
39         pjsversion              = "1.9.8"
40         geckoversion            = "0.24.0"
41         gradleversion           = "5.3.1"
42         nodejsversion           = "v12.22.12"
43         devtestDatabasePassword = "insecure_arvados_test"
44         workbench2version       = "9a62117dbe56bdfa42489415eb6696638c2bb336" // 2.6.3
45 )
46
47 //go:embed arvados.service
48 var arvadosServiceFile []byte
49
50 type installCommand struct {
51         ClusterType    string
52         SourcePath     string
53         PackageVersion string
54         EatMyData      bool
55 }
56
57 func (inst *installCommand) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
58         logger := ctxlog.New(stderr, "text", "info")
59         ctx := ctxlog.Context(context.Background(), logger)
60         ctx, cancel := context.WithCancel(ctx)
61         defer cancel()
62
63         var err error
64         defer func() {
65                 if err != nil {
66                         logger.WithError(err).Info("exiting")
67                 }
68         }()
69
70         flags := flag.NewFlagSet(prog, flag.ContinueOnError)
71         flags.SetOutput(stderr)
72         versionFlag := flags.Bool("version", false, "Write version information to stdout and exit 0")
73         flags.StringVar(&inst.ClusterType, "type", "production", "cluster `type`: development, test, production, or package")
74         flags.StringVar(&inst.SourcePath, "source", "/arvados", "source tree location (required for -type=package)")
75         flags.StringVar(&inst.PackageVersion, "package-version", "0.0.0", "version string to embed in executable files")
76         flags.BoolVar(&inst.EatMyData, "eatmydata", false, "use eatmydata to speed up install")
77
78         if ok, code := cmd.ParseFlags(flags, prog, args, "", stderr); !ok {
79                 return code
80         } else if *versionFlag {
81                 return cmd.Version.RunCommand(prog, args, stdin, stdout, stderr)
82         }
83
84         var dev, test, prod, pkg bool
85         switch inst.ClusterType {
86         case "development":
87                 dev = true
88         case "test":
89                 test = true
90         case "production":
91                 prod = true
92         case "package":
93                 pkg = true
94         default:
95                 err = fmt.Errorf("invalid cluster type %q (must be 'development', 'test', 'production', or 'package')", inst.ClusterType)
96                 return 2
97         }
98
99         if prod {
100                 err = errors.New("production install is not yet implemented")
101                 return 1
102         }
103
104         osv, err := identifyOS()
105         if err != nil {
106                 return 1
107         }
108
109         listdir, err := os.Open("/var/lib/apt/lists")
110         if err != nil {
111                 logger.Warnf("error while checking whether to run apt-get update: %s", err)
112         } else if names, _ := listdir.Readdirnames(1); len(names) == 0 {
113                 // Special case for a base docker image where the
114                 // package cache has been deleted and all "apt-get
115                 // install" commands will fail unless we fetch repos.
116                 cmd := exec.CommandContext(ctx, "apt-get", "update")
117                 cmd.Stdout = stdout
118                 cmd.Stderr = stderr
119                 err = cmd.Run()
120                 if err != nil {
121                         return 1
122                 }
123         }
124
125         if inst.EatMyData {
126                 cmd := exec.CommandContext(ctx, "apt-get", "install", "--yes", "--no-install-recommends", "eatmydata")
127                 cmd.Env = append(os.Environ(), "DEBIAN_FRONTEND=noninteractive")
128                 cmd.Stdout = stdout
129                 cmd.Stderr = stderr
130                 err = cmd.Run()
131                 if err != nil {
132                         return 1
133                 }
134         }
135
136         pkgs := prodpkgs(osv)
137
138         if pkg {
139                 pkgs = append(pkgs,
140                         "dpkg-dev",
141                         "eatmydata", // install it for later steps, even if we're not using it now
142                 )
143         }
144
145         if dev || test || pkg {
146                 pkgs = append(pkgs,
147                         "automake",
148                         "bison",
149                         "bsdmainutils",
150                         "build-essential",
151                         "cadaver",
152                         "curl",
153                         "cython3",
154                         "default-jdk-headless",
155                         "default-jre-headless",
156                         "gettext",
157                         "libattr1-dev",
158                         "libfuse-dev",
159                         "libgbm1", // cypress / workbench2 tests
160                         "libgnutls28-dev",
161                         "libpam-dev",
162                         "libpcre3-dev",
163                         "libpq-dev",
164                         "libreadline-dev",
165                         "libssl-dev",
166                         "libxml2-dev",
167                         "libxslt1-dev",
168                         "linkchecker",
169                         "lsof",
170                         "make",
171                         "net-tools",
172                         "pandoc",
173                         "pkg-config",
174                         "postgresql",
175                         "postgresql-contrib",
176                         "python3-dev",
177                         "python3-venv",
178                         "python3-virtualenv",
179                         "r-base",
180                         "r-cran-testthat",
181                         "r-cran-devtools",
182                         "r-cran-knitr",
183                         "r-cran-markdown",
184                         "r-cran-roxygen2",
185                         "r-cran-xml",
186                         "rsync",
187                         "sudo",
188                         "uuid-dev",
189                         "wget",
190                         "xvfb",
191                         "zlib1g-dev", // services/api
192                 )
193                 if test {
194                         if osv.Debian && osv.Major <= 10 {
195                                 pkgs = append(pkgs, "iceweasel")
196                         } else if osv.Debian && osv.Major >= 11 {
197                                 pkgs = append(pkgs, "firefox-esr")
198                         } else {
199                                 pkgs = append(pkgs, "firefox")
200                         }
201                 }
202                 if dev || test {
203                         pkgs = append(pkgs,
204                                 "libglib2.0-dev", // singularity (conmon)
205                                 "libseccomp-dev", // singularity (seccomp)
206                                 "squashfs-tools", // singularity
207                                 "gnupg")          // docker install recipe
208                 }
209                 switch {
210                 case osv.Debian && osv.Major >= 11:
211                         pkgs = append(pkgs, "g++", "libcurl4", "libcurl4-openssl-dev")
212                 case osv.Debian && osv.Major >= 10:
213                         pkgs = append(pkgs, "g++", "libcurl4", "libcurl4-openssl-dev")
214                 case osv.Debian || osv.Ubuntu:
215                         pkgs = append(pkgs, "g++", "libcurl3", "libcurl3-openssl-dev")
216                 case osv.Centos:
217                         pkgs = append(pkgs, "gcc", "gcc-c++", "libcurl-devel", "postgresql-devel")
218                 }
219                 cmd := exec.CommandContext(ctx, "apt-get")
220                 if inst.EatMyData {
221                         cmd = exec.CommandContext(ctx, "eatmydata", "apt-get")
222                 }
223                 cmd.Args = append(cmd.Args, "install", "--yes", "--no-install-recommends")
224                 cmd.Args = append(cmd.Args, pkgs...)
225                 cmd.Env = append(os.Environ(), "DEBIAN_FRONTEND=noninteractive")
226                 cmd.Stdout = stdout
227                 cmd.Stderr = stderr
228                 err = cmd.Run()
229                 if err != nil {
230                         return 1
231                 }
232         }
233
234         if dev || test {
235                 if havedockerversion, err := exec.Command("docker", "--version").CombinedOutput(); err == nil {
236                         logger.Printf("%s installed, assuming that version is ok", bytes.TrimSuffix(havedockerversion, []byte("\n")))
237                 } else if osv.Debian {
238                         var codename string
239                         switch osv.Major {
240                         case 10:
241                                 codename = "buster"
242                         case 11:
243                                 codename = "bullseye"
244                         default:
245                                 err = fmt.Errorf("don't know how to install docker-ce for debian %d", osv.Major)
246                                 return 1
247                         }
248                         err = inst.runBash(`
249 rm -f /usr/share/keyrings/docker-archive-keyring.gpg
250 curl -fsSL https://download.docker.com/linux/debian/gpg | gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg
251 echo 'deb [arch=amd64 signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/debian/ `+codename+` stable' | \
252     tee /etc/apt/sources.list.d/docker.list
253 apt-get update
254 DEBIAN_FRONTEND=noninteractive apt-get --yes --no-install-recommends install docker-ce
255 `, stdout, stderr)
256                         if err != nil {
257                                 return 1
258                         }
259                 } else {
260                         err = fmt.Errorf("don't know how to install docker for osversion %v", osv)
261                         return 1
262                 }
263         }
264
265         os.Mkdir("/var/lib/arvados", 0755)
266         os.Mkdir("/var/lib/arvados/tmp", 0700)
267         if prod || pkg {
268                 u, er := user.Lookup("www-data")
269                 if er != nil {
270                         err = fmt.Errorf("user.Lookup(%q): %w", "www-data", er)
271                         return 1
272                 }
273                 uid, _ := strconv.Atoi(u.Uid)
274                 gid, _ := strconv.Atoi(u.Gid)
275                 os.Mkdir("/var/lib/arvados/wwwtmp", 0700)
276                 err = os.Chown("/var/lib/arvados/wwwtmp", uid, gid)
277                 if err != nil {
278                         return 1
279                 }
280         }
281         rubymajorversion := rubyversion[:strings.LastIndex(rubyversion, ".")]
282         if haverubyversion, err := exec.Command("/var/lib/arvados/bin/ruby", "-v").CombinedOutput(); err == nil && bytes.HasPrefix(haverubyversion, []byte("ruby "+rubyversion)) {
283                 logger.Print("ruby " + rubyversion + " already installed")
284         } else {
285                 err = inst.runBash(`
286 tmp="$(mktemp -d)"
287 trap 'rm -r "${tmp}"' ERR EXIT
288 wget --progress=dot:giga -O- https://cache.ruby-lang.org/pub/ruby/`+rubymajorversion+`/ruby-`+rubyversion+`.tar.gz | tar -C "${tmp}" -xzf -
289 cd "${tmp}/ruby-`+rubyversion+`"
290 ./configure --disable-install-static-library --enable-shared --disable-install-doc --prefix /var/lib/arvados
291 make -j8
292 make install
293 /var/lib/arvados/bin/gem install bundler --no-document
294 `, stdout, stderr)
295                 if err != nil {
296                         return 1
297                 }
298         }
299
300         if !prod {
301                 if havegoversion, err := exec.Command("/usr/local/bin/go", "version").CombinedOutput(); err == nil && bytes.HasPrefix(havegoversion, []byte("go version go"+goversion+" ")) {
302                         logger.Print("go " + goversion + " already installed")
303                 } else {
304                         err = inst.runBash(`
305 cd /tmp
306 rm -rf /var/lib/arvados/go/
307 wget --progress=dot:giga -O- https://storage.googleapis.com/golang/go`+goversion+`.linux-amd64.tar.gz | tar -C /var/lib/arvados -xzf -
308 ln -sfv /var/lib/arvados/go/bin/* /usr/local/bin/
309 `, stdout, stderr)
310                         if err != nil {
311                                 return 1
312                         }
313                 }
314         }
315
316         if !prod && !pkg {
317                 if havepjsversion, err := exec.Command("/usr/local/bin/phantomjs", "--version").CombinedOutput(); err == nil && string(havepjsversion) == "1.9.8\n" {
318                         logger.Print("phantomjs " + pjsversion + " already installed")
319                 } else {
320                         err = inst.runBash(`
321 PJS=phantomjs-`+pjsversion+`-linux-x86_64
322 wget --progress=dot:giga -O- https://cache.arvados.org/$PJS.tar.bz2 | tar -C /var/lib/arvados -xjf -
323 ln -sfv /var/lib/arvados/$PJS/bin/phantomjs /usr/local/bin/
324 `, stdout, stderr)
325                         if err != nil {
326                                 return 1
327                         }
328                 }
329
330                 if havegeckoversion, err := exec.Command("/usr/local/bin/geckodriver", "--version").CombinedOutput(); err == nil && strings.Contains(string(havegeckoversion), " "+geckoversion+" ") {
331                         logger.Print("geckodriver " + geckoversion + " already installed")
332                 } else {
333                         err = inst.runBash(`
334 GD=v`+geckoversion+`
335 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
336 ln -sfv /var/lib/arvados/bin/geckodriver /usr/local/bin/
337 `, stdout, stderr)
338                         if err != nil {
339                                 return 1
340                         }
341                 }
342
343                 if havegradleversion, err := exec.Command("/usr/local/bin/gradle", "--version").CombinedOutput(); err == nil && strings.Contains(string(havegradleversion), "Gradle "+gradleversion+"\n") {
344                         logger.Print("gradle " + gradleversion + " already installed")
345                 } else {
346                         err = inst.runBash(`
347 G=`+gradleversion+`
348 zip=/var/lib/arvados/tmp/gradle-${G}-bin.zip
349 trap "rm ${zip}" ERR
350 wget --progress=dot:giga -O${zip} https://services.gradle.org/distributions/gradle-${G}-bin.zip
351 unzip -o -d /var/lib/arvados ${zip}
352 ln -sfv /var/lib/arvados/gradle-${G}/bin/gradle /usr/local/bin/
353 rm ${zip}
354 `, stdout, stderr)
355                         if err != nil {
356                                 return 1
357                         }
358                 }
359
360                 if havesingularityversion, err := exec.Command("/var/lib/arvados/bin/singularity", "--version").CombinedOutput(); err == nil && strings.Contains(string(havesingularityversion), singularityversion) {
361                         logger.Print("singularity " + singularityversion + " already installed")
362                 } else if dev || test {
363                         err = inst.runBash(`
364 S=`+singularityversion+`
365 tmp=/var/lib/arvados/tmp/singularity
366 trap "rm -r ${tmp}" ERR EXIT
367 cd /var/lib/arvados/tmp
368 git clone --recurse-submodules https://github.com/sylabs/singularity
369 cd singularity
370 git checkout v${S}
371 ./mconfig --prefix=/var/lib/arvados
372 make -C ./builddir
373 make -C ./builddir install
374 `, stdout, stderr)
375                         if err != nil {
376                                 return 1
377                         }
378                 }
379
380                 err = inst.runBash(`
381 install /usr/bin/nsenter /var/lib/arvados/bin/nsenter
382 setcap "cap_sys_admin+pei cap_sys_chroot+pei" /var/lib/arvados/bin/nsenter
383 `, stdout, stderr)
384                 if err != nil {
385                         return 1
386                 }
387
388                 // The entry in /etc/locale.gen is "en_US.UTF-8"; once
389                 // it's installed, locale -a reports it as
390                 // "en_US.utf8".
391                 wantlocale := "en_US.UTF-8"
392                 if havelocales, err := exec.Command("locale", "-a").CombinedOutput(); err == nil && bytes.Contains(havelocales, []byte(strings.Replace(wantlocale+"\n", "UTF-", "utf", 1))) {
393                         logger.Print("locale " + wantlocale + " already installed")
394                 } else {
395                         err = inst.runBash(`sed -i 's/^# *\(`+wantlocale+`\)/\1/' /etc/locale.gen && locale-gen`, stdout, stderr)
396                         if err != nil {
397                                 return 1
398                         }
399                 }
400
401                 var pgc struct {
402                         Version       string
403                         Cluster       string
404                         Port          int
405                         Status        string
406                         Owner         string
407                         DataDirectory string
408                         LogFile       string
409                 }
410                 if pgLsclusters, err2 := exec.Command("pg_lsclusters", "--no-header").CombinedOutput(); err2 != nil {
411                         err = fmt.Errorf("pg_lsclusters: %s", err2)
412                         return 1
413                 } else if pgclusters := strings.Split(strings.TrimSpace(string(pgLsclusters)), "\n"); len(pgclusters) != 1 {
414                         logger.Warnf("pg_lsclusters returned %d postgresql clusters -- skipping postgresql initdb/startup, hope that's ok", len(pgclusters))
415                 } 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 {
416                         err = fmt.Errorf("error parsing pg_lsclusters output: %s", err)
417                         return 1
418                 } else if pgc.Status == "online" {
419                         logger.Infof("postgresql cluster %s-%s is online", pgc.Version, pgc.Cluster)
420                 } else {
421                         logger.Infof("postgresql cluster %s-%s is %s; trying to start", pgc.Version, pgc.Cluster, pgc.Status)
422                         cmd := exec.Command("pg_ctlcluster", "--foreground", pgc.Version, pgc.Cluster, "start")
423                         cmd.Stdout = stdout
424                         cmd.Stderr = stderr
425                         err = cmd.Start()
426                         if err != nil {
427                                 return 1
428                         }
429                         defer func() {
430                                 cmd.Process.Signal(syscall.SIGTERM)
431                                 logger.Info("sent SIGTERM; waiting for postgres to shut down")
432                                 cmd.Wait()
433                         }()
434                         err = waitPostgreSQLReady()
435                         if err != nil {
436                                 return 1
437                         }
438                 }
439
440                 if os.Getpid() == 1 {
441                         // We are the init process (presumably in a
442                         // docker container) so although postgresql is
443                         // installed, it's not running, and initdb
444                         // might never have been run.
445                 }
446
447                 var needcoll []string
448                 // If the en_US.UTF-8 locale wasn't installed when
449                 // postgresql initdb ran, it needs to be added
450                 // explicitly before we can use it in our test suite.
451                 for _, collname := range []string{"en_US", "en_US.UTF-8"} {
452                         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')")
453                         cmd.Dir = "/"
454                         out, err2 := cmd.CombinedOutput()
455                         if err != nil {
456                                 err = fmt.Errorf("error while checking postgresql collations: %s", err2)
457                                 return 1
458                         }
459                         if strings.Contains(string(out), "1") {
460                                 logger.Infof("postgresql supports collation %s", collname)
461                         } else {
462                                 needcoll = append(needcoll, collname)
463                         }
464                 }
465                 if len(needcoll) > 0 && os.Getpid() != 1 {
466                         // In order for the CREATE COLLATION statement
467                         // below to work, the locale must have existed
468                         // when PostgreSQL started up. If we're
469                         // running as init, we must have started
470                         // PostgreSQL ourselves after installing the
471                         // locales. Otherwise, it might need a
472                         // restart, so we attempt to restart it with
473                         // systemd.
474                         if err = inst.runBash(`sudo systemctl restart postgresql`, stdout, stderr); err != nil {
475                                 logger.Warn("`systemctl restart postgresql` failed; hoping postgresql does not need to be restarted")
476                         } else if err = waitPostgreSQLReady(); err != nil {
477                                 return 1
478                         }
479                 }
480                 for _, collname := range needcoll {
481                         cmd := exec.Command("sudo", "-u", "postgres", "psql", "-c", "CREATE COLLATION \""+collname+"\" (LOCALE = \"en_US.UTF-8\")")
482                         cmd.Stdout = stdout
483                         cmd.Stderr = stderr
484                         cmd.Dir = "/"
485                         err = cmd.Run()
486                         if err != nil {
487                                 err = fmt.Errorf("error adding postgresql collation %s: %s", collname, err)
488                                 return 1
489                         }
490                 }
491
492                 withstuff := "WITH LOGIN SUPERUSER ENCRYPTED PASSWORD " + pq.QuoteLiteral(devtestDatabasePassword)
493                 cmd := exec.Command("sudo", "-u", "postgres", "psql", "-c", "ALTER ROLE arvados "+withstuff)
494                 cmd.Dir = "/"
495                 if err := cmd.Run(); err == nil {
496                         logger.Print("arvados role exists; superuser privileges added, password updated")
497                 } else {
498                         cmd := exec.Command("sudo", "-u", "postgres", "psql", "-c", "CREATE ROLE arvados "+withstuff)
499                         cmd.Dir = "/"
500                         cmd.Stdout = stdout
501                         cmd.Stderr = stderr
502                         err = cmd.Run()
503                         if err != nil {
504                                 return 1
505                         }
506                 }
507         }
508
509         if !prod {
510                 if havenodejsversion, err := exec.Command("/usr/local/bin/node", "--version").CombinedOutput(); err == nil && string(havenodejsversion) == nodejsversion+"\n" {
511                         logger.Print("nodejs " + nodejsversion + " already installed")
512                 } else {
513                         err = inst.runBash(`
514 NJS=`+nodejsversion+`
515 rm -rf /var/lib/arvados/node-*-linux-x64
516 wget --progress=dot:giga -O- https://nodejs.org/dist/${NJS}/node-${NJS}-linux-x64.tar.xz | sudo tar -C /var/lib/arvados -xJf -
517 ln -sfv /var/lib/arvados/node-${NJS}-linux-x64/bin/{node,npm} /usr/local/bin/
518 `, stdout, stderr)
519                         if err != nil {
520                                 return 1
521                         }
522                 }
523
524                 if haveyarnversion, err := exec.Command("/usr/local/bin/yarn", "--version").CombinedOutput(); err == nil && len(haveyarnversion) > 0 {
525                         logger.Print("yarn " + strings.TrimSpace(string(haveyarnversion)) + " already installed")
526                 } else {
527                         err = inst.runBash(`
528 npm install -g yarn
529 ln -sfv /var/lib/arvados/node-`+nodejsversion+`-linux-x64/bin/{yarn,yarnpkg} /usr/local/bin/
530 `, stdout, stderr)
531                         if err != nil {
532                                 return 1
533                         }
534                 }
535
536                 if havewb2version, err := exec.Command("git", "--git-dir=/var/lib/arvados/arvados-workbench2/.git", "log", "-n1", "--format=%H").CombinedOutput(); err == nil && string(havewb2version) == workbench2version+"\n" {
537                         logger.Print("workbench2 repo is already at " + workbench2version)
538                 } else {
539                         err = inst.runBash(`
540 V=`+workbench2version+`
541 cd /var/lib/arvados
542 if [[ ! -e arvados-workbench2 ]]; then
543   git clone https://git.arvados.org/arvados-workbench2.git
544   cd arvados-workbench2
545   git checkout $V
546 else
547   cd arvados-workbench2
548   if ! git checkout $V; then
549     git fetch
550     git checkout yarn.lock
551     git checkout $V
552   fi
553 fi
554 rm -rf build
555 `, stdout, stderr)
556                         if err != nil {
557                                 return 1
558                         }
559                 }
560
561                 if err = inst.runBash(`
562 cd /var/lib/arvados/arvados-workbench2
563 yarn install
564 `, stdout, stderr); err != nil {
565                         return 1
566                 }
567         }
568
569         if prod || pkg {
570                 // Install Go programs to /var/lib/arvados/bin/
571                 for _, srcdir := range []string{
572                         "cmd/arvados-client",
573                         "cmd/arvados-server",
574                 } {
575                         fmt.Fprintf(stderr, "building %s...\n", srcdir)
576                         cmd := exec.Command("go", "install", "-ldflags", "-X git.arvados.org/arvados.git/lib/cmd.version="+inst.PackageVersion+" -X main.version="+inst.PackageVersion+" -s -w")
577                         cmd.Env = append(cmd.Env, os.Environ()...)
578                         cmd.Env = append(cmd.Env, "GOBIN=/var/lib/arvados/bin")
579                         cmd.Dir = filepath.Join(inst.SourcePath, srcdir)
580                         cmd.Stdout = stdout
581                         cmd.Stderr = stderr
582                         err = cmd.Run()
583                         if err != nil {
584                                 return 1
585                         }
586                 }
587
588                 // Copy assets from source tree to /var/lib/arvados/share
589                 cmd := exec.Command("install", "-v", "-t", "/var/lib/arvados/share", filepath.Join(inst.SourcePath, "sdk/python/tests/nginx.conf"))
590                 cmd.Stdout = stdout
591                 cmd.Stderr = stderr
592                 err = cmd.Run()
593                 if err != nil {
594                         return 1
595                 }
596
597                 // Install python SDK and arv-mount in
598                 // /var/lib/arvados/lib/python.
599                 //
600                 // setup.py writes a file in the source directory in
601                 // order to include the version number in the package
602                 // itself.  We don't want to write to the source tree
603                 // (in "arvados-package" context it's mounted
604                 // readonly) so we run setup.py in a temporary copy of
605                 // the source dir.
606                 if err = inst.runBash(`
607 v=/var/lib/arvados/lib/python
608 tmp=/var/lib/arvados/tmp/python
609 python3 -m venv "$v"
610 . "$v/bin/activate"
611 pip3 install --no-cache-dir 'setuptools>=18.5' 'pip>=7'
612 export ARVADOS_BUILDING_VERSION="`+inst.PackageVersion+`"
613 for src in "`+inst.SourcePath+`/sdk/python" "`+inst.SourcePath+`/services/fuse"; do
614   rsync -a --delete-after "$src/" "$tmp/"
615   cd "$tmp"
616   python3 setup.py install
617   cd ..
618   rm -rf "$tmp"
619 done
620 `, stdout, stderr); err != nil {
621                         return 1
622                 }
623
624                 // Install Rails apps to /var/lib/arvados/{railsapi,workbench1}/
625                 for dstdir, srcdir := range map[string]string{
626                         "railsapi":   "services/api",
627                         "workbench1": "apps/workbench",
628                 } {
629                         fmt.Fprintf(stderr, "building %s...\n", srcdir)
630                         cmd := exec.Command("rsync",
631                                 "-a", "--no-owner", "--no-group", "--delete-after", "--delete-excluded",
632                                 "--exclude", "/coverage",
633                                 "--exclude", "/log",
634                                 "--exclude", "/node_modules",
635                                 "--exclude", "/tmp",
636                                 "--exclude", "/public/assets",
637                                 "--exclude", "/vendor",
638                                 "--exclude", "/config/environments",
639                                 "./", "/var/lib/arvados/"+dstdir+"/")
640                         cmd.Dir = filepath.Join(inst.SourcePath, srcdir)
641                         cmd.Stdout = stdout
642                         cmd.Stderr = stderr
643                         err = cmd.Run()
644                         if err != nil {
645                                 return 1
646                         }
647                         for _, cmdline := range [][]string{
648                                 {"mkdir", "-p", "log", "public/assets", "tmp", "vendor", ".bundle", "/var/www/.bundle", "/var/www/.gem", "/var/www/.npm", "/var/www/.passenger"},
649                                 {"touch", "log/production.log"},
650                                 {"chown", "-R", "--from=root", "www-data:www-data", "/var/www/.bundle", "/var/www/.gem", "/var/www/.npm", "/var/www/.passenger", "log", "tmp", "vendor", ".bundle", "Gemfile.lock", "config.ru", "config/environment.rb"},
651                                 {"sudo", "-u", "www-data", "/var/lib/arvados/bin/gem", "install", "--user", "--conservative", "--no-document", "bundler:" + bundlerversion},
652                                 {"sudo", "-u", "www-data", "/var/lib/arvados/bin/bundle", "config", "set", "--local", "deployment", "true"},
653                                 {"sudo", "-u", "www-data", "/var/lib/arvados/bin/bundle", "config", "set", "--local", "path", "/var/www/.gem"},
654                                 {"sudo", "-u", "www-data", "/var/lib/arvados/bin/bundle", "config", "set", "--local", "without", "development test diagnostics performance"},
655                                 {"sudo", "-u", "www-data", "/var/lib/arvados/bin/bundle", "install", "--jobs", fmt.Sprintf("%d", runtime.NumCPU())},
656
657                                 {"chown", "www-data:www-data", ".", "public/assets"},
658                                 // {"sudo", "-u", "www-data", "/var/lib/arvados/bin/bundle", "config", "set", "--local", "system", "true"},
659                                 {"sudo", "-u", "www-data", "ARVADOS_CONFIG=none", "RAILS_GROUPS=assets", "RAILS_ENV=production", "PATH=/var/lib/arvados/bin:" + os.Getenv("PATH"), "/var/lib/arvados/bin/bundle", "exec", "rake", "npm:install"},
660                                 {"sudo", "-u", "www-data", "ARVADOS_CONFIG=none", "RAILS_GROUPS=assets", "RAILS_ENV=production", "PATH=/var/lib/arvados/bin:" + os.Getenv("PATH"), "/var/lib/arvados/bin/bundle", "exec", "rake", "assets:precompile"},
661                                 {"chown", "root:root", "."},
662                                 {"chown", "-R", "root:root", "public/assets", "vendor"},
663
664                                 {"sudo", "-u", "www-data", "/var/lib/arvados/bin/bundle", "exec", "passenger-config", "build-native-support"},
665                                 {"sudo", "-u", "www-data", "/var/lib/arvados/bin/bundle", "exec", "passenger-config", "install-standalone-runtime"},
666                         } {
667                                 if cmdline[len(cmdline)-2] == "rake" && dstdir != "workbench1" {
668                                         continue
669                                 }
670                                 cmd = exec.Command(cmdline[0], cmdline[1:]...)
671                                 cmd.Dir = "/var/lib/arvados/" + dstdir
672                                 cmd.Stdout = stdout
673                                 cmd.Stderr = stderr
674                                 fmt.Fprintf(stderr, "... %s\n", cmd.Args)
675                                 err = cmd.Run()
676                                 if err != nil {
677                                         return 1
678                                 }
679                         }
680                         cmd = exec.Command("sudo", "-u", "www-data", "/var/lib/arvados/bin/bundle", "exec", "passenger-config", "validate-install")
681                         cmd.Dir = "/var/lib/arvados/" + dstdir
682                         cmd.Stdout = stdout
683                         cmd.Stderr = stderr
684                         err = cmd.Run()
685                         if err != nil && !strings.Contains(err.Error(), "exit status 2") {
686                                 // Exit code 2 indicates there were warnings (like
687                                 // "other passenger installations have been detected",
688                                 // which we can't expect to avoid) but no errors.
689                                 // Other non-zero exit codes (1, 9) indicate errors.
690                                 return 1
691                         }
692                 }
693
694                 // Install workbench2 app to /var/lib/arvados/workbench2/
695                 if err = inst.runBash(`
696 cd /var/lib/arvados/arvados-workbench2
697 VERSION="`+inst.PackageVersion+`" BUILD_NUMBER=1 GIT_COMMIT="`+workbench2version[:9]+`" yarn build
698 rsync -a --delete-after build/ /var/lib/arvados/workbench2/
699 `, stdout, stderr); err != nil {
700                         return 1
701                 }
702
703                 // Install arvados-cli gem (binaries go in
704                 // /var/lib/arvados/bin)
705                 if err = inst.runBash(`
706 /var/lib/arvados/bin/gem install --conservative --no-document arvados-cli
707 `, stdout, stderr); err != nil {
708                         return 1
709                 }
710
711                 err = os.WriteFile("/lib/systemd/system/arvados.service", arvadosServiceFile, 0777)
712                 if err != nil {
713                         return 1
714                 }
715                 if prod {
716                         // (fpm will do this for us in the pkg case)
717                         // This is equivalent to "systemd enable", but
718                         // does not depend on the systemctl program
719                         // being available:
720                         symlink := "/etc/systemd/system/multi-user.target.wants/arvados.service"
721                         err = os.Remove(symlink)
722                         if err != nil && !errors.Is(err, os.ErrNotExist) {
723                                 return 1
724                         }
725                         err = os.Symlink("/lib/systemd/system/arvados.service", symlink)
726                         if err != nil {
727                                 return 1
728                         }
729                 }
730
731                 // Add symlinks in /usr/bin for user-facing programs
732                 for _, srcdst := range [][]string{
733                         // go
734                         {"bin/arvados-client"},
735                         {"bin/arvados-client", "arv"},
736                         {"bin/arvados-server"},
737                         // sdk/cli
738                         {"bin/arv", "arv-ruby"},
739                         {"bin/arv-tag"},
740                         // sdk/python
741                         {"lib/python/bin/arv-copy"},
742                         {"lib/python/bin/arv-federation-migrate"},
743                         {"lib/python/bin/arv-get"},
744                         {"lib/python/bin/arv-keepdocker"},
745                         {"lib/python/bin/arv-ls"},
746                         {"lib/python/bin/arv-migrate-docker19"},
747                         {"lib/python/bin/arv-normalize"},
748                         {"lib/python/bin/arv-put"},
749                         {"lib/python/bin/arv-ws"},
750                         // services/fuse
751                         {"lib/python/bin/arv-mount"},
752                 } {
753                         src := "/var/lib/arvados/" + srcdst[0]
754                         if _, err = os.Stat(src); err != nil {
755                                 return 1
756                         }
757                         dst := srcdst[len(srcdst)-1]
758                         _, dst = filepath.Split(dst)
759                         dst = "/usr/bin/" + dst
760                         err = os.Remove(dst)
761                         if err != nil && !errors.Is(err, os.ErrNotExist) {
762                                 return 1
763                         }
764                         err = os.Symlink(src, dst)
765                         if err != nil {
766                                 return 1
767                         }
768                 }
769         }
770
771         return 0
772 }
773
774 type osversion struct {
775         Debian bool
776         Ubuntu bool
777         Centos bool
778         Major  int
779 }
780
781 func identifyOS() (osversion, error) {
782         var osv osversion
783         f, err := os.Open("/etc/os-release")
784         if err != nil {
785                 return osv, err
786         }
787         defer f.Close()
788
789         kv := map[string]string{}
790         scanner := bufio.NewScanner(f)
791         for scanner.Scan() {
792                 line := strings.TrimSpace(scanner.Text())
793                 if strings.HasPrefix(line, "#") {
794                         continue
795                 }
796                 toks := strings.SplitN(line, "=", 2)
797                 if len(toks) != 2 {
798                         return osv, fmt.Errorf("invalid line in /etc/os-release: %q", line)
799                 }
800                 k := toks[0]
801                 v := strings.Trim(toks[1], `"`)
802                 if v == toks[1] {
803                         v = strings.Trim(v, `'`)
804                 }
805                 kv[k] = v
806         }
807         if err = scanner.Err(); err != nil {
808                 return osv, err
809         }
810         switch kv["ID"] {
811         case "ubuntu":
812                 osv.Ubuntu = true
813         case "debian":
814                 osv.Debian = true
815         case "centos":
816                 osv.Centos = true
817         default:
818                 return osv, fmt.Errorf("unsupported ID in /etc/os-release: %q", kv["ID"])
819         }
820         vstr := kv["VERSION_ID"]
821         if i := strings.Index(vstr, "."); i > 0 {
822                 vstr = vstr[:i]
823         }
824         osv.Major, err = strconv.Atoi(vstr)
825         if err != nil {
826                 return osv, fmt.Errorf("incomprehensible VERSION_ID in /etc/os-release: %q", kv["VERSION_ID"])
827         }
828         return osv, nil
829 }
830
831 func waitPostgreSQLReady() error {
832         for deadline := time.Now().Add(10 * time.Second); ; {
833                 output, err := exec.Command("pg_isready").CombinedOutput()
834                 if err == nil {
835                         return nil
836                 } else if time.Now().After(deadline) {
837                         return fmt.Errorf("timed out waiting for pg_isready (%q)", output)
838                 } else {
839                         time.Sleep(time.Second)
840                 }
841         }
842 }
843
844 func (inst *installCommand) runBash(script string, stdout, stderr io.Writer) error {
845         cmd := exec.Command("bash", "-")
846         if inst.EatMyData {
847                 cmd = exec.Command("eatmydata", "bash", "-")
848         }
849         cmd.Stdin = bytes.NewBufferString("set -ex -o pipefail\n" + script)
850         cmd.Stdout = stdout
851         cmd.Stderr = stderr
852         return cmd.Run()
853 }
854
855 func prodpkgs(osv osversion) []string {
856         pkgs := []string{
857                 "ca-certificates",
858                 "curl",
859                 "fuse",
860                 "git",
861                 "gitolite3",
862                 "graphviz",
863                 "haveged",
864                 "libcurl3-gnutls",
865                 "libxslt1.1",
866                 "nginx",
867                 "python3",
868                 "sudo",
869         }
870         if osv.Debian || osv.Ubuntu {
871                 if osv.Debian && osv.Major == 8 {
872                         pkgs = append(pkgs, "libgnutls-deb0-28") // sdk/cwl
873                 } else if osv.Debian && osv.Major >= 10 || osv.Ubuntu && osv.Major >= 16 {
874                         pkgs = append(pkgs, "python3-distutils") // sdk/cwl
875                 }
876                 return append(pkgs,
877                         "mime-support", // keep-web
878                 )
879         } else if osv.Centos {
880                 return append(pkgs,
881                         "fuse-libs", // services/fuse
882                         "mailcap",   // keep-web
883                 )
884         } else {
885                 panic("os version not supported")
886         }
887 }
888
889 func ProductionDependencies() ([]string, error) {
890         osv, err := identifyOS()
891         if err != nil {
892                 return nil, err
893         }
894         return prodpkgs(osv), nil
895 }