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