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