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