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