Simplify mrr daily tag expression
[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     set -exuo pipefail
27
28     # Create virtual vpp-device topology. Output of the function is topology
29     # file describing created environment saved to a file.
30     #
31     # Variables read:
32     # - BASH_FUNCTION_DIR - Path to existing directory this file is located in.
33     # - TOPOLOGIES - Available topologies.
34     # - NODENESS - Node multiplicity of desired testbed.
35     # - FLAVOR - Node flavor string, usually describing the processor.
36     # - IMAGE_VER_FILE - Name of file that contains the image version.
37     # Variables set:
38     # - WORKING_TOPOLOGY - Path to topology file.
39
40     source "${BASH_FUNCTION_DIR}/device.sh" || {
41         die "Source failed!"
42     }
43
44     device_image="$(< ${CSIT_DIR}/${IMAGE_VER_FILE})"
45     case_text="${NODENESS}_${FLAVOR}"
46     case "${case_text}" in
47         "1n_skx")
48             # We execute reservation over csit-shim-dcr (ssh) which runs sourced
49             # script's functions. Env variables are read from ssh output
50             # back to localhost for further processing.
51             hostname=$(grep search /etc/resolv.conf | cut -d' ' -f3)
52             ssh="ssh root@${hostname} -p 6022"
53             run="activate_wrapper ${NODENESS} ${FLAVOR} ${device_image}"
54             # backtics to avoid https://midnight-commander.org/ticket/2142
55             env_vars=`${ssh} "$(declare -f); ${run}"` || {
56                 die "Topology reservation via shim-dcr failed!"
57             }
58             set -a
59             source <(echo "$env_vars" | grep -v /usr/bin/docker) || {
60                 die "Source failed!"
61             }
62             set +a
63             ;;
64         "1n_vbox")
65             # We execute reservation on localhost. Sourced script automatially
66             # sets environment variables for further processing.
67             activate_wrapper "${NODENESS}" "${FLAVOR}" "${device_image}" || die
68             ;;
69         *)
70             die "Unknown specification: ${case_text}!"
71     esac
72
73     trap 'deactivate_docker_topology' EXIT || {
74          die "Trap attempt failed, please cleanup manually. Aborting!"
75     }
76
77     # Replace all variables in template with those in environment.
78     source <(echo 'cat <<EOF >topo.yml'; cat ${TOPOLOGIES[0]}; echo EOF;) || {
79         die "Topology file create failed!"
80     }
81
82     WORKING_TOPOLOGY="/tmp/topology.yaml"
83     mv topo.yml "${WORKING_TOPOLOGY}" || {
84         die "Topology move failed!"
85     }
86     cat ${WORKING_TOPOLOGY} | grep -v password || {
87         die "Topology read failed!"
88     }
89 }
90
91
92 function activate_virtualenv () {
93
94     set -exuo pipefail
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     # TODO: Do we want the callers to be able to set the env dir name?
111     # TODO: + In that case, do we want to support env switching?
112     # TODO:   + In that case we want to make env_dir global.
113     # TODO: Do we want the callers to override PYTHONPATH loaction?
114
115     root_path="${1-$CSIT_DIR}"
116     env_dir="${root_path}/env"
117     req_path=${2-$CSIT_DIR/requirements.txt}
118     rm -rf "${env_dir}" || die "Failed to clean previous virtualenv."
119     pip install --upgrade virtualenv || {
120         die "Virtualenv package install failed."
121     }
122     virtualenv "${env_dir}" || {
123         die "Virtualenv creation failed."
124     }
125     set +u
126     source "${env_dir}/bin/activate" || die "Virtualenv activation failed."
127     set -u
128     pip install --upgrade -r "${req_path}" || {
129         die "Requirements installation failed."
130     }
131     # Most CSIT Python scripts assume PYTHONPATH is set and exported.
132     export PYTHONPATH="${CSIT_DIR}" || die "Export failed."
133 }
134
135
136 function archive_tests () {
137
138     set -exuo pipefail
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     tar c "${GENERATED_DIR}/tests" | xz -9e > "${ARCHIVE_DIR}/tests.tar.xz" || {
149         die "Error creating archive of generated tests."
150     }
151 }
152
153
154 function check_download_dir () {
155
156     set -exuo pipefail
157
158     # Fail if there are no files visible in ${DOWNLOAD_DIR}.
159     # TODO: Do we need this as a function, if it is (almost) a one-liner?
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     if [[ ! "$(ls -A "${DOWNLOAD_DIR}")" ]]; then
169         die "No artifacts downloaded!"
170     fi
171 }
172
173
174 function cleanup_topo () {
175
176     set -exuo pipefail
177
178     # Variables read:
179     # - WORKING_TOPOLOGY - Path to topology yaml file of the reserved testbed.
180     # - PYTHON_SCRIPTS_DIR - Path to directory holding the reservation script.
181
182     python "${PYTHON_SCRIPTS_DIR}/topo_cleanup.py" -t "${WORKING_TOPOLOGY}"
183     # Not using "|| die" as some callers might want to ignore errors,
184     # e.g. in teardowns, such as unreserve.
185 }
186
187
188 function common_dirs () {
189
190     set -exuo pipefail
191
192     # Set global variables, create some directories (without touching content).
193
194     # Variables set:
195     # - BASH_FUNCTION_DIR - Path to existing directory this file is located in.
196     # - CSIT_DIR - Path to existing root of local CSIT git repository.
197     # - TOPOLOGIES_DIR - Path to existing directory with available tpologies.
198     # - RESOURCES_DIR - Path to existing CSIT subdirectory "resources".
199     # - TOOLS_DIR - Path to existing resources subdirectory "tools".
200     # - PYTHON_SCRIPTS_DIR - Path to existing tools subdirectory "scripts".
201     # - ARCHIVE_DIR - Path to created CSIT subdirectory "archive".
202     # - DOWNLOAD_DIR - Path to created CSIT subdirectory "download_dir".
203     # - GENERATED_DIR - Path to created CSIT subdirectory "generated".
204     # Directories created if not present:
205     # ARCHIVE_DIR, DOWNLOAD_DIR, GENERATED_DIR.
206     # Functions called:
207     # - die - Print to stderr and exit.
208
209     BASH_FUNCTION_DIR="$(dirname "$(readlink -e "${BASH_SOURCE[0]}")")" || {
210         die "Some error during localizing this source directory."
211     }
212     # Current working directory could be in a different repo, e.g. VPP.
213     pushd "${BASH_FUNCTION_DIR}" || die "Pushd failed"
214     CSIT_DIR="$(readlink -e "$(git rev-parse --show-toplevel)")" || {
215         die "Readlink or git rev-parse failed."
216     }
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     set -exuo pipefail
249
250     # Variables read:
251     # - WORKING_TOPOLOGY - Path to topology yaml file of the reserved testbed.
252     # - DUT - CSIT test/ subdirectory, set while processing tags.
253     # - TAGS - Array variable holding selected tag boolean expressions.
254     # - TOPOLOGIES_TAGS - Tag boolean expression filtering tests for topology.
255     # - TEST_CODE - The test selection string from environment or argument.
256     # Variables set:
257     # - PYBOT_ARGS - String holding part of all arguments for pybot.
258     # - EXPANDED_TAGS - Array of strings pybot arguments compiled from tags.
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     set -exuo pipefail
292
293     # Variables read:
294     # - WORKSPACE - Jenkins workspace, copy only if the value is not empty.
295     #   Can be unset, then it speeds up manual testing.
296     # - ARCHIVE_DIR - Path to directory with content to be copied.
297     # Directories updated:
298     # - ${WORKSPACE}/archives/ - Created if does not exist.
299     #   Content of ${ARCHIVE_DIR}/ is copied here.
300     # Functions called:
301     # - die - Print to stderr and exit.
302
303     # We will create additional archive if workspace variable is set.
304     # This way if script is running in jenkins all will be
305     # automatically archived to logs.fd.io.
306     if [[ -n "${WORKSPACE-}" ]]; then
307         mkdir -p "${WORKSPACE}/archives/" || die "Archives dir create failed."
308         cp -rf "${ARCHIVE_DIR}"/* "${WORKSPACE}/archives" || die "Copy failed."
309     fi
310 }
311
312
313 function deactivate_docker_topology () {
314     # Deactivate virtual vpp-device topology by removing containers.
315     #
316     # Variables read:
317     # - NODENESS - Node multiplicity of desired testbed.
318     # - FLAVOR - Node flavor string, usually describing the processor.
319
320     set -exuo pipefail
321
322     case_text="${NODENESS}_${FLAVOR}"
323     case "${case_text}" in
324         "1n_skx")
325             hostname=$(grep search /etc/resolv.conf | cut -d' ' -f3)
326             ssh="ssh root@${hostname} -p 6022"
327             env_vars="$(env | grep CSIT_ | tr '\n' ' ' )"
328             ${ssh} "$(declare -f); deactivate_wrapper ${env_vars}" || {
329                 die "Topology cleanup via shim-dcr failed!"
330             }
331             ;;
332         "1n_vbox")
333             enter_mutex || die
334             clean_environment || {
335                 die "Topology cleanup locally failed!"
336             }
337             exit_mutex || die
338             ;;
339         *)
340             die "Unknown specification: ${case_text}!"
341     esac
342 }
343
344
345 function die () {
346     # Print the message to standard error end exit with error code specified
347     # by the second argument.
348     #
349     # Hardcoded values:
350     # - The default error message.
351     # Arguments:
352     # - ${1} - The whole error message, be sure to quote. Optional
353     # - ${2} - the code to exit with, default: 1.
354
355     set -x
356     set +eu
357     warn "${1:-Unspecified run-time error occurred!}"
358     exit "${2:-1}"
359 }
360
361
362 function die_on_pybot_error () {
363
364     set -exuo pipefail
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     if [[ "${PYBOT_EXIT_STATUS}" != "0" ]]; then
374         die "Test failures are present!" "${PYBOT_EXIT_STATUS}"
375     fi
376 }
377
378
379 function generate_tests () {
380
381     set -exuo pipefail
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     rm -rf "${GENERATED_DIR}/tests"
397     cp -r "${CSIT_DIR}/tests" "${GENERATED_DIR}/tests"
398     cmd_line=("find" "${GENERATED_DIR}/tests" "-type" "f")
399     cmd_line+=("-executable" "-name" "*.py")
400     file_list=$("${cmd_line[@]}") || die
401
402     for gen in ${file_list}; do
403         directory="$(dirname "${gen}")" || die
404         filename="$(basename "${gen}")" || die
405         pushd "${directory}" || die
406         ./"${filename}" || die
407         popd || die
408     done
409 }
410
411
412 function get_test_code () {
413
414     set -exuo pipefail
415
416     # Arguments:
417     # - ${1} - Optional, argument of entry script (or empty as unset).
418     #   Test code value to override job name from environment.
419     # Variables read:
420     # - JOB_NAME - String affecting test selection, default if not argument.
421     # Variables set:
422     # - TEST_CODE - The test selection string from environment or argument.
423     # - NODENESS - Node multiplicity of desired testbed.
424     # - FLAVOR - Node flavor string, usually describing the processor.
425
426     TEST_CODE="${1-}" || die "Reading optional argument failed, somehow."
427     if [[ -z "${TEST_CODE}" ]]; then
428         TEST_CODE="${JOB_NAME-}" || die "Reading job name failed, somehow."
429     fi
430
431     case "${TEST_CODE}" in
432         *"1n-vbox"*)
433             NODENESS="1n"
434             FLAVOR="vbox"
435             ;;
436         *"1n-skx"*)
437             NODENESS="1n"
438             FLAVOR="skx"
439             ;;
440         *"2n-skx"*)
441             NODENESS="2n"
442             FLAVOR="skx"
443             ;;
444         *"3n-skx"*)
445             NODENESS="3n"
446             FLAVOR="skx"
447             ;;
448         *"3n-tsh"*)
449             NODENESS="3n"
450             FLAVOR="tsh"
451             ;;
452         *)
453             # Fallback to 3-node Haswell by default (backward compatibility)
454             NODENESS="3n"
455             FLAVOR="hsw"
456             ;;
457     esac
458 }
459
460
461 function get_test_tag_string () {
462
463     set -exuo pipefail
464
465     # Variables read:
466     # - GERRIT_EVENT_TYPE - Event type set by gerrit, can be unset.
467     # - GERRIT_EVENT_COMMENT_TEXT - Comment text, read for "comment-added" type.
468     # - TEST_CODE - The test selection string from environment or argument.
469     # Variables set:
470     # - TEST_TAG_STRING - The string following "perftest" in gerrit comment,
471     #   or empty.
472
473     # TODO: ci-management scripts no longer need to perform this.
474
475     trigger=""
476     if [[ "${GERRIT_EVENT_TYPE-}" == "comment-added" ]]; then
477         case "${TEST_CODE}" in
478             *"device"*)
479                 # On parsing error, ${trigger} stays empty.
480                 trigger="$(echo "${GERRIT_EVENT_COMMENT_TEXT}" \
481                     | grep -oE '(devicetest$|devicetest[[:space:]].+$)')" \
482                     || true
483                 # Set test tags as string.
484                 TEST_TAG_STRING="${trigger#$"devicetest"}"
485                 ;;
486             *"perf"*)
487                 # On parsing error, ${trigger} stays empty.
488                 comment="${GERRIT_EVENT_COMMENT_TEXT}"
489                 # As "perftest" can be followed by something, we substitute it.
490                 comment="${comment/perftest-2n/perftest}"
491                 comment="${comment/perftest-3n/perftest}"
492                 comment="${comment/perftest-hsw/perftest}"
493                 comment="${comment/perftest-skx/perftest}"
494                 comment="${comment/perftest-tsh/perftest}"
495                 tag_string="$(echo "${comment}" \
496                     | grep -oE '(perftest$|perftest[[:space:]].+$)' || true)"
497                 # Set test tags as string.
498                 TEST_TAG_STRING="${tag_string#$"perftest"}"
499                 ;;
500             *)
501                 die "Unknown specification: ${TEST_CODE}"
502         esac
503     fi
504 }
505
506
507 function reserve_testbed () {
508
509     set -exuo pipefail
510
511     # Reserve physical testbed, perform cleanup, register trap to unreserve.
512     #
513     # Variables read:
514     # - TOPOLOGIES - Array of paths to topology yaml to attempt reservation on.
515     # - PYTHON_SCRIPTS_DIR - Path to directory holding the reservation script.
516     # Variables set:
517     # - WORKING_TOPOLOGY - Path to topology yaml file of the reserved testbed.
518     # Functions called:
519     # - die - Print to stderr and exit.
520     # Traps registered:
521     # - EXIT - Calls cancel_all for ${WORKING_TOPOLOGY}.
522
523     while true; do
524         for topo in "${TOPOLOGIES[@]}"; do
525             set +e
526             python "${PYTHON_SCRIPTS_DIR}/topo_reservation.py" -t "${topo}"
527             result="$?"
528             set -e
529             if [[ "${result}" == "0" ]]; then
530                 WORKING_TOPOLOGY="${topo}"
531                 echo "Reserved: ${WORKING_TOPOLOGY}"
532                 trap "untrap_and_unreserve_testbed" EXIT || {
533                     message="TRAP ATTEMPT AND UNRESERVE FAILED, FIX MANUALLY."
534                     untrap_and_unreserve_testbed "${message}" || {
535                         die "Teardown should have died, not failed."
536                     }
537                     die "Trap attempt failed, unreserve succeeded. Aborting."
538                 }
539                 cleanup_topo || {
540                     die "Testbed cleanup failed."
541                 }
542                 break
543             fi
544         done
545
546         if [[ -n "${WORKING_TOPOLOGY-}" ]]; then
547             # Exit the infinite while loop if we made a reservation.
548             break
549         fi
550
551         # Wait ~3minutes before next try.
552         sleep_time="$[ ( $RANDOM % 20 ) + 180 ]s" || {
553             die "Sleep time calculation failed."
554         }
555         echo "Sleeping ${sleep_time}"
556         sleep "${sleep_time}" || die "Sleep failed."
557     done
558 }
559
560
561 function run_pybot () {
562
563     set -exuo pipefail
564
565     # Variables read:
566     # - CSIT_DIR - Path to existing root of local CSIT git repository.
567     # - ARCHIVE_DIR - Path to store robot result files in.
568     # - PYBOT_ARGS, EXPANDED_TAGS - See compose_pybot_arguments.sh
569     # - GENERATED_DIR - Tests are assumed to be generated under there.
570     # Variables set:
571     # - PYBOT_EXIT_STATUS - Exit status of most recent pybot invocation.
572     # Functions called:
573     # - die - Print to stderr and exit.
574
575     all_options=("--outputdir" "${ARCHIVE_DIR}" "${PYBOT_ARGS[@]}")
576     all_options+=("${EXPANDED_TAGS[@]}")
577
578     pushd "${CSIT_DIR}" || die "Change directory operation failed."
579     set +e
580     # TODO: Make robot tests not require "$(pwd)" == "${CSIT_DIR}".
581     pybot "${all_options[@]}" "${GENERATED_DIR}/tests/"
582     PYBOT_EXIT_STATUS="$?"
583     set -e
584
585     # Generate INFO level output_info.xml for post-processing.
586     all_options=("--loglevel" "INFO")
587     all_options+=("--log" "none")
588     all_options+=("--report" "none")
589     all_options+=("--output" "${ARCHIVE_DIR}/output_info.xml")
590     all_options+=("${ARCHIVE_DIR}/output.xml")
591     rebot "${all_options[@]}"
592     popd || die "Change directory operation failed."
593 }
594
595
596 function select_tags () {
597
598     set -exuo pipefail
599
600     # Variables read:
601     # - WORKING_TOPOLOGY - Path to topology yaml file of the reserved testbed.
602     # - TEST_CODE - String affecting test selection, usually jenkins job name.
603     # - TEST_TAG_STRING - String selecting tags, from gerrit comment.
604     #   Can be unset.
605     # - TOPOLOGIES_DIR - Path to existing directory with available tpologies.
606     # Variables set:
607     # - TAGS - Array of processed tag boolean expressions.
608
609     # NIC SELECTION
610     start_pattern='^  TG:'
611     end_pattern='^ \? \?[A-Za-z0-9]\+:'
612     # Remove the TG section from topology file
613     sed_command="/${start_pattern}/,/${end_pattern}/d"
614     # All topologies DUT NICs
615     available=$(sed "${sed_command}" "${TOPOLOGIES_DIR}"/* \
616                 | grep -hoP "model: \K.*" | sort -u)
617     # Selected topology DUT NICs
618     reserved=$(sed "${sed_command}" "${WORKING_TOPOLOGY}" \
619                | grep -hoP "model: \K.*" | sort -u)
620     # All topologies DUT NICs - Selected topology DUT NICs
621     exclude_nics=($(comm -13 <(echo "${reserved}") <(echo "${available}")))
622
623     # Select default NIC
624     case "${TEST_CODE}" in
625         *"3n-tsh"*)
626             DEFAULT_NIC='nic_intel-x520-da2'
627             ;;
628         *)
629             DEFAULT_NIC='nic_intel-x710'
630             ;;
631     esac
632
633     case "${TEST_CODE}" in
634         # Select specific performance tests based on jenkins job type variable.
635         *"ndrpdr-weekly"* )
636             readarray -t test_tag_array < "${BASH_FUNCTION_DIR}/mlr-weekly.txt"
637             ;;
638         *"mrr-daily"* )
639             readarray -t test_tag_array < "${BASH_FUNCTION_DIR}/mrr-daily.txt"
640             ;;
641         *"mrr-weekly"* )
642             readarray -t test_tag_array < "${BASH_FUNCTION_DIR}/mrr-weekly.txt"
643             ;;
644         * )
645             if [[ -z "${TEST_TAG_STRING-}" ]]; then
646                 # If nothing is specified, we will run pre-selected tests by
647                 # following tags.
648                 test_tag_array=("mrrAND${DEFAULT_NIC}AND1cAND64bANDip4base"
649                                 "mrrAND${DEFAULT_NIC}AND1cAND78bANDip6base"
650                                 "mrrAND${DEFAULT_NIC}AND1cAND64bANDl2bdbase"
651                                 "mrrAND${DEFAULT_NIC}AND1cAND64bANDl2xcbase"
652                                 "!dot1q" "!drv_avf")
653             else
654                 # If trigger contains tags, split them into array.
655                 test_tag_array=(${TEST_TAG_STRING//:/ })
656             fi
657             ;;
658     esac
659
660     # Blacklisting certain tags per topology.
661     case "${TEST_CODE}" in
662         *"2n-skx"*)
663             test_tag_array+=("!ipsechw")
664             ;;
665         *"3n-skx"*)
666             test_tag_array+=("!ipsechw")
667             # Not enough nic_intel-xxv710 to support double link tests.
668             test_tag_array+=("!3_node_double_link_topoANDnic_intel-xxv710")
669             ;;
670         *"3n-tsh"*)
671             test_tag_array+=("!ipsechw")
672             test_tag_array+=("!memif")
673             test_tag_array+=("!srv6_proxy")
674             test_tag_array+=("!vhost")
675             test_tag_array+=("!vts")
676             ;;
677         *"3n-hsw"*)
678             # TODO: If AVF tests are expected to fail on haswell,
679             # add (before excluding) an explanation to:
680             # https://github.com/FDio/vpp/blob/master/src/plugins/avf/README.md
681             test_tag_array+=("!ipsechwNOTnic_intel-xl710")
682             ;;
683         *)
684             # Default to 3n-hsw due to compatibility.
685             test_tag_array+=("!ipsechwNOTnic_intel-xl710")
686             ;;
687     esac
688
689     # We will add excluded NICs.
690     test_tag_array+=("${exclude_nics[@]/#/!NIC_}")
691
692     TAGS=()
693
694     # We will prefix with perftest to prevent running other tests
695     # (e.g. Functional).
696     prefix="perftestAND"
697     set +x
698     if [[ "${TEST_CODE}" == "vpp-"* ]]; then
699         # Automatic prefixing for VPP jobs to limit the NIC used and
700         # traffic evaluation to MRR.
701         if [[ "${TEST_TAG_STRING-}" == *"nic_"* ]]; then
702             prefix="${prefix}mrrAND"
703         else
704             prefix="${prefix}mrrAND${DEFAULT_NIC}AND"
705         fi
706     fi
707     for tag in "${test_tag_array[@]}"; do
708         if [[ "${tag}" == "!"* ]]; then
709             # Exclude tags are not prefixed.
710             TAGS+=("${tag}")
711         elif [[ "${tag}" != "" && "${tag}" != "#"* ]]; then
712             # Empty and comment lines are skipped.
713             # Other lines are normal tags, they are to be prefixed.
714             TAGS+=("${prefix}${tag}")
715         fi
716     done
717     set -x
718 }
719
720
721 function select_vpp_device_tags () {
722
723     set -exuo pipefail
724
725     # Variables read:
726     # - TEST_CODE - String affecting test selection, usually jenkins job name.
727     # - TEST_TAG_STRING - String selecting tags, from gerrit comment.
728     #   Can be unset.
729     # Variables set:
730     # - TAGS - Array of processed tag boolean expressions.
731
732     case "${TEST_CODE}" in
733         # Select specific performance tests based on jenkins job type variable.
734         * )
735             if [[ -z "${TEST_TAG_STRING-}" ]]; then
736                 # If nothing is specified, we will run pre-selected tests by
737                 # following tags. Items of array will be concatenated by OR
738                 # in Robot Framework.
739                 test_tag_array=()
740             else
741                 # If trigger contains tags, split them into array.
742                 test_tag_array=(${TEST_TAG_STRING//:/ })
743             fi
744             ;;
745     esac
746
747     TAGS=()
748
749     # We will prefix with perftest to prevent running other tests
750     # (e.g. Functional).
751     prefix="devicetestAND"
752     if [[ "${TEST_CODE}" == "vpp-"* ]]; then
753         # Automatic prefixing for VPP jobs to limit testing.
754         prefix="${prefix}"
755     fi
756     for tag in "${test_tag_array[@]}"; do
757         if [[ ${tag} == "!"* ]]; then
758             # Exclude tags are not prefixed.
759             TAGS+=("${tag}")
760         else
761             TAGS+=("${prefix}${tag}")
762         fi
763     done
764 }
765
766 function select_os () {
767
768     set -exuo pipefail
769
770     # Variables set:
771     # - VPP_VER_FILE - Name of File in CSIT dir containing vpp stable version.
772     # - IMAGE_VER_FILE - Name of File in CSIT dir containing the image name.
773     # - PKG_SUFFIX - Suffix of OS package file name, "rpm" or "deb."
774
775     os_id=$(grep '^ID=' /etc/os-release | cut -f2- -d= | sed -e 's/\"//g') || {
776         die "Get OS release failed."
777     }
778
779     case "${os_id}" in
780         "ubuntu"*)
781             IMAGE_VER_FILE="VPP_DEVICE_IMAGE_UBUNTU"
782             VPP_VER_FILE="VPP_STABLE_VER_UBUNTU_BIONIC"
783             PKG_SUFFIX="deb"
784             ;;
785         "centos"*)
786             IMAGE_VER_FILE="VPP_DEVICE_IMAGE_CENTOS"
787             VPP_VER_FILE="VPP_STABLE_VER_CENTOS"
788             PKG_SUFFIX="rpm"
789             ;;
790         *)
791             die "Unable to identify distro or os from ${OS}"
792             ;;
793     esac
794 }
795
796
797 function select_topology () {
798
799     set -exuo pipefail
800
801     # Variables read:
802     # - NODENESS - Node multiplicity of testbed, either "2n" or "3n".
803     # - FLAVOR - Node flavor string, currently either "hsw" or "skx".
804     # - CSIT_DIR - Path to existing root of local CSIT git repository.
805     # - TOPOLOGIES_DIR - Path to existing directory with available topologies.
806     # Variables set:
807     # - TOPOLOGIES - Array of paths to suitable topology yaml files.
808     # - TOPOLOGIES_TAGS - Tag expression selecting tests for the topology.
809     # Functions called:
810     # - die - Print to stderr and exit.
811
812     case_text="${NODENESS}_${FLAVOR}"
813     case "${case_text}" in
814         # TODO: Move tags to "# Blacklisting certain tags per topology" section.
815         "1n_vbox")
816             TOPOLOGIES=( "${TOPOLOGIES_DIR}"/*vpp_device*.template )
817             TOPOLOGIES_TAGS="2_node_single_link_topo"
818             ;;
819         "1n_skx")
820             TOPOLOGIES=( "${TOPOLOGIES_DIR}"/*vpp_device*.template )
821             TOPOLOGIES_TAGS="2_node_single_link_topo"
822             ;;
823         "2n_skx")
824             TOPOLOGIES=( "${TOPOLOGIES_DIR}"/*2n_skx*.yaml )
825             TOPOLOGIES_TAGS="2_node_*_link_topo"
826             ;;
827         "3n_skx")
828             TOPOLOGIES=( "${TOPOLOGIES_DIR}"/*3n_skx*.yaml )
829             TOPOLOGIES_TAGS="3_node_*_link_topo"
830             ;;
831         "3n_hsw")
832             TOPOLOGIES=( "${TOPOLOGIES_DIR}"/*3n_hsw*.yaml )
833             TOPOLOGIES_TAGS="3_node_single_link_topo"
834             ;;
835         "3n_tsh")
836             TOPOLOGIES=( "${TOPOLOGIES_DIR}"/*3n_tsh*.yaml )
837             TOPOLOGIES_TAGS="3_node_*_link_topo"
838             ;;
839         *)
840             # No falling back to 3n_hsw default, that should have been done
841             # by the function which has set NODENESS and FLAVOR.
842             die "Unknown specification: ${case_text}"
843     esac
844
845     if [[ -z "${TOPOLOGIES-}" ]]; then
846         die "No applicable topology found!"
847     fi
848 }
849
850
851 function untrap_and_unreserve_testbed () {
852     # Use this as a trap function to ensure testbed does not remain reserved.
853     # Perhaps call directly before script exit, to free testbed for other jobs.
854     # This function is smart enough to avoid multiple unreservations (so safe).
855     # Topo cleanup is executed (call it best practice), ignoring failures.
856     #
857     # Hardcoded values:
858     # - default message to die with if testbed might remain reserved.
859     # Arguments:
860     # - ${1} - Message to die with if unreservation fails. Default hardcoded.
861     # Variables read (by inner function):
862     # - WORKING_TOPOLOGY - Path to topology yaml file of the reserved testbed.
863     # - PYTHON_SCRIPTS_DIR - Path to directory holding Python scripts.
864     # Variables written:
865     # - WORKING_TOPOLOGY - Set to empty string on successful unreservation.
866     # Trap unregistered:
867     # - EXIT - Failure to untrap is reported, but ignored otherwise.
868     # Functions called:
869     # - die - Print to stderr and exit.
870
871     set -xo pipefail
872     set +eu  # We do not want to exit early in a "teardown" function.
873     trap - EXIT || echo "Trap deactivation failed, continuing anyway."
874     wt="${WORKING_TOPOLOGY}"  # Just to avoid too long lines.
875     if [[ -z "${wt-}" ]]; then
876         set -eu
877         warn "Testbed looks unreserved already. Trap removal failed before?"
878     else
879         cleanup_topo || true
880         python "${PYTHON_SCRIPTS_DIR}/topo_reservation.py" -c -t "${wt}" || {
881             die "${1:-FAILED TO UNRESERVE, FIX MANUALLY.}" 2
882         }
883         WORKING_TOPOLOGY=""
884         set -eu
885     fi
886 }
887
888
889 function warn () {
890     # Print the message to standard error.
891     #
892     # Arguments:
893     # - ${@} - The text of the message.
894
895     echo "$@" >&2
896 }