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