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