Add support for aarch64 container images
[csit.git] / resources / libraries / bash / function / common.sh
1 # Copyright (c) 2019 Cisco and/or its affiliates.
2 # Copyright (c) 2019 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
46     device_image="$(< ${CSIT_DIR}/${IMAGE_VER_FILE})"
47     case_text="${NODENESS}_${FLAVOR}"
48     case "${case_text}" in
49         "1n_skx" | "1n_tx2")
50             # We execute reservation over csit-shim-dcr (ssh) which runs sourced
51             # script's functions. Env variables are read from ssh output
52             # back to localhost for further processing.
53             hostname=$(grep search /etc/resolv.conf | cut -d' ' -f3) || die
54             ssh="ssh root@${hostname} -p 6022"
55             run="activate_wrapper ${NODENESS} ${FLAVOR} ${device_image}"
56             # backtics to avoid https://midnight-commander.org/ticket/2142
57             env_vars=`${ssh} "$(declare -f); ${run}"` || {
58                 die "Topology reservation via shim-dcr failed!"
59             }
60             set -a
61             source <(echo "$env_vars" | grep -v /usr/bin/docker) || {
62                 die "Source failed!"
63             }
64             set +a
65             ;;
66         "1n_vbox")
67             # We execute reservation on localhost. Sourced script automatially
68             # sets environment variables for further processing.
69             activate_wrapper "${NODENESS}" "${FLAVOR}" "${device_image}" || die
70             ;;
71         *)
72             die "Unknown specification: ${case_text}!"
73     esac
74
75     trap 'deactivate_docker_topology' EXIT || {
76          die "Trap attempt failed, please cleanup manually. Aborting!"
77     }
78
79     # Replace all variables in template with those in environment.
80     source <(echo 'cat <<EOF >topo.yml'; cat ${TOPOLOGIES[0]}; echo EOF;) || {
81         die "Topology file create failed!"
82     }
83
84     WORKING_TOPOLOGY="/tmp/topology.yaml"
85     mv topo.yml "${WORKING_TOPOLOGY}" || {
86         die "Topology move failed!"
87     }
88     cat ${WORKING_TOPOLOGY} | grep -v password || {
89         die "Topology read failed!"
90     }
91 }
92
93
94 function activate_virtualenv () {
95
96     # Update virtualenv pip package, delete and create virtualenv directory,
97     # activate the virtualenv, install requirements, set PYTHONPATH.
98
99     # Arguments:
100     # - ${1} - Path to existing directory for creating virtualenv in.
101     #          If missing or empty, ${CSIT_DIR} is used.
102     # - ${2} - Path to requirements file, ${CSIT_DIR}/requirements.txt if empty.
103     # Variables read:
104     # - CSIT_DIR - Path to existing root of local CSIT git repository.
105     # Variables exported:
106     # - PYTHONPATH - CSIT_DIR, as CSIT Python scripts usually need this.
107     # Functions called:
108     # - die - Print to stderr and exit.
109
110     set -exuo pipefail
111
112     root_path="${1-$CSIT_DIR}"
113     env_dir="${root_path}/env"
114     req_path=${2-$CSIT_DIR/requirements.txt}
115     rm -rf "${env_dir}" || die "Failed to clean previous virtualenv."
116     pip install --upgrade virtualenv || {
117         die "Virtualenv package install failed."
118     }
119     virtualenv "${env_dir}" || {
120         die "Virtualenv creation failed."
121     }
122     set +u
123     source "${env_dir}/bin/activate" || die "Virtualenv activation failed."
124     set -u
125     pip install --upgrade -r "${req_path}" || {
126         die "Requirements installation failed."
127     }
128     # Most CSIT Python scripts assume PYTHONPATH is set and exported.
129     export PYTHONPATH="${CSIT_DIR}" || die "Export failed."
130 }
131
132
133 function archive_tests () {
134
135     # Create .tar.xz of generated/tests for archiving.
136     # To be run after generate_tests, kept separate to offer more flexibility.
137
138     # Directory read:
139     # - ${GENERATED_DIR}/tests - Tree of executed suites to archive.
140     # File rewriten:
141     # - ${ARCHIVE_DIR}/tests.tar.xz - Archive of generated tests.
142
143     set -exuo pipefail
144
145     tar c "${GENERATED_DIR}/tests" | xz -9e > "${ARCHIVE_DIR}/tests.tar.xz" || {
146         die "Error creating archive of generated tests."
147     }
148 }
149
150
151 function check_download_dir () {
152
153     # Fail if there are no files visible in ${DOWNLOAD_DIR}.
154     #
155     # Variables read:
156     # - DOWNLOAD_DIR - Path to directory pybot takes the build to test from.
157     # Directories read:
158     # - ${DOWNLOAD_DIR} - Has to be non-empty to proceed.
159     # Functions called:
160     # - die - Print to stderr and exit.
161
162     set -exuo pipefail
163
164     if [[ ! "$(ls -A "${DOWNLOAD_DIR}")" ]]; then
165         die "No artifacts downloaded!"
166     fi
167 }
168
169
170 function cleanup_topo () {
171
172     # Variables read:
173     # - WORKING_TOPOLOGY - Path to topology yaml file of the reserved testbed.
174     # - PYTHON_SCRIPTS_DIR - Path to directory holding the reservation script.
175
176     set -exuo pipefail
177
178     python "${PYTHON_SCRIPTS_DIR}/topo_cleanup.py" -t "${WORKING_TOPOLOGY}"
179     # Not using "|| die" as some callers might want to ignore errors,
180     # e.g. in teardowns, such as unreserve.
181 }
182
183
184 function common_dirs () {
185
186     # Set global variables, create some directories (without touching content).
187
188     # Variables set:
189     # - BASH_FUNCTION_DIR - Path to existing directory this file is located in.
190     # - CSIT_DIR - Path to existing root of local CSIT git repository.
191     # - TOPOLOGIES_DIR - Path to existing directory with available tpologies.
192     # - RESOURCES_DIR - Path to existing CSIT subdirectory "resources".
193     # - TOOLS_DIR - Path to existing resources subdirectory "tools".
194     # - PYTHON_SCRIPTS_DIR - Path to existing tools subdirectory "scripts".
195     # - ARCHIVE_DIR - Path to created CSIT subdirectory "archive".
196     # - DOWNLOAD_DIR - Path to created CSIT subdirectory "download_dir".
197     # - GENERATED_DIR - Path to created CSIT subdirectory "generated".
198     # Directories created if not present:
199     # ARCHIVE_DIR, DOWNLOAD_DIR, GENERATED_DIR.
200     # Functions called:
201     # - die - Print to stderr and exit.
202
203     set -exuo pipefail
204
205     this_file=$(readlink -e "${BASH_SOURCE[0]}") || {
206         die "Some error during locating of this source file."
207     }
208     BASH_FUNCTION_DIR=$(dirname "${this_file}") || {
209         die "Some error during dirname call."
210     }
211     # Current working directory could be in a different repo, e.g. VPP.
212     pushd "${BASH_FUNCTION_DIR}" || die "Pushd failed"
213     relative_csit_dir=$(git rev-parse --show-toplevel) || {
214         die "Git rev-parse failed."
215     }
216     CSIT_DIR=$(readlink -e "${relative_csit_dir}") || die "Readlink failed."
217     popd || die "Popd failed."
218     TOPOLOGIES_DIR=$(readlink -e "${CSIT_DIR}/topologies/available") || {
219         die "Readlink failed."
220     }
221     RESOURCES_DIR=$(readlink -e "${CSIT_DIR}/resources") || {
222         die "Readlink failed."
223     }
224     TOOLS_DIR=$(readlink -e "${RESOURCES_DIR}/tools") || {
225         die "Readlink failed."
226     }
227     PYTHON_SCRIPTS_DIR=$(readlink -e "${TOOLS_DIR}/scripts") || {
228         die "Readlink failed."
229     }
230
231     ARCHIVE_DIR=$(readlink -f "${CSIT_DIR}/archive") || {
232         die "Readlink failed."
233     }
234     mkdir -p "${ARCHIVE_DIR}" || die "Mkdir failed."
235     DOWNLOAD_DIR=$(readlink -f "${CSIT_DIR}/download_dir") || {
236         die "Readlink failed."
237     }
238     mkdir -p "${DOWNLOAD_DIR}" || die "Mkdir failed."
239     GENERATED_DIR=$(readlink -f "${CSIT_DIR}/generated") || {
240         die "Readlink failed."
241     }
242     mkdir -p "${GENERATED_DIR}" || die "Mkdir failed."
243 }
244
245
246 function compose_pybot_arguments () {
247
248     # Variables read:
249     # - WORKING_TOPOLOGY - Path to topology yaml file of the reserved testbed.
250     # - DUT - CSIT test/ subdirectory, set while processing tags.
251     # - TAGS - Array variable holding selected tag boolean expressions.
252     # - TOPOLOGIES_TAGS - Tag boolean expression filtering tests for topology.
253     # - TEST_CODE - The test selection string from environment or argument.
254     # Variables set:
255     # - PYBOT_ARGS - String holding part of all arguments for pybot.
256     # - EXPANDED_TAGS - Array of strings pybot arguments compiled from tags.
257
258     set -exuo pipefail
259
260     # No explicit check needed with "set -u".
261     PYBOT_ARGS=("--loglevel" "TRACE")
262     PYBOT_ARGS+=("--variable" "TOPOLOGY_PATH:${WORKING_TOPOLOGY}")
263
264     case "${TEST_CODE}" in
265         *"device"*)
266             PYBOT_ARGS+=("--suite" "tests.${DUT}.device")
267             ;;
268         *"func"*)
269             PYBOT_ARGS+=("--suite" "tests.${DUT}.func")
270             ;;
271         *"perf"*)
272             PYBOT_ARGS+=("--suite" "tests.${DUT}.perf")
273             ;;
274         *)
275             die "Unknown specification: ${TEST_CODE}"
276     esac
277
278     EXPANDED_TAGS=()
279     for tag in "${TAGS[@]}"; do
280         if [[ ${tag} == "!"* ]]; then
281             EXPANDED_TAGS+=("--exclude" "${tag#$"!"}")
282         else
283             EXPANDED_TAGS+=("--include" "${TOPOLOGIES_TAGS}AND${tag}")
284         fi
285     done
286 }
287
288
289 function copy_archives () {
290
291     # Create additional archive if workspace variable is set.
292     # This way if script is running in jenkins all will be
293     # automatically archived to logs.fd.io.
294     #
295     # Variables read:
296     # - WORKSPACE - Jenkins workspace, copy only if the value is not empty.
297     #   Can be unset, then it speeds up manual testing.
298     # - ARCHIVE_DIR - Path to directory with content to be copied.
299     # Directories updated:
300     # - ${WORKSPACE}/archives/ - Created if does not exist.
301     #   Content of ${ARCHIVE_DIR}/ is copied here.
302     # Functions called:
303     # - die - Print to stderr and exit.
304
305     set -exuo pipefail
306
307     if [[ -n "${WORKSPACE-}" ]]; then
308         mkdir -p "${WORKSPACE}/archives/" || die "Archives dir create failed."
309         cp -rf "${ARCHIVE_DIR}"/* "${WORKSPACE}/archives" || die "Copy failed."
310     fi
311 }
312
313
314 function deactivate_docker_topology () {
315
316     # Deactivate virtual vpp-device topology by removing containers.
317     #
318     # Variables read:
319     # - NODENESS - Node multiplicity of desired testbed.
320     # - FLAVOR - Node flavor string, usually describing the processor.
321
322     set -exuo pipefail
323
324     case_text="${NODENESS}_${FLAVOR}"
325     case "${case_text}" in
326         "1n_skx" | "1n_tx2")
327             hostname=$(grep search /etc/resolv.conf | cut -d' ' -f3) || die
328             ssh="ssh root@${hostname} -p 6022"
329             env_vars=$(env | grep CSIT_ | tr '\n' ' ' ) || die
330             ${ssh} "$(declare -f); deactivate_wrapper ${env_vars}" || {
331                 die "Topology cleanup via shim-dcr failed!"
332             }
333             ;;
334         "1n_vbox")
335             enter_mutex || die
336             clean_environment || {
337                 die "Topology cleanup locally failed!"
338             }
339             exit_mutex || die
340             ;;
341         *)
342             die "Unknown specification: ${case_text}!"
343     esac
344 }
345
346
347 function die () {
348
349     # Print the message to standard error end exit with error code specified
350     # by the second argument.
351     #
352     # Hardcoded values:
353     # - The default error message.
354     # Arguments:
355     # - ${1} - The whole error message, be sure to quote. Optional
356     # - ${2} - the code to exit with, default: 1.
357
358     set -x
359     set +eu
360     warn "${1:-Unspecified run-time error occurred!}"
361     exit "${2:-1}"
362 }
363
364
365 function die_on_pybot_error () {
366
367     # Source this fragment if you want to abort on any failed test case.
368     #
369     # Variables read:
370     # - PYBOT_EXIT_STATUS - Set by a pybot running fragment.
371     # Functions called:
372     # - die - Print to stderr and exit.
373
374     set -exuo pipefail
375
376     if [[ "${PYBOT_EXIT_STATUS}" != "0" ]]; then
377         die "Test failures are present!" "${PYBOT_EXIT_STATUS}"
378     fi
379 }
380
381
382 function generate_tests () {
383
384     # Populate ${GENERATED_DIR}/tests based on ${CSIT_DIR}/tests/.
385     # Any previously existing content of ${GENERATED_DIR}/tests is wiped before.
386     # The generation is done by executing any *.py executable
387     # within any subdirectory after copying.
388
389     # This is a separate function, because this code is called
390     # both by autogen checker and entries calling run_pybot.
391
392     # Directories read:
393     # - ${CSIT_DIR}/tests - Used as templates for the generated tests.
394     # Directories replaced:
395     # - ${GENERATED_DIR}/tests - Overwritten by the generated tests.
396
397     set -exuo pipefail
398
399     rm -rf "${GENERATED_DIR}/tests" || die
400     cp -r "${CSIT_DIR}/tests" "${GENERATED_DIR}/tests" || die
401     cmd_line=("find" "${GENERATED_DIR}/tests" "-type" "f")
402     cmd_line+=("-executable" "-name" "*.py")
403     file_list=$("${cmd_line[@]}") || 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-skx"*)
448             NODENESS="2n"
449             FLAVOR="skx"
450             ;;
451         *"3n-skx"*)
452             NODENESS="3n"
453             FLAVOR="skx"
454             ;;
455         *"2n-dnv"*)
456             NODENESS="2n"
457             FLAVOR="dnv"
458             ;;
459         *"3n-dnv"*)
460             NODENESS="3n"
461             FLAVOR="dnv"
462             ;;
463         *"3n-tsh"*)
464             NODENESS="3n"
465             FLAVOR="tsh"
466             ;;
467         *)
468             # Fallback to 3-node Haswell by default (backward compatibility)
469             NODENESS="3n"
470             FLAVOR="hsw"
471             ;;
472     esac
473 }
474
475
476 function get_test_tag_string () {
477
478     # Variables read:
479     # - GERRIT_EVENT_TYPE - Event type set by gerrit, can be unset.
480     # - GERRIT_EVENT_COMMENT_TEXT - Comment text, read for "comment-added" type.
481     # - TEST_CODE - The test selection string from environment or argument.
482     # Variables set:
483     # - TEST_TAG_STRING - The string following trigger word in gerrit comment.
484     #   May be empty, not set on event types not adding comment.
485
486     # TODO: ci-management scripts no longer need to perform this.
487
488     set -exuo pipefail
489
490     trigger=""
491     if [[ "${GERRIT_EVENT_TYPE-}" == "comment-added" ]]; then
492         case "${TEST_CODE}" in
493             *"device"*)
494                 # On parsing error, ${trigger} stays empty.
495                 trigger="$(echo "${GERRIT_EVENT_COMMENT_TEXT}" \
496                     | grep -oE '(devicetest$|devicetest[[:space:]].+$)')" \
497                     || true
498                 # Set test tags as string.
499                 TEST_TAG_STRING="${trigger#$"devicetest"}"
500                 ;;
501             *"perf"*)
502                 # On parsing error, ${trigger} stays empty.
503                 comment="${GERRIT_EVENT_COMMENT_TEXT}"
504                 # As "perftest" can be followed by something, we substitute it.
505                 comment="${comment/perftest-2n/perftest}"
506                 comment="${comment/perftest-3n/perftest}"
507                 comment="${comment/perftest-hsw/perftest}"
508                 comment="${comment/perftest-skx/perftest}"
509                 comment="${comment/perftest-dnv/perftest}"
510                 comment="${comment/perftest-tsh/perftest}"
511                 tag_string="$(echo "${comment}" \
512                     | grep -oE '(perftest$|perftest[[:space:]].+$)' || true)"
513                 # Set test tags as string.
514                 TEST_TAG_STRING="${tag_string#$"perftest"}"
515                 ;;
516             *)
517                 die "Unknown specification: ${TEST_CODE}"
518         esac
519     fi
520 }
521
522
523 function reserve_and_cleanup_testbed () {
524
525     # Reserve physical testbed, perform cleanup, register trap to unreserve.
526     # When cleanup fails, remove from topologies and keep retrying
527     # until all topologies are removed.
528     #
529     # Variables read:
530     # - TOPOLOGIES - Array of paths to topology yaml to attempt reservation on.
531     # - PYTHON_SCRIPTS_DIR - Path to directory holding the reservation script.
532     # - BUILD_TAG - Any string suitable as filename, identifying
533     #   test run executing this function. May be unset.
534     # - BUILD_URL - Any string suitable as URL, identifying
535     #   test run executing this function. May be unset.
536     # Variables set:
537     # - TOPOLOGIES - Array of paths to topologies, with failed cleanups removed.
538     # - WORKING_TOPOLOGY - Path to topology yaml file of the reserved testbed.
539     # Functions called:
540     # - die - Print to stderr and exit.
541     # Traps registered:
542     # - EXIT - Calls cancel_all for ${WORKING_TOPOLOGY}.
543
544     set -exuo pipefail
545
546     while [[ ${TOPOLOGIES[@]} ]]; do
547         for topo in "${TOPOLOGIES[@]}"; do
548             set +e
549             scrpt="${PYTHON_SCRIPTS_DIR}/topo_reservation.py"
550             opts=("-t" "${topo}" "-r" "${BUILD_TAG:-Unknown}")
551             opts+=("-u" "${BUILD_URL:-Unknown}")
552             python "${scrpt}" "${opts[@]}"
553             result="$?"
554             set -e
555             if [[ "${result}" == "0" ]]; then
556                 # Trap unreservation before cleanup check,
557                 # so multiple jobs showing failed cleanup improve chances
558                 # of humans to notice and fix.
559                 WORKING_TOPOLOGY="${topo}"
560                 echo "Reserved: ${WORKING_TOPOLOGY}"
561                 trap "untrap_and_unreserve_testbed" EXIT || {
562                     message="TRAP ATTEMPT AND UNRESERVE FAILED, FIX MANUALLY."
563                     untrap_and_unreserve_testbed "${message}" || {
564                         die "Teardown should have died, not failed."
565                     }
566                     die "Trap attempt failed, unreserve succeeded. Aborting."
567                 }
568                 # Cleanup check.
569                 set +e
570                 cleanup_topo
571                 result="$?"
572                 set -e
573                 if [[ "${result}" == "0" ]]; then
574                     break
575                 fi
576                 warn "Testbed cleanup failed: ${topo}"
577                 untrap_and_unreserve_testbed "Fail of unreserve after cleanup."
578                 # WORKING_TOPOLOGY is now empty again.
579                 # Build new topology array.
580                 #   TOPOLOGIES=("${TOPOLOGIES[@]/$topo}")
581                 # does not really work, see:
582                 # https://stackoverflow.com/questions/16860877/remove-an-element-from-a-bash-array
583                 new_topologies=()
584                 for item in "${TOPOLOGIES[@]}"; do
585                     if [[ "${item}" != "${topo}" ]]; then
586                         new_topologies+=("${item}")
587                     fi
588                 done
589                 TOPOLOGIES=("${new_topologies[@]}")
590                 break
591             fi
592         done
593
594         if [[ -n "${WORKING_TOPOLOGY-}" ]]; then
595             # Exit the infinite while loop if we made a reservation.
596             break
597         fi
598
599         # Wait ~3minutes before next try.
600         sleep_time="$[ ( $RANDOM % 20 ) + 180 ]s" || {
601             die "Sleep time calculation failed."
602         }
603         echo "Sleeping ${sleep_time}"
604         sleep "${sleep_time}" || die "Sleep failed."
605     done
606     if [[ ${TOPOLOGIES[@]} ]]; then
607         echo "Reservation and cleanup successful."
608     else
609         die "Run out of operational testbeds!"
610     fi
611 }
612
613
614 function run_pybot () {
615
616     # Run pybot with options based on input variables. Create output_info.xml
617     #
618     # Variables read:
619     # - CSIT_DIR - Path to existing root of local CSIT git repository.
620     # - ARCHIVE_DIR - Path to store robot result files in.
621     # - PYBOT_ARGS, EXPANDED_TAGS - See compose_pybot_arguments.sh
622     # - GENERATED_DIR - Tests are assumed to be generated under there.
623     # Variables set:
624     # - PYBOT_EXIT_STATUS - Exit status of most recent pybot invocation.
625     # Functions called:
626     # - die - Print to stderr and exit.
627
628     set -exuo pipefail
629
630     all_options=("--outputdir" "${ARCHIVE_DIR}" "${PYBOT_ARGS[@]}")
631     all_options+=("--noncritical" "EXPECTED_FAILING")
632     all_options+=("${EXPANDED_TAGS[@]}")
633
634     pushd "${CSIT_DIR}" || die "Change directory operation failed."
635     set +e
636     pybot "${all_options[@]}" "${GENERATED_DIR}/tests/"
637     PYBOT_EXIT_STATUS="$?"
638     set -e
639
640     # Generate INFO level output_info.xml for post-processing.
641     all_options=("--loglevel" "INFO")
642     all_options+=("--log" "none")
643     all_options+=("--report" "none")
644     all_options+=("--output" "${ARCHIVE_DIR}/output_info.xml")
645     all_options+=("${ARCHIVE_DIR}/output.xml")
646     rebot "${all_options[@]}" || true
647     popd || die "Change directory operation failed."
648 }
649
650
651 function select_arch_os () {
652
653     # Populate variables related to local operating system.
654     #
655     # Also install any missing prerequisities CSIT tests need.
656     # TODO: Move the installation to a separate function?
657     #
658     # Variables set:
659     # - VPP_VER_FILE - Name of File in CSIT dir containing vpp stable version.
660     # - IMAGE_VER_FILE - Name of File in CSIT dir containing the image name.
661     # - PKG_SUFFIX - Suffix of OS package file name, "rpm" or "deb."
662
663     set -exuo pipefail
664
665     os_id=$(grep '^ID=' /etc/os-release | cut -f2- -d= | sed -e 's/\"//g') || {
666         die "Get OS release failed."
667     }
668
669     case "${os_id}" in
670         "ubuntu"*)
671             IMAGE_VER_FILE="VPP_DEVICE_IMAGE_UBUNTU"
672             VPP_VER_FILE="VPP_STABLE_VER_UBUNTU_BIONIC"
673             PKG_SUFFIX="deb"
674             ;;
675         "centos"*)
676             IMAGE_VER_FILE="VPP_DEVICE_IMAGE_CENTOS"
677             VPP_VER_FILE="VPP_STABLE_VER_CENTOS"
678             PKG_SUFFIX="rpm"
679             ;;
680         *)
681             die "Unable to identify distro or os from ${os_id}"
682             ;;
683     esac
684
685     arch=$(uname -m) || {
686         die "Get CPU architecture failed."
687     }
688
689     case "${arch}" in
690         "aarch64")
691             IMAGE_VER_FILE="${IMAGE_VER_FILE}_ARM"
692             ;;
693         *)
694             ;;
695     esac
696 }
697
698
699 function select_tags () {
700
701     # Variables read:
702     # - WORKING_TOPOLOGY - Path to topology yaml file of the reserved testbed.
703     # - TEST_CODE - String affecting test selection, usually jenkins job name.
704     # - TEST_TAG_STRING - String selecting tags, from gerrit comment.
705     #   Can be unset.
706     # - TOPOLOGIES_DIR - Path to existing directory with available tpologies.
707     # - BASH_FUNCTION_DIR - Directory with input files to process.
708     # Variables set:
709     # - TAGS - Array of processed tag boolean expressions.
710
711     set -exuo pipefail
712
713     # NIC SELECTION
714     start_pattern='^  TG:'
715     end_pattern='^ \? \?[A-Za-z0-9]\+:'
716     # Remove the TG section from topology file
717     sed_command="/${start_pattern}/,/${end_pattern}/d"
718     # All topologies DUT NICs
719     available=$(sed "${sed_command}" "${TOPOLOGIES_DIR}"/* \
720                 | grep -hoP "model: \K.*" | sort -u)
721     # Selected topology DUT NICs
722     reserved=$(sed "${sed_command}" "${WORKING_TOPOLOGY}" \
723                | grep -hoP "model: \K.*" | sort -u)
724     # All topologies DUT NICs - Selected topology DUT NICs
725     exclude_nics=($(comm -13 <(echo "${reserved}") <(echo "${available}"))) || {
726         die "Computation of excluded NICs failed."
727     }
728
729     # Select default NIC tag.
730     case "${TEST_CODE}" in
731         *"3n-dnv"* | *"2n-dnv"*)
732             default_nic="nic_intel-x553"
733             ;;
734         *"3n-tsh"*)
735             default_nic="nic_intel-x520-da2"
736             ;;
737         *)
738             default_nic="nic_intel-x710"
739             ;;
740     esac
741
742     sed_nic_sub_cmd="sed s/\${default_nic}/${default_nic}/"
743     # Tag file directory shorthand.
744     tfd="${BASH_FUNCTION_DIR}"
745     case "${TEST_CODE}" in
746         # Select specific performance tests based on jenkins job type variable.
747         *"ndrpdr-weekly"* )
748             readarray -t test_tag_array < "${tfd}/mlr-weekly.txt" || die
749             ;;
750         *"mrr-daily"* )
751             readarray -t test_tag_array <<< $(${sed_nic_sub_cmd} \
752                 ${tfd}/mrr-daily-${FLAVOR}.txt) || die
753             ;;
754         *"mrr-weekly"* )
755             readarray -t test_tag_array < "${tfd}/mrr-weekly.txt" || die
756             ;;
757         * )
758             if [[ -z "${TEST_TAG_STRING-}" ]]; then
759                 # If nothing is specified, we will run pre-selected tests by
760                 # following tags.
761                 test_tag_array=("mrrAND${default_nic}AND1cAND64bANDip4base"
762                                 "mrrAND${default_nic}AND1cAND78bANDip6base"
763                                 "mrrAND${default_nic}AND1cAND64bANDl2bdbase"
764                                 "mrrAND${default_nic}AND1cAND64bANDl2xcbase"
765                                 "!dot1q" "!drv_avf")
766             else
767                 # If trigger contains tags, split them into array.
768                 test_tag_array=(${TEST_TAG_STRING//:/ })
769             fi
770             ;;
771     esac
772
773     # Blacklisting certain tags per topology.
774     #
775     # Reasons for blacklisting:
776     # - ipsechw - Blacklisted on testbeds without crypto hardware accelerator.
777     # TODO: Add missing reasons here (if general) or where used (if specific).
778     case "${TEST_CODE}" in
779         *"2n-skx"*)
780             test_tag_array+=("!ipsechw")
781             ;;
782         *"3n-skx"*)
783             test_tag_array+=("!ipsechw")
784             # Not enough nic_intel-xxv710 to support double link tests.
785             test_tag_array+=("!3_node_double_link_topoANDnic_intel-xxv710")
786             ;;
787         *"2n-dnv"*)
788             test_tag_array+=("!ipsechw")
789             test_tag_array+=("!memif")
790             test_tag_array+=("!srv6_proxy")
791             test_tag_array+=("!vhost")
792             test_tag_array+=("!vts")
793             test_tag_array+=("!drv_avf")
794             ;;
795         *"3n-dnv"*)
796             test_tag_array+=("!memif")
797             test_tag_array+=("!srv6_proxy")
798             test_tag_array+=("!vhost")
799             test_tag_array+=("!vts")
800             test_tag_array+=("!drv_avf")
801             ;;
802         *"3n-tsh"*)
803             test_tag_array+=("!ipsechw")
804             test_tag_array+=("!memif")
805             test_tag_array+=("!srv6_proxy")
806             test_tag_array+=("!vhost")
807             test_tag_array+=("!vts")
808             ;;
809         *"3n-hsw"*)
810             # TODO: Introduce NOIOMMU version of AVF tests.
811             # TODO: Make (both) AVF tests work on Haswell,
812             # or document why (some of) it is not possible.
813             # https://github.com/FDio/vpp/blob/master/src/plugins/avf/README.md
814             test_tag_array+=("!drv_avf")
815             # All cards have access to QAT. But only one card (xl710)
816             # resides in same NUMA as QAT. Other cards must go over QPI
817             # which we do not want to even run.
818             test_tag_array+=("!ipsechwNOTnic_intel-xl710")
819             ;;
820         *)
821             # Default to 3n-hsw due to compatibility.
822             test_tag_array+=("!drv_avf")
823             test_tag_array+=("!ipsechwNOTnic_intel-xl710")
824             ;;
825     esac
826
827     # We will add excluded NICs.
828     test_tag_array+=("${exclude_nics[@]/#/!NIC_}")
829
830     TAGS=()
831
832     # We will prefix with perftest to prevent running other tests
833     # (e.g. Functional).
834     prefix="perftestAND"
835     set +x
836     if [[ "${TEST_CODE}" == "vpp-"* ]]; then
837         # Automatic prefixing for VPP jobs to limit the NIC used and
838         # traffic evaluation to MRR.
839         if [[ "${TEST_TAG_STRING-}" == *"nic_"* ]]; then
840             prefix="${prefix}mrrAND"
841         else
842             prefix="${prefix}mrrAND${default_nic}AND"
843         fi
844     fi
845     for tag in "${test_tag_array[@]}"; do
846         if [[ "${tag}" == "!"* ]]; then
847             # Exclude tags are not prefixed.
848             TAGS+=("${tag}")
849         elif [[ "${tag}" != "" && "${tag}" != "#"* ]]; then
850             # Empty and comment lines are skipped.
851             # Other lines are normal tags, they are to be prefixed.
852             TAGS+=("${prefix}${tag}")
853         fi
854     done
855     set -x
856 }
857
858
859 function select_topology () {
860
861     # Variables read:
862     # - NODENESS - Node multiplicity of testbed, either "2n" or "3n".
863     # - FLAVOR - Node flavor string, currently either "hsw" or "skx".
864     # - CSIT_DIR - Path to existing root of local CSIT git repository.
865     # - TOPOLOGIES_DIR - Path to existing directory with available topologies.
866     # Variables set:
867     # - TOPOLOGIES - Array of paths to suitable topology yaml files.
868     # - TOPOLOGIES_TAGS - Tag expression selecting tests for the topology.
869     # Functions called:
870     # - die - Print to stderr and exit.
871
872     set -exuo pipefail
873
874     case_text="${NODENESS}_${FLAVOR}"
875     case "${case_text}" in
876         # TODO: Move tags to "# Blacklisting certain tags per topology" section.
877         # TODO: Double link availability depends on NIC used.
878         "1n_vbox")
879             TOPOLOGIES=( "${TOPOLOGIES_DIR}"/*vpp_device*.template )
880             TOPOLOGIES_TAGS="2_node_single_link_topo"
881             ;;
882         "1n_skx" | "1n_tx2")
883             TOPOLOGIES=( "${TOPOLOGIES_DIR}"/*vpp_device*.template )
884             TOPOLOGIES_TAGS="2_node_single_link_topo"
885             ;;
886         "2n_skx")
887             TOPOLOGIES=( "${TOPOLOGIES_DIR}"/*2n_skx*.yaml )
888             TOPOLOGIES_TAGS="2_node_*_link_topo"
889             ;;
890         "3n_skx")
891             TOPOLOGIES=( "${TOPOLOGIES_DIR}"/*3n_skx*.yaml )
892             TOPOLOGIES_TAGS="3_node_*_link_topo"
893             ;;
894         "2n_dnv")
895             TOPOLOGIES=( "${TOPOLOGIES_DIR}"/*2n_dnv*.yaml )
896             TOPOLOGIES_TAGS="2_node_single_link_topo"
897             ;;
898         "3n_dnv")
899             TOPOLOGIES=( "${TOPOLOGIES_DIR}"/*3n_dnv*.yaml )
900             TOPOLOGIES_TAGS="3_node_single_link_topo"
901             ;;
902         "3n_hsw")
903             TOPOLOGIES=( "${TOPOLOGIES_DIR}"/*3n_hsw*.yaml )
904             TOPOLOGIES_TAGS="3_node_single_link_topo"
905             ;;
906         "3n_tsh")
907             TOPOLOGIES=( "${TOPOLOGIES_DIR}"/*3n_tsh*.yaml )
908             TOPOLOGIES_TAGS="3_node_*_link_topo"
909             ;;
910         *)
911             # No falling back to 3n_hsw default, that should have been done
912             # by the function which has set NODENESS and FLAVOR.
913             die "Unknown specification: ${case_text}"
914     esac
915
916     if [[ -z "${TOPOLOGIES-}" ]]; then
917         die "No applicable topology found!"
918     fi
919 }
920
921
922 function select_vpp_device_tags () {
923
924     # Variables read:
925     # - TEST_CODE - String affecting test selection, usually jenkins job name.
926     # - TEST_TAG_STRING - String selecting tags, from gerrit comment.
927     #   Can be unset.
928     # Variables set:
929     # - TAGS - Array of processed tag boolean expressions.
930
931     set -exuo pipefail
932
933     case "${TEST_CODE}" in
934         # Select specific performance tests based on jenkins job type variable.
935         * )
936             if [[ -z "${TEST_TAG_STRING-}" ]]; then
937                 # If nothing is specified, we will run pre-selected tests by
938                 # following tags. Items of array will be concatenated by OR
939                 # in Robot Framework.
940                 test_tag_array=()
941             else
942                 # If trigger contains tags, split them into array.
943                 test_tag_array=(${TEST_TAG_STRING//:/ })
944             fi
945             ;;
946     esac
947
948     TAGS=()
949
950     # We will prefix with devicetest to prevent running other tests
951     # (e.g. Functional).
952     prefix="devicetestAND"
953     if [[ "${TEST_CODE}" == "vpp-"* ]]; then
954         # Automatic prefixing for VPP jobs to limit testing.
955         prefix="${prefix}"
956     fi
957     for tag in "${test_tag_array[@]}"; do
958         if [[ ${tag} == "!"* ]]; then
959             # Exclude tags are not prefixed.
960             TAGS+=("${tag}")
961         else
962             TAGS+=("${prefix}${tag}")
963         fi
964     done
965 }
966
967 function untrap_and_unreserve_testbed () {
968
969     # Use this as a trap function to ensure testbed does not remain reserved.
970     # Perhaps call directly before script exit, to free testbed for other jobs.
971     # This function is smart enough to avoid multiple unreservations (so safe).
972     # Topo cleanup is executed (call it best practice), ignoring failures.
973     #
974     # Hardcoded values:
975     # - default message to die with if testbed might remain reserved.
976     # Arguments:
977     # - ${1} - Message to die with if unreservation fails. Default hardcoded.
978     # Variables read (by inner function):
979     # - WORKING_TOPOLOGY - Path to topology yaml file of the reserved testbed.
980     # - PYTHON_SCRIPTS_DIR - Path to directory holding Python scripts.
981     # Variables written:
982     # - WORKING_TOPOLOGY - Set to empty string on successful unreservation.
983     # Trap unregistered:
984     # - EXIT - Failure to untrap is reported, but ignored otherwise.
985     # Functions called:
986     # - die - Print to stderr and exit.
987
988     set -xo pipefail
989     set +eu  # We do not want to exit early in a "teardown" function.
990     trap - EXIT || echo "Trap deactivation failed, continuing anyway."
991     wt="${WORKING_TOPOLOGY}"  # Just to avoid too long lines.
992     if [[ -z "${wt-}" ]]; then
993         set -eu
994         warn "Testbed looks unreserved already. Trap removal failed before?"
995     else
996         cleanup_topo || true
997         python "${PYTHON_SCRIPTS_DIR}/topo_reservation.py" -c -t "${wt}" || {
998             die "${1:-FAILED TO UNRESERVE, FIX MANUALLY.}" 2
999         }
1000         WORKING_TOPOLOGY=""
1001         set -eu
1002     fi
1003 }
1004
1005
1006 function warn () {
1007
1008     # Print the message to standard error.
1009     #
1010     # Arguments:
1011     # - ${@} - The text of the message.
1012
1013     set -exuo pipefail
1014
1015     echo "$@" >&2
1016 }