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