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