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