Revert "Avoid ci-management archiving files twice"
[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_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}"
682             ;;
683     esac
684 }
685
686
687 function select_tags () {
688
689     # Variables read:
690     # - WORKING_TOPOLOGY - Path to topology yaml file of the reserved testbed.
691     # - TEST_CODE - String affecting test selection, usually jenkins job name.
692     # - TEST_TAG_STRING - String selecting tags, from gerrit comment.
693     #   Can be unset.
694     # - TOPOLOGIES_DIR - Path to existing directory with available tpologies.
695     # - BASH_FUNCTION_DIR - Directory with input files to process.
696     # Variables set:
697     # - TAGS - Array of processed tag boolean expressions.
698
699     set -exuo pipefail
700
701     # NIC SELECTION
702     start_pattern='^  TG:'
703     end_pattern='^ \? \?[A-Za-z0-9]\+:'
704     # Remove the TG section from topology file
705     sed_command="/${start_pattern}/,/${end_pattern}/d"
706     # All topologies DUT NICs
707     available=$(sed "${sed_command}" "${TOPOLOGIES_DIR}"/* \
708                 | grep -hoP "model: \K.*" | sort -u)
709     # Selected topology DUT NICs
710     reserved=$(sed "${sed_command}" "${WORKING_TOPOLOGY}" \
711                | grep -hoP "model: \K.*" | sort -u)
712     # All topologies DUT NICs - Selected topology DUT NICs
713     exclude_nics=($(comm -13 <(echo "${reserved}") <(echo "${available}"))) || {
714         die "Computation of excluded NICs failed."
715     }
716
717     # Select default NIC tag.
718     case "${TEST_CODE}" in
719         *"3n-dnv"* | *"2n-dnv"*)
720             default_nic="nic_intel-x553"
721             ;;
722         *"3n-tsh"*)
723             default_nic="nic_intel-x520-da2"
724             ;;
725         *)
726             default_nic="nic_intel-x710"
727             ;;
728     esac
729
730     # Tag file directory shorthand.
731     tfd="${BASH_FUNCTION_DIR}"
732     case "${TEST_CODE}" in
733         # Select specific performance tests based on jenkins job type variable.
734         *"ndrpdr-weekly"* )
735             readarray -t test_tag_array < "${tfd}/mlr-weekly.txt" || die
736             ;;
737         *"mrr-daily"* )
738             readarray -t test_tag_array < \
739                 "${tfd}/mrr-daily-${FLAVOR}.txt" || die
740             ;;
741         *"mrr-weekly"* )
742             readarray -t test_tag_array < "${tfd}/mrr-weekly.txt" || die
743             ;;
744         * )
745             if [[ -z "${TEST_TAG_STRING-}" ]]; then
746                 # If nothing is specified, we will run pre-selected tests by
747                 # following tags.
748                 test_tag_array=("mrrAND${default_nic}AND1cAND64bANDip4base"
749                                 "mrrAND${default_nic}AND1cAND78bANDip6base"
750                                 "mrrAND${default_nic}AND1cAND64bANDl2bdbase"
751                                 "mrrAND${default_nic}AND1cAND64bANDl2xcbase"
752                                 "!dot1q" "!drv_avf")
753             else
754                 # If trigger contains tags, split them into array.
755                 test_tag_array=(${TEST_TAG_STRING//:/ })
756             fi
757             ;;
758     esac
759
760     # Blacklisting certain tags per topology.
761     #
762     # Reasons for blacklisting:
763     # - ipsechw - Blacklisted on testbeds without crypto hardware accelerator.
764     # TODO: Add missing reasons here (if general) or where used (if specific).
765     case "${TEST_CODE}" in
766         *"2n-skx"*)
767             test_tag_array+=("!ipsechw")
768             ;;
769         *"3n-skx"*)
770             test_tag_array+=("!ipsechw")
771             # Not enough nic_intel-xxv710 to support double link tests.
772             test_tag_array+=("!3_node_double_link_topoANDnic_intel-xxv710")
773             ;;
774         *"2n-dnv"*)
775             test_tag_array+=("!ipsechw")
776             test_tag_array+=("!memif")
777             test_tag_array+=("!srv6_proxy")
778             test_tag_array+=("!vhost")
779             test_tag_array+=("!vts")
780             test_tag_array+=("!drv_avf")
781             ;;
782         *"3n-dnv"*)
783             test_tag_array+=("!memif")
784             test_tag_array+=("!srv6_proxy")
785             test_tag_array+=("!vhost")
786             test_tag_array+=("!vts")
787             test_tag_array+=("!drv_avf")
788             ;;
789         *"3n-tsh"*)
790             test_tag_array+=("!ipsechw")
791             test_tag_array+=("!memif")
792             test_tag_array+=("!srv6_proxy")
793             test_tag_array+=("!vhost")
794             test_tag_array+=("!vts")
795             ;;
796         *"3n-hsw"*)
797             # TODO: Introduce NOIOMMU version of AVF tests.
798             # TODO: Make (both) AVF tests work on Haswell,
799             # or document why (some of) it is not possible.
800             # https://github.com/FDio/vpp/blob/master/src/plugins/avf/README.md
801             test_tag_array+=("!drv_avf")
802             # All cards have access to QAT. But only one card (xl710)
803             # resides in same NUMA as QAT. Other cards must go over QPI
804             # which we do not want to even run.
805             test_tag_array+=("!ipsechwNOTnic_intel-xl710")
806             ;;
807         *)
808             # Default to 3n-hsw due to compatibility.
809             test_tag_array+=("!drv_avf")
810             test_tag_array+=("!ipsechwNOTnic_intel-xl710")
811             ;;
812     esac
813
814     # We will add excluded NICs.
815     test_tag_array+=("${exclude_nics[@]/#/!NIC_}")
816
817     TAGS=()
818
819     # We will prefix with perftest to prevent running other tests
820     # (e.g. Functional).
821     prefix="perftestAND"
822     set +x
823     if [[ "${TEST_CODE}" == "vpp-"* ]]; then
824         # Automatic prefixing for VPP jobs to limit the NIC used and
825         # traffic evaluation to MRR.
826         if [[ "${TEST_TAG_STRING-}" == *"nic_"* ]]; then
827             prefix="${prefix}mrrAND"
828         else
829             prefix="${prefix}mrrAND${default_nic}AND"
830         fi
831     fi
832     for tag in "${test_tag_array[@]}"; do
833         if [[ "${tag}" == "!"* ]]; then
834             # Exclude tags are not prefixed.
835             TAGS+=("${tag}")
836         elif [[ "${tag}" != "" && "${tag}" != "#"* ]]; then
837             # Empty and comment lines are skipped.
838             # Other lines are normal tags, they are to be prefixed.
839             TAGS+=("${prefix}${tag}")
840         fi
841     done
842     set -x
843 }
844
845
846 function select_topology () {
847
848     # Variables read:
849     # - NODENESS - Node multiplicity of testbed, either "2n" or "3n".
850     # - FLAVOR - Node flavor string, currently either "hsw" or "skx".
851     # - CSIT_DIR - Path to existing root of local CSIT git repository.
852     # - TOPOLOGIES_DIR - Path to existing directory with available topologies.
853     # Variables set:
854     # - TOPOLOGIES - Array of paths to suitable topology yaml files.
855     # - TOPOLOGIES_TAGS - Tag expression selecting tests for the topology.
856     # Functions called:
857     # - die - Print to stderr and exit.
858
859     set -exuo pipefail
860
861     case_text="${NODENESS}_${FLAVOR}"
862     case "${case_text}" in
863         # TODO: Move tags to "# Blacklisting certain tags per topology" section.
864         # TODO: Double link availability depends on NIC used.
865         "1n_vbox")
866             TOPOLOGIES=( "${TOPOLOGIES_DIR}"/*vpp_device*.template )
867             TOPOLOGIES_TAGS="2_node_single_link_topo"
868             ;;
869         "1n_skx" | "1n_tx2")
870             TOPOLOGIES=( "${TOPOLOGIES_DIR}"/*vpp_device*.template )
871             TOPOLOGIES_TAGS="2_node_single_link_topo"
872             ;;
873         "2n_skx")
874             TOPOLOGIES=( "${TOPOLOGIES_DIR}"/*2n_skx*.yaml )
875             TOPOLOGIES_TAGS="2_node_*_link_topo"
876             ;;
877         "3n_skx")
878             TOPOLOGIES=( "${TOPOLOGIES_DIR}"/*3n_skx*.yaml )
879             TOPOLOGIES_TAGS="3_node_*_link_topo"
880             ;;
881         "2n_dnv")
882             TOPOLOGIES=( "${TOPOLOGIES_DIR}"/*2n_dnv*.yaml )
883             TOPOLOGIES_TAGS="2_node_single_link_topo"
884             ;;
885         "3n_dnv")
886             TOPOLOGIES=( "${TOPOLOGIES_DIR}"/*3n_dnv*.yaml )
887             TOPOLOGIES_TAGS="3_node_single_link_topo"
888             ;;
889         "3n_hsw")
890             TOPOLOGIES=( "${TOPOLOGIES_DIR}"/*3n_hsw*.yaml )
891             TOPOLOGIES_TAGS="3_node_single_link_topo"
892             ;;
893         "3n_tsh")
894             TOPOLOGIES=( "${TOPOLOGIES_DIR}"/*3n_tsh*.yaml )
895             TOPOLOGIES_TAGS="3_node_*_link_topo"
896             ;;
897         *)
898             # No falling back to 3n_hsw default, that should have been done
899             # by the function which has set NODENESS and FLAVOR.
900             die "Unknown specification: ${case_text}"
901     esac
902
903     if [[ -z "${TOPOLOGIES-}" ]]; then
904         die "No applicable topology found!"
905     fi
906 }
907
908
909 function select_vpp_device_tags () {
910
911     # Variables read:
912     # - TEST_CODE - String affecting test selection, usually jenkins job name.
913     # - TEST_TAG_STRING - String selecting tags, from gerrit comment.
914     #   Can be unset.
915     # Variables set:
916     # - TAGS - Array of processed tag boolean expressions.
917
918     set -exuo pipefail
919
920     case "${TEST_CODE}" in
921         # Select specific performance tests based on jenkins job type variable.
922         * )
923             if [[ -z "${TEST_TAG_STRING-}" ]]; then
924                 # If nothing is specified, we will run pre-selected tests by
925                 # following tags. Items of array will be concatenated by OR
926                 # in Robot Framework.
927                 test_tag_array=()
928             else
929                 # If trigger contains tags, split them into array.
930                 test_tag_array=(${TEST_TAG_STRING//:/ })
931             fi
932             ;;
933     esac
934
935     TAGS=()
936
937     # We will prefix with devicetest to prevent running other tests
938     # (e.g. Functional).
939     prefix="devicetestAND"
940     if [[ "${TEST_CODE}" == "vpp-"* ]]; then
941         # Automatic prefixing for VPP jobs to limit testing.
942         prefix="${prefix}"
943     fi
944     for tag in "${test_tag_array[@]}"; do
945         if [[ ${tag} == "!"* ]]; then
946             # Exclude tags are not prefixed.
947             TAGS+=("${tag}")
948         else
949             TAGS+=("${prefix}${tag}")
950         fi
951     done
952 }
953
954 function untrap_and_unreserve_testbed () {
955
956     # Use this as a trap function to ensure testbed does not remain reserved.
957     # Perhaps call directly before script exit, to free testbed for other jobs.
958     # This function is smart enough to avoid multiple unreservations (so safe).
959     # Topo cleanup is executed (call it best practice), ignoring failures.
960     #
961     # Hardcoded values:
962     # - default message to die with if testbed might remain reserved.
963     # Arguments:
964     # - ${1} - Message to die with if unreservation fails. Default hardcoded.
965     # Variables read (by inner function):
966     # - WORKING_TOPOLOGY - Path to topology yaml file of the reserved testbed.
967     # - PYTHON_SCRIPTS_DIR - Path to directory holding Python scripts.
968     # Variables written:
969     # - WORKING_TOPOLOGY - Set to empty string on successful unreservation.
970     # Trap unregistered:
971     # - EXIT - Failure to untrap is reported, but ignored otherwise.
972     # Functions called:
973     # - die - Print to stderr and exit.
974
975     set -xo pipefail
976     set +eu  # We do not want to exit early in a "teardown" function.
977     trap - EXIT || echo "Trap deactivation failed, continuing anyway."
978     wt="${WORKING_TOPOLOGY}"  # Just to avoid too long lines.
979     if [[ -z "${wt-}" ]]; then
980         set -eu
981         warn "Testbed looks unreserved already. Trap removal failed before?"
982     else
983         cleanup_topo || true
984         python "${PYTHON_SCRIPTS_DIR}/topo_reservation.py" -c -t "${wt}" || {
985             die "${1:-FAILED TO UNRESERVE, FIX MANUALLY.}" 2
986         }
987         WORKING_TOPOLOGY=""
988         set -eu
989     fi
990 }
991
992
993 function warn () {
994
995     # Print the message to standard error.
996     #
997     # Arguments:
998     # - ${@} - The text of the message.
999
1000     set -exuo pipefail
1001
1002     echo "$@" >&2
1003 }