1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
25 "git.arvados.org/arvados.git/lib/cmd"
26 "git.arvados.org/arvados.git/sdk/go/ctxlog"
30 var Command cmd.Handler = &installCommand{}
32 const goversion = "1.17.7"
36 bundlerversion = "2.2.19"
37 singularityversion = "3.9.9"
39 geckoversion = "0.24.0"
40 gradleversion = "5.3.1"
41 nodejsversion = "v12.22.11"
42 devtestDatabasePassword = "insecure_arvados_test"
43 workbench2version = "2454ac35292a79594c32a80430740317ed5005cf"
46 //go:embed arvados.service
47 var arvadosServiceFile []byte
49 type installCommand struct {
56 func (inst *installCommand) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
57 logger := ctxlog.New(stderr, "text", "info")
58 ctx := ctxlog.Context(context.Background(), logger)
59 ctx, cancel := context.WithCancel(ctx)
65 logger.WithError(err).Info("exiting")
69 flags := flag.NewFlagSet(prog, flag.ContinueOnError)
70 flags.SetOutput(stderr)
71 versionFlag := flags.Bool("version", false, "Write version information to stdout and exit 0")
72 flags.StringVar(&inst.ClusterType, "type", "production", "cluster `type`: development, test, production, or package")
73 flags.StringVar(&inst.SourcePath, "source", "/arvados", "source tree location (required for -type=package)")
74 flags.StringVar(&inst.PackageVersion, "package-version", "0.0.0", "version string to embed in executable files")
75 flags.BoolVar(&inst.EatMyData, "eatmydata", false, "use eatmydata to speed up install")
77 if ok, code := cmd.ParseFlags(flags, prog, args, "", stderr); !ok {
79 } else if *versionFlag {
80 return cmd.Version.RunCommand(prog, args, stdin, stdout, stderr)
83 var dev, test, prod, pkg bool
84 switch inst.ClusterType {
94 err = fmt.Errorf("invalid cluster type %q (must be 'development', 'test', 'production', or 'package')", inst.ClusterType)
99 err = errors.New("production install is not yet implemented")
103 osv, err := identifyOS()
108 listdir, err := os.Open("/var/lib/apt/lists")
110 logger.Warnf("error while checking whether to run apt-get update: %s", err)
111 } else if names, _ := listdir.Readdirnames(1); len(names) == 0 {
112 // Special case for a base docker image where the
113 // package cache has been deleted and all "apt-get
114 // install" commands will fail unless we fetch repos.
115 cmd := exec.CommandContext(ctx, "apt-get", "update")
125 cmd := exec.CommandContext(ctx, "apt-get", "install", "--yes", "--no-install-recommends", "eatmydata")
126 cmd.Env = append(os.Environ(), "DEBIAN_FRONTEND=noninteractive")
135 pkgs := prodpkgs(osv)
140 "eatmydata", // install it for later steps, even if we're not using it now
144 if dev || test || pkg {
153 "default-jdk-headless",
154 "default-jre-headless",
157 "libcrypt-ssleay-perl",
176 "postgresql-contrib",
179 "python3-virtualenv",
194 if osv.Debian && osv.Major <= 10 {
195 pkgs = append(pkgs, "iceweasel")
197 pkgs = append(pkgs, "firefox")
201 pkgs = append(pkgs, "squashfs-tools") // for singularity
202 pkgs = append(pkgs, "gnupg") // for docker install recipe
205 case osv.Debian && osv.Major >= 11:
206 pkgs = append(pkgs, "libcurl4", "perl-modules-5.32")
207 case osv.Debian && osv.Major >= 10:
208 pkgs = append(pkgs, "libcurl4", "perl-modules")
210 pkgs = append(pkgs, "libcurl3", "perl-modules")
212 cmd := exec.CommandContext(ctx, "apt-get")
214 cmd = exec.CommandContext(ctx, "eatmydata", "apt-get")
216 cmd.Args = append(cmd.Args, "install", "--yes", "--no-install-recommends")
217 cmd.Args = append(cmd.Args, pkgs...)
218 cmd.Env = append(os.Environ(), "DEBIAN_FRONTEND=noninteractive")
228 if havedockerversion, err := exec.Command("docker", "--version").CombinedOutput(); err == nil {
229 logger.Printf("%s installed, assuming that version is ok", bytes.TrimSuffix(havedockerversion, []byte("\n")))
230 } else if osv.Debian {
236 codename = "bullseye"
238 err = fmt.Errorf("don't know how to install docker-ce for debian %d", osv.Major)
242 rm -f /usr/share/keyrings/docker-archive-keyring.gpg
243 curl -fsSL https://download.docker.com/linux/debian/gpg | gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg
244 echo 'deb [arch=amd64 signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/debian/ `+codename+` stable' | \
245 tee /etc/apt/sources.list.d/docker.list
247 DEBIAN_FRONTEND=noninteractive apt-get --yes --no-install-recommends install docker-ce
253 err = fmt.Errorf("don't know how to install docker for osversion %v", osv)
258 os.Mkdir("/var/lib/arvados", 0755)
259 os.Mkdir("/var/lib/arvados/tmp", 0700)
261 u, er := user.Lookup("www-data")
263 err = fmt.Errorf("user.Lookup(%q): %w", "www-data", er)
266 uid, _ := strconv.Atoi(u.Uid)
267 gid, _ := strconv.Atoi(u.Gid)
268 os.Mkdir("/var/lib/arvados/wwwtmp", 0700)
269 err = os.Chown("/var/lib/arvados/wwwtmp", uid, gid)
274 rubymajorversion := rubyversion[:strings.LastIndex(rubyversion, ".")]
275 if haverubyversion, err := exec.Command("/var/lib/arvados/bin/ruby", "-v").CombinedOutput(); err == nil && bytes.HasPrefix(haverubyversion, []byte("ruby "+rubyversion)) {
276 logger.Print("ruby " + rubyversion + " already installed")
280 trap 'rm -r "${tmp}"' ERR EXIT
281 wget --progress=dot:giga -O- https://cache.ruby-lang.org/pub/ruby/`+rubymajorversion+`/ruby-`+rubyversion+`.tar.gz | tar -C "${tmp}" -xzf -
282 cd "${tmp}/ruby-`+rubyversion+`"
283 ./configure --disable-install-static-library --enable-shared --disable-install-doc --prefix /var/lib/arvados
286 /var/lib/arvados/bin/gem install bundler --no-document
294 if havegoversion, err := exec.Command("/usr/local/bin/go", "version").CombinedOutput(); err == nil && bytes.HasPrefix(havegoversion, []byte("go version go"+goversion+" ")) {
295 logger.Print("go " + goversion + " already installed")
299 rm -rf /var/lib/arvados/go/
300 wget --progress=dot:giga -O- https://storage.googleapis.com/golang/go`+goversion+`.linux-amd64.tar.gz | tar -C /var/lib/arvados -xzf -
301 ln -sfv /var/lib/arvados/go/bin/* /usr/local/bin/
310 if havepjsversion, err := exec.Command("/usr/local/bin/phantomjs", "--version").CombinedOutput(); err == nil && string(havepjsversion) == "1.9.8\n" {
311 logger.Print("phantomjs " + pjsversion + " already installed")
314 PJS=phantomjs-`+pjsversion+`-linux-x86_64
315 wget --progress=dot:giga -O- https://cache.arvados.org/$PJS.tar.bz2 | tar -C /var/lib/arvados -xjf -
316 ln -sfv /var/lib/arvados/$PJS/bin/phantomjs /usr/local/bin/
323 if havegeckoversion, err := exec.Command("/usr/local/bin/geckodriver", "--version").CombinedOutput(); err == nil && strings.Contains(string(havegeckoversion), " "+geckoversion+" ") {
324 logger.Print("geckodriver " + geckoversion + " already installed")
328 wget --progress=dot:giga -O- https://github.com/mozilla/geckodriver/releases/download/$GD/geckodriver-$GD-linux64.tar.gz | tar -C /var/lib/arvados/bin -xzf - geckodriver
329 ln -sfv /var/lib/arvados/bin/geckodriver /usr/local/bin/
336 if havegradleversion, err := exec.Command("/usr/local/bin/gradle", "--version").CombinedOutput(); err == nil && strings.Contains(string(havegradleversion), "Gradle "+gradleversion+"\n") {
337 logger.Print("gradle " + gradleversion + " already installed")
341 zip=/var/lib/arvados/tmp/gradle-${G}-bin.zip
343 wget --progress=dot:giga -O${zip} https://services.gradle.org/distributions/gradle-${G}-bin.zip
344 unzip -o -d /var/lib/arvados ${zip}
345 ln -sfv /var/lib/arvados/gradle-${G}/bin/gradle /usr/local/bin/
353 if havesingularityversion, err := exec.Command("/var/lib/arvados/bin/singularity", "--version").CombinedOutput(); err == nil && strings.Contains(string(havesingularityversion), singularityversion) {
354 logger.Print("singularity " + singularityversion + " already installed")
355 } else if dev || test {
357 S=`+singularityversion+`
358 tmp=/var/lib/arvados/tmp/singularity
359 trap "rm -r ${tmp}" ERR EXIT
360 cd /var/lib/arvados/tmp
361 git clone https://github.com/sylabs/singularity
364 ./mconfig --prefix=/var/lib/arvados
366 make -C ./builddir install
374 install /usr/bin/nsenter /var/lib/arvados/bin/nsenter
375 setcap "cap_sys_admin+pei cap_sys_chroot+pei" /var/lib/arvados/bin/nsenter
381 // The entry in /etc/locale.gen is "en_US.UTF-8"; once
382 // it's installed, locale -a reports it as
384 wantlocale := "en_US.UTF-8"
385 if havelocales, err := exec.Command("locale", "-a").CombinedOutput(); err == nil && bytes.Contains(havelocales, []byte(strings.Replace(wantlocale+"\n", "UTF-", "utf", 1))) {
386 logger.Print("locale " + wantlocale + " already installed")
388 err = inst.runBash(`sed -i 's/^# *\(`+wantlocale+`\)/\1/' /etc/locale.gen && locale-gen`, stdout, stderr)
403 if pgLsclusters, err2 := exec.Command("pg_lsclusters", "--no-header").CombinedOutput(); err2 != nil {
404 err = fmt.Errorf("pg_lsclusters: %s", err2)
406 } else if pgclusters := strings.Split(strings.TrimSpace(string(pgLsclusters)), "\n"); len(pgclusters) != 1 {
407 logger.Warnf("pg_lsclusters returned %d postgresql clusters -- skipping postgresql initdb/startup, hope that's ok", len(pgclusters))
408 } 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 {
409 err = fmt.Errorf("error parsing pg_lsclusters output: %s", err)
411 } else if pgc.Status == "online" {
412 logger.Infof("postgresql cluster %s-%s is online", pgc.Version, pgc.Cluster)
414 logger.Infof("postgresql cluster %s-%s is %s; trying to start", pgc.Version, pgc.Cluster, pgc.Status)
415 cmd := exec.Command("pg_ctlcluster", "--foreground", pgc.Version, pgc.Cluster, "start")
423 cmd.Process.Signal(syscall.SIGTERM)
424 logger.Info("sent SIGTERM; waiting for postgres to shut down")
427 err = waitPostgreSQLReady()
433 if os.Getpid() == 1 {
434 // We are the init process (presumably in a
435 // docker container) so although postgresql is
436 // installed, it's not running, and initdb
437 // might never have been run.
440 var needcoll []string
441 // If the en_US.UTF-8 locale wasn't installed when
442 // postgresql initdb ran, it needs to be added
443 // explicitly before we can use it in our test suite.
444 for _, collname := range []string{"en_US", "en_US.UTF-8"} {
445 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')")
447 out, err2 := cmd.CombinedOutput()
449 err = fmt.Errorf("error while checking postgresql collations: %s", err2)
452 if strings.Contains(string(out), "1") {
453 logger.Infof("postgresql supports collation %s", collname)
455 needcoll = append(needcoll, collname)
458 if len(needcoll) > 0 && os.Getpid() != 1 {
459 // In order for the CREATE COLLATION statement
460 // below to work, the locale must have existed
461 // when PostgreSQL started up. If we're
462 // running as init, we must have started
463 // PostgreSQL ourselves after installing the
464 // locales. Otherwise, it might need a
465 // restart, so we attempt to restart it with
467 if err = inst.runBash(`sudo systemctl restart postgresql`, stdout, stderr); err != nil {
468 logger.Warn("`systemctl restart postgresql` failed; hoping postgresql does not need to be restarted")
469 } else if err = waitPostgreSQLReady(); err != nil {
473 for _, collname := range needcoll {
474 cmd := exec.Command("sudo", "-u", "postgres", "psql", "-c", "CREATE COLLATION \""+collname+"\" (LOCALE = \"en_US.UTF-8\")")
480 err = fmt.Errorf("error adding postgresql collation %s: %s", collname, err)
485 withstuff := "WITH LOGIN SUPERUSER ENCRYPTED PASSWORD " + pq.QuoteLiteral(devtestDatabasePassword)
486 cmd := exec.Command("sudo", "-u", "postgres", "psql", "-c", "ALTER ROLE arvados "+withstuff)
488 if err := cmd.Run(); err == nil {
489 logger.Print("arvados role exists; superuser privileges added, password updated")
491 cmd := exec.Command("sudo", "-u", "postgres", "psql", "-c", "CREATE ROLE arvados "+withstuff)
503 if havenodejsversion, err := exec.Command("/usr/local/bin/node", "--version").CombinedOutput(); err == nil && string(havenodejsversion) == nodejsversion+"\n" {
504 logger.Print("nodejs " + nodejsversion + " already installed")
507 NJS=`+nodejsversion+`
508 wget --progress=dot:giga -O- https://nodejs.org/dist/${NJS}/node-${NJS}-linux-x64.tar.xz | sudo tar -C /var/lib/arvados -xJf -
509 ln -sfv /var/lib/arvados/node-${NJS}-linux-x64/bin/{node,npm} /usr/local/bin/
516 if haveyarnversion, err := exec.Command("/usr/local/bin/yarn", "--version").CombinedOutput(); err == nil && len(haveyarnversion) > 0 {
517 logger.Print("yarn " + strings.TrimSpace(string(haveyarnversion)) + " already installed")
521 ln -sfv /var/lib/arvados/node-`+nodejsversion+`-linux-x64/bin/{yarn,yarnpkg} /usr/local/bin/
528 if havewb2version, err := exec.Command("git", "--git-dir=/var/lib/arvados/arvados-workbench2/.git", "log", "-n1", "--format=%H").CombinedOutput(); err == nil && string(havewb2version) == workbench2version+"\n" {
529 logger.Print("workbench2 repo is already at " + workbench2version)
532 V=`+workbench2version+`
534 if [[ ! -e arvados-workbench2 ]]; then
535 git clone https://git.arvados.org/arvados-workbench2.git
536 cd arvados-workbench2
539 cd arvados-workbench2
540 if ! git checkout $V; then
542 git checkout yarn.lock
553 if err = inst.runBash(`
554 cd /var/lib/arvados/arvados-workbench2
556 `, stdout, stderr); err != nil {
562 // Install Go programs to /var/lib/arvados/bin/
563 for _, srcdir := range []string{
564 "cmd/arvados-client",
565 "cmd/arvados-server",
566 "services/crunch-dispatch-slurm",
568 fmt.Fprintf(stderr, "building %s...\n", srcdir)
569 cmd := exec.Command("go", "install", "-ldflags", "-X git.arvados.org/arvados.git/lib/cmd.version="+inst.PackageVersion+" -X main.version="+inst.PackageVersion+" -s -w")
570 cmd.Env = append(cmd.Env, os.Environ()...)
571 cmd.Env = append(cmd.Env, "GOBIN=/var/lib/arvados/bin")
572 cmd.Dir = filepath.Join(inst.SourcePath, srcdir)
581 // Symlink user-facing Go programs /usr/bin/x ->
582 // /var/lib/arvados/bin/x
583 for _, prog := range []string{"arvados-client", "arvados-server"} {
584 err = os.Remove("/usr/bin/" + prog)
585 if err != nil && !errors.Is(err, os.ErrNotExist) {
588 err = os.Symlink("/var/lib/arvados/bin/"+prog, "/usr/bin/"+prog)
594 // Copy assets from source tree to /var/lib/arvados/share
595 cmd := exec.Command("install", "-v", "-t", "/var/lib/arvados/share", filepath.Join(inst.SourcePath, "sdk/python/tests/nginx.conf"))
603 // Install Rails apps to /var/lib/arvados/{railsapi,workbench1}/
604 for dstdir, srcdir := range map[string]string{
605 "railsapi": "services/api",
606 "workbench1": "apps/workbench",
608 fmt.Fprintf(stderr, "building %s...\n", srcdir)
609 cmd := exec.Command("rsync",
610 "-a", "--no-owner", "--no-group", "--delete-after", "--delete-excluded",
611 "--exclude", "/coverage",
613 "--exclude", "/node_modules",
615 "--exclude", "/public/assets",
616 "--exclude", "/vendor",
617 "--exclude", "/config/environments",
618 "./", "/var/lib/arvados/"+dstdir+"/")
619 cmd.Dir = filepath.Join(inst.SourcePath, srcdir)
626 for _, cmdline := range [][]string{
627 {"mkdir", "-p", "log", "public/assets", "tmp", "vendor", ".bundle", "/var/www/.bundle", "/var/www/.gem", "/var/www/.npm", "/var/www/.passenger"},
628 {"touch", "log/production.log"},
629 {"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"},
630 {"sudo", "-u", "www-data", "/var/lib/arvados/bin/gem", "install", "--user", "--conservative", "--no-document", "bundler:" + bundlerversion},
631 {"sudo", "-u", "www-data", "/var/lib/arvados/bin/bundle", "install", "--deployment", "--jobs", "8", "--path", "/var/www/.gem", "--without", "development test diagnostics performance"},
633 {"chown", "www-data:www-data", ".", "public/assets"},
634 // {"sudo", "-u", "www-data", "/var/lib/arvados/bin/bundle", "config", "set", "--local", "system", "true"},
635 {"sudo", "-u", "www-data", "ARVADOS_CONFIG=none", "RAILS_GROUPS=assets", "RAILS_ENV=production", "/var/lib/arvados/bin/bundle", "exec", "rake", "npm:install"},
636 {"sudo", "-u", "www-data", "ARVADOS_CONFIG=none", "RAILS_GROUPS=assets", "RAILS_ENV=production", "/var/lib/arvados/bin/bundle", "exec", "rake", "assets:precompile"},
637 {"chown", "root:root", "."},
638 {"chown", "-R", "root:root", "public/assets", "vendor"},
640 {"sudo", "-u", "www-data", "/var/lib/arvados/bin/bundle", "exec", "passenger-config", "build-native-support"},
641 {"sudo", "-u", "www-data", "/var/lib/arvados/bin/bundle", "exec", "passenger-config", "install-standalone-runtime"},
643 if cmdline[len(cmdline)-2] == "rake" && dstdir != "workbench1" {
646 cmd = exec.Command(cmdline[0], cmdline[1:]...)
647 cmd.Dir = "/var/lib/arvados/" + dstdir
650 fmt.Fprintf(stderr, "... %s\n", cmd.Args)
656 cmd = exec.Command("sudo", "-u", "www-data", "/var/lib/arvados/bin/bundle", "exec", "passenger-config", "validate-install")
657 cmd.Dir = "/var/lib/arvados/" + dstdir
661 if err != nil && !strings.Contains(err.Error(), "exit status 2") {
662 // Exit code 2 indicates there were warnings (like
663 // "other passenger installations have been detected",
664 // which we can't expect to avoid) but no errors.
665 // Other non-zero exit codes (1, 9) indicate errors.
670 // Install workbench2 app to /var/lib/arvados/workbench2/
671 if err = inst.runBash(`
672 cd /var/lib/arvados/arvados-workbench2
673 VERSION="`+inst.PackageVersion+`" BUILD_NUMBER=1 GIT_COMMIT="`+workbench2version[:9]+`" yarn build
674 rsync -a --delete-after build/ /var/lib/arvados/workbench2/
675 `, stdout, stderr); err != nil {
679 err = os.WriteFile("/lib/systemd/system/arvados.service", arvadosServiceFile, 0777)
683 // This is equivalent to "systemd enable", but does
684 // not depend on the systemctl program being
686 symlink := "/etc/systemd/system/multi-user.target.wants/arvados.service"
687 err = os.Remove(symlink)
688 if err != nil && !errors.Is(err, os.ErrNotExist) {
691 err = os.Symlink("/lib/systemd/system/arvados.service", symlink)
700 type osversion struct {
707 func identifyOS() (osversion, error) {
709 f, err := os.Open("/etc/os-release")
715 kv := map[string]string{}
716 scanner := bufio.NewScanner(f)
718 line := strings.TrimSpace(scanner.Text())
719 if strings.HasPrefix(line, "#") {
722 toks := strings.SplitN(line, "=", 2)
724 return osv, fmt.Errorf("invalid line in /etc/os-release: %q", line)
727 v := strings.Trim(toks[1], `"`)
729 v = strings.Trim(v, `'`)
733 if err = scanner.Err(); err != nil {
744 return osv, fmt.Errorf("unsupported ID in /etc/os-release: %q", kv["ID"])
746 vstr := kv["VERSION_ID"]
747 if i := strings.Index(vstr, "."); i > 0 {
750 osv.Major, err = strconv.Atoi(vstr)
752 return osv, fmt.Errorf("incomprehensible VERSION_ID in /etc/os-release: %q", kv["VERSION_ID"])
757 func waitPostgreSQLReady() error {
758 for deadline := time.Now().Add(10 * time.Second); ; {
759 output, err := exec.Command("pg_isready").CombinedOutput()
762 } else if time.Now().After(deadline) {
763 return fmt.Errorf("timed out waiting for pg_isready (%q)", output)
765 time.Sleep(time.Second)
770 func (inst *installCommand) runBash(script string, stdout, stderr io.Writer) error {
771 cmd := exec.Command("bash", "-")
773 cmd = exec.Command("eatmydata", "bash", "-")
775 cmd.Stdin = bytes.NewBufferString("set -ex -o pipefail\n" + script)
781 func prodpkgs(osv osversion) []string {
796 if osv.Debian || osv.Ubuntu {
797 if osv.Debian && osv.Major == 8 {
798 pkgs = append(pkgs, "libgnutls-deb0-28") // sdk/cwl
799 } else if osv.Debian && osv.Major >= 10 || osv.Ubuntu && osv.Major >= 16 {
800 pkgs = append(pkgs, "python3-distutils") // sdk/cwl
804 "libcurl4-openssl-dev", // services/api
806 "libpython2.7", // services/fuse
807 "mime-support", // keep-web
808 "zlib1g-dev", // services/api
810 } else if osv.Centos {
812 "fuse-libs", // services/fuse
815 "libcurl-devel", // services/api
816 "mailcap", // keep-web
817 "postgresql-devel", // services/api
820 panic("os version not supported")
824 func ProductionDependencies() ([]string, error) {
825 osv, err := identifyOS()
829 return prodpkgs(osv), nil