3 # ============LICENSE_START===============================================
4 # Copyright (C) 2020 Nordix Foundation. All rights reserved.
5 # ========================================================================
6 # Licensed under the Apache License, Version 2.0 (the "License");
7 # you may not use this file except in compliance with the License.
8 # You may obtain a copy of the License at
10 # http://www.apache.org/licenses/LICENSE-2.0
12 # Unless required by applicable law or agreed to in writing, software
13 # distributed under the License is distributed on an "AS IS" BASIS,
14 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 # See the License for the specific language governing permissions and
16 # limitations under the License.
17 # ============LICENSE_END=================================================
20 # This is a script that contains all the common functions needed for auto test.
21 # Specific test function are defined in scripts XXXX_functions.sh
23 . ../common/api_curl.sh
24 . ../common/testengine_config.sh
27 echo "Args: remote|remote-remove docker|kube --env-file <environment-filename> [release] [auto-clean] [--stop-at-error] "
28 echo " [--ricsim-prefix <prefix> ] [--use-local-image <app-nam>+] [--use-snapshot-image <app-nam>+]"
29 echo " [--use-staging-image <app-nam>+] [--use-release-image <app-nam>+] [--image-repo <repo-address>]"
30 echo " [--repo-policy local|remote] [--cluster-timeout <timeout-in seconds>] [--print-stats]"
31 echo " [--override <override-environment-filename>] [--pre-clean] [--gen-stats] [--delete-namespaces]"
32 echo " [--delete-containers] [--endpoint-stats] [--kubeconfig <config-file>] [--host-path-dir <local-host-dir>]"
35 if [ $# -eq 1 ] && [ "$1" == "help" ]; then
37 if [ ! -z "$TC_ONELINE_DESCR" ]; then
38 echo "Test script description:"
39 echo $TC_ONELINE_DESCR
44 echo "remote - Use images from remote repositories. Can be overridden for individual images using the '--use_xxx' flags"
45 echo "remote-remove - Same as 'remote' but will also try to pull fresh images from remote repositories"
46 echo "docker - Test executed in docker environment"
47 echo "kube - Test executed in kubernetes environment - requires an already started kubernetes environment"
48 echo "--env-file <file> - The script will use the supplied file to read environment variables from"
49 echo "release - If this flag is given the script will use release version of the images"
50 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."
51 echo "--stop-at-error - The script will stop when the first failed test or configuration"
52 echo "--ricsim-prefix - The a1 simulator will use the supplied string as container prefix instead of 'ricsim'"
53 echo "--use-local-image - The script will use local images for the supplied apps, space separated list of app short names"
54 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"
55 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"
56 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"
57 echo "--image-repo - Url to optional image repo. Only locally built images will be re-tagged and pushed to this repo"
58 echo "--repo-policy - Policy controlling which images to re-tag and push if param --image-repo is set. Default is 'local'"
59 echo "--cluster-timeout - Optional timeout for cluster where it takes time to obtain external ip/host-name. Timeout in seconds. "
60 echo "--print-stats - Print current test stats after each test."
61 echo "--override <file> - Override setting from the file supplied by --env-file"
62 echo "--pre-clean - Will clean kube resouces when running docker and vice versa"
63 echo "--gen-stats - Collect container/pod runtime statistics"
64 echo "--delete-namespaces - Delete kubernetes namespaces before starting tests - but only those created by the test scripts. Kube mode only. Ignored if running with prestarted apps."
65 echo "--delete-containers - Delete docker containers before starting tests - but only those created by the test scripts. Docker mode only."
66 echo "--endpoint-stats - Collect endpoint statistics"
67 echo "--kubeconfig - Configure kubectl to use cluster specific cluster config file"
68 echo "--host-path-dir - (Base-)path on local-hostmounted to all VMs (nodes), for hostpath volumes in kube"
70 echo "List of app short names supported: "$APP_SHORT_NAMES
75 # Create a test case id, ATC (Auto Test Case), from the name of the test case script.
76 # FTC1.sh -> ATC == FTC1
77 ATC=$(basename "${BASH_SOURCE[$i+1]}" .sh)
79 #Create result file (containing '1' for error) for this test case
80 #Will be replaced with a file containing '0' if all test cases pass
81 echo "1" > "$PWD/.result$ATC.txt"
83 #Formatting for 'echo' cmd
88 GREEN="\033[32m\033[1m"
90 YELLOW="\033[33m\033[1m"
94 # Just resetting any previous echo formatting...
97 # default test environment variables
99 #Override env file, will be added on top of the above file
100 TEST_ENV_VAR_FILE_OVERRIDE=""
102 echo "Test case started as: ${BASH_SOURCE[$i+1]} "$@
105 LOCALHOST_NAME="localhost"
106 LOCALHOST_HTTP="http://localhost"
107 LOCALHOST_HTTPS="https://localhost"
109 # Var to hold 'auto' in case containers shall be stopped when test case ends
112 # Var to indicate pre clean, if flag --pre-clean is set the script will clean kube resouces when running docker and vice versa
115 # Var to hold the app names to use local images for
118 # Var to hold the app names to use remote snapshot images for
119 USE_SNAPSHOT_IMAGES=""
121 # Var to hold the app names to use remote staging images for
122 USE_STAGING_IMAGES=""
124 # Var to hold the app names to use remote release images for
125 USE_RELEASE_IMAGES=""
128 # 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
131 # The default value "DEV" indicate that development image tags (SNAPSHOT) and nexus repos (nexus port 10002) are used.
132 # The value "RELEASE" indicate that relase image tag and nexus repos (nexus port) are used
133 # Applies only to images defined in the test-env files with image names and tags defined as XXXX_RELEASE
136 #Var to indicate docker-compose version, V1 or V2
137 #V1 names replicated containers <proj-name>_<service-name>_<index>
138 #V2 names replicated containers <proj-name>-<service-name>-<index>
139 DOCKER_COMPOSE_VERION="V1"
141 # Function to indent cmd output with one space
142 indent1() { sed 's/^/ /'; }
144 # Function to indent cmd output with two spaces
145 indent2() { sed 's/^/ /'; }
147 # Set a description string for the test case
148 if [ -z "$TC_ONELINE_DESCR" ]; then
149 TC_ONELINE_DESCR="<no-description>"
150 echo "No test case description found, TC_ONELINE_DESCR should be set on in the test script , using "$TC_ONELINE_DESCR
153 # Counter for test suites
154 if [ -f .tmp_tcsuite_ctr ]; then
155 tmpval=$(< .tmp_tcsuite_ctr)
157 echo $tmpval > .tmp_tcsuite_ctr
160 # Create the logs dir if not already created in the current dir
161 if [ ! -d "logs" ]; then
166 # Create the tmp dir for temporary files that is not needed after the test
167 # hidden files for the test env is still stored in the current dir
168 # files in the ./tmp is moved to ./tmp/prev when a new test is started
169 if [ ! -d "tmp" ]; then
171 if [ $? -ne 0 ]; then
172 echo "Cannot create dir for temp files, $PWD/tmp"
179 if [ $? -ne 0 ]; then
180 echo "Cannot cd to $PWD/tmp"
185 TESTENV_TEMP_FILES=$PWD
187 if [ ! -d "prev" ]; then
189 if [ $? -ne 0 ]; then
190 echo "Cannot create dir for previous temp files, $PWD/prev"
196 TMPFILES=$(ls -A | grep -vw prev)
197 if [ ! -z "$TMPFILES" ]; then
198 cp -r $TMPFILES prev #Move all temp files to prev dir
199 if [ $? -ne 0 ]; then
200 echo "Cannot move temp files in $PWD to previous temp files in, $PWD/prev"
204 if [ $(pwd | xargs basename) == "tmp" ]; then #Check that current dir is tmp...for safety
206 rm -rf $TMPFILES # Remove all temp files
211 if [ $? -ne 0 ]; then
212 echo "Cannot cd to $curdir"
218 # Create a http message log for this testcase
219 HTTPLOG=$PWD"/.httplog_"$ATC".txt"
222 # Create a log dir for the test case
223 mkdir -p $TESTLOGS/$ATC
225 # Save create for current logs
226 mkdir -p $TESTLOGS/$ATC/previous
228 rm $TESTLOGS/$ATC/previous/*.log &> /dev/null
229 rm $TESTLOGS/$ATC/previous/*.txt &> /dev/null
230 rm $TESTLOGS/$ATC/previous/*.json &> /dev/null
232 mv $TESTLOGS/$ATC/*.log $TESTLOGS/$ATC/previous &> /dev/null
233 mv $TESTLOGS/$ATC/*.txt $TESTLOGS/$ATC/previous &> /dev/null
234 mv $TESTLOGS/$ATC/*.txt $TESTLOGS/$ATC/previous &> /dev/null
236 # Clear the log dir for the test case
237 rm $TESTLOGS/$ATC/*.log &> /dev/null
238 rm $TESTLOGS/$ATC/*.txt &> /dev/null
239 rm $TESTLOGS/$ATC/*.json &> /dev/null
241 #Create result file in the log dir
242 echo "1" > "$TESTLOGS/$ATC/.result$ATC.txt"
244 # Log all output from the test case to a TC log
245 TCLOG=$TESTLOGS/$ATC/TC.log
246 exec &> >(tee ${TCLOG})
248 #Variables for counting tests as well as passed and failed tests
255 #Var to control if current stats shall be printed
256 PRINT_CURRENT_STATS=0
258 #Var to control if container/pod runtim statistics shall be collected
259 COLLECT_RUNTIME_STATS=0
260 COLLECT_RUNTIME_STATS_PID=0
262 #Var to control if endpoint statistics shall be collected
263 COLLECT_ENDPOINT_STATS=0
265 #Var to control if namespaces shall be delete before test setup
266 DELETE_KUBE_NAMESPACES=0
268 #Var to control if containers shall be delete before test setup
271 #Var to configure kubectl from a config file.
274 #Var pointing to dir mounted to each kubernetes node (master and workers)
275 #Persistent volumes using "hostpath" are allocated beneath the point.
276 #Typically it is a dir on local host mounted to each VM running the master and worker.
277 #So the intention is make this dir available so the PODs can be restarted on any
278 #node and still access the persistent data
279 #If not set from cmd line, the path is defaults to "/tmp"
280 HOST_PATH_BASE_DIR=""
282 #File to keep deviation messages
283 DEVIATION_FILE=".tmp_deviations"
284 rm $DEVIATION_FILE &> /dev/null
286 # Trap "command not found" and make the script fail
289 if [ $? -eq 127 ]; then
290 echo -e $RED"Function not found, setting script to FAIL"$ERED
292 __print_current_stats
297 # Trap to kill subprocess for stats collection (if running)
299 if [ $COLLECT_RUNTIME_STATS_PID -ne 0 ]; then
300 kill $COLLECT_RUNTIME_STATS_PID
308 # Function to log the start of a test case
310 TIMESTAMP=$(date "+%Y-%m-%d %H:%M:%S")
311 echo -e $BOLD"TEST $TEST_SEQUENCE_NR (${BASH_LINENO[1]}): ${FUNCNAME[1]}" $@ $EBOLD
312 echo "TEST $TEST_SEQUENCE_NR - ${TIMESTAMP}: (${BASH_LINENO[1]}): ${FUNCNAME[1]}" $@ >> $HTTPLOG
314 ((TEST_SEQUENCE_NR++))
317 # Function to print current statistics
318 __print_current_stats() {
319 if [ $PRINT_CURRENT_STATS -ne 0 ]; then
320 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"
324 # General function to log a failed test case
325 __log_test_fail_general() {
326 echo -e $RED" FAIL."$1 $ERED
328 __print_current_stats
329 __check_stop_at_error
332 # Function to log a test case failed due to incorrect response code
333 __log_test_fail_status_code() {
334 echo -e $RED" FAIL. Exepected status "$1", got "$2 $3 $ERED
336 __print_current_stats
337 __check_stop_at_error
340 # Function to log a test case failed due to incorrect response body
341 __log_test_fail_body() {
342 echo -e $RED" FAIL, returned body not correct"$ERED
344 __print_current_stats
345 __check_stop_at_error
348 # Function to log a test case that is not supported
349 __log_test_fail_not_supported() {
350 echo -e $RED" FAIL, function not supported"$ERED
352 __print_current_stats
353 __check_stop_at_error
356 # General function to log a passed test case
358 if [ $# -gt 0 ]; then
362 echo -e $GREEN" PASS"$EGREEN
363 __print_current_stats
366 #Counter for configurations
369 # Function to log the start of a configuration setup
371 TIMESTAMP=$(date "+%Y-%m-%d %H:%M:%S")
372 echo -e $BOLD"CONF $CONF_SEQUENCE_NR (${BASH_LINENO[1]}): "${FUNCNAME[1]} $@ $EBOLD
373 echo "CONF $CONF_SEQUENCE_NR - ${TIMESTAMP}: (${BASH_LINENO[1]}): "${FUNCNAME[1]} $@ >> $HTTPLOG
374 ((CONF_SEQUENCE_NR++))
377 # Function to log a failed configuration setup
378 __log_conf_fail_general() {
379 echo -e $RED" FAIL."$1 $ERED
381 __print_current_stats
382 __check_stop_at_error
385 # Function to log a failed configuration setup due to incorrect response code
386 __log_conf_fail_status_code() {
387 echo -e $RED" FAIL. Exepected status "$1", got "$2 $3 $ERED
389 __print_current_stats
390 __check_stop_at_error
393 # Function to log a failed configuration setup due to incorrect response body
394 __log_conf_fail_body() {
395 echo -e $RED" FAIL, returned body not correct"$ERED
397 __print_current_stats
398 __check_stop_at_error
401 # Function to log a configuration that is not supported
402 __log_conf_fail_not_supported() {
403 echo -e $RED" FAIL, function not supported"$ERED$@
405 __print_current_stats
406 __check_stop_at_error
409 # Function to log a passed configuration setup
411 if [ $# -gt 0 ]; then
414 echo -e $GREEN" OK"$EGREEN
415 __print_current_stats
418 # Function to collect stats on endpoints
419 # args: <app-id> <end-point-no> <http-operation> <end-point-url> <http-status> [<count>]
420 __collect_endpoint_stats() {
421 if [ $COLLECT_ENDPOINT_STATS -eq 0 ]; then
425 if [ $# -gt 5 ]; then
428 ENDPOINT_STAT_FILE=$TESTLOGS/$ATC/endpoint_$ATC_$1_$2".log"
431 if [ -f $ENDPOINT_STAT_FILE ]; then
432 ENDPOINT_VAL=$(< $ENDPOINT_STAT_FILE)
433 ENDPOINT_POS=$(echo $ENDPOINT_VAL | cut -f4 -d ' ' | cut -f1 -d '/')
434 ENDPOINT_NEG=$(echo $ENDPOINT_VAL | cut -f5 -d ' ' | cut -f1 -d '/')
437 if [ $5 -ge 200 ] && [ $5 -lt 300 ]; then
438 let ENDPOINT_POS=ENDPOINT_POS+$ENDPOINT_COUNT
440 let ENDPOINT_NEG=ENDPOINT_NEG+$ENDPOINT_COUNT
443 printf '%-2s %-10s %-45s %-16s %-16s' "#" "$3" "$4" "$ENDPOINT_POS/$ENDPOINT_POS" "$ENDPOINT_NEG/$ENDPOINT_NEG" > $ENDPOINT_STAT_FILE
446 # Function to collect stats on endpoints
447 # args: <app-id> <image-info>
448 __collect_endpoint_stats_image_info() {
449 if [ $COLLECT_ENDPOINT_STATS -eq 0 ]; then
452 ENDPOINT_STAT_FILE=$TESTLOGS/$ATC/imageinfo_$ATC_$1".log"
453 echo $POLICY_AGENT_IMAGE > $ENDPOINT_STAT_FILE
456 #Var for measuring execution time
457 TCTEST_START=$SECONDS
459 #Vars to hold the start time and timer text for a custom timer
460 TC_TIMER_STARTTIME=""
461 TC_TIMER_TIMER_TEXT=""
462 TC_TIMER_CURRENT_FAILS="" # Then numer of failed test when timer starts.
463 # Compared with the current number of fails at timer stop
464 # to judge the measurement reliability
466 #File to save timer measurement results
467 TIMER_MEASUREMENTS=".timer_measurement.txt"
468 echo -e "Activity \t Duration \t Info" > $TIMER_MEASUREMENTS
470 # If this is set, some images (controlled by the parameter repo-policy) will be re-tagged and pushed to this repo before any
472 IMAGE_REPO_POLICY="local"
475 echo "-------------------------------------------------------------------------------------------------"
476 echo "----------------------------------- Test case: "$ATC
477 echo "----------------------------------- Started: "$(date)
478 echo "-------------------------------------------------------------------------------------------------"
479 echo "-- Description: "$TC_ONELINE_DESCR
480 echo "-------------------------------------------------------------------------------------------------"
481 echo "----------------------------------- Test case setup -----------------------------------"
483 echo "Setting AUTOTEST_HOME="$AUTOTEST_HOME
487 if [ $# -lt 1 ]; then
490 if [ $paramerror -eq 0 ]; then
491 if [ "$1" != "remote" ] && [ "$1" != "remote-remove" ]; then
493 if [ -z "$paramerror_str" ]; then
494 paramerror_str="First arg shall be 'remote' or 'remote-remove'"
500 if [ $paramerror -eq 0 ]; then
501 if [ "$1" != "docker" ] && [ "$1" != "kube" ]; then
503 if [ -z "$paramerror_str" ]; then
504 paramerror_str="Second arg shall be 'docker' or 'kube'"
507 if [ $1 == "docker" ]; then
509 echo "Setting RUNMODE=DOCKER"
511 if [ $1 == "kube" ]; then
513 echo "Setting RUNMODE=KUBE"
519 while [ $paramerror -eq 0 ] && [ $foundparm -eq 0 ]; do
521 if [ $paramerror -eq 0 ]; then
522 if [ "$1" == "release" ]; then
523 IMAGE_CATEGORY="RELEASE"
524 echo "Option set - Release image tags used for applicable images "
529 if [ $paramerror -eq 0 ]; then
530 if [ "$1" == "auto-clean" ]; then
532 echo "Option set - Auto clean at end of test script"
537 if [ $paramerror -eq 0 ]; then
538 if [ "$1" == "--stop-at-error" ]; then
540 echo "Option set - Stop at first error"
545 if [ $paramerror -eq 0 ]; then
546 if [ "$1" == "--ricsim-prefix" ]; then
548 TMP_RIC_SIM_PREFIX=$1 #RIC_SIM_PREFIX need to be updated after sourcing of the env file
551 if [ -z "$paramerror_str" ]; then
552 paramerror_str="No prefix found for flag: '--ricsim-prefix'"
555 echo "Option set - Overriding RIC_SIM_PREFIX with: "$1
561 if [ $paramerror -eq 0 ]; then
562 if [ "$1" == "--env-file" ]; then
567 if [ -z "$paramerror_str" ]; then
568 paramerror_str="No env file found for flag: '--env-file'"
571 echo "Option set - Reading test env from: "$1
577 if [ $paramerror -eq 0 ]; then
578 if [ "$1" == "--use-local-image" ]; then
581 while [ $# -gt 0 ] && [[ "$1" != "--"* ]]; do
582 USE_LOCAL_IMAGES=$USE_LOCAL_IMAGES" "$1
583 if [[ "$AVAILABLE_IMAGES_OVERRIDE" != *"$1"* ]]; then
585 if [ -z "$paramerror_str" ]; then
586 paramerror_str="App name $1 is not available for local override for flag: '--use-local-image'"
592 if [ -z "$USE_LOCAL_IMAGES" ]; then
594 if [ -z "$paramerror_str" ]; then
595 paramerror_str="No app name found for flag: '--use-local-image'"
598 echo "Option set - Overriding with local images for app(s):"$USE_LOCAL_IMAGES
602 if [ $paramerror -eq 0 ]; then
603 if [ "$1" == "--use-snapshot-image" ]; then
604 USE_SNAPSHOT_IMAGES=""
606 while [ $# -gt 0 ] && [[ "$1" != "--"* ]]; do
607 USE_SNAPSHOT_IMAGES=$USE_SNAPSHOT_IMAGES" "$1
608 if [[ "$AVAILABLE_IMAGES_OVERRIDE" != *"$1"* ]]; then
610 if [ -z "$paramerror_str" ]; then
611 paramerror_str="App name $1 is not available for snapshot override for flag: '--use-snapshot-image'"
617 if [ -z "$USE_SNAPSHOT_IMAGES" ]; then
619 if [ -z "$paramerror_str" ]; then
620 paramerror_str="No app name found for flag: '--use-snapshot-image'"
623 echo "Option set - Overriding with snapshot images for app(s):"$USE_SNAPSHOT_IMAGES
627 if [ $paramerror -eq 0 ]; then
628 if [ "$1" == "--use-staging-image" ]; then
629 USE_STAGING_IMAGES=""
631 while [ $# -gt 0 ] && [[ "$1" != "--"* ]]; do
632 USE_STAGING_IMAGES=$USE_STAGING_IMAGES" "$1
633 if [[ "$AVAILABLE_IMAGES_OVERRIDE" != *"$1"* ]]; then
635 if [ -z "$paramerror_str" ]; then
636 paramerror_str="App name $1 is not available for staging override for flag: '--use-staging-image'"
642 if [ -z "$USE_STAGING_IMAGES" ]; then
644 if [ -z "$paramerror_str" ]; then
645 paramerror_str="No app name found for flag: '--use-staging-image'"
648 echo "Option set - Overriding with staging images for app(s):"$USE_STAGING_IMAGES
652 if [ $paramerror -eq 0 ]; then
653 if [ "$1" == "--use-release-image" ]; then
654 USE_RELEASE_IMAGES=""
656 while [ $# -gt 0 ] && [[ "$1" != "--"* ]]; do
657 USE_RELEASE_IMAGES=$USE_RELEASE_IMAGES" "$1
658 if [[ "$AVAILABLE_IMAGES_OVERRIDE" != *"$1"* ]]; then
660 if [ -z "$paramerror_str" ]; then
661 paramerror_str="App name $1 is not available for release override for flag: '--use-release-image'"
667 if [ -z "$USE_RELEASE_IMAGES" ]; then
669 if [ -z "$paramerror_str" ]; then
670 paramerror_str="No app name found for flag: '--use-release-image'"
673 echo "Option set - Overriding with release images for app(s):"$USE_RELEASE_IMAGES
677 if [ $paramerror -eq 0 ]; then
678 if [ "$1" == "--image-repo" ]; then
683 if [ -z "$paramerror_str" ]; then
684 paramerror_str="No image repo url found for : '--image-repo'"
687 echo "Option set - Image repo url: "$1
693 if [ $paramerror -eq 0 ]; then
694 if [ "$1" == "--repo-policy" ]; then
699 if [ -z "$paramerror_str" ]; then
700 paramerror_str="No policy found for : '--repo-policy'"
703 if [ "$1" == "local" ] || [ "$1" == "remote" ]; then
704 echo "Option set - Image repo policy: "$1
709 if [ -z "$paramerror_str" ]; then
710 paramerror_str="Repo policy shall be 'local' or 'remote'"
716 if [ $paramerror -eq 0 ]; then
717 if [ "$1" == "--cluster-timeout" ]; then
722 if [ -z "$paramerror_str" ]; then
723 paramerror_str="No timeout value found for : '--cluster-timeout'"
726 #Check if positive int
727 case ${CLUSTER_TIME_OUT#[+]} in
730 if [ -z "$paramerror_str" ]; then
731 paramerror_str="Value for '--cluster-timeout' not an int : "$CLUSTER_TIME_OUT
736 echo "Option set - Cluster timeout: "$1
742 if [ $paramerror -eq 0 ]; then
743 if [ "$1" == "--override" ]; then
745 TEST_ENV_VAR_FILE_OVERRIDE=$1
748 if [ -z "$paramerror_str" ]; then
749 paramerror_str="No env file found for flag: '--override'"
752 if [ ! -f $TEST_ENV_VAR_FILE_OVERRIDE ]; then
754 if [ -z "$paramerror_str" ]; then
755 paramerror_str="File for '--override' does not exist : "$TEST_ENV_VAR_FILE_OVERRIDE
758 echo "Option set - Override env from: "$1
764 if [ $paramerror -eq 0 ]; then
765 if [ "$1" == "--pre-clean" ]; then
767 echo "Option set - Pre-clean of kube/docker resouces"
772 if [ $paramerror -eq 0 ]; then
773 if [ "$1" == "--print-stats" ]; then
774 PRINT_CURRENT_STATS=1
775 echo "Option set - Print stats after every test-case and config"
780 if [ $paramerror -eq 0 ]; then
781 if [ "$1" == "--gen-stats" ]; then
782 COLLECT_RUNTIME_STATS=1
783 echo "Option set - Collect runtime statistics"
788 if [ $paramerror -eq 0 ]; then
789 if [ "$1" == "--delete-namespaces" ]; then
790 if [ $RUNMODE == "DOCKER" ]; then
791 DELETE_KUBE_NAMESPACES=0
792 echo "Option ignored - Delete namespaces (ignored when running docker)"
794 if [ -z "KUBE_PRESTARTED_IMAGES" ]; then
795 DELETE_KUBE_NAMESPACES=0
796 echo "Option ignored - Delete namespaces (ignored when using prestarted apps)"
798 DELETE_KUBE_NAMESPACES=1
799 echo "Option set - Delete namespaces"
806 if [ $paramerror -eq 0 ]; then
807 if [ "$1" == "--delete-containers" ]; then
808 if [ $RUNMODE == "DOCKER" ]; then
810 echo "Option set - Delete containers started by previous test(s)"
812 echo "Option ignored - Delete containers (ignored when running kube)"
818 if [ $paramerror -eq 0 ]; then
819 if [ "$1" == "--endpoint-stats" ]; then
820 COLLECT_ENDPOINT_STATS=1
821 echo "Option set - Collect endpoint statistics"
826 if [ $paramerror -eq 0 ]; then
827 if [ "$1" == "--kubeconfig" ]; then
831 if [ -z "$paramerror_str" ]; then
832 paramerror_str="No path found for : '--kubeconfig'"
836 KUBECONF="--kubeconfig $1"
837 echo "Option set - Kubeconfig path: "$1
842 if [ -z "$paramerror_str" ]; then
843 paramerror_str="File $1 for --kubeconfig not found"
849 if [ $paramerror -eq 0 ]; then
850 if [ "$1" == "--host-path-dir" ]; then
854 if [ -z "$paramerror_str" ]; then
855 paramerror_str="No path found for : '--host-path-dir'"
858 HOST_PATH_BASE_DIR=$1
868 if [ $paramerror -eq 0 ] && [ $# -gt 0 ]; then
870 if [ -z "$paramerror_str" ]; then
871 paramerror_str="Unknown parameter(s): "$@
875 if [ $paramerror -eq 1 ]; then
876 echo -e $RED"Incorrect arg list: "$paramerror_str$ERED
881 # sourcing the selected env variables for the test case
882 if [ -f "$TEST_ENV_VAR_FILE" ]; then
883 echo -e $BOLD"Sourcing env vars from: "$TEST_ENV_VAR_FILE$EBOLD
885 if [ ! -z "$TEST_ENV_VAR_FILE_OVERRIDE" ]; then
886 echo -e $BOLD"Sourcing override env vars from: "$TEST_ENV_VAR_FILE_OVERRIDE$EBOLD
887 . $TEST_ENV_VAR_FILE_OVERRIDE
890 if [ -z "$TEST_ENV_PROFILE" ] || [ -z "$SUPPORTED_PROFILES" ]; then
891 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
894 for prof in $SUPPORTED_PROFILES; do
895 if [ "$TEST_ENV_PROFILE" == "$prof" ]; then
896 echo -e $GREEN"Test case supports the selected test env file"$EGREEN
900 if [ $found_profile -ne 1 ]; then
901 echo -e $RED"Test case does not support the selected test env file"$ERED
902 echo "Profile: "$TEST_ENV_PROFILE" Supported profiles: "$SUPPORTED_PROFILES
903 echo -e $RED"Exiting...."$ERED
908 echo -e $RED"Selected env var file does not exist: "$TEST_ENV_VAR_FILE$ERED
909 echo " Select one of following env var file matching the intended target of the test"
910 echo " Restart the test using the flag '--env-file <path-to-env-file>"
911 ls $AUTOTEST_HOME/../common/test_env* | indent1
915 #This var need be preserved from the command line option, if set, when env var is sourced.
916 if [ ! -z "$TMP_RIC_SIM_PREFIX" ]; then
917 RIC_SIM_PREFIX=$TMP_RIC_SIM_PREFIX
920 if [ -z "$PROJECT_IMAGES_APP_NAMES" ]; then
921 echo -e $RED"Var PROJECT_IMAGES_APP_NAMES must be defined in: "$TEST_ENV_VAR_FILE $ERED
925 if [[ $SUPPORTED_RUNMODES != *"$RUNMODE"* ]]; then
926 echo -e $RED"This test script does not support RUNMODE $RUNMODE"$ERED
927 echo "Supported RUNMODEs: "$SUPPORTED_RUNMODES
931 # Choose list of included apps depending on run-mode
932 if [ $RUNMODE == "KUBE" ]; then
933 INCLUDED_IMAGES=$KUBE_INCLUDED_IMAGES
935 INCLUDED_IMAGES=$DOCKER_INCLUDED_IMAGES
939 # auto adding system apps
941 echo -e $BOLD"Auto adding system apps"$EBOLD
942 if [ $RUNMODE == "KUBE" ]; then
943 INCLUDED_IMAGES=$INCLUDED_IMAGES" "$TESTENV_KUBE_SYSTEM_APPS
944 TMP_APPS=$TESTENV_KUBE_SYSTEM_APPS
946 INCLUDED_IMAGES=$INCLUDED_IMAGES" "$TESTENV_DOCKER_SYSTEM_APPS
947 TMP_APPS=$TESTENV_DOCKER_SYSTEM_APPS
949 if [ ! -z "$TMP_APPS" ]; then
950 for iapp in "$TMP_APPS"; do
951 file_pointer=$(echo $iapp | tr '[:upper:]' '[:lower:]')
952 file_pointer="../common/"$file_pointer"_api_functions.sh"
954 while [ ${#padded_iapp} -lt 16 ]; do
955 padded_iapp=$padded_iapp" "
957 echo " Auto-adding system app $padded_iapp Sourcing $file_pointer"
959 if [ $? -ne 0 ]; then
960 echo " Include file $file_pointer contain errors. Exiting..."
963 __added_apps=" $iapp "$__added_apps
969 if [ $RUNMODE == "KUBE" ]; then
970 TMP_APPS=$INCLUDED_IMAGES" "$KUBE_PRESTARTED_IMAGES
972 TMP_APPS=$INCLUDED_IMAGES
975 echo -e $BOLD"Auto adding included apps"$EBOLD
976 for iapp in $TMP_APPS; do
977 if [[ "$__added_apps" != *"$iapp"* ]]; then
978 file_pointer=$(echo $iapp | tr '[:upper:]' '[:lower:]')
979 file_pointer="../common/"$file_pointer"_api_functions.sh"
981 while [ ${#padded_iapp} -lt 16 ]; do
982 padded_iapp=$padded_iapp" "
984 echo " Auto-adding included app $padded_iapp Sourcing $file_pointer"
985 if [ ! -f "$file_pointer" ]; then
986 echo " Include file $file_pointer for app $iapp does not exist"
990 if [ $? -ne 0 ]; then
991 echo " Include file $file_pointer contain errors. Exiting..."
998 echo -e $BOLD"Test environment info"$EBOLD
1000 # Check needed installed sw
1003 if [ $? -ne 0 ] || [ -z "$tmp" ]; then
1004 echo -e $RED"bash is required to run the test environment, pls install"$ERED
1007 echo " bash is installed and using version:"
1008 echo "$(bash --version)" | indent2
1010 tmp=$(which python3)
1011 if [ $? -ne 0 ] || [ -z "$tmp" ]; then
1012 echo -e $RED"python3 is required to run the test environment, pls install"$ERED
1015 echo " python3 is installed and using version: $(python3 --version)"
1018 if [ $? -ne 0 ] || [ -z "$tmp" ]; then
1019 echo -e $RED"docker is required to run the test environment, pls install"$ERED
1022 echo " docker is installed and using versions:"
1023 echo " $(docker version --format 'Client version {{.Client.Version}} Server version {{.Server.Version}}')"
1025 tmp=$(which docker-compose)
1026 if [ $? -ne 0 ] || [ -z "$tmp" ]; then
1027 if [ $RUNMODE == "DOCKER" ]; then
1028 echo -e $RED"docker-compose is required to run the test environment, pls install"$ERED
1032 tmp=$(docker-compose version --short)
1033 echo " docker-compose installed and using version $tmp"
1034 if [[ "$tmp" == *'v2'* ]]; then
1035 DOCKER_COMPOSE_VERION="V2"
1038 tmp=$(which kubectl)
1039 if [ $? -ne 0 ] || [ -z tmp ]; then
1040 if [ $RUNMODE == "KUBE" ]; then
1041 echo -e $RED"kubectl is required to run the test environment in kubernetes mode, pls install"$ERED
1045 if [ $RUNMODE == "KUBE" ]; then
1046 echo " kubectl is installed and using versions:"
1047 echo $(kubectl $KUBECONF version --short=true) | indent2
1048 res=$(kubectl $KUBECONF cluster-info 2>&1)
1049 if [ $? -ne 0 ]; then
1050 echo -e "$BOLD$RED############################################# $ERED$EBOLD"
1051 echo -e $BOLD$RED"Command 'kubectl '$KUBECONF' cluster-info' returned error $ERED$EBOLD"
1052 echo -e "$BOLD$RED############################################# $ERED$EBOLD"
1054 echo "kubectl response:"
1057 echo "This script may have been started with user with no permission to run kubectl"
1058 echo "Try running with 'sudo', set env KUBECONFIG or set '--kubeconfig' parameter"
1059 echo "Do either 1, 2 or 3 "
1062 echo "Run with sudo"
1063 echo -e $BOLD"sudo <test-script-and-parameters>"$EBOLD
1066 echo "Export KUBECONFIG and pass env to sudo - (replace user)"
1067 echo -e $BOLD"export KUBECONFIG='/home/<user>/.kube/config'"$EBOLD
1068 echo -e $BOLD"sudo -E <test-script-and-parameters>"$EBOLD
1071 echo "Set KUBECONFIG via script parameter"
1072 echo -e $BOLD"sudo ... --kubeconfig /home/<user>/.kube/<config-file> ...."$EBOLD
1073 echo "The config file need to downloaded from the cluster"
1077 echo " Node(s) and container runtime config"
1078 kubectl $KUBECONF get nodes -o wide | indent2
1080 if [ -z "$HOST_PATH_BASE_DIR" ]; then
1081 HOST_PATH_BASE_DIR="/tmp"
1082 echo " Persistent volumes will be mounted to $HOST_PATH_BASE_DIR on applicable node"
1083 echo " No guarantee that persistent volume data is available on all nodes in the cluster"
1085 echo "Persistent volumes will be mounted to base dir: $HOST_PATH_BASE_DIR"
1086 echo "Assuming this dir is mounted from each node to a dir on the localhost or other"
1087 echo "file system available to all nodes"
1094 echo -e $BOLD"Checking configured image setting for this test case"$EBOLD
1096 #Temp var to check for image variable name errors
1098 #Create a file with image info for later printing as a table
1099 image_list_file="./tmp/.image-list"
1100 echo -e "Application\tApp short name\tImage\ttag\ttag-switch" > $image_list_file
1102 # Check if image env var is set and if so export the env var with image to use (used by docker compose files)
1103 # arg: <app-short-name> <target-variable-name> <image-variable-name> <image-tag-variable-name> <tag-suffix> <image name>
1104 __check_and_create_image_var() {
1106 if [ $# -ne 6 ]; then
1107 echo "Expected arg: <app-short-name> <target-variable-name> <image-variable-name> <image-tag-variable-name> <tag-suffix> <image name>"
1112 __check_included_image $1
1113 if [ $? -ne 0 ]; then
1114 echo -e "$6\t$1\t<image-excluded>\t<no-tag>" >> $image_list_file
1115 # Image is excluded since the corresponding app is not used in this test
1118 tmp=${6}"\t"${1}"\t"
1119 #Create var from the input var names
1124 optional_image_repo_target=""
1126 if [ -z $image ]; then
1127 __check_ignore_image $1
1128 if [ $? -eq 0 ]; then
1130 if [ -z "$6" ]; then
1131 app_ds="<app ignored>"
1133 echo -e "$app_ds\t$1\t<image-ignored>\t<no-tag>" >> $image_list_file
1134 # Image is ignored since the corresponding the images is not set in the env file
1135 __remove_included_image $1 # Remove the image from the list of included images
1138 echo -e $RED"\$"$3" not set in $TEST_ENV_VAR_FILE"$ERED
1141 tmp=$tmp"<no-image>\t"
1144 optional_image_repo_target=$image
1146 #Add repo depending on image type
1147 if [ "$5" == "REMOTE_RELEASE" ]; then
1148 image=$NEXUS_RELEASE_REPO$image
1150 if [ "$5" == "REMOTE" ]; then
1151 image=$NEXUS_STAGING_REPO$image
1153 if [ "$5" == "REMOTE_SNAPSHOT" ]; then
1154 image=$NEXUS_SNAPSHOT_REPO$image
1156 if [ "$5" == "REMOTE_PROXY" ]; then
1157 image=$NEXUS_PROXY_REPO$image
1159 if [ "$5" == "REMOTE_RELEASE_ONAP" ]; then
1160 image=$NEXUS_RELEASE_REPO_ONAP$image
1162 if [ "$5" == "REMOTE_RELEASE_ORAN" ]; then
1163 image=$NEXUS_RELEASE_REPO_ORAN$image
1165 #No nexus repo added for local images, tag: LOCAL
1168 if [ -z $tag ]; then
1169 echo -e $RED"\$"$tmptag" not set in $TEST_ENV_VAR_FILE"$ERED
1172 tmp=$tmp"<no-tag>\t"
1177 echo -e "$tmp" >> $image_list_file
1179 export "${2}"=$image":"$tag #Note, this var may be set to the value of the target value below in __check_and_pull_image
1181 remote_or_local_push=false
1182 if [ ! -z "$IMAGE_REPO_ADR" ] && [[ $5 != *"PROXY"* ]]; then
1183 if [ $5 == "LOCAL" ]; then
1184 remote_or_local_push=true
1186 if [[ $5 == *"REMOTE"* ]]; then
1187 if [ "$IMAGE_REPO_POLICY" == "remote" ]; then
1188 remote_or_local_push=true
1192 if $remote_or_local_push; then # Only re-tag and push images according to policy, if repo is given
1193 export "${2}_SOURCE"=$image":"$tag #Var to keep the actual source image
1194 if [[ $optional_image_repo_target == *"/"* ]]; then # Replace all / with _ for images to push to external repo
1195 optional_image_repo_target_tmp=${optional_image_repo_target//\//_}
1196 optional_image_repo_target=$optional_image_repo_target_tmp
1198 export "${2}_TARGET"=$IMAGE_REPO_ADR"/"$optional_image_repo_target":"$tag #Create image + tag for optional image repo - pushed later if needed
1200 export "${2}_SOURCE"=""
1201 export "${2}_TARGET"=""
1205 # Check if app uses image included in this test run
1206 # Returns 0 if image is included, 1 if not
1207 __check_included_image() {
1208 for im in $INCLUDED_IMAGES; do
1209 if [ "$1" == "$im" ]; then
1216 # Check if app uses a project image
1217 # Returns 0 if image is included, 1 if not
1218 __check_project_image() {
1219 for im in $PROJECT_IMAGES; do
1220 if [ "$1" == "$im" ]; then
1227 # Check if app uses image built by the test script
1228 # Returns 0 if image is included, 1 if not
1229 __check_image_local_build() {
1230 for im in $LOCAL_IMAGE_BUILD; do
1231 if [ "$1" == "$im" ]; then
1238 # Check if app image is conditionally ignored in this test run
1239 # Returns 0 if image is conditionally ignored, 1 if not
1240 __check_ignore_image() {
1241 for im in $CONDITIONALLY_IGNORED_IMAGES; do
1242 if [ "$1" == "$im" ]; then
1249 # Removed image from included list of included images
1250 # Used when an image is marked as conditionally ignored
1251 __remove_included_image() {
1253 for im in $INCLUDED_IMAGES; do
1254 if [ "$1" != "$im" ]; then
1255 tmp_img_rem_list=$tmp_img_rem_list" "$im
1258 INCLUDED_IMAGES=$tmp_img_rem_list
1262 # Check if app is included in the prestarted set of apps
1263 # Returns 0 if image is included, 1 if not
1264 __check_prestarted_image() {
1265 for im in $KUBE_PRESTARTED_IMAGES; do
1266 if [ "$1" == "$im" ]; then
1273 # Check if an app shall use a local image, based on the cmd parameters
1274 __check_image_local_override() {
1275 for im in $USE_LOCAL_IMAGES; do
1276 if [ "$1" == "$im" ]; then
1283 # Check if app uses image override
1284 # Returns the image/tag suffix LOCAL for local image or REMOTE/REMOTE_RELEASE/REMOTE_SNAPSHOT for staging/release/snapshot image
1285 __check_image_override() {
1287 for im in $ORAN_IMAGES_APP_NAMES; do
1288 if [ "$1" == "$im" ]; then
1289 echo "REMOTE_RELEASE_ORAN"
1294 for im in $ONAP_IMAGES_APP_NAMES; do
1295 if [ "$1" == "$im" ]; then
1296 echo "REMOTE_RELEASE_ONAP"
1302 for im in $PROJECT_IMAGES_APP_NAMES; do
1303 if [ "$1" == "$im" ]; then
1308 if [ $found -eq 0 ]; then
1314 if [ $IMAGE_CATEGORY == "RELEASE" ]; then
1315 suffix="REMOTE_RELEASE"
1317 if [ $IMAGE_CATEGORY == "DEV" ]; then
1321 for im in $USE_STAGING_IMAGES; do
1322 if [ "$1" == "$im" ]; then
1327 for im in $USE_RELEASE_IMAGES; do
1328 if [ "$1" == "$im" ]; then
1329 suffix="REMOTE_RELEASE"
1333 for im in $USE_SNAPSHOT_IMAGES; do
1334 if [ "$1" == "$im" ]; then
1335 suffix="REMOTE_SNAPSHOT"
1339 for im in $USE_LOCAL_IMAGES; do
1340 if [ "$1" == "$im" ]; then
1346 if [ $CTR -gt 1 ]; then
1352 # Function to re-tag and image and push to another image repo
1353 __retag_and_push_image() {
1354 if [ ! -z "$IMAGE_REPO_ADR" ]; then
1355 source_image="${!1}"
1356 trg_var_name=$1_"TARGET" # This var is created in func __check_and_create_image_var
1357 target_image="${!trg_var_name}"
1359 if [ -z $target_image ]; then
1360 return 0 # Image with no target shall not be pushed
1363 echo -ne " Attempt to re-tag image to: ${BOLD}${target_image}${EBOLD}${SAMELINE}"
1364 tmp=$(docker image tag $source_image ${target_image} )
1365 if [ $? -ne 0 ]; then
1366 docker stop $tmp &> ./tmp/.dockererr
1369 echo -e " Attempt to re-tag image to: ${BOLD}${target_image}${EBOLD} - ${RED}Failed${ERED}"
1370 cat ./tmp/.dockererr
1373 echo -e " Attempt to re-tag image to: ${BOLD}${target_image}${EBOLD} - ${GREEN}OK${EGREEN}"
1375 echo -ne " Attempt to push re-tagged image: ${BOLD}${target_image}${EBOLD}${SAMELINE}"
1376 tmp=$(docker push ${target_image} )
1377 if [ $? -ne 0 ]; then
1378 docker stop $tmp &> ./tmp/.dockererr
1381 echo -e " Attempt to push re-tagged image: ${BOLD}${target_image}${EBOLD} - ${RED}Failed${ERED}"
1382 cat ./tmp/.dockererr
1385 echo -e " Attempt to push re-tagged image: ${BOLD}${target_image}${EBOLD} - ${GREEN}OK${EGREEN}"
1387 export "${1}"=$target_image
1392 #Function to check if image exist and stop+remove the container+pull new images as needed
1393 #args <script-start-arg> <descriptive-image-name> <container-base-name> <image-with-tag-var-name>
1394 __check_and_pull_image() {
1396 source_image="${!4}"
1398 echo -e " Checking $BOLD$2$EBOLD container(s) with basename: $BOLD$3$EBOLD using image: $BOLD$source_image$EBOLD"
1399 format_string="\"{{.Repository}}\\t{{.Tag}}\\t{{.CreatedSince}}\\t{{.Size}}\""
1400 tmp_im=$(docker images --format $format_string $source_image)
1402 if [ $1 == "local" ]; then
1403 if [ -z "$tmp_im" ]; then
1404 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
1408 echo -e " "$2" (local image): \033[1m"$source_image"\033[0m "$GREEN"OK"$EGREEN
1410 elif [ $1 == "remote" ] || [ $1 == "remote-remove" ]; then
1411 if [ $1 == "remote-remove" ]; then
1412 if [ $RUNMODE == "DOCKER" ]; then
1413 echo -ne " Attempt to stop and remove container(s), if running - ${SAMELINE}"
1414 tmp=$(docker ps -aq --filter name=${3} --filter network=${DOCKER_SIM_NWNAME})
1415 if [ $? -eq 0 ] && [ ! -z "$tmp" ]; then
1416 docker stop $tmp &> ./tmp/.dockererr
1417 if [ $? -ne 0 ]; then
1420 echo -e $RED" Container(s) could not be stopped - try manual stopping the container(s)"$ERED
1421 cat ./tmp/.dockererr
1425 echo -ne " Attempt to stop and remove container(s), if running - "$GREEN"stopped"$EGREEN"${SAMELINE}"
1426 tmp=$(docker ps -aq --filter name=${3} --filter network=${DOCKER_SIM_NWNAME}) &> /dev/null
1427 if [ $? -eq 0 ] && [ ! -z "$tmp" ]; then
1428 docker rm $tmp &> ./tmp/.dockererr
1429 if [ $? -ne 0 ]; then
1432 echo -e $RED" Container(s) could not be removed - try manual removal of the container(s)"$ERED
1433 cat ./tmp/.dockererr
1437 echo -e " Attempt to stop and remove container(s), if running - "$GREEN"stopped removed"$EGREEN
1443 if [ -z "$tmp_im" ]; then
1444 echo -ne " Pulling image${SAMELINE}"
1445 out=$(docker pull $source_image)
1446 if [ $? -ne 0 ]; then
1448 echo -e " Pulling image -$RED could not be pulled"$ERED
1450 echo $out > ./tmp/.dockererr
1454 echo $out > ./tmp/.dockererr
1455 if [[ $out == *"up to date"* ]]; then
1456 echo -e " Pulling image -$GREEN Image is up to date $EGREEN"
1457 elif [[ $out == *"Downloaded newer image"* ]]; then
1458 echo -e " Pulling image -$GREEN Newer image pulled $EGREEN"
1460 echo -e " Pulling image -$GREEN Pulled $EGREEN"
1463 echo -e " Pulling image -$GREEN OK $EGREEN(exists in local repository)"
1467 __retag_and_push_image $4
1472 setup_testenvironment() {
1473 # Check that image env setting are available
1476 # Image var setup for all project images included in the test
1477 for imagename in $APP_SHORT_NAMES; do
1478 __check_included_image $imagename
1480 __check_project_image $imagename
1482 if [ $incl -eq 0 ]; then
1483 if [ $proj -eq 0 ]; then
1484 IMAGE_SUFFIX=$(__check_image_override $imagename)
1485 if [ $? -ne 0 ]; then
1486 echo -e $RED"Image setting from cmd line not consistent for $imagename."$ERED
1492 # A function name is created from the app short name
1493 # for example app short name 'ICS' -> produce the function
1494 # name __ICS_imagesetup
1495 # This function is called and is expected to exist in the imported
1496 # file for the ics test functions
1497 # The resulting function impl will call '__check_and_create_image_var' function
1498 # with appropriate parameters
1499 # If the image suffix is none, then the component decides the suffix
1500 function_pointer="__"$imagename"_imagesetup"
1501 $function_pointer $IMAGE_SUFFIX
1503 function_pointer="__"$imagename"_test_requirements"
1508 #Errors in image setting - exit
1509 if [ $IMAGE_ERR -ne 0 ]; then
1513 #Print a tables of the image settings
1514 echo -e $BOLD"Images configured for start arg: "$START_ARG $EBOLD
1515 column -t -s $'\t' $image_list_file | indent1
1519 #Set the SIM_GROUP var
1520 echo -e $BOLD"Setting var to main dir of all container/simulator scripts"$EBOLD
1521 if [ -z "$SIM_GROUP" ]; then
1522 SIM_GROUP=$AUTOTEST_HOME/../simulator-group
1523 if [ ! -d $SIM_GROUP ]; then
1524 echo "Trying to set env var SIM_GROUP to dir 'simulator-group' in the nontrtric repo, but failed."
1525 echo -e $RED"Please set the SIM_GROUP manually in the applicable $TEST_ENV_VAR_FILE"$ERED
1528 echo " SIM_GROUP auto set to: " $SIM_GROUP
1530 elif [ $SIM_GROUP = *simulator_group ]; then
1531 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
1534 echo " SIM_GROUP env var already set to: " $SIM_GROUP
1539 #Temp var to check for image pull errors
1543 echo -e $BOLD"Deleting namespaces"$EBOLD
1546 if [ "$DELETE_KUBE_NAMESPACES" -eq 1 ]; then
1547 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
1548 if [ $? -ne 0 ]; then
1549 echo " Cannot get list of namespaces...ignoring delete"
1551 for test_env_ns in $test_env_namespaces; do
1552 __kube_delete_namespace $test_env_ns
1556 echo " Namespace delete option not set or ignored"
1561 echo -e $BOLD"Deleting containers"$EBOLD
1563 if [ "$DELETE_CONTAINERS" -eq 1 ]; then
1564 echo " Stopping containers label 'nrttest_app'..."
1565 docker stop $(docker ps -qa --filter "label=nrttest_app") 2> /dev/null
1566 echo " Removing stopped containers..."
1567 docker rm $(docker ps -qa --filter "label=nrttest_app") 2> /dev/null
1569 echo " Contatiner delete option not set or ignored"
1573 # The following sequence pull the configured images
1574 echo -e $BOLD"Pulling configured images, if needed"$EBOLD
1575 if [ ! -z "$IMAGE_REPO_ADR" ] && [ $IMAGE_REPO_POLICY == "local" ]; then
1576 echo -e $YELLOW" Excluding all remote image check/pull when running with image repo: $IMAGE_REPO_ADR and image policy $IMAGE_REPO_POLICY"$EYELLOW
1578 for imagename in $APP_SHORT_NAMES; do
1579 __check_included_image $imagename
1581 __check_project_image $imagename
1583 if [ $incl -eq 0 ]; then
1584 if [ $proj -eq 0 ]; then
1585 START_ARG_MOD=$START_ARG
1586 __check_image_local_override $imagename
1587 if [ $? -eq 1 ]; then
1588 START_ARG_MOD="local"
1591 START_ARG_MOD=$START_ARG
1593 __check_image_local_build $imagename
1594 #No pull of images built locally
1595 if [ $? -ne 0 ]; then
1596 # A function name is created from the app short name
1597 # for example app short name 'HTTPPROXY' -> produce the function
1598 # name __HTTPPROXY_imagesetup
1599 # This function is called and is expected to exist in the imported
1600 # file for the httpproxy test functions
1601 # The resulting function impl will call '__check_and_pull_image' function
1602 # with appropriate parameters
1603 function_pointer="__"$imagename"_imagepull"
1604 $function_pointer $START_ARG_MOD $START_ARG
1607 echo -e $YELLOW" Excluding $imagename image from image check/pull"$EYELLOW
1612 #Errors in image setting - exit
1613 if [ $IMAGE_ERR -ne 0 ]; then
1615 echo "#################################################################################################"
1616 echo -e $RED"One or more images could not be pulled or containers using the images could not be stopped/removed"$ERED
1617 echo -e $RED"Or local image, overriding remote image, does not exist"$ERED
1618 if [ $IMAGE_CATEGORY == "DEV" ]; then
1620 echo -e $RED"Note that SNAPSHOT and staging images may be purged from nexus after a certain period."$ERED
1621 echo -e $RED"In addition, the image may not have been updated in the current release so no SNAPSHOT or staging image exists"$ERED
1622 echo -e $RED"In these cases, switch to use a released image instead, use the flag '--use-release-image <App-short-name>'"$ERED
1623 echo -e $RED"Use the 'App-short-name' for the applicable image from the above table: 'Images configured for start arg'."$ERED
1625 echo "#################################################################################################"
1632 echo -e $BOLD"Building images needed for test"$EBOLD
1634 for imagename in $APP_SHORT_NAMES; do
1635 cd $AUTOTEST_HOME #Always reset to orig dir
1636 __check_image_local_build $imagename
1637 if [ $? -eq 0 ]; then
1638 __check_included_image $imagename
1639 if [ $? -eq 0 ]; then
1640 # A function name is created from the app short name
1641 # for example app short name 'MR' -> produce the function
1642 # name __MR_imagebuild
1643 # This function is called and is expected to exist in the imported
1644 # file for the mr test functions
1645 # The resulting function impl shall build the imagee
1646 function_pointer="__"$imagename"_imagebuild"
1650 echo -e $YELLOW" Excluding image for app $imagename from image build"$EYELLOW
1655 cd $AUTOTEST_HOME # Just to make sure...
1659 # Create a table of the images used in the script - from local repo
1660 echo -e $BOLD"Local docker registry images used in this test script"$EBOLD
1662 docker_tmp_file=./tmp/.docker-images-table
1663 format_string="{{.Repository}}\\t{{.Tag}}\\t{{.CreatedSince}}\\t{{.Size}}\\t{{.CreatedAt}}"
1664 echo -e "Application\tRepository\tTag\tCreated since\tSize\tCreated at" > $docker_tmp_file
1666 for imagename in $APP_SHORT_NAMES; do
1667 __check_included_image $imagename
1668 if [ $? -eq 0 ]; then
1669 # Only print image data if image repo is null, or if image repo is set and image is local
1671 if [ -z "$IMAGE_REPO_ADR" ]; then
1674 __check_image_local_build $imagename
1675 if [ $? -eq 0 ]; then
1679 if [ $print_image_data -eq 1 ]; then
1680 # A function name is created from the app short name
1681 # for example app short name 'MR' -> produce the function
1682 # name __MR_imagebuild
1683 # This function is called and is expected to exist in the imported
1684 # file for the mr test functions
1685 # The resulting function impl shall build the imagee
1686 function_pointer="__"$imagename"_image_data"
1687 $function_pointer "$format_string" $docker_tmp_file
1692 column -t -s $'\t' $docker_tmp_file | indent1
1696 if [ ! -z "$IMAGE_REPO_ADR" ]; then
1698 # Create a table of the images used in the script - from remote repo
1699 echo -e $BOLD"Remote repo images used in this test script"$EBOLD
1700 echo -e $YELLOW"-- Note: These image will be pulled when the container starts. Images not managed by the test engine --"$EYELLOW
1702 docker_tmp_file=./tmp/.docker-images-table
1703 format_string="{{.Repository}}\\t{{.Tag}}"
1704 echo -e "Application\tRepository\tTag" > $docker_tmp_file
1706 for imagename in $APP_SHORT_NAMES; do
1707 __check_included_image $imagename
1708 if [ $? -eq 0 ]; then
1709 # Only print image data if image repo is null, or if image repo is set and image is local
1710 __check_image_local_build $imagename
1711 if [ $? -ne 0 ]; then
1712 # A function name is created from the app short name
1713 # for example app short name 'MR' -> produce the function
1714 # name __MR_imagebuild
1715 # This function is called and is expected to exist in the imported
1716 # file for the mr test functions
1717 # The resulting function impl shall build the imagee
1718 function_pointer="__"$imagename"_image_data"
1719 $function_pointer "$format_string" $docker_tmp_file
1724 column -t -s $'\t' $docker_tmp_file | indent1
1729 if [ $RUNMODE == "KUBE" ]; then
1731 echo "================================================================================="
1732 echo "================================================================================="
1734 if [ -z "$IMAGE_REPO_ADR" ]; then
1735 echo -e $YELLOW" The image pull policy is set to 'Never' - assuming a local image repo is available for all images"$EYELLOW
1736 echo -e " This setting only works on single node clusters on the local machine"
1737 echo -e " It does not work with multi-node clusters or remote clusters. "
1738 export KUBE_IMAGE_PULL_POLICY="Never"
1740 echo -e $YELLOW" The image pull policy is set to 'Always'"$EYELLOW
1741 echo -e " This setting work on local clusters, multi-node clusters and remote cluster. "
1742 echo -e " Only locally built images are managed. Remote images are always pulled from remote repos"
1743 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"
1744 export KUBE_IMAGE_PULL_POLICY="Always"
1746 CLUSTER_IP=$(kubectl $KUBECONF config view -o jsonpath={.clusters[0].cluster.server} | awk -F[/:] '{print $4}')
1747 echo -e $YELLOW" The cluster hostname/ip is: $CLUSTER_IP"$EYELLOW
1749 echo "================================================================================="
1750 echo "================================================================================="
1754 echo -e $BOLD"======================================================="$EBOLD
1755 echo -e $BOLD"== Common test setup completed - test script begins =="$EBOLD
1756 echo -e $BOLD"======================================================="$EBOLD
1761 for imagename in $APP_SHORT_NAMES; do
1762 __check_included_image $imagename
1764 __check_prestarted_image $imagename
1766 if [ $retcode_i -eq 0 ] || [ $retcode_p -eq 0 ]; then
1767 # A function name is created from the app short name
1768 # for example app short name 'RICMSIM' -> produce the function
1769 # name __RICSIM__initial_setup
1770 # This function is called and is expected to exist in the imported
1771 # file for the ricsim test functions
1772 # The resulting function impl shall perform initial setup of port, host etc
1774 function_pointer="__"$imagename"_initial_setup"
1777 function_pointer="__"$imagename"_statisics_setup"
1778 LOG_STAT_ARGS=$LOG_STAT_ARGS" "$($function_pointer)
1782 if [ $COLLECT_RUNTIME_STATS -eq 1 ]; then
1783 ../common/genstat.sh $RUNMODE $SECONDS $TESTLOGS/$ATC/stat_data.csv $LOG_STAT_ARGS &
1784 COLLECT_RUNTIME_STATS_PID=$!
1789 # Function to print the test result, shall be the last cmd in a test script
1791 # (Function for test scripts)
1795 duration=$((TCTEST_END-TCTEST_START))
1797 echo "-------------------------------------------------------------------------------------------------"
1798 echo "------------------------------------- Test case: "$ATC
1799 echo "------------------------------------- Ended: "$(date)
1800 echo "-------------------------------------------------------------------------------------------------"
1801 echo "-- Description: "$TC_ONELINE_DESCR
1802 echo "-- Execution time: " $duration " seconds"
1803 echo "-- Used env file: "$TEST_ENV_VAR_FILE
1804 echo "-------------------------------------------------------------------------------------------------"
1805 echo "------------------------------------- RESULTS"
1809 if [ $RES_DEVIATION -gt 0 ]; then
1810 echo "Test case deviations"
1811 echo "===================================="
1815 echo "Timer measurement in the test script"
1816 echo "===================================="
1817 column -t -s $'\t' $TIMER_MEASUREMENTS
1818 if [ $RES_PASS != $RES_TEST ]; then
1819 echo -e $RED"Measurement may not be reliable when there are failed test - failures may cause long measurement values due to timeouts etc."$ERED
1823 if [ $COLLECT_RUNTIME_STATS -eq 1 ]; then
1824 echo "Runtime statistics collected in file: "$TESTLOGS/$ATC/stat_data.csv
1828 total=$((RES_PASS+RES_FAIL))
1829 if [ $RES_TEST -eq 0 ]; then
1830 echo -e "\033[1mNo tests seem to have been executed. Check the script....\033[0m"
1831 echo -e "\033[31m\033[1m ___ ___ ___ ___ ___ _____ ___ _ ___ _ _ _ ___ ___ \033[0m"
1832 echo -e "\033[31m\033[1m/ __|/ __| _ \_ _| _ \_ _| | __/_\ |_ _| | | | | | _ \ __|\033[0m"
1833 echo -e "\033[31m\033[1m\__ \ (__| /| || _/ | | | _/ _ \ | || |_| |_| | / _| \033[0m"
1834 echo -e "\033[31m\033[1m|___/\___|_|_\___|_| |_| |_/_/ \_\___|____\___/|_|_\___|\033[0m"
1835 elif [ $total != $RES_TEST ]; then
1836 echo -e "\033[1mTotal number of tests does not match the sum of passed and failed tests. Check the script....\033[0m"
1837 echo -e "\033[31m\033[1m ___ ___ ___ ___ ___ _____ ___ _ ___ _ _ _ ___ ___ \033[0m"
1838 echo -e "\033[31m\033[1m/ __|/ __| _ \_ _| _ \_ _| | __/_\ |_ _| | | | | | _ \ __|\033[0m"
1839 echo -e "\033[31m\033[1m\__ \ (__| /| || _/ | | | _/ _ \ | || |_| |_| | / _| \033[0m"
1840 echo -e "\033[31m\033[1m|___/\___|_|_\___|_| |_| |_/_/ \_\___|____\___/|_|_\___|\033[0m"
1841 elif [ $RES_CONF_FAIL -ne 0 ]; then
1842 echo -e "\033[1mOne or more configurations has failed. Check the script log....\033[0m"
1843 echo -e "\033[31m\033[1m ___ ___ ___ ___ ___ _____ ___ _ ___ _ _ _ ___ ___ \033[0m"
1844 echo -e "\033[31m\033[1m/ __|/ __| _ \_ _| _ \_ _| | __/_\ |_ _| | | | | | _ \ __|\033[0m"
1845 echo -e "\033[31m\033[1m\__ \ (__| /| || _/ | | | _/ _ \ | || |_| |_| | / _| \033[0m"
1846 echo -e "\033[31m\033[1m|___/\___|_|_\___|_| |_| |_/_/ \_\___|____\___/|_|_\___|\033[0m"
1847 elif [ $RES_PASS = $RES_TEST ]; then
1848 echo -e "All tests \033[32m\033[1mPASS\033[0m"
1849 echo -e "\033[32m\033[1m ___ _ ___ ___ \033[0m"
1850 echo -e "\033[32m\033[1m | _ \/_\ / __/ __| \033[0m"
1851 echo -e "\033[32m\033[1m | _/ _ \\__ \__ \\ \033[0m"
1852 echo -e "\033[32m\033[1m |_|/_/ \_\___/___/ \033[0m"
1855 # Update test suite counter
1856 if [ -f .tmp_tcsuite_pass_ctr ]; then
1857 tmpval=$(< .tmp_tcsuite_pass_ctr)
1859 echo $tmpval > .tmp_tcsuite_pass_ctr
1861 if [ -f .tmp_tcsuite_pass ]; then
1862 echo " - "$ATC " -- "$TC_ONELINE_DESCR" Execution time: "$duration" seconds" >> .tmp_tcsuite_pass
1864 #Create file with OK exit code
1865 echo "0" > "$AUTOTEST_HOME/.result$ATC.txt"
1866 echo "0" > "$TESTLOGS/$ATC/.result$ATC.txt"
1868 echo -e "One or more tests with status \033[31m\033[1mFAIL\033[0m "
1869 echo -e "\033[31m\033[1m ___ _ ___ _ \033[0m"
1870 echo -e "\033[31m\033[1m | __/_\ |_ _| | \033[0m"
1871 echo -e "\033[31m\033[1m | _/ _ \ | || |__ \033[0m"
1872 echo -e "\033[31m\033[1m |_/_/ \_\___|____|\033[0m"
1874 # Update test suite counter
1875 if [ -f .tmp_tcsuite_fail_ctr ]; then
1876 tmpval=$(< .tmp_tcsuite_fail_ctr)
1878 echo $tmpval > .tmp_tcsuite_fail_ctr
1880 if [ -f .tmp_tcsuite_fail ]; then
1881 echo " - "$ATC " -- "$TC_ONELINE_DESCR" Execution time: "$duration" seconds" >> .tmp_tcsuite_fail
1885 echo "++++ Number of tests: "$RES_TEST
1886 echo "++++ Number of passed tests: "$RES_PASS
1887 echo "++++ Number of failed tests: "$RES_FAIL
1889 echo "++++ Number of failed configs: "$RES_CONF_FAIL
1891 echo "++++ Number of test case deviations: "$RES_DEVIATION
1893 echo "------------------------------------- Test case complete ---------------------------------"
1894 echo "-------------------------------------------------------------------------------------------------"
1898 #####################################################################
1899 ###### Functions for start, configuring, stoping, cleaning etc ######
1900 #####################################################################
1902 # Start timer for time measurement
1903 # args: <timer message to print> - timer value and message will be printed both on screen
1904 # and in the timer measurement report - if at least one "print_timer is called"
1906 echo -e $BOLD"INFO(${BASH_LINENO[0]}): "${FUNCNAME[0]}"," $@ $EBOLD
1907 TC_TIMER_STARTTIME=$SECONDS
1908 TC_TIMER_TIMER_TEXT="${@:1}"
1909 if [ $# -ne 1 ]; then
1910 __print_err "need 1 arg, <timer message to print>" $@
1911 TC_TIMER_TIMER_TEXT=${FUNCNAME[0]}":"${BASH_LINENO[0]}
1912 echo " Assigning timer name: "$TC_TIMER_TIMER_TEXT
1914 TC_TIMER_CURRENT_FAILS=$(($RES_FAIL+$RES_CONF_FAIL))
1915 echo " Timer started: $(date)"
1918 # Print the running timer the value of the time (in seconds)
1919 # Timer value and message will be printed both on screen and in the timer measurement report
1921 echo -e $BOLD"INFO(${BASH_LINENO[0]}): "${FUNCNAME[0]}"," $TC_TIMER_TIMER_TEXT $EBOLD
1922 if [ -z "$TC_TIMER_STARTTIME" ]; then
1923 __print_err "timer not started" $@
1926 duration=$(($SECONDS-$TC_TIMER_STARTTIME))
1927 if [ $duration -eq 0 ]; then
1928 duration="<1 second"
1930 duration=$duration" seconds"
1932 echo " Timer duration :" $duration
1934 if [ $(($RES_FAIL+$RES_CONF_FAIL)) -ne $TC_TIMER_CURRENT_FAILS ]; then
1935 res="Failures occured during test - timer not reliabled"
1938 echo -e "$TC_TIMER_TIMER_TEXT \t $duration \t $res" >> $TIMER_MEASUREMENTS
1941 # Print info about a deviations from intended tests
1942 # Each deviation counted is also printed in the testreport
1943 # args <deviation message to print>
1945 echo -e $BOLD"DEVIATION(${BASH_LINENO[0]}): "${FUNCNAME[0]} $EBOLD
1946 if [ $# -lt 1 ]; then
1948 __print_err "need 1 or more args, <deviation message to print>" $@
1952 echo -e $BOLD$YELLOW" Test case deviation: ${@:1}"$EYELLOW$EBOLD
1953 echo "Line: ${BASH_LINENO[0]} - ${@:1}" >> $DEVIATION_FILE
1954 __print_current_stats
1958 # Stop at first FAIL test case and take all logs - only for debugging/trouble shooting
1959 __check_stop_at_error() {
1960 if [ $STOP_AT_ERROR -eq 1 ]; then
1961 echo -e $RED"Test script configured to stop at first FAIL, taking all logs and stops"$ERED
1962 store_logs "STOP_AT_ERROR"
1964 # Update test suite counter
1965 if [ -f .tmp_tcsuite_fail_ctr ]; then
1966 tmpval=$(< .tmp_tcsuite_fail_ctr)
1968 echo $tmpval > .tmp_tcsuite_fail_ctr
1970 if [ -f .tmp_tcsuite_fail ]; then
1971 echo " - "$ATC " -- "$TC_ONELINE_DESCR" Execution stopped due to error" >> .tmp_tcsuite_fail
1978 # Stop and remove all containers
1980 # (Not for test scripts)
1981 __clean_containers() {
1983 echo -e $BOLD"Docker clean and stopping and removing all running containers, by container name"$EBOLD
1986 running_contr_file="./tmp/running_contr.txt"
1987 > $running_contr_file
1989 # Get list of all containers started by the test script
1990 for imagename in $APP_SHORT_NAMES; do
1991 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
1993 running_contr_file_empty="No docker containers running, started by previous test execution"
1994 if [ -s $running_contr_file ]; then
1995 running_contr_file_empty=""
1998 # Kill all containers started by the test env - to speed up shut down
1999 docker kill $(docker ps -a --filter "label=nrttest_app" --format '{{.Names}}') &> /dev/null
2001 tab_heading1="App display name"
2002 tab_heading2="App short name"
2003 tab_heading3="Container name"
2005 tab_heading1_len=${#tab_heading1}
2006 tab_heading2_len=${#tab_heading2}
2007 tab_heading3_len=${#tab_heading3}
2009 #Calc field lengths of each item in the list of containers
2011 if (( $cntr % 3 == 0 ));then
2012 if [ ${#p} -gt $tab_heading1_len ]; then
2013 tab_heading1_len=${#p}
2016 if (( $cntr % 3 == 1));then
2017 if [ ${#p} -gt $tab_heading2_len ]; then
2018 tab_heading2_len=${#p}
2021 if (( $cntr % 3 == 2));then
2022 if [ ${#p} -gt $tab_heading3_len ]; then
2023 tab_heading3_len=${#p}
2027 done <$running_contr_file
2029 let tab_heading1_len=tab_heading1_len+2
2030 while (( ${#tab_heading1} < $tab_heading1_len)); do
2031 tab_heading1="$tab_heading1"" "
2034 let tab_heading2_len=tab_heading2_len+2
2035 while (( ${#tab_heading2} < $tab_heading2_len)); do
2036 tab_heading2="$tab_heading2"" "
2039 let tab_heading3_len=tab_heading3_len+2
2040 while (( ${#tab_heading3} < $tab_heading3_len)); do
2041 tab_heading3="$tab_heading3"" "
2044 if [ ! -z "$running_contr_file_empty" ]; then
2045 echo $running_contr_file_empty | indent1
2047 echo " $tab_heading1$tab_heading2$tab_heading3"" Actions"
2050 if (( $cntr % 3 == 0 ));then
2053 heading_len=$tab_heading1_len
2055 if (( $cntr % 3 == 1));then
2057 heading_len=$tab_heading2_len
2059 if (( $cntr % 3 == 2));then
2062 heading_len=$tab_heading3_len
2064 while (( ${#heading} < $heading_len)); do
2065 heading="$heading"" "
2068 if (( $cntr % 3 == 2));then
2069 echo -ne $row$SAMELINE
2070 echo -ne " $row ${GREEN}stopping...${EGREEN}${SAMELINE}"
2071 docker stop $(docker ps -qa --filter name=${contr} --filter network=$DOCKER_SIM_NWNAME) &> /dev/null
2072 echo -ne " $row ${GREEN}stopped removing...${EGREEN}${SAMELINE}"
2073 docker rm --force $(docker ps -qa --filter name=${contr} --filter network=$DOCKER_SIM_NWNAME) &> /dev/null
2074 echo -e " $row ${GREEN}stopped removed ${EGREEN}"
2077 done <$running_contr_file
2082 echo -e $BOLD" Removing docker network"$EBOLD
2083 TMP=$(docker network ls -q --filter name=$DOCKER_SIM_NWNAME)
2084 if [ "$TMP" == $DOCKER_SIM_NWNAME ]; then
2085 docker network rm $DOCKER_SIM_NWNAME | indent2
2086 if [ $? -ne 0 ]; then
2087 echo -e $RED" Cannot remove docker network. Manually remove or disconnect containers from $DOCKER_SIM_NWNAME"$ERED
2091 echo -e "$GREEN Done$EGREEN"
2093 echo -e $BOLD" Removing all unused docker neworks"$EBOLD
2094 docker network prune --force | indent2
2095 echo -e "$GREEN Done$EGREEN"
2097 echo -e $BOLD" Removing all unused docker volumes"$EBOLD
2098 docker volume prune --force | indent2
2099 echo -e "$GREEN Done$EGREEN"
2101 echo -e $BOLD" Removing all dangling/untagged docker images"$EBOLD
2102 docker rmi --force $(docker images -q -f dangling=true) &> /dev/null
2103 echo -e "$GREEN Done$EGREEN"
2106 CONTRS=$(docker ps | awk '$1 != "CONTAINER" { n++ }; END { print n+0 }')
2107 if [ $? -eq 0 ]; then
2108 if [ $CONTRS -ne 0 ]; then
2109 echo -e $RED"Containers running, may cause distubance to the test case"$ERED
2110 docker ps -a | indent1
2116 ###################################
2117 ### Functions for kube management
2118 ###################################
2120 # Get resource type for scaling
2121 # args: <resource-name> <namespace>
2122 __kube_get_resource_type() {
2123 kubectl $KUBECONF get deployment $1 -n $2 1> /dev/null 2> ./tmp/kubeerr
2124 if [ $? -eq 0 ]; then
2128 kubectl $KUBECONF get sts $1 -n $2 1> /dev/null 2> ./tmp/kubeerr
2129 if [ $? -eq 0 ]; then
2133 echo "unknown-resource-type"
2137 # Scale a kube resource to a specific count
2138 # args: <resource-type> <resource-name> <namespace> <target-count>
2139 # (Not for test scripts)
2141 echo -ne " Setting $1 $2 replicas=$4 in namespace $3"$SAMELINE
2142 kubectl $KUBECONF scale $1 $2 -n $3 --replicas=$4 1> /dev/null 2> ./tmp/kubeerr
2143 if [ $? -ne 0 ]; then
2144 echo -e " Setting $1 $2 replicas=$4 in namespace $3 $RED Failed $ERED"
2146 echo " Message: $(<./tmp/kubeerr)"
2149 echo -e " Setting $1 $2 replicas=$4 in namespace $3 $GREEN OK $EGREEN"
2154 for i in {1..500}; do
2155 count=$(kubectl $KUBECONF get $1/$2 -n $3 -o jsonpath='{.status.replicas}' 2> /dev/null)
2157 if [ -z "$count" ]; then
2158 #No value is sometimes returned for some reason, in case the resource has replica 0
2161 if [ $retcode -ne 0 ]; then
2162 echo -e "$RED Cannot fetch current replica count for $1 $2 in namespace $3 $ERED"
2167 if [ $count -ne $4 ]; then
2168 echo -ne " Waiting for $1 $2 replicas=$4 in namespace $3. Replicas=$count after $(($SECONDS-$TSTART)) seconds $SAMELINE"
2171 echo -e " Waiting for $1 $2 replicas=$4 in namespace $3. Replicas=$count after $(($SECONDS-$TSTART)) seconds"
2172 echo -e " Replicas=$4 after $(($SECONDS-$TSTART)) seconds $GREEN OK $EGREEN"
2178 echo -e "$RED Replica count did not reach target replicas=$4. Failed with replicas=$count $ERED"
2183 # Scale all kube resource sets to 0 in a namespace for resources having a certain lable and label-id
2184 # This function does not wait for the resource to reach 0
2185 # args: <namespace> <label-name> <label-id>
2186 # (Not for test scripts)
2187 __kube_scale_all_resources() {
2191 resources="deployment replicaset statefulset"
2192 for restype in $resources; do
2193 result=$(kubectl $KUBECONF get $restype -n $namespace -o jsonpath='{.items[?(@.metadata.labels.'$labelname'=="'$labelid'")].metadata.name}')
2194 if [ $? -eq 0 ] && [ ! -z "$result" ]; then
2195 for resid in $result; do
2196 echo -ne " Ordered caling $restype $resid in namespace $namespace with label $labelname=$labelid to 0"$SAMELINE
2197 kubectl $KUBECONF scale $restype $resid -n $namespace --replicas=0 1> /dev/null 2> ./tmp/kubeerr
2198 echo -e " Ordered scaling $restype $resid in namespace $namespace with label $labelname=$labelid to 0 $GREEN OK $EGREEN"
2204 # Scale all kube resource sets to 0 in a namespace for resources having a certain lable and an optional label-id
2205 # This function do wait for the resource to reach 0
2206 # args: <namespace> <label-name> [ <label-id> ]
2207 # (Not for test scripts)
2208 __kube_scale_and_wait_all_resources() {
2212 if [ -z "$3" ]; then
2213 echo " Attempt to scale - deployment replicaset statefulset - in namespace $namespace with label $labelname"
2215 echo " Attempt to scale - deployment replicaset statefulset - in namespace $namespace with label $labelname=$labelid"
2217 resources="deployment replicaset statefulset"
2219 while [ $scaled_all -ne 0 ]; do
2221 for restype in $resources; do
2222 if [ -z "$3" ]; then
2223 result=$(kubectl $KUBECONF get $restype -n $namespace -o jsonpath='{.items[?(@.metadata.labels.'$labelname')].metadata.name}')
2225 result=$(kubectl $KUBECONF get $restype -n $namespace -o jsonpath='{.items[?(@.metadata.labels.'$labelname'=="'$labelid'")].metadata.name}')
2227 if [ $? -eq 0 ] && [ ! -z "$result" ]; then
2228 for resid in $result; do
2229 echo -e " Ordered scaling $restype $resid in namespace $namespace with label $labelname=$labelid to 0"
2230 kubectl $KUBECONF scale $restype $resid -n $namespace --replicas=0 1> /dev/null 2> ./tmp/kubeerr
2233 while [ $count -ne 0 ]; do
2234 count=$(kubectl $KUBECONF get $restype $resid -n $namespace -o jsonpath='{.status.replicas}' 2> /dev/null)
2235 echo -ne " Scaling $restype $resid in namespace $namespace with label $labelname=$labelid to 0, current count=$count"$SAMELINE
2236 if [ $? -eq 0 ] && [ ! -z "$count" ]; then
2241 duration=$(($SECONDS-$T_START))
2242 if [ $duration -gt 100 ]; then
2243 #Forcring count 0, to avoid hanging for failed scaling
2248 echo -e " Scaled $restype $resid in namespace $namespace with label $labelname=$labelid to 0, current count=$count $GREEN OK $EGREEN"
2255 # Remove all kube resources in a namespace for resources having a certain label and label-id
2256 # This function wait until the resources are gone. Scaling to 0 must have been ordered previously
2257 # args: <namespace> <label-name> <label-id>
2258 # (Not for test scripts)
2259 __kube_delete_all_resources() {
2263 resources="deployments replicaset statefulset services pods configmaps persistentvolumeclaims persistentvolumes serviceaccounts clusterrolebindings"
2264 deleted_resourcetypes=""
2265 for restype in $resources; do
2266 ns_flag="-n $namespace"
2267 ns_text="in namespace $namespace"
2268 if [ $restype == "persistentvolumes" ]; then
2272 if [ $restype == "clusterrolebindings" ]; then
2276 result=$(kubectl $KUBECONF get $restype $ns_flag -o jsonpath='{.items[?(@.metadata.labels.'$labelname'=="'$labelid'")].metadata.name}')
2277 if [ $? -eq 0 ] && [ ! -z "$result" ]; then
2278 deleted_resourcetypes=$deleted_resourcetypes" "$restype
2279 for resid in $result; do
2280 if [ $restype == "replicaset" ] || [ $restype == "statefulset" ]; then
2282 while [ $count -ne 0 ]; do
2283 count=$(kubectl $KUBECONF get $restype $resid $ns_flag -o jsonpath='{.status.replicas}' 2> /dev/null)
2284 echo -ne " Scaling $restype $resid $ns_text with label $labelname=$labelid to 0, current count=$count"$SAMELINE
2285 if [ $? -eq 0 ] && [ ! -z "$count" ]; then
2291 echo -e " Scaled $restype $resid $ns_text with label $labelname=$labelid to 0, current count=$count $GREEN OK $EGREEN"
2293 echo -ne " Deleting $restype $resid $ns_text with label $labelname=$labelid "$SAMELINE
2294 kubectl $KUBECONF delete --grace-period=1 $restype $resid $ns_flag 1> /dev/null 2> ./tmp/kubeerr
2295 if [ $? -eq 0 ]; then
2296 echo -e " Deleted $restype $resid $ns_text with label $labelname=$labelid $GREEN OK $EGREEN"
2298 echo -e " Deleted $restype $resid $ns_text with label $labelname=$labelid $GREEN Does not exist - OK $EGREEN"
2304 if [ ! -z "$deleted_resourcetypes" ]; then
2305 for restype in $deleted_resources; do
2306 ns_flag="-n $namespace"
2307 ns_text="in namespace $namespace"
2308 if [ $restype == "persistentvolumes" ]; then
2312 echo -ne " Waiting for $restype $ns_text with label $labelname=$labelid to be deleted..."$SAMELINE
2315 while [ ! -z "$result" ]; do
2317 result=$(kubectl $KUBECONF get $restype $ns_flag -o jsonpath='{.items[?(@.metadata.labels.'$labelname'=="'$labelid'")].metadata.name}')
2318 echo -ne " Waiting for $restype $ns_text with label $labelname=$labelid to be deleted...$(($SECONDS-$T_START)) seconds "$SAMELINE
2319 if [ -z "$result" ]; then
2320 echo -e " Waiting for $restype $ns_text with label $labelname=$labelid to be deleted...$(($SECONDS-$T_START)) seconds $GREEN OK $EGREEN"
2321 elif [ $(($SECONDS-$T_START)) -gt 300 ]; then
2322 echo -e " Waiting for $restype $ns_text with label $labelname=$labelid to be deleted...$(($SECONDS-$T_START)) seconds $RED Failed $ERED"
2330 # Creates a namespace if it does not exists
2332 # (Not for test scripts)
2333 __kube_create_namespace() {
2335 #Check if test namespace exists, if not create it
2336 kubectl $KUBECONF get namespace $1 1> /dev/null 2> ./tmp/kubeerr
2337 if [ $? -ne 0 ]; then
2338 echo -ne " Creating namespace "$1 $SAMELINE
2339 kubectl $KUBECONF create namespace $1 1> /dev/null 2> ./tmp/kubeerr
2340 if [ $? -ne 0 ]; then
2341 echo -e " Creating namespace $1 $RED$BOLD FAILED $EBOLD$ERED"
2343 echo " Message: $(<./tmp/kubeerr)"
2346 kubectl $KUBECONF label ns $1 autotest=engine
2347 echo -e " Creating namespace $1 $GREEN$BOLD OK $EBOLD$EGREEN"
2350 echo -e " Creating namespace $1 $GREEN$BOLD Already exists, OK $EBOLD$EGREEN"
2355 # Removes a namespace if it exists
2357 # (Not for test scripts)
2358 __kube_delete_namespace() {
2360 #Check if test namespace exists, if so remove it
2361 kubectl $KUBECONF get namespace $1 1> /dev/null 2> ./tmp/kubeerr
2362 if [ $? -eq 0 ]; then
2363 echo -ne " Removing namespace "$1 $SAMELINE
2364 kubectl $KUBECONF delete namespace $1 1> /dev/null 2> ./tmp/kubeerr
2365 if [ $? -ne 0 ]; then
2366 echo -e " Removing namespace $1 $RED$BOLD FAILED $EBOLD$ERED"
2368 echo " Message: $(<./tmp/kubeerr)"
2371 echo -e " Removing namespace $1 $GREEN$BOLD OK $EBOLD$EGREEN"
2374 echo -e " Namespace $1 $GREEN$BOLD does not exist, OK $EBOLD$EGREEN"
2379 # Removes a namespace
2381 # (Not for test scripts)
2382 clean_and_create_namespace() {
2385 if [ $# -ne 1 ]; then
2386 __print_err "<namespace>" $@
2389 __kube_delete_namespace $1
2390 if [ $? -ne 0 ]; then
2393 __kube_create_namespace $1
2394 if [ $? -ne 0 ]; then
2400 # Find the host ip of an app (using the service resource)
2401 # args: <app-name> <namespace>
2402 # (Not for test scripts)
2403 __kube_get_service_host() {
2404 if [ $# -ne 2 ]; then
2406 __print_err "need 2 args, <app-name> <namespace>" $@
2409 for timeout in {1..60}; do
2410 host=$(kubectl $KUBECONF get svc $1 -n $2 -o jsonpath='{.spec.clusterIP}')
2411 if [ $? -eq 0 ]; then
2412 if [ ! -z "$host" ]; then
2420 echo "host-not-found-fatal-error"
2424 # Find the named port to an app (using the service resource)
2425 # args: <app-name> <namespace> <port-name>
2426 # (Not for test scripts)
2427 __kube_get_service_port() {
2428 if [ $# -ne 3 ]; then
2430 __print_err "need 3 args, <app-name> <namespace> <port-name>" $@
2434 for timeout in {1..60}; do
2435 port=$(kubectl $KUBECONF get svc $1 -n $2 -o jsonpath='{...ports[?(@.name=="'$3'")].port}')
2436 if [ $? -eq 0 ]; then
2437 if [ ! -z "$port" ]; then
2449 # Find the named node port to an app (using the service resource)
2450 # args: <app-name> <namespace> <port-name>
2451 # (Not for test scripts)
2452 __kube_get_service_nodeport() {
2453 if [ $# -ne 3 ]; then
2455 __print_err "need 3 args, <app-name> <namespace> <port-name>" $@
2459 for timeout in {1..60}; do
2460 port=$(kubectl $KUBECONF get svc $1 -n $2 -o jsonpath='{...ports[?(@.name=="'$3'")].nodePort}')
2461 if [ $? -eq 0 ]; then
2462 if [ ! -z "$port" ]; then
2474 # Create a kube resource from a yaml template
2475 # args: <resource-type> <resource-name> <template-yaml> <output-yaml>
2476 # (Not for test scripts)
2477 __kube_create_instance() {
2478 echo -ne " Creating $1 $2"$SAMELINE
2480 kubectl $KUBECONF apply -f $4 1> /dev/null 2> ./tmp/kubeerr
2481 if [ $? -ne 0 ]; then
2483 echo -e " Creating $1 $2 $RED Failed $ERED"
2484 echo " Message: $(<./tmp/kubeerr)"
2487 echo -e " Creating $1 $2 $GREEN OK $EGREEN"
2491 # Function to create a configmap in kubernetes
2492 # args: <configmap-name> <namespace> <labelname> <labelid> <path-to-data-file> <path-to-output-yaml>
2493 # (Not for test scripts)
2494 __kube_create_configmap() {
2495 echo -ne " Creating configmap $1 "$SAMELINE
2496 envsubst < $5 > $5"_tmp"
2497 cp $5"_tmp" $5 #Need to copy back to orig file name since create configmap neeed the original file name
2498 kubectl $KUBECONF create configmap $1 -n $2 --from-file=$5 --dry-run=client -o yaml > $6
2499 if [ $? -ne 0 ]; then
2500 echo -e " Creating configmap $1 $RED Failed $ERED"
2505 kubectl $KUBECONF apply -f $6 1> /dev/null 2> ./tmp/kubeerr
2506 if [ $? -ne 0 ]; then
2507 echo -e " Creating configmap $1 $RED Apply failed $ERED"
2508 echo " Message: $(<./tmp/kubeerr)"
2512 kubectl $KUBECONF label configmap $1 -n $2 $3"="$4 --overwrite 1> /dev/null 2> ./tmp/kubeerr
2513 if [ $? -ne 0 ]; then
2514 echo -e " Creating configmap $1 $RED Labeling failed $ERED"
2515 echo " Message: $(<./tmp/kubeerr)"
2519 # Log the resulting map
2520 kubectl $KUBECONF get configmap $1 -n $2 -o yaml > $6
2522 echo -e " Creating configmap $1 $GREEN OK $EGREEN"
2526 # This function runs a kubectl cmd where a single output value is expected, for example get ip with jsonpath filter.
2527 # The function retries up to the timeout given in the cmd flag '--cluster-timeout'
2528 # args: <full kubectl cmd with parameters>
2529 # (Not for test scripts)
2530 __kube_cmd_with_timeout() {
2531 TS_TMP=$(($SECONDS+$CLUSTER_TIME_OUT))
2534 kube_cmd_result=$($@)
2535 if [ $? -ne 0 ]; then
2538 if [ $SECONDS -ge $TS_TMP ] || [ ! -z "$kube_cmd_result" ] ; then
2539 echo $kube_cmd_result
2546 # This function starts a pod that cleans a the contents of a path mounted as a pvc
2547 # After this action the pod should terminate
2548 # This should only be executed when the pod owning the pvc is not running
2549 # args: <appname> <namespace> <pvc-name> <path-to remove>
2550 # (Not for test scripts)
2551 __kube_clean_pvc() {
2553 #using env vars setup in pvccleaner_api_functions.sh
2555 export PVC_CLEANER_NAMESPACE=$2
2556 export PVC_CLEANER_CLAIMNAME=$3
2557 export PVC_CLEANER_RM_PATH=$4
2558 export PVC_CLEANER_APP_NAME
2559 input_yaml=$SIM_GROUP"/"$PVC_CLEANER_COMPOSE_DIR"/"pvc-cleaner.yaml
2560 output_yaml=$PWD/tmp/$2-pvc-cleaner.yaml
2562 envsubst < $input_yaml > $output_yaml
2564 kubectl $KUBECONF delete -f $output_yaml 1> /dev/null 2> /dev/null # Delete the previous terminated pod - if existing
2566 __kube_create_instance pod $PVC_CLEANER_APP_NAME $input_yaml $output_yaml
2567 if [ $? -ne 0 ]; then
2568 echo $YELLOW" Could not clean pvc for app: $1 - persistent storage not clean - tests may not work"
2572 term_ts=$(($SECONDS+30))
2573 while [ $term_ts -gt $SECONDS ]; do
2574 pod_status=$(kubectl $KUBECONF get pod pvc-cleaner -n $PVC_CLEANER_NAMESPACE --no-headers -o custom-columns=":status.phase")
2575 if [ "$pod_status" == "Succeeded" ]; then
2582 # This function scales or deletes all resources for app selected by the testcase.
2584 # (Not for test scripts)
2586 echo -e $BOLD"Initialize kube pods/statefulsets/replicaset to initial state"$EBOLD
2588 # Scale prestarted or managed apps
2589 for imagename in $APP_SHORT_NAMES; do
2590 # A function name is created from the app short name
2591 # for example app short name 'RICMSIM' -> produce the function
2592 # name __RICSIM_kube_scale_zero or __RICSIM_kube_scale_zero_and_wait
2593 # This function is called and is expected to exist in the imported
2594 # file for the ricsim test functions
2595 # The resulting function impl shall scale the resources to 0
2596 # For prestarted apps, the function waits until the resources are 0
2597 # For included (not prestated) apps, the scaling is just ordered
2598 __check_prestarted_image $imagename
2599 if [ $? -eq 0 ]; then
2600 function_pointer="__"$imagename"_kube_scale_zero_and_wait"
2601 echo -e " Scaling all kube resources for app $BOLD $imagename $EBOLD to 0"
2604 __check_included_image $imagename
2605 if [ $? -eq 0 ]; then
2606 function_pointer="__"$imagename"_kube_scale_zero"
2607 echo -e " Scaling all kube resources for app $BOLD $imagename $EBOLD to 0"
2613 # Delete managed apps
2614 for imagename in $APP_SHORT_NAMES; do
2615 __check_included_image $imagename
2616 if [ $? -eq 0 ]; then
2617 __check_prestarted_image $imagename
2618 if [ $? -ne 0 ]; then
2619 # A function name is created from the app short name
2620 # for example app short name 'RICMSIM' -> produce the function
2621 # name __RICSIM__kube_delete_all
2622 # This function is called and is expected to exist in the imported
2623 # file for the ricsim test functions
2624 # The resulting function impl shall delete all its resources
2625 function_pointer="__"$imagename"_kube_delete_all"
2626 echo -e " Deleting all kube resources for app $BOLD $imagename $EBOLD"
2635 # Function stop and remove all containers (docker) and services/deployments etc(kube)
2637 # Function for test script
2638 clean_environment() {
2639 if [ $RUNMODE == "KUBE" ]; then
2641 if [ $PRE_CLEAN -eq 1 ]; then
2642 echo " Cleaning docker resouces to free up resources, may take time..."
2643 ../common/clean_docker.sh 2>&1 /dev/null
2648 if [ $PRE_CLEAN -eq 1 ]; then
2649 echo " Cleaning kubernetes resouces to free up resources, may take time..."
2650 ../common/clean_kube.sh $KUBECONF 2>&1 /dev/null
2656 # 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
2658 # (Function for test scripts)
2659 auto_clean_environment() {
2661 if [ "$AUTO_CLEAN" == "auto" ]; then
2662 echo -e $BOLD"Initiating automatic cleaning of environment"$EBOLD
2667 # Function to sleep a test case for a numner of seconds. Prints the optional text args as info
2668 # args: <sleep-time-in-sec> [any-text-in-quotes-to-be-printed]
2669 # (Function for test scripts)
2672 echo -e $BOLD"INFO(${BASH_LINENO[0]}): "${FUNCNAME[0]}"," $@ $EBOLD
2673 if [ $# -lt 1 ]; then
2675 __print_err "need at least one arg, <sleep-time-in-sec> [any-text-to-printed]" $@
2678 #echo "---- Sleep for " $1 " seconds ---- "$2
2680 duration=$((SECONDS-start))
2681 while [ $duration -lt $1 ]; do
2682 echo -ne " Slept for ${duration} seconds${SAMELINE}"
2684 duration=$((SECONDS-start))
2686 echo -ne " Slept for ${duration} seconds${SAMELINE}"
2690 # Print error info for the call in the parent script (test case). Arg: <error-message-to-print>
2691 # Not to be called from the test script itself.
2693 echo -e $RED ${FUNCNAME[1]} " "$1" " ${BASH_SOURCE[2]} " line" ${BASH_LINENO[1]} $ERED
2694 if [ $# -gt 1 ]; then
2695 echo -e $RED" Got: "${FUNCNAME[1]} ${@:2} $ERED
2698 __check_stop_at_error
2701 # Function to create the docker network for the test
2702 # Not to be called from the test script itself.
2703 __create_docker_network() {
2704 tmp=$(docker network ls --format={{.Name}} --filter name=$DOCKER_SIM_NWNAME)
2705 if [ $? -ne 0 ]; then
2706 echo -e $RED" Could not check if docker network $DOCKER_SIM_NWNAME exists"$ERED
2709 if [ "$tmp" != $DOCKER_SIM_NWNAME ]; then
2710 echo -e " Creating docker network:$BOLD $DOCKER_SIM_NWNAME $EBOLD"
2711 docker network create $DOCKER_SIM_NWNAME | indent2
2712 if [ $? -ne 0 ]; then
2713 echo -e $RED" Could not create docker network $DOCKER_SIM_NWNAME"$ERED
2716 echo -e "$GREEN Done$EGREEN"
2719 echo -e " Docker network $DOCKER_SIM_NWNAME already exists$GREEN OK $EGREEN"
2723 # Function to start container with docker-compose and wait until all are in state running.
2724 # If the <docker-compose-file> is empty, the default 'docker-compose.yml' is assumed.
2725 #args: <docker-compose-dir> <docker-compose-file> <docker-compose-arg>|NODOCKERARGS <count> <app-name>+
2726 # (Not for test scripts)
2727 __start_container() {
2729 if [ $# -lt 5 ]; then
2731 __print_err "need 5 or more args, <docker-compose-dir> <docker-compose-file> <docker-compose-arg>|NODOCKERARGS <count> <app-name>+" $@
2735 __create_docker_network
2743 if [ -z "$compose_file" ]; then
2744 compose_file="docker-compose.yml"
2752 envsubst < $compose_file > "gen_"$compose_file
2753 compose_file="gen_"$compose_file
2754 if [ $DOCKER_COMPOSE_VERION == "V1" ]; then
2755 docker_compose_cmd="docker-compose"
2757 docker_compose_cmd="docker compose"
2760 if [ "$compose_args" == "NODOCKERARGS" ]; then
2761 $docker_compose_cmd -f $compose_file up -d &> .dockererr
2762 if [ $? -ne 0 ]; then
2763 echo -e $RED"Problem to launch container(s) with docker-compose"$ERED
2765 echo -e $RED"Stopping script...."$ERED
2769 $docker_compose_cmd -f $compose_file up -d $compose_args &> .dockererr
2770 if [ $? -ne 0 ]; then
2771 echo -e $RED"Problem to launch container(s) with docker-compose"$ERED
2773 echo -e $RED"Stopping script...."$ERED
2781 while [ $appindex -lt $appcount ]; do
2785 for i in {1..10}; do
2786 if [ "$(docker inspect --format '{{ .State.Running }}' $appname)" == "true" ]; then
2787 echo -e " Container $BOLD${appname}$EBOLD$GREEN running$EGREEN on$BOLD image $(docker inspect --format '{{ .Config.Image }}' ${appname}) $EBOLD"
2794 if [ $app_started -eq 0 ]; then
2797 echo -e $RED" Container $BOLD${appname}$EBOLD could not be started"$ERED
2798 echo -e $RED" Stopping script..."$ERED
2801 let appindex=appindex+1
2806 # Function to check if container/service is responding to http/https
2807 # args: <container-name>|<service-name> url
2808 # (Not for test scripts)
2809 __check_service_start() {
2811 if [ $# -ne 2 ]; then
2813 __print_err "need 2 args, <container-name>|<service-name> url" $@
2817 if [ $RUNMODE == "KUBE" ]; then
2818 ENTITY="service/set/deployment"
2824 echo -ne " Container $BOLD${appname}$EBOLD starting${SAMELINE}"
2828 echo -ne " Waiting for ${ENTITY} ${appname} service status...${SAMELINE}"
2831 while (( $TSTART+600 > $SECONDS )); do
2832 result="$(__do_curl -m 10 $url)"
2833 if [ $? -eq 0 ]; then
2834 if [ ${#result} -gt 15 ]; then
2835 #If response is too long, truncate
2836 result="...response text too long, omitted"
2838 echo -ne " Waiting for {ENTITY} $BOLD${appname}$EBOLD service status on ${3}, result: $result${SAMELINE}"
2839 echo -ne " The ${ENTITY} $BOLD${appname}$EBOLD$GREEN is alive$EGREEN, responds to service status:$GREEN $result $EGREEN on ${url} after $(($SECONDS-$TSTART)) seconds"
2845 if (( $TS_OFFSET > 5 )); then
2848 while [ $(($TS_TMP+$TS_OFFSET)) -gt $SECONDS ]; do
2849 echo -ne " Waiting for ${ENTITY} ${appname} service status on ${url}...$(($SECONDS-$TSTART)) seconds, retrying in $(($TS_TMP+$TS_OFFSET-$SECONDS)) seconds ${SAMELINE}"
2853 let loop_ctr=loop_ctr+1
2856 if [ "$pa_st" = "false" ]; then
2858 echo -e $RED" The ${ENTITY} ${appname} did not respond to service status on ${url} in $(($SECONDS-$TSTART)) seconds"$ERED
2871 __check_container_logs() {
2879 echo -e $BOLD"Checking $dispname container $appname log ($logpath) for WARNINGs and ERRORs"$EBOLD
2881 if [ $RUNMODE == "KUBE" ]; then
2882 echo -e $YELLOW" Internal log for $dispname not checked in kube"$EYELLOW
2886 #tmp=$(docker ps | grep $appname)
2887 tmp=$(docker ps -q --filter name=$appname) #get the container id
2888 if [ -z "$tmp" ]; then #Only check logs for running Policy Agent apps
2889 echo " "$dispname" is not running, no check made"
2892 foundentries="$(docker exec -t $tmp grep $warning $logpath | wc -l)"
2893 if [ $? -ne 0 ];then
2894 echo " Problem to search $appname log $logpath"
2896 if [ $foundentries -eq 0 ]; then
2897 echo " No WARN entries found in $appname log $logpath"
2899 echo -e " Found \033[1m"$foundentries"\033[0m WARN entries in $appname log $logpath"
2902 foundentries="$(docker exec -t $tmp grep $error $logpath | wc -l)"
2903 if [ $? -ne 0 ];then
2904 echo " Problem to search $appname log $logpath"
2906 if [ $foundentries -eq 0 ]; then
2907 echo " No ERR entries found in $appname log $logpath"
2909 echo -e $RED" Found \033[1m"$foundentries"\033[0m"$RED" ERR entries in $appname log $logpath"$ERED
2915 # Store all container logs and other logs in the log dir for the script
2916 # Logs are stored with a prefix in case logs should be stored several times during a test
2917 # args: <logfile-prefix>
2918 # (Function for test scripts)
2920 if [ $# != 1 ]; then
2922 __print_err "need one arg, <file-prefix>" $@
2925 echo -e $BOLD"Storing all docker/kube container logs and other test logs in $TESTLOGS/$ATC using prefix: "$1$EBOLD
2927 docker stats --no-stream > $TESTLOGS/$ATC/$1_docker_stats.log 2>&1
2929 docker ps -a > $TESTLOGS/$ATC/$1_docker_ps.log 2>&1
2931 cp .httplog_${ATC}.txt $TESTLOGS/$ATC/$1_httplog_${ATC}.txt 2>&1
2933 if [ $RUNMODE == "DOCKER" ]; then
2935 # Store docker logs for all container
2936 for imagename in $APP_SHORT_NAMES; do
2937 __check_included_image $imagename
2938 if [ $? -eq 0 ]; then
2939 # A function name is created from the app short name
2940 # for example app short name 'RICMSIM' -> produce the function
2941 # name __RICSIM__store_docker_logs
2942 # This function is called and is expected to exist in the imported
2943 # file for the ricsim test functions
2944 # The resulting function impl shall store the docker logs for each container
2945 function_pointer="__"$imagename"_store_docker_logs"
2946 $function_pointer "$TESTLOGS/$ATC/" $1
2950 if [ $RUNMODE == "KUBE" ]; then
2951 namespaces=$(kubectl $KUBECONF get namespaces -o jsonpath='{.items[?(@.metadata.name)].metadata.name}')
2952 for nsid in $namespaces; do
2953 pods=$(kubectl $KUBECONF get pods -n $nsid -o jsonpath='{.items[?(@.metadata.labels.autotest)].metadata.name}')
2954 for podid in $pods; do
2955 kubectl $KUBECONF logs -n $nsid $podid > $TESTLOGS/$ATC/$1_${podid}.log
2965 # Generic curl function, assumes all 200-codes are ok
2966 # args: <valid-curl-args-including full url>
2967 # returns: <returned response (without respose code)> or "<no-response-from-server>" or "<not found, <http-code>>""
2968 # returns: The return code is 0 for ok and 1 for not ok
2970 echo ${FUNCNAME[1]} "line: "${BASH_LINENO[1]} >> $HTTPLOG
2972 if [ ! -z "$KUBE_PROXY_PATH" ]; then
2973 if [ $KUBE_PROXY_HTTPX == "http" ]; then
2974 proxyflag=" --proxy $KUBE_PROXY_PATH"
2976 proxyflag=" --proxy-insecure --proxy $KUBE_PROXY_PATH"
2979 curlString="curl -skw %{http_code} $proxyflag $@"
2980 echo " CMD: $curlString" >> $HTTPLOG
2983 echo " RESP: $res" >> $HTTPLOG
2984 echo " RETCODE: $retcode" >> $HTTPLOG
2985 if [ $retcode -ne 0 ]; then
2986 echo "<no-response-from-server>"
2989 http_code="${res:${#res}-3}"
2990 if [ ${#res} -eq 3 ]; then
2991 if [ $http_code -lt 200 ] || [ $http_code -gt 299 ]; then
2992 echo "<no-response-from-server>"
2998 if [ $http_code -lt 200 ] || [ $http_code -gt 299 ]; then
2999 echo "<not found, resp:${http_code}>"
3002 if [ $# -eq 2 ]; then
3003 echo "${res:0:${#res}-3}" | xargs
3005 echo "${res:0:${#res}-3}"
3012 #######################################
3013 ### Basic helper function for test cases
3014 #######################################
3016 # Test a simulator container variable value towards target value using an condition operator with an optional timeout.
3017 # Arg: <simulator-name> <host> <variable-name> <condition-operator> <target-value> - This test is done
3018 # immediately and sets pass or fail depending on the result of comparing variable and target using the operator.
3019 # Arg: <simulator-name> <host> <variable-name> <condition-operator> <target-value> <timeout> - This test waits up to the timeout
3020 # before setting pass or fail depending on the result of comparing variable and target using the operator.
3021 # 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.
3022 # Not to be called from test script.
3025 checkjsonarraycount=0
3026 TIMESTAMP=$(date "+%Y-%m-%d %H:%M:%S")
3027 if [ $# -eq 6 ]; then
3028 if [[ $3 == "json:"* ]]; then
3029 checkjsonarraycount=1
3032 echo -e $BOLD"TEST $TEST_SEQUENCE_NR (${BASH_LINENO[1]}): ${1}, ${3} ${4} ${5} within ${6} seconds"$EBOLD
3033 echo "TEST $TEST_SEQUENCE_NR - ${TIMESTAMP}: (${BASH_LINENO[1]}): ${1}, ${3} ${4} ${5} within ${6} seconds" >> $HTTPLOG
3036 ((TEST_SEQUENCE_NR++))
3040 if [ $checkjsonarraycount -eq 0 ]; then
3041 result="$(__do_curl $2$3)"
3043 result=${result//[[:blank:]]/} #Strip blanks
3046 result="$(__do_curl $2$path)"
3048 echo "$result" > ./tmp/.tmp.curl.json
3049 result=$(python3 ../common/count_json_elements.py "./tmp/.tmp.curl.json")
3051 duration=$((SECONDS-start))
3052 echo -ne " Result=${result} after ${duration} seconds${SAMELINE}"
3054 if [ $retcode -ne 0 ]; then
3055 if [ $duration -gt $6 ]; then
3057 echo -e $RED" FAIL${ERED} - ${3} ${4} ${5} not reached in ${6} seconds, result = ${result}"
3058 __print_current_stats
3059 __check_stop_at_error
3062 elif [ "$4" == "=" ] && [ "$result" -eq $5 ]; then
3064 echo -e " Result=${result} after ${duration} seconds${SAMELINE}"
3065 echo -e $GREEN" PASS${EGREEN} - Result=${result} after ${duration} seconds"
3066 __print_current_stats
3068 elif [ "$4" == ">" ] && [ "$result" -gt $5 ]; then
3070 echo -e " Result=${result} after ${duration} seconds${SAMELINE}"
3071 echo -e $GREEN" PASS${EGREEN} - Result=${result} after ${duration} seconds"
3072 __print_current_stats
3074 elif [ "$4" == "<" ] && [ "$result" -lt $5 ]; then
3076 echo -e " Result=${result} after ${duration} seconds${SAMELINE}"
3077 echo -e $GREEN" PASS${EGREEN} - Result=${result} after ${duration} seconds"
3078 __print_current_stats
3080 elif [ "$4" == ">=" ] && [ "$result" -ge $5 ]; then
3082 echo -e " Result=${result} after ${duration} seconds${SAMELINE}"
3083 echo -e $GREEN" PASS${EGREEN} - Result=${result} after ${duration} seconds"
3084 __print_current_stats
3086 elif [ "$4" == "contain_str" ] && [[ $result =~ $5 ]]; then
3088 echo -e " Result=${result} after ${duration} seconds${SAMELINE}"
3089 echo -e $GREEN" PASS${EGREEN} - Result=${result} after ${duration} seconds"
3090 __print_current_stats
3093 if [ $duration -gt $6 ]; then
3095 echo -e $RED" FAIL${ERED} - ${3} ${4} ${5} not reached in ${6} seconds, result = ${result}"
3096 __print_current_stats
3097 __check_stop_at_error
3103 elif [ $# -eq 5 ]; then
3104 if [[ $3 == "json:"* ]]; then
3105 checkjsonarraycount=1
3108 echo -e $BOLD"TEST $TEST_SEQUENCE_NR (${BASH_LINENO[1]}): ${1}, ${3} ${4} ${5}"$EBOLD
3109 echo "TEST $TEST_SEQUENCE_NR - ${TIMESTAMP}: (${BASH_LINENO[1]}): ${1}, ${3} ${4} ${5}" >> $HTTPLOG
3111 ((TEST_SEQUENCE_NR++))
3112 if [ $checkjsonarraycount -eq 0 ]; then
3113 result="$(__do_curl $2$3)"
3115 result=${result//[[:blank:]]/} #Strip blanks
3118 result="$(__do_curl $2$path)"
3120 echo "$result" > ./tmp/.tmp.curl.json
3121 result=$(python3 ../common/count_json_elements.py "./tmp/.tmp.curl.json")
3123 if [ $retcode -ne 0 ]; then
3125 echo -e $RED" FAIL ${ERED}- ${3} ${4} ${5} not reached, result = ${result}"
3126 __print_current_stats
3127 __check_stop_at_error
3128 elif [ "$4" == "=" ] && [ "$result" -eq $5 ]; then
3130 echo -e $GREEN" PASS${EGREEN} - Result=${result}"
3131 __print_current_stats
3132 elif [ "$4" == ">" ] && [ "$result" -gt $5 ]; then
3134 echo -e $GREEN" PASS${EGREEN} - Result=${result}"
3135 __print_current_stats
3136 elif [ "$4" == "<" ] && [ "$result" -lt $5 ]; then
3138 echo -e $GREEN" PASS${EGREEN} - Result=${result}"
3139 __print_current_stats
3140 elif [ "$4" == ">=" ] && [ "$result" -ge $5 ]; then
3142 echo -e $GREEN" PASS${EGREEN} - Result=${result}"
3143 __print_current_stats
3144 elif [ "$4" == "contain_str" ] && [[ $result =~ $5 ]]; then
3146 echo -e $GREEN" PASS${EGREEN} - Result=${result}"
3147 __print_current_stats
3150 echo -e $RED" FAIL${ERED} - ${3} ${4} ${5} not reached, result = ${result}"
3151 __print_current_stats
3152 __check_stop_at_error
3155 echo "Wrong args to __var_test, needs five or six args: <simulator-name> <host> <variable-name> <condition-operator> <target-value> [ <timeout> ]"