78f27fd2662d8ada23188d7d5d2cf334906a5b54
[nonrtric.git] / test / common / testcase_common.sh
1 #!/bin/bash
2
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
9 #
10 #       http://www.apache.org/licenses/LICENSE-2.0
11 #
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=================================================
18 #
19
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
22
23 . ../common/api_curl.sh
24 . ../common/testengine_config.sh
25
26 __print_args() {
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>]"
34 }
35
36 if [ $# -eq 1 ] && [ "$1" == "help" ]; then
37
38         if [ ! -z "$TC_ONELINE_DESCR" ]; then
39                 echo "Test script description:"
40                 echo $TC_ONELINE_DESCR
41                 echo ""
42         fi
43         __print_args
44         echo ""
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"
73         echo ""
74         echo "List of app short names supported: "$APP_SHORT_NAMES
75         exit 0
76 fi
77
78 AUTOTEST_HOME=$PWD
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)
82
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"
86
87 #Formatting for 'echo' cmd
88 BOLD="\033[1m"
89 EBOLD="\033[0m"
90 RED="\033[31m\033[1m"
91 ERED="\033[0m"
92 GREEN="\033[32m\033[1m"
93 EGREEN="\033[0m"
94 YELLOW="\033[33m\033[1m"
95 EYELLOW="\033[0m"
96 SAMELINE="\033[0K\r"
97
98 # Just resetting any previous echo formatting...
99 echo -ne $EBOLD
100
101 # default test environment variables
102 TEST_ENV_VAR_FILE=""
103 #Override env file, will be added on top of the above file
104 TEST_ENV_VAR_FILE_OVERRIDE=""
105
106 echo "Test case started as: ${BASH_SOURCE[$i+1]} "$@
107
108 # Var to hold 'auto' in case containers shall be stopped when test case ends
109 AUTO_CLEAN=""
110
111 # Var to indicate pre clean, if flag --pre-clean is set the script will clean kube resouces when running docker and vice versa
112 PRE_CLEAN="0"
113
114 # Var to hold the app names to use local images for
115 USE_LOCAL_IMAGES=""
116
117 # Var to hold the app names to use remote snapshot images for
118 USE_SNAPSHOT_IMAGES=""
119
120 # Var to hold the app names to use remote staging images for
121 USE_STAGING_IMAGES=""
122
123 # Var to hold the app names to use remote release images for
124 USE_RELEASE_IMAGES=""
125
126
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
128 STOP_AT_ERROR=0
129
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
133 IMAGE_CATEGORY="DEV"
134
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"
139
140 # Function to indent cmd output with one space
141 indent1() { sed 's/^/ /'; }
142
143 # Function to indent cmd output with two spaces
144 indent2() { sed 's/^/  /'; }
145
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
150 fi
151
152 # Counter for test suites
153 if [ -f .tmp_tcsuite_ctr ]; then
154         tmpval=$(< .tmp_tcsuite_ctr)
155         ((tmpval++))
156         echo $tmpval > .tmp_tcsuite_ctr
157 fi
158
159 # Create the logs dir if not already created in the current dir
160 if [ ! -d "logs" ]; then
161     mkdir logs
162 fi
163 TESTLOGS=$PWD/logs
164
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
169     mkdir tmp
170         if [ $? -ne 0 ]; then
171                 echo "Cannot create dir for temp files, $PWD/tmp"
172                 echo "Exiting...."
173                 exit 1
174         fi
175 fi
176 curdir=$PWD
177 cd tmp
178 if [ $? -ne 0 ]; then
179         echo "Cannot cd to $PWD/tmp"
180         echo "Exiting...."
181         exit 1
182 fi
183
184 TESTENV_TEMP_FILES=$PWD
185
186 if [ ! -d "prev" ]; then
187     mkdir prev
188         if [ $? -ne 0 ]; then
189                 echo "Cannot create dir for previous temp files, $PWD/prev"
190                 echo "Exiting...."
191                 exit 1
192         fi
193 fi
194
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"
200                 echo "Exiting...."
201                 exit 1
202         fi
203         if [ $(pwd | xargs basename) == "tmp" ]; then    #Check that current dir is tmp...for safety
204
205                 rm -rf $TMPFILES # Remove all temp files
206         fi
207 fi
208
209 cd $curdir
210 if [ $? -ne 0 ]; then
211         echo "Cannot cd to $curdir"
212         echo "Exiting...."
213         exit 1
214 fi
215
216
217 # Create a http message log for this testcase
218 HTTPLOG=$PWD"/.httplog_"$ATC".txt"
219 echo "" > $HTTPLOG
220
221 # Create a log dir for the test case
222 mkdir -p $TESTLOGS/$ATC
223
224 # Save create for current logs
225 mkdir -p $TESTLOGS/$ATC/previous
226
227 rm $TESTLOGS/$ATC/previous/*.log &> /dev/null
228 rm $TESTLOGS/$ATC/previous/*.txt &> /dev/null
229 rm $TESTLOGS/$ATC/previous/*.json &> /dev/null
230
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
234
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
239
240 #Create result file in the log dir
241 echo "1" > "$TESTLOGS/$ATC/.result$ATC.txt"
242
243 # Log all output from the test case to a TC log
244 TCLOG=$TESTLOGS/$ATC/TC.log
245 exec &>  >(tee ${TCLOG})
246
247 #Variables for counting tests as well as passed and failed tests
248 RES_TEST=0
249 RES_PASS=0
250 RES_FAIL=0
251 RES_CONF_FAIL=0
252 RES_DEVIATION=0
253
254 #Var to control if current stats shall be printed
255 PRINT_CURRENT_STATS=0
256
257 #Var to control if container/pod runtim statistics shall be collected
258 COLLECT_RUNTIME_STATS=0
259 COLLECT_RUNTIME_STATS_PID=0
260
261 #Var to control if endpoint statistics shall be collected
262 COLLECT_ENDPOINT_STATS=0
263
264 #Var to control if namespaces shall be delete before test setup
265 DELETE_KUBE_NAMESPACES=0
266
267 #Var to control if containers shall be delete before test setup
268 DELETE_CONTAINERS=0
269
270 #Var to configure kubectl from a config file or context
271 KUBECONF=""
272
273 #Localhost, may be set to another host/ip by cmd parameter
274 LOCALHOST_NAME="localhost"
275
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=""
280
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=""
288
289 #File to keep deviation messages
290 DEVIATION_FILE=".tmp_deviations"
291 rm $DEVIATION_FILE &> /dev/null
292
293 # Trap "command not found" and make the script fail
294 trap_fnc() {
295
296         if [ $? -eq 127 ]; then
297                 echo -e $RED"Function not found, setting script to FAIL"$ERED
298                 ((RES_CONF_FAIL++))
299                 __print_current_stats
300         fi
301 }
302 trap trap_fnc ERR
303
304 # Trap to kill subprocess for stats collection (if running)
305 trap_fnc2() {
306         if [ $COLLECT_RUNTIME_STATS_PID -ne 0 ]; then
307                 kill $COLLECT_RUNTIME_STATS_PID
308         fi
309 }
310 trap trap_fnc2 EXIT
311
312 # Counter for tests
313 TEST_SEQUENCE_NR=1
314
315 # Function to log the start of a test case
316 __log_test_start() {
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
320         ((RES_TEST++))
321         ((TEST_SEQUENCE_NR++))
322 }
323
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"
328         fi
329 }
330
331 # General function to log a failed test case
332 __log_test_fail_general() {
333         echo -e $RED" FAIL."$1 $ERED
334         ((RES_FAIL++))
335         __print_current_stats
336         __check_stop_at_error
337 }
338
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
342         ((RES_FAIL++))
343         __print_current_stats
344         __check_stop_at_error
345 }
346
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
350         ((RES_FAIL++))
351         __print_current_stats
352         __check_stop_at_error
353 }
354
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
358         ((RES_FAIL++))
359         __print_current_stats
360         __check_stop_at_error
361 }
362
363 # General function to log a passed test case
364 __log_test_pass() {
365         if [ $# -gt 0 ]; then
366                 echo $@
367         fi
368         ((RES_PASS++))
369         echo -e $GREEN" PASS"$EGREEN
370         __print_current_stats
371 }
372
373 #Counter for configurations
374 CONF_SEQUENCE_NR=1
375
376 # Function to log the start of a configuration setup
377 __log_conf_start() {
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++))
382 }
383
384 # Function to log a failed configuration setup
385 __log_conf_fail_general() {
386         echo -e $RED" FAIL."$1 $ERED
387         ((RES_CONF_FAIL++))
388         __print_current_stats
389         __check_stop_at_error
390 }
391
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
395         ((RES_CONF_FAIL++))
396         __print_current_stats
397         __check_stop_at_error
398 }
399
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
403         ((RES_CONF_FAIL++))
404         __print_current_stats
405         __check_stop_at_error
406 }
407
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$@
411         ((RES_CONF_FAIL++))
412         __print_current_stats
413         __check_stop_at_error
414 }
415
416 # Function to log a passed configuration setup
417 __log_conf_ok() {
418         if [ $# -gt 0 ]; then
419                 echo $@
420         fi
421         echo -e $GREEN" OK"$EGREEN
422         __print_current_stats
423 }
424
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
429                 return
430         fi
431         ENDPOINT_COUNT=1
432         if [ $# -gt 5 ]; then
433                 ENDPOINT_COUNT=$6
434         fi
435         ENDPOINT_STAT_FILE=$TESTLOGS/$ATC/endpoint_$ATC_$1_$2".log"
436         ENDPOINT_POS=0
437         ENDPOINT_NEG=0
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 '/')
442         fi
443
444         if [ $5 -ge 200 ] && [ $5 -lt 300 ]; then
445                 let ENDPOINT_POS=ENDPOINT_POS+$ENDPOINT_COUNT
446         else
447                 let ENDPOINT_NEG=ENDPOINT_NEG+$ENDPOINT_COUNT
448         fi
449
450         printf '%-2s %-10s %-45s %-16s %-16s' "#" "$3" "$4" "$ENDPOINT_POS/$ENDPOINT_POS" "$ENDPOINT_NEG/$ENDPOINT_NEG" > $ENDPOINT_STAT_FILE
451 }
452
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
457                 return
458         fi
459         ENDPOINT_STAT_FILE=$TESTLOGS/$ATC/imageinfo_$ATC_$1".log"
460         echo $A1PMS_IMAGE > $ENDPOINT_STAT_FILE
461 }
462
463 #Var for measuring execution time
464 TCTEST_START=$SECONDS
465
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
472
473 #File to save timer measurement results
474 TIMER_MEASUREMENTS=".timer_measurement.txt"
475 echo -e "Activity \t Duration \t Info" > $TIMER_MEASUREMENTS
476
477 # If this is set, some images (controlled by the parameter repo-policy) will be re-tagged and pushed to this repo before any
478 IMAGE_REPO_ADR=""
479 IMAGE_REPO_POLICY="local"
480 CLUSTER_TIME_OUT=0
481
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      -----------------------------------"
489
490 echo "Setting AUTOTEST_HOME="$AUTOTEST_HOME
491 START_ARG=$1
492 paramerror=0
493 paramerror_str=""
494 if [ $# -lt 1 ]; then
495         paramerror=1
496 fi
497 if [ $paramerror -eq 0 ]; then
498         if [ "$1" != "remote" ] && [ "$1" != "remote-remove" ]; then
499                 paramerror=1
500                 if [ -z "$paramerror_str" ]; then
501                         paramerror_str="First arg shall be 'remote' or 'remote-remove'"
502                 fi
503         else
504                 shift;
505         fi
506 fi
507 if [ $paramerror -eq 0 ]; then
508         if [ "$1" != "docker" ] && [ "$1" != "kube" ]; then
509                 paramerror=1
510                 if [ -z "$paramerror_str" ]; then
511                         paramerror_str="Second arg shall be 'docker' or 'kube'"
512                 fi
513         else
514                 if [ $1 == "docker" ]; then
515                         RUNMODE="DOCKER"
516                         echo "Setting RUNMODE=DOCKER"
517                 fi
518                 if [ $1 == "kube" ]; then
519                         RUNMODE="KUBE"
520                         echo "Setting RUNMODE=KUBE"
521                 fi
522                 shift;
523         fi
524 fi
525 foundparm=0
526 while [ $paramerror -eq 0 ] && [ $foundparm -eq 0 ]; do
527         foundparm=1
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 "
532                         shift;
533                         foundparm=0
534                 fi
535         fi
536         if [ $paramerror -eq 0 ]; then
537                 if [ "$1" == "auto-clean" ]; then
538                         AUTO_CLEAN="auto"
539                         echo "Option set - Auto clean at end of test script"
540                         shift;
541                         foundparm=0
542                 fi
543         fi
544         if [ $paramerror -eq 0 ]; then
545                 if [ "$1" == "--stop-at-error" ]; then
546                         STOP_AT_ERROR=1
547                         echo "Option set - Stop at first error"
548                         shift;
549                         foundparm=0
550                 fi
551         fi
552         if [ $paramerror -eq 0 ]; then
553                 if [ "$1" == "--ricsim-prefix" ]; then
554                         shift;
555                         TMP_RIC_SIM_PREFIX=$1  #RIC_SIM_PREFIX need to be updated after sourcing of the env file
556                         if [ -z "$1" ]; then
557                                 paramerror=1
558                                 if [ -z "$paramerror_str" ]; then
559                                         paramerror_str="No prefix found for flag: '--ricsim-prefix'"
560                                 fi
561                         else
562                                 echo "Option set - Overriding RIC_SIM_PREFIX with: "$1
563                                 shift;
564                                 foundparm=0
565                         fi
566                 fi
567         fi
568         if [ $paramerror -eq 0 ]; then
569                 if [ "$1" == "--env-file" ]; then
570                         shift;
571                         TEST_ENV_VAR_FILE=$1
572                         if [ -z "$1" ]; then
573                                 paramerror=1
574                                 if [ -z "$paramerror_str" ]; then
575                                         paramerror_str="No env file found for flag: '--env-file'"
576                                 fi
577                         else
578                                 echo "Option set - Reading test env from: "$1
579                                 shift;
580                                 foundparm=0
581                         fi
582                 fi
583         fi
584         if [ $paramerror -eq 0 ]; then
585                 if [ "$1" == "--use-local-image" ]; then
586                         USE_LOCAL_IMAGES=""
587                         shift
588                         while [ $# -gt 0 ] && [[ "$1" != "--"* ]]; do
589                                 USE_LOCAL_IMAGES=$USE_LOCAL_IMAGES" "$1
590                                 if [[ "$AVAILABLE_IMAGES_OVERRIDE" != *"$1"* ]]; then
591                                         paramerror=1
592                                         if [ -z "$paramerror_str" ]; then
593                                                 paramerror_str="App name $1 is not available for local override for flag: '--use-local-image'"
594                                         fi
595                                 fi
596                                 shift;
597                         done
598                         foundparm=0
599                         if [ -z "$USE_LOCAL_IMAGES" ]; then
600                                 paramerror=1
601                                 if [ -z "$paramerror_str" ]; then
602                                         paramerror_str="No app name found for flag: '--use-local-image'"
603                                 fi
604                         else
605                                 echo "Option set - Overriding with local images for app(s):"$USE_LOCAL_IMAGES
606                         fi
607                 fi
608         fi
609         if [ $paramerror -eq 0 ]; then
610                 if [ "$1" == "--use-snapshot-image" ]; then
611                         USE_SNAPSHOT_IMAGES=""
612                         shift
613                         while [ $# -gt 0 ] && [[ "$1" != "--"* ]]; do
614                                 USE_SNAPSHOT_IMAGES=$USE_SNAPSHOT_IMAGES" "$1
615                                 if [[ "$AVAILABLE_IMAGES_OVERRIDE" != *"$1"* ]]; then
616                                         paramerror=1
617                                         if [ -z "$paramerror_str" ]; then
618                                                 paramerror_str="App name $1 is not available for snapshot override for flag: '--use-snapshot-image'"
619                                         fi
620                                 fi
621                                 shift;
622                         done
623                         foundparm=0
624                         if [ -z "$USE_SNAPSHOT_IMAGES" ]; then
625                                 paramerror=1
626                                 if [ -z "$paramerror_str" ]; then
627                                         paramerror_str="No app name found for flag: '--use-snapshot-image'"
628                                 fi
629                         else
630                                 echo "Option set - Overriding with snapshot images for app(s):"$USE_SNAPSHOT_IMAGES
631                         fi
632                 fi
633         fi
634         if [ $paramerror -eq 0 ]; then
635                 if [ "$1" == "--use-staging-image" ]; then
636                         USE_STAGING_IMAGES=""
637                         shift
638                         while [ $# -gt 0 ] && [[ "$1" != "--"* ]]; do
639                                 USE_STAGING_IMAGES=$USE_STAGING_IMAGES" "$1
640                                 if [[ "$AVAILABLE_IMAGES_OVERRIDE" != *"$1"* ]]; then
641                                         paramerror=1
642                                         if [ -z "$paramerror_str" ]; then
643                                                 paramerror_str="App name $1 is not available for staging override for flag: '--use-staging-image'"
644                                         fi
645                                 fi
646                                 shift;
647                         done
648                         foundparm=0
649                         if [ -z "$USE_STAGING_IMAGES" ]; then
650                                 paramerror=1
651                                 if [ -z "$paramerror_str" ]; then
652                                         paramerror_str="No app name found for flag: '--use-staging-image'"
653                                 fi
654                         else
655                                 echo "Option set - Overriding with staging images for app(s):"$USE_STAGING_IMAGES
656                         fi
657                 fi
658         fi
659         if [ $paramerror -eq 0 ]; then
660                 if [ "$1" == "--use-release-image" ]; then
661                         USE_RELEASE_IMAGES=""
662                         shift
663                         while [ $# -gt 0 ] && [[ "$1" != "--"* ]]; do
664                                 USE_RELEASE_IMAGES=$USE_RELEASE_IMAGES" "$1
665                                 if [[ "$AVAILABLE_IMAGES_OVERRIDE" != *"$1"* ]]; then
666                                         paramerror=1
667                                         if [ -z "$paramerror_str" ]; then
668                                                 paramerror_str="App name $1 is not available for release override for flag: '--use-release-image'"
669                                         fi
670                                 fi
671                                 shift;
672                         done
673                         foundparm=0
674                         if [ -z "$USE_RELEASE_IMAGES" ]; then
675                                 paramerror=1
676                                 if [ -z "$paramerror_str" ]; then
677                                         paramerror_str="No app name found for flag: '--use-release-image'"
678                                 fi
679                         else
680                                 echo "Option set - Overriding with release images for app(s):"$USE_RELEASE_IMAGES
681                         fi
682                 fi
683         fi
684         if [ $paramerror -eq 0 ]; then
685                 if [ "$1" == "--image-repo" ]; then
686                         shift;
687                         IMAGE_REPO_ADR=$1
688                         if [ -z "$1" ]; then
689                                 paramerror=1
690                                 if [ -z "$paramerror_str" ]; then
691                                         paramerror_str="No image repo url found for : '--image-repo'"
692                                 fi
693                         else
694                                 echo "Option set - Image repo url: "$1
695                                 shift;
696                                 foundparm=0
697                         fi
698                 fi
699         fi
700         if [ $paramerror -eq 0 ]; then
701                 if [ "$1" == "--repo-policy" ]; then
702                         shift;
703                         IMAGE_REPO_POLICY=$1
704                         if [ -z "$1" ]; then
705                                 paramerror=1
706                                 if [ -z "$paramerror_str" ]; then
707                                         paramerror_str="No policy found for : '--repo-policy'"
708                                 fi
709                         else
710                             if [ "$1" == "local" ] || [ "$1" == "remote" ]; then
711                                         echo "Option set - Image repo policy: "$1
712                                         shift;
713                                         foundparm=0
714                                 else
715                                         paramerror=1
716                                         if [ -z "$paramerror_str" ]; then
717                                                 paramerror_str="Repo policy shall be 'local' or 'remote'"
718                                         fi
719                                 fi
720                         fi
721                 fi
722         fi
723         if [ $paramerror -eq 0 ]; then
724                 if [ "$1" == "--cluster-timeout" ]; then
725                         shift;
726                         CLUSTER_TIME_OUT=$1
727                         if [ -z "$1" ]; then
728                                 paramerror=1
729                                 if [ -z "$paramerror_str" ]; then
730                                         paramerror_str="No timeout value found for : '--cluster-timeout'"
731                                 fi
732                         else
733                                 #Check if positive int
734                                 case ${CLUSTER_TIME_OUT#[+]} in
735                                         *[!0-9]* | '')
736                                                 paramerror=1
737                                                 if [ -z "$paramerror_str" ]; then
738                                                         paramerror_str="Value for '--cluster-timeout' not an int : "$CLUSTER_TIME_OUT
739                                                 fi
740                                                 ;;
741                                         * ) ;; # Ok
742                                 esac
743                                 echo "Option set - Cluster timeout: "$1
744                                 shift;
745                                 foundparm=0
746                         fi
747                 fi
748         fi
749         if [ $paramerror -eq 0 ]; then
750                 if [ "$1" == "--override" ]; then
751                         shift;
752                         TEST_ENV_VAR_FILE_OVERRIDE=$1
753                         if [ -z "$1" ]; then
754                                 paramerror=1
755                                 if [ -z "$paramerror_str" ]; then
756                                         paramerror_str="No env file found for flag: '--override'"
757                                 fi
758                         else
759                                 if [ ! -f $TEST_ENV_VAR_FILE_OVERRIDE ]; then
760                                         paramerror=1
761                                         if [ -z "$paramerror_str" ]; then
762                                                 paramerror_str="File for '--override' does not exist : "$TEST_ENV_VAR_FILE_OVERRIDE
763                                         fi
764                                 fi
765                                 echo "Option set - Override env from: "$1
766                                 shift;
767                                 foundparm=0
768                         fi
769                 fi
770         fi
771         if [ $paramerror -eq 0 ]; then
772                 if [ "$1" == "--pre-clean" ]; then
773                         PRE_CLEAN=1
774                         echo "Option set - Pre-clean of kube/docker resouces"
775                         shift;
776                         foundparm=0
777                 fi
778         fi
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"
783                         shift;
784                         foundparm=0
785                 fi
786         fi
787         if [ $paramerror -eq 0 ]; then
788                 if [ "$1" == "--gen-stats" ]; then
789                         COLLECT_RUNTIME_STATS=1
790                         echo "Option set - Collect runtime statistics"
791                         shift;
792                         foundparm=0
793                 fi
794         fi
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)"
800                         else
801                                 if [ -z "KUBE_PRESTARTED_IMAGES" ]; then
802                                         DELETE_KUBE_NAMESPACES=0
803                                         echo "Option ignored - Delete namespaces (ignored when using prestarted apps)"
804                                 else
805                                         DELETE_KUBE_NAMESPACES=1
806                                         echo "Option set - Delete namespaces"
807                                 fi
808                         fi
809                         shift;
810                         foundparm=0
811                 fi
812         fi
813         if [ $paramerror -eq 0 ]; then
814                 if [ "$1" == "--delete-containers" ]; then
815                         if [ $RUNMODE == "DOCKER" ]; then
816                                 DELETE_CONTAINERS=1
817                                 echo "Option set - Delete containers started by previous test(s)"
818                         else
819                                 echo "Option ignored - Delete containers (ignored when running kube)"
820                         fi
821                         shift;
822                         foundparm=0
823                 fi
824         fi
825         if [ $paramerror -eq 0 ]; then
826                 if [ "$1" == "--endpoint-stats" ]; then
827                         COLLECT_ENDPOINT_STATS=1
828                         echo "Option set - Collect endpoint statistics"
829                         shift;
830                         foundparm=0
831                 fi
832         fi
833         if [ $paramerror -eq 0 ]; then
834                 if [ "$1" == "--kubeconfig" ]; then
835                         shift;
836                         if [ -z "$1" ]; then
837                                 paramerror=1
838                                 if [ -z "$paramerror_str" ]; then
839                                         paramerror_str="No path found for : '--kubeconfig'"
840                                 fi
841                         else
842                             if [ -f  $1 ]; then
843                                         if [ ! -z "$KUBECONF" ]; then
844                                                 paramerror=1
845                                                 if [ -z "$paramerror_str" ]; then
846                                                         paramerror_str="Only one of --kubeconfig/--kubecontext can be set"
847                                                 fi
848                                         else
849                                                 KUBECONF="--kubeconfig $1"
850                                                 echo "Option set - Kubeconfig path: "$1
851                                                 shift;
852                                                 foundparm=0
853                                         fi
854                                 else
855                                         paramerror=1
856                                         if [ -z "$paramerror_str" ]; then
857                                                 paramerror_str="File $1 for --kubeconfig not found"
858                                         fi
859                                 fi
860                         fi
861                 fi
862         fi
863         if [ $paramerror -eq 0 ]; then
864                 if [ "$1" == "--kubecontext" ]; then
865                         shift;
866                         if [ -z "$1" ]; then
867                                 paramerror=1
868                                 if [ -z "$paramerror_str" ]; then
869                                         paramerror_str="No context-name found for : '--kubecontext'"
870                                 fi
871                         else
872                                 if [ ! -z "$KUBECONF" ]; then
873                                         paramerror=1
874                                         if [ -z "$paramerror_str" ]; then
875                                                 paramerror_str="Only one of --kubeconfig or --kubecontext can be set"
876                                         fi
877                                 else
878                                         KUBECONF="--context $1"
879                                         echo "Option set - Kubecontext name: "$1
880                                         shift;
881                                         foundparm=0
882                                 fi
883                         fi
884                 fi
885         fi
886         if [ $paramerror -eq 0 ]; then
887                 if [ "$1" == "--host-path-dir" ]; then
888                         shift;
889                         if [ -z "$1" ]; then
890                                 paramerror=1
891                                 if [ -z "$paramerror_str" ]; then
892                                         paramerror_str="No path found for : '--host-path-dir'"
893                                 fi
894                         else
895                                 HOST_PATH_BASE_DIR=$1
896                                 echo "Option set - Host path for kube set to: "$1
897                                 shift
898                                 foundparm=0
899                         fi
900                 fi
901         fi
902         if [ $paramerror -eq 0 ]; then
903                 if [ "$1" == "--docker-host" ]; then
904                         shift;
905                         if [ -z "$1" ]; then
906                                 paramerror=1
907                                 if [ -z "$paramerror_str" ]; then
908                                         paramerror_str="No url found for : '--docker-host'"
909                                 fi
910                         else
911                                 export DOCKER_HOST="$1"
912                                 echo "Option set - DOCKER_HOST set to: "$1
913                                 shift
914                                 foundparm=0
915                         fi
916                 fi
917         fi
918         if [ $paramerror -eq 0 ]; then
919                 if [ "$1" == "--docker-host" ]; then
920                         shift;
921                         if [ -z "$1" ]; then
922                                 paramerror=1
923                                 if [ -z "$paramerror_str" ]; then
924                                         paramerror_str="No url found for : '--docker-host'"
925                                 fi
926                         else
927                                 export DOCKER_HOST="$1"
928                                 echo "Option set - DOCKER_HOST set to: "$1
929                                 shift
930                                 foundparm=0
931                         fi
932                 fi
933         fi
934         if [ $paramerror -eq 0 ]; then
935                 if [ "$1" == "--docker-proxy" ]; then
936                         shift;
937                         if [ -z "$1" ]; then
938                                 paramerror=1
939                                 if [ -z "$paramerror_str" ]; then
940                                         paramerror_str="No ip/host found for : '--docker-proxy'"
941                                 fi
942                         else
943                                 export LOCALHOST_NAME=$1
944                                 echo "Option set - docker proxy set to: "$1
945                                 shift
946                                 foundparm=0
947                         fi
948                 fi
949         fi
950 done
951 echo ""
952
953 #Still params left?
954 if [ $paramerror -eq 0 ] && [ $# -gt 0 ]; then
955         paramerror=1
956         if [ -z "$paramerror_str" ]; then
957                 paramerror_str="Unknown parameter(s): "$@
958         fi
959 fi
960
961 if [ $paramerror -eq 1 ]; then
962         echo -e $RED"Incorrect arg list: "$paramerror_str$ERED
963         __print_args
964         exit 1
965 fi
966
967 LOCALHOST_HTTP="http://$LOCALHOST_NAME"
968 LOCALHOST_HTTPS="https://$LOCALHOST_NAME"
969
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
973         . $TEST_ENV_VAR_FILE
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
977         fi
978
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
981         else
982                 found_profile=0
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
986                                 found_profile=1
987                         fi
988                 done
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
993                         exit 1
994                 fi
995         fi
996 else
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
1001         exit 1
1002 fi
1003
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
1007 fi
1008
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
1011         exit 1
1012 fi
1013
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
1017         exit 1
1018 fi
1019
1020 # Choose list of included apps depending on run-mode
1021 if [ $RUNMODE == "KUBE" ]; then
1022         INCLUDED_IMAGES=$KUBE_INCLUDED_IMAGES
1023 else
1024         INCLUDED_IMAGES=$DOCKER_INCLUDED_IMAGES
1025 fi
1026
1027 echo ""
1028 # auto adding system apps
1029 __added_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
1034 else
1035         INCLUDED_IMAGES=$INCLUDED_IMAGES" "$TESTENV_DOCKER_SYSTEM_APPS
1036         TMP_APPS=$TESTENV_DOCKER_SYSTEM_APPS
1037 fi
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"
1042             padded_iapp=$iapp
1043                 while [ ${#padded_iapp} -lt 16 ]; do
1044                         padded_iapp=$padded_iapp" "
1045                 done
1046                 echo " Auto-adding system app   $padded_iapp  Sourcing $file_pointer"
1047                 . $file_pointer
1048                 if [ $? -ne 0 ]; then
1049                         echo " Include file $file_pointer contain errors. Exiting..."
1050                         exit 1
1051                 fi
1052                 __added_apps=" $iapp "$__added_apps
1053         done
1054 else
1055         echo " None"
1056 fi
1057
1058 if [ $RUNMODE == "KUBE" ]; then
1059         TMP_APPS=$INCLUDED_IMAGES" "$KUBE_PRESTARTED_IMAGES
1060 else
1061         TMP_APPS=$INCLUDED_IMAGES
1062 fi
1063
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"
1069                         padded_iapp=$iapp
1070                         while [ ${#padded_iapp} -lt 16 ]; do
1071                                 padded_iapp=$padded_iapp" "
1072                         done
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"
1076                                 exit 1
1077                         fi
1078                         . $file_pointer
1079                         if [ $? -ne 0 ]; then
1080                                 echo " Include file $file_pointer contain errors. Exiting..."
1081                                 exit 1
1082                         fi
1083                 fi
1084         done
1085 echo ""
1086
1087 echo -e $BOLD"Test environment info"$EBOLD
1088
1089 # Check needed installed sw
1090
1091 tmp=$(which bash)
1092 if [ $? -ne 0 ] || [ -z "$tmp" ]; then
1093         echo -e $RED"bash is required to run the test environment, pls install"$ERED
1094         exit 1
1095 fi
1096 echo " bash is installed and using version:"
1097 echo "$(bash --version)" | indent2
1098
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
1102         exit 1
1103 fi
1104 echo " python3 is installed and using version: $(python3 --version)"
1105
1106 tmp=$(which docker)
1107 if [ $? -ne 0 ] || [ -z "$tmp" ]; then
1108         echo -e $RED"docker is required to run the test environment, pls install"$ERED
1109         exit 1
1110 fi
1111 echo " docker is installed and using versions:"
1112 echo  "  $(docker version --format 'Client version {{.Client.Version}} Server version {{.Server.Version}}')"
1113
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
1118                 exit 1
1119         else
1120                 tmp=$(docker-compose version)
1121                 echo " docker-compose installed and using version $tmp"
1122                 if [[ "$tmp" == *'v2'* ]]; then
1123                         DOCKER_COMPOSE_VERION="V2"
1124                 fi
1125         fi
1126 fi
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
1131                 exit 1
1132         else
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"
1140                         echo " "
1141                         echo "kubectl response:"
1142                         echo $res
1143                         echo " "
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 "
1147                         echo " "
1148                         echo "1"
1149                         echo "Run with sudo"
1150                         echo -e $BOLD"sudo <test-script-and-parameters>"$EBOLD
1151                         echo " "
1152                         echo "2"
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
1156                         echo " "
1157                         echo "3"
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"
1161
1162                         exit 1
1163                 fi
1164                 echo " Node(s) and container runtime config"
1165                 kubectl $KUBECONF get nodes -o wide | indent2
1166                 echo ""
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"
1171                 else
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"
1175                 fi
1176         fi
1177 fi
1178
1179 echo ""
1180
1181 echo -e $BOLD"Checking configured image setting for this test case"$EBOLD
1182
1183 #Temp var to check for image variable name errors
1184 IMAGE_ERR=0
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
1188
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() {
1192
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>"
1195                 ((IMAGE_ERR++))
1196                 return
1197         fi
1198
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
1203                 return
1204         fi
1205         tmp=${6}"\t"${1}"\t"
1206         #Create var from the input var names
1207         image="${!3}"
1208         tmptag=$4"_"$5
1209         tag="${!tmptag}"
1210
1211         optional_image_repo_target=""
1212
1213         if [ -z $image ]; then
1214                 __check_ignore_image $1
1215                 if [ $? -eq 0 ]; then
1216                         app_ds=$6
1217                         if [ -z "$6" ]; then
1218                                 app_ds="<app ignored>"
1219                         fi
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
1223                         return
1224                 fi
1225                 echo -e $RED"\$"$3" not set in $TEST_ENV_VAR_FILE"$ERED
1226                 ((IMAGE_ERR++))
1227                 echo ""
1228                 tmp=$tmp"<no-image>\t"
1229         else
1230
1231                 optional_image_repo_target=$image
1232
1233                 #Add repo depending on image type
1234                 if [ "$5" == "REMOTE_RELEASE" ]; then
1235                         image=$NEXUS_RELEASE_REPO$image
1236                 fi
1237                 if [ "$5" == "REMOTE" ]; then
1238                         image=$NEXUS_STAGING_REPO$image
1239                 fi
1240                 if [ "$5" == "REMOTE_SNAPSHOT" ]; then
1241                         image=$NEXUS_SNAPSHOT_REPO$image
1242                 fi
1243                 if [ "$5" == "REMOTE_PROXY" ]; then
1244                         image=$NEXUS_PROXY_REPO$image
1245                 fi
1246                 if [ "$5" == "REMOTE_RELEASE_ONAP" ]; then
1247                         image=$NEXUS_RELEASE_REPO_ONAP$image
1248                 fi
1249                 if [ "$5" == "REMOTE_RELEASE_ORAN" ]; then
1250                         image=$NEXUS_RELEASE_REPO_ORAN$image
1251                 fi
1252                 #No nexus repo added for local images, tag: LOCAL
1253                 tmp=$tmp$image"\t"
1254         fi
1255         if [ -z $tag ]; then
1256                 echo -e $RED"\$"$tmptag" not set in $TEST_ENV_VAR_FILE"$ERED
1257                 ((IMAGE_ERR++))
1258                 echo ""
1259                 tmp=$tmp"<no-tag>\t"
1260         else
1261                 tmp=$tmp$tag
1262         fi
1263         tmp=$tmp"\t"$5
1264         echo -e "$tmp" >> $image_list_file
1265         #Export the env var
1266         export "${2}"=$image":"$tag  #Note, this var may be set to the value of the target value below in __check_and_pull_image
1267
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
1272                 fi
1273                 if [[ $5 == *"REMOTE"* ]]; then
1274                         if [ "$IMAGE_REPO_POLICY" == "remote" ]; then
1275                                 remote_or_local_push=true
1276                         fi
1277                 fi
1278         fi
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
1284                 fi
1285                 export "${2}_TARGET"=$IMAGE_REPO_ADR"/"$optional_image_repo_target":"$tag  #Create image + tag for optional image repo - pushed later if needed
1286         else
1287                 export "${2}_SOURCE"=""
1288                 export "${2}_TARGET"=""
1289         fi
1290 }
1291
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
1297                         return 0
1298                 fi
1299         done
1300         return 1
1301 }
1302
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
1308                         return 0
1309                 fi
1310         done
1311         return 1
1312 }
1313
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
1319                         return 0
1320                 fi
1321         done
1322         return 1
1323 }
1324
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
1330                         return 0
1331                 fi
1332         done
1333         return 1
1334 }
1335
1336 # Removed image from included list of included images
1337 # Used when an image is marked as conditionally ignored
1338 __remove_included_image() {
1339         tmp_img_rem_list=""
1340         for im in $INCLUDED_IMAGES; do
1341                 if [ "$1" != "$im" ]; then
1342                         tmp_img_rem_list=$tmp_img_rem_list" "$im
1343                 fi
1344         done
1345         INCLUDED_IMAGES=$tmp_img_rem_list
1346         return 0
1347 }
1348
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
1354                         return 0
1355                 fi
1356         done
1357         return 1
1358 }
1359
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
1364                         return 1
1365                 fi
1366         done
1367         return 0
1368 }
1369
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() {
1373
1374         for im in $ORAN_IMAGES_APP_NAMES; do
1375                 if [ "$1" == "$im" ]; then
1376                         echo "REMOTE_RELEASE_ORAN"
1377                         return 0
1378                 fi
1379         done
1380
1381         for im in $ONAP_IMAGES_APP_NAMES; do
1382                 if [ "$1" == "$im" ]; then
1383                         echo "REMOTE_RELEASE_ONAP"
1384                         return 0
1385                 fi
1386         done
1387
1388         found=0
1389         for im in $PROJECT_IMAGES_APP_NAMES; do
1390                 if [ "$1" == "$im" ]; then
1391                         found=1
1392                 fi
1393         done
1394
1395         if [ $found -eq 0 ]; then
1396                 echo "REMOTE_PROXY"
1397                 return 0
1398         fi
1399
1400         suffix=""
1401         if [ $IMAGE_CATEGORY == "RELEASE" ]; then
1402                 suffix="REMOTE_RELEASE"
1403         fi
1404         if [ $IMAGE_CATEGORY == "DEV" ]; then
1405                 suffix="REMOTE"
1406         fi
1407         CTR=0
1408         for im in $USE_STAGING_IMAGES; do
1409                 if [ "$1" == "$im" ]; then
1410                         suffix="REMOTE"
1411                         ((CTR++))
1412                 fi
1413         done
1414         for im in $USE_RELEASE_IMAGES; do
1415                 if [ "$1" == "$im" ]; then
1416                         suffix="REMOTE_RELEASE"
1417                         ((CTR++))
1418                 fi
1419         done
1420         for im in $USE_SNAPSHOT_IMAGES; do
1421                 if [ "$1" == "$im" ]; then
1422                         suffix="REMOTE_SNAPSHOT"
1423                         ((CTR++))
1424                 fi
1425         done
1426         for im in $USE_LOCAL_IMAGES; do
1427                 if [ "$1" == "$im" ]; then
1428                         suffix="LOCAL"
1429                         ((CTR++))
1430                 fi
1431         done
1432         echo $suffix
1433         if [ $CTR -gt 1 ]; then
1434                 exit 1
1435         fi
1436         return 0
1437 }
1438
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}"
1445
1446                 if [ -z $target_image ]; then
1447                         return 0  # Image with no target shall not be pushed
1448                 fi
1449
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
1454                         ((IMAGE_ERR++))
1455                         echo ""
1456                         echo -e "  Attempt to re-tag image to: ${BOLD}${target_image}${EBOLD} - ${RED}Failed${ERED}"
1457                         cat ./tmp/.dockererr
1458                         return 1
1459                 else
1460                         echo -e "  Attempt to re-tag image to: ${BOLD}${target_image}${EBOLD} - ${GREEN}OK${EGREEN}"
1461                 fi
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
1466                         ((IMAGE_ERR++))
1467                         echo ""
1468                         echo -e "  Attempt to push re-tagged image: ${BOLD}${target_image}${EBOLD} - ${RED}Failed${ERED}"
1469                         cat ./tmp/.dockererr
1470                         return 1
1471                 else
1472                         echo -e "  Attempt to push re-tagged image: ${BOLD}${target_image}${EBOLD} - ${GREEN}OK${EGREEN}"
1473                 fi
1474                 export "${1}"=$target_image
1475         fi
1476         return 0
1477 }
1478
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() {
1482
1483         source_image="${!4}"
1484
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)
1488
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
1492                         ((IMAGE_ERR++))
1493                         return 1
1494                 else
1495                         echo -e "  "$2" (local image): \033[1m"$source_image"\033[0m "$GREEN"OK"$EGREEN
1496                 fi
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
1505                                                 ((IMAGE_ERR++))
1506                                                 echo ""
1507                                                 echo -e $RED"  Container(s) could not be stopped - try manual stopping the container(s)"$ERED
1508                                                 cat ./tmp/.dockererr
1509                                                 return 1
1510                                         fi
1511                                 fi
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
1517                                                 ((IMAGE_ERR++))
1518                                                 echo ""
1519                                                 echo -e $RED"  Container(s) could not be removed - try manual removal of the container(s)"$ERED
1520                                                 cat ./tmp/.dockererr
1521                                                 return 1
1522                                         fi
1523                                 fi
1524                                 echo -e "  Attempt to stop and remove container(s), if running - "$GREEN"stopped removed"$EGREEN
1525                                 tmp_im=""
1526                         else
1527                                 tmp_im=""
1528                         fi
1529                 fi
1530                 if [ -z "$tmp_im" ]; then
1531                         echo -ne "  Pulling image${SAMELINE}"
1532                         out=$(docker pull $source_image)
1533                         if [ $? -ne 0 ]; then
1534                                 echo ""
1535                                 echo -e "  Pulling image -$RED could not be pulled"$ERED
1536                                 ((IMAGE_ERR++))
1537                                 echo $out > ./tmp/.dockererr
1538                                 echo $out
1539                                 return 1
1540                         fi
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"
1546                         else
1547                                 echo -e "  Pulling image -$GREEN Pulled $EGREEN"
1548                         fi
1549                 else
1550                         echo -e "  Pulling image -$GREEN OK $EGREEN(exists in local repository)"
1551                 fi
1552         fi
1553
1554         __retag_and_push_image $4
1555
1556         return $?
1557 }
1558
1559 setup_testenvironment() {
1560         # Check that image env setting are available
1561         echo ""
1562
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
1566                 incl=$?
1567                 __check_project_image $imagename
1568                 proj=$?
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
1574                                         ((IMAGE_ERR++))
1575                                 fi
1576                         else
1577                                 IMAGE_SUFFIX="none"
1578                         fi
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
1589
1590                         function_pointer="__"$imagename"_test_requirements"
1591                         $function_pointer
1592                 fi
1593         done
1594
1595         #Errors in image setting - exit
1596         if [ $IMAGE_ERR -ne 0 ]; then
1597                 exit 1
1598         fi
1599
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
1603
1604         echo ""
1605
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
1613                         exit 1
1614                 else
1615                         echo " SIM_GROUP auto set to: " $SIM_GROUP
1616                 fi
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
1619                 exit 1
1620         else
1621                 echo " SIM_GROUP env var already set to: " $SIM_GROUP
1622         fi
1623
1624         echo ""
1625
1626         #Temp var to check for image pull errors
1627         IMAGE_ERR=0
1628
1629         # Delete namespaces
1630         echo -e $BOLD"Deleting namespaces"$EBOLD
1631
1632
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"
1637                 else
1638                         for test_env_ns in $test_env_namespaces; do
1639                                 __kube_delete_namespace $test_env_ns
1640                         done
1641                 fi
1642         else
1643                 echo " Namespace delete option not set or ignored"
1644         fi
1645         echo ""
1646
1647         # Delete containers
1648         echo -e $BOLD"Deleting containers"$EBOLD
1649
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
1655         else
1656                 echo " Contatiner delete option not set or ignored"
1657         fi
1658         echo ""
1659
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
1664         else
1665                 for imagename in $APP_SHORT_NAMES; do
1666                         __check_included_image $imagename
1667                         incl=$?
1668                         __check_project_image $imagename
1669                         proj=$?
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"
1676                                         fi
1677                                 else
1678                                         START_ARG_MOD=$START_ARG
1679                                 fi
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
1692                                 fi
1693                         else
1694                                 echo -e $YELLOW" Excluding $imagename image from image check/pull"$EYELLOW
1695                         fi
1696                 done
1697         fi
1698
1699         #Errors in image setting - exit
1700         if [ $IMAGE_ERR -ne 0 ]; then
1701                 echo ""
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
1706                     echo ""
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
1711                 fi
1712                 echo "#################################################################################################"
1713                 echo ""
1714                 exit 1
1715         fi
1716
1717         echo ""
1718
1719         echo -e $BOLD"Building images needed for test"$EBOLD
1720
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"
1734                                 $function_pointer
1735
1736                         else
1737                                 echo -e $YELLOW" Excluding image for app $imagename from image build"$EYELLOW
1738                         fi
1739                 fi
1740         done
1741
1742         cd $AUTOTEST_HOME # Just to make sure...
1743
1744         echo ""
1745
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
1748
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
1752
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
1757                         print_image_data=0
1758                         if [ -z "$IMAGE_REPO_ADR" ]; then
1759                                 print_image_data=1
1760                         else
1761                                 __check_image_local_build $imagename
1762                                 if [ $? -eq 0 ]; then
1763                                         print_image_data=1
1764                                 fi
1765                         fi
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
1775                         fi
1776                 fi
1777         done
1778
1779         column -t -s $'\t' $docker_tmp_file | indent1
1780
1781         echo ""
1782
1783         if [ ! -z "$IMAGE_REPO_ADR" ]; then
1784
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
1788
1789                 docker_tmp_file=./tmp/.docker-images-table
1790                 format_string="{{.Repository}}\\t{{.Tag}}"
1791                 echo -e "Application\tRepository\tTag" > $docker_tmp_file
1792
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
1807                                 fi
1808                         fi
1809                 done
1810
1811                 column -t -s $'\t' $docker_tmp_file | indent1
1812
1813                 echo ""
1814         fi
1815
1816         if [ $RUNMODE == "KUBE" ]; then
1817
1818                 echo "================================================================================="
1819                 echo "================================================================================="
1820
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"
1826                 else
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"
1832                 fi
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
1835
1836                 echo "================================================================================="
1837                 echo "================================================================================="
1838                 echo ""
1839         fi
1840
1841         echo -e $BOLD"======================================================="$EBOLD
1842         echo -e $BOLD"== Common test setup completed -  test script begins =="$EBOLD
1843         echo -e $BOLD"======================================================="$EBOLD
1844         echo ""
1845
1846         LOG_STAT_ARGS=""
1847
1848         for imagename in $APP_SHORT_NAMES; do
1849                 __check_included_image $imagename
1850                 retcode_i=$?
1851                 __check_prestarted_image $imagename
1852                 retcode_p=$?
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
1860
1861                         function_pointer="__"$imagename"_initial_setup"
1862                         $function_pointer
1863
1864                         function_pointer="__"$imagename"_statisics_setup"
1865                         LOG_STAT_ARGS=$LOG_STAT_ARGS" "$($function_pointer)
1866                 fi
1867         done
1868
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=$!
1872         fi
1873
1874 }
1875
1876 # Function to print the test result, shall be the last cmd in a test script
1877 # args: -
1878 # (Function for test scripts)
1879 print_result() {
1880
1881         TCTEST_END=$SECONDS
1882         duration=$((TCTEST_END-TCTEST_START))
1883
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"
1893         echo ""
1894
1895
1896         if [ $RES_DEVIATION -gt 0 ]; then
1897                 echo "Test case deviations"
1898                 echo "===================================="
1899                 cat $DEVIATION_FILE
1900         fi
1901         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
1907         fi
1908         echo ""
1909
1910         if [ $COLLECT_RUNTIME_STATS -eq 1 ]; then
1911                 echo "Runtime statistics collected in file: "$TESTLOGS/$ATC/stat_data.csv
1912                 echo ""
1913         fi
1914
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"
1940                 echo ""
1941
1942                 # Update test suite counter
1943                 if [ -f .tmp_tcsuite_pass_ctr ]; then
1944                         tmpval=$(< .tmp_tcsuite_pass_ctr)
1945                         ((tmpval++))
1946                         echo $tmpval > .tmp_tcsuite_pass_ctr
1947                 fi
1948                 if [ -f .tmp_tcsuite_pass ]; then
1949                         echo " - "$ATC " -- "$TC_ONELINE_DESCR"  Execution time: "$duration" seconds" >> .tmp_tcsuite_pass
1950                 fi
1951                 #Create file with OK exit code
1952                 echo "0" > "$AUTOTEST_HOME/.result$ATC.txt"
1953                 echo "0" > "$TESTLOGS/$ATC/.result$ATC.txt"
1954         else
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"
1960                 echo ""
1961                 # Update test suite counter
1962                 if [ -f .tmp_tcsuite_fail_ctr ]; then
1963                         tmpval=$(< .tmp_tcsuite_fail_ctr)
1964                         ((tmpval++))
1965                         echo $tmpval > .tmp_tcsuite_fail_ctr
1966                 fi
1967                 if [ -f .tmp_tcsuite_fail ]; then
1968                         echo " - "$ATC " -- "$TC_ONELINE_DESCR"  Execution time: "$duration" seconds" >> .tmp_tcsuite_fail
1969                 fi
1970         fi
1971
1972         echo "++++ Number of tests:          "$RES_TEST
1973         echo "++++ Number of passed tests:   "$RES_PASS
1974         echo "++++ Number of failed tests:   "$RES_FAIL
1975         echo ""
1976         echo "++++ Number of failed configs: "$RES_CONF_FAIL
1977         echo ""
1978         echo "++++ Number of test case deviations: "$RES_DEVIATION
1979         echo ""
1980         echo "-------------------------------------     Test case complete    ---------------------------------"
1981         echo "-------------------------------------------------------------------------------------------------"
1982         echo ""
1983 }
1984
1985 #####################################################################
1986 ###### Functions for start, configuring, stoping, cleaning etc ######
1987 #####################################################################
1988
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"
1992 start_timer() {
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
2000         fi
2001         TC_TIMER_CURRENT_FAILS=$(($RES_FAIL+$RES_CONF_FAIL))
2002         echo " Timer started: $(date)"
2003 }
2004
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
2007 print_timer() {
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" $@
2011                 return 1
2012         fi
2013         duration=$(($SECONDS-$TC_TIMER_STARTTIME))
2014         if [ $duration -eq 0 ]; then
2015                 duration="<1 second"
2016         else
2017                 duration=$duration" seconds"
2018         fi
2019         echo " Timer duration :" $duration
2020         res="-"
2021         if [ $(($RES_FAIL+$RES_CONF_FAIL)) -ne $TC_TIMER_CURRENT_FAILS ]; then
2022                 res="Failures occured during test - timer not reliabled"
2023         fi
2024
2025         echo -e "$TC_TIMER_TIMER_TEXT \t $duration \t $res" >> $TIMER_MEASUREMENTS
2026 }
2027
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>
2031 deviation() {
2032         echo -e $BOLD"DEVIATION(${BASH_LINENO[0]}): "${FUNCNAME[0]} $EBOLD
2033         if [ $# -lt 1 ]; then
2034                 ((RES_CONF_FAIL++))
2035                 __print_err "need 1 or more args,  <deviation message to print>" $@
2036                 exit 1
2037         fi
2038         ((RES_DEVIATION++))
2039         echo -e $BOLD$YELLOW" Test case deviation: ${@:1}"$EYELLOW$EBOLD
2040         echo "Line: ${BASH_LINENO[0]} - ${@:1}" >> $DEVIATION_FILE
2041         __print_current_stats
2042         echo ""
2043 }
2044
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"
2050
2051                 # Update test suite counter
2052                 if [ -f .tmp_tcsuite_fail_ctr ]; then
2053                         tmpval=$(< .tmp_tcsuite_fail_ctr)
2054                         ((tmpval++))
2055                         echo $tmpval > .tmp_tcsuite_fail_ctr
2056                 fi
2057                 if [ -f .tmp_tcsuite_fail ]; then
2058                         echo " - "$ATC " -- "$TC_ONELINE_DESCR"  Execution stopped due to error" >> .tmp_tcsuite_fail
2059                 fi
2060                 exit 1
2061         fi
2062         return 0
2063 }
2064
2065 # Stop and remove all containers
2066 # args: -
2067 # (Not for test scripts)
2068 __clean_containers() {
2069
2070         echo -e $BOLD"Docker clean and stopping and removing all running containers, by container name"$EBOLD
2071
2072         #Create empty file
2073         running_contr_file="./tmp/running_contr.txt"
2074         > $running_contr_file
2075
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
2079         done
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=""
2083         fi
2084
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
2087
2088         tab_heading1="App display name"
2089         tab_heading2="App short name"
2090         tab_heading3="Container name"
2091
2092         tab_heading1_len=${#tab_heading1}
2093         tab_heading2_len=${#tab_heading2}
2094         tab_heading3_len=${#tab_heading3}
2095         cntr=0
2096         #Calc field lengths of each item in the list of containers
2097         while read p; do
2098                 if (( $cntr % 3 == 0 ));then
2099                         if [ ${#p} -gt $tab_heading1_len ]; then
2100                                 tab_heading1_len=${#p}
2101                         fi
2102                 fi
2103                 if (( $cntr % 3 == 1));then
2104                         if [ ${#p} -gt $tab_heading2_len ]; then
2105                                 tab_heading2_len=${#p}
2106                         fi
2107                 fi
2108                 if (( $cntr % 3 == 2));then
2109                         if [ ${#p} -gt $tab_heading3_len ]; then
2110                                 tab_heading3_len=${#p}
2111                         fi
2112                 fi
2113                 let cntr=cntr+1
2114         done <$running_contr_file
2115
2116         let tab_heading1_len=tab_heading1_len+2
2117         while (( ${#tab_heading1} < $tab_heading1_len)); do
2118                 tab_heading1="$tab_heading1"" "
2119         done
2120
2121         let tab_heading2_len=tab_heading2_len+2
2122         while (( ${#tab_heading2} < $tab_heading2_len)); do
2123                 tab_heading2="$tab_heading2"" "
2124         done
2125
2126         let tab_heading3_len=tab_heading3_len+2
2127         while (( ${#tab_heading3} < $tab_heading3_len)); do
2128                 tab_heading3="$tab_heading3"" "
2129         done
2130
2131         if [ ! -z "$running_contr_file_empty" ]; then
2132                 echo $running_contr_file_empty | indent1
2133         else
2134                 echo " $tab_heading1$tab_heading2$tab_heading3"" Actions"
2135                 cntr=0
2136                 while read p; do
2137                         if (( $cntr % 3 == 0 ));then
2138                                 row=""
2139                                 heading=$p
2140                                 heading_len=$tab_heading1_len
2141                         fi
2142                         if (( $cntr % 3 == 1));then
2143                                 heading=$p
2144                                 heading_len=$tab_heading2_len
2145                         fi
2146                         if (( $cntr % 3 == 2));then
2147                                 contr=$p
2148                                 heading=$p
2149                                 heading_len=$tab_heading3_len
2150                         fi
2151                         while (( ${#heading} < $heading_len)); do
2152                                 heading="$heading"" "
2153                         done
2154                         row=$row$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}"
2162                         fi
2163                         let cntr=cntr+1
2164                 done <$running_contr_file
2165         fi
2166
2167         echo ""
2168
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
2175                         exit 1
2176                 fi
2177         fi
2178         echo -e "$GREEN  Done$EGREEN"
2179
2180         echo -e $BOLD" Removing all unused docker neworks"$EBOLD
2181         docker network prune --force | indent2
2182         echo -e "$GREEN  Done$EGREEN"
2183
2184         echo -e $BOLD" Removing all unused docker volumes"$EBOLD
2185         docker volume prune --force | indent2
2186         echo -e "$GREEN  Done$EGREEN"
2187
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"
2191         echo ""
2192
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
2198                         echo ""
2199                 fi
2200         fi
2201 }
2202
2203 ###################################
2204 ### Functions for kube management
2205 ###################################
2206
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
2212                 echo "deployment"
2213                 return 0
2214         fi
2215         kubectl $KUBECONF get sts $1 -n $2 1> /dev/null 2> ./tmp/kubeerr
2216         if [ $? -eq 0 ]; then
2217                 echo "sts"
2218                 return 0
2219         fi
2220         echo "unknown-resource-type"
2221         return 1
2222 }
2223
2224 # Scale a kube resource to a specific count
2225 # args: <resource-type> <resource-name> <namespace> <target-count>
2226 # (Not for test scripts)
2227 __kube_scale() {
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"
2232                 ((RES_CONF_FAIL++))
2233                 echo "  Message: $(<./tmp/kubeerr)"
2234                 return 1
2235         else
2236                 echo -e "  Setting $1 $2 replicas=$4 in namespace $3 $GREEN OK $EGREEN"
2237         fi
2238
2239         TSTART=$SECONDS
2240
2241         for i in {1..500}; do
2242                 count=$(kubectl $KUBECONF get $1/$2  -n $3 -o jsonpath='{.status.replicas}' 2> /dev/null)
2243                 retcode=$?
2244                 if [ -z "$count" ]; then
2245                         #No value is sometimes returned for some reason, in case the resource has replica 0
2246                         count=0
2247                 fi
2248                 if [ $retcode -ne 0 ]; then
2249                         echo -e "$RED  Cannot fetch current replica count for $1 $2 in namespace $3 $ERED"
2250                         ((RES_CONF_FAIL++))
2251                         return 1
2252                 fi
2253                 #echo ""
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"
2256                         sleep $i
2257                 else
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"
2260                         echo ""
2261                         return 0
2262                 fi
2263         done
2264         echo ""
2265         echo -e "$RED  Replica count did not reach target replicas=$4. Failed with replicas=$count $ERED"
2266         ((RES_CONF_FAIL++))
2267         return 0
2268 }
2269
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() {
2275         namespace=$1
2276         labelname=$2
2277         labelid=$3
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"
2286                         done
2287                 fi
2288         done
2289 }
2290
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() {
2296         namespace=$1
2297         labelname=$2
2298         labelid=$3
2299         if [ -z "$3" ]; then
2300                 echo "  Attempt to scale - deployment replicaset statefulset - in namespace $namespace with label $labelname"
2301         else
2302                 echo "  Attempt to scale - deployment replicaset statefulset - in namespace $namespace with label $labelname=$labelid"
2303         fi
2304         resources="deployment replicaset statefulset"
2305         scaled_all=1
2306         while [ $scaled_all -ne 0 ]; do
2307                 scaled_all=0
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}')
2311                         else
2312                                 result=$(kubectl $KUBECONF get $restype -n $namespace -o jsonpath='{.items[?(@.metadata.labels.'$labelname'=="'$labelid'")].metadata.name}')
2313                         fi
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
2318                                         count=1
2319                                         T_START=$SECONDS
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
2324                                                         sleep 0.5
2325                                                 else
2326                                                         count=0
2327                                                 fi
2328                                                 duration=$(($SECONDS-$T_START))
2329                                                 if [ $duration -gt 100 ]; then
2330                                                         #Forcring count 0, to avoid hanging for failed scaling
2331                                                         scaled_all=1
2332                                                         count=0
2333                                                 fi
2334                                         done
2335                                         echo -e "    Scaled $restype $resid in namespace $namespace with label $labelname=$labelid to 0, current count=$count $GREEN OK $EGREEN"
2336                                 done
2337                         fi
2338                 done
2339         done
2340 }
2341
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() {
2347         namespace=$1
2348         labelname=$2
2349         labelid=$3
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
2356                         ns_flag=""
2357                         ns_text=""
2358                 fi
2359                 if [ $restype == "clusterrolebindings" ]; then
2360                         ns_flag=""
2361                         ns_text=""
2362                 fi
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
2368                                         count=1
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
2373                                                         sleep 0.5
2374                                                 else
2375                                                         count=0
2376                                                 fi
2377                                         done
2378                                         echo -e "  Scaled $restype $resid $ns_text with label $labelname=$labelid to 0, current count=$count $GREEN OK $EGREEN"
2379                                 fi
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"
2384                                 else
2385                                         echo -e "  Deleted $restype $resid $ns_text with label $labelname=$labelid $GREEN Does not exist - OK $EGREEN"
2386                                 fi
2387                                 #fi
2388                         done
2389                 fi
2390         done
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
2396                                 ns_flag=""
2397                                 ns_text=""
2398                         fi
2399                         echo -ne "  Waiting for $restype $ns_text with label $labelname=$labelid to be deleted..."$SAMELINE
2400                         T_START=$SECONDS
2401                         result="dummy"
2402                         while [ ! -z "$result" ]; do
2403                                 sleep 0.5
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"
2410                                         result=""
2411                                 fi
2412                         done
2413                 done
2414         fi
2415 }
2416
2417 # Creates a namespace if it does not exists
2418 # args: <namespace>
2419 # (Not for test scripts)
2420 __kube_create_namespace() {
2421
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"
2429                         ((RES_CONF_FAIL++))
2430                         echo "  Message: $(<./tmp/kubeerr)"
2431                         return 1
2432                 else
2433                         kubectl $KUBECONF label ns $1 autotest=engine > /dev/null
2434                         echo -e " Creating namespace $1 $GREEN$BOLD OK $EBOLD$EGREEN"
2435                 fi
2436         else
2437                 echo -e " Creating namespace $1 $GREEN$BOLD Already exists, OK $EBOLD$EGREEN"
2438         fi
2439         return 0
2440 }
2441
2442 # Removes a namespace if it exists
2443 # args: <namespace>
2444 # (Not for test scripts)
2445 __kube_delete_namespace() {
2446
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"
2454                         ((RES_CONF_FAIL++))
2455                         echo "  Message: $(<./tmp/kubeerr)"
2456                         return 1
2457                 else
2458                         echo -e " Removing namespace $1 $GREEN$BOLD OK $EBOLD$EGREEN"
2459                 fi
2460         else
2461                 echo -e " Namespace $1 $GREEN$BOLD does not exist, OK $EBOLD$EGREEN"
2462         fi
2463         return 0
2464 }
2465
2466 # Removes and re-create a namespace
2467 # args: <namespace>
2468 # (Not for test scripts)
2469 clean_and_create_namespace() {
2470         __log_conf_start $@
2471
2472     if [ $# -ne 1 ]; then
2473                 __print_err "<namespace>" $@
2474                 return 1
2475         fi
2476         __kube_delete_namespace $1
2477         if [ $? -ne 0 ]; then
2478                 return 1
2479         fi
2480         __kube_create_namespace $1
2481         if [ $? -ne 0 ]; then
2482                 return 1
2483         fi
2484 }
2485
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
2491         return $?
2492 }
2493
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
2499         return $?
2500 }
2501
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
2507                 ((RES_CONF_FAIL++))
2508         __print_err "need 2 args, <app-name> <namespace>" $@
2509                 exit 1
2510         fi
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
2515                                 echo $host
2516                                 return 0
2517                         fi
2518                 fi
2519                 sleep 0.5
2520         done
2521         ((RES_CONF_FAIL++))
2522         echo "host-not-found-fatal-error"
2523         return 1
2524 }
2525
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
2531                 ((RES_CONF_FAIL++))
2532         __print_err "need 3 args, <app-name> <namespace> <port-name>" $@
2533                 exit 1
2534         fi
2535
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
2540                                 echo $port
2541                                 return 0
2542                         fi
2543                 fi
2544                 sleep 0.5
2545         done
2546         ((RES_CONF_FAIL++))
2547         echo "0"
2548         return 1
2549 }
2550
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
2556                 ((RES_CONF_FAIL++))
2557         __print_err "need 3 args, <app-name> <namespace> <port-name>" $@
2558                 exit 1
2559         fi
2560
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
2565                                 echo $port
2566                                 return 0
2567                         fi
2568                 fi
2569                 sleep 0.5
2570         done
2571         ((RES_CONF_FAIL++))
2572         echo "0"
2573         return 1
2574 }
2575
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
2581         envsubst < $3 > $4
2582         kubectl $KUBECONF apply -f $4 1> /dev/null 2> ./tmp/kubeerr
2583         if [ $? -ne 0 ]; then
2584                 ((RES_CONF_FAIL++))
2585                 echo -e " Creating $1 $2 $RED Failed $ERED"
2586                 echo "  Message: $(<./tmp/kubeerr)"
2587                 return 1
2588         else
2589                 echo -e " Creating $1 $2 $GREEN OK $EGREEN"
2590         fi
2591 }
2592
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"
2603                 ((RES_CONF_FAIL++))
2604                 return 1
2605         fi
2606
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)"
2611                 ((RES_CONF_FAIL++))
2612                 return 1
2613         fi
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)"
2618                 ((RES_CONF_FAIL++))
2619                 return 1
2620         fi
2621         # Log the resulting map
2622         kubectl $KUBECONF get configmap $1 -n $2 -o yaml > $6
2623
2624         echo -e " Creating configmap $1 $GREEN OK $EGREEN"
2625         return 0
2626 }
2627
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))
2634
2635         while true; do
2636                 kube_cmd_result=$($@)
2637                 if [ $? -ne 0 ]; then
2638                         kube_cmd_result=""
2639                 fi
2640                 if [ $SECONDS -ge $TS_TMP ] || [ ! -z "$kube_cmd_result" ] ; then
2641                         echo $kube_cmd_result
2642                         return 0
2643                 fi
2644                 sleep 1
2645         done
2646 }
2647
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() {
2654
2655         #using env vars setup in pvccleaner_api_functions.sh
2656
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
2663
2664         envsubst < $input_yaml > $output_yaml
2665
2666         kubectl $KUBECONF delete -f $output_yaml 1> /dev/null 2> /dev/null   # Delete the previous terminated pod - if existing
2667
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"
2671                 return 1
2672         fi
2673
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
2678                         return 0
2679                 fi
2680         done
2681         return 1
2682 }
2683
2684 # This function scales or deletes all resources for app selected by the testcase.
2685 # args: -
2686 # (Not for test scripts)
2687 __clean_kube() {
2688         echo -e $BOLD"Initialize kube pods/statefulsets/replicaset to initial state"$EBOLD
2689
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"
2704                         $function_pointer
2705                 else
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"
2710                                 $function_pointer
2711                         fi
2712                 fi
2713         done
2714
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"
2729                                 $function_pointer
2730                         fi
2731                 fi
2732         done
2733
2734         echo ""
2735 }
2736
2737 # Function stop and remove all containers (docker) and services/deployments etc(kube)
2738 # args: -
2739 # Function for test script
2740 clean_environment() {
2741         if [ $RUNMODE == "KUBE" ]; then
2742                 __clean_kube
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
2746                         echo ""
2747                 fi
2748         else
2749                 __clean_containers
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
2753                         echo ""
2754                 fi
2755         fi
2756 }
2757
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
2759 # args: -
2760 # (Function for test scripts)
2761 auto_clean_environment() {
2762         echo
2763         if [ "$AUTO_CLEAN" == "auto" ]; then
2764                 echo -e $BOLD"Initiating automatic cleaning of environment"$EBOLD
2765                 clean_environment
2766         fi
2767 }
2768
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)
2772 sleep_wait() {
2773
2774         echo -e $BOLD"INFO(${BASH_LINENO[0]}): "${FUNCNAME[0]}"," $@ $EBOLD
2775         if [ $# -lt 1 ]; then
2776                 ((RES_CONF_FAIL++))
2777                 __print_err "need at least one arg, <sleep-time-in-sec> [any-text-to-printed]" $@
2778                 exit 1
2779         fi
2780         #echo "---- Sleep for " $1 " seconds ---- "$2
2781         start=$SECONDS
2782         duration=$((SECONDS-start))
2783         while [ $duration -lt $1 ]; do
2784                 echo -ne "  Slept for ${duration} seconds${SAMELINE}"
2785                 sleep 1
2786                 duration=$((SECONDS-start))
2787         done
2788         echo -ne "  Slept for ${duration} seconds${SAMELINE}"
2789         echo ""
2790 }
2791
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.
2794 __print_err() {
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
2798         fi
2799         ((RES_CONF_FAIL++))
2800         __check_stop_at_error
2801 }
2802
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
2809                 return 1
2810         fi
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
2816                         return 1
2817                 else
2818                         echo -e "$GREEN  Done$EGREEN"
2819                 fi
2820         else
2821                 echo -e " Docker network $DOCKER_SIM_NWNAME already exists$GREEN OK $EGREEN"
2822         fi
2823 }
2824
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() {
2830
2831         if [ $# -lt 5 ]; then
2832                 ((RES_CONF_FAIL++))
2833         __print_err "need 5 or more args, <docker-compose-dir> <docker-compose-file> <docker-compose-arg>|NODOCKERARGS <count> <app-name>+" $@
2834                 exit 1
2835         fi
2836
2837         __create_docker_network
2838
2839         curdir=$PWD
2840         cd $SIM_GROUP
2841         compose_dir=$1
2842         cd $1
2843         shift
2844         compose_file=$1
2845         if [ -z "$compose_file" ]; then
2846                 compose_file="docker-compose.yml"
2847         fi
2848         shift
2849         compose_args=$1
2850         shift
2851         appcount=$1
2852         shift
2853
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"
2858         else
2859                 docker_compose_cmd="docker compose"
2860         fi
2861
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
2866                         cat .dockererr
2867                         echo -e $RED"Stopping script...."$ERED
2868                         exit 1
2869                 fi
2870         else
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
2874                         cat .dockererr
2875                         echo -e $RED"Stopping script...."$ERED
2876                         exit 1
2877                 fi
2878         fi
2879
2880         cd $curdir
2881
2882         appindex=0
2883         while [ $appindex -lt $appcount ]; do
2884                 appname=$1
2885                 shift
2886                 app_started=0
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"
2890                                         app_started=1
2891                                         break
2892                                 else
2893                                         sleep $i
2894                         fi
2895                 done
2896                 if [ $app_started -eq 0 ]; then
2897                         ((RES_CONF_FAIL++))
2898                         echo ""
2899                         echo -e $RED" Container $BOLD${appname}$EBOLD could not be started"$ERED
2900                         echo -e $RED" Stopping script..."$ERED
2901                         exit 1
2902                 fi
2903                 let appindex=appindex+1
2904         done
2905         return 0
2906 }
2907
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() {
2912
2913         if [ $# -ne 2 ]; then
2914                 ((RES_CONF_FAIL++))
2915                 __print_err "need 2 args, <container-name>|<service-name> url" $@
2916                 return 1
2917         fi
2918
2919         if [ $RUNMODE == "KUBE" ]; then
2920                 ENTITY="service/set/deployment"
2921         else
2922                 ENTITY="container"
2923         fi
2924         appname=$1
2925         url=$2
2926         echo -ne " Container $BOLD${appname}$EBOLD starting${SAMELINE}"
2927
2928
2929         a1pmsst=false
2930         echo -ne " Waiting for ${ENTITY} ${appname} service status...${SAMELINE}"
2931         TSTART=$SECONDS
2932         loop_ctr=0
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"
2939                         fi
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"
2942                         a1pmsst=true
2943                         break
2944                 else
2945                         TS_TMP=$SECONDS
2946                         TS_OFFSET=$loop_ctr
2947                         if (( $TS_OFFSET > 5 )); then
2948                                 TS_OFFSET=5
2949                         fi
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}"
2952                                 sleep 1
2953                         done
2954                 fi
2955                 let loop_ctr=loop_ctr+1
2956         done
2957
2958         if [ "$a1pmsst" = "false"  ]; then
2959                 ((RES_CONF_FAIL++))
2960                 echo -e $RED" The ${ENTITY} ${appname} did not respond to service status on ${url} in $(($SECONDS-$TSTART)) seconds"$ERED
2961                 return 1
2962         fi
2963
2964         echo ""
2965         return 0
2966 }
2967
2968
2969 #################
2970 ### Log functions
2971 #################
2972
2973 __check_container_logs() {
2974
2975         dispname=$1
2976         appname=$2
2977         logpath=$3
2978         warning=$4
2979         error=$5
2980
2981         echo -e $BOLD"Checking $dispname container $appname log ($logpath) for WARNINGs and ERRORs"$EBOLD
2982
2983         if [ $RUNMODE == "KUBE" ]; then
2984                 echo -e $YELLOW" Internal log for $dispname not checked in kube"$EYELLOW
2985                 return
2986         fi
2987
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"
2992                 return
2993         fi
2994         foundentries="$(docker exec -t $tmp grep $warning $logpath | wc -l)"
2995         if [ $? -ne  0 ];then
2996                 echo "  Problem to search $appname log $logpath"
2997         else
2998                 if [ $foundentries -eq 0 ]; then
2999                         echo "  No WARN entries found in $appname log $logpath"
3000                 else
3001                         echo -e "  Found \033[1m"$foundentries"\033[0m WARN entries in $appname log $logpath"
3002                 fi
3003         fi
3004         foundentries="$(docker exec -t $tmp grep $error $logpath | wc -l)"
3005         if [ $? -ne  0 ];then
3006                 echo "  Problem to search $appname log $logpath"
3007         else
3008                 if [ $foundentries -eq 0 ]; then
3009                         echo "  No ERR entries found in $appname log $logpath"
3010                 else
3011                         echo -e $RED"  Found \033[1m"$foundentries"\033[0m"$RED" ERR entries in $appname log $logpath"$ERED
3012                 fi
3013         fi
3014         echo ""
3015 }
3016
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)
3021 store_logs() {
3022         if [ $# != 1 ]; then
3023                 ((RES_CONF_FAIL++))
3024         __print_err "need one arg, <file-prefix>" $@
3025                 exit 1
3026         fi
3027         echo -e $BOLD"Storing all docker/kube container logs and other test logs in $TESTLOGS/$ATC using prefix: "$1$EBOLD
3028
3029         docker stats --no-stream > $TESTLOGS/$ATC/$1_docker_stats.log 2>&1
3030
3031         docker ps -a  > $TESTLOGS/$ATC/$1_docker_ps.log 2>&1
3032
3033         cp .httplog_${ATC}.txt $TESTLOGS/$ATC/$1_httplog_${ATC}.txt 2>&1
3034
3035         if [ $RUNMODE == "DOCKER" ]; then
3036
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
3049                         fi
3050                 done
3051         fi
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
3058                         done
3059                 done
3060         fi
3061         echo ""
3062 }
3063
3064 ###############
3065 ## Generic curl
3066 ###############
3067 # Generic curl function, assumes all 200-codes are ok
3068 # Used proxy, set
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
3072 __do_curl() {
3073         echo ${FUNCNAME[1]} "line: "${BASH_LINENO[1]} >> $HTTPLOG
3074         proxyflag=""
3075         if [ ! -z "$KUBE_PROXY_PATH" ]; then
3076                 if [ $KUBE_PROXY_HTTPX == "http" ]; then
3077                         proxyflag=" --proxy $KUBE_PROXY_PATH"
3078                 else
3079                         proxyflag=" --proxy-insecure --proxy $KUBE_PROXY_PATH"
3080                 fi
3081         fi
3082
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")
3088                 retcode=$?
3089         else
3090                 curlString="curl -skw %{http_code} $proxyflag $@"
3091                 echo " CMD: $curlString" >> $HTTPLOG
3092                 res=$($curlString)
3093                 retcode=$?
3094         fi
3095         echo " RESP: $res" >> $HTTPLOG
3096         echo " RETCODE: $retcode" >> $HTTPLOG
3097         if [ $retcode -ne 0 ]; then
3098                 echo "<no-response-from-server>"
3099                 return 1
3100         fi
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>"
3105                         return 1
3106                 else
3107                         return 0
3108                 fi
3109         else
3110                 if [ $http_code -lt 200 ] || [ $http_code -gt 299 ]; then
3111                         echo "<not found, resp:${http_code}>"
3112                         return 1
3113                 fi
3114                 if [ $# -eq 2 ]; then
3115                         echo "${res:0:${#res}-3}" | xargs
3116                 else
3117                         echo "${res:0:${#res}-3}"
3118                 fi
3119
3120                 return 0
3121         fi
3122
3123 }
3124
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
3134         res=$($curlString)
3135         retcode=$?
3136         echo " RESP: $res" >> $HTTPLOG
3137         echo " RETCODE: $retcode" >> $HTTPLOG
3138         if [ $retcode -ne 0 ]; then
3139                 echo "<no-response-from-server>"
3140                 return 1
3141         fi
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>"
3146                         return 1
3147                 else
3148                         return 0
3149                 fi
3150         else
3151                 if [ $http_code -lt 200 ] || [ $http_code -gt 299 ]; then
3152                         echo "<not found, resp:${http_code}>"
3153                         return 1
3154                 fi
3155                 if [ $# -eq 2 ]; then
3156                         echo "${res:0:${#res}-3}" | xargs
3157                 else
3158                         echo "${res:0:${#res}-3}"
3159                 fi
3160
3161                 return 0
3162         fi
3163 }
3164
3165 #######################################
3166 ### Basic helper function for test cases
3167 #######################################
3168
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.
3176
3177 __var_test() {
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
3183                 fi
3184
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
3187
3188                 ((RES_TEST++))
3189                 ((TEST_SEQUENCE_NR++))
3190                 start=$SECONDS
3191                 ctr=0
3192                 for (( ; ; )); do
3193                         if [ $checkjsonarraycount -eq 0 ]; then
3194                                 result="$(__do_curl $2$3)"
3195                                 retcode=$?
3196                                 result=${result//[[:blank:]]/} #Strip blanks
3197                         else
3198                                 path=${3:5}
3199                                 result="$(__do_curl $2$path)"
3200                                 retcode=$?
3201                                 echo "$result" > ./tmp/.tmp.curl.json
3202                                 result=$(python3 ../common/count_json_elements.py "./tmp/.tmp.curl.json")
3203                         fi
3204                         duration=$((SECONDS-start))
3205                         echo -ne " Result=${result} after ${duration} seconds${SAMELINE}"
3206                         let ctr=ctr+1
3207                         if [ $retcode -ne 0 ]; then
3208                                 if [ $duration -gt $6 ]; then
3209                                         ((RES_FAIL++))
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
3213                                         return
3214                                 fi
3215                         elif [ "$4" == "=" ] && [ "$result" -eq $5 ]; then
3216                                 ((RES_PASS++))
3217                                 echo -e " Result=${result} after ${duration} seconds${SAMELINE}"
3218                                 echo -e $GREEN" PASS${EGREEN} - Result=${result} after ${duration} seconds"
3219                                 __print_current_stats
3220                                 return
3221                         elif [ "$4" == ">" ] && [ "$result" -gt $5 ]; then
3222                                 ((RES_PASS++))
3223                                 echo -e " Result=${result} after ${duration} seconds${SAMELINE}"
3224                                 echo -e $GREEN" PASS${EGREEN} - Result=${result} after ${duration} seconds"
3225                                 __print_current_stats
3226                                 return
3227                         elif [ "$4" == "<" ] && [ "$result" -lt $5 ]; then
3228                                 ((RES_PASS++))
3229                                 echo -e " Result=${result} after ${duration} seconds${SAMELINE}"
3230                                 echo -e $GREEN" PASS${EGREEN} - Result=${result} after ${duration} seconds"
3231                                 __print_current_stats
3232                                 return
3233                         elif [ "$4" == ">=" ] && [ "$result" -ge $5 ]; then
3234                                 ((RES_PASS++))
3235                                 echo -e " Result=${result} after ${duration} seconds${SAMELINE}"
3236                                 echo -e $GREEN" PASS${EGREEN} - Result=${result} after ${duration} seconds"
3237                                 __print_current_stats
3238                                 return
3239                         elif [ "$4" == "contain_str" ] && [[ $result =~ $5 ]]; then
3240                                 ((RES_PASS++))
3241                                 echo -e " Result=${result} after ${duration} seconds${SAMELINE}"
3242                                 echo -e $GREEN" PASS${EGREEN} - Result=${result} after ${duration} seconds"
3243                                 __print_current_stats
3244                                 return
3245                         else
3246                                 if [ $duration -gt $6 ]; then
3247                                         ((RES_FAIL++))
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
3251                                         return
3252                                 fi
3253                         fi
3254                         sleep 1
3255                 done
3256         elif [ $# -eq 5 ]; then
3257                 if [[ $3 == "json:"* ]]; then
3258                         checkjsonarraycount=1
3259                 fi
3260
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
3263                 ((RES_TEST++))
3264                 ((TEST_SEQUENCE_NR++))
3265                 if [ $checkjsonarraycount -eq 0 ]; then
3266                         result="$(__do_curl $2$3)"
3267                         retcode=$?
3268                         result=${result//[[:blank:]]/} #Strip blanks
3269                 else
3270                         path=${3:5}
3271                         result="$(__do_curl $2$path)"
3272                         retcode=$?
3273                         echo "$result" > ./tmp/.tmp.curl.json
3274                         result=$(python3 ../common/count_json_elements.py "./tmp/.tmp.curl.json")
3275                 fi
3276                 if [ $retcode -ne 0 ]; then
3277                         ((RES_FAIL++))
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
3282                         ((RES_PASS++))
3283                         echo -e $GREEN" PASS${EGREEN} - Result=${result}"
3284                         __print_current_stats
3285                 elif [ "$4" == ">" ] && [ "$result" -gt $5 ]; then
3286                         ((RES_PASS++))
3287                         echo -e $GREEN" PASS${EGREEN} - Result=${result}"
3288                         __print_current_stats
3289                 elif [ "$4" == "<" ] && [ "$result" -lt $5 ]; then
3290                         ((RES_PASS++))
3291                         echo -e $GREEN" PASS${EGREEN} - Result=${result}"
3292                         __print_current_stats
3293                 elif [ "$4" == ">=" ] && [ "$result" -ge $5 ]; then
3294                         ((RES_PASS++))
3295                         echo -e $GREEN" PASS${EGREEN} - Result=${result}"
3296                         __print_current_stats
3297                 elif [ "$4" == "contain_str" ] && [[ $result =~ $5 ]]; then
3298                         ((RES_PASS++))
3299                         echo -e $GREEN" PASS${EGREEN} - Result=${result}"
3300                         __print_current_stats
3301                 else
3302                         ((RES_FAIL++))
3303                         echo -e $RED" FAIL${ERED} - ${3} ${4} ${5} not reached, result = ${result}"
3304                         __print_current_stats
3305                         __check_stop_at_error
3306                 fi
3307         else
3308                 echo "Wrong args to __var_test, needs five or six args: <simulator-name> <host> <variable-name> <condition-operator> <target-value> [ <timeout> ]"
3309                 echo "Got:" $@
3310                 exit 1
3311         fi
3312 }