]> git.arvados.org - arvados.git/blob - build/run-tests.sh
22406: Set libpq environment variables unconditionally
[arvados.git] / build / run-tests.sh
1 #!/bin/bash
2 # Copyright (C) The Arvados Authors. All rights reserved.
3 #
4 # SPDX-License-Identifier: AGPL-3.0
5
6 COLUMNS=80
7 . `dirname "$(readlink -f "$0")"`/run-library.sh
8
9 read -rd "\000" helpmessage <<EOF
10 $(basename $0): Install and test Arvados components.
11
12 Exit non-zero if any tests fail.
13
14 Syntax:
15         $(basename $0) WORKSPACE=/path/to/arvados [options]
16
17 Options:
18
19 --skip FOO     Do not test the FOO component.
20 --skip sanity  Skip initial dev environment sanity checks.
21 --skip install Do not run any install steps. Just run tests.
22                You should provide GOPATH, GEMHOME, and VENVDIR options
23                from a previous invocation if you use this option.
24 --only FOO     Do not test anything except the FOO component. If given
25                more than once, all specified test suites are run.
26 --temp DIR     Install components and dependencies under DIR instead of
27                making a new temporary directory. Implies --leave-temp.
28 --leave-temp   Do not remove GOPATH, virtualenv, and other temp dirs at exit.
29                Instead, show the path to give as --temp to reuse them in
30                subsequent invocations.
31 --repeat N     Repeat each install/test step until it succeeds N times.
32 --retry        Prompt to retry if an install or test suite fails.
33 --only-install Run specific install step. If given more than once,
34                all but the last are ignored.
35 --short        Skip (or scale down) some slow tests.
36 --interactive  Set up, then prompt for test/install steps to perform.
37 WORKSPACE=path Arvados source tree to test.
38 CONFIGSRC=path Dir with config.yml file containing PostgreSQL section for use by tests.
39 services/api_test="TEST=test/functional/arvados/v1/collections_controller_test.rb"
40                Restrict apiserver tests to the given file
41 sdk/python_test="tests/test_api.py::ArvadosApiTest"
42                Restrict Python SDK tests to the given class
43 lib/dispatchcloud_test="-check.vv"
44                Show all log messages, even when tests pass (also works
45                with services/keepstore_test etc.)
46 ARVADOS_DEBUG=1
47                Print more debug messages
48 envvar=value   Set \$envvar to value. Primarily useful for WORKSPACE,
49                *_test, and other examples shown above.
50
51 Assuming "--skip install" is not given, all components are installed
52 into \$GOPATH, \$VENDIR, and \$GEMHOME before running any tests. Many
53 test suites depend on other components being installed, and installing
54 everything tends to be quicker than debugging dependencies.
55
56 As a special concession to the current CI server config, CONFIGSRC
57 defaults to $HOME/arvados-api-server if that directory exists.
58
59 More information and background:
60
61 https://dev.arvados.org/projects/arvados/wiki/Running_tests
62 EOF
63
64 # First make sure to remove any ARVADOS_ variables from the calling
65 # environment that could interfere with the tests.
66 unset $(env | cut -d= -f1 | grep \^ARVADOS_)
67
68 # Reset other variables that could affect our [tests'] behavior by
69 # accident.
70 GITDIR=
71 GOPATH=
72 VENV3DIR=
73 PYTHONPATH=
74 GEMHOME=
75 R_LIBS=
76 export LANG=en_US.UTF-8
77
78 short=
79 only_install=
80 temp=
81 temp_preserve=
82
83 ignore_sigint=
84
85 clear_temp() {
86     if [[ -z "$temp" ]]; then
87         # we did not even get as far as making a temp dir
88         :
89     elif [[ -z "$temp_preserve" ]]; then
90         # Go creates readonly dirs in the module cache, which cause
91         # "rm -rf" to fail unless we chmod first.
92         chmod -R u+w "$temp"
93         rm -rf "$temp"
94     else
95         echo "Leaving behind temp dirs in $temp"
96     fi
97 }
98
99 fatal() {
100     clear_temp
101     echo >&2 "Fatal: $* (encountered in ${FUNCNAME[1]} at ${BASH_SOURCE[1]} line ${BASH_LINENO[0]})"
102     exit 1
103 }
104
105 exit_cleanly() {
106     trap - INT
107     stop_services
108     rotate_logfile "$WORKSPACE/services/api/log/" "test.log"
109     report_outcomes
110     clear_temp
111     exit ${#failures}
112 }
113
114 sanity_checks() {
115     [[ -n "${skip[sanity]}" ]] && return 0
116     ( [[ -n "$WORKSPACE" ]] && [[ -d "$WORKSPACE/services" ]] ) \
117         || fatal "WORKSPACE environment variable not set to a source directory (see: $0 --help)"
118     [[ -z "$CONFIGSRC" ]] || [[ -s "$CONFIGSRC/config.yml" ]] \
119         || fatal "CONFIGSRC is $CONFIGSRC but '$CONFIGSRC/config.yml' is empty or not found (see: $0 --help)"
120     echo Checking dependencies:
121     echo "locale: ${LANG}"
122     [[ "$(locale charmap)" = "UTF-8" ]] \
123         || fatal "Locale '${LANG}' is broken/missing. Try: echo ${LANG} | sudo tee -a /etc/locale.gen && sudo locale-gen"
124     echo -n 'ruby: '
125     ruby -v \
126         || fatal "No ruby. Install >=2.7 from package or source"
127     echo -n 'go: '
128     go version \
129         || fatal "No go binary. See http://golang.org/doc/install"
130     [[ $(go version) =~ go1.([0-9]+) ]] && [[ ${BASH_REMATCH[1]} -ge 12 ]] \
131         || fatal "Go >= 1.12 required. See http://golang.org/doc/install"
132     echo -n 'gcc: '
133     gcc --version | egrep ^gcc \
134         || fatal "No gcc. Try: apt-get install build-essential"
135     echo -n 'fuse.h: '
136     find /usr/include -path '*fuse/fuse.h' | egrep --max-count=1 . \
137         || fatal "No fuse/fuse.h. Try: apt-get install libfuse-dev"
138     echo -n 'virtualenv: '
139     python3 -m venv --help | grep -q '^usage: venv ' \
140         && echo "venv module found" \
141         || fatal "No virtualenv. Try: apt-get install python3-venv"
142     echo -n 'Python3 pyconfig.h: '
143     find /usr/include -path '*/python3*/pyconfig.h' | egrep --max-count=1 . \
144         || fatal "No Python3 pyconfig.h. Try: apt-get install python3-dev"
145     which netstat \
146         || fatal "No netstat. Try: apt-get install net-tools"
147     echo -n 'nginx: '
148     PATH="$PATH:/sbin:/usr/sbin:/usr/local/sbin" nginx -v \
149         || fatal "No nginx. Try: apt-get install nginx"
150     echo -n 'npm: '
151     npm --version \
152         || fatal "No npm. Try: wget -O- https://nodejs.org/dist/v12.22.12/node-v12.22.12-linux-x64.tar.xz | sudo tar -C /usr/local -xJf - && sudo ln -s ../node-v12.22.12-linux-x64/bin/{node,npm} /usr/local/bin/"
153     echo -n 'cadaver: '
154     cadaver --version | grep -w cadaver \
155           || fatal "No cadaver. Try: apt-get install cadaver"
156     echo -n "jq: "
157     jq --version ||
158         fatal "No jq. Try: apt-get install jq"
159     echo -n 'libcurl curl.h: '
160     find /usr/include -path '*/curl/curl.h' | egrep --max-count=1 . \
161         || fatal "No libcurl curl.h. Try: apt-get install libcurl4-gnutls-dev"
162     echo -n 'libpq libpq-fe.h: '
163     find /usr/include -path '*/postgresql/libpq-fe.h' | egrep --max-count=1 . \
164         || fatal "No libpq libpq-fe.h. Try: apt-get install libpq-dev"
165     echo -n 'libpam pam_appl.h: '
166     find /usr/include -path '*/security/pam_appl.h' | egrep --max-count=1 . \
167         || fatal "No libpam pam_appl.h. Try: apt-get install libpam0g-dev"
168     echo -n 'postgresql: '
169     psql --version || fatal "No postgresql. Try: apt-get install postgresql postgresql-client-common"
170     echo -n 'xvfb: '
171     which Xvfb || fatal "No xvfb. Try: apt-get install xvfb"
172     echo -n 'singularity: '
173     singularity --version || fatal "No singularity. Try: arvados-server install"
174     echo -n 'docker client: '
175     docker --version || echo "No docker client. Try: arvados-server install"
176     echo -n 'docker server: '
177     docker info --format='{{.ServerVersion}}' || echo "No docker server. Try: arvados-server install"
178
179     if [[ "$NEED_SDK_R" = true ]]; then
180       # R SDK stuff
181       echo -n 'R: '
182       which Rscript || fatal "No Rscript. Try: apt-get install r-base"
183       echo -n 'testthat: '
184       Rscript -e "library('testthat')" || fatal "No testthat. Try: apt-get install r-cran-testthat"
185       # needed for roxygen2, needed for devtools, needed for R sdk
186       pkg-config --exists libxml-2.0 || fatal "No libxml2. Try: apt-get install libxml2-dev"
187     fi
188     echo 'procs with /dev/fuse open:'
189     find /proc/*/fd -lname /dev/fuse 2>/dev/null | cut -d/ -f3 | xargs --no-run-if-empty ps -lywww
190     echo 'grep fuse /proc/self/mountinfo:'
191     grep fuse /proc/self/mountinfo
192 }
193
194 rotate_logfile() {
195   # i.e.  rotate_logfile "$WORKSPACE/services/api/log/" "test.log"
196   # $BUILD_NUMBER is set by Jenkins if this script is being called as part of a Jenkins run
197   if [[ -f "$1/$2" ]]; then
198     THEDATE=`date +%Y%m%d%H%M%S`
199     mv "$1/$2" "$1/$THEDATE-$BUILD_NUMBER-$2"
200     gzip "$1/$THEDATE-$BUILD_NUMBER-$2"
201   fi
202 }
203
204 checkpidfile() {
205     svc="$1"
206     pid="$(cat "$WORKSPACE/tmp/${svc}.pid")"
207     if [[ -z "$pid" ]] || ! kill -0 "$pid"; then
208         tail $WORKSPACE/tmp/${1}*.log
209         echo "${svc} pid ${pid} not running"
210         return 1
211     fi
212     echo "${svc} pid ${pid} ok"
213 }
214
215 checkhealth() {
216     svc="$1"
217     base="$(yq -r "(.Clusters.zzzzz.Services.$svc.InternalURLs | keys)[0]" "$ARVADOS_CONFIG")"
218     url="$base/_health/ping"
219     if ! curl -Ss -H "Authorization: Bearer e687950a23c3a9bceec28c6223a06c79" "${url}" | tee -a /dev/stderr | grep '"OK"'; then
220         echo "${url} failed"
221         return 1
222     fi
223 }
224
225 checkdiscoverydoc() {
226     dd="https://${1}/discovery/v1/apis/arvados/v1/rest"
227     if ! (set -o pipefail; curl -fsk "$dd" | grep -q ^{ ); then
228         echo >&2 "ERROR: could not retrieve discovery doc from RailsAPI at $dd"
229         tail -v $WORKSPACE/tmp/railsapi.log
230         return 1
231     fi
232     echo "${dd} ok"
233 }
234
235 start_services() {
236     if [[ -n "$ARVADOS_TEST_API_HOST" ]]; then
237         return 0
238     fi
239     echo 'Starting API, controller, keepproxy, keep-web, ws, and nginx ssl proxy...'
240     if [[ ! -d "$WORKSPACE/services/api/log" ]]; then
241         mkdir -p "$WORKSPACE/services/api/log"
242     fi
243     # Remove empty api.pid file if it exists
244     if [[ -f "$WORKSPACE/tmp/api.pid" && ! -s "$WORKSPACE/tmp/api.pid" ]]; then
245         rm -f "$WORKSPACE/tmp/api.pid"
246     fi
247     all_services_stopped=
248     fail=1
249
250     cd "$WORKSPACE" \
251         && eval $(python3 sdk/python/tests/run_test_server.py start --auth admin) \
252         && export ARVADOS_TEST_API_HOST="$ARVADOS_API_HOST" \
253         && export ARVADOS_TEST_API_INSTALLED="$$" \
254         && checkpidfile api \
255         && checkdiscoverydoc $ARVADOS_API_HOST \
256         && eval $(python3 sdk/python/tests/run_test_server.py start_nginx) \
257         && checkpidfile nginx \
258         && python3 sdk/python/tests/run_test_server.py start_controller \
259         && checkpidfile controller \
260         && checkhealth Controller \
261         && checkdiscoverydoc $ARVADOS_API_HOST \
262         && python3 sdk/python/tests/run_test_server.py start_keep_proxy \
263         && checkpidfile keepproxy \
264         && python3 sdk/python/tests/run_test_server.py start_keep-web \
265         && checkpidfile keep-web \
266         && checkhealth WebDAV \
267         && python3 sdk/python/tests/run_test_server.py start_ws \
268         && checkpidfile ws \
269         && export ARVADOS_TEST_PROXY_SERVICES=1 \
270         && (env | egrep ^ARVADOS) \
271         && fail=0
272     if [[ $fail != 0 ]]; then
273         unset ARVADOS_TEST_API_HOST
274     fi
275     return $fail
276 }
277
278 stop_services() {
279     if [[ -n "$all_services_stopped" ]]; then
280         return
281     fi
282     unset ARVADOS_TEST_API_HOST ARVADOS_TEST_PROXY_SERVICES
283     cd "$WORKSPACE" \
284         && python3 sdk/python/tests/run_test_server.py stop_nginx \
285         && python3 sdk/python/tests/run_test_server.py stop_ws \
286         && python3 sdk/python/tests/run_test_server.py stop_keep-web \
287         && python3 sdk/python/tests/run_test_server.py stop_keep_proxy \
288         && python3 sdk/python/tests/run_test_server.py stop_controller \
289         && python3 sdk/python/tests/run_test_server.py stop \
290         && all_services_stopped=1
291     unset ARVADOS_CONFIG
292 }
293
294 interrupt() {
295     if [[ -n "$ignore_sigint" ]]; then
296         echo >&2 "ignored SIGINT"
297         return
298     fi
299     failures+=("($(basename $0) interrupted)")
300     exit_cleanly
301 }
302 trap interrupt INT
303
304 setup_ruby_environment() {
305     # When our "bundle install"s need to install new gems to
306     # satisfy dependencies, we want them to go where "gem install
307     # --user-install" would put them. (However, if the caller has
308     # already set GEM_HOME, we assume that's where dependencies
309     # should be installed, and we should leave it alone.)
310
311     if [ -z "$GEM_HOME" ]; then
312         user_gempath="$(gem env gempath)"
313         export GEM_HOME="${user_gempath%%:*}"
314     fi
315     PATH="$(gem env gemdir)/bin:$PATH"
316
317     # When we build and install our own gems, we install them in our
318     # $GEMHOME tmpdir, and we want them to be at the front of GEM_PATH and
319     # PATH so integration tests prefer them over other versions that
320     # happen to be installed in $user_gempath, system dirs, etc.
321
322     tmpdir_gem_home="$(env - PATH="$PATH" HOME="$GEMHOME" gem env gempath | cut -f1 -d:)"
323     PATH="$tmpdir_gem_home/bin:$PATH"
324     export GEM_PATH="$tmpdir_gem_home:$(gem env gempath)"
325
326     echo "Will install dependencies to $(gem env gemdir)"
327     echo "Will install bundler and arvados gems to $tmpdir_gem_home"
328     echo "Gem search path is GEM_PATH=$GEM_PATH"
329     gem install --user --no-document --conservative --version '~> 2.4.0' bundler \
330         || fatal 'install bundler'
331 }
332
333 with_test_gemset() {
334     GEM_HOME="$tmpdir_gem_home" GEM_PATH="$tmpdir_gem_home" "$@"
335 }
336
337 gem_uninstall_if_exists() {
338     if gem list "$1\$" | egrep '^\w'; then
339         gem uninstall --force --all --executables "$1"
340     fi
341 }
342
343 setup_virtualenv() {
344     if [[ -z "${VENV3DIR:-}" ]]; then
345         fatal "setup_virtualenv called before \$VENV3DIR was set"
346     elif ! [[ -e "$VENV3DIR/bin/activate" ]]; then
347         python3 -m venv "$VENV3DIR" || fatal "virtualenv creation failed"
348         # Configure pip options we always want to use.
349         "$VENV3DIR/bin/pip" config --quiet --site set global.disable-pip-version-check true
350         "$VENV3DIR/bin/pip" config --quiet --site set global.no-input true
351         "$VENV3DIR/bin/pip" config --quiet --site set global.no-python-version-warning true
352         "$VENV3DIR/bin/pip" config --quiet --site set install.progress-bar off
353         # If we didn't have a virtualenv before, we couldn't have started any
354         # services. Set the flag used by stop_services to indicate that.
355         all_services_stopped=1
356     fi
357     . "$VENV3DIR/bin/activate" || fatal "virtualenv activation failed"
358     # pip >= 20.3 is necessary for modern dependency resolution.
359     # setuptools is our chosen Python build tool.
360     # wheel modernizes the venv (as of early 2024) and makes it more closely
361     # match our package build environment.
362     # We must have these in place *before* we install the PySDK below.
363     pip install "pip>=20.3" setuptools wheel ||
364         fatal "failed to install build packages in virtualenv"
365     # run-tests.sh uses run_test_server.py from the Python SDK.
366     # This requires both the Python SDK itself and PyYAML.
367     # Hence we must install these dependencies this early for the rest of the
368     # script to work.
369     # s3cmd is used by controller and keep-web tests.
370     # yq is used by controller tests and this script.
371     pip install PyYAML s3cmd "yq~=3.4" || fatal "failed to install test dependencies in virtualenv"
372     do_install_once sdk/python pip || fatal "failed to install PySDK in virtualenv"
373 }
374
375 initialize() {
376     # If dependencies like ruby, go, etc. are installed in
377     # /var/lib/arvados -- presumably by "arvados-server install" --
378     # then we want to use those versions, instead of whatever happens
379     # to be installed in /usr.
380     PATH="/var/lib/arvados/bin:${PATH}"
381     sanity_checks
382
383     echo "WORKSPACE=$WORKSPACE"
384     cd "$WORKSPACE"
385
386     if [[ -z "$temp" ]]; then
387         temp="$(mktemp -d)"
388     fi
389
390     # Set up temporary install dirs (unless existing dirs were supplied)
391     for tmpdir in VENV3DIR GOPATH GEMHOME R_LIBS
392     do
393         if [[ -z "${!tmpdir}" ]]; then
394             eval "$tmpdir"="$temp/$tmpdir"
395         fi
396         if ! [[ -d "${!tmpdir}" ]]; then
397             mkdir "${!tmpdir}" || fatal "can't create ${!tmpdir} (does $temp exist?)"
398         fi
399     done
400
401     rm -vf "${WORKSPACE}/tmp/*.log"
402
403     export R_LIBS
404
405     export GOPATH
406     # Make sure our compiled binaries under test override anything
407     # else that might be in the environment.
408     export PATH=$GOPATH/bin:$PATH
409
410     # Jenkins config requires that glob tmp/*.log match something. Ensure
411     # that happens even if we don't end up running services that set up
412     # logging.
413     mkdir -p "${WORKSPACE}/tmp/" || fatal "could not mkdir ${WORKSPACE}/tmp"
414     touch "${WORKSPACE}/tmp/controller.log" || fatal "could not touch ${WORKSPACE}/tmp/controller.log"
415
416     unset http_proxy https_proxy no_proxy
417
418     setup_ruby_environment
419     setup_virtualenv
420
421     echo "PATH is $PATH"
422 }
423
424 install_env() {
425     go mod download || fatal "Go deps failed"
426     which goimports >/dev/null || go install golang.org/x/tools/cmd/goimports@latest || fatal "Go setup failed"
427     # parameterized and pytest are direct dependencies of Python tests.
428     # pdoc is needed to build PySDK documentation.
429     pip install parameterized pdoc pytest ||
430         fatal "failed to install test+documentation packages in virtualenv"
431 }
432
433 retry() {
434     remain="${repeat}"
435     while :
436     do
437         if ${@}; then
438             if [[ "$remain" -gt 1 ]]; then
439                 remain=$((${remain}-1))
440                 title "(repeating ${remain} more times)"
441             else
442                 break
443             fi
444         elif [[ "$retry" == 1 ]]; then
445             read -p 'Try again? [Y/n] ' x
446             if [[ "$x" != "y" ]] && [[ "$x" != "" ]]
447             then
448                 break
449             fi
450         else
451             break
452         fi
453     done
454 }
455
456 do_test() {
457     case "${1}" in
458         services/workbench2_units | services/workbench2_integration)
459             suite=services/workbench2
460             ;;
461         *)
462             suite="${1}"
463             ;;
464     esac
465     if [[ -n "${skip[$suite]}" || \
466               -n "${skip[$1]}" || \
467               (${#only[@]} -ne 0 && ${only[$suite]} -eq 0 && ${only[$1]} -eq 0) ]]; then
468         return 0
469     fi
470     case "${1}" in
471         services/api)
472             stop_services
473             check_arvados_config "$1"
474             ;;
475         gofmt \
476             | arvados_version.py \
477             | cmd/arvados-package \
478             | doc \
479             | lib/boot \
480             | lib/cli \
481             | lib/cloud/azure \
482             | lib/cloud/cloudtest \
483             | lib/cloud/ec2 \
484             | lib/cmd \
485             | lib/dispatchcloud/sshexecutor \
486             | lib/dispatchcloud/worker \
487             | lib/install \
488             | services/workbench2_integration \
489             | services/workbench2_units \
490             )
491             check_arvados_config "$1"
492             # don't care whether services are running
493             ;;
494         *)
495             check_arvados_config "$1"
496             if ! start_services; then
497                 checkexit 1 "$1 tests"
498                 title "test $1 -- failed to start services"
499                 return 1
500             fi
501             ;;
502     esac
503     retry do_test_once ${@}
504 }
505
506 go_ldflags() {
507     version=${ARVADOS_VERSION:-$(git log -n1 --format=%H)-dev}
508     echo "-X git.arvados.org/arvados.git/lib/cmd.version=${version} -X main.version=${version} -s -w"
509 }
510
511 do_test_once() {
512     unset result
513
514     if [[ "$2" == pip ]]; then
515         # We need to install the module before testing to ensure all the
516         # dependencies are satisfied. We need to do this before we start
517         # the test header+timer.
518         do_install_once "$1" "$2" || return
519     fi
520
521     title "test $1"
522     timer_reset
523
524     result=
525     if [[ "$2" == "go" ]]
526     then
527         covername="coverage-$(echo "$1" | sed -e 's/\//_/g')"
528         coverflags=("-covermode=count" "-coverprofile=$WORKSPACE/tmp/.$covername.tmp")
529         testflags=()
530         if [[ "$1" == "cmd/arvados-package" ]]; then
531             testflags+=("-timeout" "20m")
532         fi
533         # We do "go install" here to catch compilation errors
534         # before trying "go test". Otherwise, coverage-reporting
535         # mode makes Go show the wrong line numbers when reporting
536         # compilation errors.
537         go install -ldflags "$(go_ldflags)" "$WORKSPACE/$1" && \
538             cd "$WORKSPACE/$1" && \
539             if [[ -n "${testargs[$1]}" ]]
540         then
541             # "go test -check.vv giturl" doesn't work, but this
542             # does:
543             go test ${short:+-short} ${testflags[@]} ${testargs[$1]}
544         else
545             # The above form gets verbose even when testargs is
546             # empty, so use this form in such cases:
547             go test ${short:+-short} ${testflags[@]} ${coverflags[@]} "git.arvados.org/arvados.git/$1"
548         fi
549         result=${result:-$?}
550         if [[ -f "$WORKSPACE/tmp/.$covername.tmp" ]]
551         then
552             go tool cover -html="$WORKSPACE/tmp/.$covername.tmp" -o "$WORKSPACE/tmp/$covername.html"
553             rm "$WORKSPACE/tmp/.$covername.tmp"
554         fi
555         [[ $result = 0 ]] && gofmt -e -d *.go
556     elif [[ "$2" == "pip" ]]
557     then
558         tries=0
559         while :
560         do
561             tries=$((${tries}+1))
562             env -C "$WORKSPACE/$1" python3 -m pytest ${testargs[$1]}
563             result=$?
564             # pytest uses exit code 2 to mean "test collection failed."
565             # See discussion in FUSE's IntegrationTest and MountTestBase.
566             if [[ ${tries} < 3 && ${result} == 2 ]]
567             then
568                 printf '\n*****\n%s tests exited with code 2 -- retrying\n*****\n\n' "$1"
569                 continue
570             else
571                 break
572             fi
573         done
574     elif [[ "$2" != "" ]]
575     then
576         "test_$2"
577     else
578         "test_$1"
579     fi
580     result=${result:-$?}
581     checkexit $result "$1 tests"
582     title "test $1 -- `timer`"
583     return $result
584 }
585
586 check_arvados_config() {
587     if [[ "$1" = "env" ]] ; then
588         return
589     fi
590     if [[ -z "$ARVADOS_CONFIG" ]] ; then
591         cd "$WORKSPACE"
592         eval $(python3 sdk/python/tests/run_test_server.py setup_config)
593     fi
594     # Set all PostgreSQL connection variables, and write a .pgpass, to connect
595     # to the test database, so test scripts can write `psql` commands with no
596     # additional configuration.
597     export PGPASSFILE="$WORKSPACE/tmp/.pgpass"
598     # services/api/config/arvados_config.rb hardcodes `arvados_test` as the
599     # database name.
600     export PGDATABASE=arvados_test
601     export PGHOST="$(yq -r .Clusters.zzzzz.PostgreSQL.Connection.host "$ARVADOS_CONFIG")"
602     export PGPORT="$(yq -r .Clusters.zzzzz.PostgreSQL.Connection.port "$ARVADOS_CONFIG")"
603     export PGUSER="$(yq -r .Clusters.zzzzz.PostgreSQL.Connection.user "$ARVADOS_CONFIG")"
604     local pgpassword="$(yq -r .Clusters.zzzzz.PostgreSQL.Connection.password "$ARVADOS_CONFIG")"
605     echo "$PGHOST:$PGPORT:$PGDATABASE:$PGUSER:$pgpassword" >"$PGPASSFILE"
606     chmod 0600 "$PGPASSFILE"
607 }
608
609 do_install() {
610     if [[ -n ${skip["install_$1"]} || -n "${skip[install]}" || ( -n "${only_install}" && "${only_install}" != "${1}" && "${only_install}" != "${2}" ) ]]; then
611         return 0
612     fi
613     check_arvados_config "$1"
614     retry do_install_once ${@}
615 }
616
617 do_install_once() {
618     title "install $1"
619     timer_reset
620
621     result=
622     if [[ "$2" == "go" ]]
623     then
624         go install -ldflags "$(go_ldflags)" "$WORKSPACE/$1"
625     elif [[ "$2" == "pip" ]]
626     then
627         # Generate _version.py before installing.
628         python3 "$WORKSPACE/$1/arvados_version.py" >/dev/null &&
629             pip install "$WORKSPACE/$1"
630     elif [[ "$2" != "" ]]
631     then
632         "install_$2"
633     else
634         "install_$1"
635     fi
636     result=${result:-$?}
637     checkexit $result "$1 install"
638     title "install $1 -- `timer`"
639     return $result
640 }
641
642 bundle_install_trylocal() {
643     (
644         set -e
645         echo "(Running bundle install --local. 'could not find package' messages are OK.)"
646         if ! bundle install --local --no-deployment; then
647             echo "(Running bundle install again, without --local.)"
648             bundle install --no-deployment
649         fi
650         bundle package
651     )
652 }
653
654 install_doc() {
655     cd "$WORKSPACE/doc" \
656         && bundle_install_trylocal \
657         && rm -rf .site
658 }
659
660 install_gem() {
661     gemname=$1
662     srcpath=$2
663     with_test_gemset gem_uninstall_if_exists "$gemname" \
664         && cd "$WORKSPACE/$srcpath" \
665         && bundle_install_trylocal \
666         && gem build "$gemname.gemspec" \
667         && with_test_gemset gem install --no-document $(ls -t "$gemname"-*.gem|head -n1)
668 }
669
670 install_sdk/ruby() {
671     install_gem arvados sdk/ruby
672 }
673
674 install_sdk/ruby-google-api-client() {
675     install_gem arvados-google-api-client sdk/ruby-google-api-client
676 }
677
678 install_sdk/R() {
679   if [[ "$NEED_SDK_R" = true ]]; then
680     cd "$WORKSPACE/sdk/R" \
681        && Rscript --vanilla install_deps.R
682   fi
683 }
684
685 install_sdk/cli() {
686     install_gem arvados-cli sdk/cli
687 }
688
689 install_services/login-sync() {
690     install_gem arvados-google-api-client sdk/ruby-google-api-client
691     install_gem arvados sdk/ruby
692     install_gem arvados-login-sync services/login-sync
693 }
694
695 install_services/api() {
696     stop_services
697     check_arvados_config "services/api"
698     cd "$WORKSPACE/services/api" \
699         && RAILS_ENV=test bundle_install_trylocal \
700             || return 1
701
702     rm -f config/environments/test.rb
703     cp config/environments/test.rb.example config/environments/test.rb
704
705     # Clear out any lingering postgresql connections to the test
706     # database, so that we can drop it. This assumes the current user
707     # is a postgresql superuser.
708     psql -c "SELECT pg_terminate_backend (pg_stat_activity.pid::int) FROM pg_stat_activity WHERE pg_stat_activity.datname = '$PGDATABASE';" 2>/dev/null
709
710     mkdir -p "$WORKSPACE/services/api/tmp/pids"
711
712     cert="$WORKSPACE/services/api/tmp/self-signed"
713     if [[ ! -e "$cert.pem" || "$(date -r "$cert.pem" +%s)" -lt 1512659226 ]]; then
714         (
715             dir="$WORKSPACE/services/api/tmp"
716             set -e
717             openssl req -newkey rsa:2048 -nodes -subj '/C=US/ST=State/L=City/CN=localhost' -out "$cert.csr" -keyout "$cert.key" </dev/null
718             openssl x509 -req -in "$cert.csr" -signkey "$cert.key" -out "$cert.pem" -days 3650 -extfile <(printf 'subjectAltName=DNS:localhost,DNS:::1,DNS:0.0.0.0,DNS:127.0.0.1,IP:::1,IP:0.0.0.0,IP:127.0.0.1')
719         ) || return 1
720     fi
721
722     (
723         set -ex
724         cd "$WORKSPACE/services/api"
725         export RAILS_ENV=test
726         if bin/rails db:environment:set ; then
727             bin/rake db:drop
728         fi
729         bin/rake db:setup
730         bin/rake db:fixtures:load
731     ) || return 1
732 }
733
734 install_services/workbench2() {
735     cd "$WORKSPACE/services/workbench2" \
736         && make yarn-install ARVADOS_DIRECTORY="${WORKSPACE}"
737 }
738
739 do_migrate() {
740     timer_reset
741     local task="db:migrate"
742     case "$1" in
743         "")
744             ;;
745         rollback)
746             task="db:rollback"
747             shift
748             ;;
749         *)
750             task="db:migrate:$1"
751             shift
752             ;;
753     esac
754     check_arvados_config services/api
755     (
756         set -x
757         env -C "$WORKSPACE/services/api" RAILS_ENV=test \
758             bundle exec rake $task ${@}
759     )
760     checkexit "$?" "services/api $task"
761 }
762
763 migrate_down_services/api() {
764     echo "running db:migrate:down"
765     env -C "$WORKSPACE/services/api" RAILS_ENV=test \
766         bundle exec rake db:migrate:down ${testargs[services/api]}
767     checkexit "$?" "services/api db:migrate:down"
768 }
769
770 test_doc() {
771     local arvados_api_host=pirca.arvadosapi.com && \
772         env -C "$WORKSPACE/doc" \
773         bundle exec rake linkchecker \
774         arvados_api_host="$arvados_api_host" \
775         arvados_workbench_host="https://workbench.$arvados_api_host" \
776         baseurl="file://$WORKSPACE/doc/.site/" \
777         ${testargs[doc]}
778 }
779
780 test_gofmt() {
781     cd "$WORKSPACE" || return 1
782     dirs=$(ls -d */ | egrep -v 'vendor|tmp')
783     [[ -z "$(gofmt -e -d $dirs | tee -a /dev/stderr)" ]]
784     go vet -composites=false ./...
785 }
786
787 test_arvados_version.py() {
788     local orig_fn=""
789     local fail_count=0
790     while read -d "" fn; do
791         if [[ -z "$orig_fn" ]]; then
792             orig_fn="$fn"
793         elif ! cmp "$orig_fn" "$fn"; then
794             fail_count=$(( $fail_count + 1 ))
795             printf "FAIL: %s and %s are not identical\n" "$orig_fn" "$fn"
796         fi
797     done < <(git -C "$WORKSPACE" ls-files -z | grep -z '/arvados_version\.py$')
798     case "$orig_fn" in
799         "") return 66 ;;  # EX_NOINPUT
800         *) return "$fail_count" ;;
801     esac
802 }
803
804 test_services/api() {
805     rm -f "$WORKSPACE/services/api/git-commit.version"
806     cd "$WORKSPACE/services/api" \
807         && eval env RAILS_ENV=test ${short:+RAILS_TEST_SHORT=1} bundle exec rake test TESTOPTS=\'-v -d\' ${testargs[services/api]}
808 }
809
810 test_sdk/ruby() {
811     cd "$WORKSPACE/sdk/ruby" \
812         && bundle exec rake test TESTOPTS=-v ${testargs[sdk/ruby]}
813 }
814
815 test_sdk/ruby-google-api-client() {
816     echo "*** note \`test sdk/ruby-google-api-client\` does not actually run any tests, see https://dev.arvados.org/issues/20993 ***"
817     true
818 }
819
820 test_sdk/R() {
821   if [[ "$NEED_SDK_R" = true ]]; then
822     env -C "$WORKSPACE/sdk/R" make test
823   fi
824 }
825
826 test_sdk/cli() {
827     cd "$WORKSPACE/sdk/cli" \
828         && mkdir -p /tmp/keep \
829         && KEEP_LOCAL_STORE=/tmp/keep bundle exec rake test TESTOPTS=-v ${testargs[sdk/cli]}
830 }
831
832 test_sdk/java-v2() {
833     cd "$WORKSPACE/sdk/java-v2" && gradle test ${testargs[sdk/java-v2]}
834 }
835
836 test_services/login-sync() {
837     cd "$WORKSPACE/services/login-sync" \
838         && bundle exec rake test TESTOPTS=-v ${testargs[services/login-sync]}
839 }
840
841 test_services/workbench2_units() {
842     cd "$WORKSPACE/services/workbench2" && make unit-tests ARVADOS_DIRECTORY="${WORKSPACE}" WORKSPACE="$(pwd)" ${testargs[services/workbench2]}
843 }
844
845 test_services/workbench2_integration() {
846     INTERACTIVE=
847     FAIL_FAST_ENABLED=false
848     if [[ -n ${interactive} ]] && [[ -n ${DISPLAY} ]]; then
849         INTERACTIVE=-i
850         FAIL_FAST_ENABLED=true
851     fi
852     cd "$WORKSPACE/services/workbench2" && make integration-tests ARVADOS_DIRECTORY="${WORKSPACE}" \
853                                                 WORKSPACE="$(pwd)" \
854                                                 INTERACTIVE=$INTERACTIVE \
855                                                 CYPRESS_FAIL_FAST_ENABLED=$FAIL_FAST_ENABLED \
856                                                 ${testargs[services/workbench2]}
857 }
858
859 install_deps() {
860     # Install parts needed by test suites
861     do_install env
862     # Many other components rely on PySDK's run_test_server.py, which relies on
863     # the SDK itself, so install that first.
864     do_install sdk/python pip
865     # lib/controller integration tests depend on arv-mount to run containers.
866     do_install services/fuse pip
867     # sdk/cwl depends on crunchstat-summary.
868     do_install tools/crunchstat-summary pip
869     do_install cmd/arvados-server go
870     do_install sdk/ruby-google-api-client
871     do_install sdk/ruby
872     do_install sdk/cli
873     do_install services/api
874     do_install services/keepproxy go
875     do_install services/keep-web go
876 }
877
878 install_all() {
879     do_install env
880     do_install doc
881     do_install sdk/ruby-google-api-client
882     do_install sdk/ruby
883     do_install sdk/R
884     do_install sdk/cli
885     do_install services/login-sync
886     local pkg_dir
887     if [[ -z ${skip[python3]} ]]; then
888         for pkg_dir in "${pythonstuff[@]}"
889         do
890             do_install "$pkg_dir" pip
891         done
892     fi
893     for pkg_dir in "${gostuff[@]}"
894     do
895         do_install "$pkg_dir" go
896     done
897     do_install services/api
898     do_install services/workbench2
899 }
900
901 test_all() {
902     stop_services
903     do_test services/api
904     do_test gofmt
905     do_test arvados_version.py
906     do_test doc
907     do_test sdk/ruby-google-api-client
908     do_test sdk/ruby
909     do_test sdk/R
910     do_test sdk/cli
911     do_test services/login-sync
912     do_test sdk/java-v2
913     local pkg_dir
914     if [[ -z ${skip[python3]} ]]; then
915         for pkg_dir in "${pythonstuff[@]}"
916         do
917             do_test "$pkg_dir" pip
918         done
919     fi
920     for pkg_dir in "${gostuff[@]}"
921     do
922         do_test "$pkg_dir" go
923     done
924     do_test services/workbench2_units
925     do_test services/workbench2_integration
926 }
927
928 test_go() {
929     do_test gofmt
930     for g in "${gostuff[@]}"
931     do
932         do_test "$g" go
933     done
934 }
935
936 help_interactive() {
937     echo "== Interactive commands:"
938     echo "TARGET                   (short for 'test DIR')"
939     echo "test TARGET"
940     echo "10 test TARGET           (run test 10 times)"
941     echo "test TARGET -check.vv    (pass arguments to test)"
942     echo "install TARGET"
943     echo "install env              (go/python libs)"
944     echo "install deps             (go/python libs + arvados components needed for integration tests)"
945     echo "migrate                  (run outstanding migrations)"
946     echo "migrate rollback         (revert most recent migration)"
947     echo "migrate <dir> VERSION=n  (revert and/or run a single migration; <dir> is up|down|redo)"
948     echo "reset                    (...services used by integration tests)"
949     echo "exit"
950     echo "== Test targets:"
951     printf "%s\n" "${!testfuncargs[@]}" | sort | column
952 }
953
954 declare -a failures
955 declare -A skip
956 declare -A only
957 declare -A testargs
958
959 declare -a pythonstuff
960 pythonstuff=(
961     # The ordering of sdk/python, tools/crunchstat-summary, and
962     # sdk/cwl here is significant. See
963     # https://dev.arvados.org/issues/19744#note-26
964     sdk/python
965     tools/crunchstat-summary
966     sdk/cwl
967     services/dockercleaner
968     services/fuse
969     tools/cluster-activity
970 )
971
972 declare -a gostuff
973 if [[ -n "$WORKSPACE" ]]; then
974     readarray -d "" -t gostuff < <(
975         git -C "$WORKSPACE" ls-files -z |
976             grep -z '\.go$' |
977             xargs -0r dirname -z |
978             sort -zu
979     )
980 fi
981
982 declare -A testfuncargs=()
983 for testfuncname in $(declare -F | awk '
984 ($3 ~ /^test_/ && $3 !~ /_package_presence$/) {
985   print substr($3, 6);
986 }
987 '); do
988     testfuncargs[$testfuncname]="$testfuncname"
989 done
990 for g in "${gostuff[@]}"; do
991     testfuncargs[$g]="$g go"
992 done
993 for p in "${pythonstuff[@]}"; do
994     testfuncargs[$p]="$p pip"
995 done
996
997 while [[ -n "$1" ]]
998 do
999     arg="$1"; shift
1000     case "$arg" in
1001         --help)
1002             exec 1>&2
1003             echo "$helpmessage"
1004             if [[ ${#gostuff} -gt 0 ]]; then
1005                 printf "\nAvailable targets:\n\n"
1006                 printf "%s\n" "${!testfuncargs[@]}" | sort | column
1007             fi
1008             exit 1
1009             ;;
1010         --skip)
1011             skip["${1%:py3}"]=1; shift
1012             ;;
1013         --only)
1014             only["${1%:py3}"]=1; skip["${1%:py3}"]=""; shift
1015             ;;
1016         --short)
1017             short=1
1018             ;;
1019         --interactive)
1020             interactive=1
1021             ;;
1022         --skip-install)
1023             skip[install]=1
1024             ;;
1025         --only-install)
1026             only_install="$1"; shift
1027             ;;
1028         --temp)
1029             temp="$1"; shift
1030             temp_preserve=1
1031             ;;
1032         --leave-temp)
1033             temp_preserve=1
1034             ;;
1035         --repeat)
1036             repeat=$((${1}+0)); shift
1037             ;;
1038         --retry)
1039             retry=1
1040             ;;
1041         *_test=*)
1042             suite="${arg%%_test=*}"
1043             args="${arg#*=}"
1044             testargs["${suite%:py3}"]="$args"
1045             ;;
1046         *=*)
1047             eval export $(echo $arg | cut -d= -f1)=\"$(echo $arg | cut -d= -f2-)\"
1048             ;;
1049         *)
1050             echo >&2 "$0: Unrecognized option: '$arg'. Try: $0 --help"
1051             exit 1
1052             ;;
1053     esac
1054 done
1055
1056 # R SDK installation is very slow (~360s in a clean environment) and only
1057 # required when testing it. Skip that step if it is not needed.
1058 NEED_SDK_R=true
1059
1060 if [[ ${#only[@]} -ne 0 ]] &&
1061    [[ -z "${only['sdk/R']}" && -z "${only['doc']}" ]]; then
1062   NEED_SDK_R=false
1063 fi
1064
1065 if [[ ${skip["sdk/R"]} == 1 && ${skip["doc"]} == 1 ]]; then
1066   NEED_SDK_R=false
1067 fi
1068
1069 if [[ $NEED_SDK_R == false ]]; then
1070         echo "R SDK not needed, it will not be installed."
1071 fi
1072
1073 initialize
1074 if [[ -z ${interactive} ]]; then
1075     install_all
1076     test_all
1077 else
1078     skip=()
1079     only=()
1080     only_install=""
1081     stop_services
1082     setnextcmd() {
1083         if [[ "$TERM" = dumb ]]; then
1084             # assume emacs, or something, is offering a history buffer
1085             # and pre-populating the command will only cause trouble
1086             nextcmd=
1087         elif [[ ! -e "$GOPATH/bin/arvados-server" ]]; then
1088             nextcmd="install deps"
1089         else
1090             nextcmd=""
1091         fi
1092     }
1093     echo
1094     help_interactive
1095     setnextcmd
1096     HISTFILE="$WORKSPACE/tmp/.history"
1097     history -r
1098     ignore_sigint=1
1099     while read -p 'What next? ' -e -i "$nextcmd" nextcmd; do
1100         history -s "$nextcmd"
1101         history -w
1102         count=1
1103         if [[ "${nextcmd}" =~ ^[0-9] ]]; then
1104           read count nextcmd <<<"${nextcmd}"
1105         fi
1106         read verb target opts <<<"${nextcmd}"
1107         target="${target%/}"
1108         target="${target/\/:/:}"
1109         # Remove old Python version suffix for backwards compatibility
1110         target="${target%:py3}"
1111         case "${verb}" in
1112             "exit" | "quit")
1113                 exit_cleanly
1114                 ;;
1115             "reset")
1116                 stop_services
1117                 ;;
1118             "migrate")
1119                 do_migrate ${target} ${opts}
1120                 ;;
1121             "test" | "install")
1122                 case "$target" in
1123                     "")
1124                         help_interactive
1125                         ;;
1126                     all | deps)
1127                         ${verb}_${target}
1128                         ;;
1129                     *)
1130                         testargs["$target"]="${opts}"
1131                         while [ $count -gt 0 ]; do
1132                           do_$verb ${testfuncargs[${target}]}
1133                           let "count=count-1"
1134                         done
1135                         ;;
1136                 esac
1137                 ;;
1138             "" | "help" | *)
1139                 help_interactive
1140                 ;;
1141         esac
1142         if [[ ${#successes[@]} -gt 0 || ${#failures[@]} -gt 0 ]]; then
1143             report_outcomes
1144             successes=()
1145             failures=()
1146         fi
1147         cd "$WORKSPACE"
1148         setnextcmd
1149     done
1150     echo
1151 fi
1152 exit_cleanly