]> git.arvados.org - arvados.git/blob - build/run-tests.sh
23010: Uses new pg-formula supporting Ubuntu 24.04
[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     # We must have these in place *before* we install the PySDK below.
368     pip install -r "$WORKSPACE/build/requirements.tests.txt" ||
369         fatal "failed to install Python requirements in virtualenv"
370     # run-tests.sh uses run_test_server.py from the Python SDK.
371     do_install_once sdk/python pip || fatal "failed to install PySDK in virtualenv"
372 }
373
374 initialize() {
375     # If dependencies like ruby, go, etc. are installed in
376     # /var/lib/arvados -- presumably by "arvados-server install" --
377     # then we want to use those versions, instead of whatever happens
378     # to be installed in /usr.
379     PATH="/var/lib/arvados/bin:${PATH}"
380     sanity_checks
381
382     echo "WORKSPACE=$WORKSPACE"
383     cd "$WORKSPACE"
384
385     if [[ -z "$temp" ]]; then
386         temp="$(mktemp -d)"
387     fi
388
389     # Set up temporary install dirs (unless existing dirs were supplied)
390     for tmpdir in VENV3DIR GOPATH GEMHOME R_LIBS
391     do
392         if [[ -z "${!tmpdir}" ]]; then
393             eval "$tmpdir"="$temp/$tmpdir"
394         fi
395         if ! [[ -d "${!tmpdir}" ]]; then
396             mkdir "${!tmpdir}" || fatal "can't create ${!tmpdir} (does $temp exist?)"
397         fi
398     done
399
400     rm -vf "${WORKSPACE}/tmp/*.log"
401
402     export R_LIBS
403
404     export GOPATH
405     # Make sure our compiled binaries under test override anything
406     # else that might be in the environment.
407     export PATH=$GOPATH/bin:$PATH
408
409     # Jenkins config requires that glob tmp/*.log match something. Ensure
410     # that happens even if we don't end up running services that set up
411     # logging.
412     mkdir -p "${WORKSPACE}/tmp/" || fatal "could not mkdir ${WORKSPACE}/tmp"
413     touch "${WORKSPACE}/tmp/controller.log" || fatal "could not touch ${WORKSPACE}/tmp/controller.log"
414
415     unset http_proxy https_proxy no_proxy
416
417     setup_ruby_environment
418     setup_virtualenv
419
420     echo "PATH is $PATH"
421 }
422
423 install_env() {
424     go mod download || fatal "Go deps failed"
425     which goimports >/dev/null || go install golang.org/x/tools/cmd/goimports@latest || fatal "Go setup failed"
426 }
427
428 retry() {
429     remain="${repeat}"
430     while :
431     do
432         if ${@}; then
433             if [[ "$remain" -gt 1 ]]; then
434                 remain=$((${remain}-1))
435                 title "(repeating ${remain} more times)"
436             else
437                 break
438             fi
439         elif [[ "$retry" == 1 ]]; then
440             read -p 'Try again? [Y/n] ' x
441             if [[ "$x" != "y" ]] && [[ "$x" != "" ]]
442             then
443                 break
444             fi
445         else
446             break
447         fi
448     done
449 }
450
451 do_test() {
452     case "${1}" in
453         services/workbench2_units | services/workbench2_integration)
454             suite=services/workbench2
455             ;;
456         *)
457             suite="${1}"
458             ;;
459     esac
460     if [[ -n "${skip[$suite]}" || \
461               -n "${skip[$1]}" || \
462               (${#only[@]} -ne 0 && ${only[$suite]} -eq 0 && ${only[$1]} -eq 0) ]]; then
463         return 0
464     fi
465     case "${1}" in
466         services/api)
467             stop_services
468             check_arvados_config "$1"
469             ;;
470         gofmt \
471             | arvados_version.py \
472             | cmd/arvados-package \
473             | doc \
474             | lib/boot \
475             | lib/cli \
476             | lib/cloud/azure \
477             | lib/cloud/cloudtest \
478             | lib/cloud/ec2 \
479             | lib/cmd \
480             | lib/dispatchcloud/sshexecutor \
481             | lib/dispatchcloud/worker \
482             | lib/install \
483             | services/workbench2_integration \
484             | services/workbench2_units \
485             )
486             check_arvados_config "$1"
487             # don't care whether services are running
488             ;;
489         *)
490             check_arvados_config "$1"
491             if ! start_services; then
492                 checkexit 1 "$1 tests"
493                 title "test $1 -- failed to start services"
494                 return 1
495             fi
496             ;;
497     esac
498     retry do_test_once ${@}
499 }
500
501 go_ldflags() {
502     version=${ARVADOS_VERSION:-$(git log -n1 --format=%H)-dev}
503     echo "-X git.arvados.org/arvados.git/lib/cmd.version=${version} -X main.version=${version} -s -w"
504 }
505
506 do_test_once() {
507     unset result
508
509     if [[ "$2" == pip ]]; then
510         # We need to install the module before testing to ensure all the
511         # dependencies are satisfied. We need to do this before we start
512         # the test header+timer.
513         do_install_once "$1" "$2" || return
514     fi
515
516     local -a targs=()
517     case "$1" in
518         sdk/cwl )
519             # The CWL conformance/integration tests each take ~30
520             # minutes. Before July 2025 they were outside the standard test
521             # suite, so we deselect them by default for consistency.
522             targs+=(-m "not integration")
523             ;;
524     esac
525     # Append the user's arguments to targs, respecting quoted strings.
526     eval "targs+=(${testargs[$1]})"
527
528     title "test $1"
529     timer_reset
530
531     result=
532     if [[ "$2" == "go" ]]
533     then
534         covername="coverage-$(echo "$1" | sed -e 's/\//_/g')"
535         coverflags=("-covermode=count" "-coverprofile=$WORKSPACE/tmp/.$covername.tmp")
536         testflags=()
537         if [[ "$1" == "cmd/arvados-package" ]]; then
538             testflags+=("-timeout" "20m")
539         fi
540         # We do "go install" here to catch compilation errors
541         # before trying "go test". Otherwise, coverage-reporting
542         # mode makes Go show the wrong line numbers when reporting
543         # compilation errors.
544         go install -ldflags "$(go_ldflags)" "$WORKSPACE/$1" && \
545             cd "$WORKSPACE/$1" && \
546             if [[ "${#targs}" -gt 0 ]]
547         then
548             # "go test -check.vv giturl" doesn't work, but this
549             # does:
550             go test ${short:+-short} ${testflags[@]} "${targs[@]}"
551         else
552             # The above form gets verbose even when testargs is
553             # empty, so use this form in such cases:
554             go test ${short:+-short} ${testflags[@]} ${coverflags[@]} "git.arvados.org/arvados.git/$1"
555         fi
556         result=${result:-$?}
557         if [[ -f "$WORKSPACE/tmp/.$covername.tmp" ]]
558         then
559             go tool cover -html="$WORKSPACE/tmp/.$covername.tmp" -o "$WORKSPACE/tmp/$covername.html"
560             rm "$WORKSPACE/tmp/.$covername.tmp"
561         fi
562         [[ $result = 0 ]] && gofmt -e -d *.go
563     elif [[ "$2" == "pip" ]]
564     then
565         tries=0
566         while :
567         do
568             tries=$((${tries}+1))
569             env -C "$WORKSPACE/$1" python3 -m pytest "${targs[@]}"
570             result=$?
571             # pytest uses exit code 2 to mean "test collection failed."
572             # See discussion in FUSE's IntegrationTest and MountTestBase.
573             if [[ ${tries} < 3 && ${result} == 2 ]]
574             then
575                 printf '\n*****\n%s tests exited with code 2 -- retrying\n*****\n\n' "$1"
576                 continue
577             else
578                 break
579             fi
580         done
581     elif [[ "$2" != "" ]]
582     then
583         "test_$2"
584     else
585         "test_$1"
586     fi
587     result=${result:-$?}
588     checkexit $result "$1 tests"
589     title "test $1 -- `timer`"
590     return $result
591 }
592
593 check_arvados_config() {
594     if [[ "$1" = "env" ]] ; then
595         return
596     fi
597     if [[ -z "$ARVADOS_CONFIG" ]] ; then
598         cd "$WORKSPACE"
599         eval $(python3 sdk/python/tests/run_test_server.py setup_config)
600     fi
601     # Set all PostgreSQL connection variables, and write a .pgpass, to connect
602     # to the test database, so test scripts can write `psql` commands with no
603     # additional configuration.
604     export PGPASSFILE="$WORKSPACE/tmp/.pgpass"
605     export PGDATABASE="$(yq -r .Clusters.zzzzz.PostgreSQL.Connection.dbname "$ARVADOS_CONFIG")"
606     export PGHOST="$(yq -r .Clusters.zzzzz.PostgreSQL.Connection.host "$ARVADOS_CONFIG")"
607     export PGPORT="$(yq -r .Clusters.zzzzz.PostgreSQL.Connection.port "$ARVADOS_CONFIG")"
608     export PGUSER="$(yq -r .Clusters.zzzzz.PostgreSQL.Connection.user "$ARVADOS_CONFIG")"
609     local pgpassword="$(yq -r .Clusters.zzzzz.PostgreSQL.Connection.password "$ARVADOS_CONFIG")"
610     echo "$PGHOST:$PGPORT:$PGDATABASE:$PGUSER:$pgpassword" >"$PGPASSFILE"
611     chmod 0600 "$PGPASSFILE"
612 }
613
614 do_install() {
615     if [[ -n ${skip["install_$1"]} || -n "${skip[install]}" || ( -n "${only_install}" && "${only_install}" != "${1}" && "${only_install}" != "${2}" ) ]]; then
616         return 0
617     fi
618     check_arvados_config "$1"
619     retry do_install_once ${@}
620 }
621
622 do_install_once() {
623     title "install $1"
624     timer_reset
625
626     result=
627     if [[ "$2" == "go" ]]
628     then
629         go install -ldflags "$(go_ldflags)" "$WORKSPACE/$1"
630     elif [[ "$2" == "pip" ]]
631     then
632         # Generate _version.py before installing.
633         python3 "$WORKSPACE/$1/arvados_version.py" >/dev/null &&
634             pip install "$WORKSPACE/$1"
635     elif [[ "$2" != "" ]]
636     then
637         "install_$2"
638     else
639         "install_$1"
640     fi
641     result=${result:-$?}
642     checkexit $result "$1 install"
643     title "install $1 -- `timer`"
644     return $result
645 }
646
647 bundle_install_trylocal() {
648     (
649         set -e
650         echo "(Running bundle install --local. 'could not find package' messages are OK.)"
651         if ! "$BUNDLE" install --local --no-deployment; then
652             echo "(Running bundle install again, without --local.)"
653             "$BUNDLE" install --no-deployment
654         fi
655         "$BUNDLE" package
656     )
657 }
658
659 install_doc() {
660     cd "$WORKSPACE/doc" \
661         && bundle_install_trylocal \
662         && rm -rf .site
663 }
664
665 install_gem() {
666     gemname=$1
667     srcpath=$2
668     cd "$WORKSPACE/$srcpath" \
669         && bundle_install_trylocal \
670         && gem build "$gemname.gemspec" \
671         && with_test_gemset gem install --no-document $(ls -t "$gemname"-*.gem|head -n1)
672 }
673
674 install_sdk/ruby() {
675     install_gem arvados sdk/ruby
676 }
677
678 install_sdk/ruby-google-api-client() {
679     install_gem arvados-google-api-client sdk/ruby-google-api-client
680 }
681
682 install_contrib/R-sdk() {
683   if [[ "$NEED_SDK_R" = true ]]; then
684     env -C "$WORKSPACE/contrib/R-sdk" Rscript --vanilla install_deps.R
685   fi
686 }
687
688 install_sdk/cli() {
689     install_gem arvados-cli sdk/cli
690 }
691
692 install_services/login-sync() {
693     install_gem arvados-login-sync services/login-sync
694 }
695
696 install_services/api() {
697     stop_services
698     check_arvados_config "services/api"
699     cd "$WORKSPACE/services/api" \
700         && RAILS_ENV=test bundle_install_trylocal \
701             || return 1
702
703     rm -f config/environments/test.rb
704     cp config/environments/test.rb.example config/environments/test.rb
705
706     # Clear out any lingering postgresql connections to the test
707     # database, so that we can drop it. This assumes the current user
708     # is a postgresql superuser.
709     psql -c "SELECT pg_terminate_backend (pg_stat_activity.pid::int) FROM pg_stat_activity WHERE pg_stat_activity.datname = '$PGDATABASE';" 2>/dev/null
710
711     mkdir -p "$WORKSPACE/services/api/tmp/pids"
712
713     cert="$WORKSPACE/services/api/tmp/self-signed"
714     if [[ ! -e "$cert.pem" || "$(date -r "$cert.pem" +%s)" -lt 1512659226 ]]; then
715         (
716             dir="$WORKSPACE/services/api/tmp"
717             set -e
718             openssl req -newkey rsa:2048 -nodes -subj '/C=US/ST=State/L=City/CN=localhost' -out "$cert.csr" -keyout "$cert.key" </dev/null
719             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')
720         ) || return 1
721     fi
722
723     (
724         set -ex
725         cd "$WORKSPACE/services/api"
726         export RAILS_ENV=test
727         if bin/rails db:environment:set ; then
728             bin/rake db:drop
729         fi
730         bin/rake db:setup
731         bin/rake db:fixtures:load
732     ) || return 1
733 }
734
735 install_services/workbench2() {
736     cd "$WORKSPACE/services/workbench2" \
737         && make yarn-install ARVADOS_DIRECTORY="${WORKSPACE}"
738 }
739
740 do_migrate() {
741     timer_reset
742     local task="db:migrate"
743     case "$1" in
744         "")
745             ;;
746         rollback)
747             task="db:rollback"
748             shift
749             ;;
750         *)
751             task="db:migrate:$1"
752             shift
753             ;;
754     esac
755     check_arvados_config services/api
756     (
757         set -x
758         env -C "$WORKSPACE/services/api" RAILS_ENV=test \
759             "$BUNDLE" exec rake $task ${@}
760     )
761     checkexit "$?" "services/api $task"
762 }
763
764 migrate_down_services/api() {
765     echo "running db:migrate:down"
766     env -C "$WORKSPACE/services/api" RAILS_ENV=test \
767         "$BUNDLE" exec rake db:migrate:down ${testargs[services/api]}
768     checkexit "$?" "services/api db:migrate:down"
769 }
770
771 test_doc() {
772     local arvados_api_host=pirca.arvadosapi.com && \
773         env -C "$WORKSPACE/doc" \
774         "$BUNDLE" exec rake linkchecker \
775         arvados_api_host="$arvados_api_host" \
776         arvados_workbench_host="https://workbench.$arvados_api_host" \
777         baseurl="file://$WORKSPACE/doc/.site/" \
778         ${testargs[doc]}
779 }
780
781 test_gofmt() {
782     cd "$WORKSPACE" || return 1
783     dirs=$(ls -d */ | egrep -v 'vendor|tmp')
784     [[ -z "$(gofmt -e -d $dirs | tee -a /dev/stderr)" ]]
785     go vet -composites=false ./...
786 }
787
788 test_arvados_version.py() {
789     local orig_fn=""
790     local fail_count=0
791     while read -d "" fn; do
792         if [[ -z "$orig_fn" ]]; then
793             orig_fn="$fn"
794         elif ! cmp "$orig_fn" "$fn"; then
795             fail_count=$(( $fail_count + 1 ))
796             printf "FAIL: %s and %s are not identical\n" "$orig_fn" "$fn"
797         fi
798     done < <(git -C "$WORKSPACE" ls-files -z | grep -z '/arvados_version\.py$')
799     case "$orig_fn" in
800         "") return 66 ;;  # EX_NOINPUT
801         *) return "$fail_count" ;;
802     esac
803 }
804
805 test_services/api() {
806     rm -f "$WORKSPACE/services/api/git-commit.version"
807     cd "$WORKSPACE/services/api" \
808         && eval env RAILS_ENV=test ${short:+RAILS_TEST_SHORT=1} "$BUNDLE" exec rake test TESTOPTS=\'-v -d\' ${testargs[services/api]}
809 }
810
811 test_sdk/ruby() {
812     cd "$WORKSPACE/sdk/ruby" \
813         && "$BUNDLE" exec rake test TESTOPTS=-v ${testargs[sdk/ruby]}
814 }
815
816 test_sdk/ruby-google-api-client() {
817     echo "*** note \`test sdk/ruby-google-api-client\` does not actually run any tests, see https://dev.arvados.org/issues/20993 ***"
818     true
819 }
820
821 test_contrib/R-sdk() {
822   if [[ "$NEED_SDK_R" = true ]]; then
823     env -C "$WORKSPACE/contrib/R-sdk" make test
824   fi
825 }
826
827 test_sdk/cli() {
828     cd "$WORKSPACE/sdk/cli" \
829         && mkdir -p /tmp/keep \
830         && KEEP_LOCAL_STORE=/tmp/keep "$BUNDLE" exec rake test TESTOPTS=-v ${testargs[sdk/cli]}
831 }
832
833 test_contrib/java-sdk-v2() {
834     env -C "$WORKSPACE/contrib/java-sdk-v2" gradle test ${testargs[contrib/java-sdk-v2]}
835 }
836
837 test_services/login-sync() {
838     cd "$WORKSPACE/services/login-sync" \
839         && "$BUNDLE" exec rake test TESTOPTS=-v ${testargs[services/login-sync]}
840 }
841
842 test_services/workbench2_units() {
843     cd "$WORKSPACE/services/workbench2" && make unit-tests ARVADOS_DIRECTORY="${WORKSPACE}" WORKSPACE="$(pwd)" ${testargs[services/workbench2]}
844 }
845
846 test_services/workbench2_integration() {
847     INTERACTIVE=
848     FAIL_FAST_ENABLED=false
849     if [[ -n ${interactive} ]] && [[ -n ${DISPLAY} ]]; then
850         INTERACTIVE=-i
851         FAIL_FAST_ENABLED=true
852     fi
853     cd "$WORKSPACE/services/workbench2" && make integration-tests ARVADOS_DIRECTORY="${WORKSPACE}" \
854                                                 WORKSPACE="$(pwd)" \
855                                                 INTERACTIVE=$INTERACTIVE \
856                                                 CYPRESS_FAIL_FAST_ENABLED=$FAIL_FAST_ENABLED \
857                                                 ${testargs[services/workbench2]}
858 }
859
860 install_deps() {
861     # Install parts needed by test suites
862     do_install env
863     # Many other components rely on PySDK's run_test_server.py, which relies on
864     # the SDK itself, so install that first.
865     do_install sdk/python pip
866     # lib/controller integration tests depend on arv-mount to run containers.
867     do_install services/fuse pip
868     # sdk/cwl depends on crunchstat-summary.
869     do_install tools/crunchstat-summary pip
870     do_install cmd/arvados-server go
871     do_install sdk/ruby-google-api-client
872     do_install sdk/ruby
873     do_install sdk/cli
874     do_install services/api
875     do_install services/keepproxy go
876     do_install services/keep-web go
877 }
878
879 install_all() {
880     do_install env
881     do_install doc
882     do_install sdk/ruby-google-api-client
883     do_install sdk/ruby
884     do_install contrib/R-sdk
885     do_install sdk/cli
886     do_install services/login-sync
887     local pkg_dir
888     if [[ -z ${skip[python3]} ]]; then
889         for pkg_dir in "${pythonstuff[@]}"
890         do
891             do_install "$pkg_dir" pip
892         done
893     fi
894     for pkg_dir in "${gostuff[@]}"
895     do
896         do_install "$pkg_dir" go
897     done
898     do_install services/api
899     do_install services/workbench2
900 }
901
902 test_all() {
903     stop_services
904     do_test services/api
905     do_test gofmt
906     do_test arvados_version.py
907     do_test doc
908     do_test sdk/ruby-google-api-client
909     do_test sdk/ruby
910     do_test contrib/R-sdk
911     do_test sdk/cli
912     do_test services/login-sync
913     do_test contrib/java-sdk-v2
914     local pkg_dir
915     if [[ -z ${skip[python3]} ]]; then
916         for pkg_dir in "${pythonstuff[@]}"
917         do
918             do_test "$pkg_dir" pip
919         done
920     fi
921     for pkg_dir in "${gostuff[@]}"
922     do
923         do_test "$pkg_dir" go
924     done
925     do_test services/workbench2_units
926     do_test services/workbench2_integration
927 }
928
929 test_go() {
930     do_test gofmt
931     for g in "${gostuff[@]}"
932     do
933         do_test "$g" go
934     done
935 }
936
937 help_interactive() {
938     echo "== Interactive commands:"
939     echo "TARGET                   (short for 'test DIR')"
940     echo "test TARGET"
941     echo "10 test TARGET           (run test 10 times)"
942     echo "test TARGET -check.vv    (pass arguments to test)"
943     echo "install TARGET"
944     echo "install env              (go/python libs)"
945     echo "install deps             (go/python libs + arvados components needed for integration tests)"
946     echo "migrate                  (run outstanding migrations)"
947     echo "migrate rollback         (revert most recent migration)"
948     echo "migrate <dir> VERSION=n  (revert and/or run a single migration; <dir> is up|down|redo)"
949     echo "reset                    (...services used by integration tests)"
950     echo "exit"
951     echo "== Test targets:"
952     printf "%s\n" "${!testfuncargs[@]}" | sort | column
953 }
954
955 declare -a failures
956 declare -A skip
957 declare -A only
958 declare -A testargs
959
960 declare -a pythonstuff
961 pythonstuff=(
962     # The ordering of sdk/python, tools/crunchstat-summary, and
963     # sdk/cwl here is significant. See
964     # https://dev.arvados.org/issues/19744#note-26
965     sdk/python
966     tools/crunchstat-summary
967     sdk/cwl
968     services/dockercleaner
969     services/fuse
970     tools/cluster-activity
971 )
972
973 declare -a gostuff
974 if [[ -n "$WORKSPACE" ]]; then
975     readarray -d "" -t gostuff < <(
976         git -C "$WORKSPACE" ls-files -z |
977             grep -z '\.go$' |
978             xargs -0r dirname -z |
979             sort -zu
980     )
981 fi
982
983 declare -A testfuncargs=()
984 for testfuncname in $(declare -F | awk '
985 ($3 ~ /^test_/ && $3 !~ /_package_presence$/) {
986   print substr($3, 6);
987 }
988 '); do
989     testfuncargs[$testfuncname]="$testfuncname"
990 done
991 for g in "${gostuff[@]}"; do
992     testfuncargs[$g]="$g go"
993 done
994 for p in "${pythonstuff[@]}"; do
995     testfuncargs[$p]="$p pip"
996 done
997
998 while [[ -n "$1" ]]
999 do
1000     arg="$1"; shift
1001     case "$arg" in
1002         --help)
1003             exec 1>&2
1004             echo "$helpmessage"
1005             if [[ ${#gostuff} -gt 0 ]]; then
1006                 printf "\nAvailable targets:\n\n"
1007                 printf "%s\n" "${!testfuncargs[@]}" | sort | column
1008             fi
1009             exit 1
1010             ;;
1011         --skip)
1012             skip["${1%:py3}"]=1; shift
1013             ;;
1014         --only)
1015             only["${1%:py3}"]=1; skip["${1%:py3}"]=""; shift
1016             ;;
1017         --short)
1018             short=1
1019             ;;
1020         --interactive)
1021             interactive=1
1022             ;;
1023         --skip-install)
1024             skip[install]=1
1025             ;;
1026         --only-install)
1027             only_install="$1"; shift
1028             ;;
1029         --temp)
1030             temp="$1"; shift
1031             temp_preserve=1
1032             ;;
1033         --leave-temp)
1034             temp_preserve=1
1035             ;;
1036         --repeat)
1037             repeat=$((${1}+0)); shift
1038             ;;
1039         --retry)
1040             retry=1
1041             ;;
1042         *_test=*)
1043             suite="${arg%%_test=*}"
1044             args="${arg#*=}"
1045             testargs["${suite%:py3}"]="$args"
1046             ;;
1047         ARVADOS_*=*)
1048             eval export $(echo $arg | cut -d= -f1)=\"$(echo $arg | cut -d= -f2-)\"
1049             ;;
1050         *)
1051             echo >&2 "$0: Unrecognized option: '$arg'. Try: $0 --help"
1052             exit 1
1053             ;;
1054     esac
1055 done
1056
1057 # R SDK installation is very slow (~360s in a clean environment) and only
1058 # required when testing it. Skip that step if it is not needed.
1059 NEED_SDK_R=true
1060
1061 if [[ ${#only[@]} -ne 0 ]] &&
1062    [[ -z "${only['contrib/R-sdk']}" && -z "${only['doc']}" ]]; then
1063   NEED_SDK_R=false
1064 fi
1065
1066 if [[ ${skip["contrib/R-sdk"]} == 1 && ${skip["doc"]} == 1 ]]; then
1067   NEED_SDK_R=false
1068 fi
1069
1070 if [[ $NEED_SDK_R == false ]]; then
1071         echo "R SDK not needed, it will not be installed."
1072 fi
1073
1074 initialize
1075 if [[ -z ${interactive} ]]; then
1076     install_all
1077     test_all
1078 else
1079     skip=()
1080     only=()
1081     only_install=""
1082     stop_services
1083     setnextcmd() {
1084         if [[ "$TERM" = dumb ]]; then
1085             # assume emacs, or something, is offering a history buffer
1086             # and pre-populating the command will only cause trouble
1087             nextcmd=
1088         elif [[ ! -e "$GOPATH/bin/arvados-server" ]]; then
1089             nextcmd="install deps"
1090         else
1091             nextcmd=""
1092         fi
1093     }
1094     echo
1095     help_interactive
1096     setnextcmd
1097     HISTFILE="$WORKSPACE/tmp/.history"
1098     history -r
1099     ignore_sigint=1
1100     while read -p 'What next? ' -e -i "$nextcmd" nextcmd; do
1101         history -s "$nextcmd"
1102         history -w
1103         count=1
1104         if [[ "${nextcmd}" =~ ^[0-9] ]]; then
1105           read count nextcmd <<<"${nextcmd}"
1106         fi
1107         read verb target opts <<<"${nextcmd}"
1108         target="${target%/}"
1109         target="${target/\/:/:}"
1110         # Remove old Python version suffix for backwards compatibility
1111         target="${target%:py3}"
1112         case "${verb}" in
1113             "exit" | "quit")
1114                 exit_cleanly
1115                 ;;
1116             "reset")
1117                 stop_services
1118                 ;;
1119             "migrate")
1120                 do_migrate ${target} ${opts}
1121                 ;;
1122             "test" | "install")
1123                 case "$target" in
1124                     "")
1125                         help_interactive
1126                         ;;
1127                     all | deps)
1128                         ${verb}_${target}
1129                         ;;
1130                     *)
1131                         testargs["$target"]="${opts}"
1132                         while [ $count -gt 0 ]; do
1133                           do_$verb ${testfuncargs[${target}]}
1134                           let "count=count-1"
1135                         done
1136                         ;;
1137                 esac
1138                 ;;
1139             "" | "help" | *)
1140                 help_interactive
1141                 ;;
1142         esac
1143         if [[ ${#successes[@]} -gt 0 || ${#failures[@]} -gt 0 ]]; then
1144             report_outcomes
1145             successes=()
1146             failures=()
1147         fi
1148         cd "$WORKSPACE"
1149         setnextcmd
1150     done
1151     echo
1152 fi
1153 exit_cleanly