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>] [--docker-host <docker-host-url>] [--docker-proxy <host-or-ip>]"
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'"
71 echo "--docker-host - Configure docker to use docker in e.g. a VM"
72 echo "--docker-proxy - Configure ip/host to docker when docker is running in a VM"
74 echo "List of app short names supported: "$APP_SHORT_NAMES
79 # Create a test case id, ATC (Auto Test Case), from the name of the test case script.
80 # FTC1.sh -> ATC == FTC1
81 ATC=$(basename "${BASH_SOURCE[$i+1]}" .sh)
83 #Create result file (containing '1' for error) for this test case
84 #Will be replaced with a file containing '0' if all test cases pass
85 echo "1" > "$PWD/.result$ATC.txt"
87 #Formatting for 'echo' cmd
92 GREEN="\033[32m\033[1m"
94 YELLOW="\033[33m\033[1m"
98 # Just resetting any previous echo formatting...
101 # default test environment variables
103 #Override env file, will be added on top of the above file
104 TEST_ENV_VAR_FILE_OVERRIDE=""
106 echo "Test case started as: ${BASH_SOURCE[$i+1]} "$@
108 # Var to hold 'auto' in case containers shall be stopped when test case ends
111 # Var to indicate pre clean, if flag --pre-clean is set the script will clean kube resouces when running docker and vice versa
114 # Var to hold the app names to use local images for
117 # Var to hold the app names to use remote snapshot images for
118 USE_SNAPSHOT_IMAGES=""
120 # Var to hold the app names to use remote staging images for
121 USE_STAGING_IMAGES=""
123 # Var to hold the app names to use remote release images for
124 USE_RELEASE_IMAGES=""
127 # 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
130 # The default value "DEV" indicate that development image tags (SNAPSHOT) and nexus repos (nexus port 10002) are used.
131 # The value "RELEASE" indicate that relase image tag and nexus repos (nexus port) are used
132 # Applies only to images defined in the test-env files with image names and tags defined as XXXX_RELEASE
135 #Var to indicate docker-compose version, V1 or V2
136 #V1 names replicated containers <proj-name>_<service-name>_<index>
137 #V2 names replicated containers <proj-name>-<service-name>-<index>
138 DOCKER_COMPOSE_VERION="V1"
140 # Function to indent cmd output with one space
141 indent1() { sed 's/^/ /'; }
143 # Function to indent cmd output with two spaces
144 indent2() { sed 's/^/ /'; }
146 # Set a description string for the test case
147 if [ -z "$TC_ONELINE_DESCR" ]; then
148 TC_ONELINE_DESCR="<no-description>"
149 echo "No test case description found, TC_ONELINE_DESCR should be set on in the test script , using "$TC_ONELINE_DESCR
152 # Counter for test suites
153 if [ -f .tmp_tcsuite_ctr ]; then
154 tmpval=$(< .tmp_tcsuite_ctr)
156 echo $tmpval > .tmp_tcsuite_ctr
159 # Create the logs dir if not already created in the current dir
160 if [ ! -d "logs" ]; then
165 # Create the tmp dir for temporary files that is not needed after the test
166 # hidden files for the test env is still stored in the current dir
167 # files in the ./tmp is moved to ./tmp/prev when a new test is started
168 if [ ! -d "tmp" ]; then
170 if [ $? -ne 0 ]; then
171 echo "Cannot create dir for temp files, $PWD/tmp"
178 if [ $? -ne 0 ]; then
179 echo "Cannot cd to $PWD/tmp"
184 TESTENV_TEMP_FILES=$PWD
186 if [ ! -d "prev" ]; then
188 if [ $? -ne 0 ]; then
189 echo "Cannot create dir for previous temp files, $PWD/prev"
195 TMPFILES=$(ls -A | grep -vw prev)
196 if [ ! -z "$TMPFILES" ]; then
197 cp -r $TMPFILES prev #Move all temp files to prev dir
198 if [ $? -ne 0 ]; then
199 echo "Cannot move temp files in $PWD to previous temp files in, $PWD/prev"
203 if [ $(pwd | xargs basename) == "tmp" ]; then #Check that current dir is tmp...for safety
205 rm -rf $TMPFILES # Remove all temp files
210 if [ $? -ne 0 ]; then
211 echo "Cannot cd to $curdir"
217 # Create a http message log for this testcase
218 HTTPLOG=$PWD"/.httplog_"$ATC".txt"
221 # Create a log dir for the test case
222 mkdir -p $TESTLOGS/$ATC
224 # Save create for current logs
225 mkdir -p $TESTLOGS/$ATC/previous
227 rm $TESTLOGS/$ATC/previous/*.log &> /dev/null
228 rm $TESTLOGS/$ATC/previous/*.txt &> /dev/null
229 rm $TESTLOGS/$ATC/previous/*.json &> /dev/null
231 mv $TESTLOGS/$ATC/*.log $TESTLOGS/$ATC/previous &> /dev/null
232 mv $TESTLOGS/$ATC/*.txt $TESTLOGS/$ATC/previous &> /dev/null
233 mv $TESTLOGS/$ATC/*.txt $TESTLOGS/$ATC/previous &> /dev/null
235 # Clear the log dir for the test case
236 rm $TESTLOGS/$ATC/*.log &> /dev/null
237 rm $TESTLOGS/$ATC/*.txt &> /dev/null
238 rm $TESTLOGS/$ATC/*.json &> /dev/null
240 #Create result file in the log dir
241 echo "1" > "$TESTLOGS/$ATC/.result$ATC.txt"
243 # Log all output from the test case to a TC log
244 TCLOG=$TESTLOGS/$ATC/TC.log
245 exec &> >(tee ${TCLOG})
247 #Variables for counting tests as well as passed and failed tests
254 #Var to control if current stats shall be printed
255 PRINT_CURRENT_STATS=0
257 #Var to control if container/pod runtim statistics shall be collected
258 COLLECT_RUNTIME_STATS=0
259 COLLECT_RUNTIME_STATS_PID=0
261 #Var to control if endpoint statistics shall be collected
262 COLLECT_ENDPOINT_STATS=0
264 #Var to control if namespaces shall be delete before test setup
265 DELETE_KUBE_NAMESPACES=0
267 #Var to control if containers shall be delete before test setup
270 #Var to configure kubectl from a config file or context
273 #Localhost, may be set to another host/ip by cmd parameter
274 LOCALHOST_NAME="localhost"
276 #Reseting vars related to token/keys used by kubeproxy when istio is enabled
277 #The vars are populated if istio is used in the testcase
278 KUBE_PROXY_CURL_JWT=""
279 KUBE_PROXY_ISTIO_JWKS_KEYS=""
281 #Var pointing to dir mounted to each kubernetes node (master and workers)
282 #Persistent volumes using "hostpath" are allocated beneath the point.
283 #Typically it is a dir on local host mounted to each VM running the master and worker.
284 #So the intention is make this dir available so the PODs can be restarted on any
285 #node and still access the persistent data
286 #If not set from cmd line, the path is defaults to "/tmp"
287 HOST_PATH_BASE_DIR=""
289 #File to keep deviation messages
290 DEVIATION_FILE=".tmp_deviations"
291 rm $DEVIATION_FILE &> /dev/null
293 # Trap "command not found" and make the script fail
296 if [ $? -eq 127 ]; then
297 echo -e $RED"Function not found, setting script to FAIL"$ERED
299 __print_current_stats
304 # Trap to kill subprocess for stats collection (if running)
306 if [ $COLLECT_RUNTIME_STATS_PID -ne 0 ]; then
307 kill $COLLECT_RUNTIME_STATS_PID
315 # Function to log the start of a test case
317 TIMESTAMP=$(date "+%Y-%m-%d %H:%M:%S")
318 echo -e $BOLD"TEST $TEST_SEQUENCE_NR (${BASH_LINENO[1]}): ${FUNCNAME[1]}" $@ $EBOLD
319 echo "TEST $TEST_SEQUENCE_NR - ${TIMESTAMP}: (${BASH_LINENO[1]}): ${FUNCNAME[1]}" $@ >> $HTTPLOG
321 ((TEST_SEQUENCE_NR++))
324 # Function to print current statistics
325 __print_current_stats() {
326 if [ $PRINT_CURRENT_STATS -ne 0 ]; then
327 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"
331 # General function to log a failed test case
332 __log_test_fail_general() {
333 echo -e $RED" FAIL."$1 $ERED
335 __print_current_stats
336 __check_stop_at_error
339 # Function to log a test case failed due to incorrect response code
340 __log_test_fail_status_code() {
341 echo -e $RED" FAIL. Exepected status "$1", got "$2 $3 $ERED
343 __print_current_stats
344 __check_stop_at_error
347 # Function to log a test case failed due to incorrect response body
348 __log_test_fail_body() {
349 echo -e $RED" FAIL, returned body not correct"$ERED
351 __print_current_stats
352 __check_stop_at_error
355 # Function to log a test case that is not supported
356 __log_test_fail_not_supported() {
357 echo -e $RED" FAIL, function not supported"$ERED
359 __print_current_stats
360 __check_stop_at_error
363 # General function to log a passed test case
365 if [ $# -gt 0 ]; then
369 echo -e $GREEN" PASS"$EGREEN
370 __print_current_stats
373 #Counter for configurations
376 # Function to log the start of a configuration setup
378 TIMESTAMP=$(date "+%Y-%m-%d %H:%M:%S")
379 echo -e $BOLD"CONF $CONF_SEQUENCE_NR (${BASH_LINENO[1]}): "${FUNCNAME[1]} $@ $EBOLD
380 echo "CONF $CONF_SEQUENCE_NR - ${TIMESTAMP}: (${BASH_LINENO[1]}): "${FUNCNAME[1]} $@ >> $HTTPLOG
381 ((CONF_SEQUENCE_NR++))
384 # Function to log a failed configuration setup
385 __log_conf_fail_general() {
386 echo -e $RED" FAIL."$1 $ERED
388 __print_current_stats
389 __check_stop_at_error
392 # Function to log a failed configuration setup due to incorrect response code
393 __log_conf_fail_status_code() {
394 echo -e $RED" FAIL. Exepected status "$1", got "$2 $3 $ERED
396 __print_current_stats
397 __check_stop_at_error
400 # Function to log a failed configuration setup due to incorrect response body
401 __log_conf_fail_body() {
402 echo -e $RED" FAIL, returned body not correct"$ERED
404 __print_current_stats
405 __check_stop_at_error
408 # Function to log a configuration that is not supported
409 __log_conf_fail_not_supported() {
410 echo -e $RED" FAIL, function not supported"$ERED$@
412 __print_current_stats
413 __check_stop_at_error
416 # Function to log a passed configuration setup
418 if [ $# -gt 0 ]; then
421 echo -e $GREEN" OK"$EGREEN
422 __print_current_stats
425 # Function to collect stats on endpoints
426 # args: <app-id> <end-point-no> <http-operation> <end-point-url> <http-status> [<count>]
427 __collect_endpoint_stats() {
428 if [ $COLLECT_ENDPOINT_STATS -eq 0 ]; then
432 if [ $# -gt 5 ]; then
435 ENDPOINT_STAT_FILE=$TESTLOGS/$ATC/endpoint_$ATC_$1_$2".log"
438 if [ -f $ENDPOINT_STAT_FILE ]; then
439 ENDPOINT_VAL=$(< $ENDPOINT_STAT_FILE)
440 ENDPOINT_POS=$(echo $ENDPOINT_VAL | cut -f4 -d ' ' | cut -f1 -d '/')
441 ENDPOINT_NEG=$(echo $ENDPOINT_VAL | cut -f5 -d ' ' | cut -f1 -d '/')
444 if [ $5 -ge 200 ] && [ $5 -lt 300 ]; then
445 let ENDPOINT_POS=ENDPOINT_POS+$ENDPOINT_COUNT
447 let ENDPOINT_NEG=ENDPOINT_NEG+$ENDPOINT_COUNT
450 printf '%-2s %-10s %-45s %-16s %-16s' "#" "$3" "$4" "$ENDPOINT_POS/$ENDPOINT_POS" "$ENDPOINT_NEG/$ENDPOINT_NEG" > $ENDPOINT_STAT_FILE
453 # Function to collect stats on endpoints
454 # args: <app-id> <image-info>
455 __collect_endpoint_stats_image_info() {
456 if [ $COLLECT_ENDPOINT_STATS -eq 0 ]; then
459 ENDPOINT_STAT_FILE=$TESTLOGS/$ATC/imageinfo_$ATC_$1".log"
460 echo $A1PMS_IMAGE > $ENDPOINT_STAT_FILE
463 #Var for measuring execution time
464 TCTEST_START=$SECONDS
466 #Vars to hold the start time and timer text for a custom timer
467 TC_TIMER_STARTTIME=""
468 TC_TIMER_TIMER_TEXT=""
469 TC_TIMER_CURRENT_FAILS="" # Then numer of failed test when timer starts.
470 # Compared with the current number of fails at timer stop
471 # to judge the measurement reliability
473 #File to save timer measurement results
474 TIMER_MEASUREMENTS=".timer_measurement.txt"
475 echo -e "Activity \t Duration \t Info" > $TIMER_MEASUREMENTS
477 # If this is set, some images (controlled by the parameter repo-policy) will be re-tagged and pushed to this repo before any
479 IMAGE_REPO_POLICY="local"
482 echo "-------------------------------------------------------------------------------------------------"
483 echo "----------------------------------- Test case: "$ATC
484 echo "----------------------------------- Started: "$(date)
485 echo "-------------------------------------------------------------------------------------------------"
486 echo "-- Description: "$TC_ONELINE_DESCR
487 echo "-------------------------------------------------------------------------------------------------"
488 echo "----------------------------------- Test case setup -----------------------------------"
490 echo "Setting AUTOTEST_HOME="$AUTOTEST_HOME
494 if [ $# -lt 1 ]; then
497 if [ $paramerror -eq 0 ]; then
498 if [ "$1" != "remote" ] && [ "$1" != "remote-remove" ]; then
500 if [ -z "$paramerror_str" ]; then
501 paramerror_str="First arg shall be 'remote' or 'remote-remove'"
507 if [ $paramerror -eq 0 ]; then
508 if [ "$1" != "docker" ] && [ "$1" != "kube" ]; then
510 if [ -z "$paramerror_str" ]; then
511 paramerror_str="Second arg shall be 'docker' or 'kube'"
514 if [ $1 == "docker" ]; then
516 echo "Setting RUNMODE=DOCKER"
518 if [ $1 == "kube" ]; then
520 echo "Setting RUNMODE=KUBE"
526 while [ $paramerror -eq 0 ] && [ $foundparm -eq 0 ]; do
528 if [ $paramerror -eq 0 ]; then
529 if [ "$1" == "release" ]; then
530 IMAGE_CATEGORY="RELEASE"
531 echo "Option set - Release image tags used for applicable images "
536 if [ $paramerror -eq 0 ]; then
537 if [ "$1" == "auto-clean" ]; then
539 echo "Option set - Auto clean at end of test script"
544 if [ $paramerror -eq 0 ]; then
545 if [ "$1" == "--stop-at-error" ]; then
547 echo "Option set - Stop at first error"
552 if [ $paramerror -eq 0 ]; then
553 if [ "$1" == "--ricsim-prefix" ]; then
555 TMP_RIC_SIM_PREFIX=$1 #RIC_SIM_PREFIX need to be updated after sourcing of the env file
558 if [ -z "$paramerror_str" ]; then
559 paramerror_str="No prefix found for flag: '--ricsim-prefix'"
562 echo "Option set - Overriding RIC_SIM_PREFIX with: "$1
568 if [ $paramerror -eq 0 ]; then
569 if [ "$1" == "--env-file" ]; then
574 if [ -z "$paramerror_str" ]; then
575 paramerror_str="No env file found for flag: '--env-file'"
578 echo "Option set - Reading test env from: "$1
584 if [ $paramerror -eq 0 ]; then
585 if [ "$1" == "--use-local-image" ]; then
588 while [ $# -gt 0 ] && [[ "$1" != "--"* ]]; do
589 USE_LOCAL_IMAGES=$USE_LOCAL_IMAGES" "$1
590 if [[ "$AVAILABLE_IMAGES_OVERRIDE" != *"$1"* ]]; then
592 if [ -z "$paramerror_str" ]; then
593 paramerror_str="App name $1 is not available for local override for flag: '--use-local-image'"
599 if [ -z "$USE_LOCAL_IMAGES" ]; then
601 if [ -z "$paramerror_str" ]; then
602 paramerror_str="No app name found for flag: '--use-local-image'"
605 echo "Option set - Overriding with local images for app(s):"$USE_LOCAL_IMAGES
609 if [ $paramerror -eq 0 ]; then
610 if [ "$1" == "--use-snapshot-image" ]; then
611 USE_SNAPSHOT_IMAGES=""
613 while [ $# -gt 0 ] && [[ "$1" != "--"* ]]; do
614 USE_SNAPSHOT_IMAGES=$USE_SNAPSHOT_IMAGES" "$1
615 if [[ "$AVAILABLE_IMAGES_OVERRIDE" != *"$1"* ]]; then
617 if [ -z "$paramerror_str" ]; then
618 paramerror_str="App name $1 is not available for snapshot override for flag: '--use-snapshot-image'"
624 if [ -z "$USE_SNAPSHOT_IMAGES" ]; then
626 if [ -z "$paramerror_str" ]; then
627 paramerror_str="No app name found for flag: '--use-snapshot-image'"
630 echo "Option set - Overriding with snapshot images for app(s):"$USE_SNAPSHOT_IMAGES
634 if [ $paramerror -eq 0 ]; then
635 if [ "$1" == "--use-staging-image" ]; then
636 USE_STAGING_IMAGES=""
638 while [ $# -gt 0 ] && [[ "$1" != "--"* ]]; do
639 USE_STAGING_IMAGES=$USE_STAGING_IMAGES" "$1
640 if [[ "$AVAILABLE_IMAGES_OVERRIDE" != *"$1"* ]]; then
642 if [ -z "$paramerror_str" ]; then
643 paramerror_str="App name $1 is not available for staging override for flag: '--use-staging-image'"
649 if [ -z "$USE_STAGING_IMAGES" ]; then
651 if [ -z "$paramerror_str" ]; then
652 paramerror_str="No app name found for flag: '--use-staging-image'"
655 echo "Option set - Overriding with staging images for app(s):"$USE_STAGING_IMAGES
659 if [ $paramerror -eq 0 ]; then
660 if [ "$1" == "--use-release-image" ]; then
661 USE_RELEASE_IMAGES=""
663 while [ $# -gt 0 ] && [[ "$1" != "--"* ]]; do
664 USE_RELEASE_IMAGES=$USE_RELEASE_IMAGES" "$1
665 if [[ "$AVAILABLE_IMAGES_OVERRIDE" != *"$1"* ]]; then
667 if [ -z "$paramerror_str" ]; then
668 paramerror_str="App name $1 is not available for release override for flag: '--use-release-image'"
674 if [ -z "$USE_RELEASE_IMAGES" ]; then
676 if [ -z "$paramerror_str" ]; then
677 paramerror_str="No app name found for flag: '--use-release-image'"
680 echo "Option set - Overriding with release images for app(s):"$USE_RELEASE_IMAGES
684 if [ $paramerror -eq 0 ]; then
685 if [ "$1" == "--image-repo" ]; then
690 if [ -z "$paramerror_str" ]; then
691 paramerror_str="No image repo url found for : '--image-repo'"
694 echo "Option set - Image repo url: "$1
700 if [ $paramerror -eq 0 ]; then
701 if [ "$1" == "--repo-policy" ]; then
706 if [ -z "$paramerror_str" ]; then
707 paramerror_str="No policy found for : '--repo-policy'"
710 if [ "$1" == "local" ] || [ "$1" == "remote" ]; then
711 echo "Option set - Image repo policy: "$1
716 if [ -z "$paramerror_str" ]; then
717 paramerror_str="Repo policy shall be 'local' or 'remote'"
723 if [ $paramerror -eq 0 ]; then
724 if [ "$1" == "--cluster-timeout" ]; then
729 if [ -z "$paramerror_str" ]; then
730 paramerror_str="No timeout value found for : '--cluster-timeout'"
733 #Check if positive int
734 case ${CLUSTER_TIME_OUT#[+]} in
737 if [ -z "$paramerror_str" ]; then
738 paramerror_str="Value for '--cluster-timeout' not an int : "$CLUSTER_TIME_OUT
743 echo "Option set - Cluster timeout: "$1
749 if [ $paramerror -eq 0 ]; then
750 if [ "$1" == "--override" ]; then
752 TEST_ENV_VAR_FILE_OVERRIDE=$1
755 if [ -z "$paramerror_str" ]; then
756 paramerror_str="No env file found for flag: '--override'"
759 if [ ! -f $TEST_ENV_VAR_FILE_OVERRIDE ]; then
761 if [ -z "$paramerror_str" ]; then
762 paramerror_str="File for '--override' does not exist : "$TEST_ENV_VAR_FILE_OVERRIDE
765 echo "Option set - Override env from: "$1
771 if [ $paramerror -eq 0 ]; then
772 if [ "$1" == "--pre-clean" ]; then
774 echo "Option set - Pre-clean of kube/docker resouces"
779 if [ $paramerror -eq 0 ]; then
780 if [ "$1" == "--print-stats" ]; then
781 PRINT_CURRENT_STATS=1
782 echo "Option set - Print stats after every test-case and config"
787 if [ $paramerror -eq 0 ]; then
788 if [ "$1" == "--gen-stats" ]; then
789 COLLECT_RUNTIME_STATS=1
790 echo "Option set - Collect runtime statistics"
795 if [ $paramerror -eq 0 ]; then
796 if [ "$1" == "--delete-namespaces" ]; then
797 if [ $RUNMODE == "DOCKER" ]; then
798 DELETE_KUBE_NAMESPACES=0
799 echo "Option ignored - Delete namespaces (ignored when running docker)"
801 if [ -z "KUBE_PRESTARTED_IMAGES" ]; then
802 DELETE_KUBE_NAMESPACES=0
803 echo "Option ignored - Delete namespaces (ignored when using prestarted apps)"
805 DELETE_KUBE_NAMESPACES=1
806 echo "Option set - Delete namespaces"
813 if [ $paramerror -eq 0 ]; then
814 if [ "$1" == "--delete-containers" ]; then
815 if [ $RUNMODE == "DOCKER" ]; then
817 echo "Option set - Delete containers started by previous test(s)"
819 echo "Option ignored - Delete containers (ignored when running kube)"
825 if [ $paramerror -eq 0 ]; then
826 if [ "$1" == "--endpoint-stats" ]; then
827 COLLECT_ENDPOINT_STATS=1
828 echo "Option set - Collect endpoint statistics"
833 if [ $paramerror -eq 0 ]; then
834 if [ "$1" == "--kubeconfig" ]; then
838 if [ -z "$paramerror_str" ]; then
839 paramerror_str="No path found for : '--kubeconfig'"
843 if [ ! -z "$KUBECONF" ]; then
845 if [ -z "$paramerror_str" ]; then
846 paramerror_str="Only one of --kubeconfig/--kubecontext can be set"
849 KUBECONF="--kubeconfig $1"
850 echo "Option set - Kubeconfig path: "$1
856 if [ -z "$paramerror_str" ]; then
857 paramerror_str="File $1 for --kubeconfig not found"
863 if [ $paramerror -eq 0 ]; then
864 if [ "$1" == "--kubecontext" ]; then
868 if [ -z "$paramerror_str" ]; then
869 paramerror_str="No context-name found for : '--kubecontext'"
872 if [ ! -z "$KUBECONF" ]; then
874 if [ -z "$paramerror_str" ]; then
875 paramerror_str="Only one of --kubeconfig or --kubecontext can be set"
878 KUBECONF="--context $1"
879 echo "Option set - Kubecontext name: "$1
886 if [ $paramerror -eq 0 ]; then
887 if [ "$1" == "--host-path-dir" ]; then
891 if [ -z "$paramerror_str" ]; then
892 paramerror_str="No path found for : '--host-path-dir'"
895 HOST_PATH_BASE_DIR=$1
896 echo "Option set - Host path for kube set to: "$1
902 if [ $paramerror -eq 0 ]; then
903 if [ "$1" == "--docker-host" ]; then
907 if [ -z "$paramerror_str" ]; then
908 paramerror_str="No url found for : '--docker-host'"
911 export DOCKER_HOST="$1"
912 echo "Option set - DOCKER_HOST set to: "$1
918 if [ $paramerror -eq 0 ]; then
919 if [ "$1" == "--docker-host" ]; then
923 if [ -z "$paramerror_str" ]; then
924 paramerror_str="No url found for : '--docker-host'"
927 export DOCKER_HOST="$1"
928 echo "Option set - DOCKER_HOST set to: "$1
934 if [ $paramerror -eq 0 ]; then
935 if [ "$1" == "--docker-proxy" ]; then
939 if [ -z "$paramerror_str" ]; then
940 paramerror_str="No ip/host found for : '--docker-proxy'"
943 export LOCALHOST_NAME=$1
944 echo "Option set - docker proxy set to: "$1
954 if [ $paramerror -eq 0 ] && [ $# -gt 0 ]; then
956 if [ -z "$paramerror_str" ]; then
957 paramerror_str="Unknown parameter(s): "$@
961 if [ $paramerror -eq 1 ]; then
962 echo -e $RED"Incorrect arg list: "$paramerror_str$ERED
967 LOCALHOST_HTTP="http://$LOCALHOST_NAME"
968 LOCALHOST_HTTPS="https://$LOCALHOST_NAME"
970 # sourcing the selected env variables for the test case
971 if [ -f "$TEST_ENV_VAR_FILE" ]; then
972 echo -e $BOLD"Sourcing env vars from: "$TEST_ENV_VAR_FILE$EBOLD
974 if [ ! -z "$TEST_ENV_VAR_FILE_OVERRIDE" ]; then
975 echo -e $BOLD"Sourcing override env vars from: "$TEST_ENV_VAR_FILE_OVERRIDE$EBOLD
976 . $TEST_ENV_VAR_FILE_OVERRIDE
979 if [ -z "$TEST_ENV_PROFILE" ] || [ -z "$SUPPORTED_PROFILES" ]; then
980 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
983 for prof in $SUPPORTED_PROFILES; do
984 if [ "$TEST_ENV_PROFILE" == "$prof" ]; then
985 echo -e $GREEN"Test case supports the selected test env file"$EGREEN
989 if [ $found_profile -ne 1 ]; then
990 echo -e $RED"Test case does not support the selected test env file"$ERED
991 echo "Profile: "$TEST_ENV_PROFILE" Supported profiles: "$SUPPORTED_PROFILES
992 echo -e $RED"Exiting...."$ERED
997 echo -e $RED"Selected env var file does not exist: "$TEST_ENV_VAR_FILE$ERED
998 echo " Select one of following env var file matching the intended target of the test"
999 echo " Restart the test using the flag '--env-file <path-to-env-file>"
1000 ls $AUTOTEST_HOME/../common/test_env* | indent1
1004 #This var need be preserved from the command line option, if set, when env var is sourced.
1005 if [ ! -z "$TMP_RIC_SIM_PREFIX" ]; then
1006 RIC_SIM_PREFIX=$TMP_RIC_SIM_PREFIX
1009 if [ -z "$PROJECT_IMAGES_APP_NAMES" ]; then
1010 echo -e $RED"Var PROJECT_IMAGES_APP_NAMES must be defined in: "$TEST_ENV_VAR_FILE $ERED
1014 if [[ $SUPPORTED_RUNMODES != *"$RUNMODE"* ]]; then
1015 echo -e $RED"This test script does not support RUNMODE $RUNMODE"$ERED
1016 echo "Supported RUNMODEs: "$SUPPORTED_RUNMODES
1020 # Choose list of included apps depending on run-mode
1021 if [ $RUNMODE == "KUBE" ]; then
1022 INCLUDED_IMAGES=$KUBE_INCLUDED_IMAGES
1024 INCLUDED_IMAGES=$DOCKER_INCLUDED_IMAGES
1028 # auto adding system apps
1030 echo -e $BOLD"Auto adding system apps"$EBOLD
1031 if [ $RUNMODE == "KUBE" ]; then
1032 INCLUDED_IMAGES=$INCLUDED_IMAGES" "$TESTENV_KUBE_SYSTEM_APPS
1033 TMP_APPS=$TESTENV_KUBE_SYSTEM_APPS
1035 INCLUDED_IMAGES=$INCLUDED_IMAGES" "$TESTENV_DOCKER_SYSTEM_APPS
1036 TMP_APPS=$TESTENV_DOCKER_SYSTEM_APPS
1038 if [ ! -z "$TMP_APPS" ]; then
1039 for iapp in "$TMP_APPS"; do
1040 file_pointer=$(echo $iapp | tr '[:upper:]' '[:lower:]')
1041 file_pointer="../common/"$file_pointer"_api_functions.sh"
1043 while [ ${#padded_iapp} -lt 16 ]; do
1044 padded_iapp=$padded_iapp" "
1046 echo " Auto-adding system app $padded_iapp Sourcing $file_pointer"
1048 if [ $? -ne 0 ]; then
1049 echo " Include file $file_pointer contain errors. Exiting..."
1052 __added_apps=" $iapp "$__added_apps
1058 if [ $RUNMODE == "KUBE" ]; then
1059 TMP_APPS=$INCLUDED_IMAGES" "$KUBE_PRESTARTED_IMAGES
1061 TMP_APPS=$INCLUDED_IMAGES
1064 echo -e $BOLD"Auto adding included apps"$EBOLD
1065 for iapp in $TMP_APPS; do
1066 if [[ "$__added_apps" != *"$iapp"* ]]; then
1067 file_pointer=$(echo $iapp | tr '[:upper:]' '[:lower:]')
1068 file_pointer="../common/"$file_pointer"_api_functions.sh"
1070 while [ ${#padded_iapp} -lt 16 ]; do
1071 padded_iapp=$padded_iapp" "
1073 echo " Auto-adding included app $padded_iapp Sourcing $file_pointer"
1074 if [ ! -f "$file_pointer" ]; then
1075 echo " Include file $file_pointer for app $iapp does not exist"
1079 if [ $? -ne 0 ]; then
1080 echo " Include file $file_pointer contain errors. Exiting..."
1087 echo -e $BOLD"Test environment info"$EBOLD
1089 # Check needed installed sw
1092 if [ $? -ne 0 ] || [ -z "$tmp" ]; then
1093 echo -e $RED"bash is required to run the test environment, pls install"$ERED
1096 echo " bash is installed and using version:"
1097 echo "$(bash --version)" | indent2
1099 tmp=$(which python3)
1100 if [ $? -ne 0 ] || [ -z "$tmp" ]; then
1101 echo -e $RED"python3 is required to run the test environment, pls install"$ERED
1104 echo " python3 is installed and using version: $(python3 --version)"
1107 if [ $? -ne 0 ] || [ -z "$tmp" ]; then
1108 echo -e $RED"docker is required to run the test environment, pls install"$ERED
1111 echo " docker is installed and using versions:"
1112 echo " $(docker version --format 'Client version {{.Client.Version}} Server version {{.Server.Version}}')"
1114 if [ $RUNMODE == "DOCKER" ]; then
1115 tmp=$(which docker-compose)
1116 if [ $? -ne 0 ] || [ -z "$tmp" ]; then
1117 echo -e $RED"docker-compose is required to run the test environment, pls install"$ERED
1120 tmp=$(docker-compose version)
1121 echo " docker-compose installed and using version $tmp"
1122 if [[ "$tmp" == *'v2'* ]]; then
1123 DOCKER_COMPOSE_VERION="V2"
1127 if [ $RUNMODE == "KUBE" ]; then
1128 tmp=$(which kubectl)
1129 if [ $? -ne 0 ] || [ -z tmp ]; then
1130 echo -e $RED"kubectl is required to run the test environment in kubernetes mode, pls install"$ERED
1133 echo " kubectl is installed and using versions:"
1134 echo $(kubectl $KUBECONF version --short=true) | indent2
1135 res=$(kubectl $KUBECONF cluster-info 2>&1)
1136 if [ $? -ne 0 ]; then
1137 echo -e "$BOLD$RED############################################# $ERED$EBOLD"
1138 echo -e $BOLD$RED"Command 'kubectl '$KUBECONF' cluster-info' returned error $ERED$EBOLD"
1139 echo -e "$BOLD$RED############################################# $ERED$EBOLD"
1141 echo "kubectl response:"
1144 echo "This script may have been started with user with no permission to run kubectl"
1145 echo "Try running with 'sudo', set env KUBECONFIG or set '--kubeconfig' parameter"
1146 echo "Do either 1, 2 or 3 "
1149 echo "Run with sudo"
1150 echo -e $BOLD"sudo <test-script-and-parameters>"$EBOLD
1153 echo "Export KUBECONFIG and pass env to sudo - (replace user)"
1154 echo -e $BOLD"export KUBECONFIG='/home/<user>/.kube/config'"$EBOLD
1155 echo -e $BOLD"sudo -E <test-script-and-parameters>"$EBOLD
1158 echo "Set KUBECONFIG via script parameter"
1159 echo -e $BOLD"sudo ... --kubeconfig /home/<user>/.kube/<config-file> ...."$EBOLD
1160 echo "The config file need to downloaded from the cluster"
1164 echo " Node(s) and container runtime config"
1165 kubectl $KUBECONF get nodes -o wide | indent2
1167 if [ -z "$HOST_PATH_BASE_DIR" ]; then
1168 HOST_PATH_BASE_DIR="/tmp"
1169 echo " Persistent volumes will be mounted to $HOST_PATH_BASE_DIR on applicable node"
1170 echo " No guarantee that persistent volume data is available on all nodes in the cluster"
1172 echo "Persistent volumes will be mounted to base dir: $HOST_PATH_BASE_DIR"
1173 echo "Assuming this dir is mounted from each node to a dir on the localhost or other"
1174 echo "file system available to all nodes"
1181 echo -e $BOLD"Checking configured image setting for this test case"$EBOLD
1183 #Temp var to check for image variable name errors
1185 #Create a file with image info for later printing as a table
1186 image_list_file="./tmp/.image-list"
1187 echo -e "Application\tApp short name\tImage\ttag\ttag-switch" > $image_list_file
1189 # Check if image env var is set and if so export the env var with image to use (used by docker compose files)
1190 # arg: <app-short-name> <target-variable-name> <image-variable-name> <image-tag-variable-name> <tag-suffix> <image name>
1191 __check_and_create_image_var() {
1193 if [ $# -ne 6 ]; then
1194 echo "Expected arg: <app-short-name> <target-variable-name> <image-variable-name> <image-tag-variable-name> <tag-suffix> <image name>"
1199 __check_included_image $1
1200 if [ $? -ne 0 ]; then
1201 echo -e "$6\t$1\t<image-excluded>\t<no-tag>" >> $image_list_file
1202 # Image is excluded since the corresponding app is not used in this test
1205 tmp=${6}"\t"${1}"\t"
1206 #Create var from the input var names
1211 optional_image_repo_target=""
1213 if [ -z $image ]; then
1214 __check_ignore_image $1
1215 if [ $? -eq 0 ]; then
1217 if [ -z "$6" ]; then
1218 app_ds="<app ignored>"
1220 echo -e "$app_ds\t$1\t<image-ignored>\t<no-tag>" >> $image_list_file
1221 # Image is ignored since the corresponding the images is not set in the env file
1222 __remove_included_image $1 # Remove the image from the list of included images
1225 echo -e $RED"\$"$3" not set in $TEST_ENV_VAR_FILE"$ERED
1228 tmp=$tmp"<no-image>\t"
1231 optional_image_repo_target=$image
1233 #Add repo depending on image type
1234 if [ "$5" == "REMOTE_RELEASE" ]; then
1235 image=$NEXUS_RELEASE_REPO$image
1237 if [ "$5" == "REMOTE" ]; then
1238 image=$NEXUS_STAGING_REPO$image
1240 if [ "$5" == "REMOTE_SNAPSHOT" ]; then
1241 image=$NEXUS_SNAPSHOT_REPO$image
1243 if [ "$5" == "REMOTE_PROXY" ]; then
1244 image=$NEXUS_PROXY_REPO$image
1246 if [ "$5" == "REMOTE_RELEASE_ONAP" ]; then
1247 image=$NEXUS_RELEASE_REPO_ONAP$image
1249 if [ "$5" == "REMOTE_RELEASE_ORAN" ]; then
1250 image=$NEXUS_RELEASE_REPO_ORAN$image
1252 #No nexus repo added for local images, tag: LOCAL
1255 if [ -z $tag ]; then
1256 echo -e $RED"\$"$tmptag" not set in $TEST_ENV_VAR_FILE"$ERED
1259 tmp=$tmp"<no-tag>\t"
1264 echo -e "$tmp" >> $image_list_file
1266 export "${2}"=$image":"$tag #Note, this var may be set to the value of the target value below in __check_and_pull_image
1268 remote_or_local_push=false
1269 if [ ! -z "$IMAGE_REPO_ADR" ] && [[ $5 != *"PROXY"* ]]; then
1270 if [ $5 == "LOCAL" ]; then
1271 remote_or_local_push=true
1273 if [[ $5 == *"REMOTE"* ]]; then
1274 if [ "$IMAGE_REPO_POLICY" == "remote" ]; then
1275 remote_or_local_push=true
1279 if $remote_or_local_push; then # Only re-tag and push images according to policy, if repo is given
1280 export "${2}_SOURCE"=$image":"$tag #Var to keep the actual source image
1281 if [[ $optional_image_repo_target == *"/"* ]]; then # Replace all / with _ for images to push to external repo
1282 optional_image_repo_target_tmp=${optional_image_repo_target//\//_}
1283 optional_image_repo_target=$optional_image_repo_target_tmp
1285 export "${2}_TARGET"=$IMAGE_REPO_ADR"/"$optional_image_repo_target":"$tag #Create image + tag for optional image repo - pushed later if needed
1287 export "${2}_SOURCE"=""
1288 export "${2}_TARGET"=""
1292 # Check if app uses image included in this test run
1293 # Returns 0 if image is included, 1 if not
1294 __check_included_image() {
1295 for im in $INCLUDED_IMAGES; do
1296 if [ "$1" == "$im" ]; then
1303 # Check if app uses a project image
1304 # Returns 0 if image is included, 1 if not
1305 __check_project_image() {
1306 for im in $PROJECT_IMAGES; do
1307 if [ "$1" == "$im" ]; then
1314 # Check if app uses image built by the test script
1315 # Returns 0 if image is included, 1 if not
1316 __check_image_local_build() {
1317 for im in $LOCAL_IMAGE_BUILD; do
1318 if [ "$1" == "$im" ]; then
1325 # Check if app image is conditionally ignored in this test run
1326 # Returns 0 if image is conditionally ignored, 1 if not
1327 __check_ignore_image() {
1328 for im in $CONDITIONALLY_IGNORED_IMAGES; do
1329 if [ "$1" == "$im" ]; then
1336 # Removed image from included list of included images
1337 # Used when an image is marked as conditionally ignored
1338 __remove_included_image() {
1340 for im in $INCLUDED_IMAGES; do
1341 if [ "$1" != "$im" ]; then
1342 tmp_img_rem_list=$tmp_img_rem_list" "$im
1345 INCLUDED_IMAGES=$tmp_img_rem_list
1349 # Check if app is included in the prestarted set of apps
1350 # Returns 0 if image is included, 1 if not
1351 __check_prestarted_image() {
1352 for im in $KUBE_PRESTARTED_IMAGES; do
1353 if [ "$1" == "$im" ]; then
1360 # Check if an app shall use a local image, based on the cmd parameters
1361 __check_image_local_override() {
1362 for im in $USE_LOCAL_IMAGES; do
1363 if [ "$1" == "$im" ]; then
1370 # Check if app uses image override
1371 # Returns the image/tag suffix LOCAL for local image or REMOTE/REMOTE_RELEASE/REMOTE_SNAPSHOT for staging/release/snapshot image
1372 __check_image_override() {
1374 for im in $ORAN_IMAGES_APP_NAMES; do
1375 if [ "$1" == "$im" ]; then
1376 echo "REMOTE_RELEASE_ORAN"
1381 for im in $ONAP_IMAGES_APP_NAMES; do
1382 if [ "$1" == "$im" ]; then
1383 echo "REMOTE_RELEASE_ONAP"
1389 for im in $PROJECT_IMAGES_APP_NAMES; do
1390 if [ "$1" == "$im" ]; then
1395 if [ $found -eq 0 ]; then
1401 if [ $IMAGE_CATEGORY == "RELEASE" ]; then
1402 suffix="REMOTE_RELEASE"
1404 if [ $IMAGE_CATEGORY == "DEV" ]; then
1408 for im in $USE_STAGING_IMAGES; do
1409 if [ "$1" == "$im" ]; then
1414 for im in $USE_RELEASE_IMAGES; do
1415 if [ "$1" == "$im" ]; then
1416 suffix="REMOTE_RELEASE"
1420 for im in $USE_SNAPSHOT_IMAGES; do
1421 if [ "$1" == "$im" ]; then
1422 suffix="REMOTE_SNAPSHOT"
1426 for im in $USE_LOCAL_IMAGES; do
1427 if [ "$1" == "$im" ]; then
1433 if [ $CTR -gt 1 ]; then
1439 # Function to re-tag and image and push to another image repo
1440 __retag_and_push_image() {
1441 if [ ! -z "$IMAGE_REPO_ADR" ]; then
1442 source_image="${!1}"
1443 trg_var_name=$1_"TARGET" # This var is created in func __check_and_create_image_var
1444 target_image="${!trg_var_name}"
1446 if [ -z $target_image ]; then
1447 return 0 # Image with no target shall not be pushed
1450 echo -ne " Attempt to re-tag image to: ${BOLD}${target_image}${EBOLD}${SAMELINE}"
1451 tmp=$(docker image tag $source_image ${target_image} )
1452 if [ $? -ne 0 ]; then
1453 docker stop $tmp &> ./tmp/.dockererr
1456 echo -e " Attempt to re-tag image to: ${BOLD}${target_image}${EBOLD} - ${RED}Failed${ERED}"
1457 cat ./tmp/.dockererr
1460 echo -e " Attempt to re-tag image to: ${BOLD}${target_image}${EBOLD} - ${GREEN}OK${EGREEN}"
1462 echo -ne " Attempt to push re-tagged image: ${BOLD}${target_image}${EBOLD}${SAMELINE}"
1463 tmp=$(docker push ${target_image} )
1464 if [ $? -ne 0 ]; then
1465 docker stop $tmp &> ./tmp/.dockererr
1468 echo -e " Attempt to push re-tagged image: ${BOLD}${target_image}${EBOLD} - ${RED}Failed${ERED}"
1469 cat ./tmp/.dockererr
1472 echo -e " Attempt to push re-tagged image: ${BOLD}${target_image}${EBOLD} - ${GREEN}OK${EGREEN}"
1474 export "${1}"=$target_image
1479 #Function to check if image exist and stop+remove the container+pull new images as needed
1480 #args <script-start-arg> <descriptive-image-name> <container-base-name> <image-with-tag-var-name>
1481 __check_and_pull_image() {
1483 source_image="${!4}"
1485 echo -e " Checking $BOLD$2$EBOLD container(s) with basename: $BOLD$3$EBOLD using image: $BOLD$source_image$EBOLD"
1486 format_string="\"{{.Repository}}\\t{{.Tag}}\\t{{.CreatedSince}}\\t{{.Size}}\""
1487 tmp_im=$(docker images --format $format_string $source_image)
1489 if [ $1 == "local" ]; then
1490 if [ -z "$tmp_im" ]; then
1491 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
1495 echo -e " "$2" (local image): \033[1m"$source_image"\033[0m "$GREEN"OK"$EGREEN
1497 elif [ $1 == "remote" ] || [ $1 == "remote-remove" ]; then
1498 if [ $1 == "remote-remove" ]; then
1499 if [ $RUNMODE == "DOCKER" ]; then
1500 echo -ne " Attempt to stop and remove container(s), if running - ${SAMELINE}"
1501 tmp=$(docker ps -aq --filter name=${3} --filter network=${DOCKER_SIM_NWNAME})
1502 if [ $? -eq 0 ] && [ ! -z "$tmp" ]; then
1503 docker stop $tmp &> ./tmp/.dockererr
1504 if [ $? -ne 0 ]; then
1507 echo -e $RED" Container(s) could not be stopped - try manual stopping the container(s)"$ERED
1508 cat ./tmp/.dockererr
1512 echo -ne " Attempt to stop and remove container(s), if running - "$GREEN"stopped"$EGREEN"${SAMELINE}"
1513 tmp=$(docker ps -aq --filter name=${3} --filter network=${DOCKER_SIM_NWNAME}) &> /dev/null
1514 if [ $? -eq 0 ] && [ ! -z "$tmp" ]; then
1515 docker rm $tmp &> ./tmp/.dockererr
1516 if [ $? -ne 0 ]; then
1519 echo -e $RED" Container(s) could not be removed - try manual removal of the container(s)"$ERED
1520 cat ./tmp/.dockererr
1524 echo -e " Attempt to stop and remove container(s), if running - "$GREEN"stopped removed"$EGREEN
1530 if [ -z "$tmp_im" ]; then
1531 echo -ne " Pulling image${SAMELINE}"
1532 out=$(docker pull $source_image)
1533 if [ $? -ne 0 ]; then
1535 echo -e " Pulling image -$RED could not be pulled"$ERED
1537 echo $out > ./tmp/.dockererr
1541 echo $out > ./tmp/.dockererr
1542 if [[ $out == *"up to date"* ]]; then
1543 echo -e " Pulling image -$GREEN Image is up to date $EGREEN"
1544 elif [[ $out == *"Downloaded newer image"* ]]; then
1545 echo -e " Pulling image -$GREEN Newer image pulled $EGREEN"
1547 echo -e " Pulling image -$GREEN Pulled $EGREEN"
1550 echo -e " Pulling image -$GREEN OK $EGREEN(exists in local repository)"
1554 __retag_and_push_image $4
1559 setup_testenvironment() {
1560 # Check that image env setting are available
1563 # Image var setup for all project images included in the test
1564 for imagename in $APP_SHORT_NAMES; do
1565 __check_included_image $imagename
1567 __check_project_image $imagename
1569 if [ $incl -eq 0 ]; then
1570 if [ $proj -eq 0 ]; then
1571 IMAGE_SUFFIX=$(__check_image_override $imagename)
1572 if [ $? -ne 0 ]; then
1573 echo -e $RED"Image setting from cmd line not consistent for $imagename."$ERED
1579 # A function name is created from the app short name
1580 # for example app short name 'ICS' -> produce the function
1581 # name __ICS_imagesetup
1582 # This function is called and is expected to exist in the imported
1583 # file for the ics test functions
1584 # The resulting function impl will call '__check_and_create_image_var' function
1585 # with appropriate parameters
1586 # If the image suffix is none, then the component decides the suffix
1587 function_pointer="__"$imagename"_imagesetup"
1588 $function_pointer $IMAGE_SUFFIX
1590 function_pointer="__"$imagename"_test_requirements"
1595 #Errors in image setting - exit
1596 if [ $IMAGE_ERR -ne 0 ]; then
1600 #Print a tables of the image settings
1601 echo -e $BOLD"Images configured for start arg: "$START_ARG $EBOLD
1602 column -t -s $'\t' $image_list_file | indent1
1606 #Set the SIM_GROUP var
1607 echo -e $BOLD"Setting var to main dir of all container/simulator scripts"$EBOLD
1608 if [ -z "$SIM_GROUP" ]; then
1609 SIM_GROUP=$AUTOTEST_HOME/../simulator-group
1610 if [ ! -d $SIM_GROUP ]; then
1611 echo "Trying to set env var SIM_GROUP to dir 'simulator-group' in the nontrtric repo, but failed."
1612 echo -e $RED"Please set the SIM_GROUP manually in the applicable $TEST_ENV_VAR_FILE"$ERED
1615 echo " SIM_GROUP auto set to: " $SIM_GROUP
1617 elif [ $SIM_GROUP = *simulator_group ]; then
1618 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
1621 echo " SIM_GROUP env var already set to: " $SIM_GROUP
1626 #Temp var to check for image pull errors
1630 echo -e $BOLD"Deleting namespaces"$EBOLD
1633 if [ "$DELETE_KUBE_NAMESPACES" -eq 1 ]; then
1634 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
1635 if [ $? -ne 0 ]; then
1636 echo " Cannot get list of namespaces...ignoring delete"
1638 for test_env_ns in $test_env_namespaces; do
1639 __kube_delete_namespace $test_env_ns
1643 echo " Namespace delete option not set or ignored"
1648 echo -e $BOLD"Deleting containers"$EBOLD
1650 if [ "$DELETE_CONTAINERS" -eq 1 ]; then
1651 echo " Stopping containers label 'nrttest_app'..."
1652 docker stop $(docker ps -qa --filter "label=nrttest_app") 2> /dev/null
1653 echo " Removing stopped containers..."
1654 docker rm $(docker ps -qa --filter "label=nrttest_app") 2> /dev/null
1656 echo " Contatiner delete option not set or ignored"
1660 # The following sequence pull the configured images
1661 echo -e $BOLD"Pulling configured images, if needed"$EBOLD
1662 if [ ! -z "$IMAGE_REPO_ADR" ] && [ $IMAGE_REPO_POLICY == "local" ]; then
1663 echo -e $YELLOW" Excluding all remote image check/pull when running with image repo: $IMAGE_REPO_ADR and image policy $IMAGE_REPO_POLICY"$EYELLOW
1665 for imagename in $APP_SHORT_NAMES; do
1666 __check_included_image $imagename
1668 __check_project_image $imagename
1670 if [ $incl -eq 0 ]; then
1671 if [ $proj -eq 0 ]; then
1672 START_ARG_MOD=$START_ARG
1673 __check_image_local_override $imagename
1674 if [ $? -eq 1 ]; then
1675 START_ARG_MOD="local"
1678 START_ARG_MOD=$START_ARG
1680 __check_image_local_build $imagename
1681 #No pull of images built locally
1682 if [ $? -ne 0 ]; then
1683 # A function name is created from the app short name
1684 # for example app short name 'HTTPPROXY' -> produce the function
1685 # name __HTTPPROXY_imagesetup
1686 # This function is called and is expected to exist in the imported
1687 # file for the httpproxy test functions
1688 # The resulting function impl will call '__check_and_pull_image' function
1689 # with appropriate parameters
1690 function_pointer="__"$imagename"_imagepull"
1691 $function_pointer $START_ARG_MOD $START_ARG
1694 echo -e $YELLOW" Excluding $imagename image from image check/pull"$EYELLOW
1699 #Errors in image setting - exit
1700 if [ $IMAGE_ERR -ne 0 ]; then
1702 echo "#################################################################################################"
1703 echo -e $RED"One or more images could not be pulled or containers using the images could not be stopped/removed"$ERED
1704 echo -e $RED"Or local image, overriding remote image, does not exist"$ERED
1705 if [ $IMAGE_CATEGORY == "DEV" ]; then
1707 echo -e $RED"Note that SNAPSHOT and staging images may be purged from nexus after a certain period."$ERED
1708 echo -e $RED"In addition, the image may not have been updated in the current release so no SNAPSHOT or staging image exists"$ERED
1709 echo -e $RED"In these cases, switch to use a released image instead, use the flag '--use-release-image <App-short-name>'"$ERED
1710 echo -e $RED"Use the 'App-short-name' for the applicable image from the above table: 'Images configured for start arg'."$ERED
1712 echo "#################################################################################################"
1719 echo -e $BOLD"Building images needed for test"$EBOLD
1721 for imagename in $APP_SHORT_NAMES; do
1722 cd $AUTOTEST_HOME #Always reset to orig dir
1723 __check_image_local_build $imagename
1724 if [ $? -eq 0 ]; then
1725 __check_included_image $imagename
1726 if [ $? -eq 0 ]; then
1727 # A function name is created from the app short name
1728 # for example app short name 'MR' -> produce the function
1729 # name __MR_imagebuild
1730 # This function is called and is expected to exist in the imported
1731 # file for the mr test functions
1732 # The resulting function impl shall build the imagee
1733 function_pointer="__"$imagename"_imagebuild"
1737 echo -e $YELLOW" Excluding image for app $imagename from image build"$EYELLOW
1742 cd $AUTOTEST_HOME # Just to make sure...
1746 # Create a table of the images used in the script - from local repo
1747 echo -e $BOLD"Local docker registry images used in this test script"$EBOLD
1749 docker_tmp_file=./tmp/.docker-images-table
1750 format_string="{{.Repository}}\\t{{.Tag}}\\t{{.CreatedSince}}\\t{{.Size}}\\t{{.CreatedAt}}"
1751 echo -e "Application\tRepository\tTag\tCreated since\tSize\tCreated at" > $docker_tmp_file
1753 for imagename in $APP_SHORT_NAMES; do
1754 __check_included_image $imagename
1755 if [ $? -eq 0 ]; then
1756 # Only print image data if image repo is null, or if image repo is set and image is local
1758 if [ -z "$IMAGE_REPO_ADR" ]; then
1761 __check_image_local_build $imagename
1762 if [ $? -eq 0 ]; then
1766 if [ $print_image_data -eq 1 ]; then
1767 # A function name is created from the app short name
1768 # for example app short name 'MR' -> produce the function
1769 # name __MR_imagebuild
1770 # This function is called and is expected to exist in the imported
1771 # file for the mr test functions
1772 # The resulting function impl shall build the imagee
1773 function_pointer="__"$imagename"_image_data"
1774 $function_pointer "$format_string" $docker_tmp_file
1779 column -t -s $'\t' $docker_tmp_file | indent1
1783 if [ ! -z "$IMAGE_REPO_ADR" ]; then
1785 # Create a table of the images used in the script - from remote repo
1786 echo -e $BOLD"Remote repo images used in this test script"$EBOLD
1787 echo -e $YELLOW"-- Note: These image will be pulled when the container starts. Images not managed by the test engine --"$EYELLOW
1789 docker_tmp_file=./tmp/.docker-images-table
1790 format_string="{{.Repository}}\\t{{.Tag}}"
1791 echo -e "Application\tRepository\tTag" > $docker_tmp_file
1793 for imagename in $APP_SHORT_NAMES; do
1794 __check_included_image $imagename
1795 if [ $? -eq 0 ]; then
1796 # Only print image data if image repo is null, or if image repo is set and image is local
1797 __check_image_local_build $imagename
1798 if [ $? -ne 0 ]; then
1799 # A function name is created from the app short name
1800 # for example app short name 'MR' -> produce the function
1801 # name __MR_imagebuild
1802 # This function is called and is expected to exist in the imported
1803 # file for the mr test functions
1804 # The resulting function impl shall build the imagee
1805 function_pointer="__"$imagename"_image_data"
1806 $function_pointer "$format_string" $docker_tmp_file
1811 column -t -s $'\t' $docker_tmp_file | indent1
1816 if [ $RUNMODE == "KUBE" ]; then
1818 echo "================================================================================="
1819 echo "================================================================================="
1821 if [ -z "$IMAGE_REPO_ADR" ]; then
1822 echo -e $YELLOW" The image pull policy is set to 'Never' - assuming a local image repo is available for all images"$EYELLOW
1823 echo -e " This setting only works on single node clusters on the local machine"
1824 echo -e " It does not work with multi-node clusters or remote clusters. "
1825 export KUBE_IMAGE_PULL_POLICY="Never"
1827 echo -e $YELLOW" The image pull policy is set to 'Always'"$EYELLOW
1828 echo -e " This setting work on local clusters, multi-node clusters and remote cluster. "
1829 echo -e " Only locally built images are managed. Remote images are always pulled from remote repos"
1830 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"
1831 export KUBE_IMAGE_PULL_POLICY="Always"
1833 #CLUSTER_IP=$(kubectl $KUBECONF config view -o jsonpath={.clusters[0].cluster.server} | awk -F[/:] '{print $4}')
1834 #echo -e $YELLOW" The cluster hostname/ip is: $CLUSTER_IP"$EYELLOW
1836 echo "================================================================================="
1837 echo "================================================================================="
1841 echo -e $BOLD"======================================================="$EBOLD
1842 echo -e $BOLD"== Common test setup completed - test script begins =="$EBOLD
1843 echo -e $BOLD"======================================================="$EBOLD
1848 for imagename in $APP_SHORT_NAMES; do
1849 __check_included_image $imagename
1851 __check_prestarted_image $imagename
1853 if [ $retcode_i -eq 0 ] || [ $retcode_p -eq 0 ]; then
1854 # A function name is created from the app short name
1855 # for example app short name 'RICMSIM' -> produce the function
1856 # name __RICSIM__initial_setup
1857 # This function is called and is expected to exist in the imported
1858 # file for the ricsim test functions
1859 # The resulting function impl shall perform initial setup of port, host etc
1861 function_pointer="__"$imagename"_initial_setup"
1864 function_pointer="__"$imagename"_statisics_setup"
1865 LOG_STAT_ARGS=$LOG_STAT_ARGS" "$($function_pointer)
1869 if [ $COLLECT_RUNTIME_STATS -eq 1 ]; then
1870 ../common/genstat.sh $RUNMODE $SECONDS $TESTLOGS/$ATC/stat_data.csv $LOG_STAT_ARGS &
1871 COLLECT_RUNTIME_STATS_PID=$!
1876 # Function to print the test result, shall be the last cmd in a test script
1878 # (Function for test scripts)
1882 duration=$((TCTEST_END-TCTEST_START))
1884 echo "-------------------------------------------------------------------------------------------------"
1885 echo "------------------------------------- Test case: "$ATC
1886 echo "------------------------------------- Ended: "$(date)
1887 echo "-------------------------------------------------------------------------------------------------"
1888 echo "-- Description: "$TC_ONELINE_DESCR
1889 echo "-- Execution time: " $duration " seconds"
1890 echo "-- Used env file: "$TEST_ENV_VAR_FILE
1891 echo "-------------------------------------------------------------------------------------------------"
1892 echo "------------------------------------- RESULTS"
1896 if [ $RES_DEVIATION -gt 0 ]; then
1897 echo "Test case deviations"
1898 echo "===================================="
1902 echo "Timer measurement in the test script"
1903 echo "===================================="
1904 column -t -s $'\t' $TIMER_MEASUREMENTS
1905 if [ $RES_PASS != $RES_TEST ]; then
1906 echo -e $RED"Measurement may not be reliable when there are failed test - failures may cause long measurement values due to timeouts etc."$ERED
1910 if [ $COLLECT_RUNTIME_STATS -eq 1 ]; then
1911 echo "Runtime statistics collected in file: "$TESTLOGS/$ATC/stat_data.csv
1915 total=$((RES_PASS+RES_FAIL))
1916 if [ $RES_TEST -eq 0 ]; then
1917 echo -e "\033[1mNo tests seem to have been executed. Check the script....\033[0m"
1918 echo -e "\033[31m\033[1m ___ ___ ___ ___ ___ _____ ___ _ ___ _ _ _ ___ ___ \033[0m"
1919 echo -e "\033[31m\033[1m/ __|/ __| _ \_ _| _ \_ _| | __/_\ |_ _| | | | | | _ \ __|\033[0m"
1920 echo -e "\033[31m\033[1m\__ \ (__| /| || _/ | | | _/ _ \ | || |_| |_| | / _| \033[0m"
1921 echo -e "\033[31m\033[1m|___/\___|_|_\___|_| |_| |_/_/ \_\___|____\___/|_|_\___|\033[0m"
1922 elif [ $total != $RES_TEST ]; then
1923 echo -e "\033[1mTotal number of tests does not match the sum of passed and failed tests. Check the script....\033[0m"
1924 echo -e "\033[31m\033[1m ___ ___ ___ ___ ___ _____ ___ _ ___ _ _ _ ___ ___ \033[0m"
1925 echo -e "\033[31m\033[1m/ __|/ __| _ \_ _| _ \_ _| | __/_\ |_ _| | | | | | _ \ __|\033[0m"
1926 echo -e "\033[31m\033[1m\__ \ (__| /| || _/ | | | _/ _ \ | || |_| |_| | / _| \033[0m"
1927 echo -e "\033[31m\033[1m|___/\___|_|_\___|_| |_| |_/_/ \_\___|____\___/|_|_\___|\033[0m"
1928 elif [ $RES_CONF_FAIL -ne 0 ]; then
1929 echo -e "\033[1mOne or more configurations has failed. Check the script log....\033[0m"
1930 echo -e "\033[31m\033[1m ___ ___ ___ ___ ___ _____ ___ _ ___ _ _ _ ___ ___ \033[0m"
1931 echo -e "\033[31m\033[1m/ __|/ __| _ \_ _| _ \_ _| | __/_\ |_ _| | | | | | _ \ __|\033[0m"
1932 echo -e "\033[31m\033[1m\__ \ (__| /| || _/ | | | _/ _ \ | || |_| |_| | / _| \033[0m"
1933 echo -e "\033[31m\033[1m|___/\___|_|_\___|_| |_| |_/_/ \_\___|____\___/|_|_\___|\033[0m"
1934 elif [ $RES_PASS = $RES_TEST ]; then
1935 echo -e "All tests \033[32m\033[1mPASS\033[0m"
1936 echo -e "\033[32m\033[1m ___ _ ___ ___ \033[0m"
1937 echo -e "\033[32m\033[1m | _ \/_\ / __/ __| \033[0m"
1938 echo -e "\033[32m\033[1m | _/ _ \\__ \__ \\ \033[0m"
1939 echo -e "\033[32m\033[1m |_|/_/ \_\___/___/ \033[0m"
1942 # Update test suite counter
1943 if [ -f .tmp_tcsuite_pass_ctr ]; then
1944 tmpval=$(< .tmp_tcsuite_pass_ctr)
1946 echo $tmpval > .tmp_tcsuite_pass_ctr
1948 if [ -f .tmp_tcsuite_pass ]; then
1949 echo " - "$ATC " -- "$TC_ONELINE_DESCR" Execution time: "$duration" seconds" >> .tmp_tcsuite_pass
1951 #Create file with OK exit code
1952 echo "0" > "$AUTOTEST_HOME/.result$ATC.txt"
1953 echo "0" > "$TESTLOGS/$ATC/.result$ATC.txt"
1955 echo -e "One or more tests with status \033[31m\033[1mFAIL\033[0m "
1956 echo -e "\033[31m\033[1m ___ _ ___ _ \033[0m"
1957 echo -e "\033[31m\033[1m | __/_\ |_ _| | \033[0m"
1958 echo -e "\033[31m\033[1m | _/ _ \ | || |__ \033[0m"
1959 echo -e "\033[31m\033[1m |_/_/ \_\___|____|\033[0m"
1961 # Update test suite counter
1962 if [ -f .tmp_tcsuite_fail_ctr ]; then
1963 tmpval=$(< .tmp_tcsuite_fail_ctr)
1965 echo $tmpval > .tmp_tcsuite_fail_ctr
1967 if [ -f .tmp_tcsuite_fail ]; then
1968 echo " - "$ATC " -- "$TC_ONELINE_DESCR" Execution time: "$duration" seconds" >> .tmp_tcsuite_fail
1972 echo "++++ Number of tests: "$RES_TEST
1973 echo "++++ Number of passed tests: "$RES_PASS
1974 echo "++++ Number of failed tests: "$RES_FAIL
1976 echo "++++ Number of failed configs: "$RES_CONF_FAIL
1978 echo "++++ Number of test case deviations: "$RES_DEVIATION
1980 echo "------------------------------------- Test case complete ---------------------------------"
1981 echo "-------------------------------------------------------------------------------------------------"
1985 #####################################################################
1986 ###### Functions for start, configuring, stoping, cleaning etc ######
1987 #####################################################################
1989 # Start timer for time measurement
1990 # args: <timer message to print> - timer value and message will be printed both on screen
1991 # and in the timer measurement report - if at least one "print_timer is called"
1993 echo -e $BOLD"INFO(${BASH_LINENO[0]}): "${FUNCNAME[0]}"," $@ $EBOLD
1994 TC_TIMER_STARTTIME=$SECONDS
1995 TC_TIMER_TIMER_TEXT="${@:1}"
1996 if [ $# -ne 1 ]; then
1997 __print_err "need 1 arg, <timer message to print>" $@
1998 TC_TIMER_TIMER_TEXT=${FUNCNAME[0]}":"${BASH_LINENO[0]}
1999 echo " Assigning timer name: "$TC_TIMER_TIMER_TEXT
2001 TC_TIMER_CURRENT_FAILS=$(($RES_FAIL+$RES_CONF_FAIL))
2002 echo " Timer started: $(date)"
2005 # Print the running timer the value of the time (in seconds)
2006 # Timer value and message will be printed both on screen and in the timer measurement report
2008 echo -e $BOLD"INFO(${BASH_LINENO[0]}): "${FUNCNAME[0]}"," $TC_TIMER_TIMER_TEXT $EBOLD
2009 if [ -z "$TC_TIMER_STARTTIME" ]; then
2010 __print_err "timer not started" $@
2013 duration=$(($SECONDS-$TC_TIMER_STARTTIME))
2014 if [ $duration -eq 0 ]; then
2015 duration="<1 second"
2017 duration=$duration" seconds"
2019 echo " Timer duration :" $duration
2021 if [ $(($RES_FAIL+$RES_CONF_FAIL)) -ne $TC_TIMER_CURRENT_FAILS ]; then
2022 res="Failures occured during test - timer not reliabled"
2025 echo -e "$TC_TIMER_TIMER_TEXT \t $duration \t $res" >> $TIMER_MEASUREMENTS
2028 # Print info about a deviations from intended tests
2029 # Each deviation counted is also printed in the testreport
2030 # args <deviation message to print>
2032 echo -e $BOLD"DEVIATION(${BASH_LINENO[0]}): "${FUNCNAME[0]} $EBOLD
2033 if [ $# -lt 1 ]; then
2035 __print_err "need 1 or more args, <deviation message to print>" $@
2039 echo -e $BOLD$YELLOW" Test case deviation: ${@:1}"$EYELLOW$EBOLD
2040 echo "Line: ${BASH_LINENO[0]} - ${@:1}" >> $DEVIATION_FILE
2041 __print_current_stats
2045 # Stop at first FAIL test case and take all logs - only for debugging/trouble shooting
2046 __check_stop_at_error() {
2047 if [ $STOP_AT_ERROR -eq 1 ]; then
2048 echo -e $RED"Test script configured to stop at first FAIL, taking all logs and stops"$ERED
2049 store_logs "STOP_AT_ERROR"
2051 # Update test suite counter
2052 if [ -f .tmp_tcsuite_fail_ctr ]; then
2053 tmpval=$(< .tmp_tcsuite_fail_ctr)
2055 echo $tmpval > .tmp_tcsuite_fail_ctr
2057 if [ -f .tmp_tcsuite_fail ]; then
2058 echo " - "$ATC " -- "$TC_ONELINE_DESCR" Execution stopped due to error" >> .tmp_tcsuite_fail
2065 # Stop and remove all containers
2067 # (Not for test scripts)
2068 __clean_containers() {
2070 echo -e $BOLD"Docker clean and stopping and removing all running containers, by container name"$EBOLD
2073 running_contr_file="./tmp/running_contr.txt"
2074 > $running_contr_file
2076 # Get list of all containers started by the test script
2077 for imagename in $APP_SHORT_NAMES; do
2078 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
2080 running_contr_file_empty="No docker containers running, started by previous test execution"
2081 if [ -s $running_contr_file ]; then
2082 running_contr_file_empty=""
2085 # Kill all containers started by the test env - to speed up shut down
2086 docker kill $(docker ps -a --filter "label=nrttest_app" --format '{{.Names}}') &> /dev/null
2088 tab_heading1="App display name"
2089 tab_heading2="App short name"
2090 tab_heading3="Container name"
2092 tab_heading1_len=${#tab_heading1}
2093 tab_heading2_len=${#tab_heading2}
2094 tab_heading3_len=${#tab_heading3}
2096 #Calc field lengths of each item in the list of containers
2098 if (( $cntr % 3 == 0 ));then
2099 if [ ${#p} -gt $tab_heading1_len ]; then
2100 tab_heading1_len=${#p}
2103 if (( $cntr % 3 == 1));then
2104 if [ ${#p} -gt $tab_heading2_len ]; then
2105 tab_heading2_len=${#p}
2108 if (( $cntr % 3 == 2));then
2109 if [ ${#p} -gt $tab_heading3_len ]; then
2110 tab_heading3_len=${#p}
2114 done <$running_contr_file
2116 let tab_heading1_len=tab_heading1_len+2
2117 while (( ${#tab_heading1} < $tab_heading1_len)); do
2118 tab_heading1="$tab_heading1"" "
2121 let tab_heading2_len=tab_heading2_len+2
2122 while (( ${#tab_heading2} < $tab_heading2_len)); do
2123 tab_heading2="$tab_heading2"" "
2126 let tab_heading3_len=tab_heading3_len+2
2127 while (( ${#tab_heading3} < $tab_heading3_len)); do
2128 tab_heading3="$tab_heading3"" "
2131 if [ ! -z "$running_contr_file_empty" ]; then
2132 echo $running_contr_file_empty | indent1
2134 echo " $tab_heading1$tab_heading2$tab_heading3"" Actions"
2137 if (( $cntr % 3 == 0 ));then
2140 heading_len=$tab_heading1_len
2142 if (( $cntr % 3 == 1));then
2144 heading_len=$tab_heading2_len
2146 if (( $cntr % 3 == 2));then
2149 heading_len=$tab_heading3_len
2151 while (( ${#heading} < $heading_len)); do
2152 heading="$heading"" "
2155 if (( $cntr % 3 == 2));then
2156 echo -ne $row$SAMELINE
2157 echo -ne " $row ${GREEN}stopping...${EGREEN}${SAMELINE}"
2158 docker stop $(docker ps -qa --filter name=${contr} --filter network=$DOCKER_SIM_NWNAME) &> /dev/null
2159 echo -ne " $row ${GREEN}stopped removing...${EGREEN}${SAMELINE}"
2160 docker rm --force $(docker ps -qa --filter name=${contr} --filter network=$DOCKER_SIM_NWNAME) &> /dev/null
2161 echo -e " $row ${GREEN}stopped removed ${EGREEN}"
2164 done <$running_contr_file
2169 echo -e $BOLD" Removing docker network"$EBOLD
2170 TMP=$(docker network ls -q --filter name=$DOCKER_SIM_NWNAME)
2171 if [ "$TMP" == $DOCKER_SIM_NWNAME ]; then
2172 docker network rm $DOCKER_SIM_NWNAME | indent2
2173 if [ $? -ne 0 ]; then
2174 echo -e $RED" Cannot remove docker network. Manually remove or disconnect containers from $DOCKER_SIM_NWNAME"$ERED
2178 echo -e "$GREEN Done$EGREEN"
2180 echo -e $BOLD" Removing all unused docker neworks"$EBOLD
2181 docker network prune --force | indent2
2182 echo -e "$GREEN Done$EGREEN"
2184 echo -e $BOLD" Removing all unused docker volumes"$EBOLD
2185 docker volume prune --force | indent2
2186 echo -e "$GREEN Done$EGREEN"
2188 echo -e $BOLD" Removing all dangling/untagged docker images"$EBOLD
2189 docker rmi --force $(docker images -q -f dangling=true) &> /dev/null
2190 echo -e "$GREEN Done$EGREEN"
2193 CONTRS=$(docker ps | awk '$1 != "CONTAINER" { n++ }; END { print n+0 }')
2194 if [ $? -eq 0 ]; then
2195 if [ $CONTRS -ne 0 ]; then
2196 echo -e $RED"Containers running, may cause distubance to the test case"$ERED
2197 docker ps -a | indent1
2203 ###################################
2204 ### Functions for kube management
2205 ###################################
2207 # Get resource type for scaling
2208 # args: <resource-name> <namespace>
2209 __kube_get_resource_type() {
2210 kubectl $KUBECONF get deployment $1 -n $2 1> /dev/null 2> ./tmp/kubeerr
2211 if [ $? -eq 0 ]; then
2215 kubectl $KUBECONF get sts $1 -n $2 1> /dev/null 2> ./tmp/kubeerr
2216 if [ $? -eq 0 ]; then
2220 echo "unknown-resource-type"
2224 # Scale a kube resource to a specific count
2225 # args: <resource-type> <resource-name> <namespace> <target-count>
2226 # (Not for test scripts)
2228 echo -ne " Setting $1 $2 replicas=$4 in namespace $3"$SAMELINE
2229 kubectl $KUBECONF scale $1 $2 -n $3 --replicas=$4 1> /dev/null 2> ./tmp/kubeerr
2230 if [ $? -ne 0 ]; then
2231 echo -e " Setting $1 $2 replicas=$4 in namespace $3 $RED Failed $ERED"
2233 echo " Message: $(<./tmp/kubeerr)"
2236 echo -e " Setting $1 $2 replicas=$4 in namespace $3 $GREEN OK $EGREEN"
2241 for i in {1..500}; do
2242 count=$(kubectl $KUBECONF get $1/$2 -n $3 -o jsonpath='{.status.replicas}' 2> /dev/null)
2244 if [ -z "$count" ]; then
2245 #No value is sometimes returned for some reason, in case the resource has replica 0
2248 if [ $retcode -ne 0 ]; then
2249 echo -e "$RED Cannot fetch current replica count for $1 $2 in namespace $3 $ERED"
2254 if [ $count -ne $4 ]; then
2255 echo -ne " Waiting for $1 $2 replicas=$4 in namespace $3. Replicas=$count after $(($SECONDS-$TSTART)) seconds $SAMELINE"
2258 echo -e " Waiting for $1 $2 replicas=$4 in namespace $3. Replicas=$count after $(($SECONDS-$TSTART)) seconds"
2259 echo -e " Replicas=$4 after $(($SECONDS-$TSTART)) seconds $GREEN OK $EGREEN"
2265 echo -e "$RED Replica count did not reach target replicas=$4. Failed with replicas=$count $ERED"
2270 # Scale all kube resource sets to 0 in a namespace for resources having a certain lable and label-id
2271 # This function does not wait for the resource to reach 0
2272 # args: <namespace> <label-name> <label-id>
2273 # (Not for test scripts)
2274 __kube_scale_all_resources() {
2278 resources="deployment replicaset statefulset"
2279 for restype in $resources; do
2280 result=$(kubectl $KUBECONF get $restype -n $namespace -o jsonpath='{.items[?(@.metadata.labels.'$labelname'=="'$labelid'")].metadata.name}')
2281 if [ $? -eq 0 ] && [ ! -z "$result" ]; then
2282 for resid in $result; do
2283 echo -ne " Ordered caling $restype $resid in namespace $namespace with label $labelname=$labelid to 0"$SAMELINE
2284 kubectl $KUBECONF scale $restype $resid -n $namespace --replicas=0 1> /dev/null 2> ./tmp/kubeerr
2285 echo -e " Ordered scaling $restype $resid in namespace $namespace with label $labelname=$labelid to 0 $GREEN OK $EGREEN"
2291 # Scale all kube resource sets to 0 in a namespace for resources having a certain lable and an optional label-id
2292 # This function do wait for the resource to reach 0
2293 # args: <namespace> <label-name> [ <label-id> ]
2294 # (Not for test scripts)
2295 __kube_scale_and_wait_all_resources() {
2299 if [ -z "$3" ]; then
2300 echo " Attempt to scale - deployment replicaset statefulset - in namespace $namespace with label $labelname"
2302 echo " Attempt to scale - deployment replicaset statefulset - in namespace $namespace with label $labelname=$labelid"
2304 resources="deployment replicaset statefulset"
2306 while [ $scaled_all -ne 0 ]; do
2308 for restype in $resources; do
2309 if [ -z "$3" ]; then
2310 result=$(kubectl $KUBECONF get $restype -n $namespace -o jsonpath='{.items[?(@.metadata.labels.'$labelname')].metadata.name}')
2312 result=$(kubectl $KUBECONF get $restype -n $namespace -o jsonpath='{.items[?(@.metadata.labels.'$labelname'=="'$labelid'")].metadata.name}')
2314 if [ $? -eq 0 ] && [ ! -z "$result" ]; then
2315 for resid in $result; do
2316 echo -e " Ordered scaling $restype $resid in namespace $namespace with label $labelname=$labelid to 0"
2317 kubectl $KUBECONF scale $restype $resid -n $namespace --replicas=0 1> /dev/null 2> ./tmp/kubeerr
2320 while [ $count -ne 0 ]; do
2321 count=$(kubectl $KUBECONF get $restype $resid -n $namespace -o jsonpath='{.status.replicas}' 2> /dev/null)
2322 echo -ne " Scaling $restype $resid in namespace $namespace with label $labelname=$labelid to 0, current count=$count"$SAMELINE
2323 if [ $? -eq 0 ] && [ ! -z "$count" ]; then
2328 duration=$(($SECONDS-$T_START))
2329 if [ $duration -gt 100 ]; then
2330 #Forcring count 0, to avoid hanging for failed scaling
2335 echo -e " Scaled $restype $resid in namespace $namespace with label $labelname=$labelid to 0, current count=$count $GREEN OK $EGREEN"
2342 # Remove all kube resources in a namespace for resources having a certain label and label-id
2343 # This function wait until the resources are gone. Scaling to 0 must have been ordered previously
2344 # args: <namespace> <label-name> <label-id>
2345 # (Not for test scripts)
2346 __kube_delete_all_resources() {
2350 resources="deployments replicaset statefulset services pods configmaps persistentvolumeclaims persistentvolumes serviceaccounts clusterrolebindings secrets authorizationpolicies requestauthentications"
2351 deleted_resourcetypes=""
2352 for restype in $resources; do
2353 ns_flag="-n $namespace"
2354 ns_text="in namespace $namespace"
2355 if [ $restype == "persistentvolumes" ]; then
2359 if [ $restype == "clusterrolebindings" ]; then
2363 result=$(kubectl $KUBECONF get $restype $ns_flag -o jsonpath='{.items[?(@.metadata.labels.'$labelname'=="'$labelid'")].metadata.name}' 2> /dev/null)
2364 if [ $? -eq 0 ] && [ ! -z "$result" ]; then
2365 deleted_resourcetypes=$deleted_resourcetypes" "$restype
2366 for resid in $result; do
2367 if [ $restype == "replicaset" ] || [ $restype == "statefulset" ]; then
2369 while [ $count -ne 0 ]; do
2370 count=$(kubectl $KUBECONF get $restype $resid $ns_flag -o jsonpath='{.status.replicas}' 2> /dev/null)
2371 echo -ne " Scaling $restype $resid $ns_text with label $labelname=$labelid to 0, current count=$count"$SAMELINE
2372 if [ $? -eq 0 ] && [ ! -z "$count" ]; then
2378 echo -e " Scaled $restype $resid $ns_text with label $labelname=$labelid to 0, current count=$count $GREEN OK $EGREEN"
2380 echo -ne " Deleting $restype $resid $ns_text with label $labelname=$labelid "$SAMELINE
2381 kubectl $KUBECONF delete --grace-period=1 $restype $resid $ns_flag 1> /dev/null 2> ./tmp/kubeerr
2382 if [ $? -eq 0 ]; then
2383 echo -e " Deleted $restype $resid $ns_text with label $labelname=$labelid $GREEN OK $EGREEN"
2385 echo -e " Deleted $restype $resid $ns_text with label $labelname=$labelid $GREEN Does not exist - OK $EGREEN"
2391 if [ ! -z "$deleted_resourcetypes" ]; then
2392 for restype in $deleted_resources; do
2393 ns_flag="-n $namespace"
2394 ns_text="in namespace $namespace"
2395 if [ $restype == "persistentvolumes" ]; then
2399 echo -ne " Waiting for $restype $ns_text with label $labelname=$labelid to be deleted..."$SAMELINE
2402 while [ ! -z "$result" ]; do
2404 result=$(kubectl $KUBECONF get $restype $ns_flag -o jsonpath='{.items[?(@.metadata.labels.'$labelname'=="'$labelid'")].metadata.name}')
2405 echo -ne " Waiting for $restype $ns_text with label $labelname=$labelid to be deleted...$(($SECONDS-$T_START)) seconds "$SAMELINE
2406 if [ -z "$result" ]; then
2407 echo -e " Waiting for $restype $ns_text with label $labelname=$labelid to be deleted...$(($SECONDS-$T_START)) seconds $GREEN OK $EGREEN"
2408 elif [ $(($SECONDS-$T_START)) -gt 300 ]; then
2409 echo -e " Waiting for $restype $ns_text with label $labelname=$labelid to be deleted...$(($SECONDS-$T_START)) seconds $RED Failed $ERED"
2417 # Creates a namespace if it does not exists
2419 # (Not for test scripts)
2420 __kube_create_namespace() {
2422 #Check if test namespace exists, if not create it
2423 kubectl $KUBECONF get namespace $1 1> /dev/null 2> ./tmp/kubeerr
2424 if [ $? -ne 0 ]; then
2425 echo -ne " Creating namespace "$1 $SAMELINE
2426 kubectl $KUBECONF create namespace $1 1> /dev/null 2> ./tmp/kubeerr
2427 if [ $? -ne 0 ]; then
2428 echo -e " Creating namespace $1 $RED$BOLD FAILED $EBOLD$ERED"
2430 echo " Message: $(<./tmp/kubeerr)"
2433 kubectl $KUBECONF label ns $1 autotest=engine > /dev/null
2434 echo -e " Creating namespace $1 $GREEN$BOLD OK $EBOLD$EGREEN"
2437 echo -e " Creating namespace $1 $GREEN$BOLD Already exists, OK $EBOLD$EGREEN"
2442 # Removes a namespace if it exists
2444 # (Not for test scripts)
2445 __kube_delete_namespace() {
2447 #Check if test namespace exists, if so remove it
2448 kubectl $KUBECONF get namespace $1 1> /dev/null 2> ./tmp/kubeerr
2449 if [ $? -eq 0 ]; then
2450 echo -ne " Removing namespace "$1 $SAMELINE
2451 kubectl $KUBECONF delete namespace $1 1> /dev/null 2> ./tmp/kubeerr
2452 if [ $? -ne 0 ]; then
2453 echo -e " Removing namespace $1 $RED$BOLD FAILED $EBOLD$ERED"
2455 echo " Message: $(<./tmp/kubeerr)"
2458 echo -e " Removing namespace $1 $GREEN$BOLD OK $EBOLD$EGREEN"
2461 echo -e " Namespace $1 $GREEN$BOLD does not exist, OK $EBOLD$EGREEN"
2466 # Removes and re-create a namespace
2468 # (Not for test scripts)
2469 clean_and_create_namespace() {
2472 if [ $# -ne 1 ]; then
2473 __print_err "<namespace>" $@
2476 __kube_delete_namespace $1
2477 if [ $? -ne 0 ]; then
2480 __kube_create_namespace $1
2481 if [ $? -ne 0 ]; then
2486 # Add/remove label on non-namespaced kube object
2487 # args: <api> <instance> <label>
2488 # (Not for test scripts)
2489 __kube_label_non_ns_instance() {
2490 kubectl $KUBECONF label $1 $2 "$3" 1> /dev/null 2> ./tmp/kubeerr
2494 # Add/remove label on namespaced kube object
2495 # args: <api> <instance> <namespace> <label>
2496 # (Not for test scripts)
2497 __kube_label_ns_instance() {
2498 kubectl $KUBECONF label $1 $2 -n $3 "$4" 1> /dev/null 2> ./tmp/kubeerr
2502 # Find the host ip of an app (using the service resource)
2503 # args: <app-name> <namespace>
2504 # (Not for test scripts)
2505 __kube_get_service_host() {
2506 if [ $# -ne 2 ]; then
2508 __print_err "need 2 args, <app-name> <namespace>" $@
2511 for timeout in {1..60}; do
2512 host=$(kubectl $KUBECONF get svc $1 -n $2 -o jsonpath='{.spec.clusterIP}')
2513 if [ $? -eq 0 ]; then
2514 if [ ! -z "$host" ]; then
2522 echo "host-not-found-fatal-error"
2526 # Find the named port to an app (using the service resource)
2527 # args: <app-name> <namespace> <port-name>
2528 # (Not for test scripts)
2529 __kube_get_service_port() {
2530 if [ $# -ne 3 ]; then
2532 __print_err "need 3 args, <app-name> <namespace> <port-name>" $@
2536 for timeout in {1..60}; do
2537 port=$(kubectl $KUBECONF get svc $1 -n $2 -o jsonpath='{...ports[?(@.name=="'$3'")].port}')
2538 if [ $? -eq 0 ]; then
2539 if [ ! -z "$port" ]; then
2551 # Find the named node port to an app (using the service resource)
2552 # args: <app-name> <namespace> <port-name>
2553 # (Not for test scripts)
2554 __kube_get_service_nodeport() {
2555 if [ $# -ne 3 ]; then
2557 __print_err "need 3 args, <app-name> <namespace> <port-name>" $@
2561 for timeout in {1..60}; do
2562 port=$(kubectl $KUBECONF get svc $1 -n $2 -o jsonpath='{...ports[?(@.name=="'$3'")].nodePort}')
2563 if [ $? -eq 0 ]; then
2564 if [ ! -z "$port" ]; then
2576 # Create a kube resource from a yaml template
2577 # args: <resource-type> <resource-name> <template-yaml> <output-yaml>
2578 # (Not for test scripts)
2579 __kube_create_instance() {
2580 echo -ne " Creating $1 $2"$SAMELINE
2582 kubectl $KUBECONF apply -f $4 1> /dev/null 2> ./tmp/kubeerr
2583 if [ $? -ne 0 ]; then
2585 echo -e " Creating $1 $2 $RED Failed $ERED"
2586 echo " Message: $(<./tmp/kubeerr)"
2589 echo -e " Creating $1 $2 $GREEN OK $EGREEN"
2593 # Function to create a configmap in kubernetes
2594 # args: <configmap-name> <namespace> <labelname> <labelid> <path-to-data-file> <path-to-output-yaml>
2595 # (Not for test scripts)
2596 __kube_create_configmap() {
2597 echo -ne " Creating configmap $1 "$SAMELINE
2598 envsubst < $5 > $5"_tmp"
2599 cp $5"_tmp" $5 #Need to copy back to orig file name since create configmap neeed the original file name
2600 kubectl $KUBECONF create configmap $1 -n $2 --from-file=$5 --dry-run=client -o yaml > $6
2601 if [ $? -ne 0 ]; then
2602 echo -e " Creating configmap $1 $RED Failed $ERED"
2607 kubectl $KUBECONF apply -f $6 1> /dev/null 2> ./tmp/kubeerr
2608 if [ $? -ne 0 ]; then
2609 echo -e " Creating configmap $1 $RED Apply failed $ERED"
2610 echo " Message: $(<./tmp/kubeerr)"
2614 kubectl $KUBECONF label configmap $1 -n $2 $3"="$4 --overwrite 1> /dev/null 2> ./tmp/kubeerr
2615 if [ $? -ne 0 ]; then
2616 echo -e " Creating configmap $1 $RED Labeling failed $ERED"
2617 echo " Message: $(<./tmp/kubeerr)"
2621 # Log the resulting map
2622 kubectl $KUBECONF get configmap $1 -n $2 -o yaml > $6
2624 echo -e " Creating configmap $1 $GREEN OK $EGREEN"
2628 # This function runs a kubectl cmd where a single output value is expected, for example get ip with jsonpath filter.
2629 # The function retries up to the timeout given in the cmd flag '--cluster-timeout'
2630 # args: <full kubectl cmd with parameters>
2631 # (Not for test scripts)
2632 __kube_cmd_with_timeout() {
2633 TS_TMP=$(($SECONDS+$CLUSTER_TIME_OUT))
2636 kube_cmd_result=$($@)
2637 if [ $? -ne 0 ]; then
2640 if [ $SECONDS -ge $TS_TMP ] || [ ! -z "$kube_cmd_result" ] ; then
2641 echo $kube_cmd_result
2648 # This function starts a pod that cleans a the contents of a path mounted as a pvc
2649 # After this action the pod should terminate
2650 # This should only be executed when the pod owning the pvc is not running
2651 # args: <appname> <namespace> <pvc-name> <path-to remove>
2652 # (Not for test scripts)
2653 __kube_clean_pvc() {
2655 #using env vars setup in pvccleaner_api_functions.sh
2657 export PVC_CLEANER_NAMESPACE=$2
2658 export PVC_CLEANER_CLAIMNAME=$3
2659 export PVC_CLEANER_RM_PATH=$4
2660 export PVC_CLEANER_APP_NAME
2661 input_yaml=$SIM_GROUP"/"$PVC_CLEANER_COMPOSE_DIR"/"pvc-cleaner.yaml
2662 output_yaml=$PWD/tmp/$2-pvc-cleaner.yaml
2664 envsubst < $input_yaml > $output_yaml
2666 kubectl $KUBECONF delete -f $output_yaml 1> /dev/null 2> /dev/null # Delete the previous terminated pod - if existing
2668 __kube_create_instance pod $PVC_CLEANER_APP_NAME $input_yaml $output_yaml
2669 if [ $? -ne 0 ]; then
2670 echo $YELLOW" Could not clean pvc for app: $1 - persistent storage not clean - tests may not work"
2674 term_ts=$(($SECONDS+30))
2675 while [ $term_ts -gt $SECONDS ]; do
2676 pod_status=$(kubectl $KUBECONF get pod pvc-cleaner -n $PVC_CLEANER_NAMESPACE --no-headers -o custom-columns=":status.phase")
2677 if [ "$pod_status" == "Succeeded" ]; then
2684 # This function scales or deletes all resources for app selected by the testcase.
2686 # (Not for test scripts)
2688 echo -e $BOLD"Initialize kube pods/statefulsets/replicaset to initial state"$EBOLD
2690 # Scale prestarted or managed apps
2691 for imagename in $APP_SHORT_NAMES; do
2692 # A function name is created from the app short name
2693 # for example app short name 'RICMSIM' -> produce the function
2694 # name __RICSIM_kube_scale_zero or __RICSIM_kube_scale_zero_and_wait
2695 # This function is called and is expected to exist in the imported
2696 # file for the ricsim test functions
2697 # The resulting function impl shall scale the resources to 0
2698 # For prestarted apps, the function waits until the resources are 0
2699 # For included (not prestated) apps, the scaling is just ordered
2700 __check_prestarted_image $imagename
2701 if [ $? -eq 0 ]; then
2702 function_pointer="__"$imagename"_kube_scale_zero_and_wait"
2703 echo -e " Scaling all kube resources for app $BOLD $imagename $EBOLD to 0"
2706 __check_included_image $imagename
2707 if [ $? -eq 0 ]; then
2708 function_pointer="__"$imagename"_kube_scale_zero"
2709 echo -e " Scaling all kube resources for app $BOLD $imagename $EBOLD to 0"
2715 # Delete managed apps
2716 for imagename in $APP_SHORT_NAMES; do
2717 __check_included_image $imagename
2718 if [ $? -eq 0 ]; then
2719 __check_prestarted_image $imagename
2720 if [ $? -ne 0 ]; then
2721 # A function name is created from the app short name
2722 # for example app short name 'RICMSIM' -> produce the function
2723 # name __RICSIM__kube_delete_all
2724 # This function is called and is expected to exist in the imported
2725 # file for the ricsim test functions
2726 # The resulting function impl shall delete all its resources
2727 function_pointer="__"$imagename"_kube_delete_all"
2728 echo -e " Deleting all kube resources for app $BOLD $imagename $EBOLD"
2737 # Function stop and remove all containers (docker) and services/deployments etc(kube)
2739 # Function for test script
2740 clean_environment() {
2741 if [ $RUNMODE == "KUBE" ]; then
2743 if [ $PRE_CLEAN -eq 1 ]; then
2744 echo " Cleaning docker resouces to free up resources, may take time..."
2745 ../common/clean_docker.sh 2>&1 > /dev/null
2750 if [ $PRE_CLEAN -eq 1 ]; then
2751 echo " Cleaning kubernetes resouces to free up resources, may take time..."
2752 ../common/clean_kube.sh $KUBECONF 2>&1 > /dev/null
2758 # 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
2760 # (Function for test scripts)
2761 auto_clean_environment() {
2763 if [ "$AUTO_CLEAN" == "auto" ]; then
2764 echo -e $BOLD"Initiating automatic cleaning of environment"$EBOLD
2769 # Function to sleep a test case for a numner of seconds. Prints the optional text args as info
2770 # args: <sleep-time-in-sec> [any-text-in-quotes-to-be-printed]
2771 # (Function for test scripts)
2774 echo -e $BOLD"INFO(${BASH_LINENO[0]}): "${FUNCNAME[0]}"," $@ $EBOLD
2775 if [ $# -lt 1 ]; then
2777 __print_err "need at least one arg, <sleep-time-in-sec> [any-text-to-printed]" $@
2780 #echo "---- Sleep for " $1 " seconds ---- "$2
2782 duration=$((SECONDS-start))
2783 while [ $duration -lt $1 ]; do
2784 echo -ne " Slept for ${duration} seconds${SAMELINE}"
2786 duration=$((SECONDS-start))
2788 echo -ne " Slept for ${duration} seconds${SAMELINE}"
2792 # Print error info for the call in the parent script (test case). Arg: <error-message-to-print>
2793 # Not to be called from the test script itself.
2795 echo -e $RED ${FUNCNAME[1]} " "$1" " ${BASH_SOURCE[2]} " line" ${BASH_LINENO[1]} $ERED
2796 if [ $# -gt 1 ]; then
2797 echo -e $RED" Got: "${FUNCNAME[1]} ${@:2} $ERED
2800 __check_stop_at_error
2803 # Function to create the docker network for the test
2804 # Not to be called from the test script itself.
2805 __create_docker_network() {
2806 tmp=$(docker network ls --format={{.Name}} --filter name=$DOCKER_SIM_NWNAME)
2807 if [ $? -ne 0 ]; then
2808 echo -e $RED" Could not check if docker network $DOCKER_SIM_NWNAME exists"$ERED
2811 if [ "$tmp" != $DOCKER_SIM_NWNAME ]; then
2812 echo -e " Creating docker network:$BOLD $DOCKER_SIM_NWNAME $EBOLD"
2813 docker network create $DOCKER_SIM_NWNAME | indent2
2814 if [ $? -ne 0 ]; then
2815 echo -e $RED" Could not create docker network $DOCKER_SIM_NWNAME"$ERED
2818 echo -e "$GREEN Done$EGREEN"
2821 echo -e " Docker network $DOCKER_SIM_NWNAME already exists$GREEN OK $EGREEN"
2825 # Function to start container with docker-compose and wait until all are in state running.
2826 # If the <docker-compose-file> is empty, the default 'docker-compose.yml' is assumed.
2827 #args: <docker-compose-dir> <docker-compose-file> <docker-compose-arg>|NODOCKERARGS <count> <app-name>+
2828 # (Not for test scripts)
2829 __start_container() {
2831 if [ $# -lt 5 ]; then
2833 __print_err "need 5 or more args, <docker-compose-dir> <docker-compose-file> <docker-compose-arg>|NODOCKERARGS <count> <app-name>+" $@
2837 __create_docker_network
2845 if [ -z "$compose_file" ]; then
2846 compose_file="docker-compose.yml"
2854 envsubst < $compose_file > "gen_"$compose_file
2855 compose_file="gen_"$compose_file
2856 if [ $DOCKER_COMPOSE_VERION == "V1" ]; then
2857 docker_compose_cmd="docker-compose"
2859 docker_compose_cmd="docker compose"
2862 if [ "$compose_args" == "NODOCKERARGS" ]; then
2863 $docker_compose_cmd -f $compose_file up -d &> .dockererr
2864 if [ $? -ne 0 ]; then
2865 echo -e $RED"Problem to launch container(s) with docker-compose"$ERED
2867 echo -e $RED"Stopping script...."$ERED
2871 $docker_compose_cmd -f $compose_file up -d $compose_args &> .dockererr
2872 if [ $? -ne 0 ]; then
2873 echo -e $RED"Problem to launch container(s) with docker-compose"$ERED
2875 echo -e $RED"Stopping script...."$ERED
2883 while [ $appindex -lt $appcount ]; do
2887 for i in {1..10}; do
2888 if [ "$(docker inspect --format '{{ .State.Running }}' $appname)" == "true" ]; then
2889 echo -e " Container $BOLD${appname}$EBOLD$GREEN running$EGREEN on$BOLD image $(docker inspect --format '{{ .Config.Image }}' ${appname}) $EBOLD"
2896 if [ $app_started -eq 0 ]; then
2899 echo -e $RED" Container $BOLD${appname}$EBOLD could not be started"$ERED
2900 echo -e $RED" Stopping script..."$ERED
2903 let appindex=appindex+1
2908 # Function to check if container/service is responding to http/https
2909 # args: <container-name>|<service-name> url
2910 # (Not for test scripts)
2911 __check_service_start() {
2913 if [ $# -ne 2 ]; then
2915 __print_err "need 2 args, <container-name>|<service-name> url" $@
2919 if [ $RUNMODE == "KUBE" ]; then
2920 ENTITY="service/set/deployment"
2926 echo -ne " Container $BOLD${appname}$EBOLD starting${SAMELINE}"
2930 echo -ne " Waiting for ${ENTITY} ${appname} service status...${SAMELINE}"
2933 while (( $TSTART+600 > $SECONDS )); do
2934 result="$(__do_curl -m 10 $url)"
2935 if [ $? -eq 0 ]; then
2936 if [ ${#result} -gt 15 ]; then
2937 #If response is too long, truncate
2938 result="...response text too long, omitted"
2940 echo -ne " Waiting for {ENTITY} $BOLD${appname}$EBOLD service status on ${3}, result: $result${SAMELINE}"
2941 echo -ne " The ${ENTITY} $BOLD${appname}$EBOLD$GREEN is alive$EGREEN, responds to service status:$GREEN $result $EGREEN on ${url} after $(($SECONDS-$TSTART)) seconds"
2947 if (( $TS_OFFSET > 5 )); then
2950 while [ $(($TS_TMP+$TS_OFFSET)) -gt $SECONDS ]; do
2951 echo -ne " Waiting for ${ENTITY} ${appname} service status on ${url}...$(($SECONDS-$TSTART)) seconds, retrying in $(($TS_TMP+$TS_OFFSET-$SECONDS)) seconds ${SAMELINE}"
2955 let loop_ctr=loop_ctr+1
2958 if [ "$a1pmsst" = "false" ]; then
2960 echo -e $RED" The ${ENTITY} ${appname} did not respond to service status on ${url} in $(($SECONDS-$TSTART)) seconds"$ERED
2973 __check_container_logs() {
2981 echo -e $BOLD"Checking $dispname container $appname log ($logpath) for WARNINGs and ERRORs"$EBOLD
2983 if [ $RUNMODE == "KUBE" ]; then
2984 echo -e $YELLOW" Internal log for $dispname not checked in kube"$EYELLOW
2988 #tmp=$(docker ps | grep $appname)
2989 tmp=$(docker ps -q --filter name=$appname) #get the container id
2990 if [ -z "$tmp" ]; then #Only check logs for running A1PMS apps
2991 echo " "$dispname" is not running, no check made"
2994 foundentries="$(docker exec -t $tmp grep $warning $logpath | wc -l)"
2995 if [ $? -ne 0 ];then
2996 echo " Problem to search $appname log $logpath"
2998 if [ $foundentries -eq 0 ]; then
2999 echo " No WARN entries found in $appname log $logpath"
3001 echo -e " Found \033[1m"$foundentries"\033[0m WARN entries in $appname log $logpath"
3004 foundentries="$(docker exec -t $tmp grep $error $logpath | wc -l)"
3005 if [ $? -ne 0 ];then
3006 echo " Problem to search $appname log $logpath"
3008 if [ $foundentries -eq 0 ]; then
3009 echo " No ERR entries found in $appname log $logpath"
3011 echo -e $RED" Found \033[1m"$foundentries"\033[0m"$RED" ERR entries in $appname log $logpath"$ERED
3017 # Store all container logs and other logs in the log dir for the script
3018 # Logs are stored with a prefix in case logs should be stored several times during a test
3019 # args: <logfile-prefix>
3020 # (Function for test scripts)
3022 if [ $# != 1 ]; then
3024 __print_err "need one arg, <file-prefix>" $@
3027 echo -e $BOLD"Storing all docker/kube container logs and other test logs in $TESTLOGS/$ATC using prefix: "$1$EBOLD
3029 docker stats --no-stream > $TESTLOGS/$ATC/$1_docker_stats.log 2>&1
3031 docker ps -a > $TESTLOGS/$ATC/$1_docker_ps.log 2>&1
3033 cp .httplog_${ATC}.txt $TESTLOGS/$ATC/$1_httplog_${ATC}.txt 2>&1
3035 if [ $RUNMODE == "DOCKER" ]; then
3037 # Store docker logs for all container
3038 for imagename in $APP_SHORT_NAMES; do
3039 __check_included_image $imagename
3040 if [ $? -eq 0 ]; then
3041 # A function name is created from the app short name
3042 # for example app short name 'RICMSIM' -> produce the function
3043 # name __RICSIM__store_docker_logs
3044 # This function is called and is expected to exist in the imported
3045 # file for the ricsim test functions
3046 # The resulting function impl shall store the docker logs for each container
3047 function_pointer="__"$imagename"_store_docker_logs"
3048 $function_pointer "$TESTLOGS/$ATC/" $1
3052 if [ $RUNMODE == "KUBE" ]; then
3053 namespaces=$(kubectl $KUBECONF get namespaces -o jsonpath='{.items[?(@.metadata.name)].metadata.name}')
3054 for nsid in $namespaces; do
3055 pods=$(kubectl $KUBECONF get pods -n $nsid -o jsonpath='{.items[?(@.metadata.labels.autotest)].metadata.name}')
3056 for podid in $pods; do
3057 kubectl $KUBECONF logs -n $nsid $podid > $TESTLOGS/$ATC/$1_${podid}.log
3067 # Generic curl function, assumes all 200-codes are ok
3069 # args: <valid-curl-args-including full url>
3070 # returns: <returned response (without respose code)> or "<no-response-from-server>" or "<not found, <http-code>>""
3071 # returns: The return code is 0 for ok and 1 for not ok
3073 echo ${FUNCNAME[1]} "line: "${BASH_LINENO[1]} >> $HTTPLOG
3075 if [ ! -z "$KUBE_PROXY_PATH" ]; then
3076 if [ $KUBE_PROXY_HTTPX == "http" ]; then
3077 proxyflag=" --proxy $KUBE_PROXY_PATH"
3079 proxyflag=" --proxy-insecure --proxy $KUBE_PROXY_PATH"
3083 if [ ! -z "$KUBE_PROXY_CURL_JWT" ]; then
3084 jwt="-H "\""Authorization: Bearer $KUBE_PROXY_CURL_JWT"\"
3085 curlString="curl -skw %{http_code} $proxyflag $@"
3086 echo " CMD: $curlString $jwt" >> $HTTPLOG
3087 res=$($curlString -H "Authorization: Bearer $KUBE_PROXY_CURL_JWT")
3090 curlString="curl -skw %{http_code} $proxyflag $@"
3091 echo " CMD: $curlString" >> $HTTPLOG
3095 echo " RESP: $res" >> $HTTPLOG
3096 echo " RETCODE: $retcode" >> $HTTPLOG
3097 if [ $retcode -ne 0 ]; then
3098 echo "<no-response-from-server>"
3101 http_code="${res:${#res}-3}"
3102 if [ ${#res} -eq 3 ]; then
3103 if [ $http_code -lt 200 ] || [ $http_code -gt 299 ]; then
3104 echo "<no-response-from-server>"
3110 if [ $http_code -lt 200 ] || [ $http_code -gt 299 ]; then
3111 echo "<not found, resp:${http_code}>"
3114 if [ $# -eq 2 ]; then
3115 echo "${res:0:${#res}-3}" | xargs
3117 echo "${res:0:${#res}-3}"
3125 # Generic curl function, assumes all 200-codes are ok
3126 # Uses no proxy, even if it is set
3127 # args: <valid-curl-args-including full url>
3128 # returns: <returned response (without respose code)> or "<no-response-from-server>" or "<not found, <http-code>>""
3129 # returns: The return code is 0 for ok and 1 for not ok
3130 __do_curl_no_proxy() {
3131 echo ${FUNCNAME[1]} "line: "${BASH_LINENO[1]} >> $HTTPLOG
3132 curlString="curl -skw %{http_code} $@"
3133 echo " CMD: $curlString" >> $HTTPLOG
3136 echo " RESP: $res" >> $HTTPLOG
3137 echo " RETCODE: $retcode" >> $HTTPLOG
3138 if [ $retcode -ne 0 ]; then
3139 echo "<no-response-from-server>"
3142 http_code="${res:${#res}-3}"
3143 if [ ${#res} -eq 3 ]; then
3144 if [ $http_code -lt 200 ] || [ $http_code -gt 299 ]; then
3145 echo "<no-response-from-server>"
3151 if [ $http_code -lt 200 ] || [ $http_code -gt 299 ]; then
3152 echo "<not found, resp:${http_code}>"
3155 if [ $# -eq 2 ]; then
3156 echo "${res:0:${#res}-3}" | xargs
3158 echo "${res:0:${#res}-3}"
3165 #######################################
3166 ### Basic helper function for test cases
3167 #######################################
3169 # Test a simulator container variable value towards target value using an condition operator with an optional timeout.
3170 # Arg: <simulator-name> <host> <variable-name> <condition-operator> <target-value> - This test is done
3171 # immediately and sets pass or fail depending on the result of comparing variable and target using the operator.
3172 # Arg: <simulator-name> <host> <variable-name> <condition-operator> <target-value> <timeout> - This test waits up to the timeout
3173 # before setting pass or fail depending on the result of comparing variable and target using the operator.
3174 # 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.
3175 # Not to be called from test script.
3178 checkjsonarraycount=0
3179 TIMESTAMP=$(date "+%Y-%m-%d %H:%M:%S")
3180 if [ $# -eq 6 ]; then
3181 if [[ $3 == "json:"* ]]; then
3182 checkjsonarraycount=1
3185 echo -e $BOLD"TEST $TEST_SEQUENCE_NR (${BASH_LINENO[1]}): ${1}, ${3} ${4} ${5} within ${6} seconds"$EBOLD
3186 echo "TEST $TEST_SEQUENCE_NR - ${TIMESTAMP}: (${BASH_LINENO[1]}): ${1}, ${3} ${4} ${5} within ${6} seconds" >> $HTTPLOG
3189 ((TEST_SEQUENCE_NR++))
3193 if [ $checkjsonarraycount -eq 0 ]; then
3194 result="$(__do_curl $2$3)"
3196 result=${result//[[:blank:]]/} #Strip blanks
3199 result="$(__do_curl $2$path)"
3201 echo "$result" > ./tmp/.tmp.curl.json
3202 result=$(python3 ../common/count_json_elements.py "./tmp/.tmp.curl.json")
3204 duration=$((SECONDS-start))
3205 echo -ne " Result=${result} after ${duration} seconds${SAMELINE}"
3207 if [ $retcode -ne 0 ]; then
3208 if [ $duration -gt $6 ]; then
3210 echo -e $RED" FAIL${ERED} - ${3} ${4} ${5} not reached in ${6} seconds, result = ${result}"
3211 __print_current_stats
3212 __check_stop_at_error
3215 elif [ "$4" == "=" ] && [ "$result" -eq $5 ]; then
3217 echo -e " Result=${result} after ${duration} seconds${SAMELINE}"
3218 echo -e $GREEN" PASS${EGREEN} - Result=${result} after ${duration} seconds"
3219 __print_current_stats
3221 elif [ "$4" == ">" ] && [ "$result" -gt $5 ]; then
3223 echo -e " Result=${result} after ${duration} seconds${SAMELINE}"
3224 echo -e $GREEN" PASS${EGREEN} - Result=${result} after ${duration} seconds"
3225 __print_current_stats
3227 elif [ "$4" == "<" ] && [ "$result" -lt $5 ]; then
3229 echo -e " Result=${result} after ${duration} seconds${SAMELINE}"
3230 echo -e $GREEN" PASS${EGREEN} - Result=${result} after ${duration} seconds"
3231 __print_current_stats
3233 elif [ "$4" == ">=" ] && [ "$result" -ge $5 ]; then
3235 echo -e " Result=${result} after ${duration} seconds${SAMELINE}"
3236 echo -e $GREEN" PASS${EGREEN} - Result=${result} after ${duration} seconds"
3237 __print_current_stats
3239 elif [ "$4" == "contain_str" ] && [[ $result =~ $5 ]]; then
3241 echo -e " Result=${result} after ${duration} seconds${SAMELINE}"
3242 echo -e $GREEN" PASS${EGREEN} - Result=${result} after ${duration} seconds"
3243 __print_current_stats
3246 if [ $duration -gt $6 ]; then
3248 echo -e $RED" FAIL${ERED} - ${3} ${4} ${5} not reached in ${6} seconds, result = ${result}"
3249 __print_current_stats
3250 __check_stop_at_error
3256 elif [ $# -eq 5 ]; then
3257 if [[ $3 == "json:"* ]]; then
3258 checkjsonarraycount=1
3261 echo -e $BOLD"TEST $TEST_SEQUENCE_NR (${BASH_LINENO[1]}): ${1}, ${3} ${4} ${5}"$EBOLD
3262 echo "TEST $TEST_SEQUENCE_NR - ${TIMESTAMP}: (${BASH_LINENO[1]}): ${1}, ${3} ${4} ${5}" >> $HTTPLOG
3264 ((TEST_SEQUENCE_NR++))
3265 if [ $checkjsonarraycount -eq 0 ]; then
3266 result="$(__do_curl $2$3)"
3268 result=${result//[[:blank:]]/} #Strip blanks
3271 result="$(__do_curl $2$path)"
3273 echo "$result" > ./tmp/.tmp.curl.json
3274 result=$(python3 ../common/count_json_elements.py "./tmp/.tmp.curl.json")
3276 if [ $retcode -ne 0 ]; then
3278 echo -e $RED" FAIL ${ERED}- ${3} ${4} ${5} not reached, result = ${result}"
3279 __print_current_stats
3280 __check_stop_at_error
3281 elif [ "$4" == "=" ] && [ "$result" -eq $5 ]; then
3283 echo -e $GREEN" PASS${EGREEN} - Result=${result}"
3284 __print_current_stats
3285 elif [ "$4" == ">" ] && [ "$result" -gt $5 ]; then
3287 echo -e $GREEN" PASS${EGREEN} - Result=${result}"
3288 __print_current_stats
3289 elif [ "$4" == "<" ] && [ "$result" -lt $5 ]; then
3291 echo -e $GREEN" PASS${EGREEN} - Result=${result}"
3292 __print_current_stats
3293 elif [ "$4" == ">=" ] && [ "$result" -ge $5 ]; then
3295 echo -e $GREEN" PASS${EGREEN} - Result=${result}"
3296 __print_current_stats
3297 elif [ "$4" == "contain_str" ] && [[ $result =~ $5 ]]; then
3299 echo -e $GREEN" PASS${EGREEN} - Result=${result}"
3300 __print_current_stats
3303 echo -e $RED" FAIL${ERED} - ${3} ${4} ${5} not reached, result = ${result}"
3304 __print_current_stats
3305 __check_stop_at_error
3308 echo "Wrong args to __var_test, needs five or six args: <simulator-name> <host> <variable-name> <condition-operator> <target-value> [ <timeout> ]"