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