1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
24 "git.arvados.org/arvados.git/lib/cmd"
25 "git.arvados.org/arvados.git/sdk/go/ctxlog"
29 var Command cmd.Handler = &installCommand{}
31 const devtestDatabasePassword = "insecure_arvados_test"
32 const goversion = "1.17.1"
34 type installCommand struct {
41 func (inst *installCommand) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
42 logger := ctxlog.New(stderr, "text", "info")
43 ctx := ctxlog.Context(context.Background(), logger)
44 ctx, cancel := context.WithCancel(ctx)
50 logger.WithError(err).Info("exiting")
54 flags := flag.NewFlagSet(prog, flag.ContinueOnError)
55 flags.SetOutput(stderr)
56 versionFlag := flags.Bool("version", false, "Write version information to stdout and exit 0")
57 flags.StringVar(&inst.ClusterType, "type", "production", "cluster `type`: development, test, production, or package")
58 flags.StringVar(&inst.SourcePath, "source", "/arvados", "source tree location (required for -type=package)")
59 flags.StringVar(&inst.PackageVersion, "package-version", "0.0.0", "version string to embed in executable files")
60 flags.BoolVar(&inst.EatMyData, "eatmydata", false, "use eatmydata to speed up install")
62 if ok, code := cmd.ParseFlags(flags, prog, args, "", stderr); !ok {
64 } else if *versionFlag {
65 return cmd.Version.RunCommand(prog, args, stdin, stdout, stderr)
68 var dev, test, prod, pkg bool
69 switch inst.ClusterType {
79 err = fmt.Errorf("invalid cluster type %q (must be 'development', 'test', 'production', or 'package')", inst.ClusterType)
84 err = errors.New("production install is not yet implemented")
88 osv, err := identifyOS()
93 listdir, err := os.Open("/var/lib/apt/lists")
95 logger.Warnf("error while checking whether to run apt-get update: %s", err)
96 } else if names, _ := listdir.Readdirnames(1); len(names) == 0 {
97 // Special case for a base docker image where the
98 // package cache has been deleted and all "apt-get
99 // install" commands will fail unless we fetch repos.
100 cmd := exec.CommandContext(ctx, "apt-get", "update")
110 cmd := exec.CommandContext(ctx, "apt-get", "install", "--yes", "--no-install-recommends", "eatmydata")
111 cmd.Env = append(os.Environ(), "DEBIAN_FRONTEND=noninteractive")
120 pkgs := prodpkgs(osv)
125 "eatmydata", // install it for later steps, even if we're not using it now
130 if dev || test || pkg {
139 "default-jdk-headless",
140 "default-jre-headless",
144 "libcrypt-ssleay-perl",
164 "postgresql-contrib",
167 "python3-virtualenv",
182 "squashfs-tools", // for singularity
186 case osv.Debian && osv.Major >= 10:
187 pkgs = append(pkgs, "libcurl4")
189 pkgs = append(pkgs, "libcurl3")
191 cmd := exec.CommandContext(ctx, "apt-get")
193 cmd = exec.CommandContext(ctx, "eatmydata", "apt-get")
195 cmd.Args = append(cmd.Args, "install", "--yes", "--no-install-recommends")
196 cmd.Args = append(cmd.Args, pkgs...)
197 cmd.Env = append(os.Environ(), "DEBIAN_FRONTEND=noninteractive")
206 os.Mkdir("/var/lib/arvados", 0755)
207 os.Mkdir("/var/lib/arvados/tmp", 0700)
209 os.Mkdir("/var/lib/arvados/wwwtmp", 0700)
210 u, er := user.Lookup("www-data")
212 err = fmt.Errorf("user.Lookup(%q): %w", "www-data", er)
215 uid, _ := strconv.Atoi(u.Uid)
216 gid, _ := strconv.Atoi(u.Gid)
217 err = os.Chown("/var/lib/arvados/wwwtmp", uid, gid)
222 rubyversion := "2.7.2"
223 rubymajorversion := rubyversion[:strings.LastIndex(rubyversion, ".")]
224 if haverubyversion, err := exec.Command("/var/lib/arvados/bin/ruby", "-v").CombinedOutput(); err == nil && bytes.HasPrefix(haverubyversion, []byte("ruby "+rubyversion)) {
225 logger.Print("ruby " + rubyversion + " already installed")
229 trap 'rm -r "${tmp}"' ERR EXIT
230 wget --progress=dot:giga -O- https://cache.ruby-lang.org/pub/ruby/`+rubymajorversion+`/ruby-`+rubyversion+`.tar.gz | tar -C "${tmp}" -xzf -
231 cd "${tmp}/ruby-`+rubyversion+`"
232 ./configure --disable-install-static-library --enable-shared --disable-install-doc --prefix /var/lib/arvados
235 /var/lib/arvados/bin/gem install bundler --no-document
243 if havegoversion, err := exec.Command("/usr/local/bin/go", "version").CombinedOutput(); err == nil && bytes.HasPrefix(havegoversion, []byte("go version go"+goversion+" ")) {
244 logger.Print("go " + goversion + " already installed")
248 rm -rf /var/lib/arvados/go/
249 wget --progress=dot:giga -O- https://storage.googleapis.com/golang/go`+goversion+`.linux-amd64.tar.gz | tar -C /var/lib/arvados -xzf -
250 ln -sf /var/lib/arvados/go/bin/* /usr/local/bin/
259 pjsversion := "1.9.8"
260 if havepjsversion, err := exec.Command("/usr/local/bin/phantomjs", "--version").CombinedOutput(); err == nil && string(havepjsversion) == "1.9.8\n" {
261 logger.Print("phantomjs " + pjsversion + " already installed")
264 PJS=phantomjs-`+pjsversion+`-linux-x86_64
265 wget --progress=dot:giga -O- https://bitbucket.org/ariya/phantomjs/downloads/$PJS.tar.bz2 | tar -C /var/lib/arvados -xjf -
266 ln -sf /var/lib/arvados/$PJS/bin/phantomjs /usr/local/bin/
273 geckoversion := "0.24.0"
274 if havegeckoversion, err := exec.Command("/usr/local/bin/geckodriver", "--version").CombinedOutput(); err == nil && strings.Contains(string(havegeckoversion), " "+geckoversion+" ") {
275 logger.Print("geckodriver " + geckoversion + " already installed")
279 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
280 ln -sf /var/lib/arvados/bin/geckodriver /usr/local/bin/
287 nodejsversion := "v12.22.2"
288 if havenodejsversion, err := exec.Command("/usr/local/bin/node", "--version").CombinedOutput(); err == nil && string(havenodejsversion) == nodejsversion+"\n" {
289 logger.Print("nodejs " + nodejsversion + " already installed")
292 NJS=`+nodejsversion+`
293 wget --progress=dot:giga -O- https://nodejs.org/dist/${NJS}/node-${NJS}-linux-x64.tar.xz | sudo tar -C /var/lib/arvados -xJf -
294 ln -sf /var/lib/arvados/node-${NJS}-linux-x64/bin/{node,npm} /usr/local/bin/
301 gradleversion := "5.3.1"
302 if havegradleversion, err := exec.Command("/usr/local/bin/gradle", "--version").CombinedOutput(); err == nil && strings.Contains(string(havegradleversion), "Gradle "+gradleversion+"\n") {
303 logger.Print("gradle " + gradleversion + " already installed")
307 zip=/var/lib/arvados/tmp/gradle-${G}-bin.zip
309 wget --progress=dot:giga -O${zip} https://services.gradle.org/distributions/gradle-${G}-bin.zip
310 unzip -o -d /var/lib/arvados ${zip}
311 ln -sf /var/lib/arvados/gradle-${G}/bin/gradle /usr/local/bin/
319 singularityversion := "3.7.4"
320 if havesingularityversion, err := exec.Command("/var/lib/arvados/bin/singularity", "--version").CombinedOutput(); err == nil && strings.Contains(string(havesingularityversion), singularityversion) {
321 logger.Print("singularity " + singularityversion + " already installed")
322 } else if dev || test {
324 S=`+singularityversion+`
325 tmp=/var/lib/arvados/tmp/singularity
326 trap "rm -r ${tmp}" ERR EXIT
327 cd /var/lib/arvados/tmp
328 git clone https://github.com/sylabs/singularity
331 ./mconfig --prefix=/var/lib/arvados
333 make -C ./builddir install
340 // The entry in /etc/locale.gen is "en_US.UTF-8"; once
341 // it's installed, locale -a reports it as
343 wantlocale := "en_US.UTF-8"
344 if havelocales, err := exec.Command("locale", "-a").CombinedOutput(); err == nil && bytes.Contains(havelocales, []byte(strings.Replace(wantlocale+"\n", "UTF-", "utf", 1))) {
345 logger.Print("locale " + wantlocale + " already installed")
347 err = inst.runBash(`sed -i 's/^# *\(`+wantlocale+`\)/\1/' /etc/locale.gen && locale-gen`, stdout, stderr)
362 if pgLsclusters, err2 := exec.Command("pg_lsclusters", "--no-header").CombinedOutput(); err2 != nil {
363 err = fmt.Errorf("pg_lsclusters: %s", err2)
365 } else if pgclusters := strings.Split(strings.TrimSpace(string(pgLsclusters)), "\n"); len(pgclusters) != 1 {
366 logger.Warnf("pg_lsclusters returned %d postgresql clusters -- skipping postgresql initdb/startup, hope that's ok", len(pgclusters))
367 } 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 {
368 err = fmt.Errorf("error parsing pg_lsclusters output: %s", err)
370 } else if pgc.Status == "online" {
371 logger.Infof("postgresql cluster %s-%s is online", pgc.Version, pgc.Cluster)
373 logger.Infof("postgresql cluster %s-%s is %s; trying to start", pgc.Version, pgc.Cluster, pgc.Status)
374 cmd := exec.Command("pg_ctlcluster", "--foreground", pgc.Version, pgc.Cluster, "start")
382 cmd.Process.Signal(syscall.SIGTERM)
383 logger.Info("sent SIGTERM; waiting for postgres to shut down")
386 err = waitPostgreSQLReady()
392 if os.Getpid() == 1 {
393 // We are the init process (presumably in a
394 // docker container) so although postgresql is
395 // installed, it's not running, and initdb
396 // might never have been run.
399 var needcoll []string
400 // If the en_US.UTF-8 locale wasn't installed when
401 // postgresql initdb ran, it needs to be added
402 // explicitly before we can use it in our test suite.
403 for _, collname := range []string{"en_US", "en_US.UTF-8"} {
404 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')")
406 out, err2 := cmd.CombinedOutput()
408 err = fmt.Errorf("error while checking postgresql collations: %s", err2)
411 if strings.Contains(string(out), "1") {
412 logger.Infof("postgresql supports collation %s", collname)
414 needcoll = append(needcoll, collname)
417 if len(needcoll) > 0 && os.Getpid() != 1 {
418 // In order for the CREATE COLLATION statement
419 // below to work, the locale must have existed
420 // when PostgreSQL started up. If we're
421 // running as init, we must have started
422 // PostgreSQL ourselves after installing the
423 // locales. Otherwise, it might need a
424 // restart, so we attempt to restart it with
426 if err = inst.runBash(`sudo systemctl restart postgresql`, stdout, stderr); err != nil {
427 logger.Warn("`systemctl restart postgresql` failed; hoping postgresql does not need to be restarted")
428 } else if err = waitPostgreSQLReady(); err != nil {
432 for _, collname := range needcoll {
433 cmd := exec.Command("sudo", "-u", "postgres", "psql", "-c", "CREATE COLLATION \""+collname+"\" (LOCALE = \"en_US.UTF-8\")")
439 err = fmt.Errorf("error adding postgresql collation %s: %s", collname, err)
444 withstuff := "WITH LOGIN SUPERUSER ENCRYPTED PASSWORD " + pq.QuoteLiteral(devtestDatabasePassword)
445 cmd := exec.Command("sudo", "-u", "postgres", "psql", "-c", "ALTER ROLE arvados "+withstuff)
447 if err := cmd.Run(); err == nil {
448 logger.Print("arvados role exists; superuser privileges added, password updated")
450 cmd := exec.Command("sudo", "-u", "postgres", "psql", "-c", "CREATE ROLE arvados "+withstuff)
462 // Install Rails apps to /var/lib/arvados/{railsapi,workbench1}/
463 for dstdir, srcdir := range map[string]string{
464 "railsapi": "services/api",
465 "workbench1": "apps/workbench",
467 fmt.Fprintf(stderr, "building %s...\n", srcdir)
468 cmd := exec.Command("rsync",
469 "-a", "--no-owner", "--no-group", "--delete-after", "--delete-excluded",
470 "--exclude", "/coverage",
473 "--exclude", "/vendor",
474 "--exclude", "/config/environments",
475 "./", "/var/lib/arvados/"+dstdir+"/")
476 cmd.Dir = filepath.Join(inst.SourcePath, srcdir)
483 for _, cmdline := range [][]string{
484 {"mkdir", "-p", "log", "tmp", ".bundle", "/var/www/.gem", "/var/www/.bundle", "/var/www/.passenger"},
485 {"touch", "log/production.log"},
486 {"chown", "-R", "--from=root", "www-data:www-data", "/var/www/.gem", "/var/www/.bundle", "/var/www/.passenger", "log", "tmp", ".bundle", "Gemfile.lock", "config.ru", "config/environment.rb"},
487 {"sudo", "-u", "www-data", "/var/lib/arvados/bin/gem", "install", "--user", "--conservative", "--no-document", "bundler:2.2.19"},
488 {"sudo", "-u", "www-data", "/var/lib/arvados/bin/bundle", "install", "--deployment", "--jobs", "8", "--path", "/var/www/.gem"},
489 {"sudo", "-u", "www-data", "/var/lib/arvados/bin/bundle", "exec", "passenger-config", "build-native-support"},
490 {"sudo", "-u", "www-data", "/var/lib/arvados/bin/bundle", "exec", "passenger-config", "install-standalone-runtime"},
492 cmd = exec.Command(cmdline[0], cmdline[1:]...)
493 cmd.Dir = "/var/lib/arvados/" + dstdir
496 fmt.Fprintf(stderr, "... %s\n", cmd.Args)
502 cmd = exec.Command("sudo", "-u", "www-data", "/var/lib/arvados/bin/bundle", "exec", "passenger-config", "validate-install")
503 cmd.Dir = "/var/lib/arvados/" + dstdir
507 if err != nil && !strings.Contains(err.Error(), "exit status 2") {
508 // Exit code 2 indicates there were warnings (like
509 // "other passenger installations have been detected",
510 // which we can't expect to avoid) but no errors.
511 // Other non-zero exit codes (1, 9) indicate errors.
516 // Install Go programs to /var/lib/arvados/bin/
517 for _, srcdir := range []string{
518 "cmd/arvados-client",
519 "cmd/arvados-server",
520 "services/arv-git-httpd",
521 "services/crunch-dispatch-local",
522 "services/crunch-dispatch-slurm",
524 "services/keep-balance",
526 "services/keepproxy",
527 "services/keepstore",
530 fmt.Fprintf(stderr, "building %s...\n", srcdir)
531 cmd := exec.Command("go", "install", "-ldflags", "-X git.arvados.org/arvados.git/lib/cmd.version="+inst.PackageVersion+" -X main.version="+inst.PackageVersion)
532 cmd.Env = append(cmd.Env, os.Environ()...)
533 cmd.Env = append(cmd.Env, "GOBIN=/var/lib/arvados/bin")
534 cmd.Dir = filepath.Join(inst.SourcePath, srcdir)
543 // Copy assets from source tree to /var/lib/arvados/share
544 cmd := exec.Command("install", "-v", "-t", "/var/lib/arvados/share", filepath.Join(inst.SourcePath, "sdk/python/tests/nginx.conf"))
556 type osversion struct {
563 func identifyOS() (osversion, error) {
565 f, err := os.Open("/etc/os-release")
571 kv := map[string]string{}
572 scanner := bufio.NewScanner(f)
574 line := strings.TrimSpace(scanner.Text())
575 if strings.HasPrefix(line, "#") {
578 toks := strings.SplitN(line, "=", 2)
580 return osv, fmt.Errorf("invalid line in /etc/os-release: %q", line)
583 v := strings.Trim(toks[1], `"`)
585 v = strings.Trim(v, `'`)
589 if err = scanner.Err(); err != nil {
600 return osv, fmt.Errorf("unsupported ID in /etc/os-release: %q", kv["ID"])
602 vstr := kv["VERSION_ID"]
603 if i := strings.Index(vstr, "."); i > 0 {
606 osv.Major, err = strconv.Atoi(vstr)
608 return osv, fmt.Errorf("incomprehensible VERSION_ID in /etc/os-release: %q", kv["VERSION_ID"])
613 func waitPostgreSQLReady() error {
614 for deadline := time.Now().Add(10 * time.Second); ; {
615 output, err := exec.Command("pg_isready").CombinedOutput()
618 } else if time.Now().After(deadline) {
619 return fmt.Errorf("timed out waiting for pg_isready (%q)", output)
621 time.Sleep(time.Second)
626 func (inst *installCommand) runBash(script string, stdout, stderr io.Writer) error {
627 cmd := exec.Command("bash", "-")
629 cmd = exec.Command("eatmydata", "bash", "-")
631 cmd.Stdin = bytes.NewBufferString("set -ex -o pipefail\n" + script)
637 func prodpkgs(osv osversion) []string {
652 if osv.Debian || osv.Ubuntu {
653 if osv.Debian && osv.Major == 8 {
654 pkgs = append(pkgs, "libgnutls-deb0-28") // sdk/cwl
655 } else if osv.Debian && osv.Major >= 10 || osv.Ubuntu && osv.Major >= 16 {
656 pkgs = append(pkgs, "python3-distutils") // sdk/cwl
660 "libcurl4-openssl-dev", // services/api
662 "libpython2.7", // services/fuse
663 "mime-support", // keep-web
664 "zlib1g-dev", // services/api
666 } else if osv.Centos {
668 "fuse-libs", // services/fuse
671 "libcurl-devel", // services/api
672 "mailcap", // keep-web
673 "postgresql-devel", // services/api
676 panic("os version not supported")
680 func ProductionDependencies() ([]string, error) {
681 osv, err := identifyOS()
685 return prodpkgs(osv), nil