Function test updates
[nonrtric.git] / test / common / testcase_common.sh
1 #!/bin/bash
2
3 #  ============LICENSE_START===============================================
4 #  Copyright (C) 2020-22023 Nordix Foundation. All rights reserved.
5 #  ========================================================================
6 #  Licensed under the Apache License, Version 2.0 (the "License");
7 #  you may not use this file except in compliance with the License.
8 #  You may obtain a copy of the License at
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>+] [--use-external-image <app-nam>+] [--image-repo <repo-address>]"
30         echo "      [--repo-policy local|remote] [--cluster-timeout <timeout-in seconds>] [--print-stats]"
31         echo "      [--override <override-environment-filename>] [--pre-clean] [--gen-stats] [--delete-namespaces]"
32         echo "      [--delete-containers] [--endpoint-stats] [--kubeconfig <config-file>] [--host-path-dir <local-host-dir>]"
33         echo "      [--kubecontext <context-name>] [--docker-host <docker-host-url>] [--docker-proxy <host-or-ip>]"
34 }
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 "--use-external-image   - The script will use images from the external (non oran/onap) repo for the supplied apps, space separated list of app short names"
59         echo "--image-repo          -  Url to optional image repo. Only locally built images will be re-tagged and pushed to this repo"
60         echo "--repo-policy         -  Policy controlling which images to re-tag and push if param --image-repo is set. Default is 'local'"
61         echo "--cluster-timeout     -  Optional timeout for cluster where it takes time to obtain external ip/host-name. Timeout in seconds. "
62         echo "--print-stats         -  Print current test stats after each test."
63         echo "--override <file>     -  Override setting from the file supplied by --env-file"
64         echo "--pre-clean           -  Will clean kube resouces when running docker and vice versa"
65         echo "--gen-stats           -  Collect container/pod runtime statistics"
66         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."
67         echo "--delete-containers   -  Delete docker containers before starting tests - but only those created by the test scripts. Docker mode only."
68         echo "--endpoint-stats      -  Collect endpoint statistics"
69         echo "--kubeconfig          -  Configure kubectl to use cluster specific cluster config file"
70         echo "--host-path-dir       -  (Base-)path on local-hostmounted to all VMs (nodes), for hostpath volumes in kube"
71         echo "--kubecontext         -  Configure kubectl to use a certain context, e.g 'minikube'"
72         echo "--docker-host         -  Configure docker to use docker in e.g. a VM"
73         echo "--docker-proxy        -  Configure ip/host to docker when docker is running in a VM"
74         echo ""
75         echo "List of app short names supported: "$APP_SHORT_NAMES
76         exit 0
77 fi
78
79 AUTOTEST_HOME=$PWD
80 # Create a test case id, ATC (Auto Test Case), from the name of the test case script.
81 # FTC1.sh -> ATC == FTC1
82 ATC=$(basename "${BASH_SOURCE[$i+1]}" .sh)
83
84 #Create result file (containing '1' for error) for this test case
85 #Will be replaced with a file containing '0' if all test cases pass
86 echo "1" > "$PWD/.result$ATC.txt"
87
88 #Formatting for 'echo' cmd
89 BOLD="\033[1m"
90 EBOLD="\033[0m"
91 RED="\033[31m\033[1m"
92 ERED="\033[0m"
93 GREEN="\033[32m\033[1m"
94 EGREEN="\033[0m"
95 YELLOW="\033[33m\033[1m"
96 EYELLOW="\033[0m"
97 SAMELINE="\033[0K\r"
98
99 # Just resetting any previous echo formatting...
100 echo -ne $EBOLD
101
102 # default test environment variables
103 TEST_ENV_VAR_FILE=""
104 #Override env file, will be added on top of the above file
105 TEST_ENV_VAR_FILE_OVERRIDE=""
106
107 echo "Test case started as: ${BASH_SOURCE[$i+1]} "$@
108
109 # Var to hold 'auto' in case containers shall be stopped when test case ends
110 AUTO_CLEAN=""
111
112 # Var to indicate pre clean, if flag --pre-clean is set the script will clean kube resouces when running docker and vice versa
113 PRE_CLEAN="0"
114
115 # Var to hold the app names to use local images for
116 USE_LOCAL_IMAGES=""
117
118 # Var to hold the app names to use remote snapshot images for
119 USE_SNAPSHOT_IMAGES=""
120
121 # Var to hold the app names to use remote staging images for
122 USE_STAGING_IMAGES=""
123
124 # Var to hold the app names to use remote release images for
125 USE_RELEASE_IMAGES=""
126
127 # Var to hold the app names to use external release images for
128 USE_EXTERNAL_IMAGES=""
129
130 # Use this var (STOP_AT_ERROR=1 in the test script) for debugging/trouble shooting to take all logs and exit at first FAIL test case
131 STOP_AT_ERROR=0
132
133 # The default value "DEV" indicate that development image tags (SNAPSHOT) and nexus repos (nexus port 10002) are used.
134 # The value "RELEASE" indicate that relase image tag and nexus repos (nexus port) are used
135 # Applies only to images defined in the test-env files with image names and tags defined as XXXX_RELEASE
136 IMAGE_CATEGORY="DEV"
137
138 #Var to indicate docker-compose version, V1 or V2
139 #V1 names replicated containers <proj-name>_<service-name>_<index>
140 #V2 names replicated containers <proj-name>-<service-name>-<index>
141 DOCKER_COMPOSE_VERSION="V1"
142
143 # Function to indent cmd output with one space
144 indent1() { sed 's/^/ /'; }
145
146 # Function to indent cmd output with two spaces
147 indent2() { sed 's/^/  /'; }
148
149 # Set a description string for the test case
150 if [ -z "$TC_ONELINE_DESCR" ]; then
151         TC_ONELINE_DESCR="<no-description>"
152         echo "No test case description found, TC_ONELINE_DESCR should be set on in the test script , using "$TC_ONELINE_DESCR
153 fi
154
155 # Counter for test suites
156 if [ -f .tmp_tcsuite_ctr ]; then
157         tmpval=$(< .tmp_tcsuite_ctr)
158         ((tmpval++))
159         echo $tmpval > .tmp_tcsuite_ctr
160 fi
161
162 # Create the logs dir if not already created in the current dir
163 if [ ! -d "logs" ]; then
164     mkdir logs
165 fi
166 TESTLOGS=$PWD/logs
167
168 # Create the tmp dir for temporary files that is not needed after the test
169 # hidden files for the test env is still stored in the current dir
170 # files in the ./tmp is moved to ./tmp/prev when a new test is started
171 if [ ! -d "tmp" ]; then
172     mkdir tmp
173         if [ $? -ne 0 ]; then
174                 echo "Cannot create dir for temp files, $PWD/tmp"
175                 echo "Exiting...."
176                 exit 1
177         fi
178 fi
179 curdir=$PWD
180 cd tmp
181 if [ $? -ne 0 ]; then
182         echo "Cannot cd to $PWD/tmp"
183         echo "Exiting...."
184         exit 1
185 fi
186
187 TESTENV_TEMP_FILES=$PWD
188
189 if [ ! -d "prev" ]; then
190     mkdir prev
191         if [ $? -ne 0 ]; then
192                 echo "Cannot create dir for previous temp files, $PWD/prev"
193                 echo "Exiting...."
194                 exit 1
195         fi
196 fi
197
198 TMPFILES=$(ls -A  | grep -vw prev)
199 if [ ! -z "$TMPFILES" ]; then
200         cp -r $TMPFILES prev   #Move all temp files to prev dir
201         if [ $? -ne 0 ]; then
202                 echo "Cannot move temp files in $PWD to previous temp files in, $PWD/prev"
203                 echo "Exiting...."
204                 exit 1
205         fi
206         if [ $(pwd | xargs basename) == "tmp" ]; then    #Check that current dir is tmp...for safety
207
208                 rm -rf $TMPFILES # Remove all temp files
209         fi
210 fi
211
212 cd $curdir
213 if [ $? -ne 0 ]; then
214         echo "Cannot cd to $curdir"
215         echo "Exiting...."
216         exit 1
217 fi
218
219
220 # Create a http message log for this testcase
221 HTTPLOG=$PWD"/.httplog_"$ATC".txt"
222 echo "" > $HTTPLOG
223
224 # Create a log dir for the test case
225 mkdir -p $TESTLOGS/$ATC
226
227 # Save create for current logs
228 mkdir -p $TESTLOGS/$ATC/previous
229
230 rm $TESTLOGS/$ATC/previous/*.log &> /dev/null
231 rm $TESTLOGS/$ATC/previous/*.txt &> /dev/null
232 rm $TESTLOGS/$ATC/previous/*.json &> /dev/null
233
234 mv  $TESTLOGS/$ATC/*.log $TESTLOGS/$ATC/previous &> /dev/null
235 mv  $TESTLOGS/$ATC/*.txt $TESTLOGS/$ATC/previous &> /dev/null
236 mv  $TESTLOGS/$ATC/*.txt $TESTLOGS/$ATC/previous &> /dev/null
237
238 # Clear the log dir for the test case
239 rm $TESTLOGS/$ATC/*.log &> /dev/null
240 rm $TESTLOGS/$ATC/*.txt &> /dev/null
241 rm $TESTLOGS/$ATC/*.json &> /dev/null
242
243 #Create result file in the log dir
244 echo "1" > "$TESTLOGS/$ATC/.result$ATC.txt"
245
246 # Log all output from the test case to a TC log
247 TCLOG=$TESTLOGS/$ATC/TC.log
248 exec &>  >(tee ${TCLOG})
249
250 echo $(date) > $TESTLOGS/$ATC/endpoint_tc_start.log
251 echo "$TC_ONELINE_DESCR" > $TESTLOGS/$ATC/endpoint_tc_slogan.log
252 echo "Test failed" > $TESTLOGS/$ATC/endpoint_tc_end.log  # Will be overritten if test is ok
253
254 #Variables for counting tests as well as passed and failed tests
255 RES_TEST=0
256 RES_PASS=0
257 RES_FAIL=0
258 RES_CONF_FAIL=0
259 RES_DEVIATION=0
260
261 #Var to control if current stats shall be printed
262 PRINT_CURRENT_STATS=0
263
264 #Var to control if container/pod runtim statistics shall be collected
265 COLLECT_RUNTIME_STATS=0
266 COLLECT_RUNTIME_STATS_PID=0
267
268 #Var to control if endpoint statistics shall be collected
269 COLLECT_ENDPOINT_STATS=0
270
271 #Var to control if namespaces shall be delete before test setup
272 DELETE_KUBE_NAMESPACES=0
273
274 #Var to control if containers shall be delete before test setup
275 DELETE_CONTAINERS=0
276
277 #Var to configure kubectl from a config file or context
278 KUBECONF=""
279
280 #Localhost, may be set to another host/ip by cmd parameter
281 LOCALHOST_NAME="localhost"
282
283 #Reseting vars related to token/keys used by kubeproxy when istio is enabled
284 #The vars are populated if istio is used in the testcase
285 KUBE_PROXY_CURL_JWT=""
286 KUBE_PROXY_ISTIO_JWKS_KEYS=""
287
288 #Var pointing to dir mounted to each kubernetes node (master and workers)
289 #Persistent volumes using "hostpath" are allocated beneath the point.
290 #Typically it is a dir on local host mounted to each VM running the master and worker.
291 #So the intention is make this dir available so the PODs can be restarted on any
292 #node and still access the persistent data
293 #If not set from cmd line, the path is defaults to "/tmp"
294 HOST_PATH_BASE_DIR=""
295
296 #File to keep deviation messages
297 DEVIATION_FILE=".tmp_deviations"
298 rm $DEVIATION_FILE &> /dev/null
299
300 # Trap "command not found" and make the script fail
301 trap_fnc() {
302
303         if [ $? -eq 127 ]; then
304                 echo -e $RED"Function not found, setting script to FAIL"$ERED
305                 ((RES_CONF_FAIL++))
306                 __print_current_stats
307         fi
308 }
309 trap trap_fnc ERR
310
311 # Trap to kill subprocess for stats collection (if running)
312 trap_fnc2() {
313         if [ $COLLECT_RUNTIME_STATS_PID -ne 0 ]; then
314                 kill $COLLECT_RUNTIME_STATS_PID
315         fi
316 }
317 trap trap_fnc2 EXIT
318
319 # Counter for tests
320 TEST_SEQUENCE_NR=1
321
322 # Function to log the start of a test case
323 __log_test_start() {
324         TIMESTAMP=$(date "+%Y-%m-%d %H:%M:%S")
325         echo -e $BOLD"TEST $TEST_SEQUENCE_NR - (${BASH_LINENO[1]}) - ${TIMESTAMP}: ${FUNCNAME[1]}" $@ $EBOLD
326     echo "TEST $TEST_SEQUENCE_NR - (${BASH_LINENO[1]}) - ${TIMESTAMP}: ${FUNCNAME[1]}" $@ >> $HTTPLOG
327         ((RES_TEST++))
328         ((TEST_SEQUENCE_NR++))
329 }
330
331 # Function to print current statistics
332 __print_current_stats() {
333         if [ $PRINT_CURRENT_STATS -ne 0 ]; then
334                 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"
335         fi
336 }
337
338 # General function to log a failed test case
339 __log_test_fail_general() {
340         echo -e $RED" FAIL."$1 $ERED
341         ((RES_FAIL++))
342         __print_current_stats
343         __check_stop_at_error
344 }
345
346 # Function to log a test case failed due to incorrect response code
347 __log_test_fail_status_code() {
348         echo -e $RED" FAIL. Exepected status "$1", got "$2 $3 $ERED
349         ((RES_FAIL++))
350         __print_current_stats
351         __check_stop_at_error
352 }
353
354 # Function to log a test case failed due to incorrect response body
355 __log_test_fail_body() {
356         echo -e $RED" FAIL, returned body not correct"$ERED
357         ((RES_FAIL++))
358         __print_current_stats
359         __check_stop_at_error
360 }
361
362 # Function to log a test case that is not supported
363 __log_test_fail_not_supported() {
364         echo -e $RED" FAIL, function not supported"$ERED
365         ((RES_FAIL++))
366         __print_current_stats
367         __check_stop_at_error
368 }
369
370 # Function to log a test case that is not supported but will not fail
371 __log_test_info_not_supported() {
372         echo -e $YELLOW" INFO, function not supported"$YELLOW
373         __print_current_stats
374 }
375
376 # General function to log a passed test case
377 __log_test_pass() {
378         if [ $# -gt 0 ]; then
379                 echo $@
380         fi
381         ((RES_PASS++))
382         echo -e $GREEN" PASS"$EGREEN
383         __print_current_stats
384 }
385
386 #Counter for configurations
387 CONF_SEQUENCE_NR=1
388
389 # Function to log the start of a configuration setup
390 __log_conf_start() {
391         TIMESTAMP=$(date "+%Y-%m-%d %H:%M:%S")
392         echo -e $BOLD"CONF $CONF_SEQUENCE_NR - (${BASH_LINENO[1]}) - ${TIMESTAMP}: "${FUNCNAME[1]} $@ $EBOLD
393         echo "CONF $CONF_SEQUENCE_NR - (${BASH_LINENO[1]}) - ${TIMESTAMP}: "${FUNCNAME[1]} $@  >> $HTTPLOG
394         ((CONF_SEQUENCE_NR++))
395 }
396
397 # Function to log a failed configuration setup
398 __log_conf_fail_general() {
399         echo -e $RED" FAIL."$1 $ERED
400         ((RES_CONF_FAIL++))
401         __print_current_stats
402         __check_stop_at_error
403 }
404
405 # Function to log a failed configuration setup due to incorrect response code
406 __log_conf_fail_status_code() {
407         echo -e $RED" FAIL. Exepected status "$1", got "$2 $3 $ERED
408         ((RES_CONF_FAIL++))
409         __print_current_stats
410         __check_stop_at_error
411 }
412
413 # Function to log a failed configuration setup due to incorrect response body
414 __log_conf_fail_body() {
415         echo -e $RED" FAIL, returned body not correct"$ERED
416         ((RES_CONF_FAIL++))
417         __print_current_stats
418         __check_stop_at_error
419 }
420
421 # Function to log a configuration that is not supported
422 __log_conf_fail_not_supported() {
423         echo -e $RED" FAIL, function not supported"$ERED$@
424         ((RES_CONF_FAIL++))
425         __print_current_stats
426         __check_stop_at_error
427 }
428
429 # Function to log a passed configuration setup
430 __log_conf_ok() {
431         if [ $# -gt 0 ]; then
432                 echo $@
433         fi
434         echo -e $GREEN" OK"$EGREEN
435         __print_current_stats
436 }
437
438 # Function to collect stats on endpoints
439 # args: <app-id> <end-point-no> <http-operation> <end-point-url> <http-status> [<count>]
440 __collect_endpoint_stats() {
441         if [ $COLLECT_ENDPOINT_STATS -eq 0 ]; then
442                 return
443         fi
444         ENDPOINT_COUNT=1
445         if [ $# -gt 5 ]; then
446                 ENDPOINT_COUNT=$6
447         fi
448         ENDPOINT_STAT_FILE=$TESTLOGS/$ATC/endpoint_$ATC_$1_$2".log"
449         ENDPOINT_POS=0
450         ENDPOINT_NEG=0
451         if [ -f $ENDPOINT_STAT_FILE ]; then
452                 ENDPOINT_VAL=$(< $ENDPOINT_STAT_FILE)
453                 ENDPOINT_POS=$(echo $ENDPOINT_VAL | cut -f4 -d ' ' | cut -f1 -d '/')
454                 ENDPOINT_NEG=$(echo $ENDPOINT_VAL | cut -f5 -d ' ' | cut -f1 -d '/')
455         fi
456
457         if [ $5 -ge 200 ] && [ $5 -lt 300 ]; then
458                 let ENDPOINT_POS=ENDPOINT_POS+$ENDPOINT_COUNT
459         else
460                 let ENDPOINT_NEG=ENDPOINT_NEG+$ENDPOINT_COUNT
461         fi
462
463         printf '%-2s %-10s %-45s %-16s %-16s' "#" "$3" "$4" "$ENDPOINT_POS/$ENDPOINT_POS" "$ENDPOINT_NEG/$ENDPOINT_NEG" > $ENDPOINT_STAT_FILE
464 }
465
466 # Function to collect stats on endpoints
467 # args: <app-id> <image-info>
468 __collect_endpoint_stats_image_info() {
469         if [ $COLLECT_ENDPOINT_STATS -eq 0 ]; then
470                 return
471         fi
472         ENDPOINT_STAT_FILE=$TESTLOGS/$ATC/imageinfo_$ATC_$1".log"
473         echo $A1PMS_IMAGE > $ENDPOINT_STAT_FILE
474 }
475
476 #Var for measuring execution time
477 TCTEST_START=$SECONDS
478
479 #Vars to hold the start time and timer text for a custom timer
480 TC_TIMER_STARTTIME=""
481 TC_TIMER_TIMER_TEXT=""
482 TC_TIMER_CURRENT_FAILS="" # Then numer of failed test when timer starts.
483                           # Compared with the current number of fails at timer stop
484                                                   # to judge the measurement reliability
485
486 #File to save timer measurement results
487 TIMER_MEASUREMENTS=".timer_measurement.txt"
488 echo -e "Activity \t Duration \t Info" > $TIMER_MEASUREMENTS
489
490 # If this is set, some images (controlled by the parameter repo-policy) will be re-tagged and pushed to this repo before any
491 IMAGE_REPO_ADR=""
492 IMAGE_REPO_POLICY="local"
493 CLUSTER_TIME_OUT=0
494
495 echo "-------------------------------------------------------------------------------------------------"
496 echo "-----------------------------------      Test case: "$ATC
497 echo "-----------------------------------      Started:   "$(date)
498 echo "-------------------------------------------------------------------------------------------------"
499 echo "-- Description: "$TC_ONELINE_DESCR
500 echo "-------------------------------------------------------------------------------------------------"
501 echo "-----------------------------------      Test case setup      -----------------------------------"
502
503 echo "Setting AUTOTEST_HOME="$AUTOTEST_HOME
504 START_ARG=$1
505 paramerror=0
506 paramerror_str=""
507 if [ $# -lt 1 ]; then
508         paramerror=1
509 fi
510 if [ $paramerror -eq 0 ]; then
511         if [ "$1" != "remote" ] && [ "$1" != "remote-remove" ]; then
512                 paramerror=1
513                 if [ -z "$paramerror_str" ]; then
514                         paramerror_str="First arg shall be 'remote' or 'remote-remove'"
515                 fi
516         else
517                 shift;
518         fi
519 fi
520 if [ $paramerror -eq 0 ]; then
521         if [ "$1" != "docker" ] && [ "$1" != "kube" ]; then
522                 paramerror=1
523                 if [ -z "$paramerror_str" ]; then
524                         paramerror_str="Second arg shall be 'docker' or 'kube'"
525                 fi
526         else
527                 if [ $1 == "docker" ]; then
528                         RUNMODE="DOCKER"
529                         echo "Setting RUNMODE=DOCKER"
530                 fi
531                 if [ $1 == "kube" ]; then
532                         RUNMODE="KUBE"
533                         echo "Setting RUNMODE=KUBE"
534                 fi
535                 shift;
536         fi
537 fi
538 foundparm=0
539 while [ $paramerror -eq 0 ] && [ $foundparm -eq 0 ]; do
540         foundparm=1
541         if [ $paramerror -eq 0 ]; then
542                 if [ "$1" == "release" ]; then
543                         IMAGE_CATEGORY="RELEASE"
544                         echo "Option set - Release image tags used for applicable images "
545                         shift;
546                         foundparm=0
547                 fi
548         fi
549         if [ $paramerror -eq 0 ]; then
550                 if [ "$1" == "auto-clean" ]; then
551                         AUTO_CLEAN="auto"
552                         echo "Option set - Auto clean at end of test script"
553                         shift;
554                         foundparm=0
555                 fi
556         fi
557         if [ $paramerror -eq 0 ]; then
558                 if [ "$1" == "--stop-at-error" ]; then
559                         STOP_AT_ERROR=1
560                         echo "Option set - Stop at first error"
561                         shift;
562                         foundparm=0
563                 fi
564         fi
565         if [ $paramerror -eq 0 ]; then
566                 if [ "$1" == "--ricsim-prefix" ]; then
567                         shift;
568                         TMP_RIC_SIM_PREFIX=$1  #RIC_SIM_PREFIX need to be updated after sourcing of the env file
569                         if [ -z "$1" ]; then
570                                 paramerror=1
571                                 if [ -z "$paramerror_str" ]; then
572                                         paramerror_str="No prefix found for flag: '--ricsim-prefix'"
573                                 fi
574                         else
575                                 echo "Option set - Overriding RIC_SIM_PREFIX with: "$1
576                                 shift;
577                                 foundparm=0
578                         fi
579                 fi
580         fi
581         if [ $paramerror -eq 0 ]; then
582                 if [ "$1" == "--env-file" ]; then
583                         shift;
584                         TEST_ENV_VAR_FILE=$1
585                         if [ -z "$1" ]; then
586                                 paramerror=1
587                                 if [ -z "$paramerror_str" ]; then
588                                         paramerror_str="No env file found for flag: '--env-file'"
589                                 fi
590                         else
591                                 echo "Option set - Reading test env from: "$1
592                                 shift;
593                                 foundparm=0
594                         fi
595                 fi
596         fi
597         if [ $paramerror -eq 0 ]; then
598                 if [ "$1" == "--use-local-image" ]; then
599                         USE_LOCAL_IMAGES=""
600                         shift
601                         while [ $# -gt 0 ] && [[ "$1" != "--"* ]]; do
602                                 USE_LOCAL_IMAGES=$USE_LOCAL_IMAGES" "$1
603                                 if [[ "$AVAILABLE_IMAGES_OVERRIDE" != *"$1"* ]]; then
604                                         paramerror=1
605                                         if [ -z "$paramerror_str" ]; then
606                                                 paramerror_str="App name $1 is not available for local override for flag: '--use-local-image'"
607                                         fi
608                                 fi
609                                 shift;
610                         done
611                         foundparm=0
612                         if [ -z "$USE_LOCAL_IMAGES" ]; then
613                                 paramerror=1
614                                 if [ -z "$paramerror_str" ]; then
615                                         paramerror_str="No app name found for flag: '--use-local-image'"
616                                 fi
617                         else
618                                 echo "Option set - Overriding with local images for app(s):"$USE_LOCAL_IMAGES
619                         fi
620                 fi
621         fi
622         if [ $paramerror -eq 0 ]; then
623                 if [ "$1" == "--use-snapshot-image" ]; then
624                         USE_SNAPSHOT_IMAGES=""
625                         shift
626                         while [ $# -gt 0 ] && [[ "$1" != "--"* ]]; do
627                                 USE_SNAPSHOT_IMAGES=$USE_SNAPSHOT_IMAGES" "$1
628                                 if [[ "$AVAILABLE_IMAGES_OVERRIDE" != *"$1"* ]]; then
629                                         paramerror=1
630                                         if [ -z "$paramerror_str" ]; then
631                                                 paramerror_str="App name $1 is not available for snapshot override for flag: '--use-snapshot-image'"
632                                         fi
633                                 fi
634                                 shift;
635                         done
636                         foundparm=0
637                         if [ -z "$USE_SNAPSHOT_IMAGES" ]; then
638                                 paramerror=1
639                                 if [ -z "$paramerror_str" ]; then
640                                         paramerror_str="No app name found for flag: '--use-snapshot-image'"
641                                 fi
642                         else
643                                 echo "Option set - Overriding with snapshot images for app(s):"$USE_SNAPSHOT_IMAGES
644                         fi
645                 fi
646         fi
647         if [ $paramerror -eq 0 ]; then
648                 if [ "$1" == "--use-staging-image" ]; then
649                         USE_STAGING_IMAGES=""
650                         shift
651                         while [ $# -gt 0 ] && [[ "$1" != "--"* ]]; do
652                                 USE_STAGING_IMAGES=$USE_STAGING_IMAGES" "$1
653                                 if [[ "$AVAILABLE_IMAGES_OVERRIDE" != *"$1"* ]]; then
654                                         paramerror=1
655                                         if [ -z "$paramerror_str" ]; then
656                                                 paramerror_str="App name $1 is not available for staging override for flag: '--use-staging-image'"
657                                         fi
658                                 fi
659                                 shift;
660                         done
661                         foundparm=0
662                         if [ -z "$USE_STAGING_IMAGES" ]; then
663                                 paramerror=1
664                                 if [ -z "$paramerror_str" ]; then
665                                         paramerror_str="No app name found for flag: '--use-staging-image'"
666                                 fi
667                         else
668                                 echo "Option set - Overriding with staging images for app(s):"$USE_STAGING_IMAGES
669                         fi
670                 fi
671         fi
672         if [ $paramerror -eq 0 ]; then
673                 if [ "$1" == "--use-release-image" ]; then
674                         USE_RELEASE_IMAGES=""
675                         shift
676                         while [ $# -gt 0 ] && [[ "$1" != "--"* ]]; do
677                                 USE_RELEASE_IMAGES=$USE_RELEASE_IMAGES" "$1
678                                 if [[ "$AVAILABLE_IMAGES_OVERRIDE" != *"$1"* ]]; then
679                                         paramerror=1
680                                         if [ -z "$paramerror_str" ]; then
681                                                 paramerror_str="App name $1 is not available for release override for flag: '--use-release-image'"
682                                         fi
683                                 fi
684                                 shift;
685                         done
686                         foundparm=0
687                         if [ -z "$USE_RELEASE_IMAGES" ]; then
688                                 paramerror=1
689                                 if [ -z "$paramerror_str" ]; then
690                                         paramerror_str="No app name found for flag: '--use-release-image'"
691                                 fi
692                         else
693                                 echo "Option set - Overriding with release images for app(s):"$USE_RELEASE_IMAGES
694                         fi
695                 fi
696         fi
697         if [ $paramerror -eq 0 ]; then
698                 if [ "$1" == "--use-external-image" ]; then
699                         USE_EXTERNAL_IMAGES=""
700                         shift
701                         while [ $# -gt 0 ] && [[ "$1" != "--"* ]]; do
702                                 USE_EXTERNAL_IMAGES=$USE_EXTERNAL_IMAGES" "$1
703                                 if [[ "$AVAILABLE_IMAGES_OVERRIDE" != *"$1"* ]]; then
704                                         paramerror=1
705                                         if [ -z "$paramerror_str" ]; then
706                                                 paramerror_str="App name $1 is not available for release override for flag: '--use-external-image'"
707                                         fi
708                                 fi
709                                 shift;
710                         done
711                         foundparm=0
712                         if [ -z "$USE_EXTERNAL_IMAGES" ]; then
713                                 paramerror=1
714                                 if [ -z "$paramerror_str" ]; then
715                                         paramerror_str="No app name found for flag: '--use-use-external-image'"
716                                 fi
717                         else
718                                 echo "Option set - Overriding with external images for app(s):"$USE_EXTERNAL_IMAGES
719                         fi
720                 fi
721         fi
722         if [ $paramerror -eq 0 ]; then
723                 if [ "$1" == "--image-repo" ]; then
724                         shift;
725                         IMAGE_REPO_ADR=$1
726                         if [ -z "$1" ]; then
727                                 paramerror=1
728                                 if [ -z "$paramerror_str" ]; then
729                                         paramerror_str="No image repo url found for : '--image-repo'"
730                                 fi
731                         else
732                                 echo "Option set - Image repo url: "$1
733                                 shift;
734                                 foundparm=0
735                         fi
736                 fi
737         fi
738         if [ $paramerror -eq 0 ]; then
739                 if [ "$1" == "--repo-policy" ]; then
740                         shift;
741                         IMAGE_REPO_POLICY=$1
742                         if [ -z "$1" ]; then
743                                 paramerror=1
744                                 if [ -z "$paramerror_str" ]; then
745                                         paramerror_str="No policy found for : '--repo-policy'"
746                                 fi
747                         else
748                             if [ "$1" == "local" ] || [ "$1" == "remote" ]; then
749                                         echo "Option set - Image repo policy: "$1
750                                         shift;
751                                         foundparm=0
752                                 else
753                                         paramerror=1
754                                         if [ -z "$paramerror_str" ]; then
755                                                 paramerror_str="Repo policy shall be 'local' or 'remote'"
756                                         fi
757                                 fi
758                         fi
759                 fi
760         fi
761         if [ $paramerror -eq 0 ]; then
762                 if [ "$1" == "--cluster-timeout" ]; then
763                         shift;
764                         CLUSTER_TIME_OUT=$1
765                         if [ -z "$1" ]; then
766                                 paramerror=1
767                                 if [ -z "$paramerror_str" ]; then
768                                         paramerror_str="No timeout value found for : '--cluster-timeout'"
769                                 fi
770                         else
771                                 #Check if positive int
772                                 case ${CLUSTER_TIME_OUT#[+]} in
773                                         *[!0-9]* | '')
774                                                 paramerror=1
775                                                 if [ -z "$paramerror_str" ]; then
776                                                         paramerror_str="Value for '--cluster-timeout' not an int : "$CLUSTER_TIME_OUT
777                                                 fi
778                                                 ;;
779                                         * ) ;; # Ok
780                                 esac
781                                 echo "Option set - Cluster timeout: "$1
782                                 shift;
783                                 foundparm=0
784                         fi
785                 fi
786         fi
787         if [ $paramerror -eq 0 ]; then
788                 if [ "$1" == "--override" ]; then
789                         shift;
790                         TEST_ENV_VAR_FILE_OVERRIDE=$1
791                         if [ -z "$1" ]; then
792                                 paramerror=1
793                                 if [ -z "$paramerror_str" ]; then
794                                         paramerror_str="No env file found for flag: '--override'"
795                                 fi
796                         else
797                                 if [ ! -f $TEST_ENV_VAR_FILE_OVERRIDE ]; then
798                                         paramerror=1
799                                         if [ -z "$paramerror_str" ]; then
800                                                 paramerror_str="File for '--override' does not exist : "$TEST_ENV_VAR_FILE_OVERRIDE
801                                         fi
802                                 fi
803                                 echo "Option set - Override env from: "$1
804                                 shift;
805                                 foundparm=0
806                         fi
807                 fi
808         fi
809         if [ $paramerror -eq 0 ]; then
810                 if [ "$1" == "--pre-clean" ]; then
811                         PRE_CLEAN=1
812                         echo "Option set - Pre-clean of kube/docker resouces"
813                         shift;
814                         foundparm=0
815                 fi
816         fi
817         if [ $paramerror -eq 0 ]; then
818                 if [ "$1" == "--print-stats" ]; then
819                         PRINT_CURRENT_STATS=1
820                         echo "Option set - Print stats after every test-case and config"
821                         shift;
822                         foundparm=0
823                 fi
824         fi
825         if [ $paramerror -eq 0 ]; then
826                 if [ "$1" == "--gen-stats" ]; then
827                         COLLECT_RUNTIME_STATS=1
828                         echo "Option set - Collect runtime statistics"
829                         shift;
830                         foundparm=0
831                 fi
832         fi
833         if [ $paramerror -eq 0 ]; then
834                 if [ "$1" == "--delete-namespaces" ]; then
835                         if [ $RUNMODE == "DOCKER" ]; then
836                                 DELETE_KUBE_NAMESPACES=0
837                                 echo "Option ignored - Delete namespaces (ignored when running docker)"
838                         else
839                                 if [ -z "KUBE_PRESTARTED_IMAGES" ]; then
840                                         DELETE_KUBE_NAMESPACES=0
841                                         echo "Option ignored - Delete namespaces (ignored when using prestarted apps)"
842                                 else
843                                         DELETE_KUBE_NAMESPACES=1
844                                         echo "Option set - Delete namespaces"
845                                 fi
846                         fi
847                         shift;
848                         foundparm=0
849                 fi
850         fi
851         if [ $paramerror -eq 0 ]; then
852                 if [ "$1" == "--delete-containers" ]; then
853                         if [ $RUNMODE == "DOCKER" ]; then
854                                 DELETE_CONTAINERS=1
855                                 echo "Option set - Delete containers started by previous test(s)"
856                         else
857                                 echo "Option ignored - Delete containers (ignored when running kube)"
858                         fi
859                         shift;
860                         foundparm=0
861                 fi
862         fi
863         if [ $paramerror -eq 0 ]; then
864                 if [ "$1" == "--endpoint-stats" ]; then
865                         COLLECT_ENDPOINT_STATS=1
866                         echo "Option set - Collect endpoint statistics"
867                         shift;
868                         foundparm=0
869                 fi
870         fi
871         if [ $paramerror -eq 0 ]; then
872                 if [ "$1" == "--kubeconfig" ]; then
873                         shift;
874                         if [ -z "$1" ]; then
875                                 paramerror=1
876                                 if [ -z "$paramerror_str" ]; then
877                                         paramerror_str="No path found for : '--kubeconfig'"
878                                 fi
879                         else
880                             if [ -f  $1 ]; then
881                                         if [ ! -z "$KUBECONF" ]; then
882                                                 paramerror=1
883                                                 if [ -z "$paramerror_str" ]; then
884                                                         paramerror_str="Only one of --kubeconfig/--kubecontext can be set"
885                                                 fi
886                                         else
887                                                 KUBECONF="--kubeconfig $1"
888                                                 echo "Option set - Kubeconfig path: "$1
889                                                 shift;
890                                                 foundparm=0
891                                         fi
892                                 else
893                                         paramerror=1
894                                         if [ -z "$paramerror_str" ]; then
895                                                 paramerror_str="File $1 for --kubeconfig not found"
896                                         fi
897                                 fi
898                         fi
899                 fi
900         fi
901         if [ $paramerror -eq 0 ]; then
902                 if [ "$1" == "--kubecontext" ]; then
903                         shift;
904                         if [ -z "$1" ]; then
905                                 paramerror=1
906                                 if [ -z "$paramerror_str" ]; then
907                                         paramerror_str="No context-name found for : '--kubecontext'"
908                                 fi
909                         else
910                                 if [ ! -z "$KUBECONF" ]; then
911                                         paramerror=1
912                                         if [ -z "$paramerror_str" ]; then
913                                                 paramerror_str="Only one of --kubeconfig or --kubecontext can be set"
914                                         fi
915                                 else
916                                         KUBECONF="--context $1"
917                                         echo "Option set - Kubecontext name: "$1
918                                         shift;
919                                         foundparm=0
920                                 fi
921                         fi
922                 fi
923         fi
924         if [ $paramerror -eq 0 ]; then
925                 if [ "$1" == "--host-path-dir" ]; then
926                         shift;
927                         if [ -z "$1" ]; then
928                                 paramerror=1
929                                 if [ -z "$paramerror_str" ]; then
930                                         paramerror_str="No path found for : '--host-path-dir'"
931                                 fi
932                         else
933                                 HOST_PATH_BASE_DIR=$1
934                                 echo "Option set - Host path for kube set to: "$1
935                                 shift
936                                 foundparm=0
937                         fi
938                 fi
939         fi
940         if [ $paramerror -eq 0 ]; then
941                 if [ "$1" == "--docker-host" ]; then
942                         shift;
943                         if [ -z "$1" ]; then
944                                 paramerror=1
945                                 if [ -z "$paramerror_str" ]; then
946                                         paramerror_str="No url found for : '--docker-host'"
947                                 fi
948                         else
949                                 export DOCKER_HOST="$1"
950                                 echo "Option set - DOCKER_HOST set to: "$1
951                                 shift
952                                 foundparm=0
953                         fi
954                 fi
955         fi
956         if [ $paramerror -eq 0 ]; then
957                 if [ "$1" == "--docker-host" ]; then
958                         shift;
959                         if [ -z "$1" ]; then
960                                 paramerror=1
961                                 if [ -z "$paramerror_str" ]; then
962                                         paramerror_str="No url found for : '--docker-host'"
963                                 fi
964                         else
965                                 export DOCKER_HOST="$1"
966                                 echo "Option set - DOCKER_HOST set to: "$1
967                                 shift
968                                 foundparm=0
969                         fi
970                 fi
971         fi
972         if [ $paramerror -eq 0 ]; then
973                 if [ "$1" == "--docker-proxy" ]; then
974                         shift;
975                         if [ -z "$1" ]; then
976                                 paramerror=1
977                                 if [ -z "$paramerror_str" ]; then
978                                         paramerror_str="No ip/host found for : '--docker-proxy'"
979                                 fi
980                         else
981                                 export LOCALHOST_NAME=$1
982                                 echo "Option set - docker proxy set to: "$1
983                                 shift
984                                 foundparm=0
985                         fi
986                 fi
987         fi
988 done
989 echo ""
990
991 #Still params left?
992 if [ $paramerror -eq 0 ] && [ $# -gt 0 ]; then
993         paramerror=1
994         if [ -z "$paramerror_str" ]; then
995                 paramerror_str="Unknown parameter(s): "$@
996         fi
997 fi
998
999 if [ $paramerror -eq 1 ]; then
1000         echo -e $RED"Incorrect arg list: "$paramerror_str$ERED
1001         __print_args
1002         exit 1
1003 fi
1004
1005 LOCALHOST_HTTP="http://$LOCALHOST_NAME"
1006 LOCALHOST_HTTPS="https://$LOCALHOST_NAME"
1007
1008 # sourcing the selected env variables for the test case
1009 if [ -f "$TEST_ENV_VAR_FILE" ]; then
1010         echo -e $BOLD"Sourcing env vars from: "$TEST_ENV_VAR_FILE$EBOLD
1011         . $TEST_ENV_VAR_FILE
1012         if [ ! -z "$TEST_ENV_VAR_FILE_OVERRIDE" ]; then
1013                 echo -e $BOLD"Sourcing override env vars from: "$TEST_ENV_VAR_FILE_OVERRIDE$EBOLD
1014                 . $TEST_ENV_VAR_FILE_OVERRIDE
1015         fi
1016
1017         if [ -z "$TEST_ENV_PROFILE" ] || [ -z "$SUPPORTED_PROFILES" ]; then
1018                 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
1019         else
1020                 found_profile=0
1021                 for prof in $SUPPORTED_PROFILES; do
1022                         if [ "$TEST_ENV_PROFILE" == "$prof" ]; then
1023                                 echo -e $GREEN"Test case supports the selected test env file"$EGREEN
1024                                 found_profile=1
1025                         fi
1026                 done
1027                 if [ $found_profile -ne 1 ]; then
1028                         echo -e $RED"Test case does not support the selected test env file"$ERED
1029                         echo "Profile: "$TEST_ENV_PROFILE"     Supported profiles: "$SUPPORTED_PROFILES
1030                         echo -e $RED"Exiting...."$ERED
1031                         exit 1
1032                 fi
1033         fi
1034 else
1035         echo -e $RED"Selected env var file does not exist: "$TEST_ENV_VAR_FILE$ERED
1036         echo " Select one of following env var file matching the intended target of the test"
1037         echo " Restart the test using the flag '--env-file <path-to-env-file>"
1038         ls $AUTOTEST_HOME/../common/test_env* | indent1
1039         exit 1
1040 fi
1041
1042 #This var need be preserved from the command line option, if set, when env var is sourced.
1043 if [ ! -z "$TMP_RIC_SIM_PREFIX" ]; then
1044         RIC_SIM_PREFIX=$TMP_RIC_SIM_PREFIX
1045 fi
1046
1047 if [ -z "$PROJECT_IMAGES_APP_NAMES" ]; then
1048         echo -e $RED"Var PROJECT_IMAGES_APP_NAMES must be defined in: "$TEST_ENV_VAR_FILE $ERED
1049         exit 1
1050 fi
1051
1052 if [[ $SUPPORTED_RUNMODES != *"$RUNMODE"* ]]; then
1053         echo -e $RED"This test script does not support RUNMODE $RUNMODE"$ERED
1054         echo "Supported RUNMODEs: "$SUPPORTED_RUNMODES
1055         exit 1
1056 fi
1057
1058 # Choose list of included apps depending on run-mode
1059 if [ $RUNMODE == "KUBE" ]; then
1060         INCLUDED_IMAGES=$KUBE_INCLUDED_IMAGES
1061 else
1062         INCLUDED_IMAGES=$DOCKER_INCLUDED_IMAGES
1063 fi
1064
1065 echo ""
1066 # auto adding system apps
1067 __added_apps=""
1068 echo -e $BOLD"Auto adding system apps"$EBOLD
1069 if [ $RUNMODE == "KUBE" ]; then
1070         INCLUDED_IMAGES=$INCLUDED_IMAGES" "$TESTENV_KUBE_SYSTEM_APPS
1071         TMP_APPS=$TESTENV_KUBE_SYSTEM_APPS
1072 else
1073         INCLUDED_IMAGES=$INCLUDED_IMAGES" "$TESTENV_DOCKER_SYSTEM_APPS
1074         TMP_APPS=$TESTENV_DOCKER_SYSTEM_APPS
1075 fi
1076 if [ ! -z "$TMP_APPS" ]; then
1077         for iapp in "$TMP_APPS"; do
1078                 file_pointer=$(echo $iapp | tr '[:upper:]' '[:lower:]')
1079                 file_pointer="../common/"$file_pointer"_api_functions.sh"
1080             padded_iapp=$iapp
1081                 while [ ${#padded_iapp} -lt 16 ]; do
1082                         padded_iapp=$padded_iapp" "
1083                 done
1084                 echo " Auto-adding system app   $padded_iapp  Sourcing $file_pointer"
1085                 . $file_pointer
1086                 if [ $? -ne 0 ]; then
1087                         echo " Include file $file_pointer contain errors. Exiting..."
1088                         exit 1
1089                 fi
1090                 __added_apps=" $iapp "$__added_apps
1091         done
1092 else
1093         echo " None"
1094 fi
1095
1096 if [ $RUNMODE == "KUBE" ]; then
1097         TMP_APPS=$INCLUDED_IMAGES" "$KUBE_PRESTARTED_IMAGES
1098 else
1099         TMP_APPS=$INCLUDED_IMAGES
1100 fi
1101
1102 echo -e $BOLD"Auto adding included apps"$EBOLD
1103         for iapp in $TMP_APPS; do
1104                 if [[ "$__added_apps" != *"$iapp"* ]]; then
1105                         file_pointer=$(echo $iapp | tr '[:upper:]' '[:lower:]')
1106                         file_pointer="../common/"$file_pointer"_api_functions.sh"
1107                         padded_iapp=$iapp
1108                         while [ ${#padded_iapp} -lt 16 ]; do
1109                                 padded_iapp=$padded_iapp" "
1110                         done
1111                         echo " Auto-adding included app $padded_iapp  Sourcing $file_pointer"
1112                         if [ ! -f "$file_pointer" ]; then
1113                                 echo " Include file $file_pointer for app $iapp does not exist"
1114                                 exit 1
1115                         fi
1116                         . $file_pointer
1117                         if [ $? -ne 0 ]; then
1118                                 echo " Include file $file_pointer contain errors. Exiting..."
1119                                 exit 1
1120                         fi
1121                 fi
1122         done
1123 echo ""
1124
1125 echo -e $BOLD"Test environment info"$EBOLD
1126
1127 # Check needed installed sw
1128
1129 tmp=$(which bash)
1130 if [ $? -ne 0 ] || [ -z "$tmp" ]; then
1131         echo -e $RED"bash is required to run the test environment, pls install"$ERED
1132         exit 1
1133 fi
1134 echo " bash is installed and using version:"
1135 echo "$(bash --version)" | indent2
1136
1137 tmp=$(which python3)
1138 if [ $? -ne 0 ] || [ -z "$tmp" ]; then
1139         echo -e $RED"python3 is required to run the test environment, pls install"$ERED
1140         exit 1
1141 fi
1142 echo " python3 is installed and using version: $(python3 --version)"
1143
1144 tmp=$(which docker)
1145 if [ $? -ne 0 ] || [ -z "$tmp" ]; then
1146         echo -e $RED"docker is required to run the test environment, pls install"$ERED
1147         exit 1
1148 fi
1149 echo " docker is installed and using versions:"
1150 echo  "  $(docker version --format 'Client version {{.Client.Version}} Server version {{.Server.Version}}')"
1151
1152 if [ $RUNMODE == "DOCKER" ]; then
1153         tmp=$(which docker-compose)
1154         if [ $? -ne 0 ] || [ -z "$tmp" ]; then
1155                 echo -e $RED"docker-compose is required to run the test environment, pls install"$ERED
1156                 exit 1
1157         else
1158                 tmp=$(docker-compose version)
1159                 echo " docker-compose installed and using version $tmp"
1160                 if [[ "$tmp" == *'v2'* ]]; then
1161                         DOCKER_COMPOSE_VERSION="V2"
1162                 fi
1163         fi
1164 fi
1165 if [ $RUNMODE == "KUBE" ]; then
1166         tmp=$(which kubectl)
1167         if [ $? -ne 0 ] || [ -z tmp ]; then
1168                 echo -e $RED"kubectl is required to run the test environment in kubernetes mode, pls install"$ERED
1169                 exit 1
1170         else
1171                 echo " kubectl is installed and using versions:"
1172                 echo $(kubectl $KUBECONF version --short=true) | indent2
1173                 res=$(kubectl $KUBECONF cluster-info 2>&1)
1174                 if [ $? -ne 0 ]; then
1175                         echo -e "$BOLD$RED############################################# $ERED$EBOLD"
1176                         echo -e  $BOLD$RED"Command 'kubectl '$KUBECONF' cluster-info' returned error $ERED$EBOLD"
1177                         echo -e "$BOLD$RED############################################# $ERED$EBOLD"
1178                         echo " "
1179                         echo "kubectl response:"
1180                         echo $res
1181                         echo " "
1182                         echo "This script may have been started with user with no permission to run kubectl"
1183                         echo "Try running with 'sudo', set env KUBECONFIG or set '--kubeconfig' parameter"
1184                         echo "Do either 1, 2 or 3 "
1185                         echo " "
1186                         echo "1"
1187                         echo "Run with sudo"
1188                         echo -e $BOLD"sudo <test-script-and-parameters>"$EBOLD
1189                         echo " "
1190                         echo "2"
1191                         echo "Export KUBECONFIG and pass env to sudo - (replace user)"
1192                         echo -e $BOLD"export KUBECONFIG='/home/<user>/.kube/config'"$EBOLD
1193                         echo -e $BOLD"sudo -E <test-script-and-parameters>"$EBOLD
1194                         echo " "
1195                         echo "3"
1196                         echo "Set KUBECONFIG via script parameter"
1197                         echo -e $BOLD"sudo ... --kubeconfig /home/<user>/.kube/<config-file> ...."$EBOLD
1198                         echo "The config file need to downloaded from the cluster"
1199
1200                         exit 1
1201                 fi
1202                 echo " Node(s) and container runtime config"
1203                 kubectl $KUBECONF get nodes -o wide | indent2
1204                 echo ""
1205                 if [ -z "$HOST_PATH_BASE_DIR" ]; then
1206                         HOST_PATH_BASE_DIR="/tmp"
1207                         echo " Persistent volumes will be mounted to $HOST_PATH_BASE_DIR on applicable node"
1208                         echo " No guarantee that persistent volume data is available on all nodes in the cluster"
1209                 else
1210                         echo "Persistent volumes will be mounted to base dir: $HOST_PATH_BASE_DIR"
1211                         echo "Assuming this dir is mounted from each node to a dir on the localhost or other"
1212                         echo "file system available to all nodes"
1213                 fi
1214         fi
1215 fi
1216
1217 echo ""
1218
1219 echo -e $BOLD"Checking configured image setting for this test case"$EBOLD
1220
1221 #Temp var to check for image variable name errors
1222 IMAGE_ERR=0
1223 #Create a file with image info for later printing as a table
1224 image_list_file="./tmp/.image-list"
1225 echo -e "Application\tApp short name\tImage\ttag\ttag-switch" > $image_list_file
1226
1227 # Check if image env var is set and if so export the env var with image to use (used by docker compose files)
1228 # arg: <app-short-name> <target-variable-name> <image-variable-name> <image-tag-variable-name> <tag-suffix> <image name>
1229 __check_and_create_image_var() {
1230
1231         if [ $# -ne 6 ]; then
1232                 echo "Expected arg: <app-short-name> <target-variable-name> <image-variable-name> <image-tag-variable-name> <tag-suffix> <image name>"
1233                 ((IMAGE_ERR++))
1234                 return
1235         fi
1236
1237         __check_included_image $1
1238         if [ $? -ne 0 ]; then
1239                 echo -e "$6\t$1\t<image-excluded>\t<no-tag>"  >> $image_list_file
1240                 # Image is excluded since the corresponding app is not used in this test
1241                 return
1242         fi
1243         tmp=${6}"\t"${1}"\t"
1244         #Create var from the input var names
1245         image="${!3}"
1246         tmptag=$4"_"$5
1247         tag="${!tmptag}"
1248
1249         optional_image_repo_target=""
1250
1251         if [ -z $image ]; then
1252                 __check_ignore_image $1
1253                 if [ $? -eq 0 ]; then
1254                         app_ds=$6
1255                         if [ -z "$6" ]; then
1256                                 app_ds="<app ignored>"
1257                         fi
1258                         echo -e "$app_ds\t$1\t<image-ignored>\t<no-tag>"  >> $image_list_file
1259                         # Image is ignored since the corresponding the images is not set in the env file
1260                         __remove_included_image $1   # Remove the image from the list of included images
1261                         return
1262                 fi
1263                 echo -e $RED"\$"$3" not set in $TEST_ENV_VAR_FILE"$ERED
1264                 ((IMAGE_ERR++))
1265                 echo ""
1266                 tmp=$tmp"<no-image>\t"
1267         else
1268
1269                 optional_image_repo_target=$image
1270
1271                 #Add repo depending on image type
1272                 if [ "$5" == "REMOTE_RELEASE" ]; then
1273                         image=$NEXUS_RELEASE_REPO$image
1274                 fi
1275                 if [ "$5" == "REMOTE" ]; then
1276                         image=$NEXUS_STAGING_REPO$image
1277                 fi
1278                 if [ "$5" == "REMOTE_SNAPSHOT" ]; then
1279                         image=$NEXUS_SNAPSHOT_REPO$image
1280                 fi
1281                 if [ "$5" == "REMOTE_PROXY" ]; then
1282                         image=$NEXUS_PROXY_REPO$image
1283                 fi
1284                 if [ "$5" == "REMOTE_RELEASE_ONAP" ]; then
1285                         image=$NEXUS_RELEASE_REPO_ONAP$image
1286                 fi
1287                 if [ "$5" == "REMOTE_RELEASE_ORAN" ]; then
1288                         image=$NEXUS_RELEASE_REPO_ORAN$image
1289                 fi
1290                 #No nexus repo added for local images, tag: LOCAL and other tags
1291                 tmp=$tmp$image"\t"
1292         fi
1293         if [ -z $tag ]; then
1294                 echo -e $RED"\$"$tmptag" not set in $TEST_ENV_VAR_FILE"$ERED
1295                 ((IMAGE_ERR++))
1296                 echo ""
1297                 tmp=$tmp"<no-tag>\t"
1298         else
1299                 tmp=$tmp$tag
1300         fi
1301         tmp=$tmp"\t"$5
1302         echo -e "$tmp" >> $image_list_file
1303         #Export the env var
1304         export "${2}"=$image":"$tag  #Note, this var may be set to the value of the target value below in __check_and_pull_image
1305
1306         remote_or_local_push=false
1307         if [ ! -z "$IMAGE_REPO_ADR" ] && [[ $5 != *"PROXY"* ]]; then
1308                 if [ $5 == "LOCAL" ]; then
1309                         remote_or_local_push=true
1310                 fi
1311                 if [[ $5 == *"REMOTE"* ]]; then
1312                         if [ "$IMAGE_REPO_POLICY" == "remote" ]; then
1313                                 remote_or_local_push=true
1314                         fi
1315                 fi
1316         fi
1317         if $remote_or_local_push; then    # Only re-tag and push images according to policy, if repo is given
1318                 export "${2}_SOURCE"=$image":"$tag  #Var to keep the actual source image
1319                 if [[ $optional_image_repo_target == *"/"* ]]; then # Replace all / with _ for images to push to external repo
1320                         optional_image_repo_target_tmp=${optional_image_repo_target//\//_}
1321                         optional_image_repo_target=$optional_image_repo_target_tmp
1322                 fi
1323                 export "${2}_TARGET"=$IMAGE_REPO_ADR"/"$optional_image_repo_target":"$tag  #Create image + tag for optional image repo - pushed later if needed
1324         else
1325                 export "${2}_SOURCE"=""
1326                 export "${2}_TARGET"=""
1327         fi
1328 }
1329
1330 # Check if app uses image included in this test run
1331 # Returns 0 if image is included, 1 if not
1332 __check_included_image() {
1333         for im in $INCLUDED_IMAGES; do
1334                 if [ "$1" == "$im" ]; then
1335                         return 0
1336                 fi
1337         done
1338         return 1
1339 }
1340
1341 # Check if app uses a project image
1342 # Returns 0 if image is included, 1 if not
1343 __check_project_image() {
1344         for im in $PROJECT_IMAGES; do
1345                 if [ "$1" == "$im" ]; then
1346                         return 0
1347                 fi
1348         done
1349         return 1
1350 }
1351
1352 # Check if app uses image built by the test script
1353 # Returns 0 if image is included, 1 if not
1354 __check_image_local_build() {
1355         for im in $LOCAL_IMAGE_BUILD; do
1356                 if [ "$1" == "$im" ]; then
1357                         return 0
1358                 fi
1359         done
1360         return 1
1361 }
1362
1363 # Check if app image is conditionally ignored in this test run
1364 # Returns 0 if image is conditionally ignored, 1 if not
1365 __check_ignore_image() {
1366         for im in $CONDITIONALLY_IGNORED_IMAGES; do
1367                 if [ "$1" == "$im" ]; then
1368                         return 0
1369                 fi
1370         done
1371         return 1
1372 }
1373
1374 # Removed image from included list of included images
1375 # Used when an image is marked as conditionally ignored
1376 __remove_included_image() {
1377         tmp_img_rem_list=""
1378         for im in $INCLUDED_IMAGES; do
1379                 if [ "$1" != "$im" ]; then
1380                         tmp_img_rem_list=$tmp_img_rem_list" "$im
1381                 fi
1382         done
1383         INCLUDED_IMAGES=$tmp_img_rem_list
1384         return 0
1385 }
1386
1387 # Check if app is included in the prestarted set of apps
1388 # Returns 0 if image is included, 1 if not
1389 __check_prestarted_image() {
1390         for im in $KUBE_PRESTARTED_IMAGES; do
1391                 if [ "$1" == "$im" ]; then
1392                         return 0
1393                 fi
1394         done
1395         return 1
1396 }
1397
1398 # Check if an app shall use a local image, based on the cmd parameters
1399 __check_image_local_override() {
1400         for im in $USE_LOCAL_IMAGES; do
1401                 if [ "$1" == "$im" ]; then
1402                         return 1
1403                 fi
1404         done
1405         return 0
1406 }
1407
1408 # Check if app uses image override
1409 # Returns the image/tag suffix LOCAL for local image or REMOTE/REMOTE_RELEASE/REMOTE_SNAPSHOT for staging/release/snapshot image
1410 __check_image_override() {
1411
1412         for im in $ORAN_IMAGES_APP_NAMES; do
1413                 if [ "$1" == "$im" ]; then
1414                         echo "REMOTE_RELEASE_ORAN"
1415                         return 0
1416                 fi
1417         done
1418
1419         for im in $ONAP_IMAGES_APP_NAMES; do
1420                 if [ "$1" == "$im" ]; then
1421                         echo "REMOTE_RELEASE_ONAP"
1422                         return 0
1423                 fi
1424         done
1425
1426         found=0
1427         for im in $PROJECT_IMAGES_APP_NAMES; do
1428                 if [ "$1" == "$im" ]; then
1429                         found=1
1430                 fi
1431         done
1432
1433         if [ $found -eq 0 ]; then
1434                 echo "REMOTE_PROXY"
1435                 return 0
1436         fi
1437
1438         suffix=""
1439         if [ $IMAGE_CATEGORY == "RELEASE" ]; then
1440                 suffix="REMOTE_RELEASE"
1441         fi
1442         if [ $IMAGE_CATEGORY == "DEV" ]; then
1443                 suffix="REMOTE"
1444         fi
1445         CTR=0
1446         for im in $USE_STAGING_IMAGES; do
1447                 if [ "$1" == "$im" ]; then
1448                         suffix="REMOTE"
1449                         ((CTR++))
1450                 fi
1451         done
1452         for im in $USE_RELEASE_IMAGES; do
1453                 if [ "$1" == "$im" ]; then
1454                         suffix="REMOTE_RELEASE"
1455                         ((CTR++))
1456                 fi
1457         done
1458         for im in $USE_SNAPSHOT_IMAGES; do
1459                 if [ "$1" == "$im" ]; then
1460                         suffix="REMOTE_SNAPSHOT"
1461                         ((CTR++))
1462                 fi
1463         done
1464         for im in $USE_LOCAL_IMAGES; do
1465                 if [ "$1" == "$im" ]; then
1466                         suffix="LOCAL"
1467                         ((CTR++))
1468                 fi
1469         done
1470         for im in $USE_EXTERNAL_IMAGES; do
1471                 if [ "$1" == "$im" ]; then
1472                         suffix="EXTERNAL"
1473                         ((CTR++))
1474                 fi
1475         done
1476         echo $suffix
1477         if [ $CTR -gt 1 ]; then
1478                 exit 1
1479         fi
1480         return 0
1481 }
1482
1483 # Function to re-tag and image and push to another image repo
1484 __retag_and_push_image() {
1485         if [ ! -z "$IMAGE_REPO_ADR" ]; then
1486                 source_image="${!1}"
1487                 trg_var_name=$1_"TARGET" # This var is created in func __check_and_create_image_var
1488                 target_image="${!trg_var_name}"
1489
1490                 if [ -z $target_image ]; then
1491                         return 0  # Image with no target shall not be pushed
1492                 fi
1493
1494                 echo -ne "  Attempt to re-tag image to: ${BOLD}${target_image}${EBOLD}${SAMELINE}"
1495                 tmp=$(docker image tag $source_image ${target_image} )
1496                 if [ $? -ne 0 ]; then
1497                         docker stop $tmp &> ./tmp/.dockererr
1498                         ((IMAGE_ERR++))
1499                         echo ""
1500                         echo -e "  Attempt to re-tag image to: ${BOLD}${target_image}${EBOLD} - ${RED}Failed${ERED}"
1501                         cat ./tmp/.dockererr
1502                         return 1
1503                 else
1504                         echo -e "  Attempt to re-tag image to: ${BOLD}${target_image}${EBOLD} - ${GREEN}OK${EGREEN}"
1505                 fi
1506                 echo -ne "  Attempt to push re-tagged image: ${BOLD}${target_image}${EBOLD}${SAMELINE}"
1507                 tmp=$(docker push ${target_image} )
1508                 if [ $? -ne 0 ]; then
1509                         docker stop $tmp &> ./tmp/.dockererr
1510                         ((IMAGE_ERR++))
1511                         echo ""
1512                         echo -e "  Attempt to push re-tagged image: ${BOLD}${target_image}${EBOLD} - ${RED}Failed${ERED}"
1513                         cat ./tmp/.dockererr
1514                         return 1
1515                 else
1516                         echo -e "  Attempt to push re-tagged image: ${BOLD}${target_image}${EBOLD} - ${GREEN}OK${EGREEN}"
1517                 fi
1518                 export "${1}"=$target_image
1519         fi
1520         return 0
1521 }
1522
1523 #Function to check if image exist and stop+remove the container+pull new images as needed
1524 #args <script-start-arg> <descriptive-image-name> <container-base-name> <image-with-tag-var-name>
1525 __check_and_pull_image() {
1526
1527         source_image="${!4}"
1528
1529         echo -e " Checking $BOLD$2$EBOLD container(s) with basename: $BOLD$3$EBOLD using image: $BOLD$source_image$EBOLD"
1530         format_string="\"{{.Repository}}\\t{{.Tag}}\\t{{.CreatedSince}}\\t{{.Size}}\""
1531         tmp_im=$(docker images --format $format_string $source_image)
1532
1533         if [ $1 == "local" ]; then
1534                 if [ -z "$tmp_im" ]; then
1535                         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
1536                         ((IMAGE_ERR++))
1537                         return 1
1538                 else
1539                         echo -e "  "$2" (local image): \033[1m"$source_image"\033[0m "$GREEN"OK"$EGREEN
1540                 fi
1541         elif [ $1 == "remote" ] || [ $1 == "remote-remove" ]; then
1542                 if [ $1 == "remote-remove" ]; then
1543                         if [ $RUNMODE == "DOCKER" ]; then
1544
1545                                 echo -ne "  Attempt to stop and remove container(s), if running - ${SAMELINE}"
1546                                 tmp=$(docker ps -aq --filter name=${3} --filter network=${DOCKER_SIM_NWNAME})
1547                                 if [ $? -eq 0 ] && [ ! -z "$tmp" ]; then
1548                                         docker stop -t 0 $tmp &> ./tmp/.dockererr
1549                                         if [ $? -ne 0 ]; then
1550                                                 ((IMAGE_ERR++))
1551                                                 echo ""
1552                                                 echo -e $RED"  Container(s) could not be stopped - try manual stopping the container(s)"$ERED
1553                                                 cat ./tmp/.dockererr
1554                                                 return 1
1555                                         fi
1556                                 fi
1557                                 echo -ne "  Attempt to stop and remove container(s), if running - "$GREEN"stopped"$EGREEN"${SAMELINE}"
1558                                 tmp=$(docker ps -aq --filter name=${3} --filter network=${DOCKER_SIM_NWNAME}) &> /dev/null
1559                                 if [ $? -eq 0 ] && [ ! -z "$tmp" ]; then
1560                                         docker rm -f $tmp &> ./tmp/.dockererr
1561                                         if [ $? -ne 0 ]; then
1562                                                 ((IMAGE_ERR++))
1563                                                 echo ""
1564                                                 echo -e $RED"  Container(s) could not be removed - try manual removal of the container(s)"$ERED
1565                                                 cat ./tmp/.dockererr
1566                                                 return 1
1567                                         fi
1568                                 fi
1569                                 echo -e "  Attempt to stop and remove container(s), if running - "$GREEN"stopped removed"$EGREEN
1570                                 tmp_im=""
1571                         else
1572                                 tmp_im=""
1573                         fi
1574                 fi
1575                 if [ -z "$tmp_im" ]; then
1576                         echo -ne "  Pulling image${SAMELINE}"
1577                         out=$(docker pull $source_image)
1578                         if [ $? -ne 0 ]; then
1579                                 echo ""
1580                                 echo -e "  Pulling image -$RED could not be pulled"$ERED
1581                                 ((IMAGE_ERR++))
1582                                 echo $out > ./tmp/.dockererr
1583                                 echo $out
1584                                 return 1
1585                         fi
1586                         echo $out > ./tmp/.dockererr
1587                         if [[ $out == *"up to date"* ]]; then
1588                                 echo -e "  Pulling image -$GREEN Image is up to date $EGREEN"
1589                         elif [[ $out == *"Downloaded newer image"* ]]; then
1590                                 echo -e "  Pulling image -$GREEN Newer image pulled $EGREEN"
1591                         else
1592                                 echo -e "  Pulling image -$GREEN Pulled $EGREEN"
1593                         fi
1594                 else
1595                         echo -e "  Pulling image -$GREEN OK $EGREEN(exists in local repository)"
1596                 fi
1597         fi
1598
1599         __retag_and_push_image $4
1600
1601         return $?
1602 }
1603
1604 setup_testenvironment() {
1605         # Check that image env setting are available
1606         echo ""
1607
1608         # Image var setup for all project images included in the test
1609         for imagename in $APP_SHORT_NAMES; do
1610                 __check_included_image $imagename
1611                 incl=$?
1612                 __check_project_image $imagename
1613                 proj=$?
1614                 if [ $incl -eq 0 ]; then
1615                         if [ $proj -eq 0 ]; then
1616                                 IMAGE_SUFFIX=$(__check_image_override $imagename)
1617                                 if [ $? -ne 0 ]; then
1618                                         echo -e $RED"Image setting from cmd line not consistent for $imagename."$ERED
1619                                         ((IMAGE_ERR++))
1620                                 fi
1621                         else
1622                                 IMAGE_SUFFIX="none"
1623                         fi
1624                         # A function name is created from the app short name
1625                         # for example app short name 'ICS' -> produce the function
1626                         # name __ICS_imagesetup
1627                         # This function is called and is expected to exist in the imported
1628                         # file for the ics test functions
1629                         # The resulting function impl will call '__check_and_create_image_var' function
1630                         # with appropriate parameters
1631                         # If the image suffix is none, then the component decides the suffix
1632                         function_pointer="__"$imagename"_imagesetup"
1633                         $function_pointer $IMAGE_SUFFIX
1634
1635                         function_pointer="__"$imagename"_test_requirements"
1636                         $function_pointer
1637                 fi
1638         done
1639
1640         #Errors in image setting - exit
1641         if [ $IMAGE_ERR -ne 0 ]; then
1642                 exit 1
1643         fi
1644
1645         #Print a tables of the image settings
1646         echo -e $BOLD"Images configured for start arg: "$START_ARG $EBOLD
1647         column -t -s $'\t' $image_list_file | indent1
1648
1649         echo ""
1650
1651         #Set the SIM_GROUP var
1652         echo -e $BOLD"Setting var to main dir of all container/simulator scripts"$EBOLD
1653         if [ -z "$SIM_GROUP" ]; then
1654                 SIM_GROUP=$AUTOTEST_HOME/../simulator-group
1655                 if [ ! -d  $SIM_GROUP ]; then
1656                         echo "Trying to set env var SIM_GROUP to dir 'simulator-group' in the nontrtric repo, but failed."
1657                         echo -e $RED"Please set the SIM_GROUP manually in the applicable $TEST_ENV_VAR_FILE"$ERED
1658                         exit 1
1659                 else
1660                         echo " SIM_GROUP auto set to: " $SIM_GROUP
1661                 fi
1662         elif [ $SIM_GROUP = *simulator_group ]; then
1663                 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
1664                 exit 1
1665         else
1666                 echo " SIM_GROUP env var already set to: " $SIM_GROUP
1667         fi
1668
1669         echo ""
1670
1671         #Temp var to check for image pull errors
1672         IMAGE_ERR=0
1673
1674         # Delete namespaces
1675         echo -e $BOLD"Deleting namespaces"$EBOLD
1676
1677
1678         if [ "$DELETE_KUBE_NAMESPACES" -eq 1 ]; then
1679                 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
1680                 if [ $? -ne 0 ]; then
1681                         echo " Cannot get list of namespaces...ignoring delete"
1682                 else
1683                         for test_env_ns in $test_env_namespaces; do
1684                                 __kube_delete_namespace $test_env_ns
1685                         done
1686                 fi
1687         else
1688                 echo " Namespace delete option not set or ignored"
1689         fi
1690         echo ""
1691
1692         # Delete containers
1693         echo -e $BOLD"Deleting containers"$EBOLD
1694
1695         if [ "$DELETE_CONTAINERS" -eq 1 ]; then
1696                 echo " Stopping containers label 'nrttest_app'..."
1697                 docker stop $(docker ps -qa  --filter "label=nrttest_app") 2> /dev/null
1698                 echo " Removing stopped containers..."
1699                 docker rm $(docker ps -qa  --filter "label=nrttest_app") 2> /dev/null
1700         else
1701                 echo " Contatiner delete option not set or ignored"
1702         fi
1703         echo ""
1704
1705         # The following sequence pull the configured images
1706         echo -e $BOLD"Pulling configured images, if needed"$EBOLD
1707         __exclude_check=0
1708         if [ ! -z "$IMAGE_REPO_ADR" ] && [ $IMAGE_REPO_POLICY == "local" ]; then
1709                 echo -e $YELLOW" Excluding all remote image check/pull (unless local override) when running with image repo: $IMAGE_REPO_ADR and image policy: $IMAGE_REPO_POLICY"$EYELLOW
1710                 __exclude_check=1
1711         fi
1712         for imagename in $APP_SHORT_NAMES; do
1713                 __check_included_image $imagename
1714                 incl=$?
1715                 __check_project_image $imagename
1716                 proj=$?
1717                 if [ $incl -eq 0 ]; then
1718                         if [ $proj -eq 0 ]; then
1719                                 START_ARG_MOD=$START_ARG
1720                                 __check_image_local_override $imagename
1721                                 if [ $? -eq 1 ]; then
1722                                         START_ARG_MOD="local"
1723                                 fi
1724                         else
1725                                 START_ARG_MOD=$START_ARG
1726                         fi
1727                         __exclude_image_check=0
1728                         if [ $__exclude_check == 1 ] && [ "$START_ARG_MOD" != "local" ]; then
1729                                 # For to handle locally built images,  overriding remote images
1730                                 __exclude_image_check=1
1731                         fi
1732                         if [ $__exclude_image_check == 0 ]; then
1733                                 __check_image_local_build $imagename
1734                                 #No pull of images built locally
1735                                 if [ $? -ne 0 ]; then
1736                                         # A function name is created from the app short name
1737                                         # for example app short name 'HTTPPROXY' -> produce the function
1738                                         # name __HTTPPROXY_imagesetup
1739                                         # This function is called and is expected to exist in the imported
1740                                         # file for the httpproxy test functions
1741                                         # The resulting function impl will call '__check_and_pull_image' function
1742                                         # with appropriate parameters
1743                                         function_pointer="__"$imagename"_imagepull"
1744                                         $function_pointer $START_ARG_MOD $START_ARG
1745                                 fi
1746                         fi
1747                 else
1748                         echo -e $YELLOW" Excluding $imagename image from image check/pull"$EYELLOW
1749                 fi
1750         done
1751
1752
1753         #Errors in image setting - exit
1754         if [ $IMAGE_ERR -ne 0 ]; then
1755                 echo ""
1756                 echo "#################################################################################################"
1757                 echo -e $RED"One or more images could not be pulled or containers using the images could not be stopped/removed"$ERED
1758                 echo -e $RED"Or local image, overriding remote image, does not exist"$ERED
1759                 if [ $IMAGE_CATEGORY == "DEV" ]; then
1760                     echo ""
1761                         echo -e $RED"Note that SNAPSHOT and staging images may be purged from nexus after a certain period."$ERED
1762                         echo -e $RED"In addition, the image may not have been updated in the current release so no SNAPSHOT or staging image exists"$ERED
1763                         echo -e $RED"In these cases, switch to use a released image instead, use the flag '--use-release-image <App-short-name>'"$ERED
1764                         echo -e $RED"Use the 'App-short-name' for the applicable image from the above table: 'Images configured for start arg'."$ERED
1765                 fi
1766                 echo "#################################################################################################"
1767                 echo ""
1768                 exit 1
1769         fi
1770
1771         echo ""
1772
1773         echo -e $BOLD"Building images needed for test"$EBOLD
1774
1775         for imagename in $APP_SHORT_NAMES; do
1776                 cd $AUTOTEST_HOME #Always reset to orig dir
1777                 __check_image_local_build $imagename
1778                 if [ $? -eq 0 ]; then
1779                         __check_included_image $imagename
1780                         if [ $? -eq 0 ]; then
1781                                 # A function name is created from the app short name
1782                                 # for example app short name 'MR' -> produce the function
1783                                 # name __MR_imagebuild
1784                                 # This function is called and is expected to exist in the imported
1785                                 # file for the mr test functions
1786                                 # The resulting function impl shall build the imagee
1787                                 function_pointer="__"$imagename"_imagebuild"
1788                                 $function_pointer
1789
1790                         else
1791                                 echo -e $YELLOW" Excluding image for app $imagename from image build"$EYELLOW
1792                         fi
1793                 fi
1794         done
1795
1796         cd $AUTOTEST_HOME # Just to make sure...
1797
1798         echo ""
1799
1800         # Create a table of the images used in the script - from local repo
1801         echo -e $BOLD"Local docker registry images used in this test script"$EBOLD
1802
1803         docker_tmp_file=./tmp/.docker-images-table
1804         format_string="{{.Repository}}\\t{{.Tag}}\\t{{.CreatedSince}}\\t{{.Size}}\\t{{.CreatedAt}}"
1805         echo -e "Application\tRepository\tTag\tCreated since\tSize\tCreated at" > $docker_tmp_file
1806
1807         for imagename in $APP_SHORT_NAMES; do
1808                 __check_included_image $imagename
1809                 if [ $? -eq 0 ]; then
1810                         # Only print image data if image repo is null, or if image repo is set and image is local
1811                         print_image_data=0
1812                         if [ -z "$IMAGE_REPO_ADR" ]; then
1813                                 print_image_data=1
1814                         else
1815                                 __check_image_local_build $imagename
1816                                 if [ $? -eq 0 ]; then
1817                                         print_image_data=1
1818                                 fi
1819                         fi
1820                         if [ $print_image_data -eq 1 ]; then
1821                                 # A function name is created from the app short name
1822                                 # for example app short name 'MR' -> produce the function
1823                                 # name __MR_imagebuild
1824                                 # This function is called and is expected to exist in the imported
1825                                 # file for the mr test functions
1826                                 # The resulting function impl shall build the imagee
1827                                 function_pointer="__"$imagename"_image_data"
1828                                 $function_pointer "$format_string" $docker_tmp_file
1829                         fi
1830                 fi
1831         done
1832
1833         column -t -s $'\t' $docker_tmp_file | indent1
1834
1835         echo ""
1836
1837         if [ ! -z "$IMAGE_REPO_ADR" ]; then
1838
1839                 # Create a table of the images used in the script - from remote repo
1840                 echo -e $BOLD"Remote repo images used in this test script"$EBOLD
1841                 echo -e $YELLOW"-- Note: These image will be pulled when the container starts. Images not managed by the test engine "$EYELLOW
1842                 echo -e $YELLOW"-- Note: Images with local override will however be re-tagged and managed by the test engine "$EYELLOW
1843                 docker_tmp_file=./tmp/.docker-images-table
1844                 format_string="{{.Repository}}\\t{{.Tag}}"
1845                 echo -e "Application\tRepository\tTag" > $docker_tmp_file
1846
1847                 for imagename in $APP_SHORT_NAMES; do
1848                         __check_included_image $imagename
1849                         if [ $? -eq 0 ]; then
1850                                 # Only print image data if image repo is null, or if image repo is set and image is local
1851                                 __check_image_local_build $imagename
1852                                 if [ $? -ne 0 ]; then
1853                                         # A function name is created from the app short name
1854                                         # for example app short name 'MR' -> produce the function
1855                                         # name __MR_imagebuild
1856                                         # This function is called and is expected to exist in the imported
1857                                         # file for the mr test functions
1858                                         # The resulting function impl shall build the imagee
1859                                         function_pointer="__"$imagename"_image_data"
1860                                         $function_pointer "$format_string" $docker_tmp_file
1861                                 fi
1862                         fi
1863                 done
1864
1865                 column -t -s $'\t' $docker_tmp_file | indent1
1866
1867                 echo ""
1868         fi
1869
1870         if [ $RUNMODE == "KUBE" ]; then
1871
1872                 echo "================================================================================="
1873                 echo "================================================================================="
1874
1875                 if [ -z "$IMAGE_REPO_ADR" ]; then
1876                         echo -e $YELLOW" The image pull policy is set to 'Never' - assuming a local image repo is available for all images"$EYELLOW
1877                         echo -e " This setting only works on single node clusters on the local machine"
1878                         echo -e " It does not work with multi-node clusters or remote clusters. "
1879                         export KUBE_IMAGE_PULL_POLICY="Never"
1880                 else
1881                         echo -e $YELLOW" The image pull policy is set to 'Always'"$EYELLOW
1882                         echo -e " This setting work on local clusters, multi-node clusters and remote cluster. "
1883                         echo -e " Only locally built images are managed. Remote images are always pulled from remote repos"
1884                         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"
1885                         export KUBE_IMAGE_PULL_POLICY="Always"
1886                 fi
1887                 #CLUSTER_IP=$(kubectl $KUBECONF config view -o jsonpath={.clusters[0].cluster.server} | awk -F[/:] '{print $4}')
1888                 #echo -e $YELLOW" The cluster hostname/ip is: $CLUSTER_IP"$EYELLOW
1889
1890                 echo "================================================================================="
1891                 echo "================================================================================="
1892                 echo ""
1893         fi
1894
1895         echo -e $BOLD"======================================================="$EBOLD
1896         echo -e $BOLD"== Common test setup completed -  test script begins =="$EBOLD
1897         echo -e $BOLD"======================================================="$EBOLD
1898         echo ""
1899
1900         LOG_STAT_ARGS=""
1901
1902         for imagename in $APP_SHORT_NAMES; do
1903                 __check_included_image $imagename
1904                 retcode_i=$?
1905                 __check_prestarted_image $imagename
1906                 retcode_p=$?
1907                 if [ $retcode_i -eq 0 ] || [ $retcode_p -eq 0 ]; then
1908                         # A function name is created from the app short name
1909                         # for example app short name 'RICMSIM' -> produce the function
1910                         # name __RICSIM__initial_setup
1911                         # This function is called and is expected to exist in the imported
1912                         # file for the ricsim test functions
1913                         # The resulting function impl shall perform initial setup of port, host etc
1914
1915                         function_pointer="__"$imagename"_initial_setup"
1916                         $function_pointer
1917
1918                         function_pointer="__"$imagename"_statisics_setup"
1919                         LOG_STAT_ARGS=$LOG_STAT_ARGS" "$($function_pointer)
1920                 fi
1921         done
1922
1923         if [ $COLLECT_RUNTIME_STATS -eq 1 ]; then
1924                 ../common/genstat.sh $RUNMODE $SECONDS $TESTLOGS/$ATC/stat_data.csv $LOG_STAT_ARGS &
1925                 COLLECT_RUNTIME_STATS_PID=$!
1926         fi
1927
1928 }
1929
1930 # Function to print the test result, shall be the last cmd in a test script
1931 # args: -
1932 # (Function for test scripts)
1933 print_result() {
1934
1935         TCTEST_END=$SECONDS
1936         duration=$((TCTEST_END-TCTEST_START))
1937
1938         echo "-------------------------------------------------------------------------------------------------"
1939         echo "-------------------------------------     Test case: "$ATC
1940         echo "-------------------------------------     Ended:     "$(date)
1941         echo "-------------------------------------------------------------------------------------------------"
1942         echo "-- Description: "$TC_ONELINE_DESCR
1943         echo "-- Execution time: " $duration " seconds"
1944         echo "-- Used env file: "$TEST_ENV_VAR_FILE
1945         echo "-------------------------------------------------------------------------------------------------"
1946         echo "-------------------------------------     RESULTS"
1947         echo ""
1948
1949
1950         if [ $RES_DEVIATION -gt 0 ]; then
1951                 echo "Test case deviations"
1952                 echo "===================================="
1953                 cat $DEVIATION_FILE
1954         fi
1955         echo ""
1956         echo "Timer measurement in the test script"
1957         echo "===================================="
1958         column -t -s $'\t' $TIMER_MEASUREMENTS
1959         if [ $RES_PASS != $RES_TEST ]; then
1960                 echo -e $RED"Measurement may not be reliable when there are failed test - failures may cause long measurement values due to timeouts etc."$ERED
1961         fi
1962         echo ""
1963
1964         if [ $COLLECT_RUNTIME_STATS -eq 1 ]; then
1965                 echo "Runtime statistics collected in file: "$TESTLOGS/$ATC/stat_data.csv
1966                 echo ""
1967         fi
1968         TMP_FLAG_FAIL_PASS=0
1969         total=$((RES_PASS+RES_FAIL))
1970         if [ $RES_TEST -eq 0 ]; then
1971                 TMP_FLAG_FAIL_PASS=1
1972                 echo -e "\033[1mNo tests seem to have been executed. Check the script....\033[0m"
1973                 echo -e "\033[31m\033[1m ___  ___ ___ ___ ___ _____   ___ _   ___ _   _   _ ___ ___ \033[0m"
1974                 echo -e "\033[31m\033[1m/ __|/ __| _ \_ _| _ \_   _| | __/_\ |_ _| | | | | | _ \ __|\033[0m"
1975                 echo -e "\033[31m\033[1m\__ \ (__|   /| ||  _/ | |   | _/ _ \ | || |_| |_| |   / _| \033[0m"
1976                 echo -e "\033[31m\033[1m|___/\___|_|_\___|_|   |_|   |_/_/ \_\___|____\___/|_|_\___|\033[0m"
1977         elif [ $total != $RES_TEST ]; then
1978                 TMP_FLAG_FAIL_PASS=1
1979                 echo -e "\033[1mTotal number of tests does not match the sum of passed and failed tests. Check the script....\033[0m"
1980                 echo -e "\033[31m\033[1m ___  ___ ___ ___ ___ _____   ___ _   ___ _   _   _ ___ ___ \033[0m"
1981                 echo -e "\033[31m\033[1m/ __|/ __| _ \_ _| _ \_   _| | __/_\ |_ _| | | | | | _ \ __|\033[0m"
1982                 echo -e "\033[31m\033[1m\__ \ (__|   /| ||  _/ | |   | _/ _ \ | || |_| |_| |   / _| \033[0m"
1983                 echo -e "\033[31m\033[1m|___/\___|_|_\___|_|   |_|   |_/_/ \_\___|____\___/|_|_\___|\033[0m"
1984         elif [ $RES_CONF_FAIL -ne 0 ]; then
1985                 TMP_FLAG_FAIL_PASS=1
1986                 echo -e "\033[1mOne or more configurations has failed. Check the script log....\033[0m"
1987                 echo -e "\033[31m\033[1m ___  ___ ___ ___ ___ _____   ___ _   ___ _   _   _ ___ ___ \033[0m"
1988                 echo -e "\033[31m\033[1m/ __|/ __| _ \_ _| _ \_   _| | __/_\ |_ _| | | | | | _ \ __|\033[0m"
1989                 echo -e "\033[31m\033[1m\__ \ (__|   /| ||  _/ | |   | _/ _ \ | || |_| |_| |   / _| \033[0m"
1990                 echo -e "\033[31m\033[1m|___/\___|_|_\___|_|   |_|   |_/_/ \_\___|____\___/|_|_\___|\033[0m"
1991         elif [ $RES_PASS = $RES_TEST ]; then
1992                 TMP_FLAG_FAIL_PASS=0
1993                 echo -e "All tests \033[32m\033[1mPASS\033[0m"
1994                 echo -e "\033[32m\033[1m  ___  _   ___ ___ \033[0m"
1995                 echo -e "\033[32m\033[1m | _ \/_\ / __/ __| \033[0m"
1996                 echo -e "\033[32m\033[1m |  _/ _ \\__ \__ \\ \033[0m"
1997                 echo -e "\033[32m\033[1m |_|/_/ \_\___/___/ \033[0m"
1998                 echo ""
1999
2000                 # Update test suite counter
2001                 if [ -f .tmp_tcsuite_pass_ctr ]; then
2002                         tmpval=$(< .tmp_tcsuite_pass_ctr)
2003                         ((tmpval++))
2004                         echo $tmpval > .tmp_tcsuite_pass_ctr
2005                 fi
2006                 if [ -f .tmp_tcsuite_pass ]; then
2007                         echo " - "$ATC " -- "$TC_ONELINE_DESCR"  Execution time: "$duration" seconds" >> .tmp_tcsuite_pass
2008                 fi
2009                 #Create file with OK exit code
2010                 echo "0" > "$AUTOTEST_HOME/.result$ATC.txt"
2011                 echo "0" > "$TESTLOGS/$ATC/.result$ATC.txt"
2012                 echo $(date) > $TESTLOGS/$ATC/endpoint_tc_end.log
2013         else
2014                 TMP_FLAG_FAIL_PASS=1
2015                 echo -e "One or more tests with status  \033[31m\033[1mFAIL\033[0m "
2016                 echo -e "\033[31m\033[1m  ___ _   ___ _    \033[0m"
2017                 echo -e "\033[31m\033[1m | __/_\ |_ _| |   \033[0m"
2018                 echo -e "\033[31m\033[1m | _/ _ \ | || |__ \033[0m"
2019                 echo -e "\033[31m\033[1m |_/_/ \_\___|____|\033[0m"
2020                 echo ""
2021         fi
2022
2023         if [ $TMP_FLAG_FAIL_PASS -ne 0 ]; then
2024                 # Update test suite counter
2025                 if [ -f .tmp_tcsuite_fail_ctr ]; then
2026                         tmpval=$(< .tmp_tcsuite_fail_ctr)
2027                         ((tmpval++))
2028                         echo $tmpval > .tmp_tcsuite_fail_ctr
2029                 fi
2030                 if [ -f .tmp_tcsuite_fail ]; then
2031                         echo " - "$ATC " -- "$TC_ONELINE_DESCR"  Execution time: "$duration" seconds" >> .tmp_tcsuite_fail
2032                 fi
2033         fi
2034
2035         echo "++++ Number of tests:          "$RES_TEST
2036         echo "++++ Number of passed tests:   "$RES_PASS
2037         echo "++++ Number of failed tests:   "$RES_FAIL
2038         echo ""
2039         echo "++++ Number of failed configs: "$RES_CONF_FAIL
2040         echo ""
2041         echo "++++ Number of test case deviations: "$RES_DEVIATION
2042         echo ""
2043         echo "-------------------------------------     Test case complete    ---------------------------------"
2044         echo "-------------------------------------------------------------------------------------------------"
2045         echo ""
2046 }
2047
2048 #####################################################################
2049 ###### Functions for start, configuring, stoping, cleaning etc ######
2050 #####################################################################
2051
2052 # Start timer for time measurement
2053 # args:  <timer message to print>  -  timer value and message will be printed both on screen
2054 #                                     and in the timer measurement report - if at least one "print_timer is called"
2055 start_timer() {
2056         echo -e $BOLD"INFO(${BASH_LINENO[0]}): "${FUNCNAME[0]}"," $@ $EBOLD
2057         TC_TIMER_STARTTIME=$SECONDS
2058         TC_TIMER_TIMER_TEXT="${@:1}"
2059         if [ $# -ne 1 ]; then
2060                 __print_err "need 1 arg,  <timer message to print>" $@
2061                 TC_TIMER_TIMER_TEXT=${FUNCNAME[0]}":"${BASH_LINENO[0]}
2062                 echo " Assigning timer name: "$TC_TIMER_TIMER_TEXT
2063         fi
2064         TC_TIMER_CURRENT_FAILS=$(($RES_FAIL+$RES_CONF_FAIL))
2065         echo " Timer started: $(date)"
2066 }
2067
2068 # Print the running timer  the value of the time (in seconds)
2069 # Timer value and message will be printed both on screen and in the timer measurement report
2070 print_timer() {
2071         echo -e $BOLD"INFO(${BASH_LINENO[0]}): "${FUNCNAME[0]}"," $TC_TIMER_TIMER_TEXT $EBOLD
2072         if [ -z  "$TC_TIMER_STARTTIME" ]; then
2073                 __print_err "timer not started" $@
2074                 return 1
2075         fi
2076         duration=$(($SECONDS-$TC_TIMER_STARTTIME))
2077         if [ $duration -eq 0 ]; then
2078                 duration="<1 second"
2079         else
2080                 duration=$duration" seconds"
2081         fi
2082         echo " Timer duration :" $duration
2083         res="-"
2084         if [ $(($RES_FAIL+$RES_CONF_FAIL)) -ne $TC_TIMER_CURRENT_FAILS ]; then
2085                 res="Failures occured during test - timer not reliabled"
2086         fi
2087
2088         echo -e "$TC_TIMER_TIMER_TEXT \t $duration \t $res" >> $TIMER_MEASUREMENTS
2089 }
2090
2091 # Print info about a deviations from intended tests
2092 # Each deviation counted is also printed in the testreport
2093 # args <deviation message to print>
2094 deviation() {
2095         echo -e $BOLD"DEVIATION(${BASH_LINENO[0]}): "${FUNCNAME[0]} $EBOLD
2096         if [ $# -lt 1 ]; then
2097                 ((RES_CONF_FAIL++))
2098                 __print_err "need 1 or more args,  <deviation message to print>" $@
2099                 exit 1
2100         fi
2101         ((RES_DEVIATION++))
2102         echo -e $BOLD$YELLOW" Test case deviation: ${@:1}"$EYELLOW$EBOLD
2103         echo "Line: ${BASH_LINENO[0]} - ${@:1}" >> $DEVIATION_FILE
2104         __print_current_stats
2105         echo ""
2106 }
2107
2108 # Stop at first FAIL test case and take all logs - only for debugging/trouble shooting
2109 __check_stop_at_error() {
2110         if [ $STOP_AT_ERROR -eq 1 ]; then
2111                 echo -e $RED"Test script configured to stop at first FAIL, taking all logs and stops"$ERED
2112                 store_logs "STOP_AT_ERROR"
2113
2114                 # Update test suite counter
2115                 if [ -f .tmp_tcsuite_fail_ctr ]; then
2116                         tmpval=$(< .tmp_tcsuite_fail_ctr)
2117                         ((tmpval++))
2118                         echo $tmpval > .tmp_tcsuite_fail_ctr
2119                 fi
2120                 if [ -f .tmp_tcsuite_fail ]; then
2121                         echo " - "$ATC " -- "$TC_ONELINE_DESCR"  Execution stopped due to error" >> .tmp_tcsuite_fail
2122                 fi
2123                 exit 1
2124         fi
2125         return 0
2126 }
2127
2128 # Stop and remove all containers
2129 # args: -
2130 # (Not for test scripts)
2131 __clean_containers() {
2132
2133         echo -e $BOLD"Docker clean and stopping and removing all running containers, by container name"$EBOLD
2134
2135         #Create empty file
2136         running_contr_file="./tmp/running_contr.txt"
2137         > $running_contr_file
2138
2139         # Get list of all containers started by the test script
2140         for imagename in $APP_SHORT_NAMES; do
2141                 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
2142         done
2143         running_contr_file_empty="No docker containers running, started by previous test execution"
2144         if [ -s $running_contr_file ]; then
2145                 running_contr_file_empty=""
2146         fi
2147
2148         # Kill all containers started by the test env - to speed up shut down
2149     docker kill $(docker ps -a  --filter "label=nrttest_app" --format '{{.Names}}') &> /dev/null
2150
2151         tab_heading1="App display name"
2152         tab_heading2="App short name"
2153         tab_heading3="Container name"
2154
2155         tab_heading1_len=${#tab_heading1}
2156         tab_heading2_len=${#tab_heading2}
2157         tab_heading3_len=${#tab_heading3}
2158         cntr=0
2159         #Calc field lengths of each item in the list of containers
2160         while read p; do
2161                 if (( $cntr % 3 == 0 ));then
2162                         if [ ${#p} -gt $tab_heading1_len ]; then
2163                                 tab_heading1_len=${#p}
2164                         fi
2165                 fi
2166                 if (( $cntr % 3 == 1));then
2167                         if [ ${#p} -gt $tab_heading2_len ]; then
2168                                 tab_heading2_len=${#p}
2169                         fi
2170                 fi
2171                 if (( $cntr % 3 == 2));then
2172                         if [ ${#p} -gt $tab_heading3_len ]; then
2173                                 tab_heading3_len=${#p}
2174                         fi
2175                 fi
2176                 let cntr=cntr+1
2177         done <$running_contr_file
2178
2179         let tab_heading1_len=tab_heading1_len+2
2180         while (( ${#tab_heading1} < $tab_heading1_len)); do
2181                 tab_heading1="$tab_heading1"" "
2182         done
2183
2184         let tab_heading2_len=tab_heading2_len+2
2185         while (( ${#tab_heading2} < $tab_heading2_len)); do
2186                 tab_heading2="$tab_heading2"" "
2187         done
2188
2189         let tab_heading3_len=tab_heading3_len+2
2190         while (( ${#tab_heading3} < $tab_heading3_len)); do
2191                 tab_heading3="$tab_heading3"" "
2192         done
2193
2194         if [ ! -z "$running_contr_file_empty" ]; then
2195                 echo $running_contr_file_empty | indent1
2196         else
2197                 echo " $tab_heading1$tab_heading2$tab_heading3"" Actions"
2198                 cntr=0
2199                 while read p; do
2200                         if (( $cntr % 3 == 0 ));then
2201                                 row=""
2202                                 heading=$p
2203                                 heading_len=$tab_heading1_len
2204                         fi
2205                         if (( $cntr % 3 == 1));then
2206                                 heading=$p
2207                                 heading_len=$tab_heading2_len
2208                         fi
2209                         if (( $cntr % 3 == 2));then
2210                                 contr=$p
2211                                 heading=$p
2212                                 heading_len=$tab_heading3_len
2213                         fi
2214                         while (( ${#heading} < $heading_len)); do
2215                                 heading="$heading"" "
2216                         done
2217                         row=$row$heading
2218                         if (( $cntr % 3 == 2));then
2219                                 echo -ne $row$SAMELINE
2220                                 echo -ne " $row ${GREEN}stopping...${EGREEN}${SAMELINE}"
2221                                 docker stop $(docker ps -qa --filter name=${contr} --filter network=$DOCKER_SIM_NWNAME) &> /dev/null
2222                                 echo -ne " $row ${GREEN}stopped removing...${EGREEN}${SAMELINE}"
2223                                 docker rm --force $(docker ps -qa --filter name=${contr} --filter network=$DOCKER_SIM_NWNAME) &> /dev/null
2224                                 echo -e  " $row ${GREEN}stopped removed     ${EGREEN}"
2225                         fi
2226                         let cntr=cntr+1
2227                 done <$running_contr_file
2228         fi
2229
2230         echo ""
2231
2232         echo -e $BOLD" Removing docker network"$EBOLD
2233         TMP=$(docker network ls -q --filter name=$DOCKER_SIM_NWNAME)
2234         if [ "$TMP" ==  $DOCKER_SIM_NWNAME ]; then
2235                 docker network rm $DOCKER_SIM_NWNAME | indent2
2236                 if [ $? -ne 0 ];  then
2237                         echo -e $RED" Cannot remove docker network. Manually remove or disconnect containers from $DOCKER_SIM_NWNAME"$ERED
2238                         exit 1
2239                 fi
2240         fi
2241         echo -e "$GREEN  Done$EGREEN"
2242
2243         echo -e $BOLD" Removing all unused docker neworks"$EBOLD
2244         docker network prune --force | indent2
2245         echo -e "$GREEN  Done$EGREEN"
2246
2247         echo -e $BOLD" Removing all unused docker volumes"$EBOLD
2248         docker volume prune --force | indent2
2249         echo -e "$GREEN  Done$EGREEN"
2250
2251         echo -e $BOLD" Removing all dangling/untagged docker images"$EBOLD
2252     docker rmi --force $(docker images -q -f dangling=true) &> /dev/null
2253         echo -e "$GREEN  Done$EGREEN"
2254         echo ""
2255
2256         CONTRS=$(docker ps | awk '$1 != "CONTAINER" { n++ }; END { print n+0 }')
2257         if [ $? -eq 0 ]; then
2258                 if [ $CONTRS -ne 0 ]; then
2259                         echo -e $RED"Containers running, may cause distubance to the test case"$ERED
2260                         docker ps -a | indent1
2261                         echo ""
2262                 fi
2263         fi
2264 }
2265
2266 ###################################
2267 ### Functions for kube management
2268 ###################################
2269
2270 # Get resource type for scaling
2271 # args: <resource-name> <namespace>
2272 __kube_get_resource_type() {
2273         kubectl $KUBECONF get deployment $1 -n $2 1> /dev/null 2> ./tmp/kubeerr
2274         if [ $? -eq 0 ]; then
2275                 echo "deployment"
2276                 return 0
2277         fi
2278         kubectl $KUBECONF get sts $1 -n $2 1> /dev/null 2> ./tmp/kubeerr
2279         if [ $? -eq 0 ]; then
2280                 echo "sts"
2281                 return 0
2282         fi
2283         echo "unknown-resource-type"
2284         return 1
2285 }
2286
2287 # Scale a kube resource to a specific count
2288 # args: <resource-type> <resource-name> <namespace> <target-count>
2289 # (Not for test scripts)
2290 __kube_scale() {
2291         echo -ne "  Setting $1 $2 replicas=$4 in namespace $3"$SAMELINE
2292         kubectl $KUBECONF scale  $1 $2  -n $3 --replicas=$4 1> /dev/null 2> ./tmp/kubeerr
2293         if [ $? -ne 0 ]; then
2294                 echo -e "  Setting $1 $2 replicas=$4 in namespace $3 $RED Failed $ERED"
2295                 ((RES_CONF_FAIL++))
2296                 echo "  Message: $(<./tmp/kubeerr)"
2297                 return 1
2298         else
2299                 echo -e "  Setting $1 $2 replicas=$4 in namespace $3 $GREEN OK $EGREEN"
2300         fi
2301
2302         TSTART=$SECONDS
2303
2304         for i in {1..500}; do
2305                 count=$(kubectl $KUBECONF get $1/$2  -n $3 -o jsonpath='{.status.replicas}' 2> /dev/null)
2306                 retcode=$?
2307                 if [ -z "$count" ]; then
2308                         #No value is sometimes returned for some reason, in case the resource has replica 0
2309                         count=0
2310                 fi
2311                 if [ $retcode -ne 0 ]; then
2312                         echo -e "$RED  Cannot fetch current replica count for $1 $2 in namespace $3 $ERED"
2313                         ((RES_CONF_FAIL++))
2314                         return 1
2315                 fi
2316                 #echo ""
2317                 if [ $count -ne $4 ]; then
2318                         echo -ne "  Waiting for $1 $2 replicas=$4 in namespace $3. Replicas=$count after $(($SECONDS-$TSTART)) seconds $SAMELINE"
2319                         sleep $i
2320                 else
2321                         echo -e "  Waiting for $1 $2 replicas=$4 in namespace $3. Replicas=$count after $(($SECONDS-$TSTART)) seconds"
2322                         echo -e "  Replicas=$4 after $(($SECONDS-$TSTART)) seconds $GREEN OK $EGREEN"
2323                         echo ""
2324                         return 0
2325                 fi
2326         done
2327         echo ""
2328         echo -e "$RED  Replica count did not reach target replicas=$4. Failed with replicas=$count $ERED"
2329         ((RES_CONF_FAIL++))
2330         return 0
2331 }
2332
2333 # Scale all kube resource sets to 0 in a namespace for resources having a certain lable and label-id
2334 # This function does not wait for the resource to reach 0
2335 # args: <namespace> <label-name> <label-id>
2336 # (Not for test scripts)
2337 __kube_scale_all_resources() {
2338         namespace=$1
2339         labelname=$2
2340         labelid=$3
2341         resources="deployment replicaset statefulset"
2342         for restype in $resources; do
2343                 result=$(kubectl $KUBECONF get $restype -n $namespace -o jsonpath='{.items[?(@.metadata.labels.'$labelname'=="'$labelid'")].metadata.name}')
2344                 if [ $? -eq 0 ] && [ ! -z "$result" ]; then
2345                         for resid in $result; do
2346                                 echo -ne "  Ordered scaling $restype $resid in namespace $namespace with label $labelname=$labelid to 0"$SAMELINE
2347                                 kubectl $KUBECONF scale  $restype $resid  -n $namespace --replicas=0 1> /dev/null 2> ./tmp/kubeerr
2348                                 echo -e "  Ordered scaling $restype $resid in namespace $namespace with label $labelname=$labelid to 0 $GREEN OK $EGREEN"
2349                         done
2350                 fi
2351         done
2352 }
2353
2354 # Scale all kube resource sets to 0 in a namespace for resources having a certain lable and an optional label-id
2355 # This function do wait for the resource to reach 0
2356 # args: <namespace> <label-name> [ <label-id> ]
2357 # (Not for test scripts)
2358 __kube_scale_and_wait_all_resources() {
2359         namespace=$1
2360         labelname=$2
2361         labelid=$3
2362         if [ -z "$3" ]; then
2363                 echo "  Attempt to scale - deployment replicaset statefulset - in namespace $namespace with label $labelname"
2364         else
2365                 echo "  Attempt to scale - deployment replicaset statefulset - in namespace $namespace with label $labelname=$labelid"
2366         fi
2367         resources="deployment replicaset statefulset"
2368         scaled_all=1
2369         while [ $scaled_all -ne 0 ]; do
2370                 scaled_all=0
2371                 for restype in $resources; do
2372                     if [ -z "$3" ]; then
2373                                 result=$(kubectl $KUBECONF get $restype -n $namespace -o jsonpath='{.items[?(@.metadata.labels.'$labelname')].metadata.name}')
2374                         else
2375                                 result=$(kubectl $KUBECONF get $restype -n $namespace -o jsonpath='{.items[?(@.metadata.labels.'$labelname'=="'$labelid'")].metadata.name}')
2376                         fi
2377                         if [ $? -eq 0 ] && [ ! -z "$result" ]; then
2378                                 for resid in $result; do
2379                                         echo -e "   Ordered scaling $restype $resid in namespace $namespace with label $labelname=$labelid to 0"
2380                                         kubectl $KUBECONF scale  $restype $resid  -n $namespace --replicas=0 1> /dev/null 2> ./tmp/kubeerr
2381                                         count=1
2382                                         T_START=$SECONDS
2383                                         while [ $count -ne 0 ]; do
2384                                                 count=$(kubectl $KUBECONF get $restype $resid  -n $namespace -o jsonpath='{.status.replicas}' 2> /dev/null)
2385                                                 echo -ne "    Scaling $restype $resid in namespace $namespace with label $labelname=$labelid to 0, current count=$count"$SAMELINE
2386                                                 if [ $? -eq 0 ] && [ ! -z "$count" ]; then
2387                                                         sleep 0.5
2388                                                 else
2389                                                         count=0
2390                                                 fi
2391                                                 duration=$(($SECONDS-$T_START))
2392                                                 if [ $duration -gt 100 ]; then
2393                                                         #Forcring count 0, to avoid hanging for failed scaling
2394                                                         scaled_all=1
2395                                                         count=0
2396                                                 fi
2397                                         done
2398                                         echo -e "    Scaled $restype $resid in namespace $namespace with label $labelname=$labelid to 0, current count=$count $GREEN OK $EGREEN"
2399                                 done
2400                         fi
2401                 done
2402         done
2403 }
2404
2405 # Remove all kube resources in a namespace for resources having a certain label and label-id
2406 # This function wait until the resources are gone. Scaling to 0 must have been ordered previously
2407 # args: <namespace> <label-name> <label-id>
2408 # (Not for test scripts)
2409 __kube_delete_all_resources() {
2410         namespace=$1
2411         labelname=$2
2412         labelid=$3
2413         resources="deployments replicaset statefulset services pods configmaps persistentvolumeclaims persistentvolumes serviceaccounts clusterrolebindings secrets authorizationpolicies requestauthentications"
2414         deleted_resourcetypes=""
2415         for restype in $resources; do
2416                 ns_flag="-n $namespace"
2417                 ns_text="in namespace $namespace"
2418                 if [ $restype == "persistentvolumes" ]; then
2419                         ns_flag=""
2420                         ns_text=""
2421                 fi
2422                 if [ $restype == "clusterrolebindings" ]; then
2423                         ns_flag=""
2424                         ns_text=""
2425                 fi
2426                 result=$(kubectl $KUBECONF get $restype $ns_flag -o jsonpath='{.items[?(@.metadata.labels.'$labelname'=="'$labelid'")].metadata.name}' 2> /dev/null)
2427                 if [ $? -eq 0 ] && [ ! -z "$result" ]; then
2428                         deleted_resourcetypes=$deleted_resourcetypes" "$restype
2429                         for resid in $result; do
2430                                 if [ $restype == "replicaset" ] || [ $restype == "statefulset" ]; then
2431                                         count=1
2432                                         while [ $count -ne 0 ]; do
2433                                                 count=$(kubectl $KUBECONF get $restype $resid  $ns_flag -o jsonpath='{.status.replicas}' 2> /dev/null)
2434                                                 echo -ne "  Scaling $restype $resid $ns_text with label $labelname=$labelid to 0, current count=$count"$SAMELINE
2435                                                 if [ $? -eq 0 ] && [ ! -z "$count" ]; then
2436                                                         sleep 0.5
2437                                                 else
2438                                                         count=0
2439                                                 fi
2440                                         done
2441                                         echo -e "  Scaled $restype $resid $ns_text with label $labelname=$labelid to 0, current count=$count $GREEN OK $EGREEN"
2442                                 fi
2443                                 echo -ne "  Deleting $restype $resid $ns_text with label $labelname=$labelid "$SAMELINE
2444                                 kubectl $KUBECONF delete --grace-period=1 $restype $resid $ns_flag 1> /dev/null 2> ./tmp/kubeerr
2445                                 if [ $? -eq 0 ]; then
2446                                         echo -e "  Deleted $restype $resid $ns_text with label $labelname=$labelid $GREEN OK $EGREEN"
2447                                 else
2448                                         echo -e "  Deleted $restype $resid $ns_text with label $labelname=$labelid $GREEN Does not exist - OK $EGREEN"
2449                                 fi
2450                                 #fi
2451                         done
2452                 fi
2453         done
2454         if [ ! -z "$deleted_resourcetypes" ]; then
2455                 for restype in $deleted_resources; do
2456                         ns_flag="-n $namespace"
2457                         ns_text="in namespace $namespace"
2458                         if [ $restype == "persistentvolumes" ]; then
2459                                 ns_flag=""
2460                                 ns_text=""
2461                         fi
2462                         echo -ne "  Waiting for $restype $ns_text with label $labelname=$labelid to be deleted..."$SAMELINE
2463                         T_START=$SECONDS
2464                         result="dummy"
2465                         while [ ! -z "$result" ]; do
2466                                 sleep 0.5
2467                                 result=$(kubectl $KUBECONF get $restype $ns_flag -o jsonpath='{.items[?(@.metadata.labels.'$labelname'=="'$labelid'")].metadata.name}')
2468                                 echo -ne "  Waiting for $restype $ns_text with label $labelname=$labelid to be deleted...$(($SECONDS-$T_START)) seconds "$SAMELINE
2469                                 if [ -z "$result" ]; then
2470                                         echo -e " Waiting for $restype $ns_text with label $labelname=$labelid to be deleted...$(($SECONDS-$T_START)) seconds $GREEN OK $EGREEN"
2471                                 elif [ $(($SECONDS-$T_START)) -gt 300 ]; then
2472                                         echo -e " Waiting for $restype $ns_text with label $labelname=$labelid to be deleted...$(($SECONDS-$T_START)) seconds $RED Failed $ERED"
2473                                         result=""
2474                                 fi
2475                         done
2476                 done
2477         fi
2478 }
2479
2480 # Creates a namespace if it does not exists
2481 # args: <namespace>
2482 # (Not for test scripts)
2483 __kube_create_namespace() {
2484
2485         #Check if test namespace exists, if not create it
2486         kubectl $KUBECONF get namespace $1 1> /dev/null 2> ./tmp/kubeerr
2487         if [ $? -ne 0 ]; then
2488                 echo -ne " Creating namespace "$1 $SAMELINE
2489                 kubectl $KUBECONF create namespace $1 1> /dev/null 2> ./tmp/kubeerr
2490                 if [ $? -ne 0 ]; then
2491                         echo -e " Creating namespace $1 $RED$BOLD FAILED $EBOLD$ERED"
2492                         ((RES_CONF_FAIL++))
2493                         echo "  Message: $(<./tmp/kubeerr)"
2494                         return 1
2495                 else
2496                         kubectl $KUBECONF label ns $1 autotest=engine > /dev/null
2497                         echo -e " Creating namespace $1 $GREEN$BOLD OK $EBOLD$EGREEN"
2498                 fi
2499         else
2500                 echo -e " Creating namespace $1 $GREEN$BOLD Already exists, OK $EBOLD$EGREEN"
2501         fi
2502         return 0
2503 }
2504
2505 # Removes a namespace if it exists
2506 # args: <namespace>
2507 # (Not for test scripts)
2508 __kube_delete_namespace() {
2509
2510         #Check if test namespace exists, if so remove it
2511         kubectl $KUBECONF get namespace $1 1> /dev/null 2> ./tmp/kubeerr
2512         if [ $? -eq 0 ]; then
2513                 echo -ne " Removing namespace "$1 $SAMELINE
2514                 kubectl $KUBECONF delete namespace $1 1> /dev/null 2> ./tmp/kubeerr
2515                 if [ $? -ne 0 ]; then
2516                         echo -e " Removing namespace $1 $RED$BOLD FAILED $EBOLD$ERED"
2517                         ((RES_CONF_FAIL++))
2518                         echo "  Message: $(<./tmp/kubeerr)"
2519                         return 1
2520                 else
2521                         echo -e " Removing namespace $1 $GREEN$BOLD OK $EBOLD$EGREEN"
2522                 fi
2523         else
2524                 echo -e " Namespace $1 $GREEN$BOLD does not exist, OK $EBOLD$EGREEN"
2525         fi
2526         return 0
2527 }
2528
2529 # Removes and re-create a namespace
2530 # args: <namespace>
2531 # (Not for test scripts)
2532 clean_and_create_namespace() {
2533         __log_conf_start $@
2534
2535     if [ $# -ne 1 ]; then
2536                 __print_err "<namespace>" $@
2537                 return 1
2538         fi
2539         __kube_delete_namespace $1
2540         if [ $? -ne 0 ]; then
2541                 return 1
2542         fi
2543         __kube_create_namespace $1
2544         if [ $? -ne 0 ]; then
2545                 return 1
2546         fi
2547 }
2548
2549 # Add/remove label on non-namespaced kube object
2550 # args: <api> <instance> <label>
2551 # (Not for test scripts)
2552 __kube_label_non_ns_instance() {
2553         kubectl $KUBECONF label $1 $2 "$3" 1> /dev/null 2> ./tmp/kubeerr
2554         return $?
2555 }
2556
2557 # Add/remove label on namespaced kube object
2558 # args: <api> <instance> <namespace> <label>
2559 # (Not for test scripts)
2560 __kube_label_ns_instance() {
2561         kubectl $KUBECONF label $1 $2 -n $3 "$4" 1> /dev/null 2> ./tmp/kubeerr
2562         return $?
2563 }
2564
2565 # Find the host ip of an app (using the service resource)
2566 # args: <app-name> <namespace>
2567 # (Not for test scripts)
2568 __kube_get_service_host() {
2569         if [ $# -ne 2 ]; then
2570                 ((RES_CONF_FAIL++))
2571         __print_err "need 2 args, <app-name> <namespace>" $@
2572                 exit 1
2573         fi
2574         for timeout in {1..60}; do
2575                 host=$(kubectl $KUBECONF get svc $1  -n $2 -o jsonpath='{.spec.clusterIP}')
2576                 if [ $? -eq 0 ]; then
2577                         if [ ! -z "$host" ]; then
2578                                 echo $host
2579                                 return 0
2580                         fi
2581                 fi
2582                 sleep 0.5
2583         done
2584         ((RES_CONF_FAIL++))
2585         echo "host-not-found-fatal-error"
2586         return 1
2587 }
2588
2589 # Find the named port to an app (using the service resource)
2590 # args: <app-name> <namespace> <port-name>
2591 # (Not for test scripts)
2592 __kube_get_service_port() {
2593         if [ $# -ne 3 ]; then
2594                 ((RES_CONF_FAIL++))
2595         __print_err "need 3 args, <app-name> <namespace> <port-name>" $@
2596                 exit 1
2597         fi
2598
2599         for timeout in {1..60}; do
2600                 port=$(kubectl $KUBECONF get svc $1  -n $2 -o jsonpath='{...ports[?(@.name=="'$3'")].port}')
2601                 if [ $? -eq 0 ]; then
2602                         if [ ! -z "$port" ]; then
2603                                 echo $port
2604                                 return 0
2605                         fi
2606                 fi
2607                 sleep 0.5
2608         done
2609         ((RES_CONF_FAIL++))
2610         echo "0"
2611         return 1
2612 }
2613
2614 # Find the named node port to an app (using the service resource)
2615 # args: <app-name> <namespace> <port-name>
2616 # (Not for test scripts)
2617 __kube_get_service_nodeport() {
2618         if [ $# -ne 3 ]; then
2619                 ((RES_CONF_FAIL++))
2620         __print_err "need 3 args, <app-name> <namespace> <port-name>" $@
2621                 exit 1
2622         fi
2623
2624         for timeout in {1..60}; do
2625                 port=$(kubectl $KUBECONF get svc $1  -n $2 -o jsonpath='{...ports[?(@.name=="'$3'")].nodePort}')
2626                 if [ $? -eq 0 ]; then
2627                         if [ ! -z "$port" ]; then
2628                                 echo $port
2629                                 return 0
2630                         fi
2631                 fi
2632                 sleep 0.5
2633         done
2634         ((RES_CONF_FAIL++))
2635         echo "0"
2636         return 1
2637 }
2638
2639 # Create a kube resource from a yaml template
2640 # args: <resource-type> <resource-name> <template-yaml> <output-yaml>
2641 # (Not for test scripts)
2642 __kube_create_instance() {
2643         echo -ne " Creating $1 $2"$SAMELINE
2644         envsubst < $3 > $4
2645         kubectl $KUBECONF apply -f $4 1> /dev/null 2> ./tmp/kubeerr
2646         if [ $? -ne 0 ]; then
2647                 ((RES_CONF_FAIL++))
2648                 echo -e " Creating $1 $2 $RED Failed $ERED"
2649                 echo "  Message: $(<./tmp/kubeerr)"
2650                 return 1
2651         else
2652                 echo -e " Creating $1 $2 $GREEN OK $EGREEN"
2653         fi
2654 }
2655
2656 # Function to create a configmap in kubernetes
2657 # args: <configmap-name> <namespace> <labelname> <labelid> <path-to-data-file> <path-to-output-yaml>
2658 # (Not for test scripts)
2659 __kube_create_configmap() {
2660         echo -ne " Creating configmap $1 "$SAMELINE
2661         envsubst < $5 > $5"_tmp"
2662         cp $5"_tmp" $5  #Need to copy back to orig file name since create configmap neeed the original file name
2663         kubectl $KUBECONF create configmap $1  -n $2 --from-file=$5 --dry-run=client -o yaml > $6
2664         if [ $? -ne 0 ]; then
2665                 echo -e " Creating configmap $1 $RED Failed $ERED"
2666                 ((RES_CONF_FAIL++))
2667                 return 1
2668         fi
2669
2670         kubectl $KUBECONF apply -f $6 1> /dev/null 2> ./tmp/kubeerr
2671         if [ $? -ne 0 ]; then
2672                 echo -e " Creating configmap $1 $RED Apply failed $ERED"
2673                 echo "  Message: $(<./tmp/kubeerr)"
2674                 ((RES_CONF_FAIL++))
2675                 return 1
2676         fi
2677         kubectl $KUBECONF label configmap $1 -n $2 $3"="$4 --overwrite 1> /dev/null 2> ./tmp/kubeerr
2678         if [ $? -ne 0 ]; then
2679                 echo -e " Creating configmap $1 $RED Labeling failed $ERED"
2680                 echo "  Message: $(<./tmp/kubeerr)"
2681                 ((RES_CONF_FAIL++))
2682                 return 1
2683         fi
2684         # Log the resulting map
2685         kubectl $KUBECONF get configmap $1 -n $2 -o yaml > $6
2686
2687         echo -e " Creating configmap $1 $GREEN OK $EGREEN"
2688         return 0
2689 }
2690
2691 # This function runs a kubectl cmd where a single output value is expected, for example get ip with jsonpath filter.
2692 # The function retries up to the timeout given in the cmd flag '--cluster-timeout'
2693 # args: <full kubectl cmd with parameters>
2694 # (Not for test scripts)
2695 __kube_cmd_with_timeout() {
2696         TS_TMP=$(($SECONDS+$CLUSTER_TIME_OUT))
2697
2698         while true; do
2699                 kube_cmd_result=$($@)
2700                 if [ $? -ne 0 ]; then
2701                         kube_cmd_result=""
2702                 fi
2703                 if [ $SECONDS -ge $TS_TMP ] || [ ! -z "$kube_cmd_result" ] ; then
2704                         echo $kube_cmd_result
2705                         return 0
2706                 fi
2707                 sleep 1
2708         done
2709 }
2710
2711 # This function starts a pod that cleans a the contents of a path mounted as a pvc
2712 # After this action the pod should terminate
2713 # This should only be executed when the pod owning the pvc is not running
2714 # args: <appname> <namespace> <pvc-name> <path-to remove>
2715 # (Not for test scripts)
2716 __kube_clean_pvc() {
2717
2718         #using env vars setup in pvccleaner_api_functions.sh
2719
2720         export PVC_CLEANER_NAMESPACE=$2
2721         export PVC_CLEANER_CLAIMNAME=$3
2722         export PVC_CLEANER_RM_PATH=$4
2723         export PVC_CLEANER_APP_NAME
2724         input_yaml=$SIM_GROUP"/"$PVC_CLEANER_COMPOSE_DIR"/"pvc-cleaner.yaml
2725         output_yaml=$PWD/tmp/$2-pvc-cleaner.yaml
2726
2727         envsubst < $input_yaml > $output_yaml
2728
2729         kubectl $KUBECONF delete -f $output_yaml 1> /dev/null 2> /dev/null   # Delete the previous terminated pod - if existing
2730
2731         __kube_create_instance pod $PVC_CLEANER_APP_NAME $input_yaml $output_yaml
2732         if [ $? -ne 0 ]; then
2733                 echo $YELLOW" Could not clean pvc for app: $1 - persistent storage not clean - tests may not work"
2734                 return 1
2735         fi
2736
2737         term_ts=$(($SECONDS+30))
2738         while [ $term_ts -gt $SECONDS ]; do
2739                 pod_status=$(kubectl $KUBECONF get pod pvc-cleaner -n $PVC_CLEANER_NAMESPACE --no-headers -o custom-columns=":status.phase")
2740                 if [ "$pod_status" == "Succeeded" ]; then
2741                         return 0
2742                 fi
2743         done
2744         return 1
2745 }
2746
2747 # This function scales or deletes all resources for app selected by the testcase.
2748 # args: -
2749 # (Not for test scripts)
2750 __clean_kube() {
2751         echo -e $BOLD"Initialize kube pods/statefulsets/replicaset to initial state"$EBOLD
2752
2753         # Scale prestarted or managed apps
2754         for imagename in $APP_SHORT_NAMES; do
2755                 # A function name is created from the app short name
2756                 # for example app short name 'RICMSIM' -> produce the function
2757                 # name __RICSIM_kube_scale_zero or __RICSIM_kube_scale_zero_and_wait
2758                 # This function is called and is expected to exist in the imported
2759                 # file for the ricsim test functions
2760                 # The resulting function impl shall scale the resources to 0
2761                 # For prestarted apps, the function waits until the resources are 0
2762                 # For included (not prestated) apps, the scaling is just ordered
2763                 __check_prestarted_image $imagename
2764                 if [ $? -eq 0 ]; then
2765                         function_pointer="__"$imagename"_kube_scale_zero_and_wait"
2766                         echo -e " Scaling all kube resources for app $BOLD $imagename $EBOLD to 0"
2767                         $function_pointer
2768                 else
2769                         __check_included_image $imagename
2770                         if [ $? -eq 0 ]; then
2771                                 function_pointer="__"$imagename"_kube_scale_zero"
2772                                 echo -e " Scaling all kube resources for app $BOLD $imagename $EBOLD to 0"
2773                                 $function_pointer
2774                         fi
2775                 fi
2776         done
2777
2778         # Delete managed apps
2779         for imagename in $APP_SHORT_NAMES; do
2780                 __check_included_image $imagename
2781                 if [ $? -eq 0 ]; then
2782                         __check_prestarted_image $imagename
2783                         if [ $? -ne 0 ]; then
2784                                 # A function name is created from the app short name
2785                                 # for example app short name 'RICMSIM' -> produce the function
2786                                 # name __RICSIM__kube_delete_all
2787                                 # This function is called and is expected to exist in the imported
2788                                 # file for the ricsim test functions
2789                                 # The resulting function impl shall delete all its resources
2790                                 function_pointer="__"$imagename"_kube_delete_all"
2791                                 echo -e " Deleting all kube resources for app $BOLD $imagename $EBOLD"
2792                                 $function_pointer
2793                         fi
2794                 fi
2795         done
2796
2797         # Remove istio label on namespaces
2798         test_env_namespaces=$(kubectl $KUBECONF get ns  --no-headers -o custom-columns=":metadata.name" -l autotest=engine -l istio-injection=enabled) #Get list of ns created by the test env
2799         if [ $? -ne 0 ]; then
2800                 echo " Cannot get list of namespaces...continues.."
2801         else
2802                 for test_env_ns in $test_env_namespaces; do
2803                         echo " Removing istio label on ns: "$test_env_ns
2804                         __kube_label_non_ns_instance ns $test_env_ns "istio-injection-"
2805                 done
2806         fi
2807
2808         echo ""
2809 }
2810
2811 # Function stop and remove all containers (docker) and services/deployments etc(kube)
2812 # args: -
2813 # Function for test script
2814 clean_environment() {
2815         if [ $RUNMODE == "KUBE" ]; then
2816                 __clean_kube
2817                 if [ $PRE_CLEAN -eq 1 ]; then
2818                         echo " Cleaning docker resouces to free up resources, may take time..."
2819                         ../common/clean_docker.sh 2>&1 > /dev/null
2820                         echo ""
2821                 fi
2822         else
2823                 __clean_containers
2824                 if [ $PRE_CLEAN -eq 1 ]; then
2825                         echo " Cleaning kubernetes resouces to free up resources, may take time..."
2826                         ../common/clean_kube.sh $KUBECONF 2>&1 > /dev/null
2827                         echo ""
2828                 fi
2829         fi
2830 }
2831
2832 # 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
2833 # args: -
2834 # (Function for test scripts)
2835 auto_clean_environment() {
2836         echo
2837         if [ "$AUTO_CLEAN" == "auto" ]; then
2838                 echo -e $BOLD"Initiating automatic cleaning of environment"$EBOLD
2839                 clean_environment
2840         fi
2841 }
2842
2843 # Function to sleep a test case for a numner of seconds. Prints the optional text args as info
2844 # args: <sleep-time-in-sec> [any-text-in-quotes-to-be-printed]
2845 # (Function for test scripts)
2846 sleep_wait() {
2847
2848         echo -e $BOLD"INFO(${BASH_LINENO[0]}): "${FUNCNAME[0]}"," $@ $EBOLD
2849         if [ $# -lt 1 ]; then
2850                 ((RES_CONF_FAIL++))
2851                 __print_err "need at least one arg, <sleep-time-in-sec> [any-text-to-printed]" $@
2852                 exit 1
2853         fi
2854         #echo "---- Sleep for " $1 " seconds ---- "$2
2855         start=$SECONDS
2856         duration=$((SECONDS-start))
2857         while [ $duration -lt $1 ]; do
2858                 echo -ne "  Slept for ${duration} seconds${SAMELINE}"
2859                 sleep 1
2860                 duration=$((SECONDS-start))
2861         done
2862         echo -ne "  Slept for ${duration} seconds${SAMELINE}"
2863         echo ""
2864 }
2865
2866 # Print error info for the call in the parent script (test case). Arg: <error-message-to-print>
2867 # Not to be called from the test script itself.
2868 __print_err() {
2869     echo -e $RED ${FUNCNAME[1]} " "$1" " ${BASH_SOURCE[2]} " line" ${BASH_LINENO[1]} $ERED
2870         if [ $# -gt 1 ]; then
2871                 echo -e $RED" Got: "${FUNCNAME[1]} ${@:2} $ERED
2872         fi
2873         ((RES_CONF_FAIL++))
2874         __check_stop_at_error
2875 }
2876
2877 # Function to create the docker network for the test
2878 # Not to be called from the test script itself.
2879 __create_docker_network() {
2880         tmp=$(docker network ls --format={{.Name}} --filter name=$DOCKER_SIM_NWNAME)
2881         if [ $? -ne 0 ]; then
2882                 echo -e $RED" Could not check if docker network $DOCKER_SIM_NWNAME exists"$ERED
2883                 return 1
2884         fi
2885         if [ "$tmp" != $DOCKER_SIM_NWNAME ]; then
2886                 echo -e " Creating docker network:$BOLD $DOCKER_SIM_NWNAME $EBOLD"
2887                 docker network create $DOCKER_SIM_NWNAME | indent2
2888                 if [ $? -ne 0 ]; then
2889                         echo -e $RED" Could not create docker network $DOCKER_SIM_NWNAME"$ERED
2890                         return 1
2891                 else
2892                         echo -e "$GREEN  Done$EGREEN"
2893                 fi
2894         else
2895                 echo -e " Docker network $DOCKER_SIM_NWNAME already exists$GREEN OK $EGREEN"
2896         fi
2897 }
2898
2899 # Function to start container with docker-compose and wait until all are in state running.
2900 # If the <docker-compose-file> is empty, the default 'docker-compose.yml' is assumed.
2901 #args: <docker-compose-dir> <docker-compose-file> <docker-compose-arg>|NODOCKERARGS <count> <app-name>+
2902 # (Not for test scripts)
2903 __start_container() {
2904
2905         if [ $# -lt 5 ]; then
2906                 ((RES_CONF_FAIL++))
2907         __print_err "need 5 or more args, <docker-compose-dir> <docker-compose-file> <docker-compose-arg>|NODOCKERARGS <count> <app-name>+" $@
2908                 exit 1
2909         fi
2910
2911         __create_docker_network
2912
2913         curdir=$PWD
2914         cd $SIM_GROUP
2915         compose_dir=$1
2916         cd $1
2917         shift
2918         compose_file=$1
2919         if [ -z "$compose_file" ]; then
2920                 compose_file="docker-compose.yml"
2921         fi
2922         shift
2923         compose_args=$1
2924         shift
2925         appcount=$1
2926         shift
2927
2928         envsubst < $compose_file > "gen_"$compose_file
2929         compose_file="gen_"$compose_file
2930         if [ $DOCKER_COMPOSE_VERSION == "V1" ]; then
2931                 docker_compose_cmd="docker-compose"
2932         else
2933                 docker_compose_cmd="docker compose"
2934         fi
2935
2936         if [ "$compose_args" == "NODOCKERARGS" ]; then
2937                 $docker_compose_cmd -f $compose_file up -d &> .dockererr
2938                 if [ $? -ne 0 ]; then
2939                         echo -e $RED"Problem to launch container(s) with docker-compose"$ERED
2940                         cat .dockererr
2941                         echo -e $RED"Stopping script...."$ERED
2942                         exit 1
2943                 fi
2944         else
2945                 $docker_compose_cmd -f $compose_file up -d $compose_args &> .dockererr
2946                 if [ $? -ne 0 ]; then
2947                         echo -e $RED"Problem to launch container(s) with docker-compose"$ERED
2948                         cat .dockererr
2949                         echo -e $RED"Stopping script...."$ERED
2950                         exit 1
2951                 fi
2952         fi
2953
2954         cd $curdir
2955
2956         appindex=0
2957         while [ $appindex -lt $appcount ]; do
2958                 appname=$1
2959                 shift
2960                 app_started=0
2961                 for i in {1..10}; do
2962                         if [ "$(docker inspect --format '{{ .State.Running }}' $appname)" == "true" ]; then
2963                                         echo -e " Container $BOLD${appname}$EBOLD$GREEN running$EGREEN on$BOLD image $(docker inspect --format '{{ .Config.Image }}' ${appname}) $EBOLD"
2964                                         app_started=1
2965                                         break
2966                                 else
2967                                         sleep $i
2968                         fi
2969                 done
2970                 if [ $app_started -eq 0 ]; then
2971                         ((RES_CONF_FAIL++))
2972                         echo ""
2973                         echo -e $RED" Container $BOLD${appname}$EBOLD could not be started"$ERED
2974                         echo -e $RED" Stopping script..."$ERED
2975                         exit 1
2976                 fi
2977                 let appindex=appindex+1
2978         done
2979         return 0
2980 }
2981
2982 # Function to check if container/service is responding to http/https
2983 # args: <container-name>|<service-name> url
2984 # (Not for test scripts)
2985 __check_service_start() {
2986
2987         if [ $# -ne 2 ]; then
2988                 ((RES_CONF_FAIL++))
2989                 __print_err "need 2 args, <container-name>|<service-name> url" $@
2990                 return 1
2991         fi
2992
2993         if [ $RUNMODE == "KUBE" ]; then
2994                 ENTITY="service/set/deployment"
2995         else
2996                 ENTITY="container"
2997         fi
2998         appname=$1
2999         url=$2
3000         echo -ne " Container $BOLD${appname}$EBOLD starting${SAMELINE}"
3001
3002
3003         a1pmsst=false
3004         echo -ne " Waiting for ${ENTITY} ${appname} service status...${SAMELINE}"
3005         TSTART=$SECONDS
3006         loop_ctr=0
3007         while (( $TSTART+600 > $SECONDS )); do
3008                 result="$(__do_curl -m 10 $url)"
3009                 if [ $? -eq 0 ]; then
3010                         if [ ${#result} -gt 15 ]; then
3011                                 #If response is too long, truncate
3012                                 result="...response text too long, omitted"
3013                         fi
3014                         echo -ne " Waiting for {ENTITY} $BOLD${appname}$EBOLD service status on ${3}, result: $result${SAMELINE}"
3015                         echo -ne " The ${ENTITY} $BOLD${appname}$EBOLD$GREEN is alive$EGREEN, responds to service status:$GREEN $result $EGREEN on ${url} after $(($SECONDS-$TSTART)) seconds"
3016                         a1pmsst=true
3017                         break
3018                 else
3019                         TS_TMP=$SECONDS
3020                         TS_OFFSET=$loop_ctr
3021                         if (( $TS_OFFSET > 5 )); then
3022                                 TS_OFFSET=5
3023                         fi
3024                         while [ $(($TS_TMP+$TS_OFFSET)) -gt $SECONDS ]; do
3025                                 echo -ne " Waiting for ${ENTITY} ${appname} service status on ${url}...$(($SECONDS-$TSTART)) seconds, retrying in $(($TS_TMP+$TS_OFFSET-$SECONDS)) seconds   ${SAMELINE}"
3026                                 sleep 1
3027                         done
3028                 fi
3029                 let loop_ctr=loop_ctr+1
3030         done
3031
3032         if [ "$a1pmsst" = "false"  ]; then
3033                 ((RES_CONF_FAIL++))
3034                 echo -e $RED" The ${ENTITY} ${appname} did not respond to service status on ${url} in $(($SECONDS-$TSTART)) seconds"$ERED
3035                 return 1
3036         fi
3037
3038         echo ""
3039         return 0
3040 }
3041
3042
3043 #################
3044 ### Log functions
3045 #################
3046
3047 __check_container_logs() {
3048
3049         dispname=$1
3050         appname=$2
3051         logpath=$3
3052         warning=$4
3053         error=$5
3054
3055         echo -e $BOLD"Checking $dispname container $appname log ($logpath) for WARNINGs and ERRORs"$EBOLD
3056
3057         if [ $RUNMODE == "KUBE" ]; then
3058                 echo -e $YELLOW" Internal log for $dispname not checked in kube"$EYELLOW
3059                 return
3060         fi
3061
3062         #tmp=$(docker ps | grep $appname)
3063         tmp=$(docker ps -q --filter name=$appname) #get the container id
3064         if [ -z "$tmp" ]; then  #Only check logs for running A1PMS apps
3065                 echo " "$dispname" is not running, no check made"
3066                 return
3067         fi
3068         foundentries="$(docker exec -t $tmp grep $warning $logpath | wc -l)"
3069         if [ $? -ne  0 ];then
3070                 echo "  Problem to search $appname log $logpath"
3071         else
3072                 if [ $foundentries -eq 0 ]; then
3073                         echo "  No WARN entries found in $appname log $logpath"
3074                 else
3075                         echo -e "  Found \033[1m"$foundentries"\033[0m WARN entries in $appname log $logpath"
3076                 fi
3077         fi
3078         foundentries="$(docker exec -t $tmp grep $error $logpath | wc -l)"
3079         if [ $? -ne  0 ];then
3080                 echo "  Problem to search $appname log $logpath"
3081         else
3082                 if [ $foundentries -eq 0 ]; then
3083                         echo "  No ERR entries found in $appname log $logpath"
3084                 else
3085                         echo -e $RED"  Found \033[1m"$foundentries"\033[0m"$RED" ERR entries in $appname log $logpath"$ERED
3086                 fi
3087         fi
3088         echo ""
3089 }
3090
3091 # Store all container logs and other logs in the log dir for the script
3092 # Logs are stored with a prefix in case logs should be stored several times during a test
3093 # args: <logfile-prefix>
3094 # (Function for test scripts)
3095 store_logs() {
3096         if [ $# != 1 ]; then
3097                 ((RES_CONF_FAIL++))
3098         __print_err "need one arg, <file-prefix>" $@
3099                 exit 1
3100         fi
3101         echo -e $BOLD"Storing all docker/kube container logs and other test logs in $TESTLOGS/$ATC using prefix: "$1$EBOLD
3102
3103         docker stats --no-stream > $TESTLOGS/$ATC/$1_docker_stats.log 2>&1
3104
3105         docker ps -a  > $TESTLOGS/$ATC/$1_docker_ps.log 2>&1
3106
3107         cp .httplog_${ATC}.txt $TESTLOGS/$ATC/$1_httplog_${ATC}.txt 2>&1
3108
3109         if [ $RUNMODE == "DOCKER" ]; then
3110
3111                 # Store docker logs for all container
3112                 for imagename in $APP_SHORT_NAMES; do
3113                         __check_included_image $imagename
3114                         if [ $? -eq 0 ]; then
3115                                 # A function name is created from the app short name
3116                                 # for example app short name 'RICMSIM' -> produce the function
3117                                 # name __RICSIM__store_docker_logs
3118                                 # This function is called and is expected to exist in the imported
3119                                 # file for the ricsim test functions
3120                                 # The resulting function impl shall store the docker logs for each container
3121                                 function_pointer="__"$imagename"_store_docker_logs"
3122                                 $function_pointer "$TESTLOGS/$ATC/" $1
3123                         fi
3124                 done
3125         fi
3126         if [ $RUNMODE == "KUBE" ]; then
3127                 namespaces=$(kubectl $KUBECONF  get namespaces -o jsonpath='{.items[?(@.metadata.name)].metadata.name}')
3128                 for nsid in $namespaces; do
3129                         pods=$(kubectl $KUBECONF get pods -n $nsid -o jsonpath='{.items[?(@.metadata.labels.autotest)].metadata.name}')
3130                         for podid in $pods; do
3131                                 kubectl $KUBECONF logs -n $nsid $podid > $TESTLOGS/$ATC/$1_${podid}.log
3132                         done
3133                 done
3134         fi
3135         echo ""
3136 }
3137
3138 ###############
3139 ## Generic curl
3140 ###############
3141 # Generic curl function, assumes all 200-codes are ok
3142 # Used proxy, set
3143 # args: <valid-curl-args-including full url>
3144 # returns: <returned response (without respose code)>  or "<no-response-from-server>" or "<not found, <http-code>>""
3145 # returns: The return code is 0 for ok and 1 for not ok
3146 __do_curl() {
3147         echo ${FUNCNAME[1]} "line: "${BASH_LINENO[1]} >> $HTTPLOG
3148         proxyflag=""
3149         if [ ! -z "$KUBE_PROXY_PATH" ]; then
3150                 if [ $KUBE_PROXY_HTTPX == "http" ]; then
3151                         proxyflag=" --proxy $KUBE_PROXY_PATH"
3152                 else
3153                         proxyflag=" --proxy-insecure --proxy $KUBE_PROXY_PATH"
3154                 fi
3155         fi
3156
3157         if [ ! -z "$KUBE_PROXY_CURL_JWT" ]; then
3158                 jwt="-H "\""Authorization: Bearer $KUBE_PROXY_CURL_JWT"\"
3159                 curlString="curl -skw %{http_code} $proxyflag $@"
3160                 echo " CMD: $curlString $jwt" >> $HTTPLOG
3161                 res=$($curlString -H "Authorization: Bearer $KUBE_PROXY_CURL_JWT")
3162                 retcode=$?
3163         else
3164                 curlString="curl -skw %{http_code} $proxyflag $@"
3165                 echo " CMD: $curlString" >> $HTTPLOG
3166                 res=$($curlString)
3167                 retcode=$?
3168         fi
3169         echo " RESP: $res" >> $HTTPLOG
3170         echo " RETCODE: $retcode" >> $HTTPLOG
3171         if [ $retcode -ne 0 ]; then
3172                 echo "<no-response-from-server>"
3173                 return 1
3174         fi
3175         http_code="${res:${#res}-3}"
3176         if [ ${#res} -eq 3 ]; then
3177                 if [ $http_code -lt 200 ] || [ $http_code -gt 299 ]; then
3178                         echo "<no-response-from-server>"
3179                         return 1
3180                 else
3181                         return 0
3182                 fi
3183         else
3184                 if [ $http_code -lt 200 ] || [ $http_code -gt 299 ]; then
3185                         echo "<not found, resp:${http_code}>"
3186                         return 1
3187                 fi
3188                 if [ $# -eq 2 ]; then
3189                         echo "${res:0:${#res}-3}" | xargs
3190                 else
3191                         echo "${res:0:${#res}-3}"
3192                 fi
3193
3194                 return 0
3195         fi
3196
3197 }
3198
3199 # Generic curl function, assumes all 200-codes are ok
3200 # Uses no proxy, even if it is set
3201 # args: <valid-curl-args-including full url>
3202 # returns: <returned response (without respose code)>  or "<no-response-from-server>" or "<not found, <http-code>>""
3203 # returns: The return code is 0 for ok and 1 for not ok
3204 __do_curl_no_proxy() {
3205         echo ${FUNCNAME[1]} "line: "${BASH_LINENO[1]} >> $HTTPLOG
3206         curlString="curl -skw %{http_code} $@"
3207         echo " CMD: $curlString" >> $HTTPLOG
3208         res=$($curlString)
3209         retcode=$?
3210         echo " RESP: $res" >> $HTTPLOG
3211         echo " RETCODE: $retcode" >> $HTTPLOG
3212         if [ $retcode -ne 0 ]; then
3213                 echo "<no-response-from-server>"
3214                 return 1
3215         fi
3216         http_code="${res:${#res}-3}"
3217         if [ ${#res} -eq 3 ]; then
3218                 if [ $http_code -lt 200 ] || [ $http_code -gt 299 ]; then
3219                         echo "<no-response-from-server>"
3220                         return 1
3221                 else
3222                         return 0
3223                 fi
3224         else
3225                 if [ $http_code -lt 200 ] || [ $http_code -gt 299 ]; then
3226                         echo "<not found, resp:${http_code}>"
3227                         return 1
3228                 fi
3229                 if [ $# -eq 2 ]; then
3230                         echo "${res:0:${#res}-3}" | xargs
3231                 else
3232                         echo "${res:0:${#res}-3}"
3233                 fi
3234
3235                 return 0
3236         fi
3237 }
3238
3239 #######################################
3240 ### Basic helper function for test cases
3241 #######################################
3242
3243 # Test a simulator container variable value towards target value using an condition operator with an optional timeout.
3244 # Arg: <simulator-name> <host> <variable-name> <condition-operator> <target-value>  - This test is done
3245 # immediately and sets pass or fail depending on the result of comparing variable and target using the operator.
3246 # Arg: <simulator-name> <host> <variable-name> <condition-operator> <target-value> <timeout>  - This test waits up to the timeout
3247 # before setting pass or fail depending on the result of comparing variable and target using the operator.
3248 # 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.
3249 # Not to be called from test script.
3250
3251 __var_test() {
3252         checkjsonarraycount=0
3253         TIMESTAMP=$(date "+%Y-%m-%d %H:%M:%S")
3254         if [ $# -eq 6 ]; then
3255                 if [[ $3 == "json:"* ]]; then
3256                         checkjsonarraycount=1
3257                 fi
3258
3259                 echo -e $BOLD"TEST $TEST_SEQUENCE_NR - (${BASH_LINENO[1]}) - ${TIMESTAMP}: ${1}, ${3} ${4} ${5} within ${6} seconds"$EBOLD
3260         echo "TEST $TEST_SEQUENCE_NR - (${BASH_LINENO[1]}) - ${TIMESTAMP}: ${1}, ${3} ${4} ${5} within ${6} seconds" >> $HTTPLOG
3261
3262                 ((RES_TEST++))
3263                 ((TEST_SEQUENCE_NR++))
3264                 start=$SECONDS
3265                 ctr=0
3266                 for (( ; ; )); do
3267                         if [ $checkjsonarraycount -eq 0 ]; then
3268                                 result="$(__do_curl $2$3)"
3269                                 retcode=$?
3270                                 result=${result//[[:blank:]]/} #Strip blanks
3271                         else
3272                                 path=${3:5}
3273                                 result="$(__do_curl $2$path)"
3274                                 retcode=$?
3275                                 echo "$result" > ./tmp/.tmp.curl.json
3276                                 result=$(python3 ../common/count_json_elements.py "./tmp/.tmp.curl.json")
3277                         fi
3278                         duration=$((SECONDS-start))
3279                         echo -ne " Result=${result} after ${duration} seconds${SAMELINE}"
3280                         let ctr=ctr+1
3281                         if [ $retcode -ne 0 ]; then
3282                                 if [ $duration -gt $6 ]; then
3283                                         ((RES_FAIL++))
3284                                         echo -e $RED" FAIL${ERED} - ${3} ${4} ${5} not reached in ${6} seconds, result = ${result}"
3285                                         __print_current_stats
3286                                         __check_stop_at_error
3287                                         return
3288                                 fi
3289                         elif [ "$4" == "=" ] && [ "$result" -eq $5 ]; then
3290                                 ((RES_PASS++))
3291                                 echo -e " Result=${result} after ${duration} seconds${SAMELINE}"
3292                                 echo -e $GREEN" PASS${EGREEN} - Result=${result} after ${duration} seconds"
3293                                 __print_current_stats
3294                                 return
3295                         elif [ "$4" == ">" ] && [ "$result" -gt $5 ]; then
3296                                 ((RES_PASS++))
3297                                 echo -e " Result=${result} after ${duration} seconds${SAMELINE}"
3298                                 echo -e $GREEN" PASS${EGREEN} - Result=${result} after ${duration} seconds"
3299                                 __print_current_stats
3300                                 return
3301                         elif [ "$4" == "<" ] && [ "$result" -lt $5 ]; then
3302                                 ((RES_PASS++))
3303                                 echo -e " Result=${result} after ${duration} seconds${SAMELINE}"
3304                                 echo -e $GREEN" PASS${EGREEN} - Result=${result} after ${duration} seconds"
3305                                 __print_current_stats
3306                                 return
3307                         elif [ "$4" == ">=" ] && [ "$result" -ge $5 ]; then
3308                                 ((RES_PASS++))
3309                                 echo -e " Result=${result} after ${duration} seconds${SAMELINE}"
3310                                 echo -e $GREEN" PASS${EGREEN} - Result=${result} after ${duration} seconds"
3311                                 __print_current_stats
3312                                 return
3313                         elif [ "$4" == "contain_str" ] && [[ $result =~ $5 ]]; then
3314                                 ((RES_PASS++))
3315                                 echo -e " Result=${result} after ${duration} seconds${SAMELINE}"
3316                                 echo -e $GREEN" PASS${EGREEN} - Result=${result} after ${duration} seconds"
3317                                 __print_current_stats
3318                                 return
3319                         else
3320                                 if [ $duration -gt $6 ]; then
3321                                         ((RES_FAIL++))
3322                                         echo -e $RED" FAIL${ERED} - ${3} ${4} ${5} not reached in ${6} seconds, result = ${result}"
3323                                         __print_current_stats
3324                                         __check_stop_at_error
3325                                         return
3326                                 fi
3327                         fi
3328                         sleep 1
3329                 done
3330         elif [ $# -eq 5 ]; then
3331                 if [[ $3 == "json:"* ]]; then
3332                         checkjsonarraycount=1
3333                 fi
3334
3335                 echo -e $BOLD"TEST $TEST_SEQUENCE_NR - (${BASH_LINENO[1]}) - ${TIMESTAMP}: ${1}, ${3} ${4} ${5}"$EBOLD
3336                 echo "TEST $TEST_SEQUENCE_NR - (${BASH_LINENO[1]}) - ${TIMESTAMP}:  ${1}, ${3} ${4} ${5}" >> $HTTPLOG
3337                 ((RES_TEST++))
3338                 ((TEST_SEQUENCE_NR++))
3339                 if [ $checkjsonarraycount -eq 0 ]; then
3340                         result="$(__do_curl $2$3)"
3341                         retcode=$?
3342                         result=${result//[[:blank:]]/} #Strip blanks
3343                 else
3344                         path=${3:5}
3345                         result="$(__do_curl $2$path)"
3346                         retcode=$?
3347                         echo "$result" > ./tmp/.tmp.curl.json
3348                         result=$(python3 ../common/count_json_elements.py "./tmp/.tmp.curl.json")
3349                 fi
3350                 if [ $retcode -ne 0 ]; then
3351                         ((RES_FAIL++))
3352                         echo -e $RED" FAIL ${ERED}- ${3} ${4} ${5} not reached, result = ${result}"
3353                         __print_current_stats
3354                         __check_stop_at_error
3355                 elif [ "$4" == "=" ] && [ "$result" -eq $5 ]; then
3356                         ((RES_PASS++))
3357                         echo -e $GREEN" PASS${EGREEN} - Result=${result}"
3358                         __print_current_stats
3359                 elif [ "$4" == ">" ] && [ "$result" -gt $5 ]; then
3360                         ((RES_PASS++))
3361                         echo -e $GREEN" PASS${EGREEN} - Result=${result}"
3362                         __print_current_stats
3363                 elif [ "$4" == "<" ] && [ "$result" -lt $5 ]; then
3364                         ((RES_PASS++))
3365                         echo -e $GREEN" PASS${EGREEN} - Result=${result}"
3366                         __print_current_stats
3367                 elif [ "$4" == ">=" ] && [ "$result" -ge $5 ]; then
3368                         ((RES_PASS++))
3369                         echo -e $GREEN" PASS${EGREEN} - Result=${result}"
3370                         __print_current_stats
3371                 elif [ "$4" == "contain_str" ] && [[ $result =~ $5 ]]; then
3372                         ((RES_PASS++))
3373                         echo -e $GREEN" PASS${EGREEN} - Result=${result}"
3374                         __print_current_stats
3375                 else
3376                         ((RES_FAIL++))
3377                         echo -e $RED" FAIL${ERED} - ${3} ${4} ${5} not reached, result = ${result}"
3378                         __print_current_stats
3379                         __check_stop_at_error
3380                 fi
3381         else
3382                 echo "Wrong args to __var_test, needs five or six args: <simulator-name> <host> <variable-name> <condition-operator> <target-value> [ <timeout> ]"
3383                 echo "Got:" $@
3384                 exit 1
3385         fi
3386 }