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"
33 type installCommand struct {
40 func (inst *installCommand) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
41 logger := ctxlog.New(stderr, "text", "info")
42 ctx := ctxlog.Context(context.Background(), logger)
43 ctx, cancel := context.WithCancel(ctx)
49 logger.WithError(err).Info("exiting")
53 flags := flag.NewFlagSet(prog, flag.ContinueOnError)
54 flags.SetOutput(stderr)
55 versionFlag := flags.Bool("version", false, "Write version information to stdout and exit 0")
56 flags.StringVar(&inst.ClusterType, "type", "production", "cluster `type`: development, test, production, or package")
57 flags.StringVar(&inst.SourcePath, "source", "/arvados", "source tree location (required for -type=package)")
58 flags.StringVar(&inst.PackageVersion, "package-version", "0.0.0", "version string to embed in executable files")
59 flags.BoolVar(&inst.EatMyData, "eatmydata", false, "use eatmydata to speed up install")
60 err = flags.Parse(args)
61 if err == flag.ErrHelp {
64 } else if err != nil {
66 } else if *versionFlag {
67 return cmd.Version.RunCommand(prog, args, stdin, stdout, stderr)
68 } else if len(flags.Args()) > 0 {
69 err = fmt.Errorf("unrecognized command line arguments: %v", flags.Args())
73 var dev, test, prod, pkg bool
74 switch inst.ClusterType {
84 err = fmt.Errorf("invalid cluster type %q (must be 'development', 'test', 'production', or 'package')", inst.ClusterType)
89 err = errors.New("production install is not yet implemented")
93 osv, err := identifyOS()
98 listdir, err := os.Open("/var/lib/apt/lists")
100 logger.Warnf("error while checking whether to run apt-get update: %s", err)
101 } else if names, _ := listdir.Readdirnames(1); len(names) == 0 {
102 // Special case for a base docker image where the
103 // package cache has been deleted and all "apt-get
104 // install" commands will fail unless we fetch repos.
105 cmd := exec.CommandContext(ctx, "apt-get", "update")
115 cmd := exec.CommandContext(ctx, "apt-get", "install", "--yes", "--no-install-recommends", "eatmydata")
116 cmd.Env = append(os.Environ(), "DEBIAN_FRONTEND=noninteractive")
125 pkgs := prodpkgs(osv)
130 "eatmydata", // install it for later steps, even if we're not using it now
135 if dev || test || pkg {
144 "default-jdk-headless",
145 "default-jre-headless",
149 "libcrypt-ssleay-perl",
169 "postgresql-contrib",
172 "python3-virtualenv",
186 "squashfs-tools", // for singularity
190 case osv.Debian && osv.Major >= 10:
191 pkgs = append(pkgs, "libcurl4")
193 pkgs = append(pkgs, "libcurl3")
195 cmd := exec.CommandContext(ctx, "apt-get")
197 cmd = exec.CommandContext(ctx, "eatmydata", "apt-get")
199 cmd.Args = append(cmd.Args, "install", "--yes", "--no-install-recommends")
200 cmd.Args = append(cmd.Args, pkgs...)
201 cmd.Env = append(os.Environ(), "DEBIAN_FRONTEND=noninteractive")
210 os.Mkdir("/var/lib/arvados", 0755)
211 os.Mkdir("/var/lib/arvados/tmp", 0700)
213 os.Mkdir("/var/lib/arvados/wwwtmp", 0700)
214 u, er := user.Lookup("www-data")
216 err = fmt.Errorf("user.Lookup(%q): %w", "www-data", er)
219 uid, _ := strconv.Atoi(u.Uid)
220 gid, _ := strconv.Atoi(u.Gid)
221 err = os.Chown("/var/lib/arvados/wwwtmp", uid, gid)
226 rubyversion := "2.7.2"
227 rubymajorversion := rubyversion[:strings.LastIndex(rubyversion, ".")]
228 if haverubyversion, err := exec.Command("/var/lib/arvados/bin/ruby", "-v").CombinedOutput(); err == nil && bytes.HasPrefix(haverubyversion, []byte("ruby "+rubyversion)) {
229 logger.Print("ruby " + rubyversion + " already installed")
233 trap 'rm -r "${tmp}"' ERR EXIT
234 wget --progress=dot:giga -O- https://cache.ruby-lang.org/pub/ruby/`+rubymajorversion+`/ruby-`+rubyversion+`.tar.gz | tar -C "${tmp}" -xzf -
235 cd "${tmp}/ruby-`+rubyversion+`"
236 ./configure --disable-install-static-library --enable-shared --disable-install-doc --prefix /var/lib/arvados
239 /var/lib/arvados/bin/gem install bundler --no-document
247 goversion := "1.16.3"
248 if havegoversion, err := exec.Command("/usr/local/bin/go", "version").CombinedOutput(); err == nil && bytes.HasPrefix(havegoversion, []byte("go version go"+goversion+" ")) {
249 logger.Print("go " + goversion + " already installed")
253 wget --progress=dot:giga -O- https://storage.googleapis.com/golang/go`+goversion+`.linux-amd64.tar.gz | tar -C /var/lib/arvados -xzf -
254 ln -sf /var/lib/arvados/go/bin/* /usr/local/bin/
263 pjsversion := "1.9.8"
264 if havepjsversion, err := exec.Command("/usr/local/bin/phantomjs", "--version").CombinedOutput(); err == nil && string(havepjsversion) == "1.9.8\n" {
265 logger.Print("phantomjs " + pjsversion + " already installed")
268 PJS=phantomjs-`+pjsversion+`-linux-x86_64
269 wget --progress=dot:giga -O- https://bitbucket.org/ariya/phantomjs/downloads/$PJS.tar.bz2 | tar -C /var/lib/arvados -xjf -
270 ln -sf /var/lib/arvados/$PJS/bin/phantomjs /usr/local/bin/
277 geckoversion := "0.24.0"
278 if havegeckoversion, err := exec.Command("/usr/local/bin/geckodriver", "--version").CombinedOutput(); err == nil && strings.Contains(string(havegeckoversion), " "+geckoversion+" ") {
279 logger.Print("geckodriver " + geckoversion + " already installed")
283 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
284 ln -sf /var/lib/arvados/bin/geckodriver /usr/local/bin/
291 nodejsversion := "v10.23.1"
292 if havenodejsversion, err := exec.Command("/usr/local/bin/node", "--version").CombinedOutput(); err == nil && string(havenodejsversion) == nodejsversion+"\n" {
293 logger.Print("nodejs " + nodejsversion + " already installed")
296 NJS=`+nodejsversion+`
297 wget --progress=dot:giga -O- https://nodejs.org/dist/${NJS}/node-${NJS}-linux-x64.tar.xz | sudo tar -C /var/lib/arvados -xJf -
298 ln -sf /var/lib/arvados/node-${NJS}-linux-x64/bin/{node,npm} /usr/local/bin/
305 gradleversion := "5.3.1"
306 if havegradleversion, err := exec.Command("/usr/local/bin/gradle", "--version").CombinedOutput(); err == nil && strings.Contains(string(havegradleversion), "Gradle "+gradleversion+"\n") {
307 logger.Print("gradle " + gradleversion + " already installed")
311 zip=/var/lib/arvados/tmp/gradle-${G}-bin.zip
313 wget --progress=dot:giga -O${zip} https://services.gradle.org/distributions/gradle-${G}-bin.zip
314 unzip -o -d /var/lib/arvados ${zip}
315 ln -sf /var/lib/arvados/gradle-${G}/bin/gradle /usr/local/bin/
323 singularityversion := "3.5.2"
324 if havesingularityversion, err := exec.Command("/var/lib/arvados/bin/singularity", "--version").CombinedOutput(); err == nil && strings.Contains(string(havesingularityversion), singularityversion) {
325 logger.Print("singularity " + singularityversion + " already installed")
326 } else if dev || test {
328 S=`+singularityversion+`
329 tmp=/var/lib/arvados/tmp/singularity
330 trap "rm -r ${tmp}" ERR EXIT
331 cd /var/lib/arvados/tmp
332 git clone https://github.com/sylabs/singularity
335 ./mconfig --prefix=/var/lib/arvados
337 make -C ./builddir install
345 // The entry in /etc/locale.gen is "en_US.UTF-8"; once
346 // it's installed, locale -a reports it as
348 wantlocale := "en_US.UTF-8"
349 if havelocales, err := exec.Command("locale", "-a").CombinedOutput(); err == nil && bytes.Contains(havelocales, []byte(strings.Replace(wantlocale+"\n", "UTF-", "utf", 1))) {
350 logger.Print("locale " + wantlocale + " already installed")
352 err = inst.runBash(`sed -i 's/^# *\(`+wantlocale+`\)/\1/' /etc/locale.gen && locale-gen`, stdout, stderr)
367 if pgLsclusters, err2 := exec.Command("pg_lsclusters", "--no-header").CombinedOutput(); err2 != nil {
368 err = fmt.Errorf("pg_lsclusters: %s", err2)
370 } else if pgclusters := strings.Split(strings.TrimSpace(string(pgLsclusters)), "\n"); len(pgclusters) != 1 {
371 logger.Warnf("pg_lsclusters returned %d postgresql clusters -- skipping postgresql initdb/startup, hope that's ok", len(pgclusters))
372 } 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 {
373 err = fmt.Errorf("error parsing pg_lsclusters output: %s", err)
375 } else if pgc.Status == "online" {
376 logger.Infof("postgresql cluster %s-%s is online", pgc.Version, pgc.Cluster)
378 logger.Infof("postgresql cluster %s-%s is %s; trying to start", pgc.Version, pgc.Cluster, pgc.Status)
379 cmd := exec.Command("pg_ctlcluster", "--foreground", pgc.Version, pgc.Cluster, "start")
387 cmd.Process.Signal(syscall.SIGTERM)
388 logger.Info("sent SIGTERM; waiting for postgres to shut down")
391 err = waitPostgreSQLReady()
397 if os.Getpid() == 1 {
398 // We are the init process (presumably in a
399 // docker container) so although postgresql is
400 // installed, it's not running, and initdb
401 // might never have been run.
404 var needcoll []string
405 // If the en_US.UTF-8 locale wasn't installed when
406 // postgresql initdb ran, it needs to be added
407 // explicitly before we can use it in our test suite.
408 for _, collname := range []string{"en_US", "en_US.UTF-8"} {
409 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')")
411 out, err2 := cmd.CombinedOutput()
413 err = fmt.Errorf("error while checking postgresql collations: %s", err2)
416 if strings.Contains(string(out), "1") {
417 logger.Infof("postgresql supports collation %s", collname)
419 needcoll = append(needcoll, collname)
422 if len(needcoll) > 0 && os.Getpid() != 1 {
423 // In order for the CREATE COLLATION statement
424 // below to work, the locale must have existed
425 // when PostgreSQL started up. If we're
426 // running as init, we must have started
427 // PostgreSQL ourselves after installing the
428 // locales. Otherwise, it might need a
429 // restart, so we attempt to restart it with
431 if err = inst.runBash(`sudo systemctl restart postgresql`, stdout, stderr); err != nil {
432 logger.Warn("`systemctl restart postgresql` failed; hoping postgresql does not need to be restarted")
433 } else if err = waitPostgreSQLReady(); err != nil {
437 for _, collname := range needcoll {
438 cmd := exec.Command("sudo", "-u", "postgres", "psql", "-c", "CREATE COLLATION \""+collname+"\" (LOCALE = \"en_US.UTF-8\")")
444 err = fmt.Errorf("error adding postgresql collation %s: %s", collname, err)
449 withstuff := "WITH LOGIN SUPERUSER ENCRYPTED PASSWORD " + pq.QuoteLiteral(devtestDatabasePassword)
450 cmd := exec.Command("sudo", "-u", "postgres", "psql", "-c", "ALTER ROLE arvados "+withstuff)
452 if err := cmd.Run(); err == nil {
453 logger.Print("arvados role exists; superuser privileges added, password updated")
455 cmd := exec.Command("sudo", "-u", "postgres", "psql", "-c", "CREATE ROLE arvados "+withstuff)
467 // Install Rails apps to /var/lib/arvados/{railsapi,workbench1}/
468 for dstdir, srcdir := range map[string]string{
469 "railsapi": "services/api",
470 "workbench1": "apps/workbench",
472 fmt.Fprintf(stderr, "building %s...\n", srcdir)
473 cmd := exec.Command("rsync",
474 "-a", "--no-owner", "--no-group", "--delete-after", "--delete-excluded",
475 "--exclude", "/coverage",
478 "--exclude", "/vendor",
479 "--exclude", "/config/environments",
480 "./", "/var/lib/arvados/"+dstdir+"/")
481 cmd.Dir = filepath.Join(inst.SourcePath, srcdir)
488 for _, cmdline := range [][]string{
489 {"mkdir", "-p", "log", "tmp", ".bundle", "/var/www/.gem", "/var/www/.bundle", "/var/www/.passenger"},
490 {"touch", "log/production.log"},
491 {"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"},
492 {"sudo", "-u", "www-data", "/var/lib/arvados/bin/gem", "install", "--user", "--conservative", "--no-document", "bundler:1.16.6", "bundler:1.17.3", "bundler:2.0.2"},
493 {"sudo", "-u", "www-data", "/var/lib/arvados/bin/bundle", "install", "--deployment", "--jobs", "8", "--path", "/var/www/.gem"},
494 {"sudo", "-u", "www-data", "/var/lib/arvados/bin/bundle", "exec", "passenger-config", "build-native-support"},
495 {"sudo", "-u", "www-data", "/var/lib/arvados/bin/bundle", "exec", "passenger-config", "install-standalone-runtime"},
497 cmd = exec.Command(cmdline[0], cmdline[1:]...)
498 cmd.Dir = "/var/lib/arvados/" + dstdir
501 fmt.Fprintf(stderr, "... %s\n", cmd.Args)
507 cmd = exec.Command("sudo", "-u", "www-data", "/var/lib/arvados/bin/bundle", "exec", "passenger-config", "validate-install")
508 cmd.Dir = "/var/lib/arvados/" + dstdir
512 if err != nil && !strings.Contains(err.Error(), "exit status 2") {
513 // Exit code 2 indicates there were warnings (like
514 // "other passenger installations have been detected",
515 // which we can't expect to avoid) but no errors.
516 // Other non-zero exit codes (1, 9) indicate errors.
521 // Install Go programs to /var/lib/arvados/bin/
522 for _, srcdir := range []string{
523 "cmd/arvados-client",
524 "cmd/arvados-server",
525 "services/arv-git-httpd",
526 "services/crunch-dispatch-local",
527 "services/crunch-dispatch-slurm",
529 "services/keep-balance",
531 "services/keepproxy",
532 "services/keepstore",
535 fmt.Fprintf(stderr, "building %s...\n", srcdir)
536 cmd := exec.Command("go", "install", "-ldflags", "-X git.arvados.org/arvados.git/lib/cmd.version="+inst.PackageVersion+" -X main.version="+inst.PackageVersion)
537 cmd.Env = append(cmd.Env, os.Environ()...)
538 cmd.Env = append(cmd.Env, "GOBIN=/var/lib/arvados/bin")
539 cmd.Dir = filepath.Join(inst.SourcePath, srcdir)
548 // Copy assets from source tree to /var/lib/arvados/share
549 cmd := exec.Command("install", "-v", "-t", "/var/lib/arvados/share", filepath.Join(inst.SourcePath, "sdk/python/tests/nginx.conf"))
561 type osversion struct {
568 func identifyOS() (osversion, error) {
570 f, err := os.Open("/etc/os-release")
576 kv := map[string]string{}
577 scanner := bufio.NewScanner(f)
579 line := strings.TrimSpace(scanner.Text())
580 if strings.HasPrefix(line, "#") {
583 toks := strings.SplitN(line, "=", 2)
585 return osv, fmt.Errorf("invalid line in /etc/os-release: %q", line)
588 v := strings.Trim(toks[1], `"`)
590 v = strings.Trim(v, `'`)
594 if err = scanner.Err(); err != nil {
605 return osv, fmt.Errorf("unsupported ID in /etc/os-release: %q", kv["ID"])
607 vstr := kv["VERSION_ID"]
608 if i := strings.Index(vstr, "."); i > 0 {
611 osv.Major, err = strconv.Atoi(vstr)
613 return osv, fmt.Errorf("incomprehensible VERSION_ID in /etc/os-release: %q", kv["VERSION_ID"])
618 func waitPostgreSQLReady() error {
619 for deadline := time.Now().Add(10 * time.Second); ; {
620 output, err := exec.Command("pg_isready").CombinedOutput()
623 } else if time.Now().After(deadline) {
624 return fmt.Errorf("timed out waiting for pg_isready (%q)", output)
626 time.Sleep(time.Second)
631 func (inst *installCommand) runBash(script string, stdout, stderr io.Writer) error {
632 cmd := exec.Command("bash", "-")
634 cmd = exec.Command("eatmydata", "bash", "-")
636 cmd.Stdin = bytes.NewBufferString("set -ex -o pipefail\n" + script)
642 func prodpkgs(osv osversion) []string {
657 if osv.Debian || osv.Ubuntu {
658 if osv.Debian && osv.Major == 8 {
659 pkgs = append(pkgs, "libgnutls-deb0-28") // sdk/cwl
660 } else if osv.Debian && osv.Major >= 10 || osv.Ubuntu && osv.Major >= 16 {
661 pkgs = append(pkgs, "python3-distutils") // sdk/cwl
665 "libcurl4-openssl-dev", // services/api
667 "libpython2.7", // services/fuse
668 "mime-support", // keep-web
669 "zlib1g-dev", // services/api
671 } else if osv.Centos {
673 "fuse-libs", // services/fuse
676 "libcurl-devel", // services/api
677 "mailcap", // keep-web
678 "postgresql-devel", // services/api
681 panic("os version not supported")
685 func ProductionDependencies() ([]string, error) {
686 osv, err := identifyOS()
690 return prodpkgs(osv), nil