feat(pip): Upgrade
[csit.git] / resources / libraries / bash / function / common.sh
1 # Copyright (c) 2022 Cisco and/or its affiliates.
2 # Copyright (c) 2022 PANTHEON.tech and/or its affiliates.
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at:
6 #
7 #     http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 set -exuo pipefail
16
17 # This library defines functions used by multiple entry scripts.
18 # Keep functions ordered alphabetically, please.
19
20 # TODO: Add a link to bash style guide.
21 # TODO: Consider putting every die into a {} block,
22 #   the code might become more readable (but longer).
23
24
25 function activate_docker_topology () {
26
27     # Create virtual vpp-device topology. Output of the function is topology
28     # file describing created environment saved to a file.
29     #
30     # Variables read:
31     # - BASH_FUNCTION_DIR - Path to existing directory this file is located in.
32     # - TOPOLOGIES - Available topologies.
33     # - NODENESS - Node multiplicity of desired testbed.
34     # - FLAVOR - Node flavor string, usually describing the processor.
35     # - IMAGE_VER_FILE - Name of file that contains the image version.
36     # - CSIT_DIR - Directory where ${IMAGE_VER_FILE} is located.
37     # Variables set:
38     # - WORKING_TOPOLOGY - Path to topology file.
39
40     set -exuo pipefail
41
42     source "${BASH_FUNCTION_DIR}/device.sh" || {
43         die "Source failed!"
44     }
45     device_image="$(< ${CSIT_DIR}/${IMAGE_VER_FILE})"
46     case_text="${NODENESS}_${FLAVOR}"
47     case "${case_text}" in
48         "1n_skx" | "1n_tx2")
49             # We execute reservation over csit-shim-dcr (ssh) which runs sourced
50             # script's functions. Env variables are read from ssh output
51             # back to localhost for further processing.
52             # Shim and Jenkins executor are in the same network on the same host
53             # Connect to docker's default gateway IP and shim's exposed port
54             ssh="ssh root@172.17.0.1 -p 6022"
55             run="activate_wrapper ${NODENESS} ${FLAVOR} ${device_image}"
56             # The "declare -f" output is long and boring.
57             set +x
58             # backtics to avoid https://midnight-commander.org/ticket/2142
59             env_vars=`${ssh} "$(declare -f); ${run}"` || {
60                 die "Topology reservation via shim-dcr failed!"
61             }
62             set -x
63             set -a
64             source <(echo "$env_vars" | grep -v /usr/bin/docker) || {
65                 die "Source failed!"
66             }
67             set +a
68             ;;
69         "1n_vbox")
70             # We execute reservation on localhost. Sourced script automatially
71             # sets environment variables for further processing.
72             activate_wrapper "${NODENESS}" "${FLAVOR}" "${device_image}" || die
73             ;;
74         *)
75             die "Unknown specification: ${case_text}!"
76     esac
77
78     trap 'deactivate_docker_topology' EXIT || {
79          die "Trap attempt failed, please cleanup manually. Aborting!"
80     }
81
82     parse_env_variables || die "Parse of environment variables failed!"
83
84     # Replace all variables in template with those in environment.
85     source <(echo 'cat <<EOF >topo.yml'; cat ${TOPOLOGIES[0]}; echo EOF;) || {
86         die "Topology file create failed!"
87     }
88
89     WORKING_TOPOLOGY="${CSIT_DIR}/topologies/available/vpp_device.yaml"
90     mv topo.yml "${WORKING_TOPOLOGY}" || {
91         die "Topology move failed!"
92     }
93     cat ${WORKING_TOPOLOGY} | grep -v password || {
94         die "Topology read failed!"
95     }
96 }
97
98
99 function activate_virtualenv () {
100
101     # Update virtualenv pip package, delete and create virtualenv directory,
102     # activate the virtualenv, install requirements, set PYTHONPATH.
103
104     # Arguments:
105     # - ${1} - Path to existing directory for creating virtualenv in.
106     #          If missing or empty, ${CSIT_DIR} is used.
107     # - ${2} - Path to requirements file, ${CSIT_DIR}/requirements.txt if empty.
108     # Variables read:
109     # - CSIT_DIR - Path to existing root of local CSIT git repository.
110     # Variables exported:
111     # - PYTHONPATH - CSIT_DIR, as CSIT Python scripts usually need this.
112     # Functions called:
113     # - die - Print to stderr and exit.
114
115     set -exuo pipefail
116
117     root_path="${1-$CSIT_DIR}"
118     env_dir="${root_path}/env"
119     req_path=${2-$CSIT_DIR/requirements.txt}
120     rm -rf "${env_dir}" || die "Failed to clean previous virtualenv."
121     pip3 install virtualenv==20.15.1 || {
122         die "Virtualenv package install failed."
123     }
124     virtualenv --no-download --python=$(which python3) "${env_dir}" || {
125         die "Virtualenv creation for $(which python3) failed."
126     }
127     set +u
128     source "${env_dir}/bin/activate" || die "Virtualenv activation failed."
129     set -u
130     pip3 install -r "${req_path}" || {
131         die "Requirements installation failed."
132     }
133     # Most CSIT Python scripts assume PYTHONPATH is set and exported.
134     export PYTHONPATH="${CSIT_DIR}" || die "Export failed."
135 }
136
137
138 function archive_tests () {
139
140     # Create .tar.gz of generated/tests for archiving.
141     # To be run after generate_tests, kept separate to offer more flexibility.
142
143     # Directory read:
144     # - ${GENERATED_DIR}/tests - Tree of executed suites to archive.
145     # File rewriten:
146     # - ${ARCHIVE_DIR}/generated_tests.tar.gz - Archive of generated tests.
147
148     set -exuo pipefail
149
150     pushd "${ARCHIVE_DIR}" || die
151     tar czf "generated_tests.tar.gz" "${GENERATED_DIR}/tests" || true
152     popd || die
153 }
154
155
156 function check_download_dir () {
157
158     # Fail if there are no files visible in ${DOWNLOAD_DIR}.
159     #
160     # Variables read:
161     # - DOWNLOAD_DIR - Path to directory pybot takes the build to test from.
162     # Directories read:
163     # - ${DOWNLOAD_DIR} - Has to be non-empty to proceed.
164     # Functions called:
165     # - die - Print to stderr and exit.
166
167     set -exuo pipefail
168
169     if [[ ! "$(ls -A "${DOWNLOAD_DIR}")" ]]; then
170         die "No artifacts downloaded!"
171     fi
172 }
173
174
175 function check_prerequisites () {
176
177     # Fail if prerequisites are not met.
178     #
179     # Functions called:
180     # - installed - Check if application is installed/present in system.
181     # - die - Print to stderr and exit.
182
183     set -exuo pipefail
184
185     if ! installed sshpass; then
186         die "Please install sshpass before continue!"
187     fi
188 }
189
190
191 function common_dirs () {
192
193     # Set global variables, create some directories (without touching content).
194
195     # Variables set:
196     # - BASH_FUNCTION_DIR - Path to existing directory this file is located in.
197     # - CSIT_DIR - Path to existing root of local CSIT git repository.
198     # - TOPOLOGIES_DIR - Path to existing directory with available topologies.
199     # - JOB_SPECS_DIR - Path to existing directory with job test specifications.
200     # - RESOURCES_DIR - Path to existing CSIT subdirectory "resources".
201     # - TOOLS_DIR - Path to existing resources subdirectory "tools".
202     # - PYTHON_SCRIPTS_DIR - Path to existing tools subdirectory "scripts".
203     # - ARCHIVE_DIR - Path to created CSIT subdirectory "archives".
204     #   The name is chosen to match what ci-management expects.
205     # - DOWNLOAD_DIR - Path to created CSIT subdirectory "download_dir".
206     # - GENERATED_DIR - Path to created CSIT subdirectory "generated".
207     # Directories created if not present:
208     # ARCHIVE_DIR, DOWNLOAD_DIR, GENERATED_DIR.
209     # Functions called:
210     # - die - Print to stderr and exit.
211
212     set -exuo pipefail
213
214     this_file=$(readlink -e "${BASH_SOURCE[0]}") || {
215         die "Some error during locating of this source file."
216     }
217     BASH_FUNCTION_DIR=$(dirname "${this_file}") || {
218         die "Some error during dirname call."
219     }
220     # Current working directory could be in a different repo, e.g. VPP.
221     pushd "${BASH_FUNCTION_DIR}" || die "Pushd failed"
222     relative_csit_dir=$(git rev-parse --show-toplevel) || {
223         die "Git rev-parse failed."
224     }
225     CSIT_DIR=$(readlink -e "${relative_csit_dir}") || die "Readlink failed."
226     popd || die "Popd failed."
227     TOPOLOGIES_DIR=$(readlink -e "${CSIT_DIR}/topologies/available") || {
228         die "Readlink failed."
229     }
230     JOB_SPECS_DIR=$(readlink -e "${CSIT_DIR}/docs/job_specs") || {
231         die "Readlink failed."
232     }
233     RESOURCES_DIR=$(readlink -e "${CSIT_DIR}/resources") || {
234         die "Readlink failed."
235     }
236     TOOLS_DIR=$(readlink -e "${RESOURCES_DIR}/tools") || {
237         die "Readlink failed."
238     }
239     DOC_GEN_DIR=$(readlink -e "${TOOLS_DIR}/doc_gen") || {
240         die "Readlink failed."
241     }
242     PYTHON_SCRIPTS_DIR=$(readlink -e "${TOOLS_DIR}/scripts") || {
243         die "Readlink failed."
244     }
245
246     ARCHIVE_DIR=$(readlink -f "${CSIT_DIR}/archives") || {
247         die "Readlink failed."
248     }
249     mkdir -p "${ARCHIVE_DIR}" || die "Mkdir failed."
250     DOWNLOAD_DIR=$(readlink -f "${CSIT_DIR}/download_dir") || {
251         die "Readlink failed."
252     }
253     mkdir -p "${DOWNLOAD_DIR}" || die "Mkdir failed."
254     GENERATED_DIR=$(readlink -f "${CSIT_DIR}/generated") || {
255         die "Readlink failed."
256     }
257     mkdir -p "${GENERATED_DIR}" || die "Mkdir failed."
258 }
259
260
261 function compose_pybot_arguments () {
262
263     # Variables read:
264     # - WORKING_TOPOLOGY - Path to topology yaml file of the reserved testbed.
265     # - DUT - CSIT test/ subdirectory, set while processing tags.
266     # - TAGS - Array variable holding selected tag boolean expressions.
267     # - TOPOLOGIES_TAGS - Tag boolean expression filtering tests for topology.
268     # - TEST_CODE - The test selection string from environment or argument.
269     # - SELECTION_MODE - Selection criteria [test, suite, include, exclude].
270     # Variables set:
271     # - PYBOT_ARGS - String holding part of all arguments for pybot.
272     # - EXPANDED_TAGS - Array of strings pybot arguments compiled from tags.
273
274     set -exuo pipefail
275
276     # No explicit check needed with "set -u".
277     PYBOT_ARGS=("--loglevel" "TRACE")
278     PYBOT_ARGS+=("--variable" "TOPOLOGY_PATH:${WORKING_TOPOLOGY}")
279
280     case "${TEST_CODE}" in
281         *"device"*)
282             PYBOT_ARGS+=("--suite" "tests.${DUT}.device")
283             ;;
284         *"perf"*)
285             PYBOT_ARGS+=("--suite" "tests.${DUT}.perf")
286             ;;
287         *)
288             die "Unknown specification: ${TEST_CODE}"
289     esac
290
291     EXPANDED_TAGS=()
292     for tag in "${TAGS[@]}"; do
293         if [[ ${tag} == "!"* ]]; then
294             EXPANDED_TAGS+=("--exclude" "${tag#$"!"}")
295         else
296             if [[ ${SELECTION_MODE} == "--test" ]]; then
297                 EXPANDED_TAGS+=("--test" "${tag}")
298             else
299                 EXPANDED_TAGS+=("--include" "${TOPOLOGIES_TAGS}AND${tag}")
300             fi
301         fi
302     done
303
304     if [[ ${SELECTION_MODE} == "--test" ]]; then
305         EXPANDED_TAGS+=("--include" "${TOPOLOGIES_TAGS}")
306     fi
307 }
308
309
310 function deactivate_docker_topology () {
311
312     # Deactivate virtual vpp-device topology by removing containers.
313     #
314     # Variables read:
315     # - NODENESS - Node multiplicity of desired testbed.
316     # - FLAVOR - Node flavor string, usually describing the processor.
317
318     set -exuo pipefail
319
320     case_text="${NODENESS}_${FLAVOR}"
321     case "${case_text}" in
322         "1n_skx" | "1n_tx2")
323             ssh="ssh root@172.17.0.1 -p 6022"
324             env_vars=$(env | grep CSIT_ | tr '\n' ' ' ) || die
325             # The "declare -f" output is long and boring.
326             set +x
327             ${ssh} "$(declare -f); deactivate_wrapper ${env_vars}" || {
328                 die "Topology cleanup via shim-dcr failed!"
329             }
330             set -x
331             ;;
332         "1n_vbox")
333             enter_mutex || die
334             clean_environment || {
335                 die "Topology cleanup locally failed!"
336             }
337             exit_mutex || die
338             ;;
339         *)
340             die "Unknown specification: ${case_text}!"
341     esac
342 }
343
344
345 function die () {
346
347     # Print the message to standard error end exit with error code specified
348     # by the second argument.
349     #
350     # Hardcoded values:
351     # - The default error message.
352     # Arguments:
353     # - ${1} - The whole error message, be sure to quote. Optional
354     # - ${2} - the code to exit with, default: 1.
355
356     set -x
357     set +eu
358     warn "${1:-Unspecified run-time error occurred!}"
359     exit "${2:-1}"
360 }
361
362
363 function die_on_pybot_error () {
364
365     # Source this fragment if you want to abort on any failed test case.
366     #
367     # Variables read:
368     # - PYBOT_EXIT_STATUS - Set by a pybot running fragment.
369     # Functions called:
370     # - die - Print to stderr and exit.
371
372     set -exuo pipefail
373
374     if [[ "${PYBOT_EXIT_STATUS}" != "0" ]]; then
375         die "Test failures are present!" "${PYBOT_EXIT_STATUS}"
376     fi
377 }
378
379
380 function generate_tests () {
381
382     # Populate ${GENERATED_DIR}/tests based on ${CSIT_DIR}/tests/.
383     # Any previously existing content of ${GENERATED_DIR}/tests is wiped before.
384     # The generation is done by executing any *.py executable
385     # within any subdirectory after copying.
386
387     # This is a separate function, because this code is called
388     # both by autogen checker and entries calling run_pybot.
389
390     # Directories read:
391     # - ${CSIT_DIR}/tests - Used as templates for the generated tests.
392     # Directories replaced:
393     # - ${GENERATED_DIR}/tests - Overwritten by the generated tests.
394
395     set -exuo pipefail
396
397     rm -rf "${GENERATED_DIR}/tests" || die
398     cp -r "${CSIT_DIR}/tests" "${GENERATED_DIR}/tests" || die
399     cmd_line=("find" "${GENERATED_DIR}/tests" "-type" "f")
400     cmd_line+=("-executable" "-name" "*.py")
401     # We sort the directories, so log output can be compared between runs.
402     file_list=$("${cmd_line[@]}" | sort) || die
403
404     for gen in ${file_list}; do
405         directory="$(dirname "${gen}")" || die
406         filename="$(basename "${gen}")" || die
407         pushd "${directory}" || die
408         ./"${filename}" || die
409         popd || die
410     done
411 }
412
413
414 function get_test_code () {
415
416     # Arguments:
417     # - ${1} - Optional, argument of entry script (or empty as unset).
418     #   Test code value to override job name from environment.
419     # Variables read:
420     # - JOB_NAME - String affecting test selection, default if not argument.
421     # Variables set:
422     # - TEST_CODE - The test selection string from environment or argument.
423     # - NODENESS - Node multiplicity of desired testbed.
424     # - FLAVOR - Node flavor string, usually describing the processor.
425
426     set -exuo pipefail
427
428     TEST_CODE="${1-}" || die "Reading optional argument failed, somehow."
429     if [[ -z "${TEST_CODE}" ]]; then
430         TEST_CODE="${JOB_NAME-}" || die "Reading job name failed, somehow."
431     fi
432
433     case "${TEST_CODE}" in
434         *"1n-vbox"*)
435             NODENESS="1n"
436             FLAVOR="vbox"
437             ;;
438         *"1n-skx"*)
439             NODENESS="1n"
440             FLAVOR="skx"
441             ;;
442         *"1n-tx2"*)
443             NODENESS="1n"
444             FLAVOR="tx2"
445             ;;
446         *"1n-aws"*)
447             NODENESS="1n"
448             FLAVOR="aws"
449             ;;
450         *"2n-aws"*)
451             NODENESS="2n"
452             FLAVOR="aws"
453             ;;
454         *"3n-aws"*)
455             NODENESS="3n"
456             FLAVOR="aws"
457             ;;
458         *"2n-skx"*)
459             NODENESS="2n"
460             FLAVOR="skx"
461             ;;
462         *"3n-skx"*)
463             NODENESS="3n"
464             FLAVOR="skx"
465             ;;
466         *"2n-zn2"*)
467             NODENESS="2n"
468             FLAVOR="zn2"
469             ;;
470         *"2n-clx"*)
471             NODENESS="2n"
472             FLAVOR="clx"
473             ;;
474         *"2n-icx"*)
475             NODENESS="2n"
476             FLAVOR="icx"
477             ;;
478         *"3n-icx"*)
479             NODENESS="3n"
480             FLAVOR="icx"
481             ;;
482         *"2n-dnv"*)
483             NODENESS="2n"
484             FLAVOR="dnv"
485             ;;
486         *"3n-dnv"*)
487             NODENESS="3n"
488             FLAVOR="dnv"
489             ;;
490         *"3n-snr"*)
491             NODENESS="3n"
492             FLAVOR="snr"
493             ;;
494         *"2n-tx2"*)
495             NODENESS="2n"
496             FLAVOR="tx2"
497             ;;
498         *"3n-tsh"*)
499             NODENESS="3n"
500             FLAVOR="tsh"
501             ;;
502         *"3n-alt"*)
503             NODENESS="3n"
504             FLAVOR="alt"
505             ;;
506     esac
507 }
508
509
510 function get_test_tag_string () {
511
512     # Variables read:
513     # - GERRIT_EVENT_TYPE - Event type set by gerrit, can be unset.
514     # - GERRIT_EVENT_COMMENT_TEXT - Comment text, read for "comment-added" type.
515     # - TEST_CODE - The test selection string from environment or argument.
516     # Variables set:
517     # - TEST_TAG_STRING - The string following trigger word in gerrit comment.
518     #   May be empty, or even not set on event types not adding comment.
519
520     # TODO: ci-management scripts no longer need to perform this.
521
522     set -exuo pipefail
523
524     if [[ "${GERRIT_EVENT_TYPE-}" == "comment-added" ]]; then
525         case "${TEST_CODE}" in
526             *"device"*)
527                 trigger="devicetest"
528                 ;;
529             *"perf"*)
530                 trigger="perftest"
531                 ;;
532             *)
533                 die "Unknown specification: ${TEST_CODE}"
534         esac
535         # Ignore lines not containing the trigger word.
536         comment=$(fgrep "${trigger}" <<< "${GERRIT_EVENT_COMMENT_TEXT}" || true)
537         # The vpp-csit triggers trail stuff we are not interested in.
538         # Removing them and trigger word: https://unix.stackexchange.com/a/13472
539         # (except relying on \s whitespace, \S non-whitespace and . both).
540         # The last string is concatenated, only the middle part is expanded.
541         cmd=("grep" "-oP" '\S*'"${trigger}"'\S*\s\K.+$') || die "Unset trigger?"
542         # On parsing error, TEST_TAG_STRING probably stays empty.
543         TEST_TAG_STRING=$("${cmd[@]}" <<< "${comment}" || true)
544         if [[ -z "${TEST_TAG_STRING-}" ]]; then
545             # Probably we got a base64 encoded comment.
546             comment="${GERRIT_EVENT_COMMENT_TEXT}"
547             comment=$(base64 --decode <<< "${comment}" || true)
548             comment=$(fgrep "${trigger}" <<< "${comment}" || true)
549             TEST_TAG_STRING=$("${cmd[@]}" <<< "${comment}" || true)
550         fi
551         if [[ -n "${TEST_TAG_STRING-}" ]]; then
552             test_tag_array=(${TEST_TAG_STRING})
553             if [[ "${test_tag_array[0]}" == "icl" ]]; then
554                 export GRAPH_NODE_VARIANT="icl"
555                 TEST_TAG_STRING="${test_tag_array[@]:1}" || true
556             elif [[ "${test_tag_array[0]}" == "skx" ]]; then
557                 export GRAPH_NODE_VARIANT="skx"
558                 TEST_TAG_STRING="${test_tag_array[@]:1}" || true
559             fi
560         fi
561     fi
562 }
563
564
565 function installed () {
566
567     # Check if the given utility is installed. Fail if not installed.
568     #
569     # Duplicate of common.sh function, as this file is also used standalone.
570     #
571     # Arguments:
572     # - ${1} - Utility to check.
573     # Returns:
574     # - 0 - If command is installed.
575     # - 1 - If command is not installed.
576
577     set -exuo pipefail
578
579     command -v "${1}"
580 }
581
582
583 function move_archives () {
584
585     # Move archive directory to top of workspace, if not already there.
586     #
587     # ARCHIVE_DIR is positioned relative to CSIT_DIR,
588     # but in some jobs CSIT_DIR is not same as WORKSPACE
589     # (e.g. under VPP_DIR). To simplify ci-management settings,
590     # we want to move the data to the top. We do not want simple copy,
591     # as ci-management is eager with recursive search.
592     #
593     # As some scripts may call this function multiple times,
594     # the actual implementation use copying and deletion,
595     # so the workspace gets "union" of contents (except overwrites on conflict).
596     # The consequence is empty ARCHIVE_DIR remaining after this call.
597     #
598     # As the source directory is emptied,
599     # the check for dirs being different is essential.
600     #
601     # Variables read:
602     # - WORKSPACE - Jenkins workspace, move only if the value is not empty.
603     #   Can be unset, then it speeds up manual testing.
604     # - ARCHIVE_DIR - Path to directory with content to be moved.
605     # Directories updated:
606     # - ${WORKSPACE}/archives/ - Created if does not exist.
607     #   Content of ${ARCHIVE_DIR}/ is moved.
608     # Functions called:
609     # - die - Print to stderr and exit.
610
611     set -exuo pipefail
612
613     if [[ -n "${WORKSPACE-}" ]]; then
614         target=$(readlink -f "${WORKSPACE}/archives")
615         if [[ "${target}" != "${ARCHIVE_DIR}" ]]; then
616             mkdir -p "${target}" || die "Archives dir create failed."
617             cp -rf "${ARCHIVE_DIR}"/* "${target}" || die "Copy failed."
618             rm -rf "${ARCHIVE_DIR}"/* || die "Delete failed."
619         fi
620     fi
621 }
622
623
624 function post_process_robot_outputs () {
625
626     # Generate INFO level output_info.xml by rebot.
627     # Archive UTI raw json outputs.
628     #
629     # Variables read:
630     # - ARCHIVE_DIR - Path to post-processed files.
631
632     set -exuo pipefail
633
634     # Compress raw json outputs, as they will never be post-processed.
635     pushd "${ARCHIVE_DIR}" || die
636     if [ -d "tests" ]; then
637         # Use deterministic order.
638         options+=("--sort=name")
639         # We are keeping info outputs where they are.
640         # Assuming we want to move anything but info files (and dirs).
641         options+=("--exclude=*.info.json")
642         tar czf "generated_output_raw.tar.gz" "${options[@]}" "tests" || true
643         # Tar can remove when archiving, but chokes (not deterministically)
644         # on attempting to remove dirs (not empty as info files are there).
645         # So we need to delete the raw files manually.
646         find "tests" -type f -name "*.raw.json" -delete || true
647     fi
648     popd || die
649
650     # Generate INFO level output_info.xml for post-processing.
651     all_options=("--loglevel" "INFO")
652     all_options+=("--log" "none")
653     all_options+=("--report" "none")
654     all_options+=("--output" "${ARCHIVE_DIR}/output_info.xml")
655     all_options+=("${ARCHIVE_DIR}/output.xml")
656     rebot "${all_options[@]}" || true
657 }
658
659
660 function prepare_topology () {
661
662     # Prepare virtual testbed topology if needed based on flavor.
663
664     # Variables read:
665     # - TEST_CODE - String affecting test selection, usually jenkins job name.
666     # - NODENESS - Node multiplicity of testbed, either "2n" or "3n".
667     # - FLAVOR - Node flavor string, e.g. "clx" or "skx".
668     # Functions called:
669     # - die - Print to stderr and exit.
670     # - terraform_init - Terraform init topology.
671     # - terraform_apply - Terraform apply topology.
672
673     set -exuo pipefail
674
675     case_text="${NODENESS}_${FLAVOR}"
676     case "${case_text}" in
677         "1n_aws" | "2n_aws" | "3n_aws")
678             export TF_VAR_testbed_name="${TEST_CODE}"
679             terraform_init || die "Failed to call terraform init."
680             terraform_apply || die "Failed to call terraform apply."
681             ;;
682     esac
683 }
684
685
686 function reserve_and_cleanup_testbed () {
687
688     # Reserve physical testbed, perform cleanup, register trap to unreserve.
689     # When cleanup fails, remove from topologies and keep retrying
690     # until all topologies are removed.
691     #
692     # Variables read:
693     # - TOPOLOGIES - Array of paths to topology yaml to attempt reservation on.
694     # - PYTHON_SCRIPTS_DIR - Path to directory holding the reservation script.
695     # - BUILD_TAG - Any string suitable as filename, identifying
696     #   test run executing this function. May be unset.
697     # Variables set:
698     # - TOPOLOGIES - Array of paths to topologies, with failed cleanups removed.
699     # - WORKING_TOPOLOGY - Path to topology yaml file of the reserved testbed.
700     # Functions called:
701     # - die - Print to stderr and exit.
702     # - ansible_playbook - Perform an action using ansible, see ansible.sh
703     # Traps registered:
704     # - EXIT - Calls cancel_all for ${WORKING_TOPOLOGY}.
705
706     set -exuo pipefail
707
708     while true; do
709         for topo in "${TOPOLOGIES[@]}"; do
710             set +e
711             scrpt="${PYTHON_SCRIPTS_DIR}/topo_reservation.py"
712             opts=("-t" "${topo}" "-r" "${BUILD_TAG:-Unknown}")
713             python3 "${scrpt}" "${opts[@]}"
714             result="$?"
715             set -e
716             if [[ "${result}" == "0" ]]; then
717                 # Trap unreservation before cleanup check,
718                 # so multiple jobs showing failed cleanup improve chances
719                 # of humans to notice and fix.
720                 WORKING_TOPOLOGY="${topo}"
721                 echo "Reserved: ${WORKING_TOPOLOGY}"
722                 trap "untrap_and_unreserve_testbed" EXIT || {
723                     message="TRAP ATTEMPT AND UNRESERVE FAILED, FIX MANUALLY."
724                     untrap_and_unreserve_testbed "${message}" || {
725                         die "Teardown should have died, not failed."
726                     }
727                     die "Trap attempt failed, unreserve succeeded. Aborting."
728                 }
729                 # Cleanup + calibration checks
730                 set +e
731                 ansible_playbook "cleanup, calibration"
732                 result="$?"
733                 set -e
734                 if [[ "${result}" == "0" ]]; then
735                     break
736                 fi
737                 warn "Testbed cleanup failed: ${topo}"
738                 untrap_and_unreserve_testbed "Fail of unreserve after cleanup."
739             fi
740             # Else testbed is accessible but currently reserved, moving on.
741         done
742
743         if [[ -n "${WORKING_TOPOLOGY-}" ]]; then
744             # Exit the infinite while loop if we made a reservation.
745             warn "Reservation and cleanup successful."
746             break
747         fi
748
749         if [[ "${#TOPOLOGIES[@]}" == "0" ]]; then
750             die "Run out of operational testbeds!"
751         fi
752
753         # Wait ~3minutes before next try.
754         sleep_time="$[ ( ${RANDOM} % 20 ) + 180 ]s" || {
755             die "Sleep time calculation failed."
756         }
757         echo "Sleeping ${sleep_time}"
758         sleep "${sleep_time}" || die "Sleep failed."
759     done
760 }
761
762
763 function run_pybot () {
764
765     # Run pybot with options based on input variables.
766     # Generate INFO level output_info.xml by rebot.
767     # Archive UTI raw json outputs.
768     #
769     # Variables read:
770     # - CSIT_DIR - Path to existing root of local CSIT git repository.
771     # - ARCHIVE_DIR - Path to store robot result files in.
772     # - PYBOT_ARGS, EXPANDED_TAGS - See compose_pybot_arguments.sh
773     # - GENERATED_DIR - Tests are assumed to be generated under there.
774     # Variables set:
775     # - PYBOT_EXIT_STATUS - Exit status of most recent pybot invocation.
776     # Functions called:
777     # - die - Print to stderr and exit.
778
779     set -exuo pipefail
780
781     all_options=("--outputdir" "${ARCHIVE_DIR}" "${PYBOT_ARGS[@]}")
782     all_options+=("${EXPANDED_TAGS[@]}")
783
784     pushd "${CSIT_DIR}" || die "Change directory operation failed."
785     set +e
786     robot "${all_options[@]}" "${GENERATED_DIR}/tests/"
787     PYBOT_EXIT_STATUS="$?"
788     set -e
789
790     post_process_robot_outputs || die
791
792     popd || die "Change directory operation failed."
793 }
794
795
796 function select_arch_os () {
797
798     # Set variables affected by local CPU architecture and operating system.
799     #
800     # Variables set:
801     # - VPP_VER_FILE - Name of file in CSIT dir containing vpp stable version.
802     # - IMAGE_VER_FILE - Name of file in CSIT dir containing the image name.
803     # - PKG_SUFFIX - Suffix of OS package file name, "rpm" or "deb."
804
805     set -exuo pipefail
806
807     source /etc/os-release || die "Get OS release failed."
808
809     case "${ID}" in
810         "ubuntu"*)
811             case "${VERSION}" in
812                 *"LTS (Focal Fossa)"*)
813                     IMAGE_VER_FILE="VPP_DEVICE_IMAGE_UBUNTU"
814                     VPP_VER_FILE="VPP_STABLE_VER_UBUNTU_FOCAL"
815                     PKG_SUFFIX="deb"
816                     ;;
817                 *)
818                     die "Unsupported Ubuntu version!"
819                     ;;
820             esac
821             ;;
822         *)
823             die "Unsupported distro or OS!"
824             ;;
825     esac
826
827     arch=$(uname -m) || {
828         die "Get CPU architecture failed."
829     }
830
831     case "${arch}" in
832         "aarch64")
833             IMAGE_VER_FILE="${IMAGE_VER_FILE}_ARM"
834             ;;
835         *)
836             ;;
837     esac
838 }
839
840
841 function select_tags () {
842
843     # Variables read:
844     # - WORKING_TOPOLOGY - Path to topology yaml file of the reserved testbed.
845     # - TEST_CODE - String affecting test selection, usually jenkins job name.
846     # - DUT - CSIT test/ subdirectory, set while processing tags.
847     # - TEST_TAG_STRING - String selecting tags, from gerrit comment.
848     #   Can be unset.
849     # - TOPOLOGIES_DIR - Path to existing directory with available tpologies.
850     # - BASH_FUNCTION_DIR - Directory with input files to process.
851     # Variables set:
852     # - TAGS - Array of processed tag boolean expressions.
853     # - SELECTION_MODE - Selection criteria [test, suite, include, exclude].
854
855     set -exuo pipefail
856
857     # NIC SELECTION
858     case "${TEST_CODE}" in
859         *"1n-aws"*)
860             start_pattern='^  SUT:'
861             ;;
862         *)
863             start_pattern='^  TG:'
864             ;;
865     esac
866     end_pattern='^ \? \?[A-Za-z0-9]\+:'
867     # Remove the sections from topology file
868     sed_command="/${start_pattern}/,/${end_pattern}/d"
869     # All topologies NICs
870     available=$(sed "${sed_command}" "${TOPOLOGIES_DIR}"/* \
871                 | grep -hoP "model: \K.*" | sort -u)
872     # Selected topology NICs
873     reserved=$(sed "${sed_command}" "${WORKING_TOPOLOGY}" \
874                | grep -hoP "model: \K.*" | sort -u)
875     # All topologies NICs - Selected topology NICs
876     exclude_nics=($(comm -13 <(echo "${reserved}") <(echo "${available}"))) || {
877         die "Computation of excluded NICs failed."
878     }
879
880     # Select default NIC tag.
881     case "${TEST_CODE}" in
882         *"3n-dnv"* | *"2n-dnv"*)
883             default_nic="nic_intel-x553"
884             ;;
885         *"3n-snr"*)
886             default_nic="nic_intel-e810xxv"
887             ;;
888         *"3n-tsh"*)
889             default_nic="nic_intel-x520-da2"
890             ;;
891         *"3n-icx"* | *"2n-icx"*)
892             default_nic="nic_intel-xxv710"
893             ;;
894         *"3n-skx"* | *"2n-skx"* | *"2n-clx"* | *"2n-zn2"*)
895             default_nic="nic_intel-xxv710"
896             ;;
897         *"2n-tx2"* | *"3n-alt"* | *"mrr-daily-master")
898             default_nic="nic_intel-xl710"
899             ;;
900         *"1n-aws"* | *"2n-aws"* | *"3n-aws"*)
901             default_nic="nic_amazon-nitro-50g"
902             ;;
903         *)
904             default_nic="nic_intel-x710"
905             ;;
906     esac
907
908     sed_nic_sub_cmd="sed s/\${default_nic}/${default_nic}/"
909     awk_nics_sub_cmd=""
910     awk_nics_sub_cmd+='gsub("xxv710","25ge2p1xxv710");'
911     awk_nics_sub_cmd+='gsub("x710","10ge2p1x710");'
912     awk_nics_sub_cmd+='gsub("xl710","40ge2p1xl710");'
913     awk_nics_sub_cmd+='gsub("x520-da2","10ge2p1x520");'
914     awk_nics_sub_cmd+='gsub("x553","10ge2p1x553");'
915     awk_nics_sub_cmd+='gsub("cx556a","100ge2p1cx556a");'
916     awk_nics_sub_cmd+='gsub("e810cq","100ge2p1e810cq");'
917     awk_nics_sub_cmd+='gsub("vic1227","10ge2p1vic1227");'
918     awk_nics_sub_cmd+='gsub("vic1385","40ge2p1vic1385");'
919     awk_nics_sub_cmd+='gsub("nitro-50g","50ge1p1ENA");'
920     awk_nics_sub_cmd+='if ($9 =="drv_avf") drv="avf-";'
921     awk_nics_sub_cmd+='else if ($9 =="drv_rdma_core") drv ="rdma-";'
922     awk_nics_sub_cmd+='else if ($9 =="drv_af_xdp") drv ="af-xdp-";'
923     awk_nics_sub_cmd+='else drv="";'
924     awk_nics_sub_cmd+='if ($1 =="-") cores="";'
925     awk_nics_sub_cmd+='else cores=$1;'
926     awk_nics_sub_cmd+='print "*"$7"-" drv $11"-"$5"."$3"-" cores "-" drv $11"-"$5'
927
928     # Tag file directory shorthand.
929     tfd="${JOB_SPECS_DIR}"
930     case "${TEST_CODE}" in
931         # Select specific performance tests based on jenkins job type variable.
932         *"device"* )
933             readarray -t test_tag_array <<< $(grep -v "#" \
934                 ${tfd}/vpp_device/${DUT}-${NODENESS}-${FLAVOR}.md |
935                 awk {"$awk_nics_sub_cmd"} || echo "devicetest") || die
936             SELECTION_MODE="--test"
937             ;;
938         *"ndrpdr-weekly"* )
939             readarray -t test_tag_array <<< $(grep -v "#" \
940                 ${tfd}/mlr_weekly/${DUT}-${NODENESS}-${FLAVOR}.md |
941                 awk {"$awk_nics_sub_cmd"} || echo "perftest") || die
942             SELECTION_MODE="--test"
943             ;;
944         *"mrr-daily"* )
945             readarray -t test_tag_array <<< $(grep -v "#" \
946                 ${tfd}/mrr_daily/${DUT}-${NODENESS}-${FLAVOR}.md |
947                 awk {"$awk_nics_sub_cmd"} || echo "perftest") || die
948             SELECTION_MODE="--test"
949             ;;
950         *"mrr-weekly"* )
951             readarray -t test_tag_array <<< $(grep -v "#" \
952                 ${tfd}/mrr_weekly/${DUT}-${NODENESS}-${FLAVOR}.md |
953                 awk {"$awk_nics_sub_cmd"} || echo "perftest") || die
954             SELECTION_MODE="--test"
955             ;;
956         *"report-iterative"* )
957             test_sets=(${TEST_TAG_STRING//:/ })
958             # Run only one test set per run
959             report_file=${test_sets[0]}.md
960             readarray -t test_tag_array <<< $(grep -v "#" \
961                 ${tfd}/report_iterative/${NODENESS}-${FLAVOR}/${report_file} |
962                 awk {"$awk_nics_sub_cmd"} || echo "perftest") || die
963             SELECTION_MODE="--test"
964             ;;
965         *"report-coverage"* )
966             test_sets=(${TEST_TAG_STRING//:/ })
967             # Run only one test set per run
968             report_file=${test_sets[0]}.md
969             readarray -t test_tag_array <<< $(grep -v "#" \
970                 ${tfd}/report_coverage/${NODENESS}-${FLAVOR}/${report_file} |
971                 awk {"$awk_nics_sub_cmd"} || echo "perftest") || die
972             SELECTION_MODE="--test"
973             ;;
974         * )
975             if [[ -z "${TEST_TAG_STRING-}" ]]; then
976                 # If nothing is specified, we will run pre-selected tests by
977                 # following tags.
978                 test_tag_array=("mrrAND${default_nic}AND1cAND64bANDethip4-ip4base"
979                                 "mrrAND${default_nic}AND1cAND78bANDethip6-ip6base"
980                                 "mrrAND${default_nic}AND1cAND64bANDeth-l2bdbasemaclrn"
981                                 "mrrAND${default_nic}AND1cAND64bANDeth-l2xcbase"
982                                 "!drv_af_xdp" "!drv_avf")
983             else
984                 # If trigger contains tags, split them into array.
985                 test_tag_array=(${TEST_TAG_STRING//:/ })
986             fi
987             SELECTION_MODE="--include"
988             ;;
989     esac
990
991     # Blacklisting certain tags per topology.
992     #
993     # Reasons for blacklisting:
994     # - ipsechw - Blacklisted on testbeds without crypto hardware accelerator.
995     case "${TEST_CODE}" in
996         *"1n-vbox"*)
997             test_tag_array+=("!avf")
998             test_tag_array+=("!vhost")
999             test_tag_array+=("!flow")
1000             ;;
1001         *"1n_tx2"*)
1002             test_tag_array+=("!flow")
1003             ;;
1004         *"2n-skx"*)
1005             test_tag_array+=("!ipsechw")
1006             ;;
1007         *"3n-skx"*)
1008             test_tag_array+=("!ipsechw")
1009             # Not enough nic_intel-xxv710 to support double link tests.
1010             test_tag_array+=("!3_node_double_link_topoANDnic_intel-xxv710")
1011             ;;
1012         *"2n-clx"*)
1013             test_tag_array+=("!ipsechw")
1014             ;;
1015         *"2n-icx"*)
1016             test_tag_array+=("!ipsechw")
1017             ;;
1018         *"3n-icx"*)
1019             test_tag_array+=("!ipsechw")
1020             # Not enough nic_intel-xxv710 to support double link tests.
1021             test_tag_array+=("!3_node_double_link_topoANDnic_intel-xxv710")
1022             ;;
1023         *"2n-zn2"*)
1024             test_tag_array+=("!ipsechw")
1025             ;;
1026         *"2n-dnv"*)
1027             test_tag_array+=("!memif")
1028             test_tag_array+=("!srv6_proxy")
1029             test_tag_array+=("!vhost")
1030             test_tag_array+=("!vts")
1031             test_tag_array+=("!drv_avf")
1032             ;;
1033         *"2n-tx2"* | *"3n-alt"*)
1034             test_tag_array+=("!ipsechw")
1035             ;;
1036         *"3n-dnv"*)
1037             test_tag_array+=("!memif")
1038             test_tag_array+=("!srv6_proxy")
1039             test_tag_array+=("!vhost")
1040             test_tag_array+=("!vts")
1041             test_tag_array+=("!drv_avf")
1042             ;;
1043         *"3n-snr"*)
1044             ;;
1045         *"3n-tsh"*)
1046             # 3n-tsh only has x520 NICs which don't work with AVF
1047             test_tag_array+=("!drv_avf")
1048             test_tag_array+=("!ipsechw")
1049             ;;
1050         *"1n-aws"* | *"2n-aws"* | *"3n-aws"*)
1051             test_tag_array+=("!ipsechw")
1052             ;;
1053     esac
1054
1055     # We will add excluded NICs.
1056     test_tag_array+=("${exclude_nics[@]/#/!NIC_}")
1057
1058     TAGS=()
1059     prefix=""
1060
1061     set +x
1062     if [[ "${TEST_CODE}" == "vpp-"* ]]; then
1063         if [[ "${TEST_CODE}" != *"device"* ]]; then
1064             # Automatic prefixing for VPP perf jobs to limit the NIC used and
1065             # traffic evaluation to MRR.
1066             if [[ "${TEST_TAG_STRING-}" == *"nic_"* ]]; then
1067                 prefix="${prefix}mrrAND"
1068             else
1069                 prefix="${prefix}mrrAND${default_nic}AND"
1070             fi
1071         fi
1072     fi
1073     for tag in "${test_tag_array[@]}"; do
1074         if [[ "${tag}" == "!"* ]]; then
1075             # Exclude tags are not prefixed.
1076             TAGS+=("${tag}")
1077         elif [[ "${tag}" == " "* || "${tag}" == *"perftest"* ]]; then
1078             # Badly formed tag expressions can trigger way too much tests.
1079             set -x
1080             warn "The following tag expression hints at bad trigger: ${tag}"
1081             warn "Possible cause: Multiple triggers in a single comment."
1082             die "Aborting to avoid triggering too many tests."
1083         elif [[ "${tag}" == *"OR"* ]]; then
1084             # If OR had higher precedence than AND, it would be useful here.
1085             # Some people think it does, thus triggering way too much tests.
1086             set -x
1087             warn "The following tag expression hints at bad trigger: ${tag}"
1088             warn "Operator OR has lower precedence than AND. Use space instead."
1089             die "Aborting to avoid triggering too many tests."
1090         elif [[ "${tag}" != "" && "${tag}" != "#"* ]]; then
1091             # Empty and comment lines are skipped.
1092             # Other lines are normal tags, they are to be prefixed.
1093             TAGS+=("${prefix}${tag}")
1094         fi
1095     done
1096     set -x
1097 }
1098
1099
1100 function select_topology () {
1101
1102     # Variables read:
1103     # - NODENESS - Node multiplicity of testbed, either "2n" or "3n".
1104     # - FLAVOR - Node flavor string, e.g. "clx" or "skx".
1105     # - CSIT_DIR - Path to existing root of local CSIT git repository.
1106     # - TOPOLOGIES_DIR - Path to existing directory with available topologies.
1107     # Variables set:
1108     # - TOPOLOGIES - Array of paths to suitable topology yaml files.
1109     # - TOPOLOGIES_TAGS - Tag expression selecting tests for the topology.
1110     # Functions called:
1111     # - die - Print to stderr and exit.
1112
1113     set -exuo pipefail
1114
1115     case_text="${NODENESS}_${FLAVOR}"
1116     case "${case_text}" in
1117         "1n_vbox")
1118             TOPOLOGIES=( "${TOPOLOGIES_DIR}"/*vpp_device*.template )
1119             TOPOLOGIES_TAGS="2_node_single_link_topo"
1120             ;;
1121         "1n_skx" | "1n_tx2")
1122             TOPOLOGIES=( "${TOPOLOGIES_DIR}"/*vpp_device*.template )
1123             TOPOLOGIES_TAGS="2_node_single_link_topo"
1124             ;;
1125         "2n_skx")
1126             TOPOLOGIES=( "${TOPOLOGIES_DIR}"/*2n_skx*.yaml )
1127             TOPOLOGIES_TAGS="2_node_*_link_topo"
1128             ;;
1129         "2n_zn2")
1130             TOPOLOGIES=( "${TOPOLOGIES_DIR}"/*2n_zn2*.yaml )
1131             TOPOLOGIES_TAGS="2_node_*_link_topo"
1132             ;;
1133         "3n_skx")
1134             TOPOLOGIES=( "${TOPOLOGIES_DIR}"/*3n_skx*.yaml )
1135             TOPOLOGIES_TAGS="3_node_*_link_topo"
1136             ;;
1137         "3n_icx")
1138             TOPOLOGIES=( "${TOPOLOGIES_DIR}"/*3n_icx*.yaml )
1139             TOPOLOGIES_TAGS="3_node_*_link_topo"
1140             ;;
1141         "2n_clx")
1142             TOPOLOGIES=( "${TOPOLOGIES_DIR}"/*2n_clx*.yaml )
1143             TOPOLOGIES_TAGS="2_node_*_link_topo"
1144             ;;
1145         "2n_icx")
1146             TOPOLOGIES=( "${TOPOLOGIES_DIR}"/*2n_icx*.yaml )
1147             TOPOLOGIES_TAGS="2_node_*_link_topo"
1148             ;;
1149         "2n_dnv")
1150             TOPOLOGIES=( "${TOPOLOGIES_DIR}"/*2n_dnv*.yaml )
1151             TOPOLOGIES_TAGS="2_node_single_link_topo"
1152             ;;
1153         "3n_dnv")
1154             TOPOLOGIES=( "${TOPOLOGIES_DIR}"/*3n_dnv*.yaml )
1155             TOPOLOGIES_TAGS="3_node_single_link_topo"
1156             ;;
1157         "3n_tsh")
1158             TOPOLOGIES=( "${TOPOLOGIES_DIR}"/*3n_tsh*.yaml )
1159             TOPOLOGIES_TAGS="3_node_single_link_topo"
1160             ;;
1161         "2n_tx2")
1162             TOPOLOGIES=( "${TOPOLOGIES_DIR}"/*2n_tx2*.yaml )
1163             TOPOLOGIES_TAGS="2_node_single_link_topo"
1164             ;;
1165         "3n_alt")
1166             TOPOLOGIES=( "${TOPOLOGIES_DIR}"/*3n_alt*.yaml )
1167             TOPOLOGIES_TAGS="3_node_single_link_topo"
1168             ;;
1169         "1n_aws")
1170             TOPOLOGIES=( "${TOPOLOGIES_DIR}"/*1n-aws*.yaml )
1171             TOPOLOGIES_TAGS="1_node_single_link_topo"
1172             ;;
1173         "2n_aws")
1174             TOPOLOGIES=( "${TOPOLOGIES_DIR}"/*2n-aws*.yaml )
1175             TOPOLOGIES_TAGS="2_node_single_link_topo"
1176             ;;
1177         "3n_aws")
1178             TOPOLOGIES=( "${TOPOLOGIES_DIR}"/*3n-aws*.yaml )
1179             TOPOLOGIES_TAGS="3_node_single_link_topo"
1180             ;;
1181         *)
1182             # No falling back to default, that should have been done
1183             # by the function which has set NODENESS and FLAVOR.
1184             die "Unknown specification: ${case_text}"
1185     esac
1186
1187     if [[ -z "${TOPOLOGIES-}" ]]; then
1188         die "No applicable topology found!"
1189     fi
1190 }
1191
1192
1193 function set_environment_variables () {
1194
1195     # Depending on testbed topology, overwrite defaults set in the
1196     # resources/libraries/python/Constants.py file
1197     #
1198     # Variables read:
1199     # - TEST_CODE - String affecting test selection, usually jenkins job name.
1200     # Variables set:
1201     # See specific cases
1202
1203     set -exuo pipefail
1204
1205     case "${TEST_CODE}" in
1206         *"1n-aws"* | *"2n-aws"* | *"3n-aws"*)
1207             # T-Rex 2.88+ workaround for ENA NICs.
1208             export TREX_RX_DESCRIPTORS_COUNT=1024
1209             export TREX_EXTRA_CMDLINE="--mbuf-factor 19"
1210             export TREX_CORE_COUNT=6
1211             # Settings to prevent duration stretching.
1212             export PERF_TRIAL_STL_DELAY=0.1
1213             ;;
1214         *"2n-zn2"*)
1215             # Maciek's workaround for Zen2 with lower amount of cores.
1216             export TREX_CORE_COUNT=14
1217     esac
1218 }
1219
1220
1221 function untrap_and_unreserve_testbed () {
1222
1223     # Use this as a trap function to ensure testbed does not remain reserved.
1224     # Perhaps call directly before script exit, to free testbed for other jobs.
1225     # This function is smart enough to avoid multiple unreservations (so safe).
1226     # Topo cleanup is executed (call it best practice), ignoring failures.
1227     #
1228     # Hardcoded values:
1229     # - default message to die with if testbed might remain reserved.
1230     # Arguments:
1231     # - ${1} - Message to die with if unreservation fails. Default hardcoded.
1232     # Variables read (by inner function):
1233     # - WORKING_TOPOLOGY - Path to topology yaml file of the reserved testbed.
1234     # - PYTHON_SCRIPTS_DIR - Path to directory holding Python scripts.
1235     # Variables written:
1236     # - WORKING_TOPOLOGY - Set to empty string on successful unreservation.
1237     # Trap unregistered:
1238     # - EXIT - Failure to untrap is reported, but ignored otherwise.
1239     # Functions called:
1240     # - die - Print to stderr and exit.
1241     # - ansible_playbook - Perform an action using ansible, see ansible.sh
1242
1243     set -xo pipefail
1244     set +eu  # We do not want to exit early in a "teardown" function.
1245     trap - EXIT || echo "Trap deactivation failed, continuing anyway."
1246     wt="${WORKING_TOPOLOGY}"  # Just to avoid too long lines.
1247     if [[ -z "${wt-}" ]]; then
1248         set -eu
1249         warn "Testbed looks unreserved already. Trap removal failed before?"
1250     else
1251         ansible_playbook "cleanup" || true
1252         python3 "${PYTHON_SCRIPTS_DIR}/topo_reservation.py" -c -t "${wt}" || {
1253             die "${1:-FAILED TO UNRESERVE, FIX MANUALLY.}" 2
1254         }
1255         case "${TEST_CODE}" in
1256             *"1n-aws"* | *"2n-aws"* | *"3n-aws"*)
1257                 terraform_destroy || die "Failed to call terraform destroy."
1258                 ;;
1259             *)
1260                 ;;
1261         esac
1262         WORKING_TOPOLOGY=""
1263         set -eu
1264     fi
1265 }
1266
1267
1268 function warn () {
1269
1270     # Print the message to standard error.
1271     #
1272     # Arguments:
1273     # - ${@} - The text of the message.
1274
1275     set -exuo pipefail
1276
1277     echo "$@" >&2
1278 }