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