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