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