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 " [--cluster-timeout <timeout-in seconds>]"
33 if [ $# -eq 1 ] && [ "$1" == "help" ]; then
35 if [ ! -z "$TC_ONELINE_DESCR" ]; then
36 echo "Test script description:"
37 echo $TC_ONELINE_DESCR
42 echo "remote - Use images from remote repositories. Can be overridden for individual images using the '--use_xxx' flags"
43 echo "remote-remove - Same as 'remote' but will also try to pull fresh images from remote repositories"
44 echo "docker - Test executed in docker environment"
45 echo "kube - Test executed in kubernetes environment - requires an already started kubernetes environment"
46 echo "--env-file - The script will use the supplied file to read environment variables from"
47 echo "release - If this flag is given the script will use release version of the images"
48 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."
49 echo "--stop-at-error - The script will stop when the first failed test or configuration"
50 echo "--ricsim-prefix - The a1 simulator will use the supplied string as container prefix instead of 'ricsim'"
51 echo "--use-local-image - The script will use local images for the supplied apps, space separated list of app short names"
52 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"
53 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"
54 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"
55 echo "--image-repo - Url to optional image repo. Only locally built images will be re-tagged and pushed to this repo"
56 echo "--cluster-timeout - Optional timeout for cluster where it takes time to obtain external ip/host-name. Timeout in seconds. "
58 echo "List of app short names supported: "$APP_SHORT_NAMES
63 # Create a test case id, ATC (Auto Test Case), from the name of the test case script.
64 # FTC1.sh -> ATC == FTC1
65 ATC=$(basename "${BASH_SOURCE[$i+1]}" .sh)
67 #Create result file (containing '1' for error) for this test case
68 #Will be replaced with a file containing '0' if all test cases pass
69 echo "1" > "$PWD/.result$ATC.txt"
71 #Formatting for 'echo' cmd
76 GREEN="\033[32m\033[1m"
78 YELLOW="\033[33m\033[1m"
82 # Just resetting any previous echo formatting...
85 # default test environment variables
88 echo "Test case started as: ${BASH_SOURCE[$i+1]} "$@
91 LOCALHOST_NAME="localhost"
92 LOCALHOST_HTTP="http://localhost"
93 LOCALHOST_HTTPS="https://localhost"
95 # Var to hold 'auto' in case containers shall be stopped when test case ends
98 # Var to hold the app names to use local images for
101 # Var to hold the app names to use remote snapshot images for
102 USE_SNAPSHOT_IMAGES=""
104 # Var to hold the app names to use remote staging images for
105 USE_STAGING_IMAGES=""
107 # Var to hold the app names to use remote release images for
108 USE_RELEASE_IMAGES=""
111 # 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
114 # The default value "DEV" indicate that development image tags (SNAPSHOT) and nexus repos (nexus port 10002) are used.
115 # The value "RELEASE" indicate that relase image tag and nexus repos (nexus port) are used
116 # Applies only to images defined in the test-env files with image names and tags defined as XXXX_RELEASE
119 # Function to indent cmd output with one space
120 indent1() { sed 's/^/ /'; }
122 # Function to indent cmd output with two spaces
123 indent2() { sed 's/^/ /'; }
125 # Set a description string for the test case
126 if [ -z "$TC_ONELINE_DESCR" ]; then
127 TC_ONELINE_DESCR="<no-description>"
128 echo "No test case description found, TC_ONELINE_DESCR should be set on in the test script , using "$TC_ONELINE_DESCR
131 # Counter for test suites
132 if [ -f .tmp_tcsuite_ctr ]; then
133 tmpval=$(< .tmp_tcsuite_ctr)
135 echo $tmpval > .tmp_tcsuite_ctr
138 # Create the logs dir if not already created in the current dir
139 if [ ! -d "logs" ]; then
144 # Create the tmp dir for temporary files that is not needed after the test
145 # hidden files for the test env is still stored in the current dir
146 # files in the ./tmp is moved to ./tmp/prev when a new test is started
147 if [ ! -d "tmp" ]; then
152 if [ $? -ne 0 ]; then
153 echo "Cannot cd to $PWD/tmp"
154 echo "Dir cannot be created. Exiting...."
156 if [ ! -d "prev" ]; then
160 mv ./tmp/* ./tmp/prev 2> /dev/null
162 # Create a http message log for this testcase
163 HTTPLOG=$PWD"/.httplog_"$ATC".txt"
166 # Create a log dir for the test case
167 mkdir -p $TESTLOGS/$ATC
169 # Save create for current logs
170 mkdir -p $TESTLOGS/$ATC/previous
172 rm $TESTLOGS/$ATC/previous/*.log &> /dev/null
173 rm $TESTLOGS/$ATC/previous/*.txt &> /dev/null
174 rm $TESTLOGS/$ATC/previous/*.json &> /dev/null
176 mv $TESTLOGS/$ATC/*.log $TESTLOGS/$ATC/previous &> /dev/null
177 mv $TESTLOGS/$ATC/*.txt $TESTLOGS/$ATC/previous &> /dev/null
178 mv $TESTLOGS/$ATC/*.txt $TESTLOGS/$ATC/previous &> /dev/null
180 # Clear the log dir for the test case
181 rm $TESTLOGS/$ATC/*.log &> /dev/null
182 rm $TESTLOGS/$ATC/*.txt &> /dev/null
183 rm $TESTLOGS/$ATC/*.json &> /dev/null
185 # Log all output from the test case to a TC log
186 TCLOG=$TESTLOGS/$ATC/TC.log
187 exec &> >(tee ${TCLOG})
189 #Variables for counting tests as well as passed and failed tests
196 #File to keep deviation messages
197 DEVIATION_FILE=".tmp_deviations"
198 rm $DEVIATION_FILE &> /dev/null
200 # Trap "command not found" and make the script fail
203 if [ $? -eq 127 ]; then
204 echo -e $RED"Function not found, setting script to FAIL"$ERED
213 # Function to log the start of a test case
215 TIMESTAMP=$(date "+%Y-%m-%d %H:%M:%S")
216 echo -e $BOLD"TEST $TEST_SEQUENCE_NR (${BASH_LINENO[1]}): ${FUNCNAME[1]}" $@ $EBOLD
217 echo "TEST $TEST_SEQUENCE_NR - ${TIMESTAMP}: (${BASH_LINENO[1]}): ${FUNCNAME[1]}" $@ >> $HTTPLOG
219 ((TEST_SEQUENCE_NR++))
222 # General function to log a failed test case
223 __log_test_fail_general() {
224 echo -e $RED" FAIL."$1 $ERED
226 __check_stop_at_error
229 # Function to log a test case failed due to incorrect response code
230 __log_test_fail_status_code() {
231 echo -e $RED" FAIL. Exepected status "$1", got "$2 $3 $ERED
233 __check_stop_at_error
236 # Function to log a test case failed due to incorrect response body
237 __log_test_fail_body() {
238 echo -e $RED" FAIL, returned body not correct"$ERED
240 __check_stop_at_error
243 # Function to log a test case that is not supported
244 __log_test_fail_not_supported() {
245 echo -e $RED" FAIL, function not supported"$ERED
247 __check_stop_at_error
250 # General function to log a passed test case
252 if [ $# -gt 0 ]; then
256 echo -e $GREEN" PASS"$EGREEN
259 #Counter for configurations
262 # Function to log the start of a configuration setup
264 TIMESTAMP=$(date "+%Y-%m-%d %H:%M:%S")
265 echo -e $BOLD"CONF $CONF_SEQUENCE_NR (${BASH_LINENO[1]}): "${FUNCNAME[1]} $@ $EBOLD
266 echo "CONF $CONF_SEQUENCE_NR - ${TIMESTAMP}: (${BASH_LINENO[1]}): "${FUNCNAME[1]} $@ >> $HTTPLOG
267 ((CONF_SEQUENCE_NR++))
270 # Function to log a failed configuration setup
271 __log_conf_fail_general() {
272 echo -e $RED" FAIL."$1 $ERED
274 __check_stop_at_error
277 # Function to log a failed configuration setup due to incorrect response code
278 __log_conf_fail_status_code() {
279 echo -e $RED" FAIL. Exepected status "$1", got "$2 $3 $ERED
281 __check_stop_at_error
284 # Function to log a failed configuration setup due to incorrect response body
285 __log_conf_fail_body() {
286 echo -e $RED" FAIL, returned body not correct"$ERED
288 __check_stop_at_error
291 # Function to log a passed configuration setup
293 if [ $# -gt 0 ]; then
296 echo -e $GREEN" OK"$EGREEN
299 #Var for measuring execution time
300 TCTEST_START=$SECONDS
302 #File to save timer measurement results
303 TIMER_MEASUREMENTS=".timer_measurement.txt"
304 echo -e "Activity \t Duration" > $TIMER_MEASUREMENTS
306 # If this is set, all used images will be re-tagged and pushed to this repo before any
310 echo "-------------------------------------------------------------------------------------------------"
311 echo "----------------------------------- Test case: "$ATC
312 echo "----------------------------------- Started: "$(date)
313 echo "-------------------------------------------------------------------------------------------------"
314 echo "-- Description: "$TC_ONELINE_DESCR
315 echo "-------------------------------------------------------------------------------------------------"
316 echo "----------------------------------- Test case setup -----------------------------------"
318 echo "Setting AUTOTEST_HOME="$AUTOTEST_HOME
322 if [ $# -lt 1 ]; then
325 if [ $paramerror -eq 0 ]; then
326 if [ "$1" != "remote" ] && [ "$1" != "remote-remove" ]; then
328 if [ -z "$paramerror_str" ]; then
329 paramerror_str="First arg shall be 'remote' or 'remote-remove'"
335 if [ $paramerror -eq 0 ]; then
336 if [ "$1" != "docker" ] && [ "$1" != "kube" ]; then
338 if [ -z "$paramerror_str" ]; then
339 paramerror_str="Second arg shall be 'docker' or 'kube'"
342 if [ $1 == "docker" ]; then
344 echo "Setting RUNMODE=DOCKER"
346 if [ $1 == "kube" ]; then
348 echo "Setting RUNMODE=KUBE"
354 while [ $paramerror -eq 0 ] && [ $foundparm -eq 0 ]; do
356 if [ $paramerror -eq 0 ]; then
357 if [ "$1" == "release" ]; then
358 IMAGE_CATEGORY="RELEASE"
359 echo "Option set - Release image tags used for applicable images "
364 if [ $paramerror -eq 0 ]; then
365 if [ "$1" == "auto-clean" ]; then
367 echo "Option set - Auto clean at end of test script"
372 if [ $paramerror -eq 0 ]; then
373 if [ "$1" == "--stop-at-error" ]; then
375 echo "Option set - Stop at first error"
380 if [ $paramerror -eq 0 ]; then
381 if [ "$1" == "--ricsim-prefix" ]; then
383 TMP_RIC_SIM_PREFIX=$1 #RIC_SIM_PREFIX need to be updated after sourcing of the env file
386 if [ -z "$paramerror_str" ]; then
387 paramerror_str="No prefix found for flag: '--ricsim-prefix'"
390 echo "Option set - Overriding RIC_SIM_PREFIX with: "$1
396 if [ $paramerror -eq 0 ]; then
397 if [ "$1" == "--env-file" ]; then
402 if [ -z "$paramerror_str" ]; then
403 paramerror_str="No env file found for flag: '--env-file'"
406 echo "Option set - Reading test env from: "$1
412 if [ $paramerror -eq 0 ]; then
413 if [ "$1" == "--use-local-image" ]; then
416 while [ $# -gt 0 ] && [[ "$1" != "--"* ]]; do
417 USE_LOCAL_IMAGES=$USE_LOCAL_IMAGES" "$1
418 if [[ "$AVAILABLE_IMAGES_OVERRIDE" != *"$1"* ]]; then
420 if [ -z "$paramerror_str" ]; then
421 paramerror_str="App name $1 is not available for local override for flag: '--use-local-image'"
427 if [ -z "$USE_LOCAL_IMAGES" ]; then
429 if [ -z "$paramerror_str" ]; then
430 paramerror_str="No app name found for flag: '--use-local-image'"
433 echo "Option set - Overriding with local images for app(s):"$USE_LOCAL_IMAGES
437 if [ $paramerror -eq 0 ]; then
438 if [ "$1" == "--use-snapshot-image" ]; then
439 USE_SNAPSHOT_IMAGES=""
441 while [ $# -gt 0 ] && [[ "$1" != "--"* ]]; do
442 USE_SNAPSHOT_IMAGES=$USE_SNAPSHOT_IMAGES" "$1
443 if [[ "$AVAILABLE_IMAGES_OVERRIDE" != *"$1"* ]]; then
445 if [ -z "$paramerror_str" ]; then
446 paramerror_str="App name $1 is not available for snapshot override for flag: '--use-snapshot-image'"
452 if [ -z "$USE_SNAPSHOT_IMAGES" ]; then
454 if [ -z "$paramerror_str" ]; then
455 paramerror_str="No app name found for flag: '--use-snapshot-image'"
458 echo "Option set - Overriding with snapshot images for app(s):"$USE_SNAPSHOT_IMAGES
462 if [ $paramerror -eq 0 ]; then
463 if [ "$1" == "--use-staging-image" ]; then
464 USE_STAGING_IMAGES=""
466 while [ $# -gt 0 ] && [[ "$1" != "--"* ]]; do
467 USE_STAGING_IMAGES=$USE_STAGING_IMAGES" "$1
468 if [[ "$AVAILABLE_IMAGES_OVERRIDE" != *"$1"* ]]; then
470 if [ -z "$paramerror_str" ]; then
471 paramerror_str="App name $1 is not available for staging override for flag: '--use-staging-image'"
477 if [ -z "$USE_STAGING_IMAGES" ]; then
479 if [ -z "$paramerror_str" ]; then
480 paramerror_str="No app name found for flag: '--use-staging-image'"
483 echo "Option set - Overriding with staging images for app(s):"$USE_STAGING_IMAGES
487 if [ $paramerror -eq 0 ]; then
488 if [ "$1" == "--use-release-image" ]; then
489 USE_RELEASE_IMAGES=""
491 while [ $# -gt 0 ] && [[ "$1" != "--"* ]]; do
492 USE_RELEASE_IMAGES=$USE_RELEASE_IMAGES" "$1
493 if [[ "$AVAILABLE_IMAGES_OVERRIDE" != *"$1"* ]]; then
495 if [ -z "$paramerror_str" ]; then
496 paramerror_str="App name $1 is not available for release override for flag: '--use-release-image'"
502 if [ -z "$USE_RELEASE_IMAGES" ]; then
504 if [ -z "$paramerror_str" ]; then
505 paramerror_str="No app name found for flag: '--use-release-image'"
508 echo "Option set - Overriding with release images for app(s):"$USE_RELEASE_IMAGES
512 if [ $paramerror -eq 0 ]; then
513 if [ "$1" == "--image-repo" ]; then
518 if [ -z "$paramerror_str" ]; then
519 paramerror_str="No image repo url found for : '--image-repo'"
522 echo "Option set - Image repo url: "$1
528 if [ $paramerror -eq 0 ]; then
529 if [ "$1" == "--cluster-timeout" ]; then
534 if [ -z "$paramerror_str" ]; then
535 paramerror_str="No timeout value found for : '--cluster-timeout'"
538 #Check if positive int
539 case ${CLUSTER_TIME_OUT#[+]} in
542 if [ -z "$paramerror_str" ]; then
543 paramerror_str="Value for '--cluster-timeout' not an int : "$CLUSTER_TIME_OUT
548 echo "Option set - Cluster timeout: "$1
558 if [ $paramerror -eq 0 ] && [ $# -gt 0 ]; then
560 if [ -z "$paramerror_str" ]; then
561 paramerror_str="Unknown parameter(s): "$@
565 if [ $paramerror -eq 1 ]; then
566 echo -e $RED"Incorrect arg list: "$paramerror_str$ERED
571 # sourcing the selected env variables for the test case
572 if [ -f "$TEST_ENV_VAR_FILE" ]; then
573 echo -e $BOLD"Sourcing env vars from: "$TEST_ENV_VAR_FILE$EBOLD
576 if [ -z "$TEST_ENV_PROFILE" ] || [ -z "$SUPPORTED_PROFILES" ]; then
577 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
580 for prof in $SUPPORTED_PROFILES; do
581 if [ "$TEST_ENV_PROFILE" == "$prof" ]; then
582 echo -e $GREEN"Test case supports the selected test env file"$EGREEN
586 if [ $found_profile -ne 1 ]; then
587 echo -e $RED"Test case does not support the selected test env file"$ERED
588 echo "Profile: "$TEST_ENV_PROFILE" Supported profiles: "$SUPPORTED_PROFILES
589 echo -e $RED"Exiting...."$ERED
594 echo -e $RED"Selected env var file does not exist: "$TEST_ENV_VAR_FILE$ERED
595 echo " Select one of following env var file matching the intended target of the test"
596 echo " Restart the test using the flag '--env-file <path-to-env-file>"
597 ls $AUTOTEST_HOME/../common/test_env* | indent1
601 #This var need be preserved from the command line option, if set, when env var is sourced.
602 if [ ! -z "$TMP_RIC_SIM_PREFIX" ]; then
603 RIC_SIM_PREFIX=$TMP_RIC_SIM_PREFIX
606 if [ -z "$PROJECT_IMAGES_APP_NAMES" ]; then
607 echo -e $RED"Var PROJECT_IMAGES_APP_NAMES must be defined in: "$TEST_ENV_VAR_FILE $ERED
611 if [[ $SUPPORTED_RUNMODES != *"$RUNMODE"* ]]; then
612 echo -e $RED"This test script does not support RUNMODE $RUNMODE"$ERED
613 echo "Supported RUNMODEs: "$SUPPORTED_RUNMODES
617 # Choose list of included apps depending on run-mode
618 if [ $RUNMODE == "KUBE" ]; then
619 INCLUDED_IMAGES=$KUBE_INCLUDED_IMAGES
621 INCLUDED_IMAGES=$DOCKER_INCLUDED_IMAGES
624 # Check needed installed sw
626 if [ $? -ne 0 ] || [ -z tmp ]; then
627 echo -e $RED"python3 is required to run the test environment, pls install"$ERED
631 if [ $? -ne 0 ] || [ -z tmp ]; then
632 echo -e $RED"docker is required to run the test environment, pls install"$ERED
636 tmp=$(which docker-compose)
637 if [ $? -ne 0 ] || [ -z tmp ]; then
638 if [ $RUNMODE == "DOCKER" ]; then
639 echo -e $RED"docker-compose is required to run the test environment, pls install"$ERED
645 if [ $? -ne 0 ] || [ -z tmp ]; then
646 if [ $RUNMODE == "KUBE" ]; then
647 echo -e $RED"kubectl is required to run the test environment in kubernetes mode, pls install"$ERED
652 echo -e $BOLD"Checking configured image setting for this test case"$EBOLD
654 #Temp var to check for image variable name errors
656 #Create a file with image info for later printing as a table
657 image_list_file="./tmp/.image-list"
658 echo -e "Application\tApp short name\tImage\ttag\ttag-switch" > $image_list_file
660 # Check if image env var is set and if so export the env var with image to use (used by docker compose files)
661 # arg: <app-short-name> <target-variable-name> <image-variable-name> <image-tag-variable-name> <tag-suffix> <image name>
662 __check_and_create_image_var() {
664 if [ $# -ne 6 ]; then
665 echo "Expected arg: <app-short-name> <target-variable-name> <image-variable-name> <image-tag-variable-name> <tag-suffix> <image name>"
670 __check_included_image $1
671 if [ $? -ne 0 ]; then
672 echo -e "$6\t$1\t<image-excluded>\t<no-tag>" >> $image_list_file
673 # Image is excluded since the corresponding app is not used in this test
677 #Create var from the input var names
682 optional_image_repo_target=""
684 if [ -z $image ]; then
685 __check_ignore_image $1
686 if [ $? -eq 0 ]; then
689 app_ds="<app ignored>"
691 echo -e "$app_ds\t$1\t<image-ignored>\t<no-tag>" >> $image_list_file
692 # Image is ignored since the corresponding the images is not set in the env file
693 __remove_included_image $1 # Remove the image from the list of included images
696 echo -e $RED"\$"$3" not set in $TEST_ENV_VAR_FILE"$ERED
699 tmp=$tmp"<no-image>\t"
702 optional_image_repo_target=$image
704 #Add repo depending on image type
705 if [ "$5" == "REMOTE_RELEASE" ]; then
706 image=$NEXUS_RELEASE_REPO$image
708 if [ "$5" == "REMOTE" ]; then
709 image=$NEXUS_STAGING_REPO$image
711 if [ "$5" == "REMOTE_SNAPSHOT" ]; then
712 image=$NEXUS_SNAPSHOT_REPO$image
714 if [ "$5" == "REMOTE_PROXY" ]; then
715 image=$NEXUS_PROXY_REPO$image
717 if [ "$5" == "REMOTE_RELEASE_ONAP" ]; then
718 image=$NEXUS_RELEASE_REPO_ONAP$image
720 if [ "$5" == "REMOTE_RELEASE_ORAN" ]; then
721 image=$NEXUS_RELEASE_REPO_ORAN$image
723 #No nexus repo added for local images, tag: LOCAL
727 echo -e $RED"\$"$tmptag" not set in $TEST_ENV_VAR_FILE"$ERED
735 echo -e "$tmp" >> $image_list_file
737 export "${2}"=$image":"$tag #Note, this var may be set to the value of the target value below in __check_and_pull_image
738 if [ ! -z "$IMAGE_REPO_ADR" ] && [ $5 == "LOCAL" ]; then # Only push local images if repo is given
739 export "${2}_SOURCE"=$image":"$tag #Var to keep the actual source image
740 export "${2}_TARGET"=$IMAGE_REPO_ADR"/"$optional_image_repo_target":"$tag #Create image + tag for optional image repo - pushed later if needed
742 export "${2}_SOURCE"=""
743 export "${2}_TARGET"=""
747 # Check if app uses image included in this test run
748 # Returns 0 if image is included, 1 if not
749 __check_included_image() {
750 for im in $INCLUDED_IMAGES; do
751 if [ "$1" == "$im" ]; then
758 # Check if app uses a project image
759 # Returns 0 if image is included, 1 if not
760 __check_project_image() {
761 for im in $PROJECT_IMAGES; do
762 if [ "$1" == "$im" ]; then
769 # Check if app uses image built by the test script
770 # Returns 0 if image is included, 1 if not
771 __check_image_local_build() {
772 for im in $LOCAL_IMAGE_BUILD; do
773 if [ "$1" == "$im" ]; then
780 # Check if app image is conditionally ignored in this test run
781 # Returns 0 if image is conditionally ignored, 1 if not
782 __check_ignore_image() {
783 for im in $CONDITIONALLY_IGNORED_IMAGES; do
784 if [ "$1" == "$im" ]; then
791 # Removed image from included list of included images
792 # Used when an image is marked as conditionally ignored
793 __remove_included_image() {
795 for im in $INCLUDED_IMAGES; do
796 if [ "$1" != "$im" ]; then
797 tmp_img_rem_list=$tmp_img_rem_list" "$im
800 INCLUDED_IMAGES=$tmp_img_rem_list
804 # Check if app is included in the prestarted set of apps
805 # Returns 0 if image is included, 1 if not
806 __check_prestarted_image() {
807 for im in $KUBE_PRESTARTED_IMAGES; do
808 if [ "$1" == "$im" ]; then
815 # Check if an app shall use a local image, based on the cmd parameters
816 __check_image_local_override() {
817 for im in $USE_LOCAL_IMAGES; do
818 if [ "$1" == "$im" ]; then
825 # Check if app uses image override
826 # Returns the image/tag suffix LOCAL for local image or REMOTE/REMOTE_RELEASE/REMOTE_SNAPSHOT for staging/release/snapshot image
827 __check_image_override() {
829 for im in $ORAN_IMAGES_APP_NAMES; do
830 if [ "$1" == "$im" ]; then
831 echo "REMOTE_RELEASE_ORAN"
836 for im in $ONAP_IMAGES_APP_NAMES; do
837 if [ "$1" == "$im" ]; then
838 echo "REMOTE_RELEASE_ONAP"
844 for im in $PROJECT_IMAGES_APP_NAMES; do
845 if [ "$1" == "$im" ]; then
850 if [ $found -eq 0 ]; then
856 if [ $IMAGE_CATEGORY == "RELEASE" ]; then
857 suffix="REMOTE_RELEASE"
859 if [ $IMAGE_CATEGORY == "DEV" ]; then
863 for im in $USE_STAGING_IMAGES; do
864 if [ "$1" == "$im" ]; then
869 for im in $USE_RELEASE_IMAGES; do
870 if [ "$1" == "$im" ]; then
871 suffix="REMOTE_RELEASE"
875 for im in $USE_SNAPSHOT_IMAGES; do
876 if [ "$1" == "$im" ]; then
877 suffix="REMOTE_SNAPSHOT"
881 for im in $USE_LOCAL_IMAGES; do
882 if [ "$1" == "$im" ]; then
888 if [ $CTR -gt 1 ]; then
894 # Function to re-tag and image and push to another image repo
895 __retag_and_push_image() {
896 if [ ! -z "$IMAGE_REPO_ADR" ]; then
898 trg_var_name=$1_"TARGET" # This var is created in func __check_and_create_image_var
899 target_image="${!trg_var_name}"
900 echo -ne " Attempt to re-tag image to: ${BOLD}${target_image}${EBOLD}${SAMELINE}"
901 tmp=$(docker image tag $source_image ${target_image} )
902 if [ $? -ne 0 ]; then
903 docker stop $tmp &> ./tmp/.dockererr
906 echo -e " Attempt to re-tag image to: ${BOLD}${target_image}${EBOLD} - ${RED}Failed${ERED}"
910 echo -e " Attempt to re-tag image to: ${BOLD}${target_image}${EBOLD} - ${GREEN}OK${EGREEN}"
912 echo -ne " Attempt to push re-tagged image: ${BOLD}${target_image}${EBOLD}${SAMELINE}"
913 tmp=$(docker push ${target_image} )
914 if [ $? -ne 0 ]; then
915 docker stop $tmp &> ./tmp/.dockererr
918 echo -e " Attempt to push re-tagged image: ${BOLD}${target_image}${EBOLD} - ${RED}Failed${ERED}"
922 echo -e " Attempt to push re-tagged image: ${BOLD}${target_image}${EBOLD} - ${GREEN}OK${EGREEN}"
924 export "${1}"=$target_image
929 #Function to check if image exist and stop+remove the container+pull new images as needed
930 #args <script-start-arg> <descriptive-image-name> <container-base-name> <image-with-tag-var-name>
931 __check_and_pull_image() {
935 echo -e " Checking $BOLD$2$EBOLD container(s) with basename: $BOLD$3$EBOLD using image: $BOLD$source_image$EBOLD"
936 format_string="\"{{.Repository}}\\t{{.Tag}}\\t{{.CreatedSince}}\\t{{.Size}}\""
937 tmp_im=$(docker images --format $format_string $source_image)
939 if [ $1 == "local" ]; then
940 if [ -z "$tmp_im" ]; then
941 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
945 echo -e " "$2" (local image): \033[1m"$source_image"\033[0m "$GREEN"OK"$EGREEN
947 elif [ $1 == "remote" ] || [ $1 == "remote-remove" ]; then
948 if [ $1 == "remote-remove" ]; then
949 if [ $RUNMODE == "DOCKER" ]; then
950 echo -ne " Attempt to stop and remove container(s), if running - ${SAMELINE}"
951 tmp=$(docker ps -aq --filter name=${3} --filter network=${DOCKER_SIM_NWNAME})
952 if [ $? -eq 0 ] && [ ! -z "$tmp" ]; then
953 docker stop $tmp &> ./tmp/.dockererr
954 if [ $? -ne 0 ]; then
957 echo -e $RED" Container(s) could not be stopped - try manual stopping the container(s)"$ERED
962 echo -ne " Attempt to stop and remove container(s), if running - "$GREEN"stopped"$EGREEN"${SAMELINE}"
963 tmp=$(docker ps -aq --filter name=${3} --filter network=${DOCKER_SIM_NWNAME}) &> /dev/null
964 if [ $? -eq 0 ] && [ ! -z "$tmp" ]; then
965 docker rm $tmp &> ./tmp/.dockererr
966 if [ $? -ne 0 ]; then
969 echo -e $RED" Container(s) could not be removed - try manual removal of the container(s)"$ERED
974 echo -e " Attempt to stop and remove container(s), if running - "$GREEN"stopped removed"$EGREEN
980 if [ -z "$tmp_im" ]; then
981 echo -ne " Pulling image${SAMELINE}"
982 out=$(docker pull $source_image)
983 if [ $? -ne 0 ]; then
985 echo -e " Pulling image -$RED could not be pulled"$ERED
987 echo $out > ./tmp/.dockererr
991 echo $out > ./tmp/.dockererr
992 if [[ $out == *"up to date"* ]]; then
993 echo -e " Pulling image -$GREEN Image is up to date $EGREEN"
994 elif [[ $out == *"Downloaded newer image"* ]]; then
995 echo -e " Pulling image -$GREEN Newer image pulled $EGREEN"
997 echo -e " Pulling image -$GREEN Pulled $EGREEN"
1000 echo -e " Pulling image -$GREEN OK $EGREEN(exists in local repository)"
1004 __retag_and_push_image $4
1009 setup_testenvironment() {
1010 # Check that image env setting are available
1013 # Image var setup for all project images included in the test
1014 for imagename in $APP_SHORT_NAMES; do
1015 __check_included_image $imagename
1017 __check_project_image $imagename
1019 if [ $incl -eq 0 ]; then
1020 if [ $proj -eq 0 ]; then
1021 IMAGE_SUFFIX=$(__check_image_override $imagename)
1022 if [ $? -ne 0 ]; then
1023 echo -e $RED"Image setting from cmd line not consistent for $imagename."$ERED
1029 # A function name is created from the app short name
1030 # for example app short name 'ECS' -> produce the function
1031 # name __ECS_imagesetup
1032 # This function is called and is expected to exist in the imported
1033 # file for the ecs test functions
1034 # The resulting function impl will call '__check_and_create_image_var' function
1035 # with appropriate parameters
1036 # If the image suffix is none, then the component decides the suffix
1037 function_pointer="__"$imagename"_imagesetup"
1038 $function_pointer $IMAGE_SUFFIX
1042 #Errors in image setting - exit
1043 if [ $IMAGE_ERR -ne 0 ]; then
1047 #Print a tables of the image settings
1048 echo -e $BOLD"Images configured for start arg: "$START_ARG $EBOLD
1049 column -t -s $'\t' $image_list_file | indent1
1053 #Set the SIM_GROUP var
1054 echo -e $BOLD"Setting var to main dir of all container/simulator scripts"$EBOLD
1055 if [ -z "$SIM_GROUP" ]; then
1056 SIM_GROUP=$AUTOTEST_HOME/../simulator-group
1057 if [ ! -d $SIM_GROUP ]; then
1058 echo "Trying to set env var SIM_GROUP to dir 'simulator-group' in the nontrtric repo, but failed."
1059 echo -e $RED"Please set the SIM_GROUP manually in the applicable $TEST_ENV_VAR_FILE"$ERED
1062 echo " SIM_GROUP auto set to: " $SIM_GROUP
1064 elif [ $SIM_GROUP = *simulator_group ]; then
1065 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
1068 echo " SIM_GROUP env var already set to: " $SIM_GROUP
1073 #Temp var to check for image pull errors
1076 # The following sequence pull the configured images
1079 echo -e $BOLD"Pulling configured images, if needed"$EBOLD
1080 if [ ! -z "$IMAGE_REPO_ADR" ]; then
1081 echo -e $YELLOW" Excluding all remote image check/pull when running with image repo: $IMAGE_REPO_ADR"$EYELLOW
1083 for imagename in $APP_SHORT_NAMES; do
1084 __check_included_image $imagename
1086 __check_project_image $imagename
1088 if [ $incl -eq 0 ]; then
1089 if [ $proj -eq 0 ]; then
1090 START_ARG_MOD=$START_ARG
1091 __check_image_local_override $imagename
1092 if [ $? -eq 1 ]; then
1093 START_ARG_MOD="local"
1096 START_ARG_MOD=$START_ARG
1098 __check_image_local_build $imagename
1099 #No pull of images built locally
1100 if [ $? -ne 0 ]; then
1101 # A function name is created from the app short name
1102 # for example app short name 'HTTPPROXY' -> produce the function
1103 # name __HTTPPROXY_imagesetup
1104 # This function is called and is expected to exist in the imported
1105 # file for the httpproxy test functions
1106 # The resulting function impl will call '__check_and_pull_image' function
1107 # with appropriate parameters
1108 function_pointer="__"$imagename"_imagepull"
1109 $function_pointer $START_ARG_MOD $START_ARG
1112 echo -e $YELLOW" Excluding $imagename image from image check/pull"$EYELLOW
1117 #Errors in image setting - exit
1118 if [ $IMAGE_ERR -ne 0 ]; then
1120 echo "#################################################################################################"
1121 echo -e $RED"One or more images could not be pulled or containers using the images could not be stopped/removed"$ERED
1122 echo -e $RED"Or local image, overriding remote image, does not exist"$ERED
1123 if [ $IMAGE_CATEGORY == "DEV" ]; then
1124 echo -e $RED"Note that SNAPSHOT images may be purged from nexus after a certain period."$ERED
1125 echo -e $RED"In that case, switch to use a released image instead."$ERED
1127 echo "#################################################################################################"
1134 echo -e $BOLD"Building images needed for test"$EBOLD
1136 for imagename in $APP_SHORT_NAMES; do
1137 cd $AUTOTEST_HOME #Always reset to orig dir
1138 __check_image_local_build $imagename
1139 if [ $? -eq 0 ]; then
1140 __check_included_image $imagename
1141 if [ $? -eq 0 ]; then
1142 # A function name is created from the app short name
1143 # for example app short name 'MR' -> produce the function
1144 # name __MR_imagebuild
1145 # This function is called and is expected to exist in the imported
1146 # file for the mr test functions
1147 # The resulting function impl shall build the imagee
1148 function_pointer="__"$imagename"_imagebuild"
1152 echo -e $YELLOW" Excluding image for app $imagename from image build"$EYELLOW
1157 cd $AUTOTEST_HOME # Just to make sure...
1161 # Create a table of the images used in the script - from local repo
1162 echo -e $BOLD"Local docker registry images used in this test script"$EBOLD
1164 docker_tmp_file=./tmp/.docker-images-table
1165 format_string="{{.Repository}}\\t{{.Tag}}\\t{{.CreatedSince}}\\t{{.Size}}\\t{{.CreatedAt}}"
1166 echo -e "Application\tRepository\tTag\tCreated since\tSize\tCreated at" > $docker_tmp_file
1168 for imagename in $APP_SHORT_NAMES; do
1169 __check_included_image $imagename
1170 if [ $? -eq 0 ]; then
1171 # Only print image data if image repo is null, or if image repo is set and image is local
1173 if [ -z "$IMAGE_REPO_ADR" ]; then
1176 __check_image_local_build $imagename
1177 if [ $? -eq 0 ]; then
1181 if [ $print_image_data -eq 1 ]; then
1182 # A function name is created from the app short name
1183 # for example app short name 'MR' -> produce the function
1184 # name __MR_imagebuild
1185 # This function is called and is expected to exist in the imported
1186 # file for the mr test functions
1187 # The resulting function impl shall build the imagee
1188 function_pointer="__"$imagename"_image_data"
1189 $function_pointer "$format_string" $docker_tmp_file
1194 column -t -s $'\t' $docker_tmp_file | indent1
1198 if [ ! -z "$IMAGE_REPO_ADR" ]; then
1200 # Create a table of the images used in the script - from remote repo
1201 echo -e $BOLD"Remote repo images used in this test script"$EBOLD
1202 echo -e $YELLOW"-- Note: These image will be pulled when the container starts. Images not managed by the test engine --"$EYELLOW
1204 docker_tmp_file=./tmp/.docker-images-table
1205 format_string="{{.Repository}}\\t{{.Tag}}"
1206 echo -e "Application\tRepository\tTag" > $docker_tmp_file
1208 for imagename in $APP_SHORT_NAMES; do
1209 __check_included_image $imagename
1210 if [ $? -eq 0 ]; then
1211 # Only print image data if image repo is null, or if image repo is set and image is local
1212 __check_image_local_build $imagename
1213 if [ $? -ne 0 ]; then
1214 # A function name is created from the app short name
1215 # for example app short name 'MR' -> produce the function
1216 # name __MR_imagebuild
1217 # This function is called and is expected to exist in the imported
1218 # file for the mr test functions
1219 # The resulting function impl shall build the imagee
1220 function_pointer="__"$imagename"_image_data"
1221 $function_pointer "$format_string" $docker_tmp_file
1226 column -t -s $'\t' $docker_tmp_file | indent1
1231 if [ $RUNMODE == "KUBE" ]; then
1233 echo "================================================================================="
1234 echo "================================================================================="
1236 if [ -z "$IMAGE_REPO_ADR" ]; then
1237 echo -e $YELLOW" The image pull policy is set to 'Never' - assuming a local image repo is available for all images"$EYELLOW
1238 echo -e " This setting only works on single node clusters on the local machine"
1239 echo -e " It does not work with multi-node clusters or remote clusters. "
1240 export KUBE_IMAGE_PULL_POLICY="Never"
1242 echo -e $YELLOW" The image pull policy is set to 'Always'"$EYELLOW
1243 echo -e " This setting work on local clusters, multi-node clusters and remote cluster. "
1244 echo -e " Only locally built images are managed. Remote images are always pulled from remote repos"
1245 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"
1246 export KUBE_IMAGE_PULL_POLICY="Always"
1248 CLUSTER_IP=$(kubectl config view -o jsonpath={.clusters[0].cluster.server} | awk -F[/:] '{print $4}')
1249 echo -e $YELLOW" The cluster hostname/ip is: $CLUSTER_IP"$EYELLOW
1251 echo "================================================================================="
1252 echo "================================================================================="
1256 echo -e $BOLD"======================================================="$EBOLD
1257 echo -e $BOLD"== Common test setup completed - test script begins =="$EBOLD
1258 echo -e $BOLD"======================================================="$EBOLD
1263 # Function to print the test result, shall be the last cmd in a test script
1265 # (Function for test scripts)
1269 duration=$((TCTEST_END-TCTEST_START))
1271 echo "-------------------------------------------------------------------------------------------------"
1272 echo "------------------------------------- Test case: "$ATC
1273 echo "------------------------------------- Ended: "$(date)
1274 echo "-------------------------------------------------------------------------------------------------"
1275 echo "-- Description: "$TC_ONELINE_DESCR
1276 echo "-- Execution time: " $duration " seconds"
1277 echo "-- Used env file: "$TEST_ENV_VAR_FILE
1278 echo "-------------------------------------------------------------------------------------------------"
1279 echo "------------------------------------- RESULTS"
1283 if [ $RES_DEVIATION -gt 0 ]; then
1284 echo "Test case deviations"
1285 echo "===================================="
1289 echo "Timer measurement in the test script"
1290 echo "===================================="
1291 column -t -s $'\t' $TIMER_MEASUREMENTS
1294 total=$((RES_PASS+RES_FAIL))
1295 if [ $RES_TEST -eq 0 ]; then
1296 echo -e "\033[1mNo tests seem to have been executed. Check the script....\033[0m"
1297 echo -e "\033[31m\033[1m ___ ___ ___ ___ ___ _____ ___ _ ___ _ _ _ ___ ___ \033[0m"
1298 echo -e "\033[31m\033[1m/ __|/ __| _ \_ _| _ \_ _| | __/_\ |_ _| | | | | | _ \ __|\033[0m"
1299 echo -e "\033[31m\033[1m\__ \ (__| /| || _/ | | | _/ _ \ | || |_| |_| | / _| \033[0m"
1300 echo -e "\033[31m\033[1m|___/\___|_|_\___|_| |_| |_/_/ \_\___|____\___/|_|_\___|\033[0m"
1301 elif [ $total != $RES_TEST ]; then
1302 echo -e "\033[1mTotal number of tests does not match the sum of passed and failed tests. Check the script....\033[0m"
1303 echo -e "\033[31m\033[1m ___ ___ ___ ___ ___ _____ ___ _ ___ _ _ _ ___ ___ \033[0m"
1304 echo -e "\033[31m\033[1m/ __|/ __| _ \_ _| _ \_ _| | __/_\ |_ _| | | | | | _ \ __|\033[0m"
1305 echo -e "\033[31m\033[1m\__ \ (__| /| || _/ | | | _/ _ \ | || |_| |_| | / _| \033[0m"
1306 echo -e "\033[31m\033[1m|___/\___|_|_\___|_| |_| |_/_/ \_\___|____\___/|_|_\___|\033[0m"
1307 elif [ $RES_CONF_FAIL -ne 0 ]; then
1308 echo -e "\033[1mOne or more configurations has failed. Check the script log....\033[0m"
1309 echo -e "\033[31m\033[1m ___ ___ ___ ___ ___ _____ ___ _ ___ _ _ _ ___ ___ \033[0m"
1310 echo -e "\033[31m\033[1m/ __|/ __| _ \_ _| _ \_ _| | __/_\ |_ _| | | | | | _ \ __|\033[0m"
1311 echo -e "\033[31m\033[1m\__ \ (__| /| || _/ | | | _/ _ \ | || |_| |_| | / _| \033[0m"
1312 echo -e "\033[31m\033[1m|___/\___|_|_\___|_| |_| |_/_/ \_\___|____\___/|_|_\___|\033[0m"
1313 elif [ $RES_PASS = $RES_TEST ]; then
1314 echo -e "All tests \033[32m\033[1mPASS\033[0m"
1315 echo -e "\033[32m\033[1m ___ _ ___ ___ \033[0m"
1316 echo -e "\033[32m\033[1m | _ \/_\ / __/ __| \033[0m"
1317 echo -e "\033[32m\033[1m | _/ _ \\__ \__ \\ \033[0m"
1318 echo -e "\033[32m\033[1m |_|/_/ \_\___/___/ \033[0m"
1321 # Update test suite counter
1322 if [ -f .tmp_tcsuite_pass_ctr ]; then
1323 tmpval=$(< .tmp_tcsuite_pass_ctr)
1325 echo $tmpval > .tmp_tcsuite_pass_ctr
1327 if [ -f .tmp_tcsuite_pass ]; then
1328 echo " - "$ATC " -- "$TC_ONELINE_DESCR" Execution time: "$duration" seconds" >> .tmp_tcsuite_pass
1330 #Create file with OK exit code
1331 echo "0" > "$AUTOTEST_HOME/.result$ATC.txt"
1333 echo -e "One or more tests with status \033[31m\033[1mFAIL\033[0m "
1334 echo -e "\033[31m\033[1m ___ _ ___ _ \033[0m"
1335 echo -e "\033[31m\033[1m | __/_\ |_ _| | \033[0m"
1336 echo -e "\033[31m\033[1m | _/ _ \ | || |__ \033[0m"
1337 echo -e "\033[31m\033[1m |_/_/ \_\___|____|\033[0m"
1339 # Update test suite counter
1340 if [ -f .tmp_tcsuite_fail_ctr ]; then
1341 tmpval=$(< .tmp_tcsuite_fail_ctr)
1343 echo $tmpval > .tmp_tcsuite_fail_ctr
1345 if [ -f .tmp_tcsuite_fail ]; then
1346 echo " - "$ATC " -- "$TC_ONELINE_DESCR" Execution time: "$duration" seconds" >> .tmp_tcsuite_fail
1350 echo "++++ Number of tests: "$RES_TEST
1351 echo "++++ Number of passed tests: "$RES_PASS
1352 echo "++++ Number of failed tests: "$RES_FAIL
1354 echo "++++ Number of failed configs: "$RES_CONF_FAIL
1356 echo "++++ Number of test case deviations: "$RES_DEVIATION
1358 echo "------------------------------------- Test case complete ---------------------------------"
1359 echo "-------------------------------------------------------------------------------------------------"
1363 #####################################################################
1364 ###### Functions for start, configuring, stoping, cleaning etc ######
1365 #####################################################################
1367 # Start timer for time measurement
1368 # args - (any args will be printed though)
1370 echo -e $BOLD"INFO(${BASH_LINENO[0]}): "${FUNCNAME[0]}"," $@ $EBOLD
1372 echo " Timer started: $(date)"
1375 # Print the value of the time (in seconds)
1376 # args - <timer message to print> - timer value and message will be printed both on screen
1377 # and in the timer measurement report
1379 echo -e $BOLD"INFO(${BASH_LINENO[0]}): "${FUNCNAME[0]}"," $@ $EBOLD
1380 if [ $# -lt 1 ]; then
1382 __print_err "need 1 or more args, <timer message to print>" $@
1385 duration=$(($SECONDS-$TC_TIMER))
1386 if [ $duration -eq 0 ]; then
1387 duration="<1 second"
1389 duration=$duration" seconds"
1391 echo " Timer duration :" $duration
1393 echo -e "${@:1} \t $duration" >> $TIMER_MEASUREMENTS
1396 # Print the value of the time (in seconds) and reset the timer
1397 # args - <timer message to print> - timer value and message will be printed both on screen
1398 # and in the timer measurement report
1399 print_and_reset_timer() {
1400 echo -e $BOLD"INFO(${BASH_LINENO[0]}): "${FUNCNAME[0]}"," $@ $EBOLD
1401 if [ $# -lt 1 ]; then
1403 __print_err "need 1 or more args, <timer message to print>" $@
1406 duration=$(($SECONDS-$TC_TIMER))" seconds"
1407 if [ $duration -eq 0 ]; then
1408 duration="<1 second"
1410 duration=$duration" seconds"
1412 echo " Timer duration :" $duration
1416 echo -e "${@:1} \t $duration" >> $TIMER_MEASUREMENTS
1419 # Print info about a deviations from intended tests
1420 # Each deviation counted is also printed in the testreport
1421 # args <deviation message to print>
1423 echo -e $BOLD"DEVIATION(${BASH_LINENO[0]}): "${FUNCNAME[0]} $EBOLD
1424 if [ $# -lt 1 ]; then
1426 __print_err "need 1 or more args, <deviation message to print>" $@
1430 echo -e $BOLD$YELLOW" Test case deviation: ${@:1}"$EYELLOW$EBOLD
1431 echo "Line: ${BASH_LINENO[0]} - ${@:1}" >> $DEVIATION_FILE
1435 # Stop at first FAIL test case and take all logs - only for debugging/trouble shooting
1436 __check_stop_at_error() {
1437 if [ $STOP_AT_ERROR -eq 1 ]; then
1438 echo -e $RED"Test script configured to stop at first FAIL, taking all logs and stops"$ERED
1439 store_logs "STOP_AT_ERROR"
1445 # Stop and remove all containers
1447 # (Not for test scripts)
1448 __clean_containers() {
1450 echo -e $BOLD"Docker clean and stopping and removing all running containers, by container name"$EBOLD
1453 running_contr_file="./tmp/running_contr.txt"
1454 > $running_contr_file
1456 # Get list of all containers started by the test script
1457 for imagename in $APP_SHORT_NAMES; do
1458 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
1461 tab_heading1="App display name"
1462 tab_heading2="App short name"
1463 tab_heading3="Container name"
1465 tab_heading1_len=${#tab_heading1}
1466 tab_heading2_len=${#tab_heading2}
1467 tab_heading3_len=${#tab_heading3}
1469 #Calc field lengths of each item in the list of containers
1471 if (( $cntr % 3 == 0 ));then
1472 if [ ${#p} -gt $tab_heading1_len ]; then
1473 tab_heading1_len=${#p}
1476 if (( $cntr % 3 == 1));then
1477 if [ ${#p} -gt $tab_heading2_len ]; then
1478 tab_heading2_len=${#p}
1481 if (( $cntr % 3 == 2));then
1482 if [ ${#p} -gt $tab_heading3_len ]; then
1483 tab_heading3_len=${#p}
1487 done <$running_contr_file
1489 let tab_heading1_len=tab_heading1_len+2
1490 while (( ${#tab_heading1} < $tab_heading1_len)); do
1491 tab_heading1="$tab_heading1"" "
1494 let tab_heading2_len=tab_heading2_len+2
1495 while (( ${#tab_heading2} < $tab_heading2_len)); do
1496 tab_heading2="$tab_heading2"" "
1499 let tab_heading3_len=tab_heading3_len+2
1500 while (( ${#tab_heading3} < $tab_heading3_len)); do
1501 tab_heading3="$tab_heading3"" "
1504 echo " $tab_heading1$tab_heading2$tab_heading3"" Actions"
1507 if (( $cntr % 3 == 0 ));then
1510 heading_len=$tab_heading1_len
1512 if (( $cntr % 3 == 1));then
1514 heading_len=$tab_heading2_len
1516 if (( $cntr % 3 == 2));then
1519 heading_len=$tab_heading3_len
1521 while (( ${#heading} < $heading_len)); do
1522 heading="$heading"" "
1525 if (( $cntr % 3 == 2));then
1526 echo -ne $row$SAMELINE
1527 echo -ne " $row ${GREEN}stopping...${EGREEN}${SAMELINE}"
1528 docker stop $(docker ps -qa --filter name=${contr} --filter network=$DOCKER_SIM_NWNAME) &> /dev/null
1529 echo -ne " $row ${GREEN}stopped removing...${EGREEN}${SAMELINE}"
1530 docker rm --force $(docker ps -qa --filter name=${contr} --filter network=$DOCKER_SIM_NWNAME) &> /dev/null
1531 echo -e " $row ${GREEN}stopped removed ${EGREEN}"
1534 done <$running_contr_file
1538 echo -e $BOLD" Removing docker network"$EBOLD
1539 TMP=$(docker network ls -q --filter name=$DOCKER_SIM_NWNAME)
1540 if [ "$TMP" == $DOCKER_SIM_NWNAME ]; then
1541 docker network rm $DOCKER_SIM_NWNAME | indent2
1542 if [ $? -ne 0 ]; then
1543 echo -e $RED" Cannot remove docker network. Manually remove or disconnect containers from $DOCKER_SIM_NWNAME"$ERED
1547 echo -e "$GREEN Done$EGREEN"
1549 echo -e $BOLD" Removing all unused docker neworks"$EBOLD
1550 docker network prune --force | indent2
1551 echo -e "$GREEN Done$EGREEN"
1553 echo -e $BOLD" Removing all unused docker volumes"$EBOLD
1554 docker volume prune --force | indent2
1555 echo -e "$GREEN Done$EGREEN"
1557 echo -e $BOLD" Removing all dangling/untagged docker images"$EBOLD
1558 docker rmi --force $(docker images -q -f dangling=true) &> /dev/null
1559 echo -e "$GREEN Done$EGREEN"
1562 CONTRS=$(docker ps | awk '$1 != "CONTAINER" { n++ }; END { print n+0 }')
1563 if [ $? -eq 0 ]; then
1564 if [ $CONTRS -ne 0 ]; then
1565 echo -e $RED"Containers running, may cause distubance to the test case"$ERED
1566 docker ps -a | indent1
1572 ###################################
1573 ### Functions for kube management
1574 ###################################
1576 # Scale a kube resource to a specific count
1577 # args: <resource-type> <resource-name> <namespace> <target-count>
1578 # (Not for test scripts)
1580 echo -ne " Setting $1 $2 replicas=$4 in namespace $3"$SAMELINE
1581 kubectl scale $1 $2 -n $3 --replicas=$4 1> /dev/null 2> ./tmp/kubeerr
1582 if [ $? -ne 0 ]; then
1583 echo -e " Setting $1 $2 replicas=$4 in namespace $3 $RED Failed $ERED"
1585 echo " Message: $(<./tmp/kubeerr)"
1588 echo -e " Setting $1 $2 replicas=$4 in namespace $3 $GREEN OK $EGREEN"
1593 for i in {1..500}; do
1594 count=$(kubectl get $1/$2 -n $3 -o jsonpath='{.status.replicas}' 2> /dev/null)
1596 if [ -z "$count" ]; then
1597 #No value is sometimes returned for some reason, in case the resource has replica 0
1600 if [ $retcode -ne 0 ]; then
1601 echo -e "$RED Cannot fetch current replica count for $1 $2 in namespace $3 $ERED"
1606 if [ $count -ne $4 ]; then
1607 echo -ne " Waiting for $1 $2 replicas=$4 in namespace $3. Replicas=$count after $(($SECONDS-$TSTART)) seconds $SAMELINE"
1610 echo -e " Waiting for $1 $2 replicas=$4 in namespace $3. Replicas=$count after $(($SECONDS-$TSTART)) seconds"
1611 echo -e " Replicas=$4 after $(($SECONDS-$TSTART)) seconds $GREEN OK $EGREEN"
1617 echo -e "$RED Replica count did not reach target replicas=$4. Failed with replicas=$count $ERED"
1622 # Scale all kube resource sets to 0 in a namespace for resources having a certain lable and label-id
1623 # This function does not wait for the resource to reach 0
1624 # args: <namespace> <label-name> <label-id>
1625 # (Not for test scripts)
1626 __kube_scale_all_resources() {
1630 resources="deployment replicaset statefulset"
1631 for restype in $resources; do
1632 result=$(kubectl get $restype -n $namespace -o jsonpath='{.items[?(@.metadata.labels.'$labelname'=="'$labelid'")].metadata.name}')
1633 if [ $? -eq 0 ] && [ ! -z "$result" ]; then
1634 deleted_resourcetypes=$deleted_resourcetypes" "$restype
1635 for resid in $result; do
1636 echo -ne " Ordered caling $restype $resid from namespace $namespace with label $labelname=$labelid to 0"$SAMELINE
1637 kubectl scale $restype $resid -n $namespace --replicas=0 1> /dev/null 2> ./tmp/kubeerr
1638 echo -e " Ordered scaling $restype $resid from namespace $namespace with label $labelname=$labelid to 0 $GREEN OK $EGREEN"
1644 # Scale all kube resource sets to 0 in a namespace for resources having a certain lable and label-id
1645 # This function do wait for the resource to reach 0
1646 # args: <namespace> <label-name> <label-id>
1647 # (Not for test scripts)
1648 __kube_scale_and_wait_all_resources() {
1652 resources="deployment replicaset statefulset"
1654 while [ $scaled_all -ne 0 ]; do
1656 for restype in $resources; do
1657 result=$(kubectl get $restype -n $namespace -o jsonpath='{.items[?(@.metadata.labels.'$labelname'=="'$labelid'")].metadata.name}')
1658 if [ $? -eq 0 ] && [ ! -z "$result" ]; then
1659 for resid in $result; do
1660 echo -e " Ordered scaling $restype $resid from namespace $namespace with label $labelname=$labelid to 0"
1661 kubectl scale $restype $resid -n $namespace --replicas=0 1> /dev/null 2> ./tmp/kubeerr
1664 while [ $count -ne 0 ]; do
1665 count=$(kubectl get $restype $resid -n $namespace -o jsonpath='{.status.replicas}' 2> /dev/null)
1666 echo -ne " Scaling $restype $resid from namespace $namespace with label $labelname=$labelid to 0,count=$count"$SAMELINE
1667 if [ $? -eq 0 ] && [ ! -z "$count" ]; then
1672 duration=$(($SECONDS-$T_START))
1673 if [ $duration -gt 100 ]; then
1674 #Forcring count 0, to avoid hanging for failed scaling
1679 echo -e " Scaled $restype $resid from namespace $namespace with label $labelname=$labelid to 0,count=$count $GREEN OK $EGREEN"
1686 # Remove all kube resources in a namespace for resources having a certain label and label-id
1687 # This function wait until the resources are gone. Scaling to 0 must have been ordered previously
1688 # args: <namespace> <label-name> <label-id>
1689 # (Not for test scripts)
1690 __kube_delete_all_resources() {
1694 resources="deployments replicaset statefulset services pods configmaps persistentvolumeclaims persistentvolumes"
1695 deleted_resourcetypes=""
1696 for restype in $resources; do
1697 result=$(kubectl get $restype -n $namespace -o jsonpath='{.items[?(@.metadata.labels.'$labelname'=="'$labelid'")].metadata.name}')
1698 if [ $? -eq 0 ] && [ ! -z "$result" ]; then
1699 deleted_resourcetypes=$deleted_resourcetypes" "$restype
1700 for resid in $result; do
1701 if [ $restype == "replicaset" ] || [ $restype == "statefulset" ]; then
1703 while [ $count -ne 0 ]; do
1704 count=$(kubectl get $restype $resid -n $namespace -o jsonpath='{.status.replicas}' 2> /dev/null)
1705 echo -ne " Scaling $restype $resid from namespace $namespace with label $labelname=$labelid to 0,count=$count"$SAMELINE
1706 if [ $? -eq 0 ] && [ ! -z "$count" ]; then
1712 echo -e " Scaled $restype $resid from namespace $namespace with label $labelname=$labelid to 0,count=$count $GREEN OK $EGREEN"
1714 echo -ne " Deleting $restype $resid from namespace $namespace with label $labelname=$labelid "$SAMELINE
1715 kubectl delete $restype $resid -n $namespace 1> /dev/null 2> ./tmp/kubeerr
1716 if [ $? -eq 0 ]; then
1717 echo -e " Deleted $restype $resid from namespace $namespace with label $labelname=$labelid $GREEN OK $EGREEN"
1719 echo -e " Deleted $restype $resid from namespace $namespace with label $labelname=$labelid $GREEN Does not exist - OK $EGREEN"
1725 if [ ! -z "$deleted_resourcetypes" ]; then
1726 for restype in $deleted_resources; do
1727 echo -ne " Waiting for $restype in namespace $namespace with label $labelname=$labelid to be deleted..."$SAMELINE
1730 while [ ! -z "$result" ]; do
1732 result=$(kubectl get $restype -n $namespace -o jsonpath='{.items[?(@.metadata.labels.'$labelname'=="'$labelid'")].metadata.name}')
1733 echo -ne " Waiting for $restype in namespace $namespace with label $labelname=$labelid to be deleted...$(($SECONDS-$T_START)) seconds "$SAMELINE
1734 if [ -z "$result" ]; then
1735 echo -e " Waiting for $restype in namespace $namespace with label $labelname=$labelid to be deleted...$(($SECONDS-$T_START)) seconds $GREEN OK $EGREEN"
1736 elif [ $(($SECONDS-$T_START)) -gt 300 ]; then
1737 echo -e " Waiting for $restype in namespace $namespace with label $labelname=$labelid to be deleted...$(($SECONDS-$T_START)) seconds $RED Failed $ERED"
1745 # Creates a namespace if it does not exists
1747 # (Not for test scripts)
1748 __kube_create_namespace() {
1750 #Check if test namespace exists, if not create it
1751 kubectl get namespace $1 1> /dev/null 2> ./tmp/kubeerr
1752 if [ $? -ne 0 ]; then
1753 echo -ne " Creating namespace "$1 $SAMELINE
1754 kubectl create namespace $1 1> /dev/null 2> ./tmp/kubeerr
1755 if [ $? -ne 0 ]; then
1756 echo -e " Creating namespace $1 $RED$BOLD FAILED $EBOLD$ERED"
1758 echo " Message: $(<./tmp/kubeerr)"
1761 echo -e " Creating namespace $1 $GREEN$BOLD OK $EBOLD$EGREEN"
1764 echo -e " Creating namespace $1 $GREEN$BOLD Already exists, OK $EBOLD$EGREEN"
1769 # Find the host ip of an app (using the service resource)
1770 # args: <app-name> <namespace>
1771 # (Not for test scripts)
1772 __kube_get_service_host() {
1773 if [ $# -ne 2 ]; then
1775 __print_err "need 2 args, <app-name> <namespace>" $@
1778 for timeout in {1..60}; do
1779 host=$(kubectl get svc $1 -n $2 -o jsonpath='{.spec.clusterIP}')
1780 if [ $? -eq 0 ]; then
1781 if [ ! -z "$host" ]; then
1789 echo "host-not-found-fatal-error"
1793 # Find the named port to an app (using the service resource)
1794 # args: <app-name> <namespace> <port-name>
1795 # (Not for test scripts)
1796 __kube_get_service_port() {
1797 if [ $# -ne 3 ]; then
1799 __print_err "need 3 args, <app-name> <namespace> <port-name>" $@
1803 for timeout in {1..60}; do
1804 port=$(kubectl get svc $1 -n $2 -o jsonpath='{...ports[?(@.name=="'$3'")].port}')
1805 if [ $? -eq 0 ]; then
1806 if [ ! -z "$port" ]; then
1818 # Find the named node port to an app (using the service resource)
1819 # args: <app-name> <namespace> <port-name>
1820 # (Not for test scripts)
1821 __kube_get_service_nodeport() {
1822 if [ $# -ne 3 ]; then
1824 __print_err "need 3 args, <app-name> <namespace> <port-name>" $@
1828 for timeout in {1..60}; do
1829 port=$(kubectl get svc $1 -n $2 -o jsonpath='{...ports[?(@.name=="'$3'")].nodePort}')
1830 if [ $? -eq 0 ]; then
1831 if [ ! -z "$port" ]; then
1843 # Create a kube resource from a yaml template
1844 # args: <resource-type> <resource-name> <template-yaml> <output-yaml>
1845 # (Not for test scripts)
1846 __kube_create_instance() {
1847 echo -ne " Creating $1 $2"$SAMELINE
1849 kubectl apply -f $4 1> /dev/null 2> ./tmp/kubeerr
1850 if [ $? -ne 0 ]; then
1852 echo -e " Creating $1 $2 $RED Failed $ERED"
1853 echo " Message: $(<./tmp/kubeerr)"
1856 echo -e " Creating $1 $2 $GREEN OK $EGREEN"
1860 # Function to create a configmap in kubernetes
1861 # args: <configmap-name> <namespace> <labelname> <labelid> <path-to-data-file> <path-to-output-yaml>
1862 # (Not for test scripts)
1863 __kube_create_configmap() {
1864 echo -ne " Creating configmap $1 "$SAMELINE
1865 envsubst < $5 > $5"_tmp"
1866 cp $5"_tmp" $5 #Need to copy back to orig file name since create configmap neeed the original file name
1867 kubectl create configmap $1 -n $2 --from-file=$5 --dry-run=client -o yaml > $6
1868 if [ $? -ne 0 ]; then
1869 echo -e " Creating configmap $1 $RED Failed $ERED"
1874 kubectl apply -f $6 1> /dev/null 2> ./tmp/kubeerr
1875 if [ $? -ne 0 ]; then
1876 echo -e " Creating configmap $1 $RED Apply failed $ERED"
1877 echo " Message: $(<./tmp/kubeerr)"
1881 kubectl label configmap $1 -n $2 $3"="$4 --overwrite 1> /dev/null 2> ./tmp/kubeerr
1882 if [ $? -ne 0 ]; then
1883 echo -e " Creating configmap $1 $RED Labeling failed $ERED"
1884 echo " Message: $(<./tmp/kubeerr)"
1888 # Log the resulting map
1889 kubectl get configmap $1 -n $2 -o yaml > $6
1891 echo -e " Creating configmap $1 $GREEN OK $EGREEN"
1895 # This function runs a kubectl cmd where a single output value is expected, for example get ip with jsonpath filter.
1896 # The function retries up to the timeout given in the cmd flag '--cluster-timeout'
1897 # args: <full kubectl cmd with parameters>
1898 # (Not for test scripts)
1899 __kube_cmd_with_timeout() {
1900 TS_TMP=$(($SECONDS+$CLUSTER_TIME_OUT))
1903 kube_cmd_result=$($@)
1904 if [ $? -ne 0 ]; then
1907 if [ $SECONDS -ge $TS_TMP ] || [ ! -z "$kube_cmd_result" ] ; then
1908 echo $kube_cmd_result
1915 # This function starts a pod that cleans a the contents of a path mounted as a pvc
1916 # After this action the pod should terminate
1917 # This should only be executed when the pod owning the pvc is not running
1918 # args: <appname> <namespace> <pvc-name> <path-to remove>
1919 # (Not for test scripts)
1920 __kube_clean_pvc() {
1922 export PVC_CLEANER_NAMESPACE=$2
1923 export PVC_CLEANER_CLAIMNAME=$3
1924 export PVC_CLEANER_RM_PATH=$4
1925 input_yaml=$SIM_GROUP"/pvc-cleaner/"pvc-cleaner.yaml
1926 output_yaml=$PWD/tmp/$2-pvc-cleaner.yaml
1928 envsubst < $input_yaml > $output_yaml
1930 kubectl delete -f $output_yaml #> /dev/null 2>&1 # Delete the previous terminated pod - if existing
1932 __kube_create_instance pod pvc-cleaner $input_yaml $output_yaml
1933 if [ $? -ne 0 ]; then
1934 echo $YELLOW" Could not clean pvc for app: $1 - persistent storage not clean - tests may not work"
1938 term_ts=$(($SECONDS+30))
1939 while [ $term_ts -gt $SECONDS ]; do
1940 pod_status=$(kubectl get pod pvc-cleaner -n $PVC_CLEANER_NAMESPACE --no-headers -o custom-columns=":status.phase")
1941 if [ "$pod_status" == "Succeeded" ]; then
1948 # This function scales or deletes all resources for app selected by the testcase.
1950 # (Not for test scripts)
1952 echo -e $BOLD"Initialize kube services//pods/statefulsets/replicaset to initial state"$EBOLD
1954 # Scale prestarted or managed apps
1955 for imagename in $APP_SHORT_NAMES; do
1956 # A function name is created from the app short name
1957 # for example app short name 'RICMSIM' -> produce the function
1958 # name __RICSIM_kube_scale_zero or __RICSIM_kube_scale_zero_and_wait
1959 # This function is called and is expected to exist in the imported
1960 # file for the ricsim test functions
1961 # The resulting function impl shall scale the resources to 0
1962 # For prestarted apps, the function waits until the resources are 0
1963 # For included (not prestated) apps, the scaling is just ordered
1964 __check_prestarted_image $imagename
1965 if [ $? -eq 0 ]; then
1966 function_pointer="__"$imagename"_kube_scale_zero_and_wait"
1967 echo -e " Scaling all kube resources for app $BOLD $imagename $EBOLD to 0"
1970 __check_included_image $imagename
1971 if [ $? -eq 0 ]; then
1972 function_pointer="__"$imagename"_kube_scale_zero"
1973 echo -e " Scaling all kube resources for app $BOLD $imagename $EBOLD to 0"
1979 # Delete managed apps
1980 for imagename in $APP_SHORT_NAMES; do
1981 __check_included_image $imagename
1982 if [ $? -eq 0 ]; then
1983 __check_prestarted_image $imagename
1984 if [ $? -ne 0 ]; then
1985 # A function name is created from the app short name
1986 # for example app short name 'RICMSIM' -> produce the function
1987 # name __RICSIM__kube_delete_all
1988 # This function is called and is expected to exist in the imported
1989 # file for the ricsim test functions
1990 # The resulting function impl shall delete all its resources
1991 function_pointer="__"$imagename"_kube_delete_all"
1992 echo -e " Deleting all kube resources for app $BOLD $imagename $EBOLD"
2001 # Function stop and remove all containers (docker) and services/deployments etc(kube)
2003 # Function for test script
2004 clean_environment() {
2005 if [ $RUNMODE == "KUBE" ]; then
2012 # 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
2014 # (Function for test scripts)
2015 auto_clean_environment() {
2017 if [ "$AUTO_CLEAN" == "auto" ]; then
2018 echo -e $BOLD"Initiating automatic cleaning of environment"$EBOLD
2023 # Function to sleep a test case for a numner of seconds. Prints the optional text args as info
2024 # args: <sleep-time-in-sec> [any-text-in-quotes-to-be-printed]
2025 # (Function for test scripts)
2028 echo -e $BOLD"INFO(${BASH_LINENO[0]}): "${FUNCNAME[0]}"," $@ $EBOLD
2029 if [ $# -lt 1 ]; then
2031 __print_err "need at least one arg, <sleep-time-in-sec> [any-text-to-printed]" $@
2034 #echo "---- Sleep for " $1 " seconds ---- "$2
2036 duration=$((SECONDS-start))
2037 while [ $duration -lt $1 ]; do
2038 echo -ne " Slept for ${duration} seconds${SAMELINE}"
2040 duration=$((SECONDS-start))
2042 echo -ne " Slept for ${duration} seconds${SAMELINE}"
2046 # Print error info for the call in the parent script (test case). Arg: <error-message-to-print>
2047 # Not to be called from the test script itself.
2049 echo -e $RED ${FUNCNAME[1]} " "$1" " ${BASH_SOURCE[2]} " line" ${BASH_LINENO[1]} $ERED
2050 if [ $# -gt 1 ]; then
2051 echo -e $RED" Got: "${FUNCNAME[1]} ${@:2} $ERED
2056 # Function to create the docker network for the test
2057 # Not to be called from the test script itself.
2058 __create_docker_network() {
2059 tmp=$(docker network ls --format={{.Name}} --filter name=$DOCKER_SIM_NWNAME)
2060 if [ $? -ne 0 ]; then
2061 echo -e $RED" Could not check if docker network $DOCKER_SIM_NWNAME exists"$ERED
2064 if [ "$tmp" != $DOCKER_SIM_NWNAME ]; then
2065 echo -e " Creating docker network:$BOLD $DOCKER_SIM_NWNAME $EBOLD"
2066 docker network create $DOCKER_SIM_NWNAME | indent2
2067 if [ $? -ne 0 ]; then
2068 echo -e $RED" Could not create docker network $DOCKER_SIM_NWNAME"$ERED
2071 echo -e "$GREEN Done$EGREEN"
2074 echo -e " Docker network $DOCKER_SIM_NWNAME already exists$GREEN OK $EGREEN"
2078 # Function to start container with docker-compose and wait until all are in state running.
2079 # If the <docker-compose-file> is empty, the default 'docker-compose.yml' is assumed.
2080 #args: <docker-compose-dir> <docker-compose-file> <docker-compose-arg>|NODOCKERARGS <count> <app-name>+
2081 # (Not for test scripts)
2082 __start_container() {
2084 if [ $# -lt 5 ]; then
2086 __print_err "need 5 or more args, <docker-compose-dir> <docker-compose-file> <docker-compose-arg>|NODOCKERARGS <count> <app-name>+" $@
2090 __create_docker_network
2098 if [ -z "$compose_file" ]; then
2099 compose_file="docker-compose.yml"
2107 os_version=$(uname -a 2> /dev/null | awk '{print tolower($0)}' | grep "microsoft")
2108 if [[ "$os_version" == *"microsoft"* ]]; then
2109 echo -e $YELLOW" Workaround for Linux on Win - delay container start, 1 sec, to make sure files mounted in the container are available on disk - WLS problem"$EYELLOW
2114 if [ "$compose_args" == "NODOCKERARGS" ]; then
2115 docker-compose -f $compose_file up -d &> .dockererr
2116 if [ $? -ne 0 ]; then
2117 echo -e $RED"Problem to launch container(s) with docker-compose"$ERED
2119 echo -e $RED"Stopping script...."$ERED
2123 docker-compose -f $compose_file up -d $compose_args &> .dockererr
2124 if [ $? -ne 0 ]; then
2125 echo -e $RED"Problem to launch container(s) with docker-compose"$ERED
2127 echo -e $RED"Stopping script...."$ERED
2135 while [ $appindex -lt $appcount ]; do
2139 for i in {1..10}; do
2140 if [ "$(docker inspect --format '{{ .State.Running }}' $appname)" == "true" ]; then
2141 echo -e " Container $BOLD${appname}$EBOLD$GREEN running$EGREEN on$BOLD image $(docker inspect --format '{{ .Config.Image }}' ${appname}) $EBOLD"
2148 if [ $app_started -eq 0 ]; then
2151 echo -e $RED" Container $BOLD${appname}$EBOLD could not be started"$ERED
2152 echo -e $RED" Stopping script..."$ERED
2155 let appindex=appindex+1
2160 # Function to check if container/service is responding to http/https
2161 # args: <container-name>|<service-name> url
2162 # (Not for test scripts)
2163 __check_service_start() {
2165 if [ $# -ne 2 ]; then
2167 __print_err "need 2 args, <container-name>|<service-name> url" $@
2171 if [ $RUNMODE == "KUBE" ]; then
2172 ENTITY="service/set/deployment"
2178 echo -ne " Container $BOLD${appname}$EBOLD starting${SAMELINE}"
2182 echo -ne " Waiting for ${ENTITY} ${appname} service status...${SAMELINE}"
2185 while (( $TSTART+600 > $SECONDS )); do
2186 result="$(__do_curl -m 10 $url)"
2187 if [ $? -eq 0 ]; then
2188 if [ ${#result} -gt 15 ]; then
2189 #If response is too long, truncate
2190 result="...response text too long, omitted"
2192 echo -ne " Waiting for {ENTITY} $BOLD${appname}$EBOLD service status on ${3}, result: $result${SAMELINE}"
2193 echo -ne " The ${ENTITY} $BOLD${appname}$EBOLD$GREEN is alive$EGREEN, responds to service status:$GREEN $result $EGREEN on ${url} after $(($SECONDS-$TSTART)) seconds"
2199 if (( $TS_OFFSET > 5 )); then
2202 while [ $(($TS_TMP+$TS_OFFSET)) -gt $SECONDS ]; do
2203 echo -ne " Waiting for ${ENTITY} ${appname} service status on ${url}...$(($SECONDS-$TSTART)) seconds, retrying in $(($TS_TMP+$TS_OFFSET-$SECONDS)) seconds ${SAMELINE}"
2207 let loop_ctr=loop_ctr+1
2210 if [ "$pa_st" = "false" ]; then
2212 echo -e $RED" The ${ENTITY} ${appname} did not respond to service status on ${url} in $(($SECONDS-$TSTART)) seconds"$ERED
2225 __check_container_logs() {
2233 echo -e $BOLD"Checking $dispname container $appname log ($logpath) for WARNINGs and ERRORs"$EBOLD
2235 if [ $RUNMODE == "KUBE" ]; then
2236 echo -e $YELLOW" Internal log for $dispname not checked in kube"$EYELLOW
2240 #tmp=$(docker ps | grep $appname)
2241 tmp=$(docker ps -q --filter name=$appname) #get the container id
2242 if [ -z "$tmp" ]; then #Only check logs for running Policy Agent apps
2243 echo " "$dispname" is not running, no check made"
2246 foundentries="$(docker exec -t $tmp grep $warning $logpath | wc -l)"
2247 if [ $? -ne 0 ];then
2248 echo " Problem to search $appname log $logpath"
2250 if [ $foundentries -eq 0 ]; then
2251 echo " No WARN entries found in $appname log $logpath"
2253 echo -e " Found \033[1m"$foundentries"\033[0m WARN entries in $appname log $logpath"
2256 foundentries="$(docker exec -t $tmp grep $error $logpath | wc -l)"
2257 if [ $? -ne 0 ];then
2258 echo " Problem to search $appname log $logpath"
2260 if [ $foundentries -eq 0 ]; then
2261 echo " No ERR entries found in $appname log $logpath"
2263 echo -e $RED" Found \033[1m"$foundentries"\033[0m"$RED" ERR entries in $appname log $logpath"$ERED
2269 # Store all container logs and other logs in the log dir for the script
2270 # Logs are stored with a prefix in case logs should be stored several times during a test
2271 # args: <logfile-prefix>
2272 # (Function for test scripts)
2274 if [ $# != 1 ]; then
2276 __print_err "need one arg, <file-prefix>" $@
2279 echo -e $BOLD"Storing all docker/kube container logs and other test logs in $TESTLOGS/$ATC using prefix: "$1$EBOLD
2281 docker stats --no-stream > $TESTLOGS/$ATC/$1_docker_stats.log 2>&1
2283 docker ps -a > $TESTLOGS/$ATC/$1_docker_ps.log 2>&1
2285 cp .httplog_${ATC}.txt $TESTLOGS/$ATC/$1_httplog_${ATC}.txt 2>&1
2287 if [ $RUNMODE == "DOCKER" ]; then
2289 # Store docker logs for all container
2290 for imagename in $APP_SHORT_NAMES; do
2291 __check_included_image $imagename
2292 if [ $? -eq 0 ]; then
2293 # A function name is created from the app short name
2294 # for example app short name 'RICMSIM' -> produce the function
2295 # name __RICSIM__store_docker_logs
2296 # This function is called and is expected to exist in the imported
2297 # file for the ricsim test functions
2298 # The resulting function impl shall store the docker logs for each container
2299 function_pointer="__"$imagename"_store_docker_logs"
2300 $function_pointer "$TESTLOGS/$ATC/" $1
2304 if [ $RUNMODE == "KUBE" ]; then
2305 namespaces=$(kubectl get namespaces -o jsonpath='{.items[?(@.metadata.name)].metadata.name}')
2306 for nsid in $namespaces; do
2307 pods=$(kubectl get pods -n $nsid -o jsonpath='{.items[?(@.metadata.labels.autotest)].metadata.name}')
2308 for podid in $pods; do
2309 kubectl logs -n $nsid $podid > $TESTLOGS/$ATC/$1_${podid}.log
2319 # Generic curl function, assumes all 200-codes are ok
2320 # args: <valid-curl-args-including full url>
2321 # returns: <returned response (without respose code)> or "<no-response-from-server>" or "<not found, <http-code>>""
2322 # returns: The return code is 0 for ok and 1 for not ok
2324 echo ${FUNCNAME[1]} "line: "${BASH_LINENO[1]} >> $HTTPLOG
2326 if [ $RUNMODE == "KUBE" ]; then
2327 if [ ! -z "$KUBE_PROXY_PATH" ]; then
2328 proxyflag=" --proxy $KUBE_PROXY_PATH"
2331 curlString="curl -skw %{http_code} $proxyflag $@"
2332 echo " CMD: $curlString" >> $HTTPLOG
2335 echo " RESP: $res" >> $HTTPLOG
2336 echo " RETCODE: $retcode" >> $HTTPLOG
2337 if [ $retcode -ne 0 ]; then
2338 echo "<no-response-from-server>"
2341 http_code="${res:${#res}-3}"
2342 if [ ${#res} -eq 3 ]; then
2343 if [ $http_code -lt 200 ] || [ $http_code -gt 299 ]; then
2344 echo "<no-response-from-server>"
2350 if [ $http_code -lt 200 ] || [ $http_code -gt 299 ]; then
2351 echo "<not found, resp:${http_code}>"
2354 if [ $# -eq 2 ]; then
2355 echo "${res:0:${#res}-3}" | xargs
2357 echo "${res:0:${#res}-3}"
2364 #######################################
2365 ### Basic helper function for test cases
2366 #######################################
2368 # Test a simulator container variable value towards target value using an condition operator with an optional timeout.
2369 # Arg: <simulator-name> <host> <variable-name> <condition-operator> <target-value> - This test is done
2370 # immediately and sets pass or fail depending on the result of comparing variable and target using the operator.
2371 # Arg: <simulator-name> <host> <variable-name> <condition-operator> <target-value> <timeout> - This test waits up to the timeout
2372 # before setting pass or fail depending on the result of comparing variable and target using the operator.
2373 # 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.
2374 # Not to be called from test script.
2377 checkjsonarraycount=0
2379 if [ $# -eq 6 ]; then
2380 if [[ $3 == "json:"* ]]; then
2381 checkjsonarraycount=1
2384 echo -e $BOLD"TEST $TEST_SEQUENCE_NR (${BASH_LINENO[1]}): ${1}, ${3} ${4} ${5} within ${6} seconds"$EBOLD
2386 ((TEST_SEQUENCE_NR++))
2390 if [ $checkjsonarraycount -eq 0 ]; then
2391 result="$(__do_curl $2$3)"
2393 result=${result//[[:blank:]]/} #Strip blanks
2396 result="$(__do_curl $2$path)"
2398 echo "$result" > ./tmp/.tmp.curl.json
2399 result=$(python3 ../common/count_json_elements.py "./tmp/.tmp.curl.json")
2401 duration=$((SECONDS-start))
2402 echo -ne " Result=${result} after ${duration} seconds${SAMELINE}"
2404 if [ $retcode -ne 0 ]; then
2405 if [ $duration -gt $6 ]; then
2407 echo -e $RED" FAIL${ERED} - ${3} ${4} ${5} not reached in ${6} seconds, result = ${result}"
2408 __check_stop_at_error
2411 elif [ $4 = "=" ] && [ "$result" -eq $5 ]; then
2413 echo -e " Result=${result} after ${duration} seconds${SAMELINE}"
2414 echo -e $GREEN" PASS${EGREEN} - Result=${result} after ${duration} seconds"
2416 elif [ $4 = ">" ] && [ "$result" -gt $5 ]; then
2418 echo -e " Result=${result} after ${duration} seconds${SAMELINE}"
2419 echo -e $GREEN" PASS${EGREEN} - Result=${result} after ${duration} seconds"
2421 elif [ $4 = "<" ] && [ "$result" -lt $5 ]; then
2423 echo -e " Result=${result} after ${duration} seconds${SAMELINE}"
2424 echo -e $GREEN" PASS${EGREEN} - Result=${result} after ${duration} seconds"
2426 elif [ $4 = "contain_str" ] && [[ $result =~ $5 ]]; then
2428 echo -e " Result=${result} after ${duration} seconds${SAMELINE}"
2429 echo -e $GREEN" PASS${EGREEN} - Result=${result} after ${duration} seconds"
2432 if [ $duration -gt $6 ]; then
2434 echo -e $RED" FAIL${ERED} - ${3} ${4} ${5} not reached in ${6} seconds, result = ${result}"
2435 __check_stop_at_error
2441 elif [ $# -eq 5 ]; then
2442 if [[ $3 == "json:"* ]]; then
2443 checkjsonarraycount=1
2446 echo -e $BOLD"TEST $TEST_SEQUENCE_NR (${BASH_LINENO[1]}): ${1}, ${3} ${4} ${5}"$EBOLD
2448 ((TEST_SEQUENCE_NR++))
2449 if [ $checkjsonarraycount -eq 0 ]; then
2450 result="$(__do_curl $2$3)"
2452 result=${result//[[:blank:]]/} #Strip blanks
2455 result="$(__do_curl $2$path)"
2457 echo "$result" > ./tmp/.tmp.curl.json
2458 result=$(python3 ../common/count_json_elements.py "./tmp/.tmp.curl.json")
2460 if [ $retcode -ne 0 ]; then
2462 echo -e $RED" FAIL ${ERED}- ${3} ${4} ${5} not reached, result = ${result}"
2463 __check_stop_at_error
2464 elif [ $4 = "=" ] && [ "$result" -eq $5 ]; then
2466 echo -e $GREEN" PASS${EGREEN} - Result=${result}"
2467 elif [ $4 = ">" ] && [ "$result" -gt $5 ]; then
2469 echo -e $GREEN" PASS${EGREEN} - Result=${result}"
2470 elif [ $4 = "<" ] && [ "$result" -lt $5 ]; then
2472 echo -e $GREEN" PASS${EGREEN} - Result=${result}"
2473 elif [ $4 = "contain_str" ] && [[ $result =~ $5 ]]; then
2475 echo -e $GREEN" PASS${EGREEN} - Result=${result}"
2478 echo -e $RED" FAIL${ERED} - ${3} ${4} ${5} not reached, result = ${result}"
2479 __check_stop_at_error
2482 echo "Wrong args to __var_test, needs five or six args: <simulator-name> <host> <variable-name> <condition-operator> <target-value> [ <timeout> ]"