3 # ============LICENSE_START===============================================
4 # Copyright (C) 2020-22023 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>+] [--use-external-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] [--gen-stats] [--delete-namespaces]"
32 echo " [--delete-containers] [--endpoint-stats] [--kubeconfig <config-file>] [--host-path-dir <local-host-dir>]"
33 echo " [--kubecontext <context-name>] [--docker-host <docker-host-url>] [--docker-proxy <host-or-ip>]"
34 echo " [--target-platform <platform> ]"
37 if [ $# -eq 1 ] && [ "$1" == "help" ]; then
39 if [ ! -z "$TC_ONELINE_DESCR" ]; then
40 echo "Test script description:"
41 echo $TC_ONELINE_DESCR
46 echo "remote - Use images from remote repositories. Can be overridden for individual images using the '--use_xxx' flags"
47 echo "remote-remove - Same as 'remote' but will also try to pull fresh images from remote repositories"
48 echo "docker - Test executed in docker environment"
49 echo "kube - Test executed in kubernetes environment - requires an already started kubernetes environment"
50 echo "--env-file <file> - The script will use the supplied file to read environment variables from"
51 echo "release - If this flag is given the script will use release version of the images"
52 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."
53 echo "--stop-at-error - The script will stop when the first failed test or configuration"
54 echo "--ricsim-prefix - The a1 simulator will use the supplied string as container prefix instead of 'ricsim'"
55 echo "--use-local-image - The script will use local images for the supplied apps, space separated list of app short names"
56 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"
57 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"
58 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"
59 echo "--use-external-image - The script will use images from the external (non oran/onap) repo for the supplied apps, space separated list of app short names"
60 echo "--image-repo - Url to optional image repo. Only locally built images will be re-tagged and pushed to this repo"
61 echo "--repo-policy - Policy controlling which images to re-tag and push if param --image-repo is set. Default is 'local'"
62 echo "--cluster-timeout - Optional timeout for cluster where it takes time to obtain external ip/host-name. Timeout in seconds. "
63 echo "--print-stats - Print current test stats after each test."
64 echo "--override <file> - Override setting from the file supplied by --env-file"
65 echo "--pre-clean - Will clean kube resouces when running docker and vice versa"
66 echo "--gen-stats - Collect container/pod runtime statistics"
67 echo "--delete-namespaces - Delete kubernetes namespaces before starting tests - but only those created by the test scripts. Kube mode only. Ignored if running with pre-started apps."
68 echo "--delete-containers - Delete docker containers before starting tests - but only those created by the test scripts. Docker mode only."
69 echo "--endpoint-stats - Collect endpoint statistics"
70 echo "--kubeconfig - Configure kubectl to use cluster specific cluster config file"
71 echo "--host-path-dir - (Base-)path on local-hostmounted to all VMs (nodes), for hostpath volumes in kube"
72 echo "--kubecontext - Configure kubectl to use a certain context, e.g 'minikube'"
73 echo "--docker-host - Configure docker to use docker in e.g. a VM"
74 echo "--docker-proxy - Configure ip/host to docker when docker is running in a VM"
75 echo "--target-platform - Build and pull images for this target platform"
77 echo "List of app short names supported: "$APP_SHORT_NAMES
82 # Create a test case id, ATC (Auto Test Case), from the name of the test case script.
83 # FTC1.sh -> ATC == FTC1
84 ATC=$(basename "${BASH_SOURCE[$i+1]}" .sh)
86 #Create result file (containing '1' for error) for this test case
87 #Will be replaced with a file containing '0' if all test cases pass
88 echo "1" > "$PWD/.result$ATC.txt"
90 #Formatting for 'echo' cmd
95 GREEN="\033[32m\033[1m"
97 YELLOW="\033[33m\033[1m"
101 # Just resetting any previous echo formatting...
104 # default test environment variables
106 #Override env file, will be added on top of the above file
107 TEST_ENV_VAR_FILE_OVERRIDE=""
109 echo "Test case started as: ${BASH_SOURCE[$i+1]} "$@
111 # Var to hold 'auto' in case containers shall be stopped when test case ends
114 # Var to indicate pre clean, if flag --pre-clean is set the script will clean kube resources when running docker and vice versa
117 # Var to hold the app names to use local images for
120 # Var to hold the app names to use remote snapshot images for
121 USE_SNAPSHOT_IMAGES=""
123 # Var to hold the app names to use remote staging images for
124 USE_STAGING_IMAGES=""
126 # Var to hold the app names to use remote release images for
127 USE_RELEASE_IMAGES=""
129 # Var to hold the app names to use external release images for
130 USE_EXTERNAL_IMAGES=""
132 # 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
135 # The default value "DEV" indicate that development image tags (SNAPSHOT) and nexus repos (nexus port 10002) are used.
136 # The value "RELEASE" indicate that released image tag and nexus repos (nexus port) are used
137 # Applies only to images defined in the test-env files with image names and tags defined as XXXX_RELEASE
140 #Var to indicate docker-compose version, V1 or V2. V1 is not supported.
141 #V1 names replicated containers <proj-name>_<service-name>_<index>
142 #V2 names replicated containers <proj-name>-<service-name>-<index>
143 DOCKER_COMPOSE_VERSION="V2"
145 # Name of target platform, if set by start cmd
146 IMAGE_TARGET_PLATFORM=""
147 IMAGE_TARGET_PLATFORM_CMD_PARAM="" # Docker cmd param for setting target platform
148 IMAGE_TARGET_PLATFORM_IMG_TAG="" # Will be set to target platform if cmd parameter is set
149 IMAGE_TARGET_PLATFORM_IMG_TAG=$(docker info --format '{{json . }}' | jq -r .Architecture | sed 's/\//_/g')
151 # Function to indent cmd output with one space
152 indent1() { sed 's/^/ /'; }
154 # Function to indent cmd output with two spaces
155 indent2() { sed 's/^/ /'; }
157 # Set a description string for the test case
158 if [ -z "$TC_ONELINE_DESCR" ]; then
159 TC_ONELINE_DESCR="<no-description>"
160 echo "No test case description found, TC_ONELINE_DESCR should be set on in the test script , using "$TC_ONELINE_DESCR
163 # Counter for test suites
164 if [ -f .tmp_tcsuite_ctr ]; then
165 tmpval=$(< .tmp_tcsuite_ctr)
167 echo $tmpval > .tmp_tcsuite_ctr
170 # Create the logs dir if not already created in the current dir
171 if [ ! -d "logs" ]; then
176 # Create the tmp dir for temporary files that is not needed after the test
177 # hidden files for the test env is still stored in the current dir
178 # files in the ./tmp is moved to ./tmp/prev when a new test is started
179 if [ ! -d "tmp" ]; then
181 if [ $? -ne 0 ]; then
182 echo "Cannot create dir for temp files, $PWD/tmp"
189 if [ $? -ne 0 ]; then
190 echo "Cannot cd to $PWD/tmp"
195 TESTENV_TEMP_FILES=$PWD
197 if [ ! -d "prev" ]; then
199 if [ $? -ne 0 ]; then
200 echo "Cannot create dir for previous temp files, $PWD/prev"
206 TMPFILES=$(ls -A | grep -vw prev)
207 if [ ! -z "$TMPFILES" ]; then
208 cp -r $TMPFILES prev #Move all temp files to prev dir
209 if [ $? -ne 0 ]; then
210 echo "Cannot move temp files in $PWD to previous temp files in, $PWD/prev"
214 if [ $(pwd | xargs basename) == "tmp" ]; then #Check that current dir is tmp...for safety
216 rm -rf $TMPFILES # Remove all temp files
221 if [ $? -ne 0 ]; then
222 echo "Cannot cd to $curdir"
228 # Create a http message log for this testcase
229 HTTPLOG=$PWD"/.httplog_"$ATC".txt"
232 # Create a log dir for the test case
233 mkdir -p $TESTLOGS/$ATC
235 # Save create for current logs
236 mkdir -p $TESTLOGS/$ATC/previous
238 rm $TESTLOGS/$ATC/previous/*.log &> /dev/null
239 rm $TESTLOGS/$ATC/previous/*.txt &> /dev/null
240 rm $TESTLOGS/$ATC/previous/*.json &> /dev/null
242 mv $TESTLOGS/$ATC/*.log $TESTLOGS/$ATC/previous &> /dev/null
243 mv $TESTLOGS/$ATC/*.txt $TESTLOGS/$ATC/previous &> /dev/null
244 mv $TESTLOGS/$ATC/*.txt $TESTLOGS/$ATC/previous &> /dev/null
246 # Clear the log dir for the test case
247 rm $TESTLOGS/$ATC/*.log &> /dev/null
248 rm $TESTLOGS/$ATC/*.txt &> /dev/null
249 rm $TESTLOGS/$ATC/*.json &> /dev/null
251 #Create result file in the log dir
252 echo "1" > "$TESTLOGS/$ATC/.result$ATC.txt"
254 # Log all output from the test case to a TC log
255 TCLOG=$TESTLOGS/$ATC/TC.log
256 exec &> >(tee ${TCLOG})
258 echo $(date) > $TESTLOGS/$ATC/endpoint_tc_start.log
259 echo "$TC_ONELINE_DESCR" > $TESTLOGS/$ATC/endpoint_tc_slogan.log
260 echo "Test failed" > $TESTLOGS/$ATC/endpoint_tc_end.log # Will be overwritten if test is ok
262 #Variables for counting tests as well as passed and failed tests
269 #Var to control if current stats shall be printed
270 PRINT_CURRENT_STATS=0
272 #Var to control if container/pod runtime statistics shall be collected
273 COLLECT_RUNTIME_STATS=0
274 COLLECT_RUNTIME_STATS_PID=0
276 #Var to control if endpoint statistics shall be collected
277 COLLECT_ENDPOINT_STATS=0
279 #Var to control if namespaces shall be delete before test setup
280 DELETE_KUBE_NAMESPACES=0
282 #Var to control if containers shall be delete before test setup
285 #Var to configure kubectl from a config file or context
288 #Localhost, may be set to another host/ip by cmd parameter
289 LOCALHOST_NAME="localhost"
291 #Resetting vars related to token/keys used by kubeproxy when istio is enabled
292 #The vars are populated if istio is used in the testcase
293 KUBE_PROXY_CURL_JWT=""
294 KUBE_PROXY_ISTIO_JWKS_KEYS=""
296 #Var pointing to dir mounted to each kubernetes node (master and workers)
297 #Persistent volumes using "hostpath" are allocated beneath the point.
298 #Typically it is a dir on local host mounted to each VM running the master and worker.
299 #So the intention is make this dir available so the PODs can be restarted on any
300 #node and still access the persistent data
301 #If not set from cmd line, the path is defaults to "/tmp"
302 HOST_PATH_BASE_DIR=""
304 #File to keep deviation messages
305 DEVIATION_FILE=".tmp_deviations"
306 rm $DEVIATION_FILE &> /dev/null
308 # Trap "command not found" and make the script fail
311 if [ $? -eq 127 ]; then
312 echo -e $RED"Function not found, setting script to FAIL"$ERED
314 __print_current_stats
319 # Trap to kill subprocess for stats collection (if running)
321 if [ $COLLECT_RUNTIME_STATS_PID -ne 0 ]; then
322 kill $COLLECT_RUNTIME_STATS_PID
330 # Function to log the start of a test case
332 TIMESTAMP=$(date "+%Y-%m-%d %H:%M:%S")
333 echo -e $BOLD"TEST $TEST_SEQUENCE_NR - (${BASH_LINENO[1]}) - ${TIMESTAMP}: ${FUNCNAME[1]}" $@ $EBOLD
334 echo "TEST $TEST_SEQUENCE_NR - (${BASH_LINENO[1]}) - ${TIMESTAMP}: ${FUNCNAME[1]}" $@ >> $HTTPLOG
336 ((TEST_SEQUENCE_NR++))
339 # Function to print current statistics
340 __print_current_stats() {
341 if [ $PRINT_CURRENT_STATS -ne 0 ]; then
342 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"
346 # General function to log a failed test case
347 __log_test_fail_general() {
348 echo -e $RED" FAIL."$1 $ERED
350 __print_current_stats
351 __check_stop_at_error
354 # Function to log a test case failed due to incorrect response code
355 __log_test_fail_status_code() {
356 echo -e $RED" FAIL. Expected status "$1", got "$2 $3 $ERED
358 __print_current_stats
359 __check_stop_at_error
362 # Function to log a test case failed due to incorrect response body
363 __log_test_fail_body() {
364 echo -e $RED" FAIL, returned body not correct"$ERED
366 __print_current_stats
367 __check_stop_at_error
370 # Function to log a test case that is not supported
371 __log_test_fail_not_supported() {
372 echo -e $RED" FAIL, function not supported"$ERED
374 __print_current_stats
375 __check_stop_at_error
378 # Function to log a test case that is not supported but will not fail
379 __log_test_info_not_supported() {
380 echo -e $YELLOW" INFO, function not supported"$YELLOW
381 __print_current_stats
384 # General function to log a passed test case
386 if [ $# -gt 0 ]; then
390 echo -e $GREEN" PASS"$EGREEN
391 __print_current_stats
394 #Counter for configurations
397 # Function to log the start of a configuration setup
399 TIMESTAMP=$(date "+%Y-%m-%d %H:%M:%S")
400 echo -e $BOLD"CONF $CONF_SEQUENCE_NR - (${BASH_LINENO[1]}) - ${TIMESTAMP}: "${FUNCNAME[1]} $@ $EBOLD
401 echo "CONF $CONF_SEQUENCE_NR - (${BASH_LINENO[1]}) - ${TIMESTAMP}: "${FUNCNAME[1]} $@ >> $HTTPLOG
402 ((CONF_SEQUENCE_NR++))
405 # Function to log a failed configuration setup
406 __log_conf_fail_general() {
407 echo -e $RED" FAIL."$1 $ERED
409 __print_current_stats
410 __check_stop_at_error
413 # Function to log a failed configuration setup due to incorrect response code
414 __log_conf_fail_status_code() {
415 echo -e $RED" FAIL. Expected status "$1", got "$2 $3 $ERED
417 __print_current_stats
418 __check_stop_at_error
421 # Function to log a failed configuration setup due to incorrect response body
422 __log_conf_fail_body() {
423 echo -e $RED" FAIL, returned body not correct"$ERED
425 __print_current_stats
426 __check_stop_at_error
429 # Function to log a configuration that is not supported
430 __log_conf_fail_not_supported() {
431 echo -e $RED" FAIL, function not supported"$ERED$@
433 __print_current_stats
434 __check_stop_at_error
437 # Function to log a passed configuration setup
439 if [ $# -gt 0 ]; then
442 echo -e $GREEN" OK"$EGREEN
443 __print_current_stats
446 # Function to collect stats on endpoints
447 # args: <app-id> <end-point-no> <http-operation> <end-point-url> <http-status> [<count>]
448 __collect_endpoint_stats() {
449 if [ $COLLECT_ENDPOINT_STATS -eq 0 ]; then
453 if [ $# -gt 5 ]; then
456 ENDPOINT_STAT_FILE=$TESTLOGS/$ATC/endpoint_$ATC_$1_$2".log"
459 if [ -f $ENDPOINT_STAT_FILE ]; then
460 ENDPOINT_VAL=$(< $ENDPOINT_STAT_FILE)
461 ENDPOINT_POS=$(echo $ENDPOINT_VAL | cut -f4 -d ' ' | cut -f1 -d '/')
462 ENDPOINT_NEG=$(echo $ENDPOINT_VAL | cut -f5 -d ' ' | cut -f1 -d '/')
465 if [ $5 -ge 200 ] && [ $5 -lt 300 ]; then
466 let ENDPOINT_POS=ENDPOINT_POS+$ENDPOINT_COUNT
468 let ENDPOINT_NEG=ENDPOINT_NEG+$ENDPOINT_COUNT
471 printf '%-2s %-10s %-45s %-16s %-16s' "#" "$3" "$4" "$ENDPOINT_POS/$ENDPOINT_POS" "$ENDPOINT_NEG/$ENDPOINT_NEG" > $ENDPOINT_STAT_FILE
474 # Function to collect stats on endpoints
475 # args: <app-id> <image-info>
476 __collect_endpoint_stats_image_info() {
477 if [ $COLLECT_ENDPOINT_STATS -eq 0 ]; then
480 ENDPOINT_STAT_FILE=$TESTLOGS/$ATC/imageinfo_$ATC_$1".log"
481 echo $A1PMS_IMAGE > $ENDPOINT_STAT_FILE
484 #Var for measuring execution time
485 TCTEST_START=$SECONDS
487 #Vars to hold the start time and timer text for a custom timer
488 TC_TIMER_STARTTIME=""
489 TC_TIMER_TIMER_TEXT=""
490 TC_TIMER_CURRENT_FAILS="" # Then number of failed test when timer starts.
491 # Compared with the current number of fails at timer stop
492 # to judge the measurement reliability
494 #File to save timer measurement results
495 TIMER_MEASUREMENTS=".timer_measurement.txt"
496 echo -e "Activity \t Duration \t Info" > $TIMER_MEASUREMENTS
498 # If this is set, some images (controlled by the parameter repo-policy) will be re-tagged and pushed to this repo before any
500 IMAGE_REPO_POLICY="local"
503 echo "-------------------------------------------------------------------------------------------------"
504 echo "----------------------------------- Test case: "$ATC
505 echo "----------------------------------- Started: "$(date)
506 echo "-------------------------------------------------------------------------------------------------"
507 echo "-- Description: "$TC_ONELINE_DESCR
508 echo "-------------------------------------------------------------------------------------------------"
509 echo "----------------------------------- Test case setup -----------------------------------"
511 echo "Setting AUTOTEST_HOME="$AUTOTEST_HOME
515 if [ $# -lt 1 ]; then
518 if [ $paramerror -eq 0 ]; then
519 if [ "$1" != "remote" ] && [ "$1" != "remote-remove" ]; then
521 if [ -z "$paramerror_str" ]; then
522 paramerror_str="First arg shall be 'remote' or 'remote-remove'"
528 if [ $paramerror -eq 0 ]; then
529 if [ "$1" != "docker" ] && [ "$1" != "kube" ]; then
531 if [ -z "$paramerror_str" ]; then
532 paramerror_str="Second arg shall be 'docker' or 'kube'"
535 if [ $1 == "docker" ]; then
537 echo "Setting RUNMODE=DOCKER"
539 if [ $1 == "kube" ]; then
541 echo "Setting RUNMODE=KUBE"
547 while [ $paramerror -eq 0 ] && [ $foundparm -eq 0 ]; do
549 if [ $paramerror -eq 0 ]; then
550 if [ "$1" == "release" ]; then
551 IMAGE_CATEGORY="RELEASE"
552 echo "Option set - Release image tags used for applicable images "
557 if [ $paramerror -eq 0 ]; then
558 if [ "$1" == "auto-clean" ]; then
560 echo "Option set - Auto clean at end of test script"
565 if [ $paramerror -eq 0 ]; then
566 if [ "$1" == "--stop-at-error" ]; then
568 echo "Option set - Stop at first error"
573 if [ $paramerror -eq 0 ]; then
574 if [ "$1" == "--ricsim-prefix" ]; then
576 TMP_RIC_SIM_PREFIX=$1 #RIC_SIM_PREFIX need to be updated after sourcing of the env file
579 if [ -z "$paramerror_str" ]; then
580 paramerror_str="No prefix found for flag: '--ricsim-prefix'"
583 echo "Option set - Overriding RIC_SIM_PREFIX with: "$1
589 if [ $paramerror -eq 0 ]; then
590 if [ "$1" == "--env-file" ]; then
595 if [ -z "$paramerror_str" ]; then
596 paramerror_str="No env file found for flag: '--env-file'"
599 echo "Option set - Reading test env from: "$1
605 if [ $paramerror -eq 0 ]; then
606 if [ "$1" == "--use-local-image" ]; then
609 while [ $# -gt 0 ] && [[ "$1" != "--"* ]]; do
610 USE_LOCAL_IMAGES=$USE_LOCAL_IMAGES" "$1
611 if [[ "$AVAILABLE_IMAGES_OVERRIDE" != *"$1"* ]]; then
613 if [ -z "$paramerror_str" ]; then
614 paramerror_str="App name $1 is not available for local override for flag: '--use-local-image'"
620 if [ -z "$USE_LOCAL_IMAGES" ]; then
622 if [ -z "$paramerror_str" ]; then
623 paramerror_str="No app name found for flag: '--use-local-image'"
626 echo "Option set - Overriding with local images for app(s):"$USE_LOCAL_IMAGES
630 if [ $paramerror -eq 0 ]; then
631 if [ "$1" == "--use-snapshot-image" ]; then
632 USE_SNAPSHOT_IMAGES=""
634 while [ $# -gt 0 ] && [[ "$1" != "--"* ]]; do
635 USE_SNAPSHOT_IMAGES=$USE_SNAPSHOT_IMAGES" "$1
636 if [[ "$AVAILABLE_IMAGES_OVERRIDE" != *"$1"* ]]; then
638 if [ -z "$paramerror_str" ]; then
639 paramerror_str="App name $1 is not available for snapshot override for flag: '--use-snapshot-image'"
645 if [ -z "$USE_SNAPSHOT_IMAGES" ]; then
647 if [ -z "$paramerror_str" ]; then
648 paramerror_str="No app name found for flag: '--use-snapshot-image'"
651 echo "Option set - Overriding with snapshot images for app(s):"$USE_SNAPSHOT_IMAGES
655 if [ $paramerror -eq 0 ]; then
656 if [ "$1" == "--use-staging-image" ]; then
657 USE_STAGING_IMAGES=""
659 while [ $# -gt 0 ] && [[ "$1" != "--"* ]]; do
660 USE_STAGING_IMAGES=$USE_STAGING_IMAGES" "$1
661 if [[ "$AVAILABLE_IMAGES_OVERRIDE" != *"$1"* ]]; then
663 if [ -z "$paramerror_str" ]; then
664 paramerror_str="App name $1 is not available for staging override for flag: '--use-staging-image'"
670 if [ -z "$USE_STAGING_IMAGES" ]; then
672 if [ -z "$paramerror_str" ]; then
673 paramerror_str="No app name found for flag: '--use-staging-image'"
676 echo "Option set - Overriding with staging images for app(s):"$USE_STAGING_IMAGES
680 if [ $paramerror -eq 0 ]; then
681 if [ "$1" == "--use-release-image" ]; then
682 USE_RELEASE_IMAGES=""
684 while [ $# -gt 0 ] && [[ "$1" != "--"* ]]; do
685 USE_RELEASE_IMAGES=$USE_RELEASE_IMAGES" "$1
686 if [[ "$AVAILABLE_IMAGES_OVERRIDE" != *"$1"* ]]; then
688 if [ -z "$paramerror_str" ]; then
689 paramerror_str="App name $1 is not available for release override for flag: '--use-release-image'"
695 if [ -z "$USE_RELEASE_IMAGES" ]; then
697 if [ -z "$paramerror_str" ]; then
698 paramerror_str="No app name found for flag: '--use-release-image'"
701 echo "Option set - Overriding with release images for app(s):"$USE_RELEASE_IMAGES
705 if [ $paramerror -eq 0 ]; then
706 if [ "$1" == "--use-external-image" ]; then
707 USE_EXTERNAL_IMAGES=""
709 while [ $# -gt 0 ] && [[ "$1" != "--"* ]]; do
710 USE_EXTERNAL_IMAGES=$USE_EXTERNAL_IMAGES" "$1
711 if [[ "$AVAILABLE_IMAGES_OVERRIDE" != *"$1"* ]]; then
713 if [ -z "$paramerror_str" ]; then
714 paramerror_str="App name $1 is not available for release override for flag: '--use-external-image'"
720 if [ -z "$USE_EXTERNAL_IMAGES" ]; then
722 if [ -z "$paramerror_str" ]; then
723 paramerror_str="No app name found for flag: '--use-use-external-image'"
726 echo "Option set - Overriding with external images for app(s):"$USE_EXTERNAL_IMAGES
730 if [ $paramerror -eq 0 ]; then
731 if [ "$1" == "--image-repo" ]; then
736 if [ -z "$paramerror_str" ]; then
737 paramerror_str="No image repo url found for : '--image-repo'"
740 echo "Option set - Image repo url: "$1
746 if [ $paramerror -eq 0 ]; then
747 if [ "$1" == "--repo-policy" ]; then
752 if [ -z "$paramerror_str" ]; then
753 paramerror_str="No policy found for : '--repo-policy'"
756 if [ "$1" == "local" ] || [ "$1" == "remote" ]; then
757 echo "Option set - Image repo policy: "$1
762 if [ -z "$paramerror_str" ]; then
763 paramerror_str="Repo policy shall be 'local' or 'remote'"
769 if [ $paramerror -eq 0 ]; then
770 if [ "$1" == "--cluster-timeout" ]; then
775 if [ -z "$paramerror_str" ]; then
776 paramerror_str="No timeout value found for : '--cluster-timeout'"
779 #Check if positive int
780 case ${CLUSTER_TIME_OUT#[+]} in
783 if [ -z "$paramerror_str" ]; then
784 paramerror_str="Value for '--cluster-timeout' not an int : "$CLUSTER_TIME_OUT
789 echo "Option set - Cluster timeout: "$1
795 if [ $paramerror -eq 0 ]; then
796 if [ "$1" == "--override" ]; then
798 TEST_ENV_VAR_FILE_OVERRIDE=$1
801 if [ -z "$paramerror_str" ]; then
802 paramerror_str="No env file found for flag: '--override'"
805 if [ ! -f $TEST_ENV_VAR_FILE_OVERRIDE ]; then
807 if [ -z "$paramerror_str" ]; then
808 paramerror_str="File for '--override' does not exist : "$TEST_ENV_VAR_FILE_OVERRIDE
811 echo "Option set - Override env from: "$1
817 if [ $paramerror -eq 0 ]; then
818 if [ "$1" == "--pre-clean" ]; then
820 echo "Option set - Pre-clean of kube/docker resouces"
825 if [ $paramerror -eq 0 ]; then
826 if [ "$1" == "--print-stats" ]; then
827 PRINT_CURRENT_STATS=1
828 echo "Option set - Print stats after every test-case and config"
833 if [ $paramerror -eq 0 ]; then
834 if [ "$1" == "--gen-stats" ]; then
835 COLLECT_RUNTIME_STATS=1
836 echo "Option set - Collect runtime statistics"
841 if [ $paramerror -eq 0 ]; then
842 if [ "$1" == "--delete-namespaces" ]; then
843 if [ $RUNMODE == "DOCKER" ]; then
844 DELETE_KUBE_NAMESPACES=0
845 echo "Option ignored - Delete namespaces (ignored when running docker)"
847 if [ -z "KUBE_PRESTARTED_IMAGES" ]; then
848 DELETE_KUBE_NAMESPACES=0
849 echo "Option ignored - Delete namespaces (ignored when using pre-started apps)"
851 DELETE_KUBE_NAMESPACES=1
852 echo "Option set - Delete namespaces"
859 if [ $paramerror -eq 0 ]; then
860 if [ "$1" == "--delete-containers" ]; then
861 if [ $RUNMODE == "DOCKER" ]; then
863 echo "Option set - Delete containers started by previous test(s)"
865 echo "Option ignored - Delete containers (ignored when running kube)"
871 if [ $paramerror -eq 0 ]; then
872 if [ "$1" == "--endpoint-stats" ]; then
873 COLLECT_ENDPOINT_STATS=1
874 echo "Option set - Collect endpoint statistics"
879 if [ $paramerror -eq 0 ]; then
880 if [ "$1" == "--kubeconfig" ]; then
884 if [ -z "$paramerror_str" ]; then
885 paramerror_str="No path found for : '--kubeconfig'"
889 if [ ! -z "$KUBECONF" ]; then
891 if [ -z "$paramerror_str" ]; then
892 paramerror_str="Only one of --kubeconfig/--kubecontext can be set"
895 KUBECONF="--kubeconfig $1"
896 echo "Option set - Kubeconfig path: "$1
902 if [ -z "$paramerror_str" ]; then
903 paramerror_str="File $1 for --kubeconfig not found"
909 if [ $paramerror -eq 0 ]; then
910 if [ "$1" == "--kubecontext" ]; then
914 if [ -z "$paramerror_str" ]; then
915 paramerror_str="No context-name found for : '--kubecontext'"
918 if [ ! -z "$KUBECONF" ]; then
920 if [ -z "$paramerror_str" ]; then
921 paramerror_str="Only one of --kubeconfig or --kubecontext can be set"
924 KUBECONF="--context $1"
925 echo "Option set - Kubecontext name: "$1
932 if [ $paramerror -eq 0 ]; then
933 if [ "$1" == "--host-path-dir" ]; then
937 if [ -z "$paramerror_str" ]; then
938 paramerror_str="No path found for : '--host-path-dir'"
941 HOST_PATH_BASE_DIR=$1
942 echo "Option set - Host path for kube set to: "$1
948 if [ $paramerror -eq 0 ]; then
949 if [ "$1" == "--docker-host" ]; then
953 if [ -z "$paramerror_str" ]; then
954 paramerror_str="No url found for : '--docker-host'"
957 export DOCKER_HOST="$1"
958 echo "Option set - DOCKER_HOST set to: "$1
964 if [ $paramerror -eq 0 ]; then
965 if [ "$1" == "--docker-host" ]; then
969 if [ -z "$paramerror_str" ]; then
970 paramerror_str="No url found for : '--docker-host'"
973 export DOCKER_HOST="$1"
974 echo "Option set - DOCKER_HOST set to: "$1
980 if [ $paramerror -eq 0 ]; then
981 if [ "$1" == "--docker-proxy" ]; then
985 if [ -z "$paramerror_str" ]; then
986 paramerror_str="No ip/host found for : '--docker-proxy'"
989 export LOCALHOST_NAME=$1
990 echo "Option set - docker proxy set to: "$1
996 if [ $paramerror -eq 0 ]; then
997 if [ "$1" == "--target-platform" ]; then
1001 if [ -z "$paramerror_str" ]; then
1002 paramerror_str="No platform string found for : '--target-platform'"
1005 if [ "$1" != "linux/amd64" ]; then
1007 if [ -z "$paramerror_str" ]; then
1008 paramerror_str="Only target platform 'linux/amd64' currently supported"
1011 export IMAGE_TARGET_PLATFORM=$1
1012 export IMAGE_TARGET_PLATFORM_CMD_PARAM="--platform $1"
1013 echo "Option set - Build and pull platform set to: "$1
1014 IMAGE_TARGET_PLATFORM_IMG_TAG=$(echo "$1" | sed 's/\//_/g')
1015 echo "Setting 'docker build' as alias for 'docker buildx'" | indent2
1026 if [ $paramerror -eq 0 ] && [ $# -gt 0 ]; then
1028 if [ -z "$paramerror_str" ]; then
1029 paramerror_str="Unknown parameter(s): "$@
1033 if [ $paramerror -eq 1 ]; then
1034 echo -e $RED"Incorrect arg list: "$paramerror_str$ERED
1039 LOCALHOST_HTTP="http://$LOCALHOST_NAME"
1040 LOCALHOST_HTTPS="https://$LOCALHOST_NAME"
1042 # sourcing the selected env variables for the test case
1043 if [ -f "$TEST_ENV_VAR_FILE" ]; then
1044 echo -e $BOLD"Sourcing env vars from: "$TEST_ENV_VAR_FILE$EBOLD
1045 . $TEST_ENV_VAR_FILE
1046 if [ ! -z "$TEST_ENV_VAR_FILE_OVERRIDE" ]; then
1047 echo -e $BOLD"Sourcing override env vars from: "$TEST_ENV_VAR_FILE_OVERRIDE$EBOLD
1048 . $TEST_ENV_VAR_FILE_OVERRIDE
1051 if [ -z "$TEST_ENV_PROFILE" ] || [ -z "$SUPPORTED_PROFILES" ]; then
1052 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
1055 for prof in $SUPPORTED_PROFILES; do
1056 if [ "$TEST_ENV_PROFILE" == "$prof" ]; then
1057 echo -e $GREEN"Test case supports the selected test env file"$EGREEN
1061 if [ $found_profile -ne 1 ]; then
1062 echo -e $RED"Test case does not support the selected test env file"$ERED
1063 echo "Profile: "$TEST_ENV_PROFILE" Supported profiles: "$SUPPORTED_PROFILES
1064 echo -e $RED"Exiting...."$ERED
1069 echo -e $RED"Selected env var file does not exist: "$TEST_ENV_VAR_FILE$ERED
1070 echo " Select one of following env var file matching the intended target of the test"
1071 echo " Restart the test using the flag '--env-file <path-to-env-file>"
1072 ls $AUTOTEST_HOME/../common/test_env* | indent1
1076 #This var need be preserved from the command line option, if set, when env var is sourced.
1077 if [ ! -z "$TMP_RIC_SIM_PREFIX" ]; then
1078 RIC_SIM_PREFIX=$TMP_RIC_SIM_PREFIX
1081 if [ -z "$PROJECT_IMAGES_APP_NAMES" ]; then
1082 echo -e $RED"Var PROJECT_IMAGES_APP_NAMES must be defined in: "$TEST_ENV_VAR_FILE $ERED
1086 if [[ $SUPPORTED_RUNMODES != *"$RUNMODE"* ]]; then
1087 echo -e $RED"This test script does not support RUNMODE $RUNMODE"$ERED
1088 echo "Supported RUNMODEs: "$SUPPORTED_RUNMODES
1092 # Choose list of included apps depending on run-mode
1093 if [ $RUNMODE == "KUBE" ]; then
1094 INCLUDED_IMAGES=$KUBE_INCLUDED_IMAGES
1096 INCLUDED_IMAGES=$DOCKER_INCLUDED_IMAGES
1100 # auto adding system apps
1102 echo -e $BOLD"Auto adding system apps"$EBOLD
1103 if [ $RUNMODE == "KUBE" ]; then
1104 INCLUDED_IMAGES=$INCLUDED_IMAGES" "$TESTENV_KUBE_SYSTEM_APPS
1105 TMP_APPS=$TESTENV_KUBE_SYSTEM_APPS
1107 INCLUDED_IMAGES=$INCLUDED_IMAGES" "$TESTENV_DOCKER_SYSTEM_APPS
1108 TMP_APPS=$TESTENV_DOCKER_SYSTEM_APPS
1110 if [ ! -z "$TMP_APPS" ]; then
1111 for iapp in "$TMP_APPS"; do
1112 file_pointer=$(echo $iapp | tr '[:upper:]' '[:lower:]')
1113 file_pointer="../common/"$file_pointer"_api_functions.sh"
1115 while [ ${#padded_iapp} -lt 16 ]; do
1116 padded_iapp=$padded_iapp" "
1118 echo " Auto-adding system app $padded_iapp Sourcing $file_pointer"
1120 if [ $? -ne 0 ]; then
1121 echo " Include file $file_pointer contain errors. Exiting..."
1124 __added_apps=" $iapp "$__added_apps
1130 if [ $RUNMODE == "KUBE" ]; then
1131 TMP_APPS=$INCLUDED_IMAGES" "$KUBE_PRESTARTED_IMAGES
1133 TMP_APPS=$INCLUDED_IMAGES
1136 echo -e $BOLD"Auto adding included apps"$EBOLD
1137 for iapp in $TMP_APPS; do
1138 if [[ "$__added_apps" != *"$iapp"* ]]; then
1139 file_pointer=$(echo $iapp | tr '[:upper:]' '[:lower:]')
1140 file_pointer="../common/"$file_pointer"_api_functions.sh"
1142 while [ ${#padded_iapp} -lt 16 ]; do
1143 padded_iapp=$padded_iapp" "
1145 echo " Auto-adding included app $padded_iapp Sourcing $file_pointer"
1146 if [ ! -f "$file_pointer" ]; then
1147 echo " Include file $file_pointer for app $iapp does not exist"
1151 if [ $? -ne 0 ]; then
1152 echo " Include file $file_pointer contain errors. Exiting..."
1159 echo -e $BOLD"Test environment info"$EBOLD
1161 # Check needed installed sw
1164 if [ $? -ne 0 ] || [ -z "$tmp" ]; then
1165 echo -e $RED"bash is required to run the test environment, pls install"$ERED
1168 echo " bash is installed and using version:"
1169 echo "$(bash --version)" | indent2
1171 tmp=$(which python3)
1172 if [ $? -ne 0 ] || [ -z "$tmp" ]; then
1173 echo -e $RED"python3 is required to run the test environment, pls install"$ERED
1176 echo " python3 is installed and using version: $(python3 --version)"
1179 if [ $? -ne 0 ]; then
1180 echo -e $RED"command utility jq (cmd-line json processor) is not installed"$ERED
1183 tmp=$(type envsubst)
1184 if [ $? -ne 0 ]; then
1185 echo -e $RED"command utility envsubst (env var substitution in files) is not installed"$ERED
1189 if [ $? -ne 0 ] || [ -z "$tmp" ]; then
1190 echo -e $RED"docker is required to run the test environment, pls install"$ERED
1193 echo " docker is installed and using versions:"
1194 echo " $(docker version --format 'Client version {{.Client.Version}} Server version {{.Server.Version}}')"
1196 if [ $RUNMODE == "DOCKER" ]; then
1197 tmp=$(which docker-compose)
1198 if [ $? -ne 0 ] || [ -z "$tmp" ]; then
1199 echo -e $RED"docker-compose (v.2+) is required to run the test environment, pls install"$ERED
1202 tmp=$(docker-compose -v)
1203 echo " docker-compose installed and using version $tmp"
1204 if [[ "$tmp" == *'v2'* ]]; then
1205 DOCKER_COMPOSE_VERSION="V2"
1207 echo -e $RED"docker-compose version $tmp is not supported. Only version v2 is supported, pls install"$ERED
1212 if [ $RUNMODE == "KUBE" ]; then
1213 tmp=$(which kubectl)
1214 if [ $? -ne 0 ] || [ -z tmp ]; then
1215 echo -e $RED"kubectl is required to run the test environment in kubernetes mode, pls install"$ERED
1218 echo " kubectl is installed and using versions:"
1219 echo $(kubectl $KUBECONF version --short=true) | indent2
1220 res=$(kubectl $KUBECONF cluster-info 2>&1)
1221 if [ $? -ne 0 ]; then
1222 echo -e "$BOLD$RED############################################# $ERED$EBOLD"
1223 echo -e $BOLD$RED"Command 'kubectl '$KUBECONF' cluster-info' returned error $ERED$EBOLD"
1224 echo -e "$BOLD$RED############################################# $ERED$EBOLD"
1226 echo "kubectl response:"
1229 echo "This script may have been started with user with no permission to run kubectl"
1230 echo "Try running with 'sudo', set env KUBECONFIG or set '--kubeconfig' parameter"
1231 echo "Do either 1, 2 or 3 "
1234 echo "Run with sudo"
1235 echo -e $BOLD"sudo <test-script-and-parameters>"$EBOLD
1238 echo "Export KUBECONFIG and pass env to sudo - (replace user)"
1239 echo -e $BOLD"export KUBECONFIG='/home/<user>/.kube/config'"$EBOLD
1240 echo -e $BOLD"sudo -E <test-script-and-parameters>"$EBOLD
1243 echo "Set KUBECONFIG via script parameter"
1244 echo -e $BOLD"sudo ... --kubeconfig /home/<user>/.kube/<config-file> ...."$EBOLD
1245 echo "The config file need to downloaded from the cluster"
1249 echo " Node(s) and container runtime config"
1250 kubectl $KUBECONF get nodes -o wide | indent2
1252 if [ -z "$HOST_PATH_BASE_DIR" ]; then
1253 HOST_PATH_BASE_DIR="/tmp"
1254 echo " Persistent volumes will be mounted to $HOST_PATH_BASE_DIR on applicable node"
1255 echo " No guarantee that persistent volume data is available on all nodes in the cluster"
1257 echo "Persistent volumes will be mounted to base dir: $HOST_PATH_BASE_DIR"
1258 echo "Assuming this dir is mounted from each node to a dir on the localhost or other"
1259 echo "file system available to all nodes"
1266 echo -e $BOLD"Checking configured image setting for this test case"$EBOLD
1268 #Temp var to check for image variable name errors
1270 #Create a file with image info for later printing as a table
1271 image_list_file="./tmp/.image-list"
1272 echo -e "Application\tApp short name\tImage\ttag\ttag-switch" > $image_list_file
1274 # Check if image env var is set and if so export the env var with image to use (used by docker compose files)
1275 # arg: <app-short-name> <target-variable-name> <image-variable-name> <image-tag-variable-name> <tag-suffix> <image name> <target-platform>
1276 __check_and_create_image_var() {
1277 if [ $# -ne 7 ]; then
1278 echo "Expected arg: <app-short-name> <target-variable-name> <image-variable-name> <image-tag-variable-name> <tag-suffix> <image name> <target-platform>"
1283 __check_included_image $1
1284 if [ $? -ne 0 ]; then
1285 echo -e "$6\t$1\t<image-excluded>\t<no-tag>" >> $image_list_file
1286 # Image is excluded since the corresponding app is not used in this test
1289 tmp=${6}"\t"${1}"\t"
1290 #Create var from the input var names
1294 if [ ! -z "$7" ]; then
1295 tag=$tag-$7 # add platform to tag - for local images built by the test script
1297 optional_image_repo_target=""
1299 if [ -z $image ]; then
1300 __check_ignore_image $1
1301 if [ $? -eq 0 ]; then
1303 if [ -z "$6" ]; then
1304 app_ds="<app ignored>"
1306 echo -e "$app_ds\t$1\t<image-ignored>\t<no-tag>" >> $image_list_file
1307 # Image is ignored since the corresponding the images is not set in the env file
1308 __remove_included_image $1 # Remove the image from the list of included images
1311 echo -e $RED"\$"$3" not set in $TEST_ENV_VAR_FILE"$ERED
1314 tmp=$tmp"<no-image>\t"
1317 optional_image_repo_target=$image
1319 #Add repo depending on image type
1320 if [ "$5" == "REMOTE_RELEASE" ]; then
1321 image=$NEXUS_RELEASE_REPO$image
1323 if [ "$5" == "REMOTE" ]; then
1324 image=$NEXUS_STAGING_REPO$image
1326 if [ "$5" == "REMOTE_SNAPSHOT" ]; then
1327 image=$NEXUS_SNAPSHOT_REPO$image
1329 if [ "$5" == "REMOTE_PROXY" ]; then
1330 image=$NEXUS_PROXY_REPO$image
1332 if [ "$5" == "REMOTE_RELEASE_ONAP" ]; then
1333 image=$NEXUS_RELEASE_REPO_ONAP$image
1335 if [ "$5" == "REMOTE_RELEASE_ORAN" ]; then
1336 image=$NEXUS_RELEASE_REPO_ORAN$image
1338 #No nexus repo added for local images, tag: LOCAL and other tags
1341 if [ -z $tag ]; then
1342 echo -e $RED"\$"$tmptag" not set in $TEST_ENV_VAR_FILE"$ERED
1345 tmp=$tmp"<no-tag>\t"
1350 echo -e "$tmp" >> $image_list_file
1352 export "${2}"=$image":"$tag #Note, this var may be set to the value of the target value below in __check_and_pull_image
1354 remote_or_local_push=false
1355 if [ ! -z "$IMAGE_REPO_ADR" ] && [[ $5 != *"PROXY"* ]]; then
1356 if [ $5 == "LOCAL" ]; then
1357 remote_or_local_push=true
1359 if [[ $5 == *"REMOTE"* ]]; then
1360 if [ "$IMAGE_REPO_POLICY" == "remote" ]; then
1361 remote_or_local_push=true
1365 if $remote_or_local_push; then # Only re-tag and push images according to policy, if repo is given
1366 export "${2}_SOURCE"=$image":"$tag #Var to keep the actual source image
1367 if [[ $optional_image_repo_target == *"/"* ]]; then # Replace all / with _ for images to push to external repo
1368 optional_image_repo_target_tmp=${optional_image_repo_target//\//_}
1369 optional_image_repo_target=$optional_image_repo_target_tmp
1371 export "${2}_TARGET"=$IMAGE_REPO_ADR"/"$optional_image_repo_target":"$tag #Create image + tag for optional image repo - pushed later if needed
1373 export "${2}_SOURCE"=""
1374 export "${2}_TARGET"=""
1378 # Check if app uses image included in this test run
1379 # Returns 0 if image is included, 1 if not
1380 __check_included_image() {
1381 for im in $INCLUDED_IMAGES; do
1382 if [ "$1" == "$im" ]; then
1389 # Check if app uses a project image
1390 # Returns 0 if image is included, 1 if not
1391 __check_project_image() {
1392 for im in $PROJECT_IMAGES; do
1393 if [ "$1" == "$im" ]; then
1400 # Check if app uses image built by the test script
1401 # Returns 0 if image is included, 1 if not
1402 __check_image_local_build() {
1403 for im in $LOCAL_IMAGE_BUILD; do
1404 if [ "$1" == "$im" ]; then
1411 # Check if app image is conditionally ignored in this test run
1412 # Returns 0 if image is conditionally ignored, 1 if not
1413 __check_ignore_image() {
1414 for im in $CONDITIONALLY_IGNORED_IMAGES; do
1415 if [ "$1" == "$im" ]; then
1422 # Removed image from included list of included images
1423 # Used when an image is marked as conditionally ignored
1424 __remove_included_image() {
1426 for im in $INCLUDED_IMAGES; do
1427 if [ "$1" != "$im" ]; then
1428 tmp_img_rem_list=$tmp_img_rem_list" "$im
1431 INCLUDED_IMAGES=$tmp_img_rem_list
1435 # Check if app is included in the prestarted set of apps
1436 # Returns 0 if image is included, 1 if not
1437 __check_prestarted_image() {
1438 for im in $KUBE_PRESTARTED_IMAGES; do
1439 if [ "$1" == "$im" ]; then
1446 # Check if an app shall use a local image, based on the cmd parameters
1447 __check_image_local_override() {
1448 for im in $USE_LOCAL_IMAGES; do
1449 if [ "$1" == "$im" ]; then
1456 # Check if app uses image override
1457 # Returns the image/tag suffix LOCAL for local image or REMOTE/REMOTE_RELEASE/REMOTE_SNAPSHOT for staging/release/snapshot image
1458 __check_image_override() {
1460 for im in $ORAN_IMAGES_APP_NAMES; do
1461 if [ "$1" == "$im" ]; then
1462 echo "REMOTE_RELEASE_ORAN"
1467 for im in $ONAP_IMAGES_APP_NAMES; do
1468 if [ "$1" == "$im" ]; then
1469 echo "REMOTE_RELEASE_ONAP"
1475 for im in $PROJECT_IMAGES_APP_NAMES; do
1476 if [ "$1" == "$im" ]; then
1481 if [ $found -eq 0 ]; then
1487 if [ $IMAGE_CATEGORY == "RELEASE" ]; then
1488 suffix="REMOTE_RELEASE"
1490 if [ $IMAGE_CATEGORY == "DEV" ]; then
1494 for im in $USE_STAGING_IMAGES; do
1495 if [ "$1" == "$im" ]; then
1500 for im in $USE_RELEASE_IMAGES; do
1501 if [ "$1" == "$im" ]; then
1502 suffix="REMOTE_RELEASE"
1506 for im in $USE_SNAPSHOT_IMAGES; do
1507 if [ "$1" == "$im" ]; then
1508 suffix="REMOTE_SNAPSHOT"
1512 for im in $USE_LOCAL_IMAGES; do
1513 if [ "$1" == "$im" ]; then
1518 for im in $USE_EXTERNAL_IMAGES; do
1519 if [ "$1" == "$im" ]; then
1525 if [ $CTR -gt 1 ]; then
1531 # Function to re-tag and image and push to another image repo
1532 __retag_and_push_image() {
1533 if [ ! -z "$IMAGE_REPO_ADR" ]; then
1534 source_image="${!1}"
1535 trg_var_name=$1_"TARGET" # This var is created in func __check_and_create_image_var
1536 target_image="${!trg_var_name}"
1538 if [ -z $target_image ]; then
1539 return 0 # Image with no target shall not be pushed
1542 echo -ne " Attempt to re-tag image to: ${BOLD}${target_image}${EBOLD}${SAMELINE}"
1543 tmp=$(docker image tag $source_image ${target_image} )
1544 if [ $? -ne 0 ]; then
1545 docker stop $tmp &> ./tmp/.dockererr
1548 echo -e " Attempt to re-tag image to: ${BOLD}${target_image}${EBOLD} - ${RED}Failed${ERED}"
1549 cat ./tmp/.dockererr
1552 echo -e " Attempt to re-tag image to: ${BOLD}${target_image}${EBOLD} - ${GREEN}OK${EGREEN}"
1554 echo -ne " Attempt to push re-tagged image: ${BOLD}${target_image}${EBOLD}${SAMELINE}"
1555 tmp=$(docker push ${target_image} )
1556 if [ $? -ne 0 ]; then
1557 docker stop $tmp &> ./tmp/.dockererr
1560 echo -e " Attempt to push re-tagged image: ${BOLD}${target_image}${EBOLD} - ${RED}Failed${ERED}"
1561 cat ./tmp/.dockererr
1564 echo -e " Attempt to push re-tagged image: ${BOLD}${target_image}${EBOLD} - ${GREEN}OK${EGREEN}"
1566 export "${1}"=$target_image
1571 #Function to check if image exist and stop+remove the container+pull new images as needed
1572 #args <script-start-arg> <descriptive-image-name> <container-base-name> <image-with-tag-var-name>
1573 __check_and_pull_image() {
1575 source_image="${!4}"
1577 echo -e " Checking $BOLD$2$EBOLD container(s) with basename: $BOLD$3$EBOLD using image: $BOLD$source_image$EBOLD"
1578 format_string="\"{{.Repository}}\\t{{.Tag}}\\t{{.CreatedSince}}\\t{{.Size}}\""
1579 tmp_im=$(docker images --format $format_string $source_image)
1581 if [ $1 == "local" ]; then
1582 if [ -z "$tmp_im" ]; then
1583 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
1587 echo -e " "$2" (local image): \033[1m"$source_image"\033[0m "$GREEN"OK"$EGREEN
1589 elif [ $1 == "remote" ] || [ $1 == "remote-remove" ]; then
1590 if [ $1 == "remote-remove" ]; then
1591 if [ $RUNMODE == "DOCKER" ]; then
1593 echo -ne " Attempt to stop and remove container(s), if running - ${SAMELINE}"
1594 tmp=$(docker ps -aq --filter name=${3} --filter network=${DOCKER_SIM_NWNAME})
1595 if [ $? -eq 0 ] && [ ! -z "$tmp" ]; then
1596 docker stop -t 0 $tmp &> ./tmp/.dockererr
1597 if [ $? -ne 0 ]; then
1600 echo -e $RED" Container(s) could not be stopped - try manual stopping the container(s)"$ERED
1601 cat ./tmp/.dockererr
1605 echo -ne " Attempt to stop and remove container(s), if running - "$GREEN"stopped"$EGREEN"${SAMELINE}"
1606 tmp=$(docker ps -aq --filter name=${3} --filter network=${DOCKER_SIM_NWNAME}) &> /dev/null
1607 if [ $? -eq 0 ] && [ ! -z "$tmp" ]; then
1608 docker rm -f $tmp &> ./tmp/.dockererr
1609 if [ $? -ne 0 ]; then
1612 echo -e $RED" Container(s) could not be removed - try manual removal of the container(s)"$ERED
1613 cat ./tmp/.dockererr
1617 echo -e " Attempt to stop and remove container(s), if running - "$GREEN"stopped removed"$EGREEN
1623 if [ -z "$tmp_im" ]; then
1624 echo -ne " Pulling image${SAMELINE}"
1625 out=$(docker pull $IMAGE_TARGET_PLATFORM_CMD_PARAM $source_image)
1626 if [ $? -ne 0 ]; then
1628 echo -e " Pulling image -$RED could not be pulled"$ERED
1630 echo $out > ./tmp/.dockererr
1634 echo $out > ./tmp/.dockererr
1635 if [[ $out == *"up to date"* ]]; then
1636 echo -e " Pulling image -$GREEN Image is up to date $EGREEN"
1637 elif [[ $out == *"Downloaded newer image"* ]]; then
1638 echo -e " Pulling image -$GREEN Newer image pulled $EGREEN"
1640 echo -e " Pulling image -$GREEN Pulled $EGREEN"
1643 echo -e " Pulling image -$GREEN OK $EGREEN(exists in local repository)"
1647 __retag_and_push_image $4
1652 setup_testenvironment() {
1653 # Check that image env setting are available
1656 # Image var setup for all project images included in the test
1657 for imagename in $APP_SHORT_NAMES; do
1658 __check_included_image $imagename
1660 __check_project_image $imagename
1662 if [ $incl -eq 0 ]; then
1663 if [ $proj -eq 0 ]; then
1664 IMAGE_SUFFIX=$(__check_image_override $imagename)
1665 if [ $? -ne 0 ]; then
1666 echo -e $RED"Image setting from cmd line not consistent for $imagename."$ERED
1672 # A function name is created from the app short name
1673 # for example app short name 'ICS' -> produce the function
1674 # name __ICS_imagesetup
1675 # This function is called and is expected to exist in the imported
1676 # file for the ics test functions
1677 # The resulting function impl will call '__check_and_create_image_var' function
1678 # with appropriate parameters
1679 # If the image suffix is none, then the component decides the suffix
1680 function_pointer="__"$imagename"_imagesetup"
1681 $function_pointer $IMAGE_SUFFIX
1683 function_pointer="__"$imagename"_test_requirements"
1688 #Errors in image setting - exit
1689 if [ $IMAGE_ERR -ne 0 ]; then
1693 #Print a tables of the image settings
1694 echo -e $BOLD"Images configured for start arg: "$START_ARG $EBOLD
1695 column -t -s $'\t' $image_list_file | indent1
1699 #Set the SIM_GROUP var
1700 echo -e $BOLD"Setting var to main dir of all container/simulator scripts"$EBOLD
1701 if [ -z "$SIM_GROUP" ]; then
1702 SIM_GROUP=$AUTOTEST_HOME/../simulator-group
1703 if [ ! -d $SIM_GROUP ]; then
1704 echo "Trying to set env var SIM_GROUP to dir 'simulator-group' in the nontrtric repo, but failed."
1705 echo -e $RED"Please set the SIM_GROUP manually in the applicable $TEST_ENV_VAR_FILE"$ERED
1708 echo " SIM_GROUP auto set to: " $SIM_GROUP
1710 elif [ $SIM_GROUP = *simulator_group ]; then
1711 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
1714 echo " SIM_GROUP env var already set to: " $SIM_GROUP
1719 #Temp var to check for image pull errors
1723 echo -e $BOLD"Deleting namespaces"$EBOLD
1726 if [ "$DELETE_KUBE_NAMESPACES" -eq 1 ]; then
1727 test_env_namespaces=$(kubectl $KUBECONF get ns --no-headers -o custom-columns=":metadata.name" -l autotest=engine) #Get list of ns created by the test env
1728 if [ $? -ne 0 ]; then
1729 echo " Cannot get list of namespaces...ignoring delete"
1731 for test_env_ns in $test_env_namespaces; do
1732 __kube_delete_namespace $test_env_ns
1736 echo " Namespace delete option not set or ignored"
1741 echo -e $BOLD"Deleting containers"$EBOLD
1743 if [ "$DELETE_CONTAINERS" -eq 1 ]; then
1744 echo " Stopping containers label 'nrttest_app'..."
1745 docker stop $(docker ps -qa --filter "label=nrttest_app") 2> /dev/null
1746 echo " Removing stopped containers..."
1747 docker rm $(docker ps -qa --filter "label=nrttest_app") 2> /dev/null
1749 echo " Contatiner delete option not set or ignored"
1753 # The following sequence pull the configured images
1754 echo -e $BOLD"Pulling configured images, if needed"$EBOLD
1756 if [ ! -z "$IMAGE_REPO_ADR" ] && [ $IMAGE_REPO_POLICY == "local" ]; then
1757 echo -e $YELLOW" Excluding all remote image check/pull (unless local override) when running with image repo: $IMAGE_REPO_ADR and image policy: $IMAGE_REPO_POLICY"$EYELLOW
1760 for imagename in $APP_SHORT_NAMES; do
1761 __check_included_image $imagename
1763 __check_project_image $imagename
1765 if [ $incl -eq 0 ]; then
1766 if [ $proj -eq 0 ]; then
1767 START_ARG_MOD=$START_ARG
1768 __check_image_local_override $imagename
1769 if [ $? -eq 1 ]; then
1770 START_ARG_MOD="local"
1773 START_ARG_MOD=$START_ARG
1775 __exclude_image_check=0
1776 if [ $__exclude_check == 1 ] && [ "$START_ARG_MOD" != "local" ]; then
1777 # For to handle locally built images, overriding remote images
1778 __exclude_image_check=1
1780 if [ $__exclude_image_check == 0 ]; then
1781 __check_image_local_build $imagename
1782 #No pull of images built locally
1783 if [ $? -ne 0 ]; then
1784 # A function name is created from the app short name
1785 # for example app short name 'HTTPPROXY' -> produce the function
1786 # name __HTTPPROXY_imagesetup
1787 # This function is called and is expected to exist in the imported
1788 # file for the httpproxy test functions
1789 # The resulting function impl will call '__check_and_pull_image' function
1790 # with appropriate parameters
1791 function_pointer="__"$imagename"_imagepull"
1792 $function_pointer $START_ARG_MOD $START_ARG
1796 echo -e $YELLOW" Excluding $imagename image from image check/pull"$EYELLOW
1801 #Errors in image setting - exit
1802 if [ $IMAGE_ERR -ne 0 ]; then
1804 echo "#################################################################################################"
1805 echo -e $RED"One or more images could not be pulled or containers using the images could not be stopped/removed"$ERED
1806 echo -e $RED"Or local image, overriding remote image, does not exist"$ERED
1807 if [ $IMAGE_CATEGORY == "DEV" ]; then
1809 echo -e $RED"Note that SNAPSHOT and staging images may be purged from nexus after a certain period."$ERED
1810 echo -e $RED"In addition, the image may not have been updated in the current release so no SNAPSHOT or staging image exists"$ERED
1811 echo -e $RED"In these cases, switch to use a released image instead, use the flag '--use-release-image <App-short-name>'"$ERED
1812 echo -e $RED"Use the 'App-short-name' for the applicable image from the above table: 'Images configured for start arg'."$ERED
1814 echo "#################################################################################################"
1821 echo -e $BOLD"Building images needed for test"$EBOLD
1823 for imagename in $APP_SHORT_NAMES; do
1824 cd $AUTOTEST_HOME #Always reset to orig dir
1825 __check_image_local_build $imagename
1826 if [ $? -eq 0 ]; then
1827 __check_included_image $imagename
1828 if [ $? -eq 0 ]; then
1829 # A function name is created from the app short name
1830 # for example app short name 'MR' -> produce the function
1831 # name __MR_imagebuild
1832 # This function is called and is expected to exist in the imported
1833 # file for the mr test functions
1834 # The resulting function impl shall build the imagee
1835 function_pointer="__"$imagename"_imagebuild"
1839 echo -e $YELLOW" Excluding image for app $imagename from image build"$EYELLOW
1844 cd $AUTOTEST_HOME # Just to make sure...
1848 # Create a table of the images used in the script - from local repo
1849 echo -e $BOLD"Local docker registry images used in this test script"$EBOLD
1851 docker_tmp_file=./tmp/.docker-images-table
1852 format_string="{{.Repository}}\\t{{.Tag}}\\t{{.CreatedSince}}\\t{{.Size}}\\t{{.CreatedAt}}"
1853 echo -e "Application\tRepository\tTag\tCreated since\tSize\tCreated at" > $docker_tmp_file
1855 for imagename in $APP_SHORT_NAMES; do
1856 __check_included_image $imagename
1857 if [ $? -eq 0 ]; then
1858 # Only print image data if image repo is null, or if image repo is set and image is local
1860 if [ -z "$IMAGE_REPO_ADR" ]; then
1863 __check_image_local_build $imagename
1864 if [ $? -eq 0 ]; then
1868 if [ $print_image_data -eq 1 ]; then
1869 # A function name is created from the app short name
1870 # for example app short name 'MR' -> produce the function
1871 # name __MR_imagebuild
1872 # This function is called and is expected to exist in the imported
1873 # file for the mr test functions
1874 # The resulting function impl shall build the imagee
1875 function_pointer="__"$imagename"_image_data"
1876 $function_pointer "$format_string" $docker_tmp_file
1881 column -t -s $'\t' $docker_tmp_file | indent1
1885 if [ ! -z "$IMAGE_REPO_ADR" ]; then
1887 # Create a table of the images used in the script - from remote repo
1888 echo -e $BOLD"Remote repo images used in this test script"$EBOLD
1889 echo -e $YELLOW"-- Note: These image will be pulled when the container starts. Images not managed by the test engine "$EYELLOW
1890 echo -e $YELLOW"-- Note: Images with local override will however be re-tagged and managed by the test engine "$EYELLOW
1891 docker_tmp_file=./tmp/.docker-images-table
1892 format_string="{{.Repository}}\\t{{.Tag}}"
1893 echo -e "Application\tRepository\tTag" > $docker_tmp_file
1895 for imagename in $APP_SHORT_NAMES; do
1896 __check_included_image $imagename
1897 if [ $? -eq 0 ]; then
1898 # Only print image data if image repo is null, or if image repo is set and image is local
1899 __check_image_local_build $imagename
1900 if [ $? -ne 0 ]; then
1901 # A function name is created from the app short name
1902 # for example app short name 'MR' -> produce the function
1903 # name __MR_imagebuild
1904 # This function is called and is expected to exist in the imported
1905 # file for the mr test functions
1906 # The resulting function impl shall build the imagee
1907 function_pointer="__"$imagename"_image_data"
1908 $function_pointer "$format_string" $docker_tmp_file
1913 column -t -s $'\t' $docker_tmp_file | indent1
1918 if [ $RUNMODE == "KUBE" ]; then
1920 echo "================================================================================="
1921 echo "================================================================================="
1923 if [ -z "$IMAGE_REPO_ADR" ]; then
1924 echo -e $YELLOW" The image pull policy is set to 'Never' - assuming a local image repo is available for all images"$EYELLOW
1925 echo -e " This setting only works on single node clusters on the local machine"
1926 echo -e " It does not work with multi-node clusters or remote clusters. "
1927 export KUBE_IMAGE_PULL_POLICY="Never"
1929 echo -e $YELLOW" The image pull policy is set to 'Always'"$EYELLOW
1930 echo -e " This setting work on local clusters, multi-node clusters and remote cluster. "
1931 echo -e " Only locally built images are managed. Remote images are always pulled from remote repos"
1932 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"
1933 export KUBE_IMAGE_PULL_POLICY="Always"
1935 #CLUSTER_IP=$(kubectl $KUBECONF config view -o jsonpath={.clusters[0].cluster.server} | awk -F[/:] '{print $4}')
1936 #echo -e $YELLOW" The cluster hostname/ip is: $CLUSTER_IP"$EYELLOW
1938 echo "================================================================================="
1939 echo "================================================================================="
1943 echo -e $BOLD"======================================================="$EBOLD
1944 echo -e $BOLD"== Common test setup completed - test script begins =="$EBOLD
1945 echo -e $BOLD"======================================================="$EBOLD
1950 for imagename in $APP_SHORT_NAMES; do
1951 __check_included_image $imagename
1953 __check_prestarted_image $imagename
1955 if [ $retcode_i -eq 0 ] || [ $retcode_p -eq 0 ]; then
1956 # A function name is created from the app short name
1957 # for example app short name 'RICMSIM' -> produce the function
1958 # name __RICSIM__initial_setup
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 perform initial setup of port, host etc
1963 function_pointer="__"$imagename"_initial_setup"
1966 function_pointer="__"$imagename"_statistics_setup"
1967 LOG_STAT_ARGS=$LOG_STAT_ARGS" "$($function_pointer)
1971 if [ $COLLECT_RUNTIME_STATS -eq 1 ]; then
1972 ../common/genstat.sh $RUNMODE $SECONDS $TESTLOGS/$ATC/stat_data.csv $LOG_STAT_ARGS &
1973 COLLECT_RUNTIME_STATS_PID=$!
1978 # Function to print the test result, shall be the last cmd in a test script
1980 # (Function for test scripts)
1984 duration=$((TCTEST_END-TCTEST_START))
1986 echo "-------------------------------------------------------------------------------------------------"
1987 echo "------------------------------------- Test case: "$ATC
1988 echo "------------------------------------- Ended: "$(date)
1989 echo "-------------------------------------------------------------------------------------------------"
1990 echo "-- Description: "$TC_ONELINE_DESCR
1991 echo "-- Execution time: " $duration " seconds"
1992 echo "-- Used env file: "$TEST_ENV_VAR_FILE
1993 echo "-------------------------------------------------------------------------------------------------"
1994 echo "------------------------------------- RESULTS"
1998 if [ $RES_DEVIATION -gt 0 ]; then
1999 echo "Test case deviations"
2000 echo "===================================="
2004 echo "Timer measurement in the test script"
2005 echo "===================================="
2006 column -t -s $'\t' $TIMER_MEASUREMENTS
2007 if [ $RES_PASS != $RES_TEST ]; then
2008 echo -e $RED"Measurement may not be reliable when there are failed test - failures may cause long measurement values due to timeouts etc."$ERED
2012 if [ $COLLECT_RUNTIME_STATS -eq 1 ]; then
2013 echo "Runtime statistics collected in file: "$TESTLOGS/$ATC/stat_data.csv
2016 TMP_FLAG_FAIL_PASS=0
2017 total=$((RES_PASS+RES_FAIL))
2018 if [ $RES_TEST -eq 0 ]; then
2019 TMP_FLAG_FAIL_PASS=1
2020 echo -e "\033[1mNo tests seem to have been executed. Check the script....\033[0m"
2021 echo -e "\033[31m\033[1m ___ ___ ___ ___ ___ _____ ___ _ ___ _ _ _ ___ ___ \033[0m"
2022 echo -e "\033[31m\033[1m/ __|/ __| _ \_ _| _ \_ _| | __/_\ |_ _| | | | | | _ \ __|\033[0m"
2023 echo -e "\033[31m\033[1m\__ \ (__| /| || _/ | | | _/ _ \ | || |_| |_| | / _| \033[0m"
2024 echo -e "\033[31m\033[1m|___/\___|_|_\___|_| |_| |_/_/ \_\___|____\___/|_|_\___|\033[0m"
2025 elif [ $total != $RES_TEST ]; then
2026 TMP_FLAG_FAIL_PASS=1
2027 echo -e "\033[1mTotal number of tests does not match the sum of passed and failed tests. Check the script....\033[0m"
2028 echo -e "\033[31m\033[1m ___ ___ ___ ___ ___ _____ ___ _ ___ _ _ _ ___ ___ \033[0m"
2029 echo -e "\033[31m\033[1m/ __|/ __| _ \_ _| _ \_ _| | __/_\ |_ _| | | | | | _ \ __|\033[0m"
2030 echo -e "\033[31m\033[1m\__ \ (__| /| || _/ | | | _/ _ \ | || |_| |_| | / _| \033[0m"
2031 echo -e "\033[31m\033[1m|___/\___|_|_\___|_| |_| |_/_/ \_\___|____\___/|_|_\___|\033[0m"
2032 elif [ $RES_CONF_FAIL -ne 0 ]; then
2033 TMP_FLAG_FAIL_PASS=1
2034 echo -e "\033[1mOne or more configurations has failed. Check the script log....\033[0m"
2035 echo -e "\033[31m\033[1m ___ ___ ___ ___ ___ _____ ___ _ ___ _ _ _ ___ ___ \033[0m"
2036 echo -e "\033[31m\033[1m/ __|/ __| _ \_ _| _ \_ _| | __/_\ |_ _| | | | | | _ \ __|\033[0m"
2037 echo -e "\033[31m\033[1m\__ \ (__| /| || _/ | | | _/ _ \ | || |_| |_| | / _| \033[0m"
2038 echo -e "\033[31m\033[1m|___/\___|_|_\___|_| |_| |_/_/ \_\___|____\___/|_|_\___|\033[0m"
2039 elif [ $RES_PASS = $RES_TEST ]; then
2040 TMP_FLAG_FAIL_PASS=0
2041 echo -e "All tests \033[32m\033[1mPASS\033[0m"
2042 echo -e "\033[32m\033[1m ___ _ ___ ___ \033[0m"
2043 echo -e "\033[32m\033[1m | _ \/_\ / __/ __| \033[0m"
2044 echo -e "\033[32m\033[1m | _/ _ \\__ \__ \\ \033[0m"
2045 echo -e "\033[32m\033[1m |_|/_/ \_\___/___/ \033[0m"
2048 # Update test suite counter
2049 if [ -f .tmp_tcsuite_pass_ctr ]; then
2050 tmpval=$(< .tmp_tcsuite_pass_ctr)
2052 echo $tmpval > .tmp_tcsuite_pass_ctr
2054 if [ -f .tmp_tcsuite_pass ]; then
2055 echo " - "$ATC " -- "$TC_ONELINE_DESCR" Execution time: "$duration" seconds" >> .tmp_tcsuite_pass
2057 #Create file with OK exit code
2058 echo "0" > "$AUTOTEST_HOME/.result$ATC.txt"
2059 echo "0" > "$TESTLOGS/$ATC/.result$ATC.txt"
2060 echo $(date) > $TESTLOGS/$ATC/endpoint_tc_end.log
2062 TMP_FLAG_FAIL_PASS=1
2063 echo -e "One or more tests with status \033[31m\033[1mFAIL\033[0m "
2064 echo -e "\033[31m\033[1m ___ _ ___ _ \033[0m"
2065 echo -e "\033[31m\033[1m | __/_\ |_ _| | \033[0m"
2066 echo -e "\033[31m\033[1m | _/ _ \ | || |__ \033[0m"
2067 echo -e "\033[31m\033[1m |_/_/ \_\___|____|\033[0m"
2071 if [ $TMP_FLAG_FAIL_PASS -ne 0 ]; then
2072 # Update test suite counter
2073 if [ -f .tmp_tcsuite_fail_ctr ]; then
2074 tmpval=$(< .tmp_tcsuite_fail_ctr)
2076 echo $tmpval > .tmp_tcsuite_fail_ctr
2078 if [ -f .tmp_tcsuite_fail ]; then
2079 echo " - "$ATC " -- "$TC_ONELINE_DESCR" Execution time: "$duration" seconds" >> .tmp_tcsuite_fail
2083 echo "++++ Number of tests: "$RES_TEST
2084 echo "++++ Number of passed tests: "$RES_PASS
2085 echo "++++ Number of failed tests: "$RES_FAIL
2087 echo "++++ Number of failed configs: "$RES_CONF_FAIL
2089 echo "++++ Number of test case deviations: "$RES_DEVIATION
2091 echo "------------------------------------- Test case complete ---------------------------------"
2092 echo "-------------------------------------------------------------------------------------------------"
2096 #####################################################################
2097 ###### Functions for start, configuring, stoping, cleaning etc ######
2098 #####################################################################
2100 # Start timer for time measurement
2101 # args: <timer message to print> - timer value and message will be printed both on screen
2102 # and in the timer measurement report - if at least one "print_timer is called"
2104 echo -e $BOLD"INFO(${BASH_LINENO[0]}): "${FUNCNAME[0]}"," $@ $EBOLD
2105 TC_TIMER_STARTTIME=$SECONDS
2106 TC_TIMER_TIMER_TEXT="${@:1}"
2107 if [ $# -ne 1 ]; then
2108 __print_err "need 1 arg, <timer message to print>" $@
2109 TC_TIMER_TIMER_TEXT=${FUNCNAME[0]}":"${BASH_LINENO[0]}
2110 echo " Assigning timer name: "$TC_TIMER_TIMER_TEXT
2112 TC_TIMER_CURRENT_FAILS=$(($RES_FAIL+$RES_CONF_FAIL))
2113 echo " Timer started: $(date)"
2116 # Print the running timer the value of the time (in seconds)
2117 # Timer value and message will be printed both on screen and in the timer measurement report
2119 echo -e $BOLD"INFO(${BASH_LINENO[0]}): "${FUNCNAME[0]}"," $TC_TIMER_TIMER_TEXT $EBOLD
2120 if [ -z "$TC_TIMER_STARTTIME" ]; then
2121 __print_err "timer not started" $@
2124 duration=$(($SECONDS-$TC_TIMER_STARTTIME))
2125 if [ $duration -eq 0 ]; then
2126 duration="<1 second"
2128 duration=$duration" seconds"
2130 echo " Timer duration :" $duration
2132 if [ $(($RES_FAIL+$RES_CONF_FAIL)) -ne $TC_TIMER_CURRENT_FAILS ]; then
2133 res="Failures occured during test - timer not reliabled"
2136 echo -e "$TC_TIMER_TIMER_TEXT \t $duration \t $res" >> $TIMER_MEASUREMENTS
2139 # Print info about a deviations from intended tests
2140 # Each deviation counted is also printed in the testreport
2141 # args <deviation message to print>
2143 echo -e $BOLD"DEVIATION(${BASH_LINENO[0]}): "${FUNCNAME[0]} $EBOLD
2144 if [ $# -lt 1 ]; then
2146 __print_err "need 1 or more args, <deviation message to print>" $@
2150 echo -e $BOLD$YELLOW" Test case deviation: ${@:1}"$EYELLOW$EBOLD
2151 echo "Line: ${BASH_LINENO[0]} - ${@:1}" >> $DEVIATION_FILE
2152 __print_current_stats
2156 # Stop at first FAIL test case and take all logs - only for debugging/trouble shooting
2157 __check_stop_at_error() {
2158 if [ $STOP_AT_ERROR -eq 1 ]; then
2159 echo -e $RED"Test script configured to stop at first FAIL, taking all logs and stops"$ERED
2160 store_logs "STOP_AT_ERROR"
2162 # Update test suite counter
2163 if [ -f .tmp_tcsuite_fail_ctr ]; then
2164 tmpval=$(< .tmp_tcsuite_fail_ctr)
2166 echo $tmpval > .tmp_tcsuite_fail_ctr
2168 if [ -f .tmp_tcsuite_fail ]; then
2169 echo " - "$ATC " -- "$TC_ONELINE_DESCR" Execution stopped due to error" >> .tmp_tcsuite_fail
2176 # Stop and remove all containers
2178 # (Not for test scripts)
2179 __clean_containers() {
2181 echo -e $BOLD"Docker clean and stopping and removing all running containers, by container name"$EBOLD
2184 running_contr_file="./tmp/running_contr.txt"
2185 > $running_contr_file
2187 # Get list of all containers started by the test script
2188 for imagename in $APP_SHORT_NAMES; do
2189 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
2191 running_contr_file_empty="No docker containers running, started by previous test execution"
2192 if [ -s $running_contr_file ]; then
2193 running_contr_file_empty=""
2196 # Kill all containers started by the test env - to speed up shut down
2197 docker kill $(docker ps -a --filter "label=nrttest_app" --format '{{.Names}}') &> /dev/null
2199 tab_heading1="App display name"
2200 tab_heading2="App short name"
2201 tab_heading3="Container name"
2203 tab_heading1_len=${#tab_heading1}
2204 tab_heading2_len=${#tab_heading2}
2205 tab_heading3_len=${#tab_heading3}
2207 #Calc field lengths of each item in the list of containers
2209 if (( $cntr % 3 == 0 ));then
2210 if [ ${#p} -gt $tab_heading1_len ]; then
2211 tab_heading1_len=${#p}
2214 if (( $cntr % 3 == 1));then
2215 if [ ${#p} -gt $tab_heading2_len ]; then
2216 tab_heading2_len=${#p}
2219 if (( $cntr % 3 == 2));then
2220 if [ ${#p} -gt $tab_heading3_len ]; then
2221 tab_heading3_len=${#p}
2225 done <$running_contr_file
2227 let tab_heading1_len=tab_heading1_len+2
2228 while (( ${#tab_heading1} < $tab_heading1_len)); do
2229 tab_heading1="$tab_heading1"" "
2232 let tab_heading2_len=tab_heading2_len+2
2233 while (( ${#tab_heading2} < $tab_heading2_len)); do
2234 tab_heading2="$tab_heading2"" "
2237 let tab_heading3_len=tab_heading3_len+2
2238 while (( ${#tab_heading3} < $tab_heading3_len)); do
2239 tab_heading3="$tab_heading3"" "
2242 if [ ! -z "$running_contr_file_empty" ]; then
2243 echo $running_contr_file_empty | indent1
2245 echo " $tab_heading1$tab_heading2$tab_heading3"" Actions"
2248 if (( $cntr % 3 == 0 ));then
2251 heading_len=$tab_heading1_len
2253 if (( $cntr % 3 == 1));then
2255 heading_len=$tab_heading2_len
2257 if (( $cntr % 3 == 2));then
2260 heading_len=$tab_heading3_len
2262 while (( ${#heading} < $heading_len)); do
2263 heading="$heading"" "
2266 if (( $cntr % 3 == 2));then
2267 echo -ne $row$SAMELINE
2268 echo -ne " $row ${GREEN}stopping...${EGREEN}${SAMELINE}"
2269 docker stop $(docker ps -qa --filter name=${contr} --filter network=$DOCKER_SIM_NWNAME) &> /dev/null
2270 echo -ne " $row ${GREEN}stopped removing...${EGREEN}${SAMELINE}"
2271 docker rm --force $(docker ps -qa --filter name=${contr} --filter network=$DOCKER_SIM_NWNAME) &> /dev/null
2272 echo -e " $row ${GREEN}stopped removed ${EGREEN}"
2275 done <$running_contr_file
2280 echo -e $BOLD" Removing docker network"$EBOLD
2281 TMP=$(docker network ls -q --filter name=$DOCKER_SIM_NWNAME)
2282 if [ "$TMP" == $DOCKER_SIM_NWNAME ]; then
2283 docker network rm $DOCKER_SIM_NWNAME | indent2
2284 if [ $? -ne 0 ]; then
2285 echo -e $RED" Cannot remove docker network. Manually remove or disconnect containers from $DOCKER_SIM_NWNAME"$ERED
2289 echo -e "$GREEN Done$EGREEN"
2291 echo -e $BOLD" Removing all unused docker neworks"$EBOLD
2292 docker network prune --force | indent2
2293 echo -e "$GREEN Done$EGREEN"
2295 echo -e $BOLD" Removing all unused docker volumes"$EBOLD
2296 docker volume prune --force | indent2
2297 echo -e "$GREEN Done$EGREEN"
2299 echo -e $BOLD" Removing all dangling/untagged docker images"$EBOLD
2300 docker rmi --force $(docker images -q -f dangling=true) &> /dev/null
2301 echo -e "$GREEN Done$EGREEN"
2304 CONTRS=$(docker ps | awk '$1 != "CONTAINER" { n++ }; END { print n+0 }')
2305 if [ $? -eq 0 ]; then
2306 if [ $CONTRS -ne 0 ]; then
2307 echo -e $RED"Containers running, may cause distubance to the test case"$ERED
2308 docker ps -a | indent1
2314 ###################################
2315 ### Functions for kube management
2316 ###################################
2318 # Get resource type for scaling
2319 # args: <resource-name> <namespace>
2320 __kube_get_resource_type() {
2321 kubectl $KUBECONF get deployment $1 -n $2 1> /dev/null 2> ./tmp/kubeerr
2322 if [ $? -eq 0 ]; then
2326 kubectl $KUBECONF get sts $1 -n $2 1> /dev/null 2> ./tmp/kubeerr
2327 if [ $? -eq 0 ]; then
2331 echo "unknown-resource-type"
2335 # Scale a kube resource to a specific count
2336 # args: <resource-type> <resource-name> <namespace> <target-count>
2337 # (Not for test scripts)
2339 echo -ne " Setting $1 $2 replicas=$4 in namespace $3"$SAMELINE
2340 kubectl $KUBECONF scale $1 $2 -n $3 --replicas=$4 1> /dev/null 2> ./tmp/kubeerr
2341 if [ $? -ne 0 ]; then
2342 echo -e " Setting $1 $2 replicas=$4 in namespace $3 $RED Failed $ERED"
2344 echo " Message: $(<./tmp/kubeerr)"
2347 echo -e " Setting $1 $2 replicas=$4 in namespace $3 $GREEN OK $EGREEN"
2352 for i in {1..500}; do
2353 count=$(kubectl $KUBECONF get $1/$2 -n $3 -o jsonpath='{.status.replicas}' 2> /dev/null)
2355 if [ -z "$count" ]; then
2356 #No value is sometimes returned for some reason, in case the resource has replica 0
2359 if [ $retcode -ne 0 ]; then
2360 echo -e "$RED Cannot fetch current replica count for $1 $2 in namespace $3 $ERED"
2365 if [ $count -ne $4 ]; then
2366 echo -ne " Waiting for $1 $2 replicas=$4 in namespace $3. Replicas=$count after $(($SECONDS-$TSTART)) seconds $SAMELINE"
2369 echo -e " Waiting for $1 $2 replicas=$4 in namespace $3. Replicas=$count after $(($SECONDS-$TSTART)) seconds"
2370 echo -e " Replicas=$4 after $(($SECONDS-$TSTART)) seconds $GREEN OK $EGREEN"
2376 echo -e "$RED Replica count did not reach target replicas=$4. Failed with replicas=$count $ERED"
2381 # Scale all kube resource sets to 0 in a namespace for resources having a certain lable and label-id
2382 # This function does not wait for the resource to reach 0
2383 # args: <namespace> <label-name> <label-id>
2384 # (Not for test scripts)
2385 __kube_scale_all_resources() {
2389 resources="deployment replicaset statefulset"
2390 for restype in $resources; do
2391 result=$(kubectl $KUBECONF get $restype -n $namespace -o jsonpath='{.items[?(@.metadata.labels.'$labelname'=="'$labelid'")].metadata.name}')
2392 if [ $? -eq 0 ] && [ ! -z "$result" ]; then
2393 for resid in $result; do
2394 echo -ne " Ordered scaling $restype $resid in namespace $namespace with label $labelname=$labelid to 0"$SAMELINE
2395 kubectl $KUBECONF scale $restype $resid -n $namespace --replicas=0 1> /dev/null 2> ./tmp/kubeerr
2396 echo -e " Ordered scaling $restype $resid in namespace $namespace with label $labelname=$labelid to 0 $GREEN OK $EGREEN"
2402 # Scale all kube resource sets to 0 in a namespace for resources having a certain lable and an optional label-id
2403 # This function do wait for the resource to reach 0
2404 # args: <namespace> <label-name> [ <label-id> ]
2405 # (Not for test scripts)
2406 __kube_scale_and_wait_all_resources() {
2410 if [ -z "$3" ]; then
2411 echo " Attempt to scale - deployment replicaset statefulset - in namespace $namespace with label $labelname"
2413 echo " Attempt to scale - deployment replicaset statefulset - in namespace $namespace with label $labelname=$labelid"
2415 resources="deployment replicaset statefulset"
2417 while [ $scaled_all -ne 0 ]; do
2419 for restype in $resources; do
2420 if [ -z "$3" ]; then
2421 result=$(kubectl $KUBECONF get $restype -n $namespace -o jsonpath='{.items[?(@.metadata.labels.'$labelname')].metadata.name}')
2423 result=$(kubectl $KUBECONF get $restype -n $namespace -o jsonpath='{.items[?(@.metadata.labels.'$labelname'=="'$labelid'")].metadata.name}')
2425 if [ $? -eq 0 ] && [ ! -z "$result" ]; then
2426 for resid in $result; do
2427 echo -e " Ordered scaling $restype $resid in namespace $namespace with label $labelname=$labelid to 0"
2428 kubectl $KUBECONF scale $restype $resid -n $namespace --replicas=0 1> /dev/null 2> ./tmp/kubeerr
2431 while [ $count -ne 0 ]; do
2432 count=$(kubectl $KUBECONF get $restype $resid -n $namespace -o jsonpath='{.status.replicas}' 2> /dev/null)
2433 echo -ne " Scaling $restype $resid in namespace $namespace with label $labelname=$labelid to 0, current count=$count"$SAMELINE
2434 if [ $? -eq 0 ] && [ ! -z "$count" ]; then
2439 duration=$(($SECONDS-$T_START))
2440 if [ $duration -gt 100 ]; then
2441 #Forcring count 0, to avoid hanging for failed scaling
2446 echo -e " Scaled $restype $resid in namespace $namespace with label $labelname=$labelid to 0, current count=$count $GREEN OK $EGREEN"
2453 # Remove all kube resources in a namespace for resources having a certain label and label-id
2454 # This function wait until the resources are gone. Scaling to 0 must have been ordered previously
2455 # args: <namespace> <label-name> <label-id>
2456 # (Not for test scripts)
2457 __kube_delete_all_resources() {
2461 resources="deployments replicaset statefulset services pods configmaps persistentvolumeclaims persistentvolumes serviceaccounts clusterrolebindings secrets authorizationpolicies requestauthentications"
2462 deleted_resourcetypes=""
2463 for restype in $resources; do
2464 ns_flag="-n $namespace"
2465 ns_text="in namespace $namespace"
2466 if [ $restype == "persistentvolumes" ]; then
2470 if [ $restype == "clusterrolebindings" ]; then
2474 result=$(kubectl $KUBECONF get $restype $ns_flag -o jsonpath='{.items[?(@.metadata.labels.'$labelname'=="'$labelid'")].metadata.name}' 2> /dev/null)
2475 if [ $? -eq 0 ] && [ ! -z "$result" ]; then
2476 deleted_resourcetypes=$deleted_resourcetypes" "$restype
2477 for resid in $result; do
2478 if [ $restype == "replicaset" ] || [ $restype == "statefulset" ]; then
2480 while [ $count -ne 0 ]; do
2481 count=$(kubectl $KUBECONF get $restype $resid $ns_flag -o jsonpath='{.status.replicas}' 2> /dev/null)
2482 echo -ne " Scaling $restype $resid $ns_text with label $labelname=$labelid to 0, current count=$count"$SAMELINE
2483 if [ $? -eq 0 ] && [ ! -z "$count" ]; then
2489 echo -e " Scaled $restype $resid $ns_text with label $labelname=$labelid to 0, current count=$count $GREEN OK $EGREEN"
2491 echo -ne " Deleting $restype $resid $ns_text with label $labelname=$labelid "$SAMELINE
2492 kubectl $KUBECONF delete --grace-period=1 $restype $resid $ns_flag 1> /dev/null 2> ./tmp/kubeerr
2493 if [ $? -eq 0 ]; then
2494 echo -e " Deleted $restype $resid $ns_text with label $labelname=$labelid $GREEN OK $EGREEN"
2496 echo -e " Deleted $restype $resid $ns_text with label $labelname=$labelid $GREEN Does not exist - OK $EGREEN"
2502 if [ ! -z "$deleted_resourcetypes" ]; then
2503 for restype in $deleted_resources; do
2504 ns_flag="-n $namespace"
2505 ns_text="in namespace $namespace"
2506 if [ $restype == "persistentvolumes" ]; then
2510 echo -ne " Waiting for $restype $ns_text with label $labelname=$labelid to be deleted..."$SAMELINE
2513 while [ ! -z "$result" ]; do
2515 result=$(kubectl $KUBECONF get $restype $ns_flag -o jsonpath='{.items[?(@.metadata.labels.'$labelname'=="'$labelid'")].metadata.name}')
2516 echo -ne " Waiting for $restype $ns_text with label $labelname=$labelid to be deleted...$(($SECONDS-$T_START)) seconds "$SAMELINE
2517 if [ -z "$result" ]; then
2518 echo -e " Waiting for $restype $ns_text with label $labelname=$labelid to be deleted...$(($SECONDS-$T_START)) seconds $GREEN OK $EGREEN"
2519 elif [ $(($SECONDS-$T_START)) -gt 300 ]; then
2520 echo -e " Waiting for $restype $ns_text with label $labelname=$labelid to be deleted...$(($SECONDS-$T_START)) seconds $RED Failed $ERED"
2528 # Creates a namespace if it does not exists
2530 # (Not for test scripts)
2531 __kube_create_namespace() {
2533 #Check if test namespace exists, if not create it
2534 kubectl $KUBECONF get namespace $1 1> /dev/null 2> ./tmp/kubeerr
2535 if [ $? -ne 0 ]; then
2536 echo -ne " Creating namespace "$1 $SAMELINE
2537 kubectl $KUBECONF create namespace $1 1> /dev/null 2> ./tmp/kubeerr
2538 if [ $? -ne 0 ]; then
2539 echo -e " Creating namespace $1 $RED$BOLD FAILED $EBOLD$ERED"
2541 echo " Message: $(<./tmp/kubeerr)"
2544 kubectl $KUBECONF label ns $1 autotest=engine > /dev/null
2545 echo -e " Creating namespace $1 $GREEN$BOLD OK $EBOLD$EGREEN"
2548 echo -e " Creating namespace $1 $GREEN$BOLD Already exists, OK $EBOLD$EGREEN"
2553 # Removes a namespace if it exists
2555 # (Not for test scripts)
2556 __kube_delete_namespace() {
2558 #Check if test namespace exists, if so remove it
2559 kubectl $KUBECONF get namespace $1 1> /dev/null 2> ./tmp/kubeerr
2560 if [ $? -eq 0 ]; then
2561 echo -ne " Removing namespace "$1 $SAMELINE
2562 kubectl $KUBECONF delete namespace $1 1> /dev/null 2> ./tmp/kubeerr
2563 if [ $? -ne 0 ]; then
2564 echo -e " Removing namespace $1 $RED$BOLD FAILED $EBOLD$ERED"
2566 echo " Message: $(<./tmp/kubeerr)"
2569 echo -e " Removing namespace $1 $GREEN$BOLD OK $EBOLD$EGREEN"
2572 echo -e " Namespace $1 $GREEN$BOLD does not exist, OK $EBOLD$EGREEN"
2577 # Removes and re-create a namespace
2579 # (Not for test scripts)
2580 clean_and_create_namespace() {
2583 if [ $# -ne 1 ]; then
2584 __print_err "<namespace>" $@
2587 __kube_delete_namespace $1
2588 if [ $? -ne 0 ]; then
2591 __kube_create_namespace $1
2592 if [ $? -ne 0 ]; then
2597 # Add/remove label on non-namespaced kube object
2598 # args: <api> <instance> <label>
2599 # (Not for test scripts)
2600 __kube_label_non_ns_instance() {
2601 kubectl $KUBECONF label $1 $2 "$3" 1> /dev/null 2> ./tmp/kubeerr
2605 # Add/remove label on namespaced kube object
2606 # args: <api> <instance> <namespace> <label>
2607 # (Not for test scripts)
2608 __kube_label_ns_instance() {
2609 kubectl $KUBECONF label $1 $2 -n $3 "$4" 1> /dev/null 2> ./tmp/kubeerr
2613 # Find the host ip of an app (using the service resource)
2614 # args: <app-name> <namespace>
2615 # (Not for test scripts)
2616 __kube_get_service_host() {
2617 if [ $# -ne 2 ]; then
2619 __print_err "need 2 args, <app-name> <namespace>" $@
2622 for timeout in {1..60}; do
2623 host=$(kubectl $KUBECONF get svc $1 -n $2 -o jsonpath='{.spec.clusterIP}')
2624 if [ $? -eq 0 ]; then
2625 if [ ! -z "$host" ]; then
2633 echo "host-not-found-fatal-error"
2637 # Find the named port to an app (using the service resource)
2638 # args: <app-name> <namespace> <port-name>
2639 # (Not for test scripts)
2640 __kube_get_service_port() {
2641 if [ $# -ne 3 ]; then
2643 __print_err "need 3 args, <app-name> <namespace> <port-name>" $@
2647 for timeout in {1..60}; do
2648 port=$(kubectl $KUBECONF get svc $1 -n $2 -o jsonpath='{...ports[?(@.name=="'$3'")].port}')
2649 if [ $? -eq 0 ]; then
2650 if [ ! -z "$port" ]; then
2662 # Find the named node port to an app (using the service resource)
2663 # args: <app-name> <namespace> <port-name>
2664 # (Not for test scripts)
2665 __kube_get_service_nodeport() {
2666 if [ $# -ne 3 ]; then
2668 __print_err "need 3 args, <app-name> <namespace> <port-name>" $@
2672 for timeout in {1..60}; do
2673 port=$(kubectl $KUBECONF get svc $1 -n $2 -o jsonpath='{...ports[?(@.name=="'$3'")].nodePort}')
2674 if [ $? -eq 0 ]; then
2675 if [ ! -z "$port" ]; then
2687 # Create a kube resource from a yaml template
2688 # args: <resource-type> <resource-name> <template-yaml> <output-yaml>
2689 # (Not for test scripts)
2690 __kube_create_instance() {
2691 echo -ne " Creating $1 $2"$SAMELINE
2693 kubectl $KUBECONF apply -f $4 1> /dev/null 2> ./tmp/kubeerr
2694 if [ $? -ne 0 ]; then
2696 echo -e " Creating $1 $2 $RED Failed $ERED"
2697 echo " Message: $(<./tmp/kubeerr)"
2700 echo -e " Creating $1 $2 $GREEN OK $EGREEN"
2704 # Function to create a configmap in kubernetes
2705 # args: <configmap-name> <namespace> <labelname> <labelid> <path-to-data-file> <path-to-output-yaml>
2706 # (Not for test scripts)
2707 __kube_create_configmap() {
2708 echo -ne " Creating configmap $1 "$SAMELINE
2709 envsubst < $5 > $5"_tmp"
2710 cp $5"_tmp" $5 #Need to copy back to orig file name since create configmap neeed the original file name
2711 kubectl $KUBECONF create configmap $1 -n $2 --from-file=$5 --dry-run=client -o yaml > $6
2712 if [ $? -ne 0 ]; then
2713 echo -e " Creating configmap $1 $RED Failed $ERED"
2718 kubectl $KUBECONF apply -f $6 1> /dev/null 2> ./tmp/kubeerr
2719 if [ $? -ne 0 ]; then
2720 echo -e " Creating configmap $1 $RED Apply failed $ERED"
2721 echo " Message: $(<./tmp/kubeerr)"
2725 kubectl $KUBECONF label configmap $1 -n $2 $3"="$4 --overwrite 1> /dev/null 2> ./tmp/kubeerr
2726 if [ $? -ne 0 ]; then
2727 echo -e " Creating configmap $1 $RED Labeling failed $ERED"
2728 echo " Message: $(<./tmp/kubeerr)"
2732 # Log the resulting map
2733 kubectl $KUBECONF get configmap $1 -n $2 -o yaml > $6
2735 echo -e " Creating configmap $1 $GREEN OK $EGREEN"
2739 # This function runs a kubectl cmd where a single output value is expected, for example get ip with jsonpath filter.
2740 # The function retries up to the timeout given in the cmd flag '--cluster-timeout'
2741 # args: <full kubectl cmd with parameters>
2742 # (Not for test scripts)
2743 __kube_cmd_with_timeout() {
2744 TS_TMP=$(($SECONDS+$CLUSTER_TIME_OUT))
2747 kube_cmd_result=$($@)
2748 if [ $? -ne 0 ]; then
2751 if [ $SECONDS -ge $TS_TMP ] || [ ! -z "$kube_cmd_result" ] ; then
2752 echo $kube_cmd_result
2759 # This function starts a pod that cleans a the contents of a path mounted as a pvc
2760 # After this action the pod should terminate
2761 # This should only be executed when the pod owning the pvc is not running
2762 # args: <appname> <namespace> <pvc-name> <path-to remove>
2763 # (Not for test scripts)
2764 __kube_clean_pvc() {
2766 #using env vars setup in pvccleaner_api_functions.sh
2768 export PVC_CLEANER_NAMESPACE=$2
2769 export PVC_CLEANER_CLAIMNAME=$3
2770 export PVC_CLEANER_RM_PATH=$4
2771 export PVC_CLEANER_APP_NAME
2772 input_yaml=$SIM_GROUP"/"$PVC_CLEANER_COMPOSE_DIR"/"pvc-cleaner.yaml
2773 output_yaml=$PWD/tmp/$2-pvc-cleaner.yaml
2775 envsubst < $input_yaml > $output_yaml
2777 kubectl $KUBECONF delete -f $output_yaml 1> /dev/null 2> /dev/null # Delete the previous terminated pod - if existing
2779 __kube_create_instance pod $PVC_CLEANER_APP_NAME $input_yaml $output_yaml
2780 if [ $? -ne 0 ]; then
2781 echo $YELLOW" Could not clean pvc for app: $1 - persistent storage not clean - tests may not work"
2785 term_ts=$(($SECONDS+30))
2786 while [ $term_ts -gt $SECONDS ]; do
2787 pod_status=$(kubectl $KUBECONF get pod pvc-cleaner -n $PVC_CLEANER_NAMESPACE --no-headers -o custom-columns=":status.phase")
2788 if [ "$pod_status" == "Succeeded" ]; then
2795 # This function scales or deletes all resources for app selected by the testcase.
2797 # (Not for test scripts)
2799 echo -e $BOLD"Initialize kube pods/statefulsets/replicaset to initial state"$EBOLD
2801 # Scale prestarted or managed apps
2802 for imagename in $APP_SHORT_NAMES; do
2803 # A function name is created from the app short name
2804 # for example app short name 'RICMSIM' -> produce the function
2805 # name __RICSIM_kube_scale_zero or __RICSIM_kube_scale_zero_and_wait
2806 # This function is called and is expected to exist in the imported
2807 # file for the ricsim test functions
2808 # The resulting function impl shall scale the resources to 0
2809 # For pre-started apps, the function waits until the resources are 0
2810 # For included (not prestated) apps, the scaling is just ordered
2811 __check_prestarted_image $imagename
2812 if [ $? -eq 0 ]; then
2813 function_pointer="__"$imagename"_kube_scale_zero_and_wait"
2814 echo -e " Scaling all kube resources for app $BOLD $imagename $EBOLD to 0"
2817 __check_included_image $imagename
2818 if [ $? -eq 0 ]; then
2819 function_pointer="__"$imagename"_kube_scale_zero"
2820 echo -e " Scaling all kube resources for app $BOLD $imagename $EBOLD to 0"
2826 # Delete managed apps
2827 for imagename in $APP_SHORT_NAMES; do
2828 __check_included_image $imagename
2829 if [ $? -eq 0 ]; then
2830 __check_prestarted_image $imagename
2831 if [ $? -ne 0 ]; then
2832 # A function name is created from the app short name
2833 # for example app short name 'RICMSIM' -> produce the function
2834 # name __RICSIM__kube_delete_all
2835 # This function is called and is expected to exist in the imported
2836 # file for the ricsim test functions
2837 # The resulting function impl shall delete all its resources
2838 function_pointer="__"$imagename"_kube_delete_all"
2839 echo -e " Deleting all kube resources for app $BOLD $imagename $EBOLD"
2845 # Remove istio label on namespaces
2846 test_env_namespaces=$(kubectl $KUBECONF get ns --no-headers -o custom-columns=":metadata.name" -l autotest=engine -l istio-injection=enabled) #Get list of ns created by the test env
2847 if [ $? -ne 0 ]; then
2848 echo " Cannot get list of namespaces...continues.."
2850 for test_env_ns in $test_env_namespaces; do
2851 echo " Removing istio label on ns: "$test_env_ns
2852 __kube_label_non_ns_instance ns $test_env_ns "istio-injection-"
2859 # Function stop and remove all containers (docker) and services/deployments etc(kube)
2861 # Function for test script
2862 clean_environment() {
2863 if [ $RUNMODE == "KUBE" ]; then
2865 if [ $PRE_CLEAN -eq 1 ]; then
2866 echo " Cleaning docker resouces to free up resources, may take time..."
2867 ../common/clean_docker.sh 2>&1 > /dev/null
2872 if [ $PRE_CLEAN -eq 1 ]; then
2873 echo " Cleaning kubernetes resouces to free up resources, may take time..."
2874 ../common/clean_kube.sh $KUBECONF 2>&1 > /dev/null
2880 # 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
2882 # (Function for test scripts)
2883 auto_clean_environment() {
2885 if [ "$AUTO_CLEAN" == "auto" ]; then
2886 echo -e $BOLD"Initiating automatic cleaning of environment"$EBOLD
2891 # Function to sleep a test case for a numner of seconds. Prints the optional text args as info
2892 # args: <sleep-time-in-sec> [any-text-in-quotes-to-be-printed]
2893 # (Function for test scripts)
2896 echo -e $BOLD"INFO(${BASH_LINENO[0]}): "${FUNCNAME[0]}"," $@ $EBOLD
2897 if [ $# -lt 1 ]; then
2899 __print_err "need at least one arg, <sleep-time-in-sec> [any-text-to-printed]" $@
2902 #echo "---- Sleep for " $1 " seconds ---- "$2
2904 duration=$((SECONDS-start))
2905 while [ $duration -lt $1 ]; do
2906 echo -ne " Slept for ${duration} seconds${SAMELINE}"
2908 duration=$((SECONDS-start))
2910 echo -ne " Slept for ${duration} seconds${SAMELINE}"
2914 # Print error info for the call in the parent script (test case). Arg: <error-message-to-print>
2915 # Not to be called from the test script itself.
2917 echo -e $RED ${FUNCNAME[1]} " "$1" " ${BASH_SOURCE[2]} " line" ${BASH_LINENO[1]} $ERED
2918 if [ $# -gt 1 ]; then
2919 echo -e $RED" Got: "${FUNCNAME[1]} ${@:2} $ERED
2922 __check_stop_at_error
2925 # Function to create the docker network for the test
2926 # Not to be called from the test script itself.
2927 __create_docker_network() {
2928 tmp=$(docker network ls --format={{.Name}} --filter name=$DOCKER_SIM_NWNAME)
2929 if [ $? -ne 0 ]; then
2930 echo -e $RED" Could not check if docker network $DOCKER_SIM_NWNAME exists"$ERED
2933 if [ "$tmp" != $DOCKER_SIM_NWNAME ]; then
2934 echo -e " Creating docker network:$BOLD $DOCKER_SIM_NWNAME $EBOLD"
2935 docker network create $DOCKER_SIM_NWNAME | indent2
2936 if [ $? -ne 0 ]; then
2937 echo -e $RED" Could not create docker network $DOCKER_SIM_NWNAME"$ERED
2940 echo -e "$GREEN Done$EGREEN"
2943 echo -e " Docker network $DOCKER_SIM_NWNAME already exists$GREEN OK $EGREEN"
2947 # Function to start container with docker-compose and wait until all are in state running.
2948 # If the <docker-compose-file> is empty, the default 'docker-compose.yml' is assumed.
2949 #args: <docker-compose-dir> <docker-compose-file> <docker-compose-arg>|NODOCKERARGS <count> <app-name>+
2950 # (Not for test scripts)
2951 __start_container() {
2953 if [ $# -lt 5 ]; then
2955 __print_err "need 5 or more args, <docker-compose-dir> <docker-compose-file> <docker-compose-arg>|NODOCKERARGS <count> <app-name>+" $@
2959 __create_docker_network
2967 if [ -z "$compose_file" ]; then
2968 compose_file="docker-compose.yml"
2976 envsubst < $compose_file > "gen_"$compose_file
2977 compose_file="gen_"$compose_file
2978 docker_compose_cmd="docker compose"
2980 if [ "$compose_args" == "NODOCKERARGS" ]; then
2981 $docker_compose_cmd -f $compose_file up -d &> .dockererr
2982 if [ $? -ne 0 ]; then
2983 echo -e $RED"Problem to launch container(s) with docker-compose"$ERED
2985 echo -e $RED"Stopping script...."$ERED
2989 $docker_compose_cmd -f $compose_file up -d $compose_args &> .dockererr
2990 if [ $? -ne 0 ]; then
2991 echo -e $RED"Problem to launch container(s) with docker-compose"$ERED
2993 echo -e $RED"Stopping script...."$ERED
3001 while [ $appindex -lt $appcount ]; do
3005 for i in {1..10}; do
3006 if [ "$(docker inspect --format '{{ .State.Running }}' $appname)" == "true" ]; then
3007 echo -e " Container $BOLD${appname}$EBOLD$GREEN running$EGREEN on$BOLD image $(docker inspect --format '{{ .Config.Image }}' ${appname}) $EBOLD"
3014 if [ $app_started -eq 0 ]; then
3017 echo -e $RED" Container $BOLD${appname}$EBOLD could not be started"$ERED
3018 echo -e $RED" Stopping script..."$ERED
3021 let appindex=appindex+1
3026 # Function to check if container/service is responding to http/https
3027 # args: <container-name>|<service-name> url
3028 # (Not for test scripts)
3029 __check_service_start() {
3031 if [ $# -ne 2 ]; then
3033 __print_err "need 2 args, <container-name>|<service-name> url" $@
3037 if [ $RUNMODE == "KUBE" ]; then
3038 ENTITY="service/set/deployment"
3044 echo -ne " Container $BOLD${appname}$EBOLD starting${SAMELINE}"
3048 echo -ne " Waiting for ${ENTITY} ${appname} service status...${SAMELINE}"
3051 while (( $TSTART+600 > $SECONDS )); do
3052 result="$(__do_curl -m 10 $url)"
3053 if [ $? -eq 0 ]; then
3054 if [ ${#result} -gt 15 ]; then
3055 #If response is too long, truncate
3056 result="...response text too long, omitted"
3058 echo -ne " Waiting for {ENTITY} $BOLD${appname}$EBOLD service status on ${3}, result: $result${SAMELINE}"
3059 echo -ne " The ${ENTITY} $BOLD${appname}$EBOLD$GREEN is alive$EGREEN, responds to service status:$GREEN $result $EGREEN on ${url} after $(($SECONDS-$TSTART)) seconds"
3065 if (( $TS_OFFSET > 5 )); then
3068 while [ $(($TS_TMP+$TS_OFFSET)) -gt $SECONDS ]; do
3069 echo -ne " Waiting for ${ENTITY} ${appname} service status on ${url}...$(($SECONDS-$TSTART)) seconds, retrying in $(($TS_TMP+$TS_OFFSET-$SECONDS)) seconds ${SAMELINE}"
3073 let loop_ctr=loop_ctr+1
3076 if [ "$a1pmsst" = "false" ]; then
3078 echo -e $RED" The ${ENTITY} ${appname} did not respond to service status on ${url} in $(($SECONDS-$TSTART)) seconds"$ERED
3091 __check_container_logs() {
3099 echo -e $BOLD"Checking $dispname container $appname log ($logpath) for WARNINGs and ERRORs"$EBOLD
3101 if [ $RUNMODE == "KUBE" ]; then
3102 echo -e $YELLOW" Internal log for $dispname not checked in kube"$EYELLOW
3106 #tmp=$(docker ps | grep $appname)
3107 tmp=$(docker ps -q --filter name=$appname) #get the container id
3108 if [ -z "$tmp" ]; then #Only check logs for running A1PMS apps
3109 echo " "$dispname" is not running, no check made"
3112 foundentries="$(docker exec -t $tmp grep $warning $logpath | wc -l)"
3113 if [ $? -ne 0 ];then
3114 echo " Problem to search $appname log $logpath"
3116 if [ $foundentries -eq 0 ]; then
3117 echo " No WARN entries found in $appname log $logpath"
3119 echo -e " Found \033[1m"$foundentries"\033[0m WARN entries in $appname log $logpath"
3122 foundentries="$(docker exec -t $tmp grep $error $logpath | wc -l)"
3123 if [ $? -ne 0 ];then
3124 echo " Problem to search $appname log $logpath"
3126 if [ $foundentries -eq 0 ]; then
3127 echo " No ERR entries found in $appname log $logpath"
3129 echo -e $RED" Found \033[1m"$foundentries"\033[0m"$RED" ERR entries in $appname log $logpath"$ERED
3135 # Store all container logs and other logs in the log dir for the script
3136 # Logs are stored with a prefix in case logs should be stored several times during a test
3137 # args: <logfile-prefix>
3138 # (Function for test scripts)
3140 if [ $# != 1 ]; then
3142 __print_err "need one arg, <file-prefix>" $@
3145 echo -e $BOLD"Storing all docker/kube container logs and other test logs in $TESTLOGS/$ATC using prefix: "$1$EBOLD
3147 docker stats --no-stream > $TESTLOGS/$ATC/$1_docker_stats.log 2>&1
3149 docker ps -a > $TESTLOGS/$ATC/$1_docker_ps.log 2>&1
3151 cp .httplog_${ATC}.txt $TESTLOGS/$ATC/$1_httplog_${ATC}.txt 2>&1
3153 if [ $RUNMODE == "DOCKER" ]; then
3155 # Store docker logs for all container
3156 for imagename in $APP_SHORT_NAMES; do
3157 __check_included_image $imagename
3158 if [ $? -eq 0 ]; then
3159 # A function name is created from the app short name
3160 # for example app short name 'RICMSIM' -> produce the function
3161 # name __RICSIM__store_docker_logs
3162 # This function is called and is expected to exist in the imported
3163 # file for the ricsim test functions
3164 # The resulting function impl shall store the docker logs for each container
3165 function_pointer="__"$imagename"_store_docker_logs"
3166 $function_pointer "$TESTLOGS/$ATC/" $1
3170 if [ $RUNMODE == "KUBE" ]; then
3171 namespaces=$(kubectl $KUBECONF get namespaces -o jsonpath='{.items[?(@.metadata.name)].metadata.name}')
3172 for nsid in $namespaces; do
3173 pods=$(kubectl $KUBECONF get pods -n $nsid -o jsonpath='{.items[?(@.metadata.labels.autotest)].metadata.name}')
3174 for podid in $pods; do
3175 kubectl $KUBECONF logs -n $nsid $podid > $TESTLOGS/$ATC/$1_${podid}.log
3185 # Generic curl function, assumes all 200-codes are ok
3187 # args: <valid-curl-args-including full url>
3188 # returns: <returned response (without respose code)> or "<no-response-from-server>" or "<not found, <http-code>>""
3189 # returns: The return code is 0 for ok and 1 for not ok
3191 echo ${FUNCNAME[1]} "line: "${BASH_LINENO[1]} >> $HTTPLOG
3193 if [ ! -z "$KUBE_PROXY_PATH" ]; then
3194 if [ $KUBE_PROXY_HTTPX == "http" ]; then
3195 proxyflag=" --proxy $KUBE_PROXY_PATH"
3197 proxyflag=" --proxy-insecure --proxy $KUBE_PROXY_PATH"
3201 if [ ! -z "$KUBE_PROXY_CURL_JWT" ]; then
3202 jwt="-H "\""Authorization: Bearer $KUBE_PROXY_CURL_JWT"\"
3203 curlString="curl -skw %{http_code} $proxyflag $@"
3204 echo " CMD: $curlString $jwt" >> $HTTPLOG
3205 res=$($curlString -H "Authorization: Bearer $KUBE_PROXY_CURL_JWT")
3208 curlString="curl -skw %{http_code} $proxyflag $@"
3209 echo " CMD: $curlString" >> $HTTPLOG
3213 echo " RESP: $res" >> $HTTPLOG
3214 echo " RETCODE: $retcode" >> $HTTPLOG
3215 if [ $retcode -ne 0 ]; then
3216 echo "<no-response-from-server>"
3219 http_code="${res:${#res}-3}"
3220 if [ ${#res} -eq 3 ]; then
3221 if [ $http_code -lt 200 ] || [ $http_code -gt 299 ]; then
3222 echo "<no-response-from-server>"
3228 if [ $http_code -lt 200 ] || [ $http_code -gt 299 ]; then
3229 echo "<not found, resp:${http_code}>"
3232 if [ $# -eq 2 ]; then
3233 echo "${res:0:${#res}-3}" | xargs
3235 echo "${res:0:${#res}-3}"
3243 # Generic curl function, assumes all 200-codes are ok
3244 # Uses no proxy, even if it is set
3245 # args: <valid-curl-args-including full url>
3246 # returns: <returned response (without respose code)> or "<no-response-from-server>" or "<not found, <http-code>>""
3247 # returns: The return code is 0 for ok and 1 for not ok
3248 __do_curl_no_proxy() {
3249 echo ${FUNCNAME[1]} "line: "${BASH_LINENO[1]} >> $HTTPLOG
3250 curlString="curl -skw %{http_code} $@"
3251 echo " CMD: $curlString" >> $HTTPLOG
3254 echo " RESP: $res" >> $HTTPLOG
3255 echo " RETCODE: $retcode" >> $HTTPLOG
3256 if [ $retcode -ne 0 ]; then
3257 echo "<no-response-from-server>"
3260 http_code="${res:${#res}-3}"
3261 if [ ${#res} -eq 3 ]; then
3262 if [ $http_code -lt 200 ] || [ $http_code -gt 299 ]; then
3263 echo "<no-response-from-server>"
3269 if [ $http_code -lt 200 ] || [ $http_code -gt 299 ]; then
3270 echo "<not found, resp:${http_code}>"
3273 if [ $# -eq 2 ]; then
3274 echo "${res:0:${#res}-3}" | xargs
3276 echo "${res:0:${#res}-3}"
3283 #######################################
3284 ### Basic helper function for test cases
3285 #######################################
3287 # Test a simulator container variable value towards target value using an condition operator with an optional timeout.
3288 # Arg: <simulator-name> <host> <variable-name> <condition-operator> <target-value> - This test is done
3289 # immediately and sets pass or fail depending on the result of comparing variable and target using the operator.
3290 # Arg: <simulator-name> <host> <variable-name> <condition-operator> <target-value> <timeout> - This test waits up to the timeout
3291 # before setting pass or fail depending on the result of comparing variable and target using the operator.
3292 # 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.
3293 # Not to be called from test script.
3296 checkjsonarraycount=0
3297 TIMESTAMP=$(date "+%Y-%m-%d %H:%M:%S")
3298 if [ $# -eq 6 ]; then
3299 if [[ $3 == "json:"* ]]; then
3300 checkjsonarraycount=1
3303 echo -e $BOLD"TEST $TEST_SEQUENCE_NR - (${BASH_LINENO[1]}) - ${TIMESTAMP}: ${1}, ${3} ${4} ${5} within ${6} seconds"$EBOLD
3304 echo "TEST $TEST_SEQUENCE_NR - (${BASH_LINENO[1]}) - ${TIMESTAMP}: ${1}, ${3} ${4} ${5} within ${6} seconds" >> $HTTPLOG
3307 ((TEST_SEQUENCE_NR++))
3311 if [ $checkjsonarraycount -eq 0 ]; then
3312 result="$(__do_curl $2$3)"
3314 result=${result//[[:blank:]]/} #Strip blanks
3317 result="$(__do_curl $2$path)"
3319 echo "$result" > ./tmp/.tmp.curl.json
3320 result=$(python3 ../common/count_json_elements.py "./tmp/.tmp.curl.json")
3322 duration=$((SECONDS-start))
3323 echo -ne " Result=${result} after ${duration} seconds${SAMELINE}"
3325 if [ $retcode -ne 0 ]; then
3326 if [ $duration -gt $6 ]; then
3328 echo -e $RED" FAIL${ERED} - ${3} ${4} ${5} not reached in ${6} seconds, result = ${result}"
3329 __print_current_stats
3330 __check_stop_at_error
3333 elif [ "$4" == "=" ] && [ "$result" -eq $5 ]; then
3335 echo -e " Result=${result} after ${duration} seconds${SAMELINE}"
3336 echo -e $GREEN" PASS${EGREEN} - Result=${result} after ${duration} seconds"
3337 __print_current_stats
3339 elif [ "$4" == ">" ] && [ "$result" -gt $5 ]; then
3341 echo -e " Result=${result} after ${duration} seconds${SAMELINE}"
3342 echo -e $GREEN" PASS${EGREEN} - Result=${result} after ${duration} seconds"
3343 __print_current_stats
3345 elif [ "$4" == "<" ] && [ "$result" -lt $5 ]; then
3347 echo -e " Result=${result} after ${duration} seconds${SAMELINE}"
3348 echo -e $GREEN" PASS${EGREEN} - Result=${result} after ${duration} seconds"
3349 __print_current_stats
3351 elif [ "$4" == ">=" ] && [ "$result" -ge $5 ]; then
3353 echo -e " Result=${result} after ${duration} seconds${SAMELINE}"
3354 echo -e $GREEN" PASS${EGREEN} - Result=${result} after ${duration} seconds"
3355 __print_current_stats
3357 elif [ "$4" == "contain_str" ] && [[ $result =~ $5 ]]; then
3359 echo -e " Result=${result} after ${duration} seconds${SAMELINE}"
3360 echo -e $GREEN" PASS${EGREEN} - Result=${result} after ${duration} seconds"
3361 __print_current_stats
3364 if [ $duration -gt $6 ]; then
3366 echo -e $RED" FAIL${ERED} - ${3} ${4} ${5} not reached in ${6} seconds, result = ${result}"
3367 __print_current_stats
3368 __check_stop_at_error
3374 elif [ $# -eq 5 ]; then
3375 if [[ $3 == "json:"* ]]; then
3376 checkjsonarraycount=1
3379 echo -e $BOLD"TEST $TEST_SEQUENCE_NR - (${BASH_LINENO[1]}) - ${TIMESTAMP}: ${1}, ${3} ${4} ${5}"$EBOLD
3380 echo "TEST $TEST_SEQUENCE_NR - (${BASH_LINENO[1]}) - ${TIMESTAMP}: ${1}, ${3} ${4} ${5}" >> $HTTPLOG
3382 ((TEST_SEQUENCE_NR++))
3383 if [ $checkjsonarraycount -eq 0 ]; then
3384 result="$(__do_curl $2$3)"
3386 result=${result//[[:blank:]]/} #Strip blanks
3389 result="$(__do_curl $2$path)"
3391 echo "$result" > ./tmp/.tmp.curl.json
3392 result=$(python3 ../common/count_json_elements.py "./tmp/.tmp.curl.json")
3394 if [ $retcode -ne 0 ]; then
3396 echo -e $RED" FAIL ${ERED}- ${3} ${4} ${5} not reached, result = ${result}"
3397 __print_current_stats
3398 __check_stop_at_error
3399 elif [ "$4" == "=" ] && [ "$result" -eq $5 ]; then
3401 echo -e $GREEN" PASS${EGREEN} - Result=${result}"
3402 __print_current_stats
3403 elif [ "$4" == ">" ] && [ "$result" -gt $5 ]; then
3405 echo -e $GREEN" PASS${EGREEN} - Result=${result}"
3406 __print_current_stats
3407 elif [ "$4" == "<" ] && [ "$result" -lt $5 ]; then
3409 echo -e $GREEN" PASS${EGREEN} - Result=${result}"
3410 __print_current_stats
3411 elif [ "$4" == ">=" ] && [ "$result" -ge $5 ]; then
3413 echo -e $GREEN" PASS${EGREEN} - Result=${result}"
3414 __print_current_stats
3415 elif [ "$4" == "contain_str" ] && [[ $result =~ $5 ]]; then
3417 echo -e $GREEN" PASS${EGREEN} - Result=${result}"
3418 __print_current_stats
3421 echo -e $RED" FAIL${ERED} - ${3} ${4} ${5} not reached, result = ${result}"
3422 __print_current_stats
3423 __check_stop_at_error
3426 echo "Wrong args to __var_test, needs five or six args: <simulator-name> <host> <variable-name> <condition-operator> <target-value> [ <timeout> ]"