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