fix(core): Missing link
[csit.git] / resources / libraries / bash / function / common.sh
1 # Copyright (c) 2023 Cisco and/or its affiliates.
2 # Copyright (c) 2023 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}/resources/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     PYTHON_SCRIPTS_DIR=$(readlink -e "${TOOLS_DIR}/scripts") || {
240         die "Readlink failed."
241     }
242
243     ARCHIVE_DIR=$(readlink -f "${CSIT_DIR}/archives") || {
244         die "Readlink failed."
245     }
246     mkdir -p "${ARCHIVE_DIR}" || die "Mkdir failed."
247     DOWNLOAD_DIR=$(readlink -f "${CSIT_DIR}/download_dir") || {
248         die "Readlink failed."
249     }
250     mkdir -p "${DOWNLOAD_DIR}" || die "Mkdir failed."
251     GENERATED_DIR=$(readlink -f "${CSIT_DIR}/generated") || {
252         die "Readlink failed."
253     }
254     mkdir -p "${GENERATED_DIR}" || die "Mkdir failed."
255 }
256
257
258 function compose_pybot_arguments () {
259
260     # Variables read:
261     # - WORKING_TOPOLOGY - Path to topology yaml file of the reserved testbed.
262     # - DUT - CSIT test/ subdirectory, set while processing tags.
263     # - TAGS - Array variable holding selected tag boolean expressions.
264     # - TOPOLOGIES_TAGS - Tag boolean expression filtering tests for topology.
265     # - TEST_CODE - The test selection string from environment or argument.
266     # - SELECTION_MODE - Selection criteria [test, suite, include, exclude].
267     # Variables set:
268     # - PYBOT_ARGS - String holding part of all arguments for pybot.
269     # - EXPANDED_TAGS - Array of strings pybot arguments compiled from tags.
270
271     set -exuo pipefail
272
273     # No explicit check needed with "set -u".
274     PYBOT_ARGS=("--loglevel" "TRACE")
275     PYBOT_ARGS+=("--variable" "TOPOLOGY_PATH:${WORKING_TOPOLOGY}")
276
277     case "${TEST_CODE}" in
278         *"device"*)
279             PYBOT_ARGS+=("--suite" "tests.${DUT}.device")
280             ;;
281         *"perf"*)
282             PYBOT_ARGS+=("--suite" "tests.${DUT}.perf")
283             ;;
284         *)
285             die "Unknown specification: ${TEST_CODE}"
286     esac
287
288     EXPANDED_TAGS=()
289     for tag in "${TAGS[@]}"; do
290         if [[ ${tag} == "!"* ]]; then
291             EXPANDED_TAGS+=("--exclude" "${tag#$"!"}")
292         else
293             if [[ ${SELECTION_MODE} == "--test" ]]; then
294                 EXPANDED_TAGS+=("--test" "${tag}")
295             else
296                 EXPANDED_TAGS+=("--include" "${TOPOLOGIES_TAGS}AND${tag}")
297             fi
298         fi
299     done
300
301     if [[ ${SELECTION_MODE} == "--test" ]]; then
302         EXPANDED_TAGS+=("--include" "${TOPOLOGIES_TAGS}")
303     fi
304 }
305
306
307 function deactivate_docker_topology () {
308
309     # Deactivate virtual vpp-device topology by removing containers.
310     #
311     # Variables read:
312     # - NODENESS - Node multiplicity of desired testbed.
313     # - FLAVOR - Node flavor string, usually describing the processor.
314
315     set -exuo pipefail
316
317     case_text="${NODENESS}_${FLAVOR}"
318     case "${case_text}" in
319         "1n_skx" | "1n_tx2")
320             ssh="ssh root@172.17.0.1 -p 6022"
321             env_vars=$(env | grep CSIT_ | tr '\n' ' ' ) || die
322             # The "declare -f" output is long and boring.
323             set +x
324             ${ssh} "$(declare -f); deactivate_wrapper ${env_vars}" || {
325                 die "Topology cleanup via shim-dcr failed!"
326             }
327             set -x
328             ;;
329         "1n_vbox")
330             enter_mutex || die
331             clean_environment || {
332                 die "Topology cleanup locally failed!"
333             }
334             exit_mutex || die
335             ;;
336         *)
337             die "Unknown specification: ${case_text}!"
338     esac
339 }
340
341
342 function die () {
343
344     # Print the message to standard error end exit with error code specified
345     # by the second argument.
346     #
347     # Hardcoded values:
348     # - The default error message.
349     # Arguments:
350     # - ${1} - The whole error message, be sure to quote. Optional
351     # - ${2} - the code to exit with, default: 1.
352
353     set -x
354     set +eu
355     warn "${1:-Unspecified run-time error occurred!}"
356     exit "${2:-1}"
357 }
358
359
360 function die_on_pybot_error () {
361
362     # Source this fragment if you want to abort on any failed test case.
363     #
364     # Variables read:
365     # - PYBOT_EXIT_STATUS - Set by a pybot running fragment.
366     # Functions called:
367     # - die - Print to stderr and exit.
368
369     set -exuo pipefail
370
371     if [[ "${PYBOT_EXIT_STATUS}" != "0" ]]; then
372         die "Test failures are present!" "${PYBOT_EXIT_STATUS}"
373     fi
374 }
375
376
377 function generate_tests () {
378
379     # Populate ${GENERATED_DIR}/tests based on ${CSIT_DIR}/tests/.
380     # Any previously existing content of ${GENERATED_DIR}/tests is wiped before.
381     # The generation is done by executing any *.py executable
382     # within any subdirectory after copying.
383
384     # This is a separate function, because this code is called
385     # both by autogen checker and entries calling run_pybot.
386
387     # Directories read:
388     # - ${CSIT_DIR}/tests - Used as templates for the generated tests.
389     # Directories replaced:
390     # - ${GENERATED_DIR}/tests - Overwritten by the generated tests.
391
392     set -exuo pipefail
393
394     rm -rf "${GENERATED_DIR}/tests" || die
395     cp -r "${CSIT_DIR}/tests" "${GENERATED_DIR}/tests" || die
396     cmd_line=("find" "${GENERATED_DIR}/tests" "-type" "f")
397     cmd_line+=("-executable" "-name" "*.py")
398     # We sort the directories, so log output can be compared between runs.
399     file_list=$("${cmd_line[@]}" | sort) || die
400
401     for gen in ${file_list}; do
402         directory="$(dirname "${gen}")" || die
403         filename="$(basename "${gen}")" || die
404         pushd "${directory}" || die
405         ./"${filename}" || die
406         popd || die
407     done
408 }
409
410
411 function get_test_code () {
412
413     # Arguments:
414     # - ${1} - Optional, argument of entry script (or empty as unset).
415     #   Test code value to override job name from environment.
416     # Variables read:
417     # - JOB_NAME - String affecting test selection, default if not argument.
418     # Variables set:
419     # - TEST_CODE - The test selection string from environment or argument.
420     # - NODENESS - Node multiplicity of desired testbed.
421     # - FLAVOR - Node flavor string, usually describing the processor.
422
423     set -exuo pipefail
424
425     TEST_CODE="${1-}" || die "Reading optional argument failed, somehow."
426     if [[ -z "${TEST_CODE}" ]]; then
427         TEST_CODE="${JOB_NAME-}" || die "Reading job name failed, somehow."
428     fi
429
430     case "${TEST_CODE}" in
431         *"1n-vbox"*)
432             NODENESS="1n"
433             FLAVOR="vbox"
434             ;;
435         *"1n-skx"*)
436             NODENESS="1n"
437             FLAVOR="skx"
438             ;;
439         *"1n-tx2"*)
440             NODENESS="1n"
441             FLAVOR="tx2"
442             ;;
443         *"1n-aws"*)
444             NODENESS="1n"
445             FLAVOR="aws"
446             ;;
447         *"2n-aws"*)
448             NODENESS="2n"
449             FLAVOR="aws"
450             ;;
451         *"3n-aws"*)
452             NODENESS="3n"
453             FLAVOR="aws"
454             ;;
455         *"2n-zn2"*)
456             NODENESS="2n"
457             FLAVOR="zn2"
458             ;;
459         *"2n-clx"*)
460             NODENESS="2n"
461             FLAVOR="clx"
462             ;;
463         *"2n-icx"*)
464             NODENESS="2n"
465             FLAVOR="icx"
466             ;;
467         *"2n-spr"*)
468             NODENESS="2n"
469             FLAVOR="spr"
470             ;;
471         *"3n-icx"*)
472             NODENESS="3n"
473             FLAVOR="icx"
474             ;;
475         *"3na-spr"*)
476             NODENESS="3na"
477             FLAVOR="spr"
478             ;;
479         *"3nb-spr"*)
480             NODENESS="3nb"
481             FLAVOR="spr"
482             ;;
483         *"3n-snr"*)
484             NODENESS="3n"
485             FLAVOR="snr"
486             ;;
487         *"2n-tx2"*)
488             NODENESS="2n"
489             FLAVOR="tx2"
490             ;;
491         *"3n-tsh"*)
492             NODENESS="3n"
493             FLAVOR="tsh"
494             ;;
495         *"3n-alt"*)
496             NODENESS="3n"
497             FLAVOR="alt"
498             ;;
499     esac
500 }
501
502
503 function get_test_tag_string () {
504
505     # Variables read:
506     # - GERRIT_EVENT_TYPE - Event type set by gerrit, can be unset.
507     # - GERRIT_EVENT_COMMENT_TEXT - Comment text, read for "comment-added" type.
508     # - TEST_CODE - The test selection string from environment or argument.
509     # Variables set:
510     # - TEST_TAG_STRING - The string following trigger word in gerrit comment.
511     #   May be empty, or even not set on event types not adding comment.
512
513     # TODO: ci-management scripts no longer need to perform this.
514
515     set -exuo pipefail
516
517     if [[ "${GERRIT_EVENT_TYPE-}" == "comment-added" ]]; then
518         case "${TEST_CODE}" in
519             *"device"*)
520                 trigger="devicetest"
521                 ;;
522             *"perf"*)
523                 trigger="perftest"
524                 ;;
525             *)
526                 die "Unknown specification: ${TEST_CODE}"
527         esac
528         # Ignore lines not containing the trigger word.
529         comment=$(fgrep "${trigger}" <<< "${GERRIT_EVENT_COMMENT_TEXT}" || true)
530         # The vpp-csit triggers trail stuff we are not interested in.
531         # Removing them and trigger word: https://unix.stackexchange.com/a/13472
532         # (except relying on \s whitespace, \S non-whitespace and . both).
533         # The last string is concatenated, only the middle part is expanded.
534         cmd=("grep" "-oP" '\S*'"${trigger}"'\S*\s\K.+$') || die "Unset trigger?"
535         # On parsing error, TEST_TAG_STRING probably stays empty.
536         TEST_TAG_STRING=$("${cmd[@]}" <<< "${comment}" || true)
537         if [[ -z "${TEST_TAG_STRING-}" ]]; then
538             # Probably we got a base64 encoded comment.
539             comment="${GERRIT_EVENT_COMMENT_TEXT}"
540             comment=$(base64 --decode <<< "${comment}" || true)
541             comment=$(fgrep "${trigger}" <<< "${comment}" || true)
542             TEST_TAG_STRING=$("${cmd[@]}" <<< "${comment}" || true)
543         fi
544         if [[ -n "${TEST_TAG_STRING-}" ]]; then
545             test_tag_array=(${TEST_TAG_STRING})
546             if [[ "${test_tag_array[0]}" == "icl" ]]; then
547                 export GRAPH_NODE_VARIANT="icl"
548                 TEST_TAG_STRING="${test_tag_array[@]:1}" || true
549             elif [[ "${test_tag_array[0]}" == "skx" ]]; then
550                 export GRAPH_NODE_VARIANT="skx"
551                 TEST_TAG_STRING="${test_tag_array[@]:1}" || true
552             fi
553         fi
554     fi
555 }
556
557
558 function installed () {
559
560     # Check if the given utility is installed. Fail if not installed.
561     #
562     # Duplicate of common.sh function, as this file is also used standalone.
563     #
564     # Arguments:
565     # - ${1} - Utility to check.
566     # Returns:
567     # - 0 - If command is installed.
568     # - 1 - If command is not installed.
569
570     set -exuo pipefail
571
572     command -v "${1}"
573 }
574
575
576 function move_archives () {
577
578     # Move archive directory to top of workspace, if not already there.
579     #
580     # ARCHIVE_DIR is positioned relative to CSIT_DIR,
581     # but in some jobs CSIT_DIR is not same as WORKSPACE
582     # (e.g. under VPP_DIR). To simplify ci-management settings,
583     # we want to move the data to the top. We do not want simple copy,
584     # as ci-management is eager with recursive search.
585     #
586     # As some scripts may call this function multiple times,
587     # the actual implementation use copying and deletion,
588     # so the workspace gets "union" of contents (except overwrites on conflict).
589     # The consequence is empty ARCHIVE_DIR remaining after this call.
590     #
591     # As the source directory is emptied,
592     # the check for dirs being different is essential.
593     #
594     # Variables read:
595     # - WORKSPACE - Jenkins workspace, move only if the value is not empty.
596     #   Can be unset, then it speeds up manual testing.
597     # - ARCHIVE_DIR - Path to directory with content to be moved.
598     # Directories updated:
599     # - ${WORKSPACE}/archives/ - Created if does not exist.
600     #   Content of ${ARCHIVE_DIR}/ is moved.
601     # Functions called:
602     # - die - Print to stderr and exit.
603
604     set -exuo pipefail
605
606     if [[ -n "${WORKSPACE-}" ]]; then
607         target=$(readlink -f "${WORKSPACE}/archives")
608         if [[ "${target}" != "${ARCHIVE_DIR}" ]]; then
609             mkdir -p "${target}" || die "Archives dir create failed."
610             cp -rf "${ARCHIVE_DIR}"/* "${target}" || die "Copy failed."
611             rm -rf "${ARCHIVE_DIR}"/* || die "Delete failed."
612         fi
613     fi
614 }
615
616
617 function post_process_robot_outputs () {
618
619     # Generate INFO level output_info.xml by rebot.
620     #
621     # Variables read:
622     # - ARCHIVE_DIR - Path to post-processed files.
623
624     set -exuo pipefail
625
626     # Generate INFO level output_info.xml for post-processing.
627     all_options=("--loglevel" "INFO")
628     all_options+=("--log" "none")
629     all_options+=("--report" "none")
630     all_options+=("--output" "${ARCHIVE_DIR}/output_info.xml")
631     all_options+=("${ARCHIVE_DIR}/output.xml")
632     rebot "${all_options[@]}" || true
633 }
634
635
636 function prepare_topology () {
637
638     # Prepare virtual testbed topology if needed based on flavor.
639
640     # Variables read:
641     # - TEST_CODE - String affecting test selection, usually jenkins job name.
642     # - NODENESS - Node multiplicity of testbed, either "2n" or "3n".
643     # - FLAVOR - Node flavor string, e.g. "clx" or "skx".
644     # Variables set:
645     # - TERRAFORM_MODULE_DIR - Terraform module directory.
646     # Functions called:
647     # - die - Print to stderr and exit.
648     # - terraform_init - Terraform init topology.
649     # - terraform_apply - Terraform apply topology.
650
651     set -exuo pipefail
652
653     case_text="${NODENESS}_${FLAVOR}"
654     case "${case_text}" in
655         "1n_aws" | "2n_aws" | "3n_aws")
656             export TF_VAR_testbed_name="${TEST_CODE}"
657             TERRAFORM_MODULE_DIR="terraform-aws-${NODENESS}-${FLAVOR}-c5n"
658             terraform_init || die "Failed to call terraform init."
659             trap 'terraform_destroy' ERR || {
660                 die "Trap attempt failed, please cleanup manually. Aborting!"
661             }
662             terraform_apply || die "Failed to call terraform apply."
663             ;;
664     esac
665 }
666
667
668 function reserve_and_cleanup_testbed () {
669
670     # Reserve physical testbed, perform cleanup, register trap to unreserve.
671     # When cleanup fails, remove from topologies and keep retrying
672     # until all topologies are removed.
673     #
674     # Variables read:
675     # - TOPOLOGIES - Array of paths to topology yaml to attempt reservation on.
676     # - PYTHON_SCRIPTS_DIR - Path to directory holding the reservation script.
677     # - BUILD_TAG - Any string suitable as filename, identifying
678     #   test run executing this function. May be unset.
679     # Variables set:
680     # - TOPOLOGIES - Array of paths to topologies, with failed cleanups removed.
681     # - WORKING_TOPOLOGY - Path to topology yaml file of the reserved testbed.
682     # Functions called:
683     # - die - Print to stderr and exit.
684     # - ansible_playbook - Perform an action using ansible, see ansible.sh
685     # Traps registered:
686     # - EXIT - Calls cancel_all for ${WORKING_TOPOLOGY}.
687
688     set -exuo pipefail
689
690     while true; do
691         for topo in "${TOPOLOGIES[@]}"; do
692             set +e
693             scrpt="${PYTHON_SCRIPTS_DIR}/topo_reservation.py"
694             opts=("-t" "${topo}" "-r" "${BUILD_TAG:-Unknown}")
695             python3 "${scrpt}" "${opts[@]}"
696             result="$?"
697             set -e
698             if [[ "${result}" == "0" ]]; then
699                 # Trap unreservation before cleanup check,
700                 # so multiple jobs showing failed cleanup improve chances
701                 # of humans to notice and fix.
702                 WORKING_TOPOLOGY="${topo}"
703                 echo "Reserved: ${WORKING_TOPOLOGY}"
704                 trap "untrap_and_unreserve_testbed" EXIT || {
705                     message="TRAP ATTEMPT AND UNRESERVE FAILED, FIX MANUALLY."
706                     untrap_and_unreserve_testbed "${message}" || {
707                         die "Teardown should have died, not failed."
708                     }
709                     die "Trap attempt failed, unreserve succeeded. Aborting."
710                 }
711                 # Cleanup + calibration checks
712                 set +e
713                 ansible_playbook "cleanup, calibration"
714                 result="$?"
715                 set -e
716                 if [[ "${result}" == "0" ]]; then
717                     break
718                 fi
719                 warn "Testbed cleanup failed: ${topo}"
720                 untrap_and_unreserve_testbed "Fail of unreserve after cleanup."
721             fi
722             # Else testbed is accessible but currently reserved, moving on.
723         done
724
725         if [[ -n "${WORKING_TOPOLOGY-}" ]]; then
726             # Exit the infinite while loop if we made a reservation.
727             warn "Reservation and cleanup successful."
728             break
729         fi
730
731         if [[ "${#TOPOLOGIES[@]}" == "0" ]]; then
732             die "Run out of operational testbeds!"
733         fi
734
735         # Wait ~3minutes before next try.
736         sleep_time="$[ ( ${RANDOM} % 20 ) + 180 ]s" || {
737             die "Sleep time calculation failed."
738         }
739         echo "Sleeping ${sleep_time}"
740         sleep "${sleep_time}" || die "Sleep failed."
741     done
742 }
743
744
745 function run_pybot () {
746
747     # Run pybot with options based on input variables.
748     # Generate INFO level output_info.xml by rebot.
749     #
750     # Variables read:
751     # - CSIT_DIR - Path to existing root of local CSIT git repository.
752     # - ARCHIVE_DIR - Path to store robot result files in.
753     # - PYBOT_ARGS, EXPANDED_TAGS - See compose_pybot_arguments.sh
754     # - GENERATED_DIR - Tests are assumed to be generated under there.
755     # Variables set:
756     # - PYBOT_EXIT_STATUS - Exit status of most recent pybot invocation.
757     # Functions called:
758     # - die - Print to stderr and exit.
759
760     set -exuo pipefail
761
762     all_options=("--outputdir" "${ARCHIVE_DIR}" "${PYBOT_ARGS[@]}")
763     all_options+=("${EXPANDED_TAGS[@]}")
764
765     pushd "${CSIT_DIR}" || die "Change directory operation failed."
766     set +e
767     robot "${all_options[@]}" "${GENERATED_DIR}/tests/"
768     PYBOT_EXIT_STATUS="$?"
769     set -e
770
771     post_process_robot_outputs || die
772
773     popd || die "Change directory operation failed."
774 }
775
776
777 function select_arch_os () {
778
779     # Set variables affected by local CPU architecture and operating system.
780     #
781     # Variables set:
782     # - VPP_VER_FILE - Name of file in CSIT dir containing vpp stable version.
783     # - IMAGE_VER_FILE - Name of file in CSIT dir containing the image name.
784     # - PKG_SUFFIX - Suffix of OS package file name, "rpm" or "deb."
785
786     set -exuo pipefail
787
788     source /etc/os-release || die "Get OS release failed."
789
790     case "${ID}" in
791         "ubuntu"*)
792             case "${VERSION}" in
793                 *"LTS (Jammy Jellyfish)"*)
794                     IMAGE_VER_FILE="VPP_DEVICE_IMAGE_UBUNTU_JAMMY"
795                     VPP_VER_FILE="VPP_STABLE_VER_UBUNTU_JAMMY"
796                     PKG_SUFFIX="deb"
797                     ;;
798                 *)
799                     die "Unsupported Ubuntu version!"
800                     ;;
801             esac
802             ;;
803         *)
804             die "Unsupported distro or OS!"
805             ;;
806     esac
807
808     arch=$(uname -m) || {
809         die "Get CPU architecture failed."
810     }
811
812     case "${arch}" in
813         "aarch64")
814             IMAGE_VER_FILE="${IMAGE_VER_FILE}_ARM"
815             ;;
816         *)
817             ;;
818     esac
819 }
820
821
822 function select_tags () {
823
824     # Variables read:
825     # - WORKING_TOPOLOGY - Path to topology yaml file of the reserved testbed.
826     # - TEST_CODE - String affecting test selection, usually jenkins job name.
827     # - DUT - CSIT test/ subdirectory, set while processing tags.
828     # - TEST_TAG_STRING - String selecting tags, from gerrit comment.
829     #   Can be unset.
830     # - TOPOLOGIES_DIR - Path to existing directory with available tpologies.
831     # - BASH_FUNCTION_DIR - Directory with input files to process.
832     # Variables set:
833     # - TAGS - Array of processed tag boolean expressions.
834     # - SELECTION_MODE - Selection criteria [test, suite, include, exclude].
835
836     set -exuo pipefail
837
838     # NIC SELECTION
839     case "${TEST_CODE}" in
840         *"1n-aws"*)
841             start_pattern='^  SUT:'
842             ;;
843         *)
844             start_pattern='^  TG:'
845             ;;
846     esac
847     end_pattern='^ \? \?[A-Za-z0-9]\+:'
848     # Remove the sections from topology file
849     sed_command="/${start_pattern}/,/${end_pattern}/d"
850     # All topologies NICs
851     available=$(sed "${sed_command}" "${TOPOLOGIES_DIR}"/* \
852                 | grep -hoP "model: \K.*" | sort -u)
853     # Selected topology NICs
854     reserved=$(sed "${sed_command}" "${WORKING_TOPOLOGY}" \
855                | grep -hoP "model: \K.*" | sort -u)
856     # All topologies NICs - Selected topology NICs
857     exclude_nics=($(comm -13 <(echo "${reserved}") <(echo "${available}"))) || {
858         die "Computation of excluded NICs failed."
859     }
860
861     # Select default NIC tag.
862     case "${TEST_CODE}" in
863         *"3n-snr"*)
864             default_nic="nic_intel-e822cq"
865             ;;
866         *"3n-tsh"*)
867             default_nic="nic_intel-x520-da2"
868             ;;
869         *"3n-icx"* | *"2n-icx"*)
870             default_nic="nic_intel-xxv710"
871             ;;
872         *"3na-spr"*)
873             default_nic="nic_mellanox-cx7veat"
874             ;;
875         *"3nb-spr"*)
876             default_nic="nic_intel-e810cq"
877             ;;
878         *"2n-spr"*)
879             default_nic="nic_intel-e810cq"
880             ;;
881         *"2n-clx"* | *"2n-zn2"*)
882             default_nic="nic_intel-xxv710"
883             ;;
884         *"2n-tx2"* | *"3n-alt"*)
885             default_nic="nic_intel-xl710"
886             ;;
887         *"1n-aws"* | *"2n-aws"* | *"3n-aws"*)
888             default_nic="nic_amazon-nitro-50g"
889             ;;
890         *)
891             default_nic="nic_intel-x710"
892             ;;
893     esac
894
895     sed_nic_sub_cmd="sed s/\${default_nic}/${default_nic}/"
896     awk_nics_sub_cmd=""
897     awk_nics_sub_cmd+='gsub("xxv710","25ge2p1xxv710");'
898     awk_nics_sub_cmd+='gsub("x710","10ge2p1x710");'
899     awk_nics_sub_cmd+='gsub("xl710","40ge2p1xl710");'
900     awk_nics_sub_cmd+='gsub("x520-da2","10ge2p1x520");'
901     awk_nics_sub_cmd+='gsub("cx556a","100ge2p1cx556a");'
902     awk_nics_sub_cmd+='gsub("cx7veat","200ge2p1cx7veat");'
903     awk_nics_sub_cmd+='gsub("e810cq","100ge2p1e810cq");'
904     awk_nics_sub_cmd+='gsub("vic1227","10ge2p1vic1227");'
905     awk_nics_sub_cmd+='gsub("vic1385","40ge2p1vic1385");'
906     awk_nics_sub_cmd+='gsub("nitro-50g","50ge1p1ENA");'
907     awk_nics_sub_cmd+='if ($9 =="drv_avf") drv="avf-";'
908     awk_nics_sub_cmd+='else if ($9 =="drv_rdma_core") drv ="rdma-";'
909     awk_nics_sub_cmd+='else if ($9 =="drv_mlx5_core") drv ="mlx5-";'
910     awk_nics_sub_cmd+='else if ($9 =="drv_af_xdp") drv ="af-xdp-";'
911     awk_nics_sub_cmd+='else drv="";'
912     awk_nics_sub_cmd+='if ($1 =="-") cores="";'
913     awk_nics_sub_cmd+='else cores=$1;'
914     awk_nics_sub_cmd+='print "*"$7"-" drv $11"-"$5"."$3"-" cores "-" drv $11"-"$5'
915
916     # Tag file directory shorthand.
917     tfd="${JOB_SPECS_DIR}"
918     case "${TEST_CODE}" in
919         # Select specific performance tests based on jenkins job type variable.
920         *"device"* )
921             readarray -t test_tag_array <<< $(grep -v "#" \
922                 ${tfd}/vpp_device/${DUT}-${NODENESS}-${FLAVOR}.md |
923                 awk {"$awk_nics_sub_cmd"} || echo "devicetest") || die
924             SELECTION_MODE="--test"
925             ;;
926         *"hoststack-daily"* )
927             readarray -t test_tag_array <<< $(grep -v "#" \
928                 ${tfd}/hoststack_daily/${DUT}-${NODENESS}-${FLAVOR}.md |
929                 awk {"$awk_nics_sub_cmd"} || echo "perftest") || die
930             SELECTION_MODE="--test"
931             ;;
932         *"ndrpdr-weekly"* )
933             readarray -t test_tag_array <<< $(grep -v "#" \
934                 ${tfd}/ndrpdr_weekly/${DUT}-${NODENESS}-${FLAVOR}.md |
935                 awk {"$awk_nics_sub_cmd"} || echo "perftest") || die
936             SELECTION_MODE="--test"
937             ;;
938         *"mrr-daily"* )
939             readarray -t test_tag_array <<< $(grep -v "#" \
940                 ${tfd}/mrr_daily/${DUT}-${NODENESS}-${FLAVOR}.md |
941                 awk {"$awk_nics_sub_cmd"} || echo "perftest") || die
942             SELECTION_MODE="--test"
943             ;;
944         *"mrr-weekly"* )
945             readarray -t test_tag_array <<< $(grep -v "#" \
946                 ${tfd}/mrr_weekly/${DUT}-${NODENESS}-${FLAVOR}.md |
947                 awk {"$awk_nics_sub_cmd"} || echo "perftest") || die
948             SELECTION_MODE="--test"
949             ;;
950         *"report-iterative"* )
951             test_sets=(${TEST_TAG_STRING//:/ })
952             # Run only one test set per run
953             report_file=${test_sets[0]}.md
954             readarray -t test_tag_array <<< $(grep -v "#" \
955                 ${tfd}/report_iterative/${NODENESS}-${FLAVOR}/${report_file} |
956                 awk {"$awk_nics_sub_cmd"} || echo "perftest") || die
957             SELECTION_MODE="--test"
958             ;;
959         *"report-coverage"* )
960             test_sets=(${TEST_TAG_STRING//:/ })
961             # Run only one test set per run
962             report_file=${test_sets[0]}.md
963             readarray -t test_tag_array <<< $(grep -v "#" \
964                 ${tfd}/report_coverage/${NODENESS}-${FLAVOR}/${report_file} |
965                 awk {"$awk_nics_sub_cmd"} || echo "perftest") || die
966             SELECTION_MODE="--test"
967             ;;
968         * )
969             if [[ -z "${TEST_TAG_STRING-}" ]]; then
970                 # If nothing is specified, we will run pre-selected tests by
971                 # following tags.
972                 test_tag_array=("mrrAND${default_nic}AND1cAND64bANDethip4-ip4base"
973                                 "mrrAND${default_nic}AND1cAND78bANDethip6-ip6base"
974                                 "mrrAND${default_nic}AND1cAND64bANDeth-l2bdbasemaclrn"
975                                 "mrrAND${default_nic}AND1cAND64bANDeth-l2xcbase"
976                                 "!drv_af_xdp" "!drv_avf")
977             else
978                 # If trigger contains tags, split them into array.
979                 test_tag_array=(${TEST_TAG_STRING//:/ })
980             fi
981             SELECTION_MODE="--include"
982             ;;
983     esac
984
985     # Blacklisting certain tags per topology.
986     #
987     # Reasons for blacklisting:
988     # - ipsechw - Blacklisted on testbeds without crypto hardware accelerator.
989     case "${TEST_CODE}" in
990         *"1n-vbox"*)
991             test_tag_array+=("!avf")
992             test_tag_array+=("!vhost")
993             test_tag_array+=("!flow")
994             ;;
995         *"1n_tx2"*)
996             test_tag_array+=("!flow")
997             ;;
998         *"2n-clx"*)
999             test_tag_array+=("!ipsechw")
1000             ;;
1001         *"2n-icx"*)
1002             test_tag_array+=("!ipsechw")
1003             ;;
1004         *"2n-spr"*)
1005             test_tag_array+=("!ipsechw")
1006             ;;
1007         *"2n-tx2"*)
1008             test_tag_array+=("!ipsechw")
1009             ;;
1010         *"2n-zn2"*)
1011             test_tag_array+=("!ipsechw")
1012             ;;
1013         *"3n-alt"*)
1014             test_tag_array+=("!ipsechw")
1015             ;;
1016         *"3n-icx"*)
1017             test_tag_array+=("!ipsechw")
1018             test_tag_array+=("!3_node_double_link_topoANDnic_intel-xxv710")
1019             ;;
1020         *"3n-snr"*)
1021             ;;
1022         *"3na-spr"*)
1023             test_tag_array+=("!ipsechw")
1024             ;;
1025         *"3nb-spr"*)
1026             test_tag_array+=("!ipsechw")
1027             ;;
1028         *"3n-tsh"*)
1029             test_tag_array+=("!drv_avf")
1030             test_tag_array+=("!ipsechw")
1031             ;;
1032         *"1n-aws"* | *"2n-aws"* | *"3n-aws"*)
1033             test_tag_array+=("!ipsechw")
1034             ;;
1035     esac
1036
1037     # We will add excluded NICs.
1038     test_tag_array+=("${exclude_nics[@]/#/!NIC_}")
1039
1040     TAGS=()
1041     prefix=""
1042
1043     set +x
1044     if [[ "${TEST_CODE}" == "vpp-"* ]]; then
1045         if [[ "${TEST_CODE}" != *"device"* ]]; then
1046             # Automatic prefixing for VPP perf jobs to limit the NIC used and
1047             # traffic evaluation to MRR.
1048             if [[ "${TEST_TAG_STRING-}" == *"nic_"* ]]; then
1049                 prefix="${prefix}mrrAND"
1050             else
1051                 prefix="${prefix}mrrAND${default_nic}AND"
1052             fi
1053         fi
1054     fi
1055     for tag in "${test_tag_array[@]}"; do
1056         if [[ "${tag}" == "!"* ]]; then
1057             # Exclude tags are not prefixed.
1058             TAGS+=("${tag}")
1059         elif [[ "${tag}" == " "* || "${tag}" == *"perftest"* ]]; then
1060             # Badly formed tag expressions can trigger way too much tests.
1061             set -x
1062             warn "The following tag expression hints at bad trigger: ${tag}"
1063             warn "Possible cause: Multiple triggers in a single comment."
1064             die "Aborting to avoid triggering too many tests."
1065         elif [[ "${tag}" == *"OR"* ]]; then
1066             # If OR had higher precedence than AND, it would be useful here.
1067             # Some people think it does, thus triggering way too much tests.
1068             set -x
1069             warn "The following tag expression hints at bad trigger: ${tag}"
1070             warn "Operator OR has lower precedence than AND. Use space instead."
1071             die "Aborting to avoid triggering too many tests."
1072         elif [[ "${tag}" != "" && "${tag}" != "#"* ]]; then
1073             # Empty and comment lines are skipped.
1074             # Other lines are normal tags, they are to be prefixed.
1075             TAGS+=("${prefix}${tag}")
1076         fi
1077     done
1078     set -x
1079 }
1080
1081
1082 function select_topology () {
1083
1084     # Variables read:
1085     # - NODENESS - Node multiplicity of testbed, either "2n" or "3n".
1086     # - FLAVOR - Node flavor string, e.g. "clx" or "skx".
1087     # - CSIT_DIR - Path to existing root of local CSIT git repository.
1088     # - TOPOLOGIES_DIR - Path to existing directory with available topologies.
1089     # Variables set:
1090     # - TOPOLOGIES - Array of paths to suitable topology yaml files.
1091     # - TOPOLOGIES_TAGS - Tag expression selecting tests for the topology.
1092     # Functions called:
1093     # - die - Print to stderr and exit.
1094
1095     set -exuo pipefail
1096
1097     case_text="${NODENESS}_${FLAVOR}"
1098     case "${case_text}" in
1099         "1n_vbox")
1100             TOPOLOGIES=( "${TOPOLOGIES_DIR}"/*vpp_device*.template )
1101             TOPOLOGIES_TAGS="2_node_single_link_topo"
1102             ;;
1103         "1n_skx" | "1n_tx2")
1104             TOPOLOGIES=( "${TOPOLOGIES_DIR}"/*vpp_device*.template )
1105             TOPOLOGIES_TAGS="2_node_single_link_topo"
1106             ;;
1107         "2n_skx")
1108             TOPOLOGIES=( "${TOPOLOGIES_DIR}"/*2n_skx*.yaml )
1109             TOPOLOGIES_TAGS="2_node_*_link_topo"
1110             ;;
1111         "2n_zn2")
1112             TOPOLOGIES=( "${TOPOLOGIES_DIR}"/*2n_zn2*.yaml )
1113             TOPOLOGIES_TAGS="2_node_*_link_topo"
1114             ;;
1115         "3n_skx")
1116             TOPOLOGIES=( "${TOPOLOGIES_DIR}"/*3n_skx*.yaml )
1117             TOPOLOGIES_TAGS="3_node_*_link_topo"
1118             ;;
1119         "3n_icx")
1120             TOPOLOGIES=( "${TOPOLOGIES_DIR}"/*3n_icx*.yaml )
1121             TOPOLOGIES_TAGS="3_node_*_link_topo"
1122             ;;
1123         "3na_spr")
1124             TOPOLOGIES=( "${TOPOLOGIES_DIR}"/*3na_spr*.yaml )
1125             TOPOLOGIES_TAGS="3_node_*_link_topo"
1126             ;;
1127         "3nb_spr")
1128             TOPOLOGIES=( "${TOPOLOGIES_DIR}"/*3nb_spr*.yaml )
1129             TOPOLOGIES_TAGS="3_node_*_link_topo"
1130             ;;
1131         "2n_clx")
1132             TOPOLOGIES=( "${TOPOLOGIES_DIR}"/*2n_clx*.yaml )
1133             TOPOLOGIES_TAGS="2_node_*_link_topo"
1134             ;;
1135         "2n_icx")
1136             TOPOLOGIES=( "${TOPOLOGIES_DIR}"/*2n_icx*.yaml )
1137             TOPOLOGIES_TAGS="2_node_*_link_topo"
1138             ;;
1139         "2n_spr")
1140             TOPOLOGIES=( "${TOPOLOGIES_DIR}"/*2n_spr*.yaml )
1141             TOPOLOGIES_TAGS="2_node_*_link_topo"
1142             ;;
1143         "3n_snr")
1144             TOPOLOGIES=( "${TOPOLOGIES_DIR}"/*3n_snr*.yaml )
1145             TOPOLOGIES_TAGS="3_node_single_link_topo"
1146             ;;
1147         "3n_tsh")
1148             TOPOLOGIES=( "${TOPOLOGIES_DIR}"/*3n_tsh*.yaml )
1149             TOPOLOGIES_TAGS="3_node_single_link_topo"
1150             ;;
1151         "2n_tx2")
1152             TOPOLOGIES=( "${TOPOLOGIES_DIR}"/*2n_tx2*.yaml )
1153             TOPOLOGIES_TAGS="2_node_single_link_topo"
1154             ;;
1155         "3n_alt")
1156             TOPOLOGIES=( "${TOPOLOGIES_DIR}"/*3n_alt*.yaml )
1157             TOPOLOGIES_TAGS="3_node_single_link_topo"
1158             ;;
1159         "1n_aws")
1160             TOPOLOGIES=( "${TOPOLOGIES_DIR}"/*1n-aws*.yaml )
1161             TOPOLOGIES_TAGS="1_node_single_link_topo"
1162             ;;
1163         "2n_aws")
1164             TOPOLOGIES=( "${TOPOLOGIES_DIR}"/*2n-aws*.yaml )
1165             TOPOLOGIES_TAGS="2_node_single_link_topo"
1166             ;;
1167         "3n_aws")
1168             TOPOLOGIES=( "${TOPOLOGIES_DIR}"/*3n-aws*.yaml )
1169             TOPOLOGIES_TAGS="3_node_single_link_topo"
1170             ;;
1171         *)
1172             # No falling back to default, that should have been done
1173             # by the function which has set NODENESS and FLAVOR.
1174             die "Unknown specification: ${case_text}"
1175     esac
1176
1177     if [[ -z "${TOPOLOGIES-}" ]]; then
1178         die "No applicable topology found!"
1179     fi
1180 }
1181
1182
1183 function set_environment_variables () {
1184
1185     # Depending on testbed topology, overwrite defaults set in the
1186     # resources/libraries/python/Constants.py file
1187     #
1188     # Variables read:
1189     # - TEST_CODE - String affecting test selection, usually jenkins job name.
1190     # Variables set:
1191     # See specific cases
1192
1193     set -exuo pipefail
1194
1195     case "${TEST_CODE}" in
1196         *"1n-aws"* | *"2n-aws"* | *"3n-aws"*)
1197             # T-Rex 2.88+ workaround for ENA NICs.
1198             export TREX_RX_DESCRIPTORS_COUNT=1024
1199             export TREX_EXTRA_CMDLINE="--mbuf-factor 19"
1200             export TREX_CORE_COUNT=6
1201             # Settings to prevent duration stretching.
1202             export PERF_TRIAL_STL_DELAY=0.1
1203             ;;
1204         *"2n-zn2"*)
1205             # Maciek's workaround for Zen2 with lower amount of cores.
1206             export TREX_CORE_COUNT=14
1207     esac
1208 }
1209
1210
1211 function untrap_and_unreserve_testbed () {
1212
1213     # Use this as a trap function to ensure testbed does not remain reserved.
1214     # Perhaps call directly before script exit, to free testbed for other jobs.
1215     # This function is smart enough to avoid multiple unreservations (so safe).
1216     # Topo cleanup is executed (call it best practice), ignoring failures.
1217     #
1218     # Hardcoded values:
1219     # - default message to die with if testbed might remain reserved.
1220     # Arguments:
1221     # - ${1} - Message to die with if unreservation fails. Default hardcoded.
1222     # Variables read (by inner function):
1223     # - WORKING_TOPOLOGY - Path to topology yaml file of the reserved testbed.
1224     # - PYTHON_SCRIPTS_DIR - Path to directory holding Python scripts.
1225     # Variables set:
1226     # - TERRAFORM_MODULE_DIR - Terraform module directory.
1227     # - WORKING_TOPOLOGY - Set to empty string on successful unreservation.
1228     # Trap unregistered:
1229     # - EXIT - Failure to untrap is reported, but ignored otherwise.
1230     # Functions called:
1231     # - die - Print to stderr and exit.
1232     # - ansible_playbook - Perform an action using ansible, see ansible.sh
1233
1234     set -xo pipefail
1235     set +eu  # We do not want to exit early in a "teardown" function.
1236     trap - EXIT || echo "Trap deactivation failed, continuing anyway."
1237     wt="${WORKING_TOPOLOGY}"  # Just to avoid too long lines.
1238     if [[ -z "${wt-}" ]]; then
1239         set -eu
1240         warn "Testbed looks unreserved already. Trap removal failed before?"
1241     else
1242         ansible_playbook "cleanup" || true
1243         python3 "${PYTHON_SCRIPTS_DIR}/topo_reservation.py" -c -t "${wt}" || {
1244             die "${1:-FAILED TO UNRESERVE, FIX MANUALLY.}" 2
1245         }
1246         case "${TEST_CODE}" in
1247             *"1n-aws"* | *"2n-aws"* | *"3n-aws"*)
1248                 TERRAFORM_MODULE_DIR="terraform-aws-${NODENESS}-${FLAVOR}-c5n"
1249                 terraform_destroy || die "Failed to call terraform destroy."
1250                 ;;
1251             *)
1252                 ;;
1253         esac
1254         WORKING_TOPOLOGY=""
1255         set -eu
1256     fi
1257 }
1258
1259
1260 function warn () {
1261
1262     # Print the message to standard error.
1263     #
1264     # Arguments:
1265     # - ${@} - The text of the message.
1266
1267     set -exuo pipefail
1268
1269     echo "$@" >&2
1270 }