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",
185 case osv.Debian && osv.Major >= 10:
186 pkgs = append(pkgs, "libcurl4")
188 pkgs = append(pkgs, "libcurl3")
190 cmd := exec.CommandContext(ctx, "apt-get")
192 cmd = exec.CommandContext(ctx, "eatmydata", "apt-get")
194 cmd.Args = append(cmd.Args, "install", "--yes", "--no-install-recommends")
195 cmd.Args = append(cmd.Args, pkgs...)
196 cmd.Env = append(os.Environ(), "DEBIAN_FRONTEND=noninteractive")
205 os.Mkdir("/var/lib/arvados", 0755)
206 os.Mkdir("/var/lib/arvados/tmp", 0700)
208 os.Mkdir("/var/lib/arvados/wwwtmp", 0700)
209 u, er := user.Lookup("www-data")
211 err = fmt.Errorf("user.Lookup(%q): %w", "www-data", er)
214 uid, _ := strconv.Atoi(u.Uid)
215 gid, _ := strconv.Atoi(u.Gid)
216 err = os.Chown("/var/lib/arvados/wwwtmp", uid, gid)
221 rubyversion := "2.7.2"
222 rubymajorversion := rubyversion[:strings.LastIndex(rubyversion, ".")]
223 if haverubyversion, err := exec.Command("/var/lib/arvados/bin/ruby", "-v").CombinedOutput(); err == nil && bytes.HasPrefix(haverubyversion, []byte("ruby "+rubyversion)) {
224 logger.Print("ruby " + rubyversion + " already installed")
228 trap 'rm -r "${tmp}"' ERR EXIT
229 wget --progress=dot:giga -O- https://cache.ruby-lang.org/pub/ruby/`+rubymajorversion+`/ruby-`+rubyversion+`.tar.gz | tar -C "${tmp}" -xzf -
230 cd "${tmp}/ruby-`+rubyversion+`"
231 ./configure --disable-install-static-library --enable-shared --disable-install-doc --prefix /var/lib/arvados
234 /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 wget --progress=dot:giga -O- https://storage.googleapis.com/golang/go`+goversion+`.linux-amd64.tar.gz | tar -C /var/lib/arvados -xzf -
249 ln -sf /var/lib/arvados/go/bin/* /usr/local/bin/
258 pjsversion := "1.9.8"
259 if havepjsversion, err := exec.Command("/usr/local/bin/phantomjs", "--version").CombinedOutput(); err == nil && string(havepjsversion) == "1.9.8\n" {
260 logger.Print("phantomjs " + pjsversion + " already installed")
263 PJS=phantomjs-`+pjsversion+`-linux-x86_64
264 wget --progress=dot:giga -O- https://bitbucket.org/ariya/phantomjs/downloads/$PJS.tar.bz2 | tar -C /var/lib/arvados -xjf -
265 ln -sf /var/lib/arvados/$PJS/bin/phantomjs /usr/local/bin/
272 geckoversion := "0.24.0"
273 if havegeckoversion, err := exec.Command("/usr/local/bin/geckodriver", "--version").CombinedOutput(); err == nil && strings.Contains(string(havegeckoversion), " "+geckoversion+" ") {
274 logger.Print("geckodriver " + geckoversion + " already installed")
278 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
279 ln -sf /var/lib/arvados/bin/geckodriver /usr/local/bin/
286 nodejsversion := "v8.15.1"
287 if havenodejsversion, err := exec.Command("/usr/local/bin/node", "--version").CombinedOutput(); err == nil && string(havenodejsversion) == nodejsversion+"\n" {
288 logger.Print("nodejs " + nodejsversion + " already installed")
291 NJS=`+nodejsversion+`
292 wget --progress=dot:giga -O- https://nodejs.org/dist/${NJS}/node-${NJS}-linux-x64.tar.xz | sudo tar -C /var/lib/arvados -xJf -
293 ln -sf /var/lib/arvados/node-${NJS}-linux-x64/bin/{node,npm} /usr/local/bin/
300 gradleversion := "5.3.1"
301 if havegradleversion, err := exec.Command("/usr/local/bin/gradle", "--version").CombinedOutput(); err == nil && strings.Contains(string(havegradleversion), "Gradle "+gradleversion+"\n") {
302 logger.Print("gradle " + gradleversion + " already installed")
306 zip=/var/lib/arvados/tmp/gradle-${G}-bin.zip
308 wget --progress=dot:giga -O${zip} https://services.gradle.org/distributions/gradle-${G}-bin.zip
309 unzip -o -d /var/lib/arvados ${zip}
310 ln -sf /var/lib/arvados/gradle-${G}/bin/gradle /usr/local/bin/
318 // The entry in /etc/locale.gen is "en_US.UTF-8"; once
319 // it's installed, locale -a reports it as
321 wantlocale := "en_US.UTF-8"
322 if havelocales, err := exec.Command("locale", "-a").CombinedOutput(); err == nil && bytes.Contains(havelocales, []byte(strings.Replace(wantlocale+"\n", "UTF-", "utf", 1))) {
323 logger.Print("locale " + wantlocale + " already installed")
325 err = inst.runBash(`sed -i 's/^# *\(`+wantlocale+`\)/\1/' /etc/locale.gen && locale-gen`, stdout, stderr)
340 if pgLsclusters, err2 := exec.Command("pg_lsclusters", "--no-header").CombinedOutput(); err2 != nil {
341 err = fmt.Errorf("pg_lsclusters: %s", err2)
343 } else if pgclusters := strings.Split(strings.TrimSpace(string(pgLsclusters)), "\n"); len(pgclusters) != 1 {
344 logger.Warnf("pg_lsclusters returned %d postgresql clusters -- skipping postgresql initdb/startup, hope that's ok", len(pgclusters))
345 } 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 {
346 err = fmt.Errorf("error parsing pg_lsclusters output: %s", err)
348 } else if pgc.Status == "online" {
349 logger.Infof("postgresql cluster %s-%s is online", pgc.Version, pgc.Cluster)
351 logger.Infof("postgresql cluster %s-%s is %s; trying to start", pgc.Version, pgc.Cluster, pgc.Status)
352 cmd := exec.Command("pg_ctlcluster", "--foreground", pgc.Version, pgc.Cluster, "start")
360 cmd.Process.Signal(syscall.SIGTERM)
361 logger.Info("sent SIGTERM; waiting for postgres to shut down")
364 err = waitPostgreSQLReady()
370 if os.Getpid() == 1 {
371 // We are the init process (presumably in a
372 // docker container) so although postgresql is
373 // installed, it's not running, and initdb
374 // might never have been run.
377 var needcoll []string
378 // If the en_US.UTF-8 locale wasn't installed when
379 // postgresql initdb ran, it needs to be added
380 // explicitly before we can use it in our test suite.
381 for _, collname := range []string{"en_US", "en_US.UTF-8"} {
382 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')")
384 out, err2 := cmd.CombinedOutput()
386 err = fmt.Errorf("error while checking postgresql collations: %s", err2)
389 if strings.Contains(string(out), "1") {
390 logger.Infof("postgresql supports collation %s", collname)
392 needcoll = append(needcoll, collname)
395 if len(needcoll) > 0 && os.Getpid() != 1 {
396 // In order for the CREATE COLLATION statement
397 // below to work, the locale must have existed
398 // when PostgreSQL started up. If we're
399 // running as init, we must have started
400 // PostgreSQL ourselves after installing the
401 // locales. Otherwise, it might need a
402 // restart, so we attempt to restart it with
404 if err = inst.runBash(`sudo systemctl restart postgresql`, stdout, stderr); err != nil {
405 logger.Warn("`systemctl restart postgresql` failed; hoping postgresql does not need to be restarted")
406 } else if err = waitPostgreSQLReady(); err != nil {
410 for _, collname := range needcoll {
411 cmd := exec.Command("sudo", "-u", "postgres", "psql", "-c", "CREATE COLLATION \""+collname+"\" (LOCALE = \"en_US.UTF-8\")")
417 err = fmt.Errorf("error adding postgresql collation %s: %s", collname, err)
422 withstuff := "WITH LOGIN SUPERUSER ENCRYPTED PASSWORD " + pq.QuoteLiteral(devtestDatabasePassword)
423 cmd := exec.Command("sudo", "-u", "postgres", "psql", "-c", "ALTER ROLE arvados "+withstuff)
425 if err := cmd.Run(); err == nil {
426 logger.Print("arvados role exists; superuser privileges added, password updated")
428 cmd := exec.Command("sudo", "-u", "postgres", "psql", "-c", "CREATE ROLE arvados "+withstuff)
440 // Install Rails apps to /var/lib/arvados/{railsapi,workbench1}/
441 for dstdir, srcdir := range map[string]string{
442 "railsapi": "services/api",
443 "workbench1": "apps/workbench",
445 fmt.Fprintf(stderr, "building %s...\n", srcdir)
446 cmd := exec.Command("rsync",
447 "-a", "--no-owner", "--no-group", "--delete-after", "--delete-excluded",
448 "--exclude", "/coverage",
451 "--exclude", "/vendor",
452 "./", "/var/lib/arvados/"+dstdir+"/")
453 cmd.Dir = filepath.Join(inst.SourcePath, srcdir)
460 for _, cmdline := range [][]string{
461 {"mkdir", "-p", "log", "tmp", ".bundle", "/var/www/.gem", "/var/www/.bundle", "/var/www/.passenger"},
462 {"touch", "log/production.log"},
463 {"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"},
464 {"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"},
465 {"sudo", "-u", "www-data", "/var/lib/arvados/bin/bundle", "install", "--deployment", "--jobs", "8", "--path", "/var/www/.gem"},
466 {"sudo", "-u", "www-data", "/var/lib/arvados/bin/bundle", "exec", "passenger-config", "build-native-support"},
467 {"sudo", "-u", "www-data", "/var/lib/arvados/bin/bundle", "exec", "passenger-config", "install-standalone-runtime"},
469 cmd = exec.Command(cmdline[0], cmdline[1:]...)
470 cmd.Dir = "/var/lib/arvados/" + dstdir
473 fmt.Fprintf(stderr, "... %s\n", cmd.Args)
479 cmd = exec.Command("sudo", "-u", "www-data", "/var/lib/arvados/bin/bundle", "exec", "passenger-config", "validate-install")
480 cmd.Dir = "/var/lib/arvados/" + dstdir
484 if err != nil && !strings.Contains(err.Error(), "exit status 2") {
485 // Exit code 2 indicates there were warnings (like
486 // "other passenger installations have been detected",
487 // which we can't expect to avoid) but no errors.
488 // Other non-zero exit codes (1, 9) indicate errors.
493 // Install Go programs to /var/lib/arvados/bin/
494 for _, srcdir := range []string{
495 "cmd/arvados-client",
496 "cmd/arvados-server",
497 "services/arv-git-httpd",
498 "services/crunch-dispatch-local",
499 "services/crunch-dispatch-slurm",
501 "services/keep-balance",
503 "services/keepproxy",
504 "services/keepstore",
507 fmt.Fprintf(stderr, "building %s...\n", srcdir)
508 cmd := exec.Command("go", "install", "-ldflags", "-X git.arvados.org/arvados.git/lib/cmd.version="+inst.PackageVersion+" -X main.version="+inst.PackageVersion)
509 cmd.Env = append(cmd.Env, os.Environ()...)
510 cmd.Env = append(cmd.Env, "GOBIN=/var/lib/arvados/bin")
511 cmd.Dir = filepath.Join(inst.SourcePath, srcdir)
520 // Copy assets from source tree to /var/lib/arvados/share
521 cmd := exec.Command("install", "-v", "-t", "/var/lib/arvados/share", filepath.Join(inst.SourcePath, "sdk/python/tests/nginx.conf"))
533 type osversion struct {
540 func identifyOS() (osversion, error) {
542 f, err := os.Open("/etc/os-release")
548 kv := map[string]string{}
549 scanner := bufio.NewScanner(f)
551 line := strings.TrimSpace(scanner.Text())
552 if strings.HasPrefix(line, "#") {
555 toks := strings.SplitN(line, "=", 2)
557 return osv, fmt.Errorf("invalid line in /etc/os-release: %q", line)
560 v := strings.Trim(toks[1], `"`)
562 v = strings.Trim(v, `'`)
566 if err = scanner.Err(); err != nil {
577 return osv, fmt.Errorf("unsupported ID in /etc/os-release: %q", kv["ID"])
579 vstr := kv["VERSION_ID"]
580 if i := strings.Index(vstr, "."); i > 0 {
583 osv.Major, err = strconv.Atoi(vstr)
585 return osv, fmt.Errorf("incomprehensible VERSION_ID in /etc/os-release: %q", kv["VERSION_ID"])
590 func waitPostgreSQLReady() error {
591 for deadline := time.Now().Add(10 * time.Second); ; {
592 output, err := exec.Command("pg_isready").CombinedOutput()
595 } else if time.Now().After(deadline) {
596 return fmt.Errorf("timed out waiting for pg_isready (%q)", output)
598 time.Sleep(time.Second)
603 func (inst *installCommand) runBash(script string, stdout, stderr io.Writer) error {
604 cmd := exec.Command("bash", "-")
606 cmd = exec.Command("eatmydata", "bash", "-")
608 cmd.Stdin = bytes.NewBufferString("set -ex -o pipefail\n" + script)
614 func prodpkgs(osv osversion) []string {
629 if osv.Debian || osv.Ubuntu {
630 if osv.Debian && osv.Major == 8 {
631 pkgs = append(pkgs, "libgnutls-deb0-28") // sdk/cwl
632 } else if osv.Debian && osv.Major >= 10 || osv.Ubuntu && osv.Major >= 16 {
633 pkgs = append(pkgs, "python3-distutils") // sdk/cwl
637 "libcurl4-openssl-dev", // services/api
639 "libpython2.7", // services/fuse
640 "mime-support", // keep-web
641 "zlib1g-dev", // services/api
643 } else if osv.Centos {
645 "fuse-libs", // services/fuse
648 "libcurl-devel", // services/api
649 "mailcap", // keep-web
650 "postgresql-devel", // services/api
653 panic("os version not supported")
657 func ProductionDependencies() ([]string, error) {
658 osv, err := identifyOS()
662 return prodpkgs(osv), nil