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