3 # ============LICENSE_START===============================================
4 # Copyright (C) 2020 Nordix Foundation. All rights reserved.
5 # ========================================================================
6 # Licensed under the Apache License, Version 2.0 (the "License");
7 # you may not use this file except in compliance with the License.
8 # You may obtain a copy of the License at
10 # http://www.apache.org/licenses/LICENSE-2.0
12 # Unless required by applicable law or agreed to in writing, software
13 # distributed under the License is distributed on an "AS IS" BASIS,
14 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 # See the License for the specific language governing permissions and
16 # limitations under the License.
17 # ============LICENSE_END=================================================
20 # This is a script that contains all the common functions needed for auto test.
21 # Specific test function are defined in scripts XXXX_functions.sh
23 . ../common/api_curl.sh
24 . ../common/testengine_config.sh
27 echo "Args: remote|remote-remove docker|kube --env-file <environment-filename> [release] [auto-clean] [--stop-at-error] "
28 echo " [--ricsim-prefix <prefix> ] [--use-local-image <app-nam>+] [--use-snapshot-image <app-nam>+]"
29 echo " [--use-staging-image <app-nam>+] [--use-release-image <app-nam>+] [--image-repo <repo-address]"
30 echo " [--repo-policy local|remote] [--cluster-timeout <timeout-in seconds>] [--print-stats]"
31 echo " [--override <override-environment-filename> --pre-clean]"
34 if [ $# -eq 1 ] && [ "$1" == "help" ]; then
36 if [ ! -z "$TC_ONELINE_DESCR" ]; then
37 echo "Test script description:"
38 echo $TC_ONELINE_DESCR
43 echo "remote - Use images from remote repositories. Can be overridden for individual images using the '--use_xxx' flags"
44 echo "remote-remove - Same as 'remote' but will also try to pull fresh images from remote repositories"
45 echo "docker - Test executed in docker environment"
46 echo "kube - Test executed in kubernetes environment - requires an already started kubernetes environment"
47 echo "--env-file <file> - The script will use the supplied file to read environment variables from"
48 echo "release - If this flag is given the script will use release version of the images"
49 echo "auto-clean - If the function 'auto_clean_containers' is present in the end of the test script then all containers will be stopped and removed. If 'auto-clean' is not given then the function has no effect."
50 echo "--stop-at-error - The script will stop when the first failed test or configuration"
51 echo "--ricsim-prefix - The a1 simulator will use the supplied string as container prefix instead of 'ricsim'"
52 echo "--use-local-image - The script will use local images for the supplied apps, space separated list of app short names"
53 echo "--use-snapshot-image - The script will use images from the nexus snapshot repo for the supplied apps, space separated list of app short names"
54 echo "--use-staging-image - The script will use images from the nexus staging repo for the supplied apps, space separated list of app short names"
55 echo "--use-release-image - The script will use images from the nexus release repo for the supplied apps, space separated list of app short names"
56 echo "--image-repo - Url to optional image repo. Only locally built images will be re-tagged and pushed to this repo"
57 echo "--repo-policy - Policy controlling which images to re-tag and push if param --image-repo is set. Default is 'local'"
58 echo "--cluster-timeout - Optional timeout for cluster where it takes time to obtain external ip/host-name. Timeout in seconds. "
59 echo "--print-stats - Print current test stats after each test."
60 echo "--override <file> - Override setting from the file supplied by --env-file"
61 echo "--pre-clean - Will clean kube resouces when running docker and vice versa"
64 echo "List of app short names supported: "$APP_SHORT_NAMES
69 # Create a test case id, ATC (Auto Test Case), from the name of the test case script.
70 # FTC1.sh -> ATC == FTC1
71 ATC=$(basename "${BASH_SOURCE[$i+1]}" .sh)
73 #Create result file (containing '1' for error) for this test case
74 #Will be replaced with a file containing '0' if all test cases pass
75 echo "1" > "$PWD/.result$ATC.txt"
77 #Formatting for 'echo' cmd
82 GREEN="\033[32m\033[1m"
84 YELLOW="\033[33m\033[1m"
88 # Just resetting any previous echo formatting...
91 # default test environment variables
93 #Override env file, will be added on top of the above file
94 TEST_ENV_VAR_FILE_OVERRIDE=""
96 echo "Test case started as: ${BASH_SOURCE[$i+1]} "$@
99 LOCALHOST_NAME="localhost"
100 LOCALHOST_HTTP="http://localhost"
101 LOCALHOST_HTTPS="https://localhost"
103 # Var to hold 'auto' in case containers shall be stopped when test case ends
106 # Var to indicate pre clean, if flag --pre-clean is set the script will clean kube resouces when running docker and vice versa
109 # Var to hold the app names to use local images for
112 # Var to hold the app names to use remote snapshot images for
113 USE_SNAPSHOT_IMAGES=""
115 # Var to hold the app names to use remote staging images for
116 USE_STAGING_IMAGES=""
118 # Var to hold the app names to use remote release images for
119 USE_RELEASE_IMAGES=""
122 # Use this var (STOP_AT_ERROR=1 in the test script) for debugging/trouble shooting to take all logs and exit at first FAIL test case
125 # The default value "DEV" indicate that development image tags (SNAPSHOT) and nexus repos (nexus port 10002) are used.
126 # The value "RELEASE" indicate that relase image tag and nexus repos (nexus port) are used
127 # Applies only to images defined in the test-env files with image names and tags defined as XXXX_RELEASE
130 # Function to indent cmd output with one space
131 indent1() { sed 's/^/ /'; }
133 # Function to indent cmd output with two spaces
134 indent2() { sed 's/^/ /'; }
136 # Set a description string for the test case
137 if [ -z "$TC_ONELINE_DESCR" ]; then
138 TC_ONELINE_DESCR="<no-description>"
139 echo "No test case description found, TC_ONELINE_DESCR should be set on in the test script , using "$TC_ONELINE_DESCR
142 # Counter for test suites
143 if [ -f .tmp_tcsuite_ctr ]; then
144 tmpval=$(< .tmp_tcsuite_ctr)
146 echo $tmpval > .tmp_tcsuite_ctr
149 # Create the logs dir if not already created in the current dir
150 if [ ! -d "logs" ]; then
155 # Create the tmp dir for temporary files that is not needed after the test
156 # hidden files for the test env is still stored in the current dir
157 # files in the ./tmp is moved to ./tmp/prev when a new test is started
158 if [ ! -d "tmp" ]; then
163 if [ $? -ne 0 ]; then
164 echo "Cannot cd to $PWD/tmp"
165 echo "Dir cannot be created. Exiting...."
167 if [ ! -d "prev" ]; then
171 mv ./tmp/* ./tmp/prev 2> /dev/null
173 # Create a http message log for this testcase
174 HTTPLOG=$PWD"/.httplog_"$ATC".txt"
177 # Create a log dir for the test case
178 mkdir -p $TESTLOGS/$ATC
180 # Save create for current logs
181 mkdir -p $TESTLOGS/$ATC/previous
183 rm $TESTLOGS/$ATC/previous/*.log &> /dev/null
184 rm $TESTLOGS/$ATC/previous/*.txt &> /dev/null
185 rm $TESTLOGS/$ATC/previous/*.json &> /dev/null
187 mv $TESTLOGS/$ATC/*.log $TESTLOGS/$ATC/previous &> /dev/null
188 mv $TESTLOGS/$ATC/*.txt $TESTLOGS/$ATC/previous &> /dev/null
189 mv $TESTLOGS/$ATC/*.txt $TESTLOGS/$ATC/previous &> /dev/null
191 # Clear the log dir for the test case
192 rm $TESTLOGS/$ATC/*.log &> /dev/null
193 rm $TESTLOGS/$ATC/*.txt &> /dev/null
194 rm $TESTLOGS/$ATC/*.json &> /dev/null
196 # Log all output from the test case to a TC log
197 TCLOG=$TESTLOGS/$ATC/TC.log
198 exec &> >(tee ${TCLOG})
200 #Variables for counting tests as well as passed and failed tests
207 #Var to control if current stats shall be printed
208 PRINT_CURRENT_STATS=0
210 #File to keep deviation messages
211 DEVIATION_FILE=".tmp_deviations"
212 rm $DEVIATION_FILE &> /dev/null
214 # Trap "command not found" and make the script fail
217 if [ $? -eq 127 ]; then
218 echo -e $RED"Function not found, setting script to FAIL"$ERED
220 __print_current_stats
228 # Function to log the start of a test case
230 TIMESTAMP=$(date "+%Y-%m-%d %H:%M:%S")
231 echo -e $BOLD"TEST $TEST_SEQUENCE_NR (${BASH_LINENO[1]}): ${FUNCNAME[1]}" $@ $EBOLD
232 echo "TEST $TEST_SEQUENCE_NR - ${TIMESTAMP}: (${BASH_LINENO[1]}): ${FUNCNAME[1]}" $@ >> $HTTPLOG
234 ((TEST_SEQUENCE_NR++))
237 # Function to print current statistics
238 __print_current_stats() {
239 if [ $PRINT_CURRENT_STATS -ne 0 ]; then
240 echo " Current stats - exe-time, tests, passes, fails, conf fails, deviations: $(($SECONDS-$TCTEST_START)), $RES_TEST, $RES_PASS, $RES_FAIL, $RES_CONF_FAIL, $RES_DEVIATION"
244 # General function to log a failed test case
245 __log_test_fail_general() {
246 echo -e $RED" FAIL."$1 $ERED
248 __print_current_stats
249 __check_stop_at_error
252 # Function to log a test case failed due to incorrect response code
253 __log_test_fail_status_code() {
254 echo -e $RED" FAIL. Exepected status "$1", got "$2 $3 $ERED
256 __print_current_stats
257 __check_stop_at_error
260 # Function to log a test case failed due to incorrect response body
261 __log_test_fail_body() {
262 echo -e $RED" FAIL, returned body not correct"$ERED
264 __print_current_stats
265 __check_stop_at_error
268 # Function to log a test case that is not supported
269 __log_test_fail_not_supported() {
270 echo -e $RED" FAIL, function not supported"$ERED
272 __print_current_stats
273 __check_stop_at_error
276 # General function to log a passed test case
278 if [ $# -gt 0 ]; then
282 echo -e $GREEN" PASS"$EGREEN
283 __print_current_stats
286 #Counter for configurations
289 # Function to log the start of a configuration setup
291 TIMESTAMP=$(date "+%Y-%m-%d %H:%M:%S")
292 echo -e $BOLD"CONF $CONF_SEQUENCE_NR (${BASH_LINENO[1]}): "${FUNCNAME[1]} $@ $EBOLD
293 echo "CONF $CONF_SEQUENCE_NR - ${TIMESTAMP}: (${BASH_LINENO[1]}): "${FUNCNAME[1]} $@ >> $HTTPLOG
294 ((CONF_SEQUENCE_NR++))
297 # Function to log a failed configuration setup
298 __log_conf_fail_general() {
299 echo -e $RED" FAIL."$1 $ERED
301 __print_current_stats
302 __check_stop_at_error
305 # Function to log a failed configuration setup due to incorrect response code
306 __log_conf_fail_status_code() {
307 echo -e $RED" FAIL. Exepected status "$1", got "$2 $3 $ERED
309 __print_current_stats
310 __check_stop_at_error
313 # Function to log a failed configuration setup due to incorrect response body
314 __log_conf_fail_body() {
315 echo -e $RED" FAIL, returned body not correct"$ERED
317 __print_current_stats
318 __check_stop_at_error
321 # Function to log a configuration that is not supported
322 __log_conf_fail_not_supported() {
323 echo -e $RED" FAIL, function not supported"$ERED$@
325 __print_current_stats
326 __check_stop_at_error
329 # Function to log a passed configuration setup
331 if [ $# -gt 0 ]; then
334 echo -e $GREEN" OK"$EGREEN
335 __print_current_stats
338 #Var for measuring execution time
339 TCTEST_START=$SECONDS
341 #File to save timer measurement results
342 TIMER_MEASUREMENTS=".timer_measurement.txt"
343 echo -e "Activity \t Duration" > $TIMER_MEASUREMENTS
345 # If this is set, some images (control by the parameter repo-polcy) will be re-tagged and pushed to this repo before any
347 IMAGE_REPO_POLICY="local"
350 echo "-------------------------------------------------------------------------------------------------"
351 echo "----------------------------------- Test case: "$ATC
352 echo "----------------------------------- Started: "$(date)
353 echo "-------------------------------------------------------------------------------------------------"
354 echo "-- Description: "$TC_ONELINE_DESCR
355 echo "-------------------------------------------------------------------------------------------------"
356 echo "----------------------------------- Test case setup -----------------------------------"
358 echo "Setting AUTOTEST_HOME="$AUTOTEST_HOME
362 if [ $# -lt 1 ]; then
365 if [ $paramerror -eq 0 ]; then
366 if [ "$1" != "remote" ] && [ "$1" != "remote-remove" ]; then
368 if [ -z "$paramerror_str" ]; then
369 paramerror_str="First arg shall be 'remote' or 'remote-remove'"
375 if [ $paramerror -eq 0 ]; then
376 if [ "$1" != "docker" ] && [ "$1" != "kube" ]; then
378 if [ -z "$paramerror_str" ]; then
379 paramerror_str="Second arg shall be 'docker' or 'kube'"
382 if [ $1 == "docker" ]; then
384 echo "Setting RUNMODE=DOCKER"
386 if [ $1 == "kube" ]; then
388 echo "Setting RUNMODE=KUBE"
394 while [ $paramerror -eq 0 ] && [ $foundparm -eq 0 ]; do
396 if [ $paramerror -eq 0 ]; then
397 if [ "$1" == "release" ]; then
398 IMAGE_CATEGORY="RELEASE"
399 echo "Option set - Release image tags used for applicable images "
404 if [ $paramerror -eq 0 ]; then
405 if [ "$1" == "auto-clean" ]; then
407 echo "Option set - Auto clean at end of test script"
412 if [ $paramerror -eq 0 ]; then
413 if [ "$1" == "--stop-at-error" ]; then
415 echo "Option set - Stop at first error"
420 if [ $paramerror -eq 0 ]; then
421 if [ "$1" == "--ricsim-prefix" ]; then
423 TMP_RIC_SIM_PREFIX=$1 #RIC_SIM_PREFIX need to be updated after sourcing of the env file
426 if [ -z "$paramerror_str" ]; then
427 paramerror_str="No prefix found for flag: '--ricsim-prefix'"
430 echo "Option set - Overriding RIC_SIM_PREFIX with: "$1
436 if [ $paramerror -eq 0 ]; then
437 if [ "$1" == "--env-file" ]; then
442 if [ -z "$paramerror_str" ]; then
443 paramerror_str="No env file found for flag: '--env-file'"
446 echo "Option set - Reading test env from: "$1
452 if [ $paramerror -eq 0 ]; then
453 if [ "$1" == "--use-local-image" ]; then
456 while [ $# -gt 0 ] && [[ "$1" != "--"* ]]; do
457 USE_LOCAL_IMAGES=$USE_LOCAL_IMAGES" "$1
458 if [[ "$AVAILABLE_IMAGES_OVERRIDE" != *"$1"* ]]; then
460 if [ -z "$paramerror_str" ]; then
461 paramerror_str="App name $1 is not available for local override for flag: '--use-local-image'"
467 if [ -z "$USE_LOCAL_IMAGES" ]; then
469 if [ -z "$paramerror_str" ]; then
470 paramerror_str="No app name found for flag: '--use-local-image'"
473 echo "Option set - Overriding with local images for app(s):"$USE_LOCAL_IMAGES
477 if [ $paramerror -eq 0 ]; then
478 if [ "$1" == "--use-snapshot-image" ]; then
479 USE_SNAPSHOT_IMAGES=""
481 while [ $# -gt 0 ] && [[ "$1" != "--"* ]]; do
482 USE_SNAPSHOT_IMAGES=$USE_SNAPSHOT_IMAGES" "$1
483 if [[ "$AVAILABLE_IMAGES_OVERRIDE" != *"$1"* ]]; then
485 if [ -z "$paramerror_str" ]; then
486 paramerror_str="App name $1 is not available for snapshot override for flag: '--use-snapshot-image'"
492 if [ -z "$USE_SNAPSHOT_IMAGES" ]; then
494 if [ -z "$paramerror_str" ]; then
495 paramerror_str="No app name found for flag: '--use-snapshot-image'"
498 echo "Option set - Overriding with snapshot images for app(s):"$USE_SNAPSHOT_IMAGES
502 if [ $paramerror -eq 0 ]; then
503 if [ "$1" == "--use-staging-image" ]; then
504 USE_STAGING_IMAGES=""
506 while [ $# -gt 0 ] && [[ "$1" != "--"* ]]; do
507 USE_STAGING_IMAGES=$USE_STAGING_IMAGES" "$1
508 if [[ "$AVAILABLE_IMAGES_OVERRIDE" != *"$1"* ]]; then
510 if [ -z "$paramerror_str" ]; then
511 paramerror_str="App name $1 is not available for staging override for flag: '--use-staging-image'"
517 if [ -z "$USE_STAGING_IMAGES" ]; then
519 if [ -z "$paramerror_str" ]; then
520 paramerror_str="No app name found for flag: '--use-staging-image'"
523 echo "Option set - Overriding with staging images for app(s):"$USE_STAGING_IMAGES
527 if [ $paramerror -eq 0 ]; then
528 if [ "$1" == "--use-release-image" ]; then
529 USE_RELEASE_IMAGES=""
531 while [ $# -gt 0 ] && [[ "$1" != "--"* ]]; do
532 USE_RELEASE_IMAGES=$USE_RELEASE_IMAGES" "$1
533 if [[ "$AVAILABLE_IMAGES_OVERRIDE" != *"$1"* ]]; then
535 if [ -z "$paramerror_str" ]; then
536 paramerror_str="App name $1 is not available for release override for flag: '--use-release-image'"
542 if [ -z "$USE_RELEASE_IMAGES" ]; then
544 if [ -z "$paramerror_str" ]; then
545 paramerror_str="No app name found for flag: '--use-release-image'"
548 echo "Option set - Overriding with release images for app(s):"$USE_RELEASE_IMAGES
552 if [ $paramerror -eq 0 ]; then
553 if [ "$1" == "--image-repo" ]; then
558 if [ -z "$paramerror_str" ]; then
559 paramerror_str="No image repo url found for : '--image-repo'"
562 echo "Option set - Image repo url: "$1
568 if [ $paramerror -eq 0 ]; then
569 if [ "$1" == "--repo-policy" ]; then
574 if [ -z "$paramerror_str" ]; then
575 paramerror_str="No policy found for : '--repo-policy'"
578 if [ "$1" == "local" ] || [ "$1" == "remote" ]; then
579 echo "Option set - Image repo policy: "$1
584 if [ -z "$paramerror_str" ]; then
585 paramerror_str="Repo policy shall be 'local' or 'remote'"
591 if [ $paramerror -eq 0 ]; then
592 if [ "$1" == "--cluster-timeout" ]; then
597 if [ -z "$paramerror_str" ]; then
598 paramerror_str="No timeout value found for : '--cluster-timeout'"
601 #Check if positive int
602 case ${CLUSTER_TIME_OUT#[+]} in
605 if [ -z "$paramerror_str" ]; then
606 paramerror_str="Value for '--cluster-timeout' not an int : "$CLUSTER_TIME_OUT
611 echo "Option set - Cluster timeout: "$1
617 if [ $paramerror -eq 0 ]; then
618 if [ "$1" == "--override" ]; then
620 TEST_ENV_VAR_FILE_OVERRIDE=$1
623 if [ -z "$paramerror_str" ]; then
624 paramerror_str="No env file found for flag: '--override'"
627 if [ ! -f $TEST_ENV_VAR_FILE_OVERRIDE ]; then
629 if [ -z "$paramerror_str" ]; then
630 paramerror_str="File for '--override' does not exist : "$TEST_ENV_VAR_FILE_OVERRIDE
633 echo "Option set - Override env from: "$1
639 if [ $paramerror -eq 0 ]; then
640 if [ "$1" == "--pre-clean" ]; then
642 echo "Option set - Pre-clean of kube/docker resouces"
647 if [ $paramerror -eq 0 ]; then
648 if [ "$1" == "--print-stats" ]; then
649 PRINT_CURRENT_STATS=1
650 echo "Option set - Print stats"
659 if [ $paramerror -eq 0 ] && [ $# -gt 0 ]; then
661 if [ -z "$paramerror_str" ]; then
662 paramerror_str="Unknown parameter(s): "$@
666 if [ $paramerror -eq 1 ]; then
667 echo -e $RED"Incorrect arg list: "$paramerror_str$ERED
672 # sourcing the selected env variables for the test case
673 if [ -f "$TEST_ENV_VAR_FILE" ]; then
674 echo -e $BOLD"Sourcing env vars from: "$TEST_ENV_VAR_FILE$EBOLD
676 if [ ! -z "$TEST_ENV_VAR_FILE_OVERRIDE" ]; then
677 echo -e $BOLD"Sourcing override env vars from: "$TEST_ENV_VAR_FILE_OVERRIDE$EBOLD
678 . $TEST_ENV_VAR_FILE_OVERRIDE
681 if [ -z "$TEST_ENV_PROFILE" ] || [ -z "$SUPPORTED_PROFILES" ]; then
682 echo -e $YELLOW"This test case may not work with selected test env file. TEST_ENV_PROFILE is missing in test_env file or SUPPORTED_PROFILES is missing in test case file"$EYELLOW
685 for prof in $SUPPORTED_PROFILES; do
686 if [ "$TEST_ENV_PROFILE" == "$prof" ]; then
687 echo -e $GREEN"Test case supports the selected test env file"$EGREEN
691 if [ $found_profile -ne 1 ]; then
692 echo -e $RED"Test case does not support the selected test env file"$ERED
693 echo "Profile: "$TEST_ENV_PROFILE" Supported profiles: "$SUPPORTED_PROFILES
694 echo -e $RED"Exiting...."$ERED
699 echo -e $RED"Selected env var file does not exist: "$TEST_ENV_VAR_FILE$ERED
700 echo " Select one of following env var file matching the intended target of the test"
701 echo " Restart the test using the flag '--env-file <path-to-env-file>"
702 ls $AUTOTEST_HOME/../common/test_env* | indent1
706 #This var need be preserved from the command line option, if set, when env var is sourced.
707 if [ ! -z "$TMP_RIC_SIM_PREFIX" ]; then
708 RIC_SIM_PREFIX=$TMP_RIC_SIM_PREFIX
711 if [ -z "$PROJECT_IMAGES_APP_NAMES" ]; then
712 echo -e $RED"Var PROJECT_IMAGES_APP_NAMES must be defined in: "$TEST_ENV_VAR_FILE $ERED
716 if [[ $SUPPORTED_RUNMODES != *"$RUNMODE"* ]]; then
717 echo -e $RED"This test script does not support RUNMODE $RUNMODE"$ERED
718 echo "Supported RUNMODEs: "$SUPPORTED_RUNMODES
722 # Choose list of included apps depending on run-mode
723 if [ $RUNMODE == "KUBE" ]; then
724 INCLUDED_IMAGES=$KUBE_INCLUDED_IMAGES
726 INCLUDED_IMAGES=$DOCKER_INCLUDED_IMAGES
730 # auto adding system apps
731 echo -e $BOLD"Auto adding system apps"$EBOLD
732 if [ $RUNMODE == "KUBE" ]; then
733 INCLUDED_IMAGES=$INCLUDED_IMAGES" "$TESTENV_KUBE_SYSTEM_APPS
734 TMP_APPS=$TESTENV_KUBE_SYSTEM_APPS
736 INCLUDED_IMAGES=$INCLUDED_IMAGES" "$TESTENV_DOCKER_SYSTEM_APPS
737 TMP_APPS=$TESTENV_DOCKER_SYSTEM_APPS
739 if [ ! -z "$TMP_APPS" ]; then
740 for iapp in "$TMP_APPS"; do
741 file_pointer=$(echo $iapp | tr '[:upper:]' '[:lower:]')
742 file_pointer="../common/"$file_pointer"_api_functions.sh"
743 echo " Auto-adding system app $iapp. Sourcing $file_pointer"
751 # Check needed installed sw
753 if [ $? -ne 0 ] || [ -z tmp ]; then
754 echo -e $RED"python3 is required to run the test environment, pls install"$ERED
758 if [ $? -ne 0 ] || [ -z tmp ]; then
759 echo -e $RED"docker is required to run the test environment, pls install"$ERED
763 tmp=$(which docker-compose)
764 if [ $? -ne 0 ] || [ -z tmp ]; then
765 if [ $RUNMODE == "DOCKER" ]; then
766 echo -e $RED"docker-compose is required to run the test environment, pls install"$ERED
770 if [ $RUNMODE == "DOCKER" ]; then
771 tmp=$(docker-compose version | grep -i 'Docker Compose version')
772 if [[ "$tmp" == *'v2'* ]]; then
773 echo -e $RED"docker-compose is using docker-compose version 2"$ERED
774 echo -e $RED"The test environment only support version 1"$ERED
775 echo -e $RED"Disable version 2 by cmd 'docker-compose disable-v2' and re-run the script "$ERED
781 if [ $? -ne 0 ] || [ -z tmp ]; then
782 if [ $RUNMODE == "KUBE" ]; then
783 echo -e $RED"kubectl is required to run the test environment in kubernetes mode, pls install"$ERED
787 if [ $RUNMODE == "KUBE" ]; then
788 res=$(kubectl cluster-info 2>&1)
789 if [ $? -ne 0 ]; then
790 echo -e "$BOLD$RED############################################# $ERED$EBOLD"
791 echo -e $BOLD$RED"Command 'kubectl cluster-info' returned error $ERED$EBOLD"
792 echo -e "$BOLD$RED############################################# $ERED$EBOLD"
794 echo "kubectl response:"
797 echo "This script may have been started with user with no permission to run kubectl"
798 echo "Try running with 'sudo' or set 'KUBECONFIG'"
799 echo "Do either 1, 2 or 3 "
803 echo -e $BOLD"sudo <test-script-and-parameters>"$EBOLD
806 echo "Export KUBECONFIG and pass env to sudo - (replace user)"
807 echo -e $BOLD"export KUBECONFIG='/home/<user>/.kube/config'"$EBOLD
808 echo -e $BOLD"sudo -E <test-script-and-parameters>"$EBOLD
811 echo "Set KUBECONFIG inline (replace user)"
812 echo -e $BOLD"sudo KUBECONFIG='/home/<user>/.kube/config' <test-script-and-parameters>"$EBOLD
819 echo -e $BOLD"Checking configured image setting for this test case"$EBOLD
821 #Temp var to check for image variable name errors
823 #Create a file with image info for later printing as a table
824 image_list_file="./tmp/.image-list"
825 echo -e "Application\tApp short name\tImage\ttag\ttag-switch" > $image_list_file
827 # Check if image env var is set and if so export the env var with image to use (used by docker compose files)
828 # arg: <app-short-name> <target-variable-name> <image-variable-name> <image-tag-variable-name> <tag-suffix> <image name>
829 __check_and_create_image_var() {
831 if [ $# -ne 6 ]; then
832 echo "Expected arg: <app-short-name> <target-variable-name> <image-variable-name> <image-tag-variable-name> <tag-suffix> <image name>"
837 __check_included_image $1
838 if [ $? -ne 0 ]; then
839 echo -e "$6\t$1\t<image-excluded>\t<no-tag>" >> $image_list_file
840 # Image is excluded since the corresponding app is not used in this test
844 #Create var from the input var names
849 optional_image_repo_target=""
851 if [ -z $image ]; then
852 __check_ignore_image $1
853 if [ $? -eq 0 ]; then
856 app_ds="<app ignored>"
858 echo -e "$app_ds\t$1\t<image-ignored>\t<no-tag>" >> $image_list_file
859 # Image is ignored since the corresponding the images is not set in the env file
860 __remove_included_image $1 # Remove the image from the list of included images
863 echo -e $RED"\$"$3" not set in $TEST_ENV_VAR_FILE"$ERED
866 tmp=$tmp"<no-image>\t"
869 optional_image_repo_target=$image
871 #Add repo depending on image type
872 if [ "$5" == "REMOTE_RELEASE" ]; then
873 image=$NEXUS_RELEASE_REPO$image
875 if [ "$5" == "REMOTE" ]; then
876 image=$NEXUS_STAGING_REPO$image
878 if [ "$5" == "REMOTE_SNAPSHOT" ]; then
879 image=$NEXUS_SNAPSHOT_REPO$image
881 if [ "$5" == "REMOTE_PROXY" ]; then
882 image=$NEXUS_PROXY_REPO$image
884 if [ "$5" == "REMOTE_RELEASE_ONAP" ]; then
885 image=$NEXUS_RELEASE_REPO_ONAP$image
887 if [ "$5" == "REMOTE_RELEASE_ORAN" ]; then
888 image=$NEXUS_RELEASE_REPO_ORAN$image
890 #No nexus repo added for local images, tag: LOCAL
894 echo -e $RED"\$"$tmptag" not set in $TEST_ENV_VAR_FILE"$ERED
902 echo -e "$tmp" >> $image_list_file
904 export "${2}"=$image":"$tag #Note, this var may be set to the value of the target value below in __check_and_pull_image
906 remote_or_local_push=false
907 if [ ! -z "$IMAGE_REPO_ADR" ] && [[ $5 != *"PROXY"* ]]; then
908 if [ $5 == "LOCAL" ]; then
909 remote_or_local_push=true
911 if [[ $5 == *"REMOTE"* ]]; then
912 if [ "$IMAGE_REPO_POLICY" == "remote" ]; then
913 remote_or_local_push=true
917 if $remote_or_local_push; then # Only re-tag and push images according to policy, if repo is given
918 export "${2}_SOURCE"=$image":"$tag #Var to keep the actual source image
919 if [[ $optional_image_repo_target == *"/"* ]]; then # Replace all / with _ for images to push to external repo
920 optional_image_repo_target_tmp=${optional_image_repo_target//\//_}
921 optional_image_repo_target=$optional_image_repo_target_tmp
923 export "${2}_TARGET"=$IMAGE_REPO_ADR"/"$optional_image_repo_target":"$tag #Create image + tag for optional image repo - pushed later if needed
925 export "${2}_SOURCE"=""
926 export "${2}_TARGET"=""
930 # Check if app uses image included in this test run
931 # Returns 0 if image is included, 1 if not
932 __check_included_image() {
933 for im in $INCLUDED_IMAGES; do
934 if [ "$1" == "$im" ]; then
941 # Check if app uses a project image
942 # Returns 0 if image is included, 1 if not
943 __check_project_image() {
944 for im in $PROJECT_IMAGES; do
945 if [ "$1" == "$im" ]; then
952 # Check if app uses image built by the test script
953 # Returns 0 if image is included, 1 if not
954 __check_image_local_build() {
955 for im in $LOCAL_IMAGE_BUILD; do
956 if [ "$1" == "$im" ]; then
963 # Check if app image is conditionally ignored in this test run
964 # Returns 0 if image is conditionally ignored, 1 if not
965 __check_ignore_image() {
966 for im in $CONDITIONALLY_IGNORED_IMAGES; do
967 if [ "$1" == "$im" ]; then
974 # Removed image from included list of included images
975 # Used when an image is marked as conditionally ignored
976 __remove_included_image() {
978 for im in $INCLUDED_IMAGES; do
979 if [ "$1" != "$im" ]; then
980 tmp_img_rem_list=$tmp_img_rem_list" "$im
983 INCLUDED_IMAGES=$tmp_img_rem_list
987 # Check if app is included in the prestarted set of apps
988 # Returns 0 if image is included, 1 if not
989 __check_prestarted_image() {
990 for im in $KUBE_PRESTARTED_IMAGES; do
991 if [ "$1" == "$im" ]; then
998 # Check if an app shall use a local image, based on the cmd parameters
999 __check_image_local_override() {
1000 for im in $USE_LOCAL_IMAGES; do
1001 if [ "$1" == "$im" ]; then
1008 # Check if app uses image override
1009 # Returns the image/tag suffix LOCAL for local image or REMOTE/REMOTE_RELEASE/REMOTE_SNAPSHOT for staging/release/snapshot image
1010 __check_image_override() {
1012 for im in $ORAN_IMAGES_APP_NAMES; do
1013 if [ "$1" == "$im" ]; then
1014 echo "REMOTE_RELEASE_ORAN"
1019 for im in $ONAP_IMAGES_APP_NAMES; do
1020 if [ "$1" == "$im" ]; then
1021 echo "REMOTE_RELEASE_ONAP"
1027 for im in $PROJECT_IMAGES_APP_NAMES; do
1028 if [ "$1" == "$im" ]; then
1033 if [ $found -eq 0 ]; then
1039 if [ $IMAGE_CATEGORY == "RELEASE" ]; then
1040 suffix="REMOTE_RELEASE"
1042 if [ $IMAGE_CATEGORY == "DEV" ]; then
1046 for im in $USE_STAGING_IMAGES; do
1047 if [ "$1" == "$im" ]; then
1052 for im in $USE_RELEASE_IMAGES; do
1053 if [ "$1" == "$im" ]; then
1054 suffix="REMOTE_RELEASE"
1058 for im in $USE_SNAPSHOT_IMAGES; do
1059 if [ "$1" == "$im" ]; then
1060 suffix="REMOTE_SNAPSHOT"
1064 for im in $USE_LOCAL_IMAGES; do
1065 if [ "$1" == "$im" ]; then
1071 if [ $CTR -gt 1 ]; then
1077 # Function to re-tag and image and push to another image repo
1078 __retag_and_push_image() {
1079 if [ ! -z "$IMAGE_REPO_ADR" ]; then
1080 source_image="${!1}"
1081 trg_var_name=$1_"TARGET" # This var is created in func __check_and_create_image_var
1082 target_image="${!trg_var_name}"
1084 if [ -z $target_image ]; then
1085 return 0 # Image with no target shall not be pushed
1088 echo -ne " Attempt to re-tag image to: ${BOLD}${target_image}${EBOLD}${SAMELINE}"
1089 tmp=$(docker image tag $source_image ${target_image} )
1090 if [ $? -ne 0 ]; then
1091 docker stop $tmp &> ./tmp/.dockererr
1094 echo -e " Attempt to re-tag image to: ${BOLD}${target_image}${EBOLD} - ${RED}Failed${ERED}"
1095 cat ./tmp/.dockererr
1098 echo -e " Attempt to re-tag image to: ${BOLD}${target_image}${EBOLD} - ${GREEN}OK${EGREEN}"
1100 echo -ne " Attempt to push re-tagged image: ${BOLD}${target_image}${EBOLD}${SAMELINE}"
1101 tmp=$(docker push ${target_image} )
1102 if [ $? -ne 0 ]; then
1103 docker stop $tmp &> ./tmp/.dockererr
1106 echo -e " Attempt to push re-tagged image: ${BOLD}${target_image}${EBOLD} - ${RED}Failed${ERED}"
1107 cat ./tmp/.dockererr
1110 echo -e " Attempt to push re-tagged image: ${BOLD}${target_image}${EBOLD} - ${GREEN}OK${EGREEN}"
1112 export "${1}"=$target_image
1117 #Function to check if image exist and stop+remove the container+pull new images as needed
1118 #args <script-start-arg> <descriptive-image-name> <container-base-name> <image-with-tag-var-name>
1119 __check_and_pull_image() {
1121 source_image="${!4}"
1123 echo -e " Checking $BOLD$2$EBOLD container(s) with basename: $BOLD$3$EBOLD using image: $BOLD$source_image$EBOLD"
1124 format_string="\"{{.Repository}}\\t{{.Tag}}\\t{{.CreatedSince}}\\t{{.Size}}\""
1125 tmp_im=$(docker images --format $format_string $source_image)
1127 if [ $1 == "local" ]; then
1128 if [ -z "$tmp_im" ]; then
1129 echo -e " "$2" (local image): \033[1m"$source_image"\033[0m $RED does not exist in local registry, need to be built (or manually pulled)"$ERED
1133 echo -e " "$2" (local image): \033[1m"$source_image"\033[0m "$GREEN"OK"$EGREEN
1135 elif [ $1 == "remote" ] || [ $1 == "remote-remove" ]; then
1136 if [ $1 == "remote-remove" ]; then
1137 if [ $RUNMODE == "DOCKER" ]; then
1138 echo -ne " Attempt to stop and remove container(s), if running - ${SAMELINE}"
1139 tmp=$(docker ps -aq --filter name=${3} --filter network=${DOCKER_SIM_NWNAME})
1140 if [ $? -eq 0 ] && [ ! -z "$tmp" ]; then
1141 docker stop $tmp &> ./tmp/.dockererr
1142 if [ $? -ne 0 ]; then
1145 echo -e $RED" Container(s) could not be stopped - try manual stopping the container(s)"$ERED
1146 cat ./tmp/.dockererr
1150 echo -ne " Attempt to stop and remove container(s), if running - "$GREEN"stopped"$EGREEN"${SAMELINE}"
1151 tmp=$(docker ps -aq --filter name=${3} --filter network=${DOCKER_SIM_NWNAME}) &> /dev/null
1152 if [ $? -eq 0 ] && [ ! -z "$tmp" ]; then
1153 docker rm $tmp &> ./tmp/.dockererr
1154 if [ $? -ne 0 ]; then
1157 echo -e $RED" Container(s) could not be removed - try manual removal of the container(s)"$ERED
1158 cat ./tmp/.dockererr
1162 echo -e " Attempt to stop and remove container(s), if running - "$GREEN"stopped removed"$EGREEN
1168 if [ -z "$tmp_im" ]; then
1169 echo -ne " Pulling image${SAMELINE}"
1170 out=$(docker pull $source_image)
1171 if [ $? -ne 0 ]; then
1173 echo -e " Pulling image -$RED could not be pulled"$ERED
1175 echo $out > ./tmp/.dockererr
1179 echo $out > ./tmp/.dockererr
1180 if [[ $out == *"up to date"* ]]; then
1181 echo -e " Pulling image -$GREEN Image is up to date $EGREEN"
1182 elif [[ $out == *"Downloaded newer image"* ]]; then
1183 echo -e " Pulling image -$GREEN Newer image pulled $EGREEN"
1185 echo -e " Pulling image -$GREEN Pulled $EGREEN"
1188 echo -e " Pulling image -$GREEN OK $EGREEN(exists in local repository)"
1192 __retag_and_push_image $4
1197 setup_testenvironment() {
1198 # Check that image env setting are available
1201 # Image var setup for all project images included in the test
1202 for imagename in $APP_SHORT_NAMES; do
1203 __check_included_image $imagename
1205 __check_project_image $imagename
1207 if [ $incl -eq 0 ]; then
1208 if [ $proj -eq 0 ]; then
1209 IMAGE_SUFFIX=$(__check_image_override $imagename)
1210 if [ $? -ne 0 ]; then
1211 echo -e $RED"Image setting from cmd line not consistent for $imagename."$ERED
1217 # A function name is created from the app short name
1218 # for example app short name 'ECS' -> produce the function
1219 # name __ECS_imagesetup
1220 # This function is called and is expected to exist in the imported
1221 # file for the ecs test functions
1222 # The resulting function impl will call '__check_and_create_image_var' function
1223 # with appropriate parameters
1224 # If the image suffix is none, then the component decides the suffix
1225 function_pointer="__"$imagename"_imagesetup"
1226 $function_pointer $IMAGE_SUFFIX
1230 #Errors in image setting - exit
1231 if [ $IMAGE_ERR -ne 0 ]; then
1235 #Print a tables of the image settings
1236 echo -e $BOLD"Images configured for start arg: "$START_ARG $EBOLD
1237 column -t -s $'\t' $image_list_file | indent1
1241 #Set the SIM_GROUP var
1242 echo -e $BOLD"Setting var to main dir of all container/simulator scripts"$EBOLD
1243 if [ -z "$SIM_GROUP" ]; then
1244 SIM_GROUP=$AUTOTEST_HOME/../simulator-group
1245 if [ ! -d $SIM_GROUP ]; then
1246 echo "Trying to set env var SIM_GROUP to dir 'simulator-group' in the nontrtric repo, but failed."
1247 echo -e $RED"Please set the SIM_GROUP manually in the applicable $TEST_ENV_VAR_FILE"$ERED
1250 echo " SIM_GROUP auto set to: " $SIM_GROUP
1252 elif [ $SIM_GROUP = *simulator_group ]; then
1253 echo -e $RED"Env var SIM_GROUP does not seem to point to dir 'simulator-group' in the repo, check $TEST_ENV_VAR_FILE"$ERED
1256 echo " SIM_GROUP env var already set to: " $SIM_GROUP
1261 #Temp var to check for image pull errors
1264 # The following sequence pull the configured images
1267 echo -e $BOLD"Pulling configured images, if needed"$EBOLD
1268 if [ ! -z "$IMAGE_REPO_ADR" ] && [ $IMAGE_REPO_POLICY == "local" ]; then
1269 echo -e $YELLOW" Excluding all remote image check/pull when running with image repo: $IMAGE_REPO_ADR and image policy $IMAGE_REPO_POLICY"$EYELLOW
1271 for imagename in $APP_SHORT_NAMES; do
1272 __check_included_image $imagename
1274 __check_project_image $imagename
1276 if [ $incl -eq 0 ]; then
1277 if [ $proj -eq 0 ]; then
1278 START_ARG_MOD=$START_ARG
1279 __check_image_local_override $imagename
1280 if [ $? -eq 1 ]; then
1281 START_ARG_MOD="local"
1284 START_ARG_MOD=$START_ARG
1286 __check_image_local_build $imagename
1287 #No pull of images built locally
1288 if [ $? -ne 0 ]; then
1289 # A function name is created from the app short name
1290 # for example app short name 'HTTPPROXY' -> produce the function
1291 # name __HTTPPROXY_imagesetup
1292 # This function is called and is expected to exist in the imported
1293 # file for the httpproxy test functions
1294 # The resulting function impl will call '__check_and_pull_image' function
1295 # with appropriate parameters
1296 function_pointer="__"$imagename"_imagepull"
1297 $function_pointer $START_ARG_MOD $START_ARG
1300 echo -e $YELLOW" Excluding $imagename image from image check/pull"$EYELLOW
1305 #Errors in image setting - exit
1306 if [ $IMAGE_ERR -ne 0 ]; then
1308 echo "#################################################################################################"
1309 echo -e $RED"One or more images could not be pulled or containers using the images could not be stopped/removed"$ERED
1310 echo -e $RED"Or local image, overriding remote image, does not exist"$ERED
1311 if [ $IMAGE_CATEGORY == "DEV" ]; then
1313 echo -e $RED"Note that SNAPSHOT and staging images may be purged from nexus after a certain period."$ERED
1314 echo -e $RED"In addition, the image may not have been updated in the current release so no SNAPSHOT or staging image exists"$ERED
1315 echo -e $RED"In these cases, switch to use a released image instead, use the flag '--use-release-image <App-short-name>'"$ERED
1316 echo -e $RED"Use the 'App-short-name' for the applicable image from the above table: 'Images configured for start arg'."$ERED
1318 echo "#################################################################################################"
1325 echo -e $BOLD"Building images needed for test"$EBOLD
1327 for imagename in $APP_SHORT_NAMES; do
1328 cd $AUTOTEST_HOME #Always reset to orig dir
1329 __check_image_local_build $imagename
1330 if [ $? -eq 0 ]; then
1331 __check_included_image $imagename
1332 if [ $? -eq 0 ]; then
1333 # A function name is created from the app short name
1334 # for example app short name 'MR' -> produce the function
1335 # name __MR_imagebuild
1336 # This function is called and is expected to exist in the imported
1337 # file for the mr test functions
1338 # The resulting function impl shall build the imagee
1339 function_pointer="__"$imagename"_imagebuild"
1343 echo -e $YELLOW" Excluding image for app $imagename from image build"$EYELLOW
1348 cd $AUTOTEST_HOME # Just to make sure...
1352 # Create a table of the images used in the script - from local repo
1353 echo -e $BOLD"Local docker registry images used in this test script"$EBOLD
1355 docker_tmp_file=./tmp/.docker-images-table
1356 format_string="{{.Repository}}\\t{{.Tag}}\\t{{.CreatedSince}}\\t{{.Size}}\\t{{.CreatedAt}}"
1357 echo -e "Application\tRepository\tTag\tCreated since\tSize\tCreated at" > $docker_tmp_file
1359 for imagename in $APP_SHORT_NAMES; do
1360 __check_included_image $imagename
1361 if [ $? -eq 0 ]; then
1362 # Only print image data if image repo is null, or if image repo is set and image is local
1364 if [ -z "$IMAGE_REPO_ADR" ]; then
1367 __check_image_local_build $imagename
1368 if [ $? -eq 0 ]; then
1372 if [ $print_image_data -eq 1 ]; then
1373 # A function name is created from the app short name
1374 # for example app short name 'MR' -> produce the function
1375 # name __MR_imagebuild
1376 # This function is called and is expected to exist in the imported
1377 # file for the mr test functions
1378 # The resulting function impl shall build the imagee
1379 function_pointer="__"$imagename"_image_data"
1380 $function_pointer "$format_string" $docker_tmp_file
1385 column -t -s $'\t' $docker_tmp_file | indent1
1389 if [ ! -z "$IMAGE_REPO_ADR" ]; then
1391 # Create a table of the images used in the script - from remote repo
1392 echo -e $BOLD"Remote repo images used in this test script"$EBOLD
1393 echo -e $YELLOW"-- Note: These image will be pulled when the container starts. Images not managed by the test engine --"$EYELLOW
1395 docker_tmp_file=./tmp/.docker-images-table
1396 format_string="{{.Repository}}\\t{{.Tag}}"
1397 echo -e "Application\tRepository\tTag" > $docker_tmp_file
1399 for imagename in $APP_SHORT_NAMES; do
1400 __check_included_image $imagename
1401 if [ $? -eq 0 ]; then
1402 # Only print image data if image repo is null, or if image repo is set and image is local
1403 __check_image_local_build $imagename
1404 if [ $? -ne 0 ]; then
1405 # A function name is created from the app short name
1406 # for example app short name 'MR' -> produce the function
1407 # name __MR_imagebuild
1408 # This function is called and is expected to exist in the imported
1409 # file for the mr test functions
1410 # The resulting function impl shall build the imagee
1411 function_pointer="__"$imagename"_image_data"
1412 $function_pointer "$format_string" $docker_tmp_file
1417 column -t -s $'\t' $docker_tmp_file | indent1
1422 if [ $RUNMODE == "KUBE" ]; then
1424 echo "================================================================================="
1425 echo "================================================================================="
1427 if [ -z "$IMAGE_REPO_ADR" ]; then
1428 echo -e $YELLOW" The image pull policy is set to 'Never' - assuming a local image repo is available for all images"$EYELLOW
1429 echo -e " This setting only works on single node clusters on the local machine"
1430 echo -e " It does not work with multi-node clusters or remote clusters. "
1431 export KUBE_IMAGE_PULL_POLICY="Never"
1433 echo -e $YELLOW" The image pull policy is set to 'Always'"$EYELLOW
1434 echo -e " This setting work on local clusters, multi-node clusters and remote cluster. "
1435 echo -e " Only locally built images are managed. Remote images are always pulled from remote repos"
1436 echo -e " Pulling remote snapshot or staging images my in some case result in pulling newer image versions outside the control of the test engine"
1437 export KUBE_IMAGE_PULL_POLICY="Always"
1439 CLUSTER_IP=$(kubectl config view -o jsonpath={.clusters[0].cluster.server} | awk -F[/:] '{print $4}')
1440 echo -e $YELLOW" The cluster hostname/ip is: $CLUSTER_IP"$EYELLOW
1442 echo "================================================================================="
1443 echo "================================================================================="
1447 echo -e $BOLD"======================================================="$EBOLD
1448 echo -e $BOLD"== Common test setup completed - test script begins =="$EBOLD
1449 echo -e $BOLD"======================================================="$EBOLD
1452 for imagename in $APP_SHORT_NAMES; do
1453 __check_included_image $imagename
1455 __check_prestarted_image $imagename
1457 if [ $retcode_i -eq 0 ] || [ $retcode_p -eq 0 ]; then
1458 # A function name is created from the app short name
1459 # for example app short name 'RICMSIM' -> produce the function
1460 # name __RICSIM__initial_setup
1461 # This function is called and is expected to exist in the imported
1462 # file for the ricsim test functions
1463 # The resulting function impl shall perform initial setup of port, host etc
1465 function_pointer="__"$imagename"_initial_setup"
1472 # Function to print the test result, shall be the last cmd in a test script
1474 # (Function for test scripts)
1478 duration=$((TCTEST_END-TCTEST_START))
1480 echo "-------------------------------------------------------------------------------------------------"
1481 echo "------------------------------------- Test case: "$ATC
1482 echo "------------------------------------- Ended: "$(date)
1483 echo "-------------------------------------------------------------------------------------------------"
1484 echo "-- Description: "$TC_ONELINE_DESCR
1485 echo "-- Execution time: " $duration " seconds"
1486 echo "-- Used env file: "$TEST_ENV_VAR_FILE
1487 echo "-------------------------------------------------------------------------------------------------"
1488 echo "------------------------------------- RESULTS"
1492 if [ $RES_DEVIATION -gt 0 ]; then
1493 echo "Test case deviations"
1494 echo "===================================="
1498 echo "Timer measurement in the test script"
1499 echo "===================================="
1500 column -t -s $'\t' $TIMER_MEASUREMENTS
1503 total=$((RES_PASS+RES_FAIL))
1504 if [ $RES_TEST -eq 0 ]; then
1505 echo -e "\033[1mNo tests seem to have been executed. Check the script....\033[0m"
1506 echo -e "\033[31m\033[1m ___ ___ ___ ___ ___ _____ ___ _ ___ _ _ _ ___ ___ \033[0m"
1507 echo -e "\033[31m\033[1m/ __|/ __| _ \_ _| _ \_ _| | __/_\ |_ _| | | | | | _ \ __|\033[0m"
1508 echo -e "\033[31m\033[1m\__ \ (__| /| || _/ | | | _/ _ \ | || |_| |_| | / _| \033[0m"
1509 echo -e "\033[31m\033[1m|___/\___|_|_\___|_| |_| |_/_/ \_\___|____\___/|_|_\___|\033[0m"
1510 elif [ $total != $RES_TEST ]; then
1511 echo -e "\033[1mTotal number of tests does not match the sum of passed and failed tests. Check the script....\033[0m"
1512 echo -e "\033[31m\033[1m ___ ___ ___ ___ ___ _____ ___ _ ___ _ _ _ ___ ___ \033[0m"
1513 echo -e "\033[31m\033[1m/ __|/ __| _ \_ _| _ \_ _| | __/_\ |_ _| | | | | | _ \ __|\033[0m"
1514 echo -e "\033[31m\033[1m\__ \ (__| /| || _/ | | | _/ _ \ | || |_| |_| | / _| \033[0m"
1515 echo -e "\033[31m\033[1m|___/\___|_|_\___|_| |_| |_/_/ \_\___|____\___/|_|_\___|\033[0m"
1516 elif [ $RES_CONF_FAIL -ne 0 ]; then
1517 echo -e "\033[1mOne or more configurations has failed. Check the script log....\033[0m"
1518 echo -e "\033[31m\033[1m ___ ___ ___ ___ ___ _____ ___ _ ___ _ _ _ ___ ___ \033[0m"
1519 echo -e "\033[31m\033[1m/ __|/ __| _ \_ _| _ \_ _| | __/_\ |_ _| | | | | | _ \ __|\033[0m"
1520 echo -e "\033[31m\033[1m\__ \ (__| /| || _/ | | | _/ _ \ | || |_| |_| | / _| \033[0m"
1521 echo -e "\033[31m\033[1m|___/\___|_|_\___|_| |_| |_/_/ \_\___|____\___/|_|_\___|\033[0m"
1522 elif [ $RES_PASS = $RES_TEST ]; then
1523 echo -e "All tests \033[32m\033[1mPASS\033[0m"
1524 echo -e "\033[32m\033[1m ___ _ ___ ___ \033[0m"
1525 echo -e "\033[32m\033[1m | _ \/_\ / __/ __| \033[0m"
1526 echo -e "\033[32m\033[1m | _/ _ \\__ \__ \\ \033[0m"
1527 echo -e "\033[32m\033[1m |_|/_/ \_\___/___/ \033[0m"
1530 # Update test suite counter
1531 if [ -f .tmp_tcsuite_pass_ctr ]; then
1532 tmpval=$(< .tmp_tcsuite_pass_ctr)
1534 echo $tmpval > .tmp_tcsuite_pass_ctr
1536 if [ -f .tmp_tcsuite_pass ]; then
1537 echo " - "$ATC " -- "$TC_ONELINE_DESCR" Execution time: "$duration" seconds" >> .tmp_tcsuite_pass
1539 #Create file with OK exit code
1540 echo "0" > "$AUTOTEST_HOME/.result$ATC.txt"
1542 echo -e "One or more tests with status \033[31m\033[1mFAIL\033[0m "
1543 echo -e "\033[31m\033[1m ___ _ ___ _ \033[0m"
1544 echo -e "\033[31m\033[1m | __/_\ |_ _| | \033[0m"
1545 echo -e "\033[31m\033[1m | _/ _ \ | || |__ \033[0m"
1546 echo -e "\033[31m\033[1m |_/_/ \_\___|____|\033[0m"
1548 # Update test suite counter
1549 if [ -f .tmp_tcsuite_fail_ctr ]; then
1550 tmpval=$(< .tmp_tcsuite_fail_ctr)
1552 echo $tmpval > .tmp_tcsuite_fail_ctr
1554 if [ -f .tmp_tcsuite_fail ]; then
1555 echo " - "$ATC " -- "$TC_ONELINE_DESCR" Execution time: "$duration" seconds" >> .tmp_tcsuite_fail
1559 echo "++++ Number of tests: "$RES_TEST
1560 echo "++++ Number of passed tests: "$RES_PASS
1561 echo "++++ Number of failed tests: "$RES_FAIL
1563 echo "++++ Number of failed configs: "$RES_CONF_FAIL
1565 echo "++++ Number of test case deviations: "$RES_DEVIATION
1567 echo "------------------------------------- Test case complete ---------------------------------"
1568 echo "-------------------------------------------------------------------------------------------------"
1572 #####################################################################
1573 ###### Functions for start, configuring, stoping, cleaning etc ######
1574 #####################################################################
1576 # Start timer for time measurement
1577 # args - (any args will be printed though)
1579 echo -e $BOLD"INFO(${BASH_LINENO[0]}): "${FUNCNAME[0]}"," $@ $EBOLD
1581 echo " Timer started: $(date)"
1584 # Print the value of the time (in seconds)
1585 # args - <timer message to print> - timer value and message will be printed both on screen
1586 # and in the timer measurement report
1588 echo -e $BOLD"INFO(${BASH_LINENO[0]}): "${FUNCNAME[0]}"," $@ $EBOLD
1589 if [ $# -lt 1 ]; then
1591 __print_err "need 1 or more args, <timer message to print>" $@
1594 duration=$(($SECONDS-$TC_TIMER))
1595 if [ $duration -eq 0 ]; then
1596 duration="<1 second"
1598 duration=$duration" seconds"
1600 echo " Timer duration :" $duration
1602 echo -e "${@:1} \t $duration" >> $TIMER_MEASUREMENTS
1605 # Print the value of the time (in seconds) and reset the timer
1606 # args - <timer message to print> - timer value and message will be printed both on screen
1607 # and in the timer measurement report
1608 print_and_reset_timer() {
1609 echo -e $BOLD"INFO(${BASH_LINENO[0]}): "${FUNCNAME[0]}"," $@ $EBOLD
1610 if [ $# -lt 1 ]; then
1612 __print_err "need 1 or more args, <timer message to print>" $@
1615 duration=$(($SECONDS-$TC_TIMER))" seconds"
1616 if [ $duration -eq 0 ]; then
1617 duration="<1 second"
1619 duration=$duration" seconds"
1621 echo " Timer duration :" $duration
1625 echo -e "${@:1} \t $duration" >> $TIMER_MEASUREMENTS
1628 # Print info about a deviations from intended tests
1629 # Each deviation counted is also printed in the testreport
1630 # args <deviation message to print>
1632 echo -e $BOLD"DEVIATION(${BASH_LINENO[0]}): "${FUNCNAME[0]} $EBOLD
1633 if [ $# -lt 1 ]; then
1635 __print_err "need 1 or more args, <deviation message to print>" $@
1639 echo -e $BOLD$YELLOW" Test case deviation: ${@:1}"$EYELLOW$EBOLD
1640 echo "Line: ${BASH_LINENO[0]} - ${@:1}" >> $DEVIATION_FILE
1641 __print_current_stats
1645 # Stop at first FAIL test case and take all logs - only for debugging/trouble shooting
1646 __check_stop_at_error() {
1647 if [ $STOP_AT_ERROR -eq 1 ]; then
1648 echo -e $RED"Test script configured to stop at first FAIL, taking all logs and stops"$ERED
1649 store_logs "STOP_AT_ERROR"
1655 # Stop and remove all containers
1657 # (Not for test scripts)
1658 __clean_containers() {
1660 echo -e $BOLD"Docker clean and stopping and removing all running containers, by container name"$EBOLD
1663 running_contr_file="./tmp/running_contr.txt"
1664 > $running_contr_file
1666 # Get list of all containers started by the test script
1667 for imagename in $APP_SHORT_NAMES; do
1668 docker ps -a --filter "label=nrttest_app=$imagename" --filter "network=$DOCKER_SIM_NWNAME" --format ' {{.Label "nrttest_dp"}}\n{{.Label "nrttest_app"}}\n{{.Names}}' >> $running_contr_file
1671 # Kill all containers started by the test env - to speed up shut down
1672 docker kill $(docker ps -a --filter "label=nrttest_app" --format '{{.Names}}') &> /dev/null
1674 tab_heading1="App display name"
1675 tab_heading2="App short name"
1676 tab_heading3="Container name"
1678 tab_heading1_len=${#tab_heading1}
1679 tab_heading2_len=${#tab_heading2}
1680 tab_heading3_len=${#tab_heading3}
1682 #Calc field lengths of each item in the list of containers
1684 if (( $cntr % 3 == 0 ));then
1685 if [ ${#p} -gt $tab_heading1_len ]; then
1686 tab_heading1_len=${#p}
1689 if (( $cntr % 3 == 1));then
1690 if [ ${#p} -gt $tab_heading2_len ]; then
1691 tab_heading2_len=${#p}
1694 if (( $cntr % 3 == 2));then
1695 if [ ${#p} -gt $tab_heading3_len ]; then
1696 tab_heading3_len=${#p}
1700 done <$running_contr_file
1702 let tab_heading1_len=tab_heading1_len+2
1703 while (( ${#tab_heading1} < $tab_heading1_len)); do
1704 tab_heading1="$tab_heading1"" "
1707 let tab_heading2_len=tab_heading2_len+2
1708 while (( ${#tab_heading2} < $tab_heading2_len)); do
1709 tab_heading2="$tab_heading2"" "
1712 let tab_heading3_len=tab_heading3_len+2
1713 while (( ${#tab_heading3} < $tab_heading3_len)); do
1714 tab_heading3="$tab_heading3"" "
1717 echo " $tab_heading1$tab_heading2$tab_heading3"" Actions"
1720 if (( $cntr % 3 == 0 ));then
1723 heading_len=$tab_heading1_len
1725 if (( $cntr % 3 == 1));then
1727 heading_len=$tab_heading2_len
1729 if (( $cntr % 3 == 2));then
1732 heading_len=$tab_heading3_len
1734 while (( ${#heading} < $heading_len)); do
1735 heading="$heading"" "
1738 if (( $cntr % 3 == 2));then
1739 echo -ne $row$SAMELINE
1740 echo -ne " $row ${GREEN}stopping...${EGREEN}${SAMELINE}"
1741 docker stop $(docker ps -qa --filter name=${contr} --filter network=$DOCKER_SIM_NWNAME) &> /dev/null
1742 echo -ne " $row ${GREEN}stopped removing...${EGREEN}${SAMELINE}"
1743 docker rm --force $(docker ps -qa --filter name=${contr} --filter network=$DOCKER_SIM_NWNAME) &> /dev/null
1744 echo -e " $row ${GREEN}stopped removed ${EGREEN}"
1747 done <$running_contr_file
1751 echo -e $BOLD" Removing docker network"$EBOLD
1752 TMP=$(docker network ls -q --filter name=$DOCKER_SIM_NWNAME)
1753 if [ "$TMP" == $DOCKER_SIM_NWNAME ]; then
1754 docker network rm $DOCKER_SIM_NWNAME | indent2
1755 if [ $? -ne 0 ]; then
1756 echo -e $RED" Cannot remove docker network. Manually remove or disconnect containers from $DOCKER_SIM_NWNAME"$ERED
1760 echo -e "$GREEN Done$EGREEN"
1762 echo -e $BOLD" Removing all unused docker neworks"$EBOLD
1763 docker network prune --force | indent2
1764 echo -e "$GREEN Done$EGREEN"
1766 echo -e $BOLD" Removing all unused docker volumes"$EBOLD
1767 docker volume prune --force | indent2
1768 echo -e "$GREEN Done$EGREEN"
1770 echo -e $BOLD" Removing all dangling/untagged docker images"$EBOLD
1771 docker rmi --force $(docker images -q -f dangling=true) &> /dev/null
1772 echo -e "$GREEN Done$EGREEN"
1775 CONTRS=$(docker ps | awk '$1 != "CONTAINER" { n++ }; END { print n+0 }')
1776 if [ $? -eq 0 ]; then
1777 if [ $CONTRS -ne 0 ]; then
1778 echo -e $RED"Containers running, may cause distubance to the test case"$ERED
1779 docker ps -a | indent1
1785 ###################################
1786 ### Functions for kube management
1787 ###################################
1789 # Get resource type for scaling
1790 # args: <resource-name> <namespace>
1791 __kube_get_resource_type() {
1792 kubectl get deployment $1 -n $2 1> /dev/null 2> ./tmp/kubeerr
1793 if [ $? -eq 0 ]; then
1797 kubectl get sts $1 -n $2 1> /dev/null 2> ./tmp/kubeerr
1798 if [ $? -eq 0 ]; then
1802 echo "unknown-resource-type"
1806 # Scale a kube resource to a specific count
1807 # args: <resource-type> <resource-name> <namespace> <target-count>
1808 # (Not for test scripts)
1810 echo -ne " Setting $1 $2 replicas=$4 in namespace $3"$SAMELINE
1811 kubectl scale $1 $2 -n $3 --replicas=$4 1> /dev/null 2> ./tmp/kubeerr
1812 if [ $? -ne 0 ]; then
1813 echo -e " Setting $1 $2 replicas=$4 in namespace $3 $RED Failed $ERED"
1815 echo " Message: $(<./tmp/kubeerr)"
1818 echo -e " Setting $1 $2 replicas=$4 in namespace $3 $GREEN OK $EGREEN"
1823 for i in {1..500}; do
1824 count=$(kubectl get $1/$2 -n $3 -o jsonpath='{.status.replicas}' 2> /dev/null)
1826 if [ -z "$count" ]; then
1827 #No value is sometimes returned for some reason, in case the resource has replica 0
1830 if [ $retcode -ne 0 ]; then
1831 echo -e "$RED Cannot fetch current replica count for $1 $2 in namespace $3 $ERED"
1836 if [ $count -ne $4 ]; then
1837 echo -ne " Waiting for $1 $2 replicas=$4 in namespace $3. Replicas=$count after $(($SECONDS-$TSTART)) seconds $SAMELINE"
1840 echo -e " Waiting for $1 $2 replicas=$4 in namespace $3. Replicas=$count after $(($SECONDS-$TSTART)) seconds"
1841 echo -e " Replicas=$4 after $(($SECONDS-$TSTART)) seconds $GREEN OK $EGREEN"
1847 echo -e "$RED Replica count did not reach target replicas=$4. Failed with replicas=$count $ERED"
1852 # Scale all kube resource sets to 0 in a namespace for resources having a certain lable and label-id
1853 # This function does not wait for the resource to reach 0
1854 # args: <namespace> <label-name> <label-id>
1855 # (Not for test scripts)
1856 __kube_scale_all_resources() {
1860 resources="deployment replicaset statefulset"
1861 for restype in $resources; do
1862 result=$(kubectl get $restype -n $namespace -o jsonpath='{.items[?(@.metadata.labels.'$labelname'=="'$labelid'")].metadata.name}')
1863 if [ $? -eq 0 ] && [ ! -z "$result" ]; then
1864 for resid in $result; do
1865 echo -ne " Ordered caling $restype $resid in namespace $namespace with label $labelname=$labelid to 0"$SAMELINE
1866 kubectl scale $restype $resid -n $namespace --replicas=0 1> /dev/null 2> ./tmp/kubeerr
1867 echo -e " Ordered scaling $restype $resid in namespace $namespace with label $labelname=$labelid to 0 $GREEN OK $EGREEN"
1873 # Scale all kube resource sets to 0 in a namespace for resources having a certain lable and an optional label-id
1874 # This function do wait for the resource to reach 0
1875 # args: <namespace> <label-name> [ <label-id> ]
1876 # (Not for test scripts)
1877 __kube_scale_and_wait_all_resources() {
1881 if [ -z "$3" ]; then
1882 echo " Attempt to scale - deployment replicaset statefulset - in namespace $namespace with label $labelname"
1884 echo " Attempt to scale - deployment replicaset statefulset - in namespace $namespace with label $labelname=$labelid"
1886 resources="deployment replicaset statefulset"
1888 while [ $scaled_all -ne 0 ]; do
1890 for restype in $resources; do
1891 if [ -z "$3" ]; then
1892 result=$(kubectl get $restype -n $namespace -o jsonpath='{.items[?(@.metadata.labels.'$labelname')].metadata.name}')
1894 result=$(kubectl get $restype -n $namespace -o jsonpath='{.items[?(@.metadata.labels.'$labelname'=="'$labelid'")].metadata.name}')
1896 if [ $? -eq 0 ] && [ ! -z "$result" ]; then
1897 for resid in $result; do
1898 echo -e " Ordered scaling $restype $resid in namespace $namespace with label $labelname=$labelid to 0"
1899 kubectl scale $restype $resid -n $namespace --replicas=0 1> /dev/null 2> ./tmp/kubeerr
1902 while [ $count -ne 0 ]; do
1903 count=$(kubectl get $restype $resid -n $namespace -o jsonpath='{.status.replicas}' 2> /dev/null)
1904 echo -ne " Scaling $restype $resid in namespace $namespace with label $labelname=$labelid to 0, current count=$count"$SAMELINE
1905 if [ $? -eq 0 ] && [ ! -z "$count" ]; then
1910 duration=$(($SECONDS-$T_START))
1911 if [ $duration -gt 100 ]; then
1912 #Forcring count 0, to avoid hanging for failed scaling
1917 echo -e " Scaled $restype $resid in namespace $namespace with label $labelname=$labelid to 0, current count=$count $GREEN OK $EGREEN"
1924 # Remove all kube resources in a namespace for resources having a certain label and label-id
1925 # This function wait until the resources are gone. Scaling to 0 must have been ordered previously
1926 # args: <namespace> <label-name> <label-id>
1927 # (Not for test scripts)
1928 __kube_delete_all_resources() {
1932 resources="deployments replicaset statefulset services pods configmaps persistentvolumeclaims persistentvolumes"
1933 deleted_resourcetypes=""
1934 for restype in $resources; do
1935 ns_flag="-n $namespace"
1936 ns_text="in namespace $namespace"
1937 if [ $restype == "persistentvolumes" ]; then
1941 result=$(kubectl get $restype $ns_flag -o jsonpath='{.items[?(@.metadata.labels.'$labelname'=="'$labelid'")].metadata.name}')
1942 if [ $? -eq 0 ] && [ ! -z "$result" ]; then
1943 deleted_resourcetypes=$deleted_resourcetypes" "$restype
1944 for resid in $result; do
1945 if [ $restype == "replicaset" ] || [ $restype == "statefulset" ]; then
1947 while [ $count -ne 0 ]; do
1948 count=$(kubectl get $restype $resid $ns_flag -o jsonpath='{.status.replicas}' 2> /dev/null)
1949 echo -ne " Scaling $restype $resid $ns_text with label $labelname=$labelid to 0, current count=$count"$SAMELINE
1950 if [ $? -eq 0 ] && [ ! -z "$count" ]; then
1956 echo -e " Scaled $restype $resid $ns_text with label $labelname=$labelid to 0, current count=$count $GREEN OK $EGREEN"
1958 echo -ne " Deleting $restype $resid $ns_text with label $labelname=$labelid "$SAMELINE
1959 kubectl delete $restype $resid $ns_flag 1> /dev/null 2> ./tmp/kubeerr
1960 if [ $? -eq 0 ]; then
1961 echo -e " Deleted $restype $resid $ns_text with label $labelname=$labelid $GREEN OK $EGREEN"
1963 echo -e " Deleted $restype $resid $ns_text with label $labelname=$labelid $GREEN Does not exist - OK $EGREEN"
1969 if [ ! -z "$deleted_resourcetypes" ]; then
1970 for restype in $deleted_resources; do
1971 ns_flag="-n $namespace"
1972 ns_text="in namespace $namespace"
1973 if [ $restype == "persistentvolumes" ]; then
1977 echo -ne " Waiting for $restype $ns_text with label $labelname=$labelid to be deleted..."$SAMELINE
1980 while [ ! -z "$result" ]; do
1982 result=$(kubectl get $restype $ns_flag -o jsonpath='{.items[?(@.metadata.labels.'$labelname'=="'$labelid'")].metadata.name}')
1983 echo -ne " Waiting for $restype $ns_text with label $labelname=$labelid to be deleted...$(($SECONDS-$T_START)) seconds "$SAMELINE
1984 if [ -z "$result" ]; then
1985 echo -e " Waiting for $restype $ns_text with label $labelname=$labelid to be deleted...$(($SECONDS-$T_START)) seconds $GREEN OK $EGREEN"
1986 elif [ $(($SECONDS-$T_START)) -gt 300 ]; then
1987 echo -e " Waiting for $restype $ns_text with label $labelname=$labelid to be deleted...$(($SECONDS-$T_START)) seconds $RED Failed $ERED"
1995 # Creates a namespace if it does not exists
1997 # (Not for test scripts)
1998 __kube_create_namespace() {
2000 #Check if test namespace exists, if not create it
2001 kubectl get namespace $1 1> /dev/null 2> ./tmp/kubeerr
2002 if [ $? -ne 0 ]; then
2003 echo -ne " Creating namespace "$1 $SAMELINE
2004 kubectl create namespace $1 1> /dev/null 2> ./tmp/kubeerr
2005 if [ $? -ne 0 ]; then
2006 echo -e " Creating namespace $1 $RED$BOLD FAILED $EBOLD$ERED"
2008 echo " Message: $(<./tmp/kubeerr)"
2011 echo -e " Creating namespace $1 $GREEN$BOLD OK $EBOLD$EGREEN"
2014 echo -e " Creating namespace $1 $GREEN$BOLD Already exists, OK $EBOLD$EGREEN"
2019 # Find the host ip of an app (using the service resource)
2020 # args: <app-name> <namespace>
2021 # (Not for test scripts)
2022 __kube_get_service_host() {
2023 if [ $# -ne 2 ]; then
2025 __print_err "need 2 args, <app-name> <namespace>" $@
2028 for timeout in {1..60}; do
2029 host=$(kubectl get svc $1 -n $2 -o jsonpath='{.spec.clusterIP}')
2030 if [ $? -eq 0 ]; then
2031 if [ ! -z "$host" ]; then
2039 echo "host-not-found-fatal-error"
2043 # Find the named port to an app (using the service resource)
2044 # args: <app-name> <namespace> <port-name>
2045 # (Not for test scripts)
2046 __kube_get_service_port() {
2047 if [ $# -ne 3 ]; then
2049 __print_err "need 3 args, <app-name> <namespace> <port-name>" $@
2053 for timeout in {1..60}; do
2054 port=$(kubectl get svc $1 -n $2 -o jsonpath='{...ports[?(@.name=="'$3'")].port}')
2055 if [ $? -eq 0 ]; then
2056 if [ ! -z "$port" ]; then
2068 # Find the named node port to an app (using the service resource)
2069 # args: <app-name> <namespace> <port-name>
2070 # (Not for test scripts)
2071 __kube_get_service_nodeport() {
2072 if [ $# -ne 3 ]; then
2074 __print_err "need 3 args, <app-name> <namespace> <port-name>" $@
2078 for timeout in {1..60}; do
2079 port=$(kubectl get svc $1 -n $2 -o jsonpath='{...ports[?(@.name=="'$3'")].nodePort}')
2080 if [ $? -eq 0 ]; then
2081 if [ ! -z "$port" ]; then
2093 # Create a kube resource from a yaml template
2094 # args: <resource-type> <resource-name> <template-yaml> <output-yaml>
2095 # (Not for test scripts)
2096 __kube_create_instance() {
2097 echo -ne " Creating $1 $2"$SAMELINE
2099 kubectl apply -f $4 1> /dev/null 2> ./tmp/kubeerr
2100 if [ $? -ne 0 ]; then
2102 echo -e " Creating $1 $2 $RED Failed $ERED"
2103 echo " Message: $(<./tmp/kubeerr)"
2106 echo -e " Creating $1 $2 $GREEN OK $EGREEN"
2110 # Function to create a configmap in kubernetes
2111 # args: <configmap-name> <namespace> <labelname> <labelid> <path-to-data-file> <path-to-output-yaml>
2112 # (Not for test scripts)
2113 __kube_create_configmap() {
2114 echo -ne " Creating configmap $1 "$SAMELINE
2115 envsubst < $5 > $5"_tmp"
2116 cp $5"_tmp" $5 #Need to copy back to orig file name since create configmap neeed the original file name
2117 kubectl create configmap $1 -n $2 --from-file=$5 --dry-run=client -o yaml > $6
2118 if [ $? -ne 0 ]; then
2119 echo -e " Creating configmap $1 $RED Failed $ERED"
2124 kubectl apply -f $6 1> /dev/null 2> ./tmp/kubeerr
2125 if [ $? -ne 0 ]; then
2126 echo -e " Creating configmap $1 $RED Apply failed $ERED"
2127 echo " Message: $(<./tmp/kubeerr)"
2131 kubectl label configmap $1 -n $2 $3"="$4 --overwrite 1> /dev/null 2> ./tmp/kubeerr
2132 if [ $? -ne 0 ]; then
2133 echo -e " Creating configmap $1 $RED Labeling failed $ERED"
2134 echo " Message: $(<./tmp/kubeerr)"
2138 # Log the resulting map
2139 kubectl get configmap $1 -n $2 -o yaml > $6
2141 echo -e " Creating configmap $1 $GREEN OK $EGREEN"
2145 # Function to create a configmap in kubernetes
2146 # args: <configmap-name> <namespace> <labelname> <labelid> <path-to-data-file> <path-to-output-yaml>
2147 # (Not for test scripts)
2148 __kube_create_configmapXXXXXXXXXXXXX() {
2149 echo -ne " Creating configmap $1 "$SAMELINE
2150 #envsubst < $5 > $5"_tmp"
2151 #cp $5"_tmp" $5 #Need to copy back to orig file name since create configmap neeed the original file name
2152 kubectl create configmap $1 -n $2 --from-file=$5 --dry-run=client -o yaml > $6
2153 if [ $? -ne 0 ]; then
2154 echo -e " Creating configmap $1 $RED Failed $ERED"
2159 kubectl apply -f $6 1> /dev/null 2> ./tmp/kubeerr
2160 if [ $? -ne 0 ]; then
2161 echo -e " Creating configmap $1 $RED Apply failed $ERED"
2162 echo " Message: $(<./tmp/kubeerr)"
2166 kubectl label configmap $1 -n $2 $3"="$4 --overwrite 1> /dev/null 2> ./tmp/kubeerr
2167 if [ $? -ne 0 ]; then
2168 echo -e " Creating configmap $1 $RED Labeling failed $ERED"
2169 echo " Message: $(<./tmp/kubeerr)"
2173 # Log the resulting map
2174 kubectl get configmap $1 -n $2 -o yaml > $6
2176 echo -e " Creating configmap $1 $GREEN OK $EGREEN"
2180 # This function runs a kubectl cmd where a single output value is expected, for example get ip with jsonpath filter.
2181 # The function retries up to the timeout given in the cmd flag '--cluster-timeout'
2182 # args: <full kubectl cmd with parameters>
2183 # (Not for test scripts)
2184 __kube_cmd_with_timeout() {
2185 TS_TMP=$(($SECONDS+$CLUSTER_TIME_OUT))
2188 kube_cmd_result=$($@)
2189 if [ $? -ne 0 ]; then
2192 if [ $SECONDS -ge $TS_TMP ] || [ ! -z "$kube_cmd_result" ] ; then
2193 echo $kube_cmd_result
2200 # This function starts a pod that cleans a the contents of a path mounted as a pvc
2201 # After this action the pod should terminate
2202 # This should only be executed when the pod owning the pvc is not running
2203 # args: <appname> <namespace> <pvc-name> <path-to remove>
2204 # (Not for test scripts)
2205 __kube_clean_pvc() {
2207 #using env vars setup in pvccleaner_api_functions.sh
2209 export PVC_CLEANER_NAMESPACE=$2
2210 export PVC_CLEANER_CLAIMNAME=$3
2211 export PVC_CLEANER_RM_PATH=$4
2212 input_yaml=$SIM_GROUP"/"$PVC_CLEANER_COMPOSE_DIR"/"pvc-cleaner.yaml
2213 output_yaml=$PWD/tmp/$2-pvc-cleaner.yaml
2215 envsubst < $input_yaml > $output_yaml
2217 kubectl delete -f $output_yaml 1> /dev/null 2> /dev/null # Delete the previous terminated pod - if existing
2219 __kube_create_instance pod $PVC_CLEANER_APP_NAME $input_yaml $output_yaml
2220 if [ $? -ne 0 ]; then
2221 echo $YELLOW" Could not clean pvc for app: $1 - persistent storage not clean - tests may not work"
2225 term_ts=$(($SECONDS+30))
2226 while [ $term_ts -gt $SECONDS ]; do
2227 pod_status=$(kubectl get pod pvc-cleaner -n $PVC_CLEANER_NAMESPACE --no-headers -o custom-columns=":status.phase")
2228 if [ "$pod_status" == "Succeeded" ]; then
2235 # This function scales or deletes all resources for app selected by the testcase.
2237 # (Not for test scripts)
2239 echo -e $BOLD"Initialize kube pods/statefulsets/replicaset to initial state"$EBOLD
2241 # Scale prestarted or managed apps
2242 for imagename in $APP_SHORT_NAMES; do
2243 # A function name is created from the app short name
2244 # for example app short name 'RICMSIM' -> produce the function
2245 # name __RICSIM_kube_scale_zero or __RICSIM_kube_scale_zero_and_wait
2246 # This function is called and is expected to exist in the imported
2247 # file for the ricsim test functions
2248 # The resulting function impl shall scale the resources to 0
2249 # For prestarted apps, the function waits until the resources are 0
2250 # For included (not prestated) apps, the scaling is just ordered
2251 __check_prestarted_image $imagename
2252 if [ $? -eq 0 ]; then
2253 function_pointer="__"$imagename"_kube_scale_zero_and_wait"
2254 echo -e " Scaling all kube resources for app $BOLD $imagename $EBOLD to 0"
2257 __check_included_image $imagename
2258 if [ $? -eq 0 ]; then
2259 function_pointer="__"$imagename"_kube_scale_zero"
2260 echo -e " Scaling all kube resources for app $BOLD $imagename $EBOLD to 0"
2266 # Delete managed apps
2267 for imagename in $APP_SHORT_NAMES; do
2268 __check_included_image $imagename
2269 if [ $? -eq 0 ]; then
2270 __check_prestarted_image $imagename
2271 if [ $? -ne 0 ]; then
2272 # A function name is created from the app short name
2273 # for example app short name 'RICMSIM' -> produce the function
2274 # name __RICSIM__kube_delete_all
2275 # This function is called and is expected to exist in the imported
2276 # file for the ricsim test functions
2277 # The resulting function impl shall delete all its resources
2278 function_pointer="__"$imagename"_kube_delete_all"
2279 echo -e " Deleting all kube resources for app $BOLD $imagename $EBOLD"
2288 # Function stop and remove all containers (docker) and services/deployments etc(kube)
2290 # Function for test script
2291 clean_environment() {
2292 if [ $RUNMODE == "KUBE" ]; then
2294 if [ $PRE_CLEAN -eq 1 ]; then
2295 echo " Clean docker resouces to free up resources, may take time..."
2296 ../common/clean_docker.sh 2&>1 /dev/null
2300 if [ $PRE_CLEAN -eq 1 ]; then
2301 echo " Clean kubernetes resouces to free up resources, may take time..."
2302 ../common/clean_kube.sh 2&>1 /dev/null
2307 # Function stop and remove all containers (docker) and services/deployments etc(kube) in the end of the test script, if the arg 'auto-clean' is given at test script start
2309 # (Function for test scripts)
2310 auto_clean_environment() {
2312 if [ "$AUTO_CLEAN" == "auto" ]; then
2313 echo -e $BOLD"Initiating automatic cleaning of environment"$EBOLD
2318 # Function to sleep a test case for a numner of seconds. Prints the optional text args as info
2319 # args: <sleep-time-in-sec> [any-text-in-quotes-to-be-printed]
2320 # (Function for test scripts)
2323 echo -e $BOLD"INFO(${BASH_LINENO[0]}): "${FUNCNAME[0]}"," $@ $EBOLD
2324 if [ $# -lt 1 ]; then
2326 __print_err "need at least one arg, <sleep-time-in-sec> [any-text-to-printed]" $@
2329 #echo "---- Sleep for " $1 " seconds ---- "$2
2331 duration=$((SECONDS-start))
2332 while [ $duration -lt $1 ]; do
2333 echo -ne " Slept for ${duration} seconds${SAMELINE}"
2335 duration=$((SECONDS-start))
2337 echo -ne " Slept for ${duration} seconds${SAMELINE}"
2341 # Print error info for the call in the parent script (test case). Arg: <error-message-to-print>
2342 # Not to be called from the test script itself.
2344 echo -e $RED ${FUNCNAME[1]} " "$1" " ${BASH_SOURCE[2]} " line" ${BASH_LINENO[1]} $ERED
2345 if [ $# -gt 1 ]; then
2346 echo -e $RED" Got: "${FUNCNAME[1]} ${@:2} $ERED
2351 # Function to create the docker network for the test
2352 # Not to be called from the test script itself.
2353 __create_docker_network() {
2354 tmp=$(docker network ls --format={{.Name}} --filter name=$DOCKER_SIM_NWNAME)
2355 if [ $? -ne 0 ]; then
2356 echo -e $RED" Could not check if docker network $DOCKER_SIM_NWNAME exists"$ERED
2359 if [ "$tmp" != $DOCKER_SIM_NWNAME ]; then
2360 echo -e " Creating docker network:$BOLD $DOCKER_SIM_NWNAME $EBOLD"
2361 docker network create $DOCKER_SIM_NWNAME | indent2
2362 if [ $? -ne 0 ]; then
2363 echo -e $RED" Could not create docker network $DOCKER_SIM_NWNAME"$ERED
2366 echo -e "$GREEN Done$EGREEN"
2369 echo -e " Docker network $DOCKER_SIM_NWNAME already exists$GREEN OK $EGREEN"
2373 # Function to start container with docker-compose and wait until all are in state running.
2374 # If the <docker-compose-file> is empty, the default 'docker-compose.yml' is assumed.
2375 #args: <docker-compose-dir> <docker-compose-file> <docker-compose-arg>|NODOCKERARGS <count> <app-name>+
2376 # (Not for test scripts)
2377 __start_container() {
2379 if [ $# -lt 5 ]; then
2381 __print_err "need 5 or more args, <docker-compose-dir> <docker-compose-file> <docker-compose-arg>|NODOCKERARGS <count> <app-name>+" $@
2385 __create_docker_network
2393 if [ -z "$compose_file" ]; then
2394 compose_file="docker-compose.yml"
2402 if [ "$compose_args" == "NODOCKERARGS" ]; then
2403 docker-compose -f $compose_file up -d &> .dockererr
2404 if [ $? -ne 0 ]; then
2405 echo -e $RED"Problem to launch container(s) with docker-compose"$ERED
2407 echo -e $RED"Stopping script...."$ERED
2411 docker-compose -f $compose_file up -d $compose_args &> .dockererr
2412 if [ $? -ne 0 ]; then
2413 echo -e $RED"Problem to launch container(s) with docker-compose"$ERED
2415 echo -e $RED"Stopping script...."$ERED
2423 while [ $appindex -lt $appcount ]; do
2427 for i in {1..10}; do
2428 if [ "$(docker inspect --format '{{ .State.Running }}' $appname)" == "true" ]; then
2429 echo -e " Container $BOLD${appname}$EBOLD$GREEN running$EGREEN on$BOLD image $(docker inspect --format '{{ .Config.Image }}' ${appname}) $EBOLD"
2436 if [ $app_started -eq 0 ]; then
2439 echo -e $RED" Container $BOLD${appname}$EBOLD could not be started"$ERED
2440 echo -e $RED" Stopping script..."$ERED
2443 let appindex=appindex+1
2448 # Function to check if container/service is responding to http/https
2449 # args: <container-name>|<service-name> url
2450 # (Not for test scripts)
2451 __check_service_start() {
2453 if [ $# -ne 2 ]; then
2455 __print_err "need 2 args, <container-name>|<service-name> url" $@
2459 if [ $RUNMODE == "KUBE" ]; then
2460 ENTITY="service/set/deployment"
2466 echo -ne " Container $BOLD${appname}$EBOLD starting${SAMELINE}"
2470 echo -ne " Waiting for ${ENTITY} ${appname} service status...${SAMELINE}"
2473 while (( $TSTART+600 > $SECONDS )); do
2474 result="$(__do_curl -m 10 $url)"
2475 if [ $? -eq 0 ]; then
2476 if [ ${#result} -gt 15 ]; then
2477 #If response is too long, truncate
2478 result="...response text too long, omitted"
2480 echo -ne " Waiting for {ENTITY} $BOLD${appname}$EBOLD service status on ${3}, result: $result${SAMELINE}"
2481 echo -ne " The ${ENTITY} $BOLD${appname}$EBOLD$GREEN is alive$EGREEN, responds to service status:$GREEN $result $EGREEN on ${url} after $(($SECONDS-$TSTART)) seconds"
2487 if (( $TS_OFFSET > 5 )); then
2490 while [ $(($TS_TMP+$TS_OFFSET)) -gt $SECONDS ]; do
2491 echo -ne " Waiting for ${ENTITY} ${appname} service status on ${url}...$(($SECONDS-$TSTART)) seconds, retrying in $(($TS_TMP+$TS_OFFSET-$SECONDS)) seconds ${SAMELINE}"
2495 let loop_ctr=loop_ctr+1
2498 if [ "$pa_st" = "false" ]; then
2500 echo -e $RED" The ${ENTITY} ${appname} did not respond to service status on ${url} in $(($SECONDS-$TSTART)) seconds"$ERED
2513 __check_container_logs() {
2521 echo -e $BOLD"Checking $dispname container $appname log ($logpath) for WARNINGs and ERRORs"$EBOLD
2523 if [ $RUNMODE == "KUBE" ]; then
2524 echo -e $YELLOW" Internal log for $dispname not checked in kube"$EYELLOW
2528 #tmp=$(docker ps | grep $appname)
2529 tmp=$(docker ps -q --filter name=$appname) #get the container id
2530 if [ -z "$tmp" ]; then #Only check logs for running Policy Agent apps
2531 echo " "$dispname" is not running, no check made"
2534 foundentries="$(docker exec -t $tmp grep $warning $logpath | wc -l)"
2535 if [ $? -ne 0 ];then
2536 echo " Problem to search $appname log $logpath"
2538 if [ $foundentries -eq 0 ]; then
2539 echo " No WARN entries found in $appname log $logpath"
2541 echo -e " Found \033[1m"$foundentries"\033[0m WARN entries in $appname log $logpath"
2544 foundentries="$(docker exec -t $tmp grep $error $logpath | wc -l)"
2545 if [ $? -ne 0 ];then
2546 echo " Problem to search $appname log $logpath"
2548 if [ $foundentries -eq 0 ]; then
2549 echo " No ERR entries found in $appname log $logpath"
2551 echo -e $RED" Found \033[1m"$foundentries"\033[0m"$RED" ERR entries in $appname log $logpath"$ERED
2557 # Store all container logs and other logs in the log dir for the script
2558 # Logs are stored with a prefix in case logs should be stored several times during a test
2559 # args: <logfile-prefix>
2560 # (Function for test scripts)
2562 if [ $# != 1 ]; then
2564 __print_err "need one arg, <file-prefix>" $@
2567 echo -e $BOLD"Storing all docker/kube container logs and other test logs in $TESTLOGS/$ATC using prefix: "$1$EBOLD
2569 docker stats --no-stream > $TESTLOGS/$ATC/$1_docker_stats.log 2>&1
2571 docker ps -a > $TESTLOGS/$ATC/$1_docker_ps.log 2>&1
2573 cp .httplog_${ATC}.txt $TESTLOGS/$ATC/$1_httplog_${ATC}.txt 2>&1
2575 if [ $RUNMODE == "DOCKER" ]; then
2577 # Store docker logs for all container
2578 for imagename in $APP_SHORT_NAMES; do
2579 __check_included_image $imagename
2580 if [ $? -eq 0 ]; then
2581 # A function name is created from the app short name
2582 # for example app short name 'RICMSIM' -> produce the function
2583 # name __RICSIM__store_docker_logs
2584 # This function is called and is expected to exist in the imported
2585 # file for the ricsim test functions
2586 # The resulting function impl shall store the docker logs for each container
2587 function_pointer="__"$imagename"_store_docker_logs"
2588 $function_pointer "$TESTLOGS/$ATC/" $1
2592 if [ $RUNMODE == "KUBE" ]; then
2593 namespaces=$(kubectl get namespaces -o jsonpath='{.items[?(@.metadata.name)].metadata.name}')
2594 for nsid in $namespaces; do
2595 pods=$(kubectl get pods -n $nsid -o jsonpath='{.items[?(@.metadata.labels.autotest)].metadata.name}')
2596 for podid in $pods; do
2597 kubectl logs -n $nsid $podid > $TESTLOGS/$ATC/$1_${podid}.log
2607 # Generic curl function, assumes all 200-codes are ok
2608 # args: <valid-curl-args-including full url>
2609 # returns: <returned response (without respose code)> or "<no-response-from-server>" or "<not found, <http-code>>""
2610 # returns: The return code is 0 for ok and 1 for not ok
2612 echo ${FUNCNAME[1]} "line: "${BASH_LINENO[1]} >> $HTTPLOG
2614 if [ ! -z "$KUBE_PROXY_PATH" ]; then
2615 if [ $KUBE_PROXY_HTTPX == "http" ]; then
2616 proxyflag=" --proxy $KUBE_PROXY_PATH"
2618 proxyflag=" --proxy-insecure --proxy $KUBE_PROXY_PATH"
2621 curlString="curl -skw %{http_code} $proxyflag $@"
2622 echo " CMD: $curlString" >> $HTTPLOG
2625 echo " RESP: $res" >> $HTTPLOG
2626 echo " RETCODE: $retcode" >> $HTTPLOG
2627 if [ $retcode -ne 0 ]; then
2628 echo "<no-response-from-server>"
2631 http_code="${res:${#res}-3}"
2632 if [ ${#res} -eq 3 ]; then
2633 if [ $http_code -lt 200 ] || [ $http_code -gt 299 ]; then
2634 echo "<no-response-from-server>"
2640 if [ $http_code -lt 200 ] || [ $http_code -gt 299 ]; then
2641 echo "<not found, resp:${http_code}>"
2644 if [ $# -eq 2 ]; then
2645 echo "${res:0:${#res}-3}" | xargs
2647 echo "${res:0:${#res}-3}"
2654 #######################################
2655 ### Basic helper function for test cases
2656 #######################################
2658 # Test a simulator container variable value towards target value using an condition operator with an optional timeout.
2659 # Arg: <simulator-name> <host> <variable-name> <condition-operator> <target-value> - This test is done
2660 # immediately and sets pass or fail depending on the result of comparing variable and target using the operator.
2661 # Arg: <simulator-name> <host> <variable-name> <condition-operator> <target-value> <timeout> - This test waits up to the timeout
2662 # before setting pass or fail depending on the result of comparing variable and target using the operator.
2663 # If the <variable-name> has the 'json:' prefix, the the variable will be used as url and the <target-value> will be compared towards the length of the json array in the response.
2664 # Not to be called from test script.
2667 checkjsonarraycount=0
2668 TIMESTAMP=$(date "+%Y-%m-%d %H:%M:%S")
2669 if [ $# -eq 6 ]; then
2670 if [[ $3 == "json:"* ]]; then
2671 checkjsonarraycount=1
2674 echo -e $BOLD"TEST $TEST_SEQUENCE_NR (${BASH_LINENO[1]}): ${1}, ${3} ${4} ${5} within ${6} seconds"$EBOLD
2675 echo "TEST $TEST_SEQUENCE_NR - ${TIMESTAMP}: (${BASH_LINENO[1]}): ${1}, ${3} ${4} ${5} within ${6} seconds" >> $HTTPLOG
2678 ((TEST_SEQUENCE_NR++))
2682 if [ $checkjsonarraycount -eq 0 ]; then
2683 result="$(__do_curl $2$3)"
2685 result=${result//[[:blank:]]/} #Strip blanks
2688 result="$(__do_curl $2$path)"
2690 echo "$result" > ./tmp/.tmp.curl.json
2691 result=$(python3 ../common/count_json_elements.py "./tmp/.tmp.curl.json")
2693 duration=$((SECONDS-start))
2694 echo -ne " Result=${result} after ${duration} seconds${SAMELINE}"
2696 if [ $retcode -ne 0 ]; then
2697 if [ $duration -gt $6 ]; then
2699 echo -e $RED" FAIL${ERED} - ${3} ${4} ${5} not reached in ${6} seconds, result = ${result}"
2700 __print_current_stats
2701 __check_stop_at_error
2704 elif [ $4 = "=" ] && [ "$result" -eq $5 ]; then
2706 echo -e " Result=${result} after ${duration} seconds${SAMELINE}"
2707 echo -e $GREEN" PASS${EGREEN} - Result=${result} after ${duration} seconds"
2708 __print_current_stats
2710 elif [ $4 = ">" ] && [ "$result" -gt $5 ]; then
2712 echo -e " Result=${result} after ${duration} seconds${SAMELINE}"
2713 echo -e $GREEN" PASS${EGREEN} - Result=${result} after ${duration} seconds"
2714 __print_current_stats
2716 elif [ $4 = "<" ] && [ "$result" -lt $5 ]; then
2718 echo -e " Result=${result} after ${duration} seconds${SAMELINE}"
2719 echo -e $GREEN" PASS${EGREEN} - Result=${result} after ${duration} seconds"
2720 __print_current_stats
2722 elif [ $4 = "contain_str" ] && [[ $result =~ $5 ]]; then
2724 echo -e " Result=${result} after ${duration} seconds${SAMELINE}"
2725 echo -e $GREEN" PASS${EGREEN} - Result=${result} after ${duration} seconds"
2726 __print_current_stats
2729 if [ $duration -gt $6 ]; then
2731 echo -e $RED" FAIL${ERED} - ${3} ${4} ${5} not reached in ${6} seconds, result = ${result}"
2732 __print_current_stats
2733 __check_stop_at_error
2739 elif [ $# -eq 5 ]; then
2740 if [[ $3 == "json:"* ]]; then
2741 checkjsonarraycount=1
2744 echo -e $BOLD"TEST $TEST_SEQUENCE_NR (${BASH_LINENO[1]}): ${1}, ${3} ${4} ${5}"$EBOLD
2745 echo "TEST $TEST_SEQUENCE_NR - ${TIMESTAMP}: (${BASH_LINENO[1]}): ${1}, ${3} ${4} ${5}" >> $HTTPLOG
2747 ((TEST_SEQUENCE_NR++))
2748 if [ $checkjsonarraycount -eq 0 ]; then
2749 result="$(__do_curl $2$3)"
2751 result=${result//[[:blank:]]/} #Strip blanks
2754 result="$(__do_curl $2$path)"
2756 echo "$result" > ./tmp/.tmp.curl.json
2757 result=$(python3 ../common/count_json_elements.py "./tmp/.tmp.curl.json")
2759 if [ $retcode -ne 0 ]; then
2761 echo -e $RED" FAIL ${ERED}- ${3} ${4} ${5} not reached, result = ${result}"
2762 __print_current_stats
2763 __check_stop_at_error
2764 elif [ $4 = "=" ] && [ "$result" -eq $5 ]; then
2766 echo -e $GREEN" PASS${EGREEN} - Result=${result}"
2767 __print_current_stats
2768 elif [ $4 = ">" ] && [ "$result" -gt $5 ]; then
2770 echo -e $GREEN" PASS${EGREEN} - Result=${result}"
2771 __print_current_stats
2772 elif [ $4 = "<" ] && [ "$result" -lt $5 ]; then
2774 echo -e $GREEN" PASS${EGREEN} - Result=${result}"
2775 __print_current_stats
2776 elif [ $4 = "contain_str" ] && [[ $result =~ $5 ]]; then
2778 echo -e $GREEN" PASS${EGREEN} - Result=${result}"
2779 __print_current_stats
2782 echo -e $RED" FAIL${ERED} - ${3} ${4} ${5} not reached, result = ${result}"
2783 __print_current_stats
2784 __check_stop_at_error
2787 echo "Wrong args to __var_test, needs five or six args: <simulator-name> <host> <variable-name> <condition-operator> <target-value> [ <timeout> ]"