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