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>]"
33 echo " [--kubecontext <context-name>]"
36 if [ $# -eq 1 ] && [ "$1" == "help" ]; then
38 if [ ! -z "$TC_ONELINE_DESCR" ]; then
39 echo "Test script description:"
40 echo $TC_ONELINE_DESCR
45 echo "remote - Use images from remote repositories. Can be overridden for individual images using the '--use_xxx' flags"
46 echo "remote-remove - Same as 'remote' but will also try to pull fresh images from remote repositories"
47 echo "docker - Test executed in docker environment"
48 echo "kube - Test executed in kubernetes environment - requires an already started kubernetes environment"
49 echo "--env-file <file> - The script will use the supplied file to read environment variables from"
50 echo "release - If this flag is given the script will use release version of the images"
51 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."
52 echo "--stop-at-error - The script will stop when the first failed test or configuration"
53 echo "--ricsim-prefix - The a1 simulator will use the supplied string as container prefix instead of 'ricsim'"
54 echo "--use-local-image - The script will use local images for the supplied apps, space separated list of app short names"
55 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"
56 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"
57 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"
58 echo "--image-repo - Url to optional image repo. Only locally built images will be re-tagged and pushed to this repo"
59 echo "--repo-policy - Policy controlling which images to re-tag and push if param --image-repo is set. Default is 'local'"
60 echo "--cluster-timeout - Optional timeout for cluster where it takes time to obtain external ip/host-name. Timeout in seconds. "
61 echo "--print-stats - Print current test stats after each test."
62 echo "--override <file> - Override setting from the file supplied by --env-file"
63 echo "--pre-clean - Will clean kube resouces when running docker and vice versa"
64 echo "--gen-stats - Collect container/pod runtime statistics"
65 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."
66 echo "--delete-containers - Delete docker containers before starting tests - but only those created by the test scripts. Docker mode only."
67 echo "--endpoint-stats - Collect endpoint statistics"
68 echo "--kubeconfig - Configure kubectl to use cluster specific cluster config file"
69 echo "--host-path-dir - (Base-)path on local-hostmounted to all VMs (nodes), for hostpath volumes in kube"
70 echo "--kubecontext - Configure kubectl to use a certain context, e.g 'minikube'"
72 echo "List of app short names supported: "$APP_SHORT_NAMES
77 # Create a test case id, ATC (Auto Test Case), from the name of the test case script.
78 # FTC1.sh -> ATC == FTC1
79 ATC=$(basename "${BASH_SOURCE[$i+1]}" .sh)
81 #Create result file (containing '1' for error) for this test case
82 #Will be replaced with a file containing '0' if all test cases pass
83 echo "1" > "$PWD/.result$ATC.txt"
85 #Formatting for 'echo' cmd
90 GREEN="\033[32m\033[1m"
92 YELLOW="\033[33m\033[1m"
96 # Just resetting any previous echo formatting...
99 # default test environment variables
101 #Override env file, will be added on top of the above file
102 TEST_ENV_VAR_FILE_OVERRIDE=""
104 echo "Test case started as: ${BASH_SOURCE[$i+1]} "$@
106 # Var to hold 'auto' in case containers shall be stopped when test case ends
109 # Var to indicate pre clean, if flag --pre-clean is set the script will clean kube resouces when running docker and vice versa
112 # Var to hold the app names to use local images for
115 # Var to hold the app names to use remote snapshot images for
116 USE_SNAPSHOT_IMAGES=""
118 # Var to hold the app names to use remote staging images for
119 USE_STAGING_IMAGES=""
121 # Var to hold the app names to use remote release images for
122 USE_RELEASE_IMAGES=""
125 # 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
128 # The default value "DEV" indicate that development image tags (SNAPSHOT) and nexus repos (nexus port 10002) are used.
129 # The value "RELEASE" indicate that relase image tag and nexus repos (nexus port) are used
130 # Applies only to images defined in the test-env files with image names and tags defined as XXXX_RELEASE
133 #Var to indicate docker-compose version, V1 or V2
134 #V1 names replicated containers <proj-name>_<service-name>_<index>
135 #V2 names replicated containers <proj-name>-<service-name>-<index>
136 DOCKER_COMPOSE_VERION="V1"
138 # Function to indent cmd output with one space
139 indent1() { sed 's/^/ /'; }
141 # Function to indent cmd output with two spaces
142 indent2() { sed 's/^/ /'; }
144 # Set a description string for the test case
145 if [ -z "$TC_ONELINE_DESCR" ]; then
146 TC_ONELINE_DESCR="<no-description>"
147 echo "No test case description found, TC_ONELINE_DESCR should be set on in the test script , using "$TC_ONELINE_DESCR
150 # Counter for test suites
151 if [ -f .tmp_tcsuite_ctr ]; then
152 tmpval=$(< .tmp_tcsuite_ctr)
154 echo $tmpval > .tmp_tcsuite_ctr
157 # Create the logs dir if not already created in the current dir
158 if [ ! -d "logs" ]; then
163 # Create the tmp dir for temporary files that is not needed after the test
164 # hidden files for the test env is still stored in the current dir
165 # files in the ./tmp is moved to ./tmp/prev when a new test is started
166 if [ ! -d "tmp" ]; then
168 if [ $? -ne 0 ]; then
169 echo "Cannot create dir for temp files, $PWD/tmp"
176 if [ $? -ne 0 ]; then
177 echo "Cannot cd to $PWD/tmp"
182 TESTENV_TEMP_FILES=$PWD
184 if [ ! -d "prev" ]; then
186 if [ $? -ne 0 ]; then
187 echo "Cannot create dir for previous temp files, $PWD/prev"
193 TMPFILES=$(ls -A | grep -vw prev)
194 if [ ! -z "$TMPFILES" ]; then
195 cp -r $TMPFILES prev #Move all temp files to prev dir
196 if [ $? -ne 0 ]; then
197 echo "Cannot move temp files in $PWD to previous temp files in, $PWD/prev"
201 if [ $(pwd | xargs basename) == "tmp" ]; then #Check that current dir is tmp...for safety
203 rm -rf $TMPFILES # Remove all temp files
208 if [ $? -ne 0 ]; then
209 echo "Cannot cd to $curdir"
215 # Create a http message log for this testcase
216 HTTPLOG=$PWD"/.httplog_"$ATC".txt"
219 # Create a log dir for the test case
220 mkdir -p $TESTLOGS/$ATC
222 # Save create for current logs
223 mkdir -p $TESTLOGS/$ATC/previous
225 rm $TESTLOGS/$ATC/previous/*.log &> /dev/null
226 rm $TESTLOGS/$ATC/previous/*.txt &> /dev/null
227 rm $TESTLOGS/$ATC/previous/*.json &> /dev/null
229 mv $TESTLOGS/$ATC/*.log $TESTLOGS/$ATC/previous &> /dev/null
230 mv $TESTLOGS/$ATC/*.txt $TESTLOGS/$ATC/previous &> /dev/null
231 mv $TESTLOGS/$ATC/*.txt $TESTLOGS/$ATC/previous &> /dev/null
233 # Clear the log dir for the test case
234 rm $TESTLOGS/$ATC/*.log &> /dev/null
235 rm $TESTLOGS/$ATC/*.txt &> /dev/null
236 rm $TESTLOGS/$ATC/*.json &> /dev/null
238 #Create result file in the log dir
239 echo "1" > "$TESTLOGS/$ATC/.result$ATC.txt"
241 # Log all output from the test case to a TC log
242 TCLOG=$TESTLOGS/$ATC/TC.log
243 exec &> >(tee ${TCLOG})
245 #Variables for counting tests as well as passed and failed tests
252 #Var to control if current stats shall be printed
253 PRINT_CURRENT_STATS=0
255 #Var to control if container/pod runtim statistics shall be collected
256 COLLECT_RUNTIME_STATS=0
257 COLLECT_RUNTIME_STATS_PID=0
259 #Var to control if endpoint statistics shall be collected
260 COLLECT_ENDPOINT_STATS=0
262 #Var to control if namespaces shall be delete before test setup
263 DELETE_KUBE_NAMESPACES=0
265 #Var to control if containers shall be delete before test setup
268 #Var to configure kubectl from a config file or context
271 #Var pointing to dir mounted to each kubernetes node (master and workers)
272 #Persistent volumes using "hostpath" are allocated beneath the point.
273 #Typically it is a dir on local host mounted to each VM running the master and worker.
274 #So the intention is make this dir available so the PODs can be restarted on any
275 #node and still access the persistent data
276 #If not set from cmd line, the path is defaults to "/tmp"
277 HOST_PATH_BASE_DIR=""
279 #File to keep deviation messages
280 DEVIATION_FILE=".tmp_deviations"
281 rm $DEVIATION_FILE &> /dev/null
283 # Trap "command not found" and make the script fail
286 if [ $? -eq 127 ]; then
287 echo -e $RED"Function not found, setting script to FAIL"$ERED
289 __print_current_stats
294 # Trap to kill subprocess for stats collection (if running)
296 if [ $COLLECT_RUNTIME_STATS_PID -ne 0 ]; then
297 kill $COLLECT_RUNTIME_STATS_PID
305 # Function to log the start of a test case
307 TIMESTAMP=$(date "+%Y-%m-%d %H:%M:%S")
308 echo -e $BOLD"TEST $TEST_SEQUENCE_NR (${BASH_LINENO[1]}): ${FUNCNAME[1]}" $@ $EBOLD
309 echo "TEST $TEST_SEQUENCE_NR - ${TIMESTAMP}: (${BASH_LINENO[1]}): ${FUNCNAME[1]}" $@ >> $HTTPLOG
311 ((TEST_SEQUENCE_NR++))
314 # Function to print current statistics
315 __print_current_stats() {
316 if [ $PRINT_CURRENT_STATS -ne 0 ]; then
317 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"
321 # General function to log a failed test case
322 __log_test_fail_general() {
323 echo -e $RED" FAIL."$1 $ERED
325 __print_current_stats
326 __check_stop_at_error
329 # Function to log a test case failed due to incorrect response code
330 __log_test_fail_status_code() {
331 echo -e $RED" FAIL. Exepected status "$1", got "$2 $3 $ERED
333 __print_current_stats
334 __check_stop_at_error
337 # Function to log a test case failed due to incorrect response body
338 __log_test_fail_body() {
339 echo -e $RED" FAIL, returned body not correct"$ERED
341 __print_current_stats
342 __check_stop_at_error
345 # Function to log a test case that is not supported
346 __log_test_fail_not_supported() {
347 echo -e $RED" FAIL, function not supported"$ERED
349 __print_current_stats
350 __check_stop_at_error
353 # General function to log a passed test case
355 if [ $# -gt 0 ]; then
359 echo -e $GREEN" PASS"$EGREEN
360 __print_current_stats
363 #Counter for configurations
366 # Function to log the start of a configuration setup
368 TIMESTAMP=$(date "+%Y-%m-%d %H:%M:%S")
369 echo -e $BOLD"CONF $CONF_SEQUENCE_NR (${BASH_LINENO[1]}): "${FUNCNAME[1]} $@ $EBOLD
370 echo "CONF $CONF_SEQUENCE_NR - ${TIMESTAMP}: (${BASH_LINENO[1]}): "${FUNCNAME[1]} $@ >> $HTTPLOG
371 ((CONF_SEQUENCE_NR++))
374 # Function to log a failed configuration setup
375 __log_conf_fail_general() {
376 echo -e $RED" FAIL."$1 $ERED
378 __print_current_stats
379 __check_stop_at_error
382 # Function to log a failed configuration setup due to incorrect response code
383 __log_conf_fail_status_code() {
384 echo -e $RED" FAIL. Exepected status "$1", got "$2 $3 $ERED
386 __print_current_stats
387 __check_stop_at_error
390 # Function to log a failed configuration setup due to incorrect response body
391 __log_conf_fail_body() {
392 echo -e $RED" FAIL, returned body not correct"$ERED
394 __print_current_stats
395 __check_stop_at_error
398 # Function to log a configuration that is not supported
399 __log_conf_fail_not_supported() {
400 echo -e $RED" FAIL, function not supported"$ERED$@
402 __print_current_stats
403 __check_stop_at_error
406 # Function to log a passed configuration setup
408 if [ $# -gt 0 ]; then
411 echo -e $GREEN" OK"$EGREEN
412 __print_current_stats
415 # Function to collect stats on endpoints
416 # args: <app-id> <end-point-no> <http-operation> <end-point-url> <http-status> [<count>]
417 __collect_endpoint_stats() {
418 if [ $COLLECT_ENDPOINT_STATS -eq 0 ]; then
422 if [ $# -gt 5 ]; then
425 ENDPOINT_STAT_FILE=$TESTLOGS/$ATC/endpoint_$ATC_$1_$2".log"
428 if [ -f $ENDPOINT_STAT_FILE ]; then
429 ENDPOINT_VAL=$(< $ENDPOINT_STAT_FILE)
430 ENDPOINT_POS=$(echo $ENDPOINT_VAL | cut -f4 -d ' ' | cut -f1 -d '/')
431 ENDPOINT_NEG=$(echo $ENDPOINT_VAL | cut -f5 -d ' ' | cut -f1 -d '/')
434 if [ $5 -ge 200 ] && [ $5 -lt 300 ]; then
435 let ENDPOINT_POS=ENDPOINT_POS+$ENDPOINT_COUNT
437 let ENDPOINT_NEG=ENDPOINT_NEG+$ENDPOINT_COUNT
440 printf '%-2s %-10s %-45s %-16s %-16s' "#" "$3" "$4" "$ENDPOINT_POS/$ENDPOINT_POS" "$ENDPOINT_NEG/$ENDPOINT_NEG" > $ENDPOINT_STAT_FILE
443 # Function to collect stats on endpoints
444 # args: <app-id> <image-info>
445 __collect_endpoint_stats_image_info() {
446 if [ $COLLECT_ENDPOINT_STATS -eq 0 ]; then
449 ENDPOINT_STAT_FILE=$TESTLOGS/$ATC/imageinfo_$ATC_$1".log"
450 echo $A1PMS_IMAGE > $ENDPOINT_STAT_FILE
453 #Var for measuring execution time
454 TCTEST_START=$SECONDS
456 #Vars to hold the start time and timer text for a custom timer
457 TC_TIMER_STARTTIME=""
458 TC_TIMER_TIMER_TEXT=""
459 TC_TIMER_CURRENT_FAILS="" # Then numer of failed test when timer starts.
460 # Compared with the current number of fails at timer stop
461 # to judge the measurement reliability
463 #File to save timer measurement results
464 TIMER_MEASUREMENTS=".timer_measurement.txt"
465 echo -e "Activity \t Duration \t Info" > $TIMER_MEASUREMENTS
467 # If this is set, some images (controlled by the parameter repo-policy) will be re-tagged and pushed to this repo before any
469 IMAGE_REPO_POLICY="local"
472 echo "-------------------------------------------------------------------------------------------------"
473 echo "----------------------------------- Test case: "$ATC
474 echo "----------------------------------- Started: "$(date)
475 echo "-------------------------------------------------------------------------------------------------"
476 echo "-- Description: "$TC_ONELINE_DESCR
477 echo "-------------------------------------------------------------------------------------------------"
478 echo "----------------------------------- Test case setup -----------------------------------"
480 echo "Setting AUTOTEST_HOME="$AUTOTEST_HOME
484 if [ $# -lt 1 ]; then
487 if [ $paramerror -eq 0 ]; then
488 if [ "$1" != "remote" ] && [ "$1" != "remote-remove" ]; then
490 if [ -z "$paramerror_str" ]; then
491 paramerror_str="First arg shall be 'remote' or 'remote-remove'"
497 if [ $paramerror -eq 0 ]; then
498 if [ "$1" != "docker" ] && [ "$1" != "kube" ]; then
500 if [ -z "$paramerror_str" ]; then
501 paramerror_str="Second arg shall be 'docker' or 'kube'"
504 if [ $1 == "docker" ]; then
506 echo "Setting RUNMODE=DOCKER"
508 if [ $1 == "kube" ]; then
510 echo "Setting RUNMODE=KUBE"
516 while [ $paramerror -eq 0 ] && [ $foundparm -eq 0 ]; do
518 if [ $paramerror -eq 0 ]; then
519 if [ "$1" == "release" ]; then
520 IMAGE_CATEGORY="RELEASE"
521 echo "Option set - Release image tags used for applicable images "
526 if [ $paramerror -eq 0 ]; then
527 if [ "$1" == "auto-clean" ]; then
529 echo "Option set - Auto clean at end of test script"
534 if [ $paramerror -eq 0 ]; then
535 if [ "$1" == "--stop-at-error" ]; then
537 echo "Option set - Stop at first error"
542 if [ $paramerror -eq 0 ]; then
543 if [ "$1" == "--ricsim-prefix" ]; then
545 TMP_RIC_SIM_PREFIX=$1 #RIC_SIM_PREFIX need to be updated after sourcing of the env file
548 if [ -z "$paramerror_str" ]; then
549 paramerror_str="No prefix found for flag: '--ricsim-prefix'"
552 echo "Option set - Overriding RIC_SIM_PREFIX with: "$1
558 if [ $paramerror -eq 0 ]; then
559 if [ "$1" == "--env-file" ]; then
564 if [ -z "$paramerror_str" ]; then
565 paramerror_str="No env file found for flag: '--env-file'"
568 echo "Option set - Reading test env from: "$1
574 if [ $paramerror -eq 0 ]; then
575 if [ "$1" == "--use-local-image" ]; then
578 while [ $# -gt 0 ] && [[ "$1" != "--"* ]]; do
579 USE_LOCAL_IMAGES=$USE_LOCAL_IMAGES" "$1
580 if [[ "$AVAILABLE_IMAGES_OVERRIDE" != *"$1"* ]]; then
582 if [ -z "$paramerror_str" ]; then
583 paramerror_str="App name $1 is not available for local override for flag: '--use-local-image'"
589 if [ -z "$USE_LOCAL_IMAGES" ]; then
591 if [ -z "$paramerror_str" ]; then
592 paramerror_str="No app name found for flag: '--use-local-image'"
595 echo "Option set - Overriding with local images for app(s):"$USE_LOCAL_IMAGES
599 if [ $paramerror -eq 0 ]; then
600 if [ "$1" == "--use-snapshot-image" ]; then
601 USE_SNAPSHOT_IMAGES=""
603 while [ $# -gt 0 ] && [[ "$1" != "--"* ]]; do
604 USE_SNAPSHOT_IMAGES=$USE_SNAPSHOT_IMAGES" "$1
605 if [[ "$AVAILABLE_IMAGES_OVERRIDE" != *"$1"* ]]; then
607 if [ -z "$paramerror_str" ]; then
608 paramerror_str="App name $1 is not available for snapshot override for flag: '--use-snapshot-image'"
614 if [ -z "$USE_SNAPSHOT_IMAGES" ]; then
616 if [ -z "$paramerror_str" ]; then
617 paramerror_str="No app name found for flag: '--use-snapshot-image'"
620 echo "Option set - Overriding with snapshot images for app(s):"$USE_SNAPSHOT_IMAGES
624 if [ $paramerror -eq 0 ]; then
625 if [ "$1" == "--use-staging-image" ]; then
626 USE_STAGING_IMAGES=""
628 while [ $# -gt 0 ] && [[ "$1" != "--"* ]]; do
629 USE_STAGING_IMAGES=$USE_STAGING_IMAGES" "$1
630 if [[ "$AVAILABLE_IMAGES_OVERRIDE" != *"$1"* ]]; then
632 if [ -z "$paramerror_str" ]; then
633 paramerror_str="App name $1 is not available for staging override for flag: '--use-staging-image'"
639 if [ -z "$USE_STAGING_IMAGES" ]; then
641 if [ -z "$paramerror_str" ]; then
642 paramerror_str="No app name found for flag: '--use-staging-image'"
645 echo "Option set - Overriding with staging images for app(s):"$USE_STAGING_IMAGES
649 if [ $paramerror -eq 0 ]; then
650 if [ "$1" == "--use-release-image" ]; then
651 USE_RELEASE_IMAGES=""
653 while [ $# -gt 0 ] && [[ "$1" != "--"* ]]; do
654 USE_RELEASE_IMAGES=$USE_RELEASE_IMAGES" "$1
655 if [[ "$AVAILABLE_IMAGES_OVERRIDE" != *"$1"* ]]; then
657 if [ -z "$paramerror_str" ]; then
658 paramerror_str="App name $1 is not available for release override for flag: '--use-release-image'"
664 if [ -z "$USE_RELEASE_IMAGES" ]; then
666 if [ -z "$paramerror_str" ]; then
667 paramerror_str="No app name found for flag: '--use-release-image'"
670 echo "Option set - Overriding with release images for app(s):"$USE_RELEASE_IMAGES
674 if [ $paramerror -eq 0 ]; then
675 if [ "$1" == "--image-repo" ]; then
680 if [ -z "$paramerror_str" ]; then
681 paramerror_str="No image repo url found for : '--image-repo'"
684 echo "Option set - Image repo url: "$1
690 if [ $paramerror -eq 0 ]; then
691 if [ "$1" == "--repo-policy" ]; then
696 if [ -z "$paramerror_str" ]; then
697 paramerror_str="No policy found for : '--repo-policy'"
700 if [ "$1" == "local" ] || [ "$1" == "remote" ]; then
701 echo "Option set - Image repo policy: "$1
706 if [ -z "$paramerror_str" ]; then
707 paramerror_str="Repo policy shall be 'local' or 'remote'"
713 if [ $paramerror -eq 0 ]; then
714 if [ "$1" == "--cluster-timeout" ]; then
719 if [ -z "$paramerror_str" ]; then
720 paramerror_str="No timeout value found for : '--cluster-timeout'"
723 #Check if positive int
724 case ${CLUSTER_TIME_OUT#[+]} in
727 if [ -z "$paramerror_str" ]; then
728 paramerror_str="Value for '--cluster-timeout' not an int : "$CLUSTER_TIME_OUT
733 echo "Option set - Cluster timeout: "$1
739 if [ $paramerror -eq 0 ]; then
740 if [ "$1" == "--override" ]; then
742 TEST_ENV_VAR_FILE_OVERRIDE=$1
745 if [ -z "$paramerror_str" ]; then
746 paramerror_str="No env file found for flag: '--override'"
749 if [ ! -f $TEST_ENV_VAR_FILE_OVERRIDE ]; then
751 if [ -z "$paramerror_str" ]; then
752 paramerror_str="File for '--override' does not exist : "$TEST_ENV_VAR_FILE_OVERRIDE
755 echo "Option set - Override env from: "$1
761 if [ $paramerror -eq 0 ]; then
762 if [ "$1" == "--pre-clean" ]; then
764 echo "Option set - Pre-clean of kube/docker resouces"
769 if [ $paramerror -eq 0 ]; then
770 if [ "$1" == "--print-stats" ]; then
771 PRINT_CURRENT_STATS=1
772 echo "Option set - Print stats after every test-case and config"
777 if [ $paramerror -eq 0 ]; then
778 if [ "$1" == "--gen-stats" ]; then
779 COLLECT_RUNTIME_STATS=1
780 echo "Option set - Collect runtime statistics"
785 if [ $paramerror -eq 0 ]; then
786 if [ "$1" == "--delete-namespaces" ]; then
787 if [ $RUNMODE == "DOCKER" ]; then
788 DELETE_KUBE_NAMESPACES=0
789 echo "Option ignored - Delete namespaces (ignored when running docker)"
791 if [ -z "KUBE_PRESTARTED_IMAGES" ]; then
792 DELETE_KUBE_NAMESPACES=0
793 echo "Option ignored - Delete namespaces (ignored when using prestarted apps)"
795 DELETE_KUBE_NAMESPACES=1
796 echo "Option set - Delete namespaces"
803 if [ $paramerror -eq 0 ]; then
804 if [ "$1" == "--delete-containers" ]; then
805 if [ $RUNMODE == "DOCKER" ]; then
807 echo "Option set - Delete containers started by previous test(s)"
809 echo "Option ignored - Delete containers (ignored when running kube)"
815 if [ $paramerror -eq 0 ]; then
816 if [ "$1" == "--endpoint-stats" ]; then
817 COLLECT_ENDPOINT_STATS=1
818 echo "Option set - Collect endpoint statistics"
823 if [ $paramerror -eq 0 ]; then
824 if [ "$1" == "--kubeconfig" ]; then
828 if [ -z "$paramerror_str" ]; then
829 paramerror_str="No path found for : '--kubeconfig'"
833 if [ ! -z "$KUBECONF" ]; then
835 if [ -z "$paramerror_str" ]; then
836 paramerror_str="Only one of --kubeconfig/--kubecontext can be set"
839 KUBECONF="--kubeconfig $1"
840 echo "Option set - Kubeconfig path: "$1
846 if [ -z "$paramerror_str" ]; then
847 paramerror_str="File $1 for --kubeconfig not found"
853 if [ $paramerror -eq 0 ]; then
854 if [ "$1" == "--kubecontext" ]; then
858 if [ -z "$paramerror_str" ]; then
859 paramerror_str="No context-name found for : '--kubecontext'"
862 if [ ! -z "$KUBECONF" ]; then
864 if [ -z "$paramerror_str" ]; then
865 paramerror_str="Only one of --kubeconfig or --kubecontext can be set"
868 KUBECONF="--context $1"
869 echo "Option set - Kubecontext name: "$1
876 if [ $paramerror -eq 0 ]; then
877 if [ "$1" == "--host-path-dir" ]; then
881 if [ -z "$paramerror_str" ]; then
882 paramerror_str="No path found for : '--host-path-dir'"
885 HOST_PATH_BASE_DIR=$1
895 if [ $paramerror -eq 0 ] && [ $# -gt 0 ]; then
897 if [ -z "$paramerror_str" ]; then
898 paramerror_str="Unknown parameter(s): "$@
902 if [ $paramerror -eq 1 ]; then
903 echo -e $RED"Incorrect arg list: "$paramerror_str$ERED
909 LOCALHOST_NAME="localhost"
910 # if [ ! -z "$DOCKER_HOST" ]; then
911 # LOCALHOST_NAME=$(echo $DOCKER_HOST | awk -F[/:] '{print $4}' )
913 LOCALHOST_HTTP="http://$LOCALHOST_NAME"
914 LOCALHOST_HTTPS="https://$LOCALHOST_NAME"
916 # sourcing the selected env variables for the test case
917 if [ -f "$TEST_ENV_VAR_FILE" ]; then
918 echo -e $BOLD"Sourcing env vars from: "$TEST_ENV_VAR_FILE$EBOLD
920 if [ ! -z "$TEST_ENV_VAR_FILE_OVERRIDE" ]; then
921 echo -e $BOLD"Sourcing override env vars from: "$TEST_ENV_VAR_FILE_OVERRIDE$EBOLD
922 . $TEST_ENV_VAR_FILE_OVERRIDE
925 if [ -z "$TEST_ENV_PROFILE" ] || [ -z "$SUPPORTED_PROFILES" ]; then
926 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
929 for prof in $SUPPORTED_PROFILES; do
930 if [ "$TEST_ENV_PROFILE" == "$prof" ]; then
931 echo -e $GREEN"Test case supports the selected test env file"$EGREEN
935 if [ $found_profile -ne 1 ]; then
936 echo -e $RED"Test case does not support the selected test env file"$ERED
937 echo "Profile: "$TEST_ENV_PROFILE" Supported profiles: "$SUPPORTED_PROFILES
938 echo -e $RED"Exiting...."$ERED
943 echo -e $RED"Selected env var file does not exist: "$TEST_ENV_VAR_FILE$ERED
944 echo " Select one of following env var file matching the intended target of the test"
945 echo " Restart the test using the flag '--env-file <path-to-env-file>"
946 ls $AUTOTEST_HOME/../common/test_env* | indent1
950 #This var need be preserved from the command line option, if set, when env var is sourced.
951 if [ ! -z "$TMP_RIC_SIM_PREFIX" ]; then
952 RIC_SIM_PREFIX=$TMP_RIC_SIM_PREFIX
955 if [ -z "$PROJECT_IMAGES_APP_NAMES" ]; then
956 echo -e $RED"Var PROJECT_IMAGES_APP_NAMES must be defined in: "$TEST_ENV_VAR_FILE $ERED
960 if [[ $SUPPORTED_RUNMODES != *"$RUNMODE"* ]]; then
961 echo -e $RED"This test script does not support RUNMODE $RUNMODE"$ERED
962 echo "Supported RUNMODEs: "$SUPPORTED_RUNMODES
966 # Choose list of included apps depending on run-mode
967 if [ $RUNMODE == "KUBE" ]; then
968 INCLUDED_IMAGES=$KUBE_INCLUDED_IMAGES
970 INCLUDED_IMAGES=$DOCKER_INCLUDED_IMAGES
974 # auto adding system apps
976 echo -e $BOLD"Auto adding system apps"$EBOLD
977 if [ $RUNMODE == "KUBE" ]; then
978 INCLUDED_IMAGES=$INCLUDED_IMAGES" "$TESTENV_KUBE_SYSTEM_APPS
979 TMP_APPS=$TESTENV_KUBE_SYSTEM_APPS
981 INCLUDED_IMAGES=$INCLUDED_IMAGES" "$TESTENV_DOCKER_SYSTEM_APPS
982 TMP_APPS=$TESTENV_DOCKER_SYSTEM_APPS
984 if [ ! -z "$TMP_APPS" ]; then
985 for iapp in "$TMP_APPS"; do
986 file_pointer=$(echo $iapp | tr '[:upper:]' '[:lower:]')
987 file_pointer="../common/"$file_pointer"_api_functions.sh"
989 while [ ${#padded_iapp} -lt 16 ]; do
990 padded_iapp=$padded_iapp" "
992 echo " Auto-adding system app $padded_iapp Sourcing $file_pointer"
994 if [ $? -ne 0 ]; then
995 echo " Include file $file_pointer contain errors. Exiting..."
998 __added_apps=" $iapp "$__added_apps
1004 if [ $RUNMODE == "KUBE" ]; then
1005 TMP_APPS=$INCLUDED_IMAGES" "$KUBE_PRESTARTED_IMAGES
1007 TMP_APPS=$INCLUDED_IMAGES
1010 echo -e $BOLD"Auto adding included apps"$EBOLD
1011 for iapp in $TMP_APPS; do
1012 if [[ "$__added_apps" != *"$iapp"* ]]; then
1013 file_pointer=$(echo $iapp | tr '[:upper:]' '[:lower:]')
1014 file_pointer="../common/"$file_pointer"_api_functions.sh"
1016 while [ ${#padded_iapp} -lt 16 ]; do
1017 padded_iapp=$padded_iapp" "
1019 echo " Auto-adding included app $padded_iapp Sourcing $file_pointer"
1020 if [ ! -f "$file_pointer" ]; then
1021 echo " Include file $file_pointer for app $iapp does not exist"
1025 if [ $? -ne 0 ]; then
1026 echo " Include file $file_pointer contain errors. Exiting..."
1033 echo -e $BOLD"Test environment info"$EBOLD
1035 # Check needed installed sw
1038 if [ $? -ne 0 ] || [ -z "$tmp" ]; then
1039 echo -e $RED"bash is required to run the test environment, pls install"$ERED
1042 echo " bash is installed and using version:"
1043 echo "$(bash --version)" | indent2
1045 tmp=$(which python3)
1046 if [ $? -ne 0 ] || [ -z "$tmp" ]; then
1047 echo -e $RED"python3 is required to run the test environment, pls install"$ERED
1050 echo " python3 is installed and using version: $(python3 --version)"
1053 if [ $? -ne 0 ] || [ -z "$tmp" ]; then
1054 echo -e $RED"docker is required to run the test environment, pls install"$ERED
1057 echo " docker is installed and using versions:"
1058 echo " $(docker version --format 'Client version {{.Client.Version}} Server version {{.Server.Version}}')"
1060 if [ $RUNMODE == "DOCKER" ]; then
1061 tmp=$(which docker-compose)
1062 if [ $? -ne 0 ] || [ -z "$tmp" ]; then
1063 echo -e $RED"docker-compose is required to run the test environment, pls install"$ERED
1066 tmp=$(docker-compose version --short)
1067 echo " docker-compose installed and using version $tmp"
1068 if [[ "$tmp" == *'v2'* ]]; then
1069 DOCKER_COMPOSE_VERION="V2"
1073 if [ $RUNMODE == "KUBE" ]; then
1074 tmp=$(which kubectl)
1075 if [ $? -ne 0 ] || [ -z tmp ]; then
1076 echo -e $RED"kubectl is required to run the test environment in kubernetes mode, pls install"$ERED
1079 echo " kubectl is installed and using versions:"
1080 echo $(kubectl $KUBECONF version --short=true) | indent2
1081 res=$(kubectl $KUBECONF cluster-info 2>&1)
1082 if [ $? -ne 0 ]; then
1083 echo -e "$BOLD$RED############################################# $ERED$EBOLD"
1084 echo -e $BOLD$RED"Command 'kubectl '$KUBECONF' cluster-info' returned error $ERED$EBOLD"
1085 echo -e "$BOLD$RED############################################# $ERED$EBOLD"
1087 echo "kubectl response:"
1090 echo "This script may have been started with user with no permission to run kubectl"
1091 echo "Try running with 'sudo', set env KUBECONFIG or set '--kubeconfig' parameter"
1092 echo "Do either 1, 2 or 3 "
1095 echo "Run with sudo"
1096 echo -e $BOLD"sudo <test-script-and-parameters>"$EBOLD
1099 echo "Export KUBECONFIG and pass env to sudo - (replace user)"
1100 echo -e $BOLD"export KUBECONFIG='/home/<user>/.kube/config'"$EBOLD
1101 echo -e $BOLD"sudo -E <test-script-and-parameters>"$EBOLD
1104 echo "Set KUBECONFIG via script parameter"
1105 echo -e $BOLD"sudo ... --kubeconfig /home/<user>/.kube/<config-file> ...."$EBOLD
1106 echo "The config file need to downloaded from the cluster"
1110 echo " Node(s) and container runtime config"
1111 kubectl $KUBECONF get nodes -o wide | indent2
1113 if [ -z "$HOST_PATH_BASE_DIR" ]; then
1114 HOST_PATH_BASE_DIR="/tmp"
1115 echo " Persistent volumes will be mounted to $HOST_PATH_BASE_DIR on applicable node"
1116 echo " No guarantee that persistent volume data is available on all nodes in the cluster"
1118 echo "Persistent volumes will be mounted to base dir: $HOST_PATH_BASE_DIR"
1119 echo "Assuming this dir is mounted from each node to a dir on the localhost or other"
1120 echo "file system available to all nodes"
1127 echo -e $BOLD"Checking configured image setting for this test case"$EBOLD
1129 #Temp var to check for image variable name errors
1131 #Create a file with image info for later printing as a table
1132 image_list_file="./tmp/.image-list"
1133 echo -e "Application\tApp short name\tImage\ttag\ttag-switch" > $image_list_file
1135 # Check if image env var is set and if so export the env var with image to use (used by docker compose files)
1136 # arg: <app-short-name> <target-variable-name> <image-variable-name> <image-tag-variable-name> <tag-suffix> <image name>
1137 __check_and_create_image_var() {
1139 if [ $# -ne 6 ]; then
1140 echo "Expected arg: <app-short-name> <target-variable-name> <image-variable-name> <image-tag-variable-name> <tag-suffix> <image name>"
1145 __check_included_image $1
1146 if [ $? -ne 0 ]; then
1147 echo -e "$6\t$1\t<image-excluded>\t<no-tag>" >> $image_list_file
1148 # Image is excluded since the corresponding app is not used in this test
1151 tmp=${6}"\t"${1}"\t"
1152 #Create var from the input var names
1157 optional_image_repo_target=""
1159 if [ -z $image ]; then
1160 __check_ignore_image $1
1161 if [ $? -eq 0 ]; then
1163 if [ -z "$6" ]; then
1164 app_ds="<app ignored>"
1166 echo -e "$app_ds\t$1\t<image-ignored>\t<no-tag>" >> $image_list_file
1167 # Image is ignored since the corresponding the images is not set in the env file
1168 __remove_included_image $1 # Remove the image from the list of included images
1171 echo -e $RED"\$"$3" not set in $TEST_ENV_VAR_FILE"$ERED
1174 tmp=$tmp"<no-image>\t"
1177 optional_image_repo_target=$image
1179 #Add repo depending on image type
1180 if [ "$5" == "REMOTE_RELEASE" ]; then
1181 image=$NEXUS_RELEASE_REPO$image
1183 if [ "$5" == "REMOTE" ]; then
1184 image=$NEXUS_STAGING_REPO$image
1186 if [ "$5" == "REMOTE_SNAPSHOT" ]; then
1187 image=$NEXUS_SNAPSHOT_REPO$image
1189 if [ "$5" == "REMOTE_PROXY" ]; then
1190 image=$NEXUS_PROXY_REPO$image
1192 if [ "$5" == "REMOTE_RELEASE_ONAP" ]; then
1193 image=$NEXUS_RELEASE_REPO_ONAP$image
1195 if [ "$5" == "REMOTE_RELEASE_ORAN" ]; then
1196 image=$NEXUS_RELEASE_REPO_ORAN$image
1198 #No nexus repo added for local images, tag: LOCAL
1201 if [ -z $tag ]; then
1202 echo -e $RED"\$"$tmptag" not set in $TEST_ENV_VAR_FILE"$ERED
1205 tmp=$tmp"<no-tag>\t"
1210 echo -e "$tmp" >> $image_list_file
1212 export "${2}"=$image":"$tag #Note, this var may be set to the value of the target value below in __check_and_pull_image
1214 remote_or_local_push=false
1215 if [ ! -z "$IMAGE_REPO_ADR" ] && [[ $5 != *"PROXY"* ]]; then
1216 if [ $5 == "LOCAL" ]; then
1217 remote_or_local_push=true
1219 if [[ $5 == *"REMOTE"* ]]; then
1220 if [ "$IMAGE_REPO_POLICY" == "remote" ]; then
1221 remote_or_local_push=true
1225 if $remote_or_local_push; then # Only re-tag and push images according to policy, if repo is given
1226 export "${2}_SOURCE"=$image":"$tag #Var to keep the actual source image
1227 if [[ $optional_image_repo_target == *"/"* ]]; then # Replace all / with _ for images to push to external repo
1228 optional_image_repo_target_tmp=${optional_image_repo_target//\//_}
1229 optional_image_repo_target=$optional_image_repo_target_tmp
1231 export "${2}_TARGET"=$IMAGE_REPO_ADR"/"$optional_image_repo_target":"$tag #Create image + tag for optional image repo - pushed later if needed
1233 export "${2}_SOURCE"=""
1234 export "${2}_TARGET"=""
1238 # Check if app uses image included in this test run
1239 # Returns 0 if image is included, 1 if not
1240 __check_included_image() {
1241 for im in $INCLUDED_IMAGES; do
1242 if [ "$1" == "$im" ]; then
1249 # Check if app uses a project image
1250 # Returns 0 if image is included, 1 if not
1251 __check_project_image() {
1252 for im in $PROJECT_IMAGES; do
1253 if [ "$1" == "$im" ]; then
1260 # Check if app uses image built by the test script
1261 # Returns 0 if image is included, 1 if not
1262 __check_image_local_build() {
1263 for im in $LOCAL_IMAGE_BUILD; do
1264 if [ "$1" == "$im" ]; then
1271 # Check if app image is conditionally ignored in this test run
1272 # Returns 0 if image is conditionally ignored, 1 if not
1273 __check_ignore_image() {
1274 for im in $CONDITIONALLY_IGNORED_IMAGES; do
1275 if [ "$1" == "$im" ]; then
1282 # Removed image from included list of included images
1283 # Used when an image is marked as conditionally ignored
1284 __remove_included_image() {
1286 for im in $INCLUDED_IMAGES; do
1287 if [ "$1" != "$im" ]; then
1288 tmp_img_rem_list=$tmp_img_rem_list" "$im
1291 INCLUDED_IMAGES=$tmp_img_rem_list
1295 # Check if app is included in the prestarted set of apps
1296 # Returns 0 if image is included, 1 if not
1297 __check_prestarted_image() {
1298 for im in $KUBE_PRESTARTED_IMAGES; do
1299 if [ "$1" == "$im" ]; then
1306 # Check if an app shall use a local image, based on the cmd parameters
1307 __check_image_local_override() {
1308 for im in $USE_LOCAL_IMAGES; do
1309 if [ "$1" == "$im" ]; then
1316 # Check if app uses image override
1317 # Returns the image/tag suffix LOCAL for local image or REMOTE/REMOTE_RELEASE/REMOTE_SNAPSHOT for staging/release/snapshot image
1318 __check_image_override() {
1320 for im in $ORAN_IMAGES_APP_NAMES; do
1321 if [ "$1" == "$im" ]; then
1322 echo "REMOTE_RELEASE_ORAN"
1327 for im in $ONAP_IMAGES_APP_NAMES; do
1328 if [ "$1" == "$im" ]; then
1329 echo "REMOTE_RELEASE_ONAP"
1335 for im in $PROJECT_IMAGES_APP_NAMES; do
1336 if [ "$1" == "$im" ]; then
1341 if [ $found -eq 0 ]; then
1347 if [ $IMAGE_CATEGORY == "RELEASE" ]; then
1348 suffix="REMOTE_RELEASE"
1350 if [ $IMAGE_CATEGORY == "DEV" ]; then
1354 for im in $USE_STAGING_IMAGES; do
1355 if [ "$1" == "$im" ]; then
1360 for im in $USE_RELEASE_IMAGES; do
1361 if [ "$1" == "$im" ]; then
1362 suffix="REMOTE_RELEASE"
1366 for im in $USE_SNAPSHOT_IMAGES; do
1367 if [ "$1" == "$im" ]; then
1368 suffix="REMOTE_SNAPSHOT"
1372 for im in $USE_LOCAL_IMAGES; do
1373 if [ "$1" == "$im" ]; then
1379 if [ $CTR -gt 1 ]; then
1385 # Function to re-tag and image and push to another image repo
1386 __retag_and_push_image() {
1387 if [ ! -z "$IMAGE_REPO_ADR" ]; then
1388 source_image="${!1}"
1389 trg_var_name=$1_"TARGET" # This var is created in func __check_and_create_image_var
1390 target_image="${!trg_var_name}"
1392 if [ -z $target_image ]; then
1393 return 0 # Image with no target shall not be pushed
1396 echo -ne " Attempt to re-tag image to: ${BOLD}${target_image}${EBOLD}${SAMELINE}"
1397 tmp=$(docker image tag $source_image ${target_image} )
1398 if [ $? -ne 0 ]; then
1399 docker stop $tmp &> ./tmp/.dockererr
1402 echo -e " Attempt to re-tag image to: ${BOLD}${target_image}${EBOLD} - ${RED}Failed${ERED}"
1403 cat ./tmp/.dockererr
1406 echo -e " Attempt to re-tag image to: ${BOLD}${target_image}${EBOLD} - ${GREEN}OK${EGREEN}"
1408 echo -ne " Attempt to push re-tagged image: ${BOLD}${target_image}${EBOLD}${SAMELINE}"
1409 tmp=$(docker push ${target_image} )
1410 if [ $? -ne 0 ]; then
1411 docker stop $tmp &> ./tmp/.dockererr
1414 echo -e " Attempt to push re-tagged image: ${BOLD}${target_image}${EBOLD} - ${RED}Failed${ERED}"
1415 cat ./tmp/.dockererr
1418 echo -e " Attempt to push re-tagged image: ${BOLD}${target_image}${EBOLD} - ${GREEN}OK${EGREEN}"
1420 export "${1}"=$target_image
1425 #Function to check if image exist and stop+remove the container+pull new images as needed
1426 #args <script-start-arg> <descriptive-image-name> <container-base-name> <image-with-tag-var-name>
1427 __check_and_pull_image() {
1429 source_image="${!4}"
1431 echo -e " Checking $BOLD$2$EBOLD container(s) with basename: $BOLD$3$EBOLD using image: $BOLD$source_image$EBOLD"
1432 format_string="\"{{.Repository}}\\t{{.Tag}}\\t{{.CreatedSince}}\\t{{.Size}}\""
1433 tmp_im=$(docker images --format $format_string $source_image)
1435 if [ $1 == "local" ]; then
1436 if [ -z "$tmp_im" ]; then
1437 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
1441 echo -e " "$2" (local image): \033[1m"$source_image"\033[0m "$GREEN"OK"$EGREEN
1443 elif [ $1 == "remote" ] || [ $1 == "remote-remove" ]; then
1444 if [ $1 == "remote-remove" ]; then
1445 if [ $RUNMODE == "DOCKER" ]; then
1446 echo -ne " Attempt to stop and remove container(s), if running - ${SAMELINE}"
1447 tmp=$(docker ps -aq --filter name=${3} --filter network=${DOCKER_SIM_NWNAME})
1448 if [ $? -eq 0 ] && [ ! -z "$tmp" ]; then
1449 docker stop $tmp &> ./tmp/.dockererr
1450 if [ $? -ne 0 ]; then
1453 echo -e $RED" Container(s) could not be stopped - try manual stopping the container(s)"$ERED
1454 cat ./tmp/.dockererr
1458 echo -ne " Attempt to stop and remove container(s), if running - "$GREEN"stopped"$EGREEN"${SAMELINE}"
1459 tmp=$(docker ps -aq --filter name=${3} --filter network=${DOCKER_SIM_NWNAME}) &> /dev/null
1460 if [ $? -eq 0 ] && [ ! -z "$tmp" ]; then
1461 docker rm $tmp &> ./tmp/.dockererr
1462 if [ $? -ne 0 ]; then
1465 echo -e $RED" Container(s) could not be removed - try manual removal of the container(s)"$ERED
1466 cat ./tmp/.dockererr
1470 echo -e " Attempt to stop and remove container(s), if running - "$GREEN"stopped removed"$EGREEN
1476 if [ -z "$tmp_im" ]; then
1477 echo -ne " Pulling image${SAMELINE}"
1478 out=$(docker pull $source_image)
1479 if [ $? -ne 0 ]; then
1481 echo -e " Pulling image -$RED could not be pulled"$ERED
1483 echo $out > ./tmp/.dockererr
1487 echo $out > ./tmp/.dockererr
1488 if [[ $out == *"up to date"* ]]; then
1489 echo -e " Pulling image -$GREEN Image is up to date $EGREEN"
1490 elif [[ $out == *"Downloaded newer image"* ]]; then
1491 echo -e " Pulling image -$GREEN Newer image pulled $EGREEN"
1493 echo -e " Pulling image -$GREEN Pulled $EGREEN"
1496 echo -e " Pulling image -$GREEN OK $EGREEN(exists in local repository)"
1500 __retag_and_push_image $4
1505 setup_testenvironment() {
1506 # Check that image env setting are available
1509 # Image var setup for all project images included in the test
1510 for imagename in $APP_SHORT_NAMES; do
1511 __check_included_image $imagename
1513 __check_project_image $imagename
1515 if [ $incl -eq 0 ]; then
1516 if [ $proj -eq 0 ]; then
1517 IMAGE_SUFFIX=$(__check_image_override $imagename)
1518 if [ $? -ne 0 ]; then
1519 echo -e $RED"Image setting from cmd line not consistent for $imagename."$ERED
1525 # A function name is created from the app short name
1526 # for example app short name 'ICS' -> produce the function
1527 # name __ICS_imagesetup
1528 # This function is called and is expected to exist in the imported
1529 # file for the ics test functions
1530 # The resulting function impl will call '__check_and_create_image_var' function
1531 # with appropriate parameters
1532 # If the image suffix is none, then the component decides the suffix
1533 function_pointer="__"$imagename"_imagesetup"
1534 $function_pointer $IMAGE_SUFFIX
1536 function_pointer="__"$imagename"_test_requirements"
1541 #Errors in image setting - exit
1542 if [ $IMAGE_ERR -ne 0 ]; then
1546 #Print a tables of the image settings
1547 echo -e $BOLD"Images configured for start arg: "$START_ARG $EBOLD
1548 column -t -s $'\t' $image_list_file | indent1
1552 #Set the SIM_GROUP var
1553 echo -e $BOLD"Setting var to main dir of all container/simulator scripts"$EBOLD
1554 if [ -z "$SIM_GROUP" ]; then
1555 SIM_GROUP=$AUTOTEST_HOME/../simulator-group
1556 if [ ! -d $SIM_GROUP ]; then
1557 echo "Trying to set env var SIM_GROUP to dir 'simulator-group' in the nontrtric repo, but failed."
1558 echo -e $RED"Please set the SIM_GROUP manually in the applicable $TEST_ENV_VAR_FILE"$ERED
1561 echo " SIM_GROUP auto set to: " $SIM_GROUP
1563 elif [ $SIM_GROUP = *simulator_group ]; then
1564 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
1567 echo " SIM_GROUP env var already set to: " $SIM_GROUP
1572 #Temp var to check for image pull errors
1576 echo -e $BOLD"Deleting namespaces"$EBOLD
1579 if [ "$DELETE_KUBE_NAMESPACES" -eq 1 ]; then
1580 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
1581 if [ $? -ne 0 ]; then
1582 echo " Cannot get list of namespaces...ignoring delete"
1584 for test_env_ns in $test_env_namespaces; do
1585 __kube_delete_namespace $test_env_ns
1589 echo " Namespace delete option not set or ignored"
1594 echo -e $BOLD"Deleting containers"$EBOLD
1596 if [ "$DELETE_CONTAINERS" -eq 1 ]; then
1597 echo " Stopping containers label 'nrttest_app'..."
1598 docker stop $(docker ps -qa --filter "label=nrttest_app") 2> /dev/null
1599 echo " Removing stopped containers..."
1600 docker rm $(docker ps -qa --filter "label=nrttest_app") 2> /dev/null
1602 echo " Contatiner delete option not set or ignored"
1606 # The following sequence pull the configured images
1607 echo -e $BOLD"Pulling configured images, if needed"$EBOLD
1608 if [ ! -z "$IMAGE_REPO_ADR" ] && [ $IMAGE_REPO_POLICY == "local" ]; then
1609 echo -e $YELLOW" Excluding all remote image check/pull when running with image repo: $IMAGE_REPO_ADR and image policy $IMAGE_REPO_POLICY"$EYELLOW
1611 for imagename in $APP_SHORT_NAMES; do
1612 __check_included_image $imagename
1614 __check_project_image $imagename
1616 if [ $incl -eq 0 ]; then
1617 if [ $proj -eq 0 ]; then
1618 START_ARG_MOD=$START_ARG
1619 __check_image_local_override $imagename
1620 if [ $? -eq 1 ]; then
1621 START_ARG_MOD="local"
1624 START_ARG_MOD=$START_ARG
1626 __check_image_local_build $imagename
1627 #No pull of images built locally
1628 if [ $? -ne 0 ]; then
1629 # A function name is created from the app short name
1630 # for example app short name 'HTTPPROXY' -> produce the function
1631 # name __HTTPPROXY_imagesetup
1632 # This function is called and is expected to exist in the imported
1633 # file for the httpproxy test functions
1634 # The resulting function impl will call '__check_and_pull_image' function
1635 # with appropriate parameters
1636 function_pointer="__"$imagename"_imagepull"
1637 $function_pointer $START_ARG_MOD $START_ARG
1640 echo -e $YELLOW" Excluding $imagename image from image check/pull"$EYELLOW
1645 #Errors in image setting - exit
1646 if [ $IMAGE_ERR -ne 0 ]; then
1648 echo "#################################################################################################"
1649 echo -e $RED"One or more images could not be pulled or containers using the images could not be stopped/removed"$ERED
1650 echo -e $RED"Or local image, overriding remote image, does not exist"$ERED
1651 if [ $IMAGE_CATEGORY == "DEV" ]; then
1653 echo -e $RED"Note that SNAPSHOT and staging images may be purged from nexus after a certain period."$ERED
1654 echo -e $RED"In addition, the image may not have been updated in the current release so no SNAPSHOT or staging image exists"$ERED
1655 echo -e $RED"In these cases, switch to use a released image instead, use the flag '--use-release-image <App-short-name>'"$ERED
1656 echo -e $RED"Use the 'App-short-name' for the applicable image from the above table: 'Images configured for start arg'."$ERED
1658 echo "#################################################################################################"
1665 echo -e $BOLD"Building images needed for test"$EBOLD
1667 for imagename in $APP_SHORT_NAMES; do
1668 cd $AUTOTEST_HOME #Always reset to orig dir
1669 __check_image_local_build $imagename
1670 if [ $? -eq 0 ]; then
1671 __check_included_image $imagename
1672 if [ $? -eq 0 ]; then
1673 # A function name is created from the app short name
1674 # for example app short name 'MR' -> produce the function
1675 # name __MR_imagebuild
1676 # This function is called and is expected to exist in the imported
1677 # file for the mr test functions
1678 # The resulting function impl shall build the imagee
1679 function_pointer="__"$imagename"_imagebuild"
1683 echo -e $YELLOW" Excluding image for app $imagename from image build"$EYELLOW
1688 cd $AUTOTEST_HOME # Just to make sure...
1692 # Create a table of the images used in the script - from local repo
1693 echo -e $BOLD"Local docker registry images used in this test script"$EBOLD
1695 docker_tmp_file=./tmp/.docker-images-table
1696 format_string="{{.Repository}}\\t{{.Tag}}\\t{{.CreatedSince}}\\t{{.Size}}\\t{{.CreatedAt}}"
1697 echo -e "Application\tRepository\tTag\tCreated since\tSize\tCreated at" > $docker_tmp_file
1699 for imagename in $APP_SHORT_NAMES; do
1700 __check_included_image $imagename
1701 if [ $? -eq 0 ]; then
1702 # Only print image data if image repo is null, or if image repo is set and image is local
1704 if [ -z "$IMAGE_REPO_ADR" ]; then
1707 __check_image_local_build $imagename
1708 if [ $? -eq 0 ]; then
1712 if [ $print_image_data -eq 1 ]; then
1713 # A function name is created from the app short name
1714 # for example app short name 'MR' -> produce the function
1715 # name __MR_imagebuild
1716 # This function is called and is expected to exist in the imported
1717 # file for the mr test functions
1718 # The resulting function impl shall build the imagee
1719 function_pointer="__"$imagename"_image_data"
1720 $function_pointer "$format_string" $docker_tmp_file
1725 column -t -s $'\t' $docker_tmp_file | indent1
1729 if [ ! -z "$IMAGE_REPO_ADR" ]; then
1731 # Create a table of the images used in the script - from remote repo
1732 echo -e $BOLD"Remote repo images used in this test script"$EBOLD
1733 echo -e $YELLOW"-- Note: These image will be pulled when the container starts. Images not managed by the test engine --"$EYELLOW
1735 docker_tmp_file=./tmp/.docker-images-table
1736 format_string="{{.Repository}}\\t{{.Tag}}"
1737 echo -e "Application\tRepository\tTag" > $docker_tmp_file
1739 for imagename in $APP_SHORT_NAMES; do
1740 __check_included_image $imagename
1741 if [ $? -eq 0 ]; then
1742 # Only print image data if image repo is null, or if image repo is set and image is local
1743 __check_image_local_build $imagename
1744 if [ $? -ne 0 ]; then
1745 # A function name is created from the app short name
1746 # for example app short name 'MR' -> produce the function
1747 # name __MR_imagebuild
1748 # This function is called and is expected to exist in the imported
1749 # file for the mr test functions
1750 # The resulting function impl shall build the imagee
1751 function_pointer="__"$imagename"_image_data"
1752 $function_pointer "$format_string" $docker_tmp_file
1757 column -t -s $'\t' $docker_tmp_file | indent1
1762 if [ $RUNMODE == "KUBE" ]; then
1764 echo "================================================================================="
1765 echo "================================================================================="
1767 if [ -z "$IMAGE_REPO_ADR" ]; then
1768 echo -e $YELLOW" The image pull policy is set to 'Never' - assuming a local image repo is available for all images"$EYELLOW
1769 echo -e " This setting only works on single node clusters on the local machine"
1770 echo -e " It does not work with multi-node clusters or remote clusters. "
1771 export KUBE_IMAGE_PULL_POLICY="Never"
1773 echo -e $YELLOW" The image pull policy is set to 'Always'"$EYELLOW
1774 echo -e " This setting work on local clusters, multi-node clusters and remote cluster. "
1775 echo -e " Only locally built images are managed. Remote images are always pulled from remote repos"
1776 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"
1777 export KUBE_IMAGE_PULL_POLICY="Always"
1779 #CLUSTER_IP=$(kubectl $KUBECONF config view -o jsonpath={.clusters[0].cluster.server} | awk -F[/:] '{print $4}')
1780 #echo -e $YELLOW" The cluster hostname/ip is: $CLUSTER_IP"$EYELLOW
1782 echo "================================================================================="
1783 echo "================================================================================="
1787 echo -e $BOLD"======================================================="$EBOLD
1788 echo -e $BOLD"== Common test setup completed - test script begins =="$EBOLD
1789 echo -e $BOLD"======================================================="$EBOLD
1794 for imagename in $APP_SHORT_NAMES; do
1795 __check_included_image $imagename
1797 __check_prestarted_image $imagename
1799 if [ $retcode_i -eq 0 ] || [ $retcode_p -eq 0 ]; then
1800 # A function name is created from the app short name
1801 # for example app short name 'RICMSIM' -> produce the function
1802 # name __RICSIM__initial_setup
1803 # This function is called and is expected to exist in the imported
1804 # file for the ricsim test functions
1805 # The resulting function impl shall perform initial setup of port, host etc
1807 function_pointer="__"$imagename"_initial_setup"
1810 function_pointer="__"$imagename"_statisics_setup"
1811 LOG_STAT_ARGS=$LOG_STAT_ARGS" "$($function_pointer)
1815 if [ $COLLECT_RUNTIME_STATS -eq 1 ]; then
1816 ../common/genstat.sh $RUNMODE $SECONDS $TESTLOGS/$ATC/stat_data.csv $LOG_STAT_ARGS &
1817 COLLECT_RUNTIME_STATS_PID=$!
1822 # Function to print the test result, shall be the last cmd in a test script
1824 # (Function for test scripts)
1828 duration=$((TCTEST_END-TCTEST_START))
1830 echo "-------------------------------------------------------------------------------------------------"
1831 echo "------------------------------------- Test case: "$ATC
1832 echo "------------------------------------- Ended: "$(date)
1833 echo "-------------------------------------------------------------------------------------------------"
1834 echo "-- Description: "$TC_ONELINE_DESCR
1835 echo "-- Execution time: " $duration " seconds"
1836 echo "-- Used env file: "$TEST_ENV_VAR_FILE
1837 echo "-------------------------------------------------------------------------------------------------"
1838 echo "------------------------------------- RESULTS"
1842 if [ $RES_DEVIATION -gt 0 ]; then
1843 echo "Test case deviations"
1844 echo "===================================="
1848 echo "Timer measurement in the test script"
1849 echo "===================================="
1850 column -t -s $'\t' $TIMER_MEASUREMENTS
1851 if [ $RES_PASS != $RES_TEST ]; then
1852 echo -e $RED"Measurement may not be reliable when there are failed test - failures may cause long measurement values due to timeouts etc."$ERED
1856 if [ $COLLECT_RUNTIME_STATS -eq 1 ]; then
1857 echo "Runtime statistics collected in file: "$TESTLOGS/$ATC/stat_data.csv
1861 total=$((RES_PASS+RES_FAIL))
1862 if [ $RES_TEST -eq 0 ]; then
1863 echo -e "\033[1mNo tests seem to have been executed. Check the script....\033[0m"
1864 echo -e "\033[31m\033[1m ___ ___ ___ ___ ___ _____ ___ _ ___ _ _ _ ___ ___ \033[0m"
1865 echo -e "\033[31m\033[1m/ __|/ __| _ \_ _| _ \_ _| | __/_\ |_ _| | | | | | _ \ __|\033[0m"
1866 echo -e "\033[31m\033[1m\__ \ (__| /| || _/ | | | _/ _ \ | || |_| |_| | / _| \033[0m"
1867 echo -e "\033[31m\033[1m|___/\___|_|_\___|_| |_| |_/_/ \_\___|____\___/|_|_\___|\033[0m"
1868 elif [ $total != $RES_TEST ]; then
1869 echo -e "\033[1mTotal number of tests does not match the sum of passed and failed tests. Check the script....\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"
1873 echo -e "\033[31m\033[1m|___/\___|_|_\___|_| |_| |_/_/ \_\___|____\___/|_|_\___|\033[0m"
1874 elif [ $RES_CONF_FAIL -ne 0 ]; then
1875 echo -e "\033[1mOne or more configurations has failed. Check the script log....\033[0m"
1876 echo -e "\033[31m\033[1m ___ ___ ___ ___ ___ _____ ___ _ ___ _ _ _ ___ ___ \033[0m"
1877 echo -e "\033[31m\033[1m/ __|/ __| _ \_ _| _ \_ _| | __/_\ |_ _| | | | | | _ \ __|\033[0m"
1878 echo -e "\033[31m\033[1m\__ \ (__| /| || _/ | | | _/ _ \ | || |_| |_| | / _| \033[0m"
1879 echo -e "\033[31m\033[1m|___/\___|_|_\___|_| |_| |_/_/ \_\___|____\___/|_|_\___|\033[0m"
1880 elif [ $RES_PASS = $RES_TEST ]; then
1881 echo -e "All tests \033[32m\033[1mPASS\033[0m"
1882 echo -e "\033[32m\033[1m ___ _ ___ ___ \033[0m"
1883 echo -e "\033[32m\033[1m | _ \/_\ / __/ __| \033[0m"
1884 echo -e "\033[32m\033[1m | _/ _ \\__ \__ \\ \033[0m"
1885 echo -e "\033[32m\033[1m |_|/_/ \_\___/___/ \033[0m"
1888 # Update test suite counter
1889 if [ -f .tmp_tcsuite_pass_ctr ]; then
1890 tmpval=$(< .tmp_tcsuite_pass_ctr)
1892 echo $tmpval > .tmp_tcsuite_pass_ctr
1894 if [ -f .tmp_tcsuite_pass ]; then
1895 echo " - "$ATC " -- "$TC_ONELINE_DESCR" Execution time: "$duration" seconds" >> .tmp_tcsuite_pass
1897 #Create file with OK exit code
1898 echo "0" > "$AUTOTEST_HOME/.result$ATC.txt"
1899 echo "0" > "$TESTLOGS/$ATC/.result$ATC.txt"
1901 echo -e "One or more tests with status \033[31m\033[1mFAIL\033[0m "
1902 echo -e "\033[31m\033[1m ___ _ ___ _ \033[0m"
1903 echo -e "\033[31m\033[1m | __/_\ |_ _| | \033[0m"
1904 echo -e "\033[31m\033[1m | _/ _ \ | || |__ \033[0m"
1905 echo -e "\033[31m\033[1m |_/_/ \_\___|____|\033[0m"
1907 # Update test suite counter
1908 if [ -f .tmp_tcsuite_fail_ctr ]; then
1909 tmpval=$(< .tmp_tcsuite_fail_ctr)
1911 echo $tmpval > .tmp_tcsuite_fail_ctr
1913 if [ -f .tmp_tcsuite_fail ]; then
1914 echo " - "$ATC " -- "$TC_ONELINE_DESCR" Execution time: "$duration" seconds" >> .tmp_tcsuite_fail
1918 echo "++++ Number of tests: "$RES_TEST
1919 echo "++++ Number of passed tests: "$RES_PASS
1920 echo "++++ Number of failed tests: "$RES_FAIL
1922 echo "++++ Number of failed configs: "$RES_CONF_FAIL
1924 echo "++++ Number of test case deviations: "$RES_DEVIATION
1926 echo "------------------------------------- Test case complete ---------------------------------"
1927 echo "-------------------------------------------------------------------------------------------------"
1931 #####################################################################
1932 ###### Functions for start, configuring, stoping, cleaning etc ######
1933 #####################################################################
1935 # Start timer for time measurement
1936 # args: <timer message to print> - timer value and message will be printed both on screen
1937 # and in the timer measurement report - if at least one "print_timer is called"
1939 echo -e $BOLD"INFO(${BASH_LINENO[0]}): "${FUNCNAME[0]}"," $@ $EBOLD
1940 TC_TIMER_STARTTIME=$SECONDS
1941 TC_TIMER_TIMER_TEXT="${@:1}"
1942 if [ $# -ne 1 ]; then
1943 __print_err "need 1 arg, <timer message to print>" $@
1944 TC_TIMER_TIMER_TEXT=${FUNCNAME[0]}":"${BASH_LINENO[0]}
1945 echo " Assigning timer name: "$TC_TIMER_TIMER_TEXT
1947 TC_TIMER_CURRENT_FAILS=$(($RES_FAIL+$RES_CONF_FAIL))
1948 echo " Timer started: $(date)"
1951 # Print the running timer the value of the time (in seconds)
1952 # Timer value and message will be printed both on screen and in the timer measurement report
1954 echo -e $BOLD"INFO(${BASH_LINENO[0]}): "${FUNCNAME[0]}"," $TC_TIMER_TIMER_TEXT $EBOLD
1955 if [ -z "$TC_TIMER_STARTTIME" ]; then
1956 __print_err "timer not started" $@
1959 duration=$(($SECONDS-$TC_TIMER_STARTTIME))
1960 if [ $duration -eq 0 ]; then
1961 duration="<1 second"
1963 duration=$duration" seconds"
1965 echo " Timer duration :" $duration
1967 if [ $(($RES_FAIL+$RES_CONF_FAIL)) -ne $TC_TIMER_CURRENT_FAILS ]; then
1968 res="Failures occured during test - timer not reliabled"
1971 echo -e "$TC_TIMER_TIMER_TEXT \t $duration \t $res" >> $TIMER_MEASUREMENTS
1974 # Print info about a deviations from intended tests
1975 # Each deviation counted is also printed in the testreport
1976 # args <deviation message to print>
1978 echo -e $BOLD"DEVIATION(${BASH_LINENO[0]}): "${FUNCNAME[0]} $EBOLD
1979 if [ $# -lt 1 ]; then
1981 __print_err "need 1 or more args, <deviation message to print>" $@
1985 echo -e $BOLD$YELLOW" Test case deviation: ${@:1}"$EYELLOW$EBOLD
1986 echo "Line: ${BASH_LINENO[0]} - ${@:1}" >> $DEVIATION_FILE
1987 __print_current_stats
1991 # Stop at first FAIL test case and take all logs - only for debugging/trouble shooting
1992 __check_stop_at_error() {
1993 if [ $STOP_AT_ERROR -eq 1 ]; then
1994 echo -e $RED"Test script configured to stop at first FAIL, taking all logs and stops"$ERED
1995 store_logs "STOP_AT_ERROR"
1997 # Update test suite counter
1998 if [ -f .tmp_tcsuite_fail_ctr ]; then
1999 tmpval=$(< .tmp_tcsuite_fail_ctr)
2001 echo $tmpval > .tmp_tcsuite_fail_ctr
2003 if [ -f .tmp_tcsuite_fail ]; then
2004 echo " - "$ATC " -- "$TC_ONELINE_DESCR" Execution stopped due to error" >> .tmp_tcsuite_fail
2011 # Stop and remove all containers
2013 # (Not for test scripts)
2014 __clean_containers() {
2016 echo -e $BOLD"Docker clean and stopping and removing all running containers, by container name"$EBOLD
2019 running_contr_file="./tmp/running_contr.txt"
2020 > $running_contr_file
2022 # Get list of all containers started by the test script
2023 for imagename in $APP_SHORT_NAMES; do
2024 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
2026 running_contr_file_empty="No docker containers running, started by previous test execution"
2027 if [ -s $running_contr_file ]; then
2028 running_contr_file_empty=""
2031 # Kill all containers started by the test env - to speed up shut down
2032 docker kill $(docker ps -a --filter "label=nrttest_app" --format '{{.Names}}') &> /dev/null
2034 tab_heading1="App display name"
2035 tab_heading2="App short name"
2036 tab_heading3="Container name"
2038 tab_heading1_len=${#tab_heading1}
2039 tab_heading2_len=${#tab_heading2}
2040 tab_heading3_len=${#tab_heading3}
2042 #Calc field lengths of each item in the list of containers
2044 if (( $cntr % 3 == 0 ));then
2045 if [ ${#p} -gt $tab_heading1_len ]; then
2046 tab_heading1_len=${#p}
2049 if (( $cntr % 3 == 1));then
2050 if [ ${#p} -gt $tab_heading2_len ]; then
2051 tab_heading2_len=${#p}
2054 if (( $cntr % 3 == 2));then
2055 if [ ${#p} -gt $tab_heading3_len ]; then
2056 tab_heading3_len=${#p}
2060 done <$running_contr_file
2062 let tab_heading1_len=tab_heading1_len+2
2063 while (( ${#tab_heading1} < $tab_heading1_len)); do
2064 tab_heading1="$tab_heading1"" "
2067 let tab_heading2_len=tab_heading2_len+2
2068 while (( ${#tab_heading2} < $tab_heading2_len)); do
2069 tab_heading2="$tab_heading2"" "
2072 let tab_heading3_len=tab_heading3_len+2
2073 while (( ${#tab_heading3} < $tab_heading3_len)); do
2074 tab_heading3="$tab_heading3"" "
2077 if [ ! -z "$running_contr_file_empty" ]; then
2078 echo $running_contr_file_empty | indent1
2080 echo " $tab_heading1$tab_heading2$tab_heading3"" Actions"
2083 if (( $cntr % 3 == 0 ));then
2086 heading_len=$tab_heading1_len
2088 if (( $cntr % 3 == 1));then
2090 heading_len=$tab_heading2_len
2092 if (( $cntr % 3 == 2));then
2095 heading_len=$tab_heading3_len
2097 while (( ${#heading} < $heading_len)); do
2098 heading="$heading"" "
2101 if (( $cntr % 3 == 2));then
2102 echo -ne $row$SAMELINE
2103 echo -ne " $row ${GREEN}stopping...${EGREEN}${SAMELINE}"
2104 docker stop $(docker ps -qa --filter name=${contr} --filter network=$DOCKER_SIM_NWNAME) &> /dev/null
2105 echo -ne " $row ${GREEN}stopped removing...${EGREEN}${SAMELINE}"
2106 docker rm --force $(docker ps -qa --filter name=${contr} --filter network=$DOCKER_SIM_NWNAME) &> /dev/null
2107 echo -e " $row ${GREEN}stopped removed ${EGREEN}"
2110 done <$running_contr_file
2115 echo -e $BOLD" Removing docker network"$EBOLD
2116 TMP=$(docker network ls -q --filter name=$DOCKER_SIM_NWNAME)
2117 if [ "$TMP" == $DOCKER_SIM_NWNAME ]; then
2118 docker network rm $DOCKER_SIM_NWNAME | indent2
2119 if [ $? -ne 0 ]; then
2120 echo -e $RED" Cannot remove docker network. Manually remove or disconnect containers from $DOCKER_SIM_NWNAME"$ERED
2124 echo -e "$GREEN Done$EGREEN"
2126 echo -e $BOLD" Removing all unused docker neworks"$EBOLD
2127 docker network prune --force | indent2
2128 echo -e "$GREEN Done$EGREEN"
2130 echo -e $BOLD" Removing all unused docker volumes"$EBOLD
2131 docker volume prune --force | indent2
2132 echo -e "$GREEN Done$EGREEN"
2134 echo -e $BOLD" Removing all dangling/untagged docker images"$EBOLD
2135 docker rmi --force $(docker images -q -f dangling=true) &> /dev/null
2136 echo -e "$GREEN Done$EGREEN"
2139 CONTRS=$(docker ps | awk '$1 != "CONTAINER" { n++ }; END { print n+0 }')
2140 if [ $? -eq 0 ]; then
2141 if [ $CONTRS -ne 0 ]; then
2142 echo -e $RED"Containers running, may cause distubance to the test case"$ERED
2143 docker ps -a | indent1
2149 ###################################
2150 ### Functions for kube management
2151 ###################################
2153 # Get resource type for scaling
2154 # args: <resource-name> <namespace>
2155 __kube_get_resource_type() {
2156 kubectl $KUBECONF get deployment $1 -n $2 1> /dev/null 2> ./tmp/kubeerr
2157 if [ $? -eq 0 ]; then
2161 kubectl $KUBECONF get sts $1 -n $2 1> /dev/null 2> ./tmp/kubeerr
2162 if [ $? -eq 0 ]; then
2166 echo "unknown-resource-type"
2170 # Scale a kube resource to a specific count
2171 # args: <resource-type> <resource-name> <namespace> <target-count>
2172 # (Not for test scripts)
2174 echo -ne " Setting $1 $2 replicas=$4 in namespace $3"$SAMELINE
2175 kubectl $KUBECONF scale $1 $2 -n $3 --replicas=$4 1> /dev/null 2> ./tmp/kubeerr
2176 if [ $? -ne 0 ]; then
2177 echo -e " Setting $1 $2 replicas=$4 in namespace $3 $RED Failed $ERED"
2179 echo " Message: $(<./tmp/kubeerr)"
2182 echo -e " Setting $1 $2 replicas=$4 in namespace $3 $GREEN OK $EGREEN"
2187 for i in {1..500}; do
2188 count=$(kubectl $KUBECONF get $1/$2 -n $3 -o jsonpath='{.status.replicas}' 2> /dev/null)
2190 if [ -z "$count" ]; then
2191 #No value is sometimes returned for some reason, in case the resource has replica 0
2194 if [ $retcode -ne 0 ]; then
2195 echo -e "$RED Cannot fetch current replica count for $1 $2 in namespace $3 $ERED"
2200 if [ $count -ne $4 ]; then
2201 echo -ne " Waiting for $1 $2 replicas=$4 in namespace $3. Replicas=$count after $(($SECONDS-$TSTART)) seconds $SAMELINE"
2204 echo -e " Waiting for $1 $2 replicas=$4 in namespace $3. Replicas=$count after $(($SECONDS-$TSTART)) seconds"
2205 echo -e " Replicas=$4 after $(($SECONDS-$TSTART)) seconds $GREEN OK $EGREEN"
2211 echo -e "$RED Replica count did not reach target replicas=$4. Failed with replicas=$count $ERED"
2216 # Scale all kube resource sets to 0 in a namespace for resources having a certain lable and label-id
2217 # This function does not wait for the resource to reach 0
2218 # args: <namespace> <label-name> <label-id>
2219 # (Not for test scripts)
2220 __kube_scale_all_resources() {
2224 resources="deployment replicaset statefulset"
2225 for restype in $resources; do
2226 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 -ne " Ordered caling $restype $resid in namespace $namespace with label $labelname=$labelid to 0"$SAMELINE
2230 kubectl $KUBECONF scale $restype $resid -n $namespace --replicas=0 1> /dev/null 2> ./tmp/kubeerr
2231 echo -e " Ordered scaling $restype $resid in namespace $namespace with label $labelname=$labelid to 0 $GREEN OK $EGREEN"
2237 # Scale all kube resource sets to 0 in a namespace for resources having a certain lable and an optional label-id
2238 # This function do wait for the resource to reach 0
2239 # args: <namespace> <label-name> [ <label-id> ]
2240 # (Not for test scripts)
2241 __kube_scale_and_wait_all_resources() {
2245 if [ -z "$3" ]; then
2246 echo " Attempt to scale - deployment replicaset statefulset - in namespace $namespace with label $labelname"
2248 echo " Attempt to scale - deployment replicaset statefulset - in namespace $namespace with label $labelname=$labelid"
2250 resources="deployment replicaset statefulset"
2252 while [ $scaled_all -ne 0 ]; do
2254 for restype in $resources; do
2255 if [ -z "$3" ]; then
2256 result=$(kubectl $KUBECONF get $restype -n $namespace -o jsonpath='{.items[?(@.metadata.labels.'$labelname')].metadata.name}')
2258 result=$(kubectl $KUBECONF get $restype -n $namespace -o jsonpath='{.items[?(@.metadata.labels.'$labelname'=="'$labelid'")].metadata.name}')
2260 if [ $? -eq 0 ] && [ ! -z "$result" ]; then
2261 for resid in $result; do
2262 echo -e " Ordered scaling $restype $resid in namespace $namespace with label $labelname=$labelid to 0"
2263 kubectl $KUBECONF scale $restype $resid -n $namespace --replicas=0 1> /dev/null 2> ./tmp/kubeerr
2266 while [ $count -ne 0 ]; do
2267 count=$(kubectl $KUBECONF get $restype $resid -n $namespace -o jsonpath='{.status.replicas}' 2> /dev/null)
2268 echo -ne " Scaling $restype $resid in namespace $namespace with label $labelname=$labelid to 0, current count=$count"$SAMELINE
2269 if [ $? -eq 0 ] && [ ! -z "$count" ]; then
2274 duration=$(($SECONDS-$T_START))
2275 if [ $duration -gt 100 ]; then
2276 #Forcring count 0, to avoid hanging for failed scaling
2281 echo -e " Scaled $restype $resid in namespace $namespace with label $labelname=$labelid to 0, current count=$count $GREEN OK $EGREEN"
2288 # Remove all kube resources in a namespace for resources having a certain label and label-id
2289 # This function wait until the resources are gone. Scaling to 0 must have been ordered previously
2290 # args: <namespace> <label-name> <label-id>
2291 # (Not for test scripts)
2292 __kube_delete_all_resources() {
2296 resources="deployments replicaset statefulset services pods configmaps persistentvolumeclaims persistentvolumes serviceaccounts clusterrolebindings secrets"
2297 deleted_resourcetypes=""
2298 for restype in $resources; do
2299 ns_flag="-n $namespace"
2300 ns_text="in namespace $namespace"
2301 if [ $restype == "persistentvolumes" ]; then
2305 if [ $restype == "clusterrolebindings" ]; then
2309 result=$(kubectl $KUBECONF get $restype $ns_flag -o jsonpath='{.items[?(@.metadata.labels.'$labelname'=="'$labelid'")].metadata.name}')
2310 if [ $? -eq 0 ] && [ ! -z "$result" ]; then
2311 deleted_resourcetypes=$deleted_resourcetypes" "$restype
2312 for resid in $result; do
2313 if [ $restype == "replicaset" ] || [ $restype == "statefulset" ]; then
2315 while [ $count -ne 0 ]; do
2316 count=$(kubectl $KUBECONF get $restype $resid $ns_flag -o jsonpath='{.status.replicas}' 2> /dev/null)
2317 echo -ne " Scaling $restype $resid $ns_text with label $labelname=$labelid to 0, current count=$count"$SAMELINE
2318 if [ $? -eq 0 ] && [ ! -z "$count" ]; then
2324 echo -e " Scaled $restype $resid $ns_text with label $labelname=$labelid to 0, current count=$count $GREEN OK $EGREEN"
2326 echo -ne " Deleting $restype $resid $ns_text with label $labelname=$labelid "$SAMELINE
2327 kubectl $KUBECONF delete --grace-period=1 $restype $resid $ns_flag 1> /dev/null 2> ./tmp/kubeerr
2328 if [ $? -eq 0 ]; then
2329 echo -e " Deleted $restype $resid $ns_text with label $labelname=$labelid $GREEN OK $EGREEN"
2331 echo -e " Deleted $restype $resid $ns_text with label $labelname=$labelid $GREEN Does not exist - OK $EGREEN"
2337 if [ ! -z "$deleted_resourcetypes" ]; then
2338 for restype in $deleted_resources; do
2339 ns_flag="-n $namespace"
2340 ns_text="in namespace $namespace"
2341 if [ $restype == "persistentvolumes" ]; then
2345 echo -ne " Waiting for $restype $ns_text with label $labelname=$labelid to be deleted..."$SAMELINE
2348 while [ ! -z "$result" ]; do
2350 result=$(kubectl $KUBECONF get $restype $ns_flag -o jsonpath='{.items[?(@.metadata.labels.'$labelname'=="'$labelid'")].metadata.name}')
2351 echo -ne " Waiting for $restype $ns_text with label $labelname=$labelid to be deleted...$(($SECONDS-$T_START)) seconds "$SAMELINE
2352 if [ -z "$result" ]; then
2353 echo -e " Waiting for $restype $ns_text with label $labelname=$labelid to be deleted...$(($SECONDS-$T_START)) seconds $GREEN OK $EGREEN"
2354 elif [ $(($SECONDS-$T_START)) -gt 300 ]; then
2355 echo -e " Waiting for $restype $ns_text with label $labelname=$labelid to be deleted...$(($SECONDS-$T_START)) seconds $RED Failed $ERED"
2363 # Creates a namespace if it does not exists
2365 # (Not for test scripts)
2366 __kube_create_namespace() {
2368 #Check if test namespace exists, if not create it
2369 kubectl $KUBECONF get namespace $1 1> /dev/null 2> ./tmp/kubeerr
2370 if [ $? -ne 0 ]; then
2371 echo -ne " Creating namespace "$1 $SAMELINE
2372 kubectl $KUBECONF create namespace $1 1> /dev/null 2> ./tmp/kubeerr
2373 if [ $? -ne 0 ]; then
2374 echo -e " Creating namespace $1 $RED$BOLD FAILED $EBOLD$ERED"
2376 echo " Message: $(<./tmp/kubeerr)"
2379 kubectl $KUBECONF label ns $1 autotest=engine > /dev/null
2380 echo -e " Creating namespace $1 $GREEN$BOLD OK $EBOLD$EGREEN"
2383 echo -e " Creating namespace $1 $GREEN$BOLD Already exists, OK $EBOLD$EGREEN"
2388 # Removes a namespace if it exists
2390 # (Not for test scripts)
2391 __kube_delete_namespace() {
2393 #Check if test namespace exists, if so remove it
2394 kubectl $KUBECONF get namespace $1 1> /dev/null 2> ./tmp/kubeerr
2395 if [ $? -eq 0 ]; then
2396 echo -ne " Removing namespace "$1 $SAMELINE
2397 kubectl $KUBECONF delete namespace $1 1> /dev/null 2> ./tmp/kubeerr
2398 if [ $? -ne 0 ]; then
2399 echo -e " Removing namespace $1 $RED$BOLD FAILED $EBOLD$ERED"
2401 echo " Message: $(<./tmp/kubeerr)"
2404 echo -e " Removing namespace $1 $GREEN$BOLD OK $EBOLD$EGREEN"
2407 echo -e " Namespace $1 $GREEN$BOLD does not exist, OK $EBOLD$EGREEN"
2412 # Removes a namespace
2414 # (Not for test scripts)
2415 clean_and_create_namespace() {
2418 if [ $# -ne 1 ]; then
2419 __print_err "<namespace>" $@
2422 __kube_delete_namespace $1
2423 if [ $? -ne 0 ]; then
2426 __kube_create_namespace $1
2427 if [ $? -ne 0 ]; then
2433 # Find the host ip of an app (using the service resource)
2434 # args: <app-name> <namespace>
2435 # (Not for test scripts)
2436 __kube_get_service_host() {
2437 if [ $# -ne 2 ]; then
2439 __print_err "need 2 args, <app-name> <namespace>" $@
2442 for timeout in {1..60}; do
2443 host=$(kubectl $KUBECONF get svc $1 -n $2 -o jsonpath='{.spec.clusterIP}')
2444 if [ $? -eq 0 ]; then
2445 if [ ! -z "$host" ]; then
2453 echo "host-not-found-fatal-error"
2457 # Find the named port to an app (using the service resource)
2458 # args: <app-name> <namespace> <port-name>
2459 # (Not for test scripts)
2460 __kube_get_service_port() {
2461 if [ $# -ne 3 ]; then
2463 __print_err "need 3 args, <app-name> <namespace> <port-name>" $@
2467 for timeout in {1..60}; do
2468 port=$(kubectl $KUBECONF get svc $1 -n $2 -o jsonpath='{...ports[?(@.name=="'$3'")].port}')
2469 if [ $? -eq 0 ]; then
2470 if [ ! -z "$port" ]; then
2482 # Find the named node port to an app (using the service resource)
2483 # args: <app-name> <namespace> <port-name>
2484 # (Not for test scripts)
2485 __kube_get_service_nodeport() {
2486 if [ $# -ne 3 ]; then
2488 __print_err "need 3 args, <app-name> <namespace> <port-name>" $@
2492 for timeout in {1..60}; do
2493 port=$(kubectl $KUBECONF get svc $1 -n $2 -o jsonpath='{...ports[?(@.name=="'$3'")].nodePort}')
2494 if [ $? -eq 0 ]; then
2495 if [ ! -z "$port" ]; then
2507 # Create a kube resource from a yaml template
2508 # args: <resource-type> <resource-name> <template-yaml> <output-yaml>
2509 # (Not for test scripts)
2510 __kube_create_instance() {
2511 echo -ne " Creating $1 $2"$SAMELINE
2513 kubectl $KUBECONF apply -f $4 1> /dev/null 2> ./tmp/kubeerr
2514 if [ $? -ne 0 ]; then
2516 echo -e " Creating $1 $2 $RED Failed $ERED"
2517 echo " Message: $(<./tmp/kubeerr)"
2520 echo -e " Creating $1 $2 $GREEN OK $EGREEN"
2524 # Function to create a configmap in kubernetes
2525 # args: <configmap-name> <namespace> <labelname> <labelid> <path-to-data-file> <path-to-output-yaml>
2526 # (Not for test scripts)
2527 __kube_create_configmap() {
2528 echo -ne " Creating configmap $1 "$SAMELINE
2529 envsubst < $5 > $5"_tmp"
2530 cp $5"_tmp" $5 #Need to copy back to orig file name since create configmap neeed the original file name
2531 kubectl $KUBECONF create configmap $1 -n $2 --from-file=$5 --dry-run=client -o yaml > $6
2532 if [ $? -ne 0 ]; then
2533 echo -e " Creating configmap $1 $RED Failed $ERED"
2538 kubectl $KUBECONF apply -f $6 1> /dev/null 2> ./tmp/kubeerr
2539 if [ $? -ne 0 ]; then
2540 echo -e " Creating configmap $1 $RED Apply failed $ERED"
2541 echo " Message: $(<./tmp/kubeerr)"
2545 kubectl $KUBECONF label configmap $1 -n $2 $3"="$4 --overwrite 1> /dev/null 2> ./tmp/kubeerr
2546 if [ $? -ne 0 ]; then
2547 echo -e " Creating configmap $1 $RED Labeling failed $ERED"
2548 echo " Message: $(<./tmp/kubeerr)"
2552 # Log the resulting map
2553 kubectl $KUBECONF get configmap $1 -n $2 -o yaml > $6
2555 echo -e " Creating configmap $1 $GREEN OK $EGREEN"
2559 # This function runs a kubectl cmd where a single output value is expected, for example get ip with jsonpath filter.
2560 # The function retries up to the timeout given in the cmd flag '--cluster-timeout'
2561 # args: <full kubectl cmd with parameters>
2562 # (Not for test scripts)
2563 __kube_cmd_with_timeout() {
2564 TS_TMP=$(($SECONDS+$CLUSTER_TIME_OUT))
2567 kube_cmd_result=$($@)
2568 if [ $? -ne 0 ]; then
2571 if [ $SECONDS -ge $TS_TMP ] || [ ! -z "$kube_cmd_result" ] ; then
2572 echo $kube_cmd_result
2579 # This function starts a pod that cleans a the contents of a path mounted as a pvc
2580 # After this action the pod should terminate
2581 # This should only be executed when the pod owning the pvc is not running
2582 # args: <appname> <namespace> <pvc-name> <path-to remove>
2583 # (Not for test scripts)
2584 __kube_clean_pvc() {
2586 #using env vars setup in pvccleaner_api_functions.sh
2588 export PVC_CLEANER_NAMESPACE=$2
2589 export PVC_CLEANER_CLAIMNAME=$3
2590 export PVC_CLEANER_RM_PATH=$4
2591 export PVC_CLEANER_APP_NAME
2592 input_yaml=$SIM_GROUP"/"$PVC_CLEANER_COMPOSE_DIR"/"pvc-cleaner.yaml
2593 output_yaml=$PWD/tmp/$2-pvc-cleaner.yaml
2595 envsubst < $input_yaml > $output_yaml
2597 kubectl $KUBECONF delete -f $output_yaml 1> /dev/null 2> /dev/null # Delete the previous terminated pod - if existing
2599 __kube_create_instance pod $PVC_CLEANER_APP_NAME $input_yaml $output_yaml
2600 if [ $? -ne 0 ]; then
2601 echo $YELLOW" Could not clean pvc for app: $1 - persistent storage not clean - tests may not work"
2605 term_ts=$(($SECONDS+30))
2606 while [ $term_ts -gt $SECONDS ]; do
2607 pod_status=$(kubectl $KUBECONF get pod pvc-cleaner -n $PVC_CLEANER_NAMESPACE --no-headers -o custom-columns=":status.phase")
2608 if [ "$pod_status" == "Succeeded" ]; then
2615 # This function scales or deletes all resources for app selected by the testcase.
2617 # (Not for test scripts)
2619 echo -e $BOLD"Initialize kube pods/statefulsets/replicaset to initial state"$EBOLD
2621 # Scale prestarted or managed apps
2622 for imagename in $APP_SHORT_NAMES; do
2623 # A function name is created from the app short name
2624 # for example app short name 'RICMSIM' -> produce the function
2625 # name __RICSIM_kube_scale_zero or __RICSIM_kube_scale_zero_and_wait
2626 # This function is called and is expected to exist in the imported
2627 # file for the ricsim test functions
2628 # The resulting function impl shall scale the resources to 0
2629 # For prestarted apps, the function waits until the resources are 0
2630 # For included (not prestated) apps, the scaling is just ordered
2631 __check_prestarted_image $imagename
2632 if [ $? -eq 0 ]; then
2633 function_pointer="__"$imagename"_kube_scale_zero_and_wait"
2634 echo -e " Scaling all kube resources for app $BOLD $imagename $EBOLD to 0"
2637 __check_included_image $imagename
2638 if [ $? -eq 0 ]; then
2639 function_pointer="__"$imagename"_kube_scale_zero"
2640 echo -e " Scaling all kube resources for app $BOLD $imagename $EBOLD to 0"
2646 # Delete managed apps
2647 for imagename in $APP_SHORT_NAMES; do
2648 __check_included_image $imagename
2649 if [ $? -eq 0 ]; then
2650 __check_prestarted_image $imagename
2651 if [ $? -ne 0 ]; then
2652 # A function name is created from the app short name
2653 # for example app short name 'RICMSIM' -> produce the function
2654 # name __RICSIM__kube_delete_all
2655 # This function is called and is expected to exist in the imported
2656 # file for the ricsim test functions
2657 # The resulting function impl shall delete all its resources
2658 function_pointer="__"$imagename"_kube_delete_all"
2659 echo -e " Deleting all kube resources for app $BOLD $imagename $EBOLD"
2668 # Function stop and remove all containers (docker) and services/deployments etc(kube)
2670 # Function for test script
2671 clean_environment() {
2672 if [ $RUNMODE == "KUBE" ]; then
2674 if [ $PRE_CLEAN -eq 1 ]; then
2675 echo " Cleaning docker resouces to free up resources, may take time..."
2676 ../common/clean_docker.sh 2>&1 > /dev/null
2681 if [ $PRE_CLEAN -eq 1 ]; then
2682 echo " Cleaning kubernetes resouces to free up resources, may take time..."
2683 ../common/clean_kube.sh $KUBECONF 2>&1 > /dev/null
2689 # 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
2691 # (Function for test scripts)
2692 auto_clean_environment() {
2694 if [ "$AUTO_CLEAN" == "auto" ]; then
2695 echo -e $BOLD"Initiating automatic cleaning of environment"$EBOLD
2700 # Function to sleep a test case for a numner of seconds. Prints the optional text args as info
2701 # args: <sleep-time-in-sec> [any-text-in-quotes-to-be-printed]
2702 # (Function for test scripts)
2705 echo -e $BOLD"INFO(${BASH_LINENO[0]}): "${FUNCNAME[0]}"," $@ $EBOLD
2706 if [ $# -lt 1 ]; then
2708 __print_err "need at least one arg, <sleep-time-in-sec> [any-text-to-printed]" $@
2711 #echo "---- Sleep for " $1 " seconds ---- "$2
2713 duration=$((SECONDS-start))
2714 while [ $duration -lt $1 ]; do
2715 echo -ne " Slept for ${duration} seconds${SAMELINE}"
2717 duration=$((SECONDS-start))
2719 echo -ne " Slept for ${duration} seconds${SAMELINE}"
2723 # Print error info for the call in the parent script (test case). Arg: <error-message-to-print>
2724 # Not to be called from the test script itself.
2726 echo -e $RED ${FUNCNAME[1]} " "$1" " ${BASH_SOURCE[2]} " line" ${BASH_LINENO[1]} $ERED
2727 if [ $# -gt 1 ]; then
2728 echo -e $RED" Got: "${FUNCNAME[1]} ${@:2} $ERED
2731 __check_stop_at_error
2734 # Function to create the docker network for the test
2735 # Not to be called from the test script itself.
2736 __create_docker_network() {
2737 tmp=$(docker network ls --format={{.Name}} --filter name=$DOCKER_SIM_NWNAME)
2738 if [ $? -ne 0 ]; then
2739 echo -e $RED" Could not check if docker network $DOCKER_SIM_NWNAME exists"$ERED
2742 if [ "$tmp" != $DOCKER_SIM_NWNAME ]; then
2743 echo -e " Creating docker network:$BOLD $DOCKER_SIM_NWNAME $EBOLD"
2744 docker network create $DOCKER_SIM_NWNAME | indent2
2745 if [ $? -ne 0 ]; then
2746 echo -e $RED" Could not create docker network $DOCKER_SIM_NWNAME"$ERED
2749 echo -e "$GREEN Done$EGREEN"
2752 echo -e " Docker network $DOCKER_SIM_NWNAME already exists$GREEN OK $EGREEN"
2756 # Function to start container with docker-compose and wait until all are in state running.
2757 # If the <docker-compose-file> is empty, the default 'docker-compose.yml' is assumed.
2758 #args: <docker-compose-dir> <docker-compose-file> <docker-compose-arg>|NODOCKERARGS <count> <app-name>+
2759 # (Not for test scripts)
2760 __start_container() {
2762 if [ $# -lt 5 ]; then
2764 __print_err "need 5 or more args, <docker-compose-dir> <docker-compose-file> <docker-compose-arg>|NODOCKERARGS <count> <app-name>+" $@
2768 __create_docker_network
2776 if [ -z "$compose_file" ]; then
2777 compose_file="docker-compose.yml"
2785 envsubst < $compose_file > "gen_"$compose_file
2786 compose_file="gen_"$compose_file
2787 if [ $DOCKER_COMPOSE_VERION == "V1" ]; then
2788 docker_compose_cmd="docker-compose"
2790 docker_compose_cmd="docker compose"
2793 if [ "$compose_args" == "NODOCKERARGS" ]; then
2794 $docker_compose_cmd -f $compose_file up -d &> .dockererr
2795 if [ $? -ne 0 ]; then
2796 echo -e $RED"Problem to launch container(s) with docker-compose"$ERED
2798 echo -e $RED"Stopping script...."$ERED
2802 $docker_compose_cmd -f $compose_file up -d $compose_args &> .dockererr
2803 if [ $? -ne 0 ]; then
2804 echo -e $RED"Problem to launch container(s) with docker-compose"$ERED
2806 echo -e $RED"Stopping script...."$ERED
2814 while [ $appindex -lt $appcount ]; do
2818 for i in {1..10}; do
2819 if [ "$(docker inspect --format '{{ .State.Running }}' $appname)" == "true" ]; then
2820 echo -e " Container $BOLD${appname}$EBOLD$GREEN running$EGREEN on$BOLD image $(docker inspect --format '{{ .Config.Image }}' ${appname}) $EBOLD"
2827 if [ $app_started -eq 0 ]; then
2830 echo -e $RED" Container $BOLD${appname}$EBOLD could not be started"$ERED
2831 echo -e $RED" Stopping script..."$ERED
2834 let appindex=appindex+1
2839 # Function to check if container/service is responding to http/https
2840 # args: <container-name>|<service-name> url
2841 # (Not for test scripts)
2842 __check_service_start() {
2844 if [ $# -ne 2 ]; then
2846 __print_err "need 2 args, <container-name>|<service-name> url" $@
2850 if [ $RUNMODE == "KUBE" ]; then
2851 ENTITY="service/set/deployment"
2857 echo -ne " Container $BOLD${appname}$EBOLD starting${SAMELINE}"
2861 echo -ne " Waiting for ${ENTITY} ${appname} service status...${SAMELINE}"
2864 while (( $TSTART+600 > $SECONDS )); do
2865 result="$(__do_curl -m 10 $url)"
2866 if [ $? -eq 0 ]; then
2867 if [ ${#result} -gt 15 ]; then
2868 #If response is too long, truncate
2869 result="...response text too long, omitted"
2871 echo -ne " Waiting for {ENTITY} $BOLD${appname}$EBOLD service status on ${3}, result: $result${SAMELINE}"
2872 echo -ne " The ${ENTITY} $BOLD${appname}$EBOLD$GREEN is alive$EGREEN, responds to service status:$GREEN $result $EGREEN on ${url} after $(($SECONDS-$TSTART)) seconds"
2878 if (( $TS_OFFSET > 5 )); then
2881 while [ $(($TS_TMP+$TS_OFFSET)) -gt $SECONDS ]; do
2882 echo -ne " Waiting for ${ENTITY} ${appname} service status on ${url}...$(($SECONDS-$TSTART)) seconds, retrying in $(($TS_TMP+$TS_OFFSET-$SECONDS)) seconds ${SAMELINE}"
2886 let loop_ctr=loop_ctr+1
2889 if [ "$a1pmsst" = "false" ]; then
2891 echo -e $RED" The ${ENTITY} ${appname} did not respond to service status on ${url} in $(($SECONDS-$TSTART)) seconds"$ERED
2904 __check_container_logs() {
2912 echo -e $BOLD"Checking $dispname container $appname log ($logpath) for WARNINGs and ERRORs"$EBOLD
2914 if [ $RUNMODE == "KUBE" ]; then
2915 echo -e $YELLOW" Internal log for $dispname not checked in kube"$EYELLOW
2919 #tmp=$(docker ps | grep $appname)
2920 tmp=$(docker ps -q --filter name=$appname) #get the container id
2921 if [ -z "$tmp" ]; then #Only check logs for running A1PMS apps
2922 echo " "$dispname" is not running, no check made"
2925 foundentries="$(docker exec -t $tmp grep $warning $logpath | wc -l)"
2926 if [ $? -ne 0 ];then
2927 echo " Problem to search $appname log $logpath"
2929 if [ $foundentries -eq 0 ]; then
2930 echo " No WARN entries found in $appname log $logpath"
2932 echo -e " Found \033[1m"$foundentries"\033[0m WARN entries in $appname log $logpath"
2935 foundentries="$(docker exec -t $tmp grep $error $logpath | wc -l)"
2936 if [ $? -ne 0 ];then
2937 echo " Problem to search $appname log $logpath"
2939 if [ $foundentries -eq 0 ]; then
2940 echo " No ERR entries found in $appname log $logpath"
2942 echo -e $RED" Found \033[1m"$foundentries"\033[0m"$RED" ERR entries in $appname log $logpath"$ERED
2948 # Store all container logs and other logs in the log dir for the script
2949 # Logs are stored with a prefix in case logs should be stored several times during a test
2950 # args: <logfile-prefix>
2951 # (Function for test scripts)
2953 if [ $# != 1 ]; then
2955 __print_err "need one arg, <file-prefix>" $@
2958 echo -e $BOLD"Storing all docker/kube container logs and other test logs in $TESTLOGS/$ATC using prefix: "$1$EBOLD
2960 docker stats --no-stream > $TESTLOGS/$ATC/$1_docker_stats.log 2>&1
2962 docker ps -a > $TESTLOGS/$ATC/$1_docker_ps.log 2>&1
2964 cp .httplog_${ATC}.txt $TESTLOGS/$ATC/$1_httplog_${ATC}.txt 2>&1
2966 if [ $RUNMODE == "DOCKER" ]; then
2968 # Store docker logs for all container
2969 for imagename in $APP_SHORT_NAMES; do
2970 __check_included_image $imagename
2971 if [ $? -eq 0 ]; then
2972 # A function name is created from the app short name
2973 # for example app short name 'RICMSIM' -> produce the function
2974 # name __RICSIM__store_docker_logs
2975 # This function is called and is expected to exist in the imported
2976 # file for the ricsim test functions
2977 # The resulting function impl shall store the docker logs for each container
2978 function_pointer="__"$imagename"_store_docker_logs"
2979 $function_pointer "$TESTLOGS/$ATC/" $1
2983 if [ $RUNMODE == "KUBE" ]; then
2984 namespaces=$(kubectl $KUBECONF get namespaces -o jsonpath='{.items[?(@.metadata.name)].metadata.name}')
2985 for nsid in $namespaces; do
2986 pods=$(kubectl $KUBECONF get pods -n $nsid -o jsonpath='{.items[?(@.metadata.labels.autotest)].metadata.name}')
2987 for podid in $pods; do
2988 kubectl $KUBECONF logs -n $nsid $podid > $TESTLOGS/$ATC/$1_${podid}.log
2998 # Generic curl function, assumes all 200-codes are ok
3000 # args: <valid-curl-args-including full url>
3001 # returns: <returned response (without respose code)> or "<no-response-from-server>" or "<not found, <http-code>>""
3002 # returns: The return code is 0 for ok and 1 for not ok
3004 echo ${FUNCNAME[1]} "line: "${BASH_LINENO[1]} >> $HTTPLOG
3006 if [ ! -z "$KUBE_PROXY_PATH" ]; then
3007 if [ $KUBE_PROXY_HTTPX == "http" ]; then
3008 proxyflag=" --proxy $KUBE_PROXY_PATH"
3010 proxyflag=" --proxy-insecure --proxy $KUBE_PROXY_PATH"
3013 curlString="curl -skw %{http_code} $proxyflag $@"
3014 echo " CMD: $curlString" >> $HTTPLOG
3017 echo " RESP: $res" >> $HTTPLOG
3018 echo " RETCODE: $retcode" >> $HTTPLOG
3019 if [ $retcode -ne 0 ]; then
3020 echo "<no-response-from-server>"
3023 http_code="${res:${#res}-3}"
3024 if [ ${#res} -eq 3 ]; then
3025 if [ $http_code -lt 200 ] || [ $http_code -gt 299 ]; then
3026 echo "<no-response-from-server>"
3032 if [ $http_code -lt 200 ] || [ $http_code -gt 299 ]; then
3033 echo "<not found, resp:${http_code}>"
3036 if [ $# -eq 2 ]; then
3037 echo "${res:0:${#res}-3}" | xargs
3039 echo "${res:0:${#res}-3}"
3046 # Generic curl function, assumes all 200-codes are ok
3047 # Uses no proxy, even if it is set
3048 # args: <valid-curl-args-including full url>
3049 # returns: <returned response (without respose code)> or "<no-response-from-server>" or "<not found, <http-code>>""
3050 # returns: The return code is 0 for ok and 1 for not ok
3051 __do_curl_no_proxy() {
3052 echo ${FUNCNAME[1]} "line: "${BASH_LINENO[1]} >> $HTTPLOG
3053 curlString="curl -skw %{http_code} $@"
3054 echo " CMD: $curlString" >> $HTTPLOG
3057 echo " RESP: $res" >> $HTTPLOG
3058 echo " RETCODE: $retcode" >> $HTTPLOG
3059 if [ $retcode -ne 0 ]; then
3060 echo "<no-response-from-server>"
3063 http_code="${res:${#res}-3}"
3064 if [ ${#res} -eq 3 ]; then
3065 if [ $http_code -lt 200 ] || [ $http_code -gt 299 ]; then
3066 echo "<no-response-from-server>"
3072 if [ $http_code -lt 200 ] || [ $http_code -gt 299 ]; then
3073 echo "<not found, resp:${http_code}>"
3076 if [ $# -eq 2 ]; then
3077 echo "${res:0:${#res}-3}" | xargs
3079 echo "${res:0:${#res}-3}"
3086 #######################################
3087 ### Basic helper function for test cases
3088 #######################################
3090 # Test a simulator container variable value towards target value using an condition operator with an optional timeout.
3091 # Arg: <simulator-name> <host> <variable-name> <condition-operator> <target-value> - This test is done
3092 # immediately and sets pass or fail depending on the result of comparing variable and target using the operator.
3093 # Arg: <simulator-name> <host> <variable-name> <condition-operator> <target-value> <timeout> - This test waits up to the timeout
3094 # before setting pass or fail depending on the result of comparing variable and target using the operator.
3095 # 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.
3096 # Not to be called from test script.
3099 checkjsonarraycount=0
3100 TIMESTAMP=$(date "+%Y-%m-%d %H:%M:%S")
3101 if [ $# -eq 6 ]; then
3102 if [[ $3 == "json:"* ]]; then
3103 checkjsonarraycount=1
3106 echo -e $BOLD"TEST $TEST_SEQUENCE_NR (${BASH_LINENO[1]}): ${1}, ${3} ${4} ${5} within ${6} seconds"$EBOLD
3107 echo "TEST $TEST_SEQUENCE_NR - ${TIMESTAMP}: (${BASH_LINENO[1]}): ${1}, ${3} ${4} ${5} within ${6} seconds" >> $HTTPLOG
3110 ((TEST_SEQUENCE_NR++))
3114 if [ $checkjsonarraycount -eq 0 ]; then
3115 result="$(__do_curl $2$3)"
3117 result=${result//[[:blank:]]/} #Strip blanks
3120 result="$(__do_curl $2$path)"
3122 echo "$result" > ./tmp/.tmp.curl.json
3123 result=$(python3 ../common/count_json_elements.py "./tmp/.tmp.curl.json")
3125 duration=$((SECONDS-start))
3126 echo -ne " Result=${result} after ${duration} seconds${SAMELINE}"
3128 if [ $retcode -ne 0 ]; then
3129 if [ $duration -gt $6 ]; then
3131 echo -e $RED" FAIL${ERED} - ${3} ${4} ${5} not reached in ${6} seconds, result = ${result}"
3132 __print_current_stats
3133 __check_stop_at_error
3136 elif [ "$4" == "=" ] && [ "$result" -eq $5 ]; then
3138 echo -e " Result=${result} after ${duration} seconds${SAMELINE}"
3139 echo -e $GREEN" PASS${EGREEN} - Result=${result} after ${duration} seconds"
3140 __print_current_stats
3142 elif [ "$4" == ">" ] && [ "$result" -gt $5 ]; then
3144 echo -e " Result=${result} after ${duration} seconds${SAMELINE}"
3145 echo -e $GREEN" PASS${EGREEN} - Result=${result} after ${duration} seconds"
3146 __print_current_stats
3148 elif [ "$4" == "<" ] && [ "$result" -lt $5 ]; then
3150 echo -e " Result=${result} after ${duration} seconds${SAMELINE}"
3151 echo -e $GREEN" PASS${EGREEN} - Result=${result} after ${duration} seconds"
3152 __print_current_stats
3154 elif [ "$4" == ">=" ] && [ "$result" -ge $5 ]; then
3156 echo -e " Result=${result} after ${duration} seconds${SAMELINE}"
3157 echo -e $GREEN" PASS${EGREEN} - Result=${result} after ${duration} seconds"
3158 __print_current_stats
3160 elif [ "$4" == "contain_str" ] && [[ $result =~ $5 ]]; then
3162 echo -e " Result=${result} after ${duration} seconds${SAMELINE}"
3163 echo -e $GREEN" PASS${EGREEN} - Result=${result} after ${duration} seconds"
3164 __print_current_stats
3167 if [ $duration -gt $6 ]; then
3169 echo -e $RED" FAIL${ERED} - ${3} ${4} ${5} not reached in ${6} seconds, result = ${result}"
3170 __print_current_stats
3171 __check_stop_at_error
3177 elif [ $# -eq 5 ]; then
3178 if [[ $3 == "json:"* ]]; then
3179 checkjsonarraycount=1
3182 echo -e $BOLD"TEST $TEST_SEQUENCE_NR (${BASH_LINENO[1]}): ${1}, ${3} ${4} ${5}"$EBOLD
3183 echo "TEST $TEST_SEQUENCE_NR - ${TIMESTAMP}: (${BASH_LINENO[1]}): ${1}, ${3} ${4} ${5}" >> $HTTPLOG
3185 ((TEST_SEQUENCE_NR++))
3186 if [ $checkjsonarraycount -eq 0 ]; then
3187 result="$(__do_curl $2$3)"
3189 result=${result//[[:blank:]]/} #Strip blanks
3192 result="$(__do_curl $2$path)"
3194 echo "$result" > ./tmp/.tmp.curl.json
3195 result=$(python3 ../common/count_json_elements.py "./tmp/.tmp.curl.json")
3197 if [ $retcode -ne 0 ]; then
3199 echo -e $RED" FAIL ${ERED}- ${3} ${4} ${5} not reached, result = ${result}"
3200 __print_current_stats
3201 __check_stop_at_error
3202 elif [ "$4" == "=" ] && [ "$result" -eq $5 ]; then
3204 echo -e $GREEN" PASS${EGREEN} - Result=${result}"
3205 __print_current_stats
3206 elif [ "$4" == ">" ] && [ "$result" -gt $5 ]; then
3208 echo -e $GREEN" PASS${EGREEN} - Result=${result}"
3209 __print_current_stats
3210 elif [ "$4" == "<" ] && [ "$result" -lt $5 ]; then
3212 echo -e $GREEN" PASS${EGREEN} - Result=${result}"
3213 __print_current_stats
3214 elif [ "$4" == ">=" ] && [ "$result" -ge $5 ]; then
3216 echo -e $GREEN" PASS${EGREEN} - Result=${result}"
3217 __print_current_stats
3218 elif [ "$4" == "contain_str" ] && [[ $result =~ $5 ]]; then
3220 echo -e $GREEN" PASS${EGREEN} - Result=${result}"
3221 __print_current_stats
3224 echo -e $RED" FAIL${ERED} - ${3} ${4} ${5} not reached, result = ${result}"
3225 __print_current_stats
3226 __check_stop_at_error
3229 echo "Wrong args to __var_test, needs five or six args: <simulator-name> <host> <variable-name> <condition-operator> <target-value> [ <timeout> ]"