Update test env to remove '-' in ric hostnames
[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. V1 is not supported. 
141 #V1 names replicated containers <proj-name>_<service-name>_<index>
142 #V2 names replicated containers <proj-name>-<service-name>-<index>
143 DOCKER_COMPOSE_VERSION="V2"
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=$(type jq)
1179 if [ $? -ne 0 ]; then
1180         echo -e $RED"command utility jq (cmd-line json processor) is not installed"$ERED
1181         exit 1
1182 fi
1183 tmp=$(type envsubst)
1184 if [ $? -ne 0 ]; then
1185         echo -e $RED"command utility envsubst (env var substitution in files) is not installed"$ERED
1186         exit 1
1187 fi
1188 tmp=$(which docker)
1189 if [ $? -ne 0 ] || [ -z "$tmp" ]; then
1190         echo -e $RED"docker is required to run the test environment, pls install"$ERED
1191         exit 1
1192 fi
1193 echo " docker is installed and using versions:"
1194 echo  "  $(docker version --format 'Client version {{.Client.Version}} Server version {{.Server.Version}}')"
1195
1196 if [ $RUNMODE == "DOCKER" ]; then
1197         tmp=$(which docker-compose)
1198         if [ $? -ne 0 ] || [ -z "$tmp" ]; then
1199                 echo -e $RED"docker-compose (v.2+) is required to run the test environment, pls install"$ERED
1200                 exit 1
1201         else
1202                 tmp=$(docker-compose version)
1203                 echo " docker-compose installed and using version $tmp"
1204                 if [[ "$tmp" == *'v2'* ]]; then
1205                         DOCKER_COMPOSE_VERSION="V2"
1206                 else
1207                         echo -e $RED"docker-compose version $tmp is not supported. Only version v2 is supported, pls install"$ERED
1208                         exit 1
1209                 fi
1210         fi
1211 fi
1212 if [ $RUNMODE == "KUBE" ]; then
1213         tmp=$(which kubectl)
1214         if [ $? -ne 0 ] || [ -z tmp ]; then
1215                 echo -e $RED"kubectl is required to run the test environment in kubernetes mode, pls install"$ERED
1216                 exit 1
1217         else
1218                 echo " kubectl is installed and using versions:"
1219                 echo $(kubectl $KUBECONF version --short=true) | indent2
1220                 res=$(kubectl $KUBECONF cluster-info 2>&1)
1221                 if [ $? -ne 0 ]; then
1222                         echo -e "$BOLD$RED############################################# $ERED$EBOLD"
1223                         echo -e  $BOLD$RED"Command 'kubectl '$KUBECONF' cluster-info' returned error $ERED$EBOLD"
1224                         echo -e "$BOLD$RED############################################# $ERED$EBOLD"
1225                         echo " "
1226                         echo "kubectl response:"
1227                         echo $res
1228                         echo " "
1229                         echo "This script may have been started with user with no permission to run kubectl"
1230                         echo "Try running with 'sudo', set env KUBECONFIG or set '--kubeconfig' parameter"
1231                         echo "Do either 1, 2 or 3 "
1232                         echo " "
1233                         echo "1"
1234                         echo "Run with sudo"
1235                         echo -e $BOLD"sudo <test-script-and-parameters>"$EBOLD
1236                         echo " "
1237                         echo "2"
1238                         echo "Export KUBECONFIG and pass env to sudo - (replace user)"
1239                         echo -e $BOLD"export KUBECONFIG='/home/<user>/.kube/config'"$EBOLD
1240                         echo -e $BOLD"sudo -E <test-script-and-parameters>"$EBOLD
1241                         echo " "
1242                         echo "3"
1243                         echo "Set KUBECONFIG via script parameter"
1244                         echo -e $BOLD"sudo ... --kubeconfig /home/<user>/.kube/<config-file> ...."$EBOLD
1245                         echo "The config file need to downloaded from the cluster"
1246
1247                         exit 1
1248                 fi
1249                 echo " Node(s) and container runtime config"
1250                 kubectl $KUBECONF get nodes -o wide | indent2
1251                 echo ""
1252                 if [ -z "$HOST_PATH_BASE_DIR" ]; then
1253                         HOST_PATH_BASE_DIR="/tmp"
1254                         echo " Persistent volumes will be mounted to $HOST_PATH_BASE_DIR on applicable node"
1255                         echo " No guarantee that persistent volume data is available on all nodes in the cluster"
1256                 else
1257                         echo "Persistent volumes will be mounted to base dir: $HOST_PATH_BASE_DIR"
1258                         echo "Assuming this dir is mounted from each node to a dir on the localhost or other"
1259                         echo "file system available to all nodes"
1260                 fi
1261         fi
1262 fi
1263
1264 echo ""
1265
1266 echo -e $BOLD"Checking configured image setting for this test case"$EBOLD
1267
1268 #Temp var to check for image variable name errors
1269 IMAGE_ERR=0
1270 #Create a file with image info for later printing as a table
1271 image_list_file="./tmp/.image-list"
1272 echo -e "Application\tApp short name\tImage\ttag\ttag-switch" > $image_list_file
1273
1274 # Check if image env var is set and if so export the env var with image to use (used by docker compose files)
1275 # arg: <app-short-name> <target-variable-name> <image-variable-name> <image-tag-variable-name> <tag-suffix> <image name> <target-platform>
1276 __check_and_create_image_var() {
1277         if [ $# -ne 7 ]; then
1278                 echo "Expected arg: <app-short-name> <target-variable-name> <image-variable-name> <image-tag-variable-name> <tag-suffix> <image name> <target-platform>"
1279                 ((IMAGE_ERR++))
1280                 return
1281         fi
1282
1283         __check_included_image $1
1284         if [ $? -ne 0 ]; then
1285                 echo -e "$6\t$1\t<image-excluded>\t<no-tag>"  >> $image_list_file
1286                 # Image is excluded since the corresponding app is not used in this test
1287                 return
1288         fi
1289         tmp=${6}"\t"${1}"\t"
1290         #Create var from the input var names
1291         image="${!3}"
1292         tmptag=$4"_"$5
1293         tag="${!tmptag}"
1294         if [ ! -z "$7" ]; then
1295                 tag=$tag-$7   # add platform to tag - for local images built by the test script
1296         fi
1297         optional_image_repo_target=""
1298
1299         if [ -z $image ]; then
1300                 __check_ignore_image $1
1301                 if [ $? -eq 0 ]; then
1302                         app_ds=$6
1303                         if [ -z "$6" ]; then
1304                                 app_ds="<app ignored>"
1305                         fi
1306                         echo -e "$app_ds\t$1\t<image-ignored>\t<no-tag>"  >> $image_list_file
1307                         # Image is ignored since the corresponding the images is not set in the env file
1308                         __remove_included_image $1   # Remove the image from the list of included images
1309                         return
1310                 fi
1311                 echo -e $RED"\$"$3" not set in $TEST_ENV_VAR_FILE"$ERED
1312                 ((IMAGE_ERR++))
1313                 echo ""
1314                 tmp=$tmp"<no-image>\t"
1315         else
1316
1317                 optional_image_repo_target=$image
1318
1319                 #Add repo depending on image type
1320                 if [ "$5" == "REMOTE_RELEASE" ]; then
1321                         image=$NEXUS_RELEASE_REPO$image
1322                 fi
1323                 if [ "$5" == "REMOTE" ]; then
1324                         image=$NEXUS_STAGING_REPO$image
1325                 fi
1326                 if [ "$5" == "REMOTE_SNAPSHOT" ]; then
1327                         image=$NEXUS_SNAPSHOT_REPO$image
1328                 fi
1329                 if [ "$5" == "REMOTE_PROXY" ]; then
1330                         image=$NEXUS_PROXY_REPO$image
1331                 fi
1332                 if [ "$5" == "REMOTE_RELEASE_ONAP" ]; then
1333                         image=$NEXUS_RELEASE_REPO_ONAP$image
1334                 fi
1335                 if [ "$5" == "REMOTE_RELEASE_ORAN" ]; then
1336                         image=$NEXUS_RELEASE_REPO_ORAN$image
1337                 fi
1338                 #No nexus repo added for local images, tag: LOCAL and other tags
1339                 tmp=$tmp$image"\t"
1340         fi
1341         if [ -z $tag ]; then
1342                 echo -e $RED"\$"$tmptag" not set in $TEST_ENV_VAR_FILE"$ERED
1343                 ((IMAGE_ERR++))
1344                 echo ""
1345                 tmp=$tmp"<no-tag>\t"
1346         else
1347                 tmp=$tmp$tag
1348         fi
1349         tmp=$tmp"\t"$5
1350         echo -e "$tmp" >> $image_list_file
1351         #Export the env var
1352         export "${2}"=$image":"$tag  #Note, this var may be set to the value of the target value below in __check_and_pull_image
1353
1354         remote_or_local_push=false
1355         if [ ! -z "$IMAGE_REPO_ADR" ] && [[ $5 != *"PROXY"* ]]; then
1356                 if [ $5 == "LOCAL" ]; then
1357                         remote_or_local_push=true
1358                 fi
1359                 if [[ $5 == *"REMOTE"* ]]; then
1360                         if [ "$IMAGE_REPO_POLICY" == "remote" ]; then
1361                                 remote_or_local_push=true
1362                         fi
1363                 fi
1364         fi
1365         if $remote_or_local_push; then    # Only re-tag and push images according to policy, if repo is given
1366                 export "${2}_SOURCE"=$image":"$tag  #Var to keep the actual source image
1367                 if [[ $optional_image_repo_target == *"/"* ]]; then # Replace all / with _ for images to push to external repo
1368                         optional_image_repo_target_tmp=${optional_image_repo_target//\//_}
1369                         optional_image_repo_target=$optional_image_repo_target_tmp
1370                 fi
1371                 export "${2}_TARGET"=$IMAGE_REPO_ADR"/"$optional_image_repo_target":"$tag  #Create image + tag for optional image repo - pushed later if needed
1372         else
1373                 export "${2}_SOURCE"=""
1374                 export "${2}_TARGET"=""
1375         fi
1376 }
1377
1378 # Check if app uses image included in this test run
1379 # Returns 0 if image is included, 1 if not
1380 __check_included_image() {
1381         for im in $INCLUDED_IMAGES; do
1382                 if [ "$1" == "$im" ]; then
1383                         return 0
1384                 fi
1385         done
1386         return 1
1387 }
1388
1389 # Check if app uses a project image
1390 # Returns 0 if image is included, 1 if not
1391 __check_project_image() {
1392         for im in $PROJECT_IMAGES; do
1393                 if [ "$1" == "$im" ]; then
1394                         return 0
1395                 fi
1396         done
1397         return 1
1398 }
1399
1400 # Check if app uses image built by the test script
1401 # Returns 0 if image is included, 1 if not
1402 __check_image_local_build() {
1403         for im in $LOCAL_IMAGE_BUILD; do
1404                 if [ "$1" == "$im" ]; then
1405                         return 0
1406                 fi
1407         done
1408         return 1
1409 }
1410
1411 # Check if app image is conditionally ignored in this test run
1412 # Returns 0 if image is conditionally ignored, 1 if not
1413 __check_ignore_image() {
1414         for im in $CONDITIONALLY_IGNORED_IMAGES; do
1415                 if [ "$1" == "$im" ]; then
1416                         return 0
1417                 fi
1418         done
1419         return 1
1420 }
1421
1422 # Removed image from included list of included images
1423 # Used when an image is marked as conditionally ignored
1424 __remove_included_image() {
1425         tmp_img_rem_list=""
1426         for im in $INCLUDED_IMAGES; do
1427                 if [ "$1" != "$im" ]; then
1428                         tmp_img_rem_list=$tmp_img_rem_list" "$im
1429                 fi
1430         done
1431         INCLUDED_IMAGES=$tmp_img_rem_list
1432         return 0
1433 }
1434
1435 # Check if app is included in the prestarted set of apps
1436 # Returns 0 if image is included, 1 if not
1437 __check_prestarted_image() {
1438         for im in $KUBE_PRESTARTED_IMAGES; do
1439                 if [ "$1" == "$im" ]; then
1440                         return 0
1441                 fi
1442         done
1443         return 1
1444 }
1445
1446 # Check if an app shall use a local image, based on the cmd parameters
1447 __check_image_local_override() {
1448         for im in $USE_LOCAL_IMAGES; do
1449                 if [ "$1" == "$im" ]; then
1450                         return 1
1451                 fi
1452         done
1453         return 0
1454 }
1455
1456 # Check if app uses image override
1457 # Returns the image/tag suffix LOCAL for local image or REMOTE/REMOTE_RELEASE/REMOTE_SNAPSHOT for staging/release/snapshot image
1458 __check_image_override() {
1459
1460         for im in $ORAN_IMAGES_APP_NAMES; do
1461                 if [ "$1" == "$im" ]; then
1462                         echo "REMOTE_RELEASE_ORAN"
1463                         return 0
1464                 fi
1465         done
1466
1467         for im in $ONAP_IMAGES_APP_NAMES; do
1468                 if [ "$1" == "$im" ]; then
1469                         echo "REMOTE_RELEASE_ONAP"
1470                         return 0
1471                 fi
1472         done
1473
1474         found=0
1475         for im in $PROJECT_IMAGES_APP_NAMES; do
1476                 if [ "$1" == "$im" ]; then
1477                         found=1
1478                 fi
1479         done
1480
1481         if [ $found -eq 0 ]; then
1482                 echo "REMOTE_PROXY"
1483                 return 0
1484         fi
1485
1486         suffix=""
1487         if [ $IMAGE_CATEGORY == "RELEASE" ]; then
1488                 suffix="REMOTE_RELEASE"
1489         fi
1490         if [ $IMAGE_CATEGORY == "DEV" ]; then
1491                 suffix="REMOTE"
1492         fi
1493         CTR=0
1494         for im in $USE_STAGING_IMAGES; do
1495                 if [ "$1" == "$im" ]; then
1496                         suffix="REMOTE"
1497                         ((CTR++))
1498                 fi
1499         done
1500         for im in $USE_RELEASE_IMAGES; do
1501                 if [ "$1" == "$im" ]; then
1502                         suffix="REMOTE_RELEASE"
1503                         ((CTR++))
1504                 fi
1505         done
1506         for im in $USE_SNAPSHOT_IMAGES; do
1507                 if [ "$1" == "$im" ]; then
1508                         suffix="REMOTE_SNAPSHOT"
1509                         ((CTR++))
1510                 fi
1511         done
1512         for im in $USE_LOCAL_IMAGES; do
1513                 if [ "$1" == "$im" ]; then
1514                         suffix="LOCAL"
1515                         ((CTR++))
1516                 fi
1517         done
1518         for im in $USE_EXTERNAL_IMAGES; do
1519                 if [ "$1" == "$im" ]; then
1520                         suffix="EXTERNAL"
1521                         ((CTR++))
1522                 fi
1523         done
1524         echo $suffix
1525         if [ $CTR -gt 1 ]; then
1526                 exit 1
1527         fi
1528         return 0
1529 }
1530
1531 # Function to re-tag and image and push to another image repo
1532 __retag_and_push_image() {
1533         if [ ! -z "$IMAGE_REPO_ADR" ]; then
1534                 source_image="${!1}"
1535                 trg_var_name=$1_"TARGET" # This var is created in func __check_and_create_image_var
1536                 target_image="${!trg_var_name}"
1537
1538                 if [ -z $target_image ]; then
1539                         return 0  # Image with no target shall not be pushed
1540                 fi
1541
1542                 echo -ne "  Attempt to re-tag image to: ${BOLD}${target_image}${EBOLD}${SAMELINE}"
1543                 tmp=$(docker image tag $source_image ${target_image} )
1544                 if [ $? -ne 0 ]; then
1545                         docker stop $tmp &> ./tmp/.dockererr
1546                         ((IMAGE_ERR++))
1547                         echo ""
1548                         echo -e "  Attempt to re-tag image to: ${BOLD}${target_image}${EBOLD} - ${RED}Failed${ERED}"
1549                         cat ./tmp/.dockererr
1550                         return 1
1551                 else
1552                         echo -e "  Attempt to re-tag image to: ${BOLD}${target_image}${EBOLD} - ${GREEN}OK${EGREEN}"
1553                 fi
1554                 echo -ne "  Attempt to push re-tagged image: ${BOLD}${target_image}${EBOLD}${SAMELINE}"
1555                 tmp=$(docker push ${target_image} )
1556                 if [ $? -ne 0 ]; then
1557                         docker stop $tmp &> ./tmp/.dockererr
1558                         ((IMAGE_ERR++))
1559                         echo ""
1560                         echo -e "  Attempt to push re-tagged image: ${BOLD}${target_image}${EBOLD} - ${RED}Failed${ERED}"
1561                         cat ./tmp/.dockererr
1562                         return 1
1563                 else
1564                         echo -e "  Attempt to push re-tagged image: ${BOLD}${target_image}${EBOLD} - ${GREEN}OK${EGREEN}"
1565                 fi
1566                 export "${1}"=$target_image
1567         fi
1568         return 0
1569 }
1570
1571 #Function to check if image exist and stop+remove the container+pull new images as needed
1572 #args <script-start-arg> <descriptive-image-name> <container-base-name> <image-with-tag-var-name>
1573 __check_and_pull_image() {
1574
1575         source_image="${!4}"
1576
1577         echo -e " Checking $BOLD$2$EBOLD container(s) with basename: $BOLD$3$EBOLD using image: $BOLD$source_image$EBOLD"
1578         format_string="\"{{.Repository}}\\t{{.Tag}}\\t{{.CreatedSince}}\\t{{.Size}}\""
1579         tmp_im=$(docker images --format $format_string $source_image)
1580
1581         if [ $1 == "local" ]; then
1582                 if [ -z "$tmp_im" ]; then
1583                         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
1584                         ((IMAGE_ERR++))
1585                         return 1
1586                 else
1587                         echo -e "  "$2" (local image): \033[1m"$source_image"\033[0m "$GREEN"OK"$EGREEN
1588                 fi
1589         elif [ $1 == "remote" ] || [ $1 == "remote-remove" ]; then
1590                 if [ $1 == "remote-remove" ]; then
1591                         if [ $RUNMODE == "DOCKER" ]; then
1592
1593                                 echo -ne "  Attempt to stop and remove container(s), if running - ${SAMELINE}"
1594                                 tmp=$(docker ps -aq --filter name=${3} --filter network=${DOCKER_SIM_NWNAME})
1595                                 if [ $? -eq 0 ] && [ ! -z "$tmp" ]; then
1596                                         docker stop -t 0 $tmp &> ./tmp/.dockererr
1597                                         if [ $? -ne 0 ]; then
1598                                                 ((IMAGE_ERR++))
1599                                                 echo ""
1600                                                 echo -e $RED"  Container(s) could not be stopped - try manual stopping the container(s)"$ERED
1601                                                 cat ./tmp/.dockererr
1602                                                 return 1
1603                                         fi
1604                                 fi
1605                                 echo -ne "  Attempt to stop and remove container(s), if running - "$GREEN"stopped"$EGREEN"${SAMELINE}"
1606                                 tmp=$(docker ps -aq --filter name=${3} --filter network=${DOCKER_SIM_NWNAME}) &> /dev/null
1607                                 if [ $? -eq 0 ] && [ ! -z "$tmp" ]; then
1608                                         docker rm -f $tmp &> ./tmp/.dockererr
1609                                         if [ $? -ne 0 ]; then
1610                                                 ((IMAGE_ERR++))
1611                                                 echo ""
1612                                                 echo -e $RED"  Container(s) could not be removed - try manual removal of the container(s)"$ERED
1613                                                 cat ./tmp/.dockererr
1614                                                 return 1
1615                                         fi
1616                                 fi
1617                                 echo -e "  Attempt to stop and remove container(s), if running - "$GREEN"stopped removed"$EGREEN
1618                                 tmp_im=""
1619                         else
1620                                 tmp_im=""
1621                         fi
1622                 fi
1623                 if [ -z "$tmp_im" ]; then
1624                         echo -ne "  Pulling image${SAMELINE}"
1625                         out=$(docker pull $IMAGE_TARGET_PLATFORM_CMD_PARAM $source_image)
1626                         if [ $? -ne 0 ]; then
1627                                 echo ""
1628                                 echo -e "  Pulling image -$RED could not be pulled"$ERED
1629                                 ((IMAGE_ERR++))
1630                                 echo $out > ./tmp/.dockererr
1631                                 echo $out
1632                                 return 1
1633                         fi
1634                         echo $out > ./tmp/.dockererr
1635                         if [[ $out == *"up to date"* ]]; then
1636                                 echo -e "  Pulling image -$GREEN Image is up to date $EGREEN"
1637                         elif [[ $out == *"Downloaded newer image"* ]]; then
1638                                 echo -e "  Pulling image -$GREEN Newer image pulled $EGREEN"
1639                         else
1640                                 echo -e "  Pulling image -$GREEN Pulled $EGREEN"
1641                         fi
1642                 else
1643                         echo -e "  Pulling image -$GREEN OK $EGREEN(exists in local repository)"
1644                 fi
1645         fi
1646
1647         __retag_and_push_image $4
1648
1649         return $?
1650 }
1651
1652 setup_testenvironment() {
1653         # Check that image env setting are available
1654         echo ""
1655
1656         # Image var setup for all project images included in the test
1657         for imagename in $APP_SHORT_NAMES; do
1658                 __check_included_image $imagename
1659                 incl=$?
1660                 __check_project_image $imagename
1661                 proj=$?
1662                 if [ $incl -eq 0 ]; then
1663                         if [ $proj -eq 0 ]; then
1664                                 IMAGE_SUFFIX=$(__check_image_override $imagename)
1665                                 if [ $? -ne 0 ]; then
1666                                         echo -e $RED"Image setting from cmd line not consistent for $imagename."$ERED
1667                                         ((IMAGE_ERR++))
1668                                 fi
1669                         else
1670                                 IMAGE_SUFFIX="none"
1671                         fi
1672                         # A function name is created from the app short name
1673                         # for example app short name 'ICS' -> produce the function
1674                         # name __ICS_imagesetup
1675                         # This function is called and is expected to exist in the imported
1676                         # file for the ics test functions
1677                         # The resulting function impl will call '__check_and_create_image_var' function
1678                         # with appropriate parameters
1679                         # If the image suffix is none, then the component decides the suffix
1680                         function_pointer="__"$imagename"_imagesetup"
1681                         $function_pointer $IMAGE_SUFFIX
1682
1683                         function_pointer="__"$imagename"_test_requirements"
1684                         $function_pointer
1685                 fi
1686         done
1687
1688         #Errors in image setting - exit
1689         if [ $IMAGE_ERR -ne 0 ]; then
1690                 exit 1
1691         fi
1692
1693         #Print a tables of the image settings
1694         echo -e $BOLD"Images configured for start arg: "$START_ARG $EBOLD
1695         column -t -s $'\t' $image_list_file | indent1
1696
1697         echo ""
1698
1699         #Set the SIM_GROUP var
1700         echo -e $BOLD"Setting var to main dir of all container/simulator scripts"$EBOLD
1701         if [ -z "$SIM_GROUP" ]; then
1702                 SIM_GROUP=$AUTOTEST_HOME/../simulator-group
1703                 if [ ! -d  $SIM_GROUP ]; then
1704                         echo "Trying to set env var SIM_GROUP to dir 'simulator-group' in the nontrtric repo, but failed."
1705                         echo -e $RED"Please set the SIM_GROUP manually in the applicable $TEST_ENV_VAR_FILE"$ERED
1706                         exit 1
1707                 else
1708                         echo " SIM_GROUP auto set to: " $SIM_GROUP
1709                 fi
1710         elif [ $SIM_GROUP = *simulator_group ]; then
1711                 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
1712                 exit 1
1713         else
1714                 echo " SIM_GROUP env var already set to: " $SIM_GROUP
1715         fi
1716
1717         echo ""
1718
1719         #Temp var to check for image pull errors
1720         IMAGE_ERR=0
1721
1722         # Delete namespaces
1723         echo -e $BOLD"Deleting namespaces"$EBOLD
1724
1725
1726         if [ "$DELETE_KUBE_NAMESPACES" -eq 1 ]; then
1727                 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
1728                 if [ $? -ne 0 ]; then
1729                         echo " Cannot get list of namespaces...ignoring delete"
1730                 else
1731                         for test_env_ns in $test_env_namespaces; do
1732                                 __kube_delete_namespace $test_env_ns
1733                         done
1734                 fi
1735         else
1736                 echo " Namespace delete option not set or ignored"
1737         fi
1738         echo ""
1739
1740         # Delete containers
1741         echo -e $BOLD"Deleting containers"$EBOLD
1742
1743         if [ "$DELETE_CONTAINERS" -eq 1 ]; then
1744                 echo " Stopping containers label 'nrttest_app'..."
1745                 docker stop $(docker ps -qa  --filter "label=nrttest_app") 2> /dev/null
1746                 echo " Removing stopped containers..."
1747                 docker rm $(docker ps -qa  --filter "label=nrttest_app") 2> /dev/null
1748         else
1749                 echo " Contatiner delete option not set or ignored"
1750         fi
1751         echo ""
1752
1753         # The following sequence pull the configured images
1754         echo -e $BOLD"Pulling configured images, if needed"$EBOLD
1755         __exclude_check=0
1756         if [ ! -z "$IMAGE_REPO_ADR" ] && [ $IMAGE_REPO_POLICY == "local" ]; then
1757                 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
1758                 __exclude_check=1
1759         fi
1760         for imagename in $APP_SHORT_NAMES; do
1761                 __check_included_image $imagename
1762                 incl=$?
1763                 __check_project_image $imagename
1764                 proj=$?
1765                 if [ $incl -eq 0 ]; then
1766                         if [ $proj -eq 0 ]; then
1767                                 START_ARG_MOD=$START_ARG
1768                                 __check_image_local_override $imagename
1769                                 if [ $? -eq 1 ]; then
1770                                         START_ARG_MOD="local"
1771                                 fi
1772                         else
1773                                 START_ARG_MOD=$START_ARG
1774                         fi
1775                         __exclude_image_check=0
1776                         if [ $__exclude_check == 1 ] && [ "$START_ARG_MOD" != "local" ]; then
1777                                 # For to handle locally built images,  overriding remote images
1778                                 __exclude_image_check=1
1779                         fi
1780                         if [ $__exclude_image_check == 0 ]; then
1781                                 __check_image_local_build $imagename
1782                                 #No pull of images built locally
1783                                 if [ $? -ne 0 ]; then
1784                                         # A function name is created from the app short name
1785                                         # for example app short name 'HTTPPROXY' -> produce the function
1786                                         # name __HTTPPROXY_imagesetup
1787                                         # This function is called and is expected to exist in the imported
1788                                         # file for the httpproxy test functions
1789                                         # The resulting function impl will call '__check_and_pull_image' function
1790                                         # with appropriate parameters
1791                                         function_pointer="__"$imagename"_imagepull"
1792                                         $function_pointer $START_ARG_MOD $START_ARG
1793                                 fi
1794                         fi
1795                 else
1796                         echo -e $YELLOW" Excluding $imagename image from image check/pull"$EYELLOW
1797                 fi
1798         done
1799
1800
1801         #Errors in image setting - exit
1802         if [ $IMAGE_ERR -ne 0 ]; then
1803                 echo ""
1804                 echo "#################################################################################################"
1805                 echo -e $RED"One or more images could not be pulled or containers using the images could not be stopped/removed"$ERED
1806                 echo -e $RED"Or local image, overriding remote image, does not exist"$ERED
1807                 if [ $IMAGE_CATEGORY == "DEV" ]; then
1808                     echo ""
1809                         echo -e $RED"Note that SNAPSHOT and staging images may be purged from nexus after a certain period."$ERED
1810                         echo -e $RED"In addition, the image may not have been updated in the current release so no SNAPSHOT or staging image exists"$ERED
1811                         echo -e $RED"In these cases, switch to use a released image instead, use the flag '--use-release-image <App-short-name>'"$ERED
1812                         echo -e $RED"Use the 'App-short-name' for the applicable image from the above table: 'Images configured for start arg'."$ERED
1813                 fi
1814                 echo "#################################################################################################"
1815                 echo ""
1816                 exit 1
1817         fi
1818
1819         echo ""
1820
1821         echo -e $BOLD"Building images needed for test"$EBOLD
1822
1823         for imagename in $APP_SHORT_NAMES; do
1824                 cd $AUTOTEST_HOME #Always reset to orig dir
1825                 __check_image_local_build $imagename
1826                 if [ $? -eq 0 ]; then
1827                         __check_included_image $imagename
1828                         if [ $? -eq 0 ]; then
1829                                 # A function name is created from the app short name
1830                                 # for example app short name 'MR' -> produce the function
1831                                 # name __MR_imagebuild
1832                                 # This function is called and is expected to exist in the imported
1833                                 # file for the mr test functions
1834                                 # The resulting function impl shall build the imagee
1835                                 function_pointer="__"$imagename"_imagebuild"
1836                                 $function_pointer
1837
1838                         else
1839                                 echo -e $YELLOW" Excluding image for app $imagename from image build"$EYELLOW
1840                         fi
1841                 fi
1842         done
1843
1844         cd $AUTOTEST_HOME # Just to make sure...
1845
1846         echo ""
1847
1848         # Create a table of the images used in the script - from local repo
1849         echo -e $BOLD"Local docker registry images used in this test script"$EBOLD
1850
1851         docker_tmp_file=./tmp/.docker-images-table
1852         format_string="{{.Repository}}\\t{{.Tag}}\\t{{.CreatedSince}}\\t{{.Size}}\\t{{.CreatedAt}}"
1853         echo -e "Application\tRepository\tTag\tCreated since\tSize\tCreated at" > $docker_tmp_file
1854
1855         for imagename in $APP_SHORT_NAMES; do
1856                 __check_included_image $imagename
1857                 if [ $? -eq 0 ]; then
1858                         # Only print image data if image repo is null, or if image repo is set and image is local
1859                         print_image_data=0
1860                         if [ -z "$IMAGE_REPO_ADR" ]; then
1861                                 print_image_data=1
1862                         else
1863                                 __check_image_local_build $imagename
1864                                 if [ $? -eq 0 ]; then
1865                                         print_image_data=1
1866                                 fi
1867                         fi
1868                         if [ $print_image_data -eq 1 ]; then
1869                                 # A function name is created from the app short name
1870                                 # for example app short name 'MR' -> produce the function
1871                                 # name __MR_imagebuild
1872                                 # This function is called and is expected to exist in the imported
1873                                 # file for the mr test functions
1874                                 # The resulting function impl shall build the imagee
1875                                 function_pointer="__"$imagename"_image_data"
1876                                 $function_pointer "$format_string" $docker_tmp_file
1877                         fi
1878                 fi
1879         done
1880
1881         column -t -s $'\t' $docker_tmp_file | indent1
1882
1883         echo ""
1884
1885         if [ ! -z "$IMAGE_REPO_ADR" ]; then
1886
1887                 # Create a table of the images used in the script - from remote repo
1888                 echo -e $BOLD"Remote repo images used in this test script"$EBOLD
1889                 echo -e $YELLOW"-- Note: These image will be pulled when the container starts. Images not managed by the test engine "$EYELLOW
1890                 echo -e $YELLOW"-- Note: Images with local override will however be re-tagged and managed by the test engine "$EYELLOW
1891                 docker_tmp_file=./tmp/.docker-images-table
1892                 format_string="{{.Repository}}\\t{{.Tag}}"
1893                 echo -e "Application\tRepository\tTag" > $docker_tmp_file
1894
1895                 for imagename in $APP_SHORT_NAMES; do
1896                         __check_included_image $imagename
1897                         if [ $? -eq 0 ]; then
1898                                 # Only print image data if image repo is null, or if image repo is set and image is local
1899                                 __check_image_local_build $imagename
1900                                 if [ $? -ne 0 ]; then
1901                                         # A function name is created from the app short name
1902                                         # for example app short name 'MR' -> produce the function
1903                                         # name __MR_imagebuild
1904                                         # This function is called and is expected to exist in the imported
1905                                         # file for the mr test functions
1906                                         # The resulting function impl shall build the imagee
1907                                         function_pointer="__"$imagename"_image_data"
1908                                         $function_pointer "$format_string" $docker_tmp_file
1909                                 fi
1910                         fi
1911                 done
1912
1913                 column -t -s $'\t' $docker_tmp_file | indent1
1914
1915                 echo ""
1916         fi
1917
1918         if [ $RUNMODE == "KUBE" ]; then
1919
1920                 echo "================================================================================="
1921                 echo "================================================================================="
1922
1923                 if [ -z "$IMAGE_REPO_ADR" ]; then
1924                         echo -e $YELLOW" The image pull policy is set to 'Never' - assuming a local image repo is available for all images"$EYELLOW
1925                         echo -e " This setting only works on single node clusters on the local machine"
1926                         echo -e " It does not work with multi-node clusters or remote clusters. "
1927                         export KUBE_IMAGE_PULL_POLICY="Never"
1928                 else
1929                         echo -e $YELLOW" The image pull policy is set to 'Always'"$EYELLOW
1930                         echo -e " This setting work on local clusters, multi-node clusters and remote cluster. "
1931                         echo -e " Only locally built images are managed. Remote images are always pulled from remote repos"
1932                         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"
1933                         export KUBE_IMAGE_PULL_POLICY="Always"
1934                 fi
1935                 #CLUSTER_IP=$(kubectl $KUBECONF config view -o jsonpath={.clusters[0].cluster.server} | awk -F[/:] '{print $4}')
1936                 #echo -e $YELLOW" The cluster hostname/ip is: $CLUSTER_IP"$EYELLOW
1937
1938                 echo "================================================================================="
1939                 echo "================================================================================="
1940                 echo ""
1941         fi
1942
1943         echo -e $BOLD"======================================================="$EBOLD
1944         echo -e $BOLD"== Common test setup completed -  test script begins =="$EBOLD
1945         echo -e $BOLD"======================================================="$EBOLD
1946         echo ""
1947
1948         LOG_STAT_ARGS=""
1949
1950         for imagename in $APP_SHORT_NAMES; do
1951                 __check_included_image $imagename
1952                 retcode_i=$?
1953                 __check_prestarted_image $imagename
1954                 retcode_p=$?
1955                 if [ $retcode_i -eq 0 ] || [ $retcode_p -eq 0 ]; then
1956                         # A function name is created from the app short name
1957                         # for example app short name 'RICMSIM' -> produce the function
1958                         # name __RICSIM__initial_setup
1959                         # This function is called and is expected to exist in the imported
1960                         # file for the ricsim test functions
1961                         # The resulting function impl shall perform initial setup of port, host etc
1962
1963                         function_pointer="__"$imagename"_initial_setup"
1964                         $function_pointer
1965
1966                         function_pointer="__"$imagename"_statistics_setup"
1967                         LOG_STAT_ARGS=$LOG_STAT_ARGS" "$($function_pointer)
1968                 fi
1969         done
1970
1971         if [ $COLLECT_RUNTIME_STATS -eq 1 ]; then
1972                 ../common/genstat.sh $RUNMODE $SECONDS $TESTLOGS/$ATC/stat_data.csv $LOG_STAT_ARGS &
1973                 COLLECT_RUNTIME_STATS_PID=$!
1974         fi
1975
1976 }
1977
1978 # Function to print the test result, shall be the last cmd in a test script
1979 # args: -
1980 # (Function for test scripts)
1981 print_result() {
1982
1983         TCTEST_END=$SECONDS
1984         duration=$((TCTEST_END-TCTEST_START))
1985
1986         echo "-------------------------------------------------------------------------------------------------"
1987         echo "-------------------------------------     Test case: "$ATC
1988         echo "-------------------------------------     Ended:     "$(date)
1989         echo "-------------------------------------------------------------------------------------------------"
1990         echo "-- Description: "$TC_ONELINE_DESCR
1991         echo "-- Execution time: " $duration " seconds"
1992         echo "-- Used env file: "$TEST_ENV_VAR_FILE
1993         echo "-------------------------------------------------------------------------------------------------"
1994         echo "-------------------------------------     RESULTS"
1995         echo ""
1996
1997
1998         if [ $RES_DEVIATION -gt 0 ]; then
1999                 echo "Test case deviations"
2000                 echo "===================================="
2001                 cat $DEVIATION_FILE
2002         fi
2003         echo ""
2004         echo "Timer measurement in the test script"
2005         echo "===================================="
2006         column -t -s $'\t' $TIMER_MEASUREMENTS
2007         if [ $RES_PASS != $RES_TEST ]; then
2008                 echo -e $RED"Measurement may not be reliable when there are failed test - failures may cause long measurement values due to timeouts etc."$ERED
2009         fi
2010         echo ""
2011
2012         if [ $COLLECT_RUNTIME_STATS -eq 1 ]; then
2013                 echo "Runtime statistics collected in file: "$TESTLOGS/$ATC/stat_data.csv
2014                 echo ""
2015         fi
2016         TMP_FLAG_FAIL_PASS=0
2017         total=$((RES_PASS+RES_FAIL))
2018         if [ $RES_TEST -eq 0 ]; then
2019                 TMP_FLAG_FAIL_PASS=1
2020                 echo -e "\033[1mNo tests seem to have been executed. Check the script....\033[0m"
2021                 echo -e "\033[31m\033[1m ___  ___ ___ ___ ___ _____   ___ _   ___ _   _   _ ___ ___ \033[0m"
2022                 echo -e "\033[31m\033[1m/ __|/ __| _ \_ _| _ \_   _| | __/_\ |_ _| | | | | | _ \ __|\033[0m"
2023                 echo -e "\033[31m\033[1m\__ \ (__|   /| ||  _/ | |   | _/ _ \ | || |_| |_| |   / _| \033[0m"
2024                 echo -e "\033[31m\033[1m|___/\___|_|_\___|_|   |_|   |_/_/ \_\___|____\___/|_|_\___|\033[0m"
2025         elif [ $total != $RES_TEST ]; then
2026                 TMP_FLAG_FAIL_PASS=1
2027                 echo -e "\033[1mTotal number of tests does not match the sum of passed and failed tests. Check the script....\033[0m"
2028                 echo -e "\033[31m\033[1m ___  ___ ___ ___ ___ _____   ___ _   ___ _   _   _ ___ ___ \033[0m"
2029                 echo -e "\033[31m\033[1m/ __|/ __| _ \_ _| _ \_   _| | __/_\ |_ _| | | | | | _ \ __|\033[0m"
2030                 echo -e "\033[31m\033[1m\__ \ (__|   /| ||  _/ | |   | _/ _ \ | || |_| |_| |   / _| \033[0m"
2031                 echo -e "\033[31m\033[1m|___/\___|_|_\___|_|   |_|   |_/_/ \_\___|____\___/|_|_\___|\033[0m"
2032         elif [ $RES_CONF_FAIL -ne 0 ]; then
2033                 TMP_FLAG_FAIL_PASS=1
2034                 echo -e "\033[1mOne or more configurations has failed. Check the script log....\033[0m"
2035                 echo -e "\033[31m\033[1m ___  ___ ___ ___ ___ _____   ___ _   ___ _   _   _ ___ ___ \033[0m"
2036                 echo -e "\033[31m\033[1m/ __|/ __| _ \_ _| _ \_   _| | __/_\ |_ _| | | | | | _ \ __|\033[0m"
2037                 echo -e "\033[31m\033[1m\__ \ (__|   /| ||  _/ | |   | _/ _ \ | || |_| |_| |   / _| \033[0m"
2038                 echo -e "\033[31m\033[1m|___/\___|_|_\___|_|   |_|   |_/_/ \_\___|____\___/|_|_\___|\033[0m"
2039         elif [ $RES_PASS = $RES_TEST ]; then
2040                 TMP_FLAG_FAIL_PASS=0
2041                 echo -e "All tests \033[32m\033[1mPASS\033[0m"
2042                 echo -e "\033[32m\033[1m  ___  _   ___ ___ \033[0m"
2043                 echo -e "\033[32m\033[1m | _ \/_\ / __/ __| \033[0m"
2044                 echo -e "\033[32m\033[1m |  _/ _ \\__ \__ \\ \033[0m"
2045                 echo -e "\033[32m\033[1m |_|/_/ \_\___/___/ \033[0m"
2046                 echo ""
2047
2048                 # Update test suite counter
2049                 if [ -f .tmp_tcsuite_pass_ctr ]; then
2050                         tmpval=$(< .tmp_tcsuite_pass_ctr)
2051                         ((tmpval++))
2052                         echo $tmpval > .tmp_tcsuite_pass_ctr
2053                 fi
2054                 if [ -f .tmp_tcsuite_pass ]; then
2055                         echo " - "$ATC " -- "$TC_ONELINE_DESCR"  Execution time: "$duration" seconds" >> .tmp_tcsuite_pass
2056                 fi
2057                 #Create file with OK exit code
2058                 echo "0" > "$AUTOTEST_HOME/.result$ATC.txt"
2059                 echo "0" > "$TESTLOGS/$ATC/.result$ATC.txt"
2060                 echo $(date) > $TESTLOGS/$ATC/endpoint_tc_end.log
2061         else
2062                 TMP_FLAG_FAIL_PASS=1
2063                 echo -e "One or more tests with status  \033[31m\033[1mFAIL\033[0m "
2064                 echo -e "\033[31m\033[1m  ___ _   ___ _    \033[0m"
2065                 echo -e "\033[31m\033[1m | __/_\ |_ _| |   \033[0m"
2066                 echo -e "\033[31m\033[1m | _/ _ \ | || |__ \033[0m"
2067                 echo -e "\033[31m\033[1m |_/_/ \_\___|____|\033[0m"
2068                 echo ""
2069         fi
2070
2071         if [ $TMP_FLAG_FAIL_PASS -ne 0 ]; then
2072                 # Update test suite counter
2073                 if [ -f .tmp_tcsuite_fail_ctr ]; then
2074                         tmpval=$(< .tmp_tcsuite_fail_ctr)
2075                         ((tmpval++))
2076                         echo $tmpval > .tmp_tcsuite_fail_ctr
2077                 fi
2078                 if [ -f .tmp_tcsuite_fail ]; then
2079                         echo " - "$ATC " -- "$TC_ONELINE_DESCR"  Execution time: "$duration" seconds" >> .tmp_tcsuite_fail
2080                 fi
2081         fi
2082
2083         echo "++++ Number of tests:          "$RES_TEST
2084         echo "++++ Number of passed tests:   "$RES_PASS
2085         echo "++++ Number of failed tests:   "$RES_FAIL
2086         echo ""
2087         echo "++++ Number of failed configs: "$RES_CONF_FAIL
2088         echo ""
2089         echo "++++ Number of test case deviations: "$RES_DEVIATION
2090         echo ""
2091         echo "-------------------------------------     Test case complete    ---------------------------------"
2092         echo "-------------------------------------------------------------------------------------------------"
2093         echo ""
2094 }
2095
2096 #####################################################################
2097 ###### Functions for start, configuring, stoping, cleaning etc ######
2098 #####################################################################
2099
2100 # Start timer for time measurement
2101 # args:  <timer message to print>  -  timer value and message will be printed both on screen
2102 #                                     and in the timer measurement report - if at least one "print_timer is called"
2103 start_timer() {
2104         echo -e $BOLD"INFO(${BASH_LINENO[0]}): "${FUNCNAME[0]}"," $@ $EBOLD
2105         TC_TIMER_STARTTIME=$SECONDS
2106         TC_TIMER_TIMER_TEXT="${@:1}"
2107         if [ $# -ne 1 ]; then
2108                 __print_err "need 1 arg,  <timer message to print>" $@
2109                 TC_TIMER_TIMER_TEXT=${FUNCNAME[0]}":"${BASH_LINENO[0]}
2110                 echo " Assigning timer name: "$TC_TIMER_TIMER_TEXT
2111         fi
2112         TC_TIMER_CURRENT_FAILS=$(($RES_FAIL+$RES_CONF_FAIL))
2113         echo " Timer started: $(date)"
2114 }
2115
2116 # Print the running timer  the value of the time (in seconds)
2117 # Timer value and message will be printed both on screen and in the timer measurement report
2118 print_timer() {
2119         echo -e $BOLD"INFO(${BASH_LINENO[0]}): "${FUNCNAME[0]}"," $TC_TIMER_TIMER_TEXT $EBOLD
2120         if [ -z  "$TC_TIMER_STARTTIME" ]; then
2121                 __print_err "timer not started" $@
2122                 return 1
2123         fi
2124         duration=$(($SECONDS-$TC_TIMER_STARTTIME))
2125         if [ $duration -eq 0 ]; then
2126                 duration="<1 second"
2127         else
2128                 duration=$duration" seconds"
2129         fi
2130         echo " Timer duration :" $duration
2131         res="-"
2132         if [ $(($RES_FAIL+$RES_CONF_FAIL)) -ne $TC_TIMER_CURRENT_FAILS ]; then
2133                 res="Failures occured during test - timer not reliabled"
2134         fi
2135
2136         echo -e "$TC_TIMER_TIMER_TEXT \t $duration \t $res" >> $TIMER_MEASUREMENTS
2137 }
2138
2139 # Print info about a deviations from intended tests
2140 # Each deviation counted is also printed in the testreport
2141 # args <deviation message to print>
2142 deviation() {
2143         echo -e $BOLD"DEVIATION(${BASH_LINENO[0]}): "${FUNCNAME[0]} $EBOLD
2144         if [ $# -lt 1 ]; then
2145                 ((RES_CONF_FAIL++))
2146                 __print_err "need 1 or more args,  <deviation message to print>" $@
2147                 exit 1
2148         fi
2149         ((RES_DEVIATION++))
2150         echo -e $BOLD$YELLOW" Test case deviation: ${@:1}"$EYELLOW$EBOLD
2151         echo "Line: ${BASH_LINENO[0]} - ${@:1}" >> $DEVIATION_FILE
2152         __print_current_stats
2153         echo ""
2154 }
2155
2156 # Stop at first FAIL test case and take all logs - only for debugging/trouble shooting
2157 __check_stop_at_error() {
2158         if [ $STOP_AT_ERROR -eq 1 ]; then
2159                 echo -e $RED"Test script configured to stop at first FAIL, taking all logs and stops"$ERED
2160                 store_logs "STOP_AT_ERROR"
2161
2162                 # Update test suite counter
2163                 if [ -f .tmp_tcsuite_fail_ctr ]; then
2164                         tmpval=$(< .tmp_tcsuite_fail_ctr)
2165                         ((tmpval++))
2166                         echo $tmpval > .tmp_tcsuite_fail_ctr
2167                 fi
2168                 if [ -f .tmp_tcsuite_fail ]; then
2169                         echo " - "$ATC " -- "$TC_ONELINE_DESCR"  Execution stopped due to error" >> .tmp_tcsuite_fail
2170                 fi
2171                 exit 1
2172         fi
2173         return 0
2174 }
2175
2176 # Stop and remove all containers
2177 # args: -
2178 # (Not for test scripts)
2179 __clean_containers() {
2180
2181         echo -e $BOLD"Docker clean and stopping and removing all running containers, by container name"$EBOLD
2182
2183         #Create empty file
2184         running_contr_file="./tmp/running_contr.txt"
2185         > $running_contr_file
2186
2187         # Get list of all containers started by the test script
2188         for imagename in $APP_SHORT_NAMES; do
2189                 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
2190         done
2191         running_contr_file_empty="No docker containers running, started by previous test execution"
2192         if [ -s $running_contr_file ]; then
2193                 running_contr_file_empty=""
2194         fi
2195
2196         # Kill all containers started by the test env - to speed up shut down
2197     docker kill $(docker ps -a  --filter "label=nrttest_app" --format '{{.Names}}') &> /dev/null
2198
2199         tab_heading1="App display name"
2200         tab_heading2="App short name"
2201         tab_heading3="Container name"
2202
2203         tab_heading1_len=${#tab_heading1}
2204         tab_heading2_len=${#tab_heading2}
2205         tab_heading3_len=${#tab_heading3}
2206         cntr=0
2207         #Calc field lengths of each item in the list of containers
2208         while read p; do
2209                 if (( $cntr % 3 == 0 ));then
2210                         if [ ${#p} -gt $tab_heading1_len ]; then
2211                                 tab_heading1_len=${#p}
2212                         fi
2213                 fi
2214                 if (( $cntr % 3 == 1));then
2215                         if [ ${#p} -gt $tab_heading2_len ]; then
2216                                 tab_heading2_len=${#p}
2217                         fi
2218                 fi
2219                 if (( $cntr % 3 == 2));then
2220                         if [ ${#p} -gt $tab_heading3_len ]; then
2221                                 tab_heading3_len=${#p}
2222                         fi
2223                 fi
2224                 let cntr=cntr+1
2225         done <$running_contr_file
2226
2227         let tab_heading1_len=tab_heading1_len+2
2228         while (( ${#tab_heading1} < $tab_heading1_len)); do
2229                 tab_heading1="$tab_heading1"" "
2230         done
2231
2232         let tab_heading2_len=tab_heading2_len+2
2233         while (( ${#tab_heading2} < $tab_heading2_len)); do
2234                 tab_heading2="$tab_heading2"" "
2235         done
2236
2237         let tab_heading3_len=tab_heading3_len+2
2238         while (( ${#tab_heading3} < $tab_heading3_len)); do
2239                 tab_heading3="$tab_heading3"" "
2240         done
2241
2242         if [ ! -z "$running_contr_file_empty" ]; then
2243                 echo $running_contr_file_empty | indent1
2244         else
2245                 echo " $tab_heading1$tab_heading2$tab_heading3"" Actions"
2246                 cntr=0
2247                 while read p; do
2248                         if (( $cntr % 3 == 0 ));then
2249                                 row=""
2250                                 heading=$p
2251                                 heading_len=$tab_heading1_len
2252                         fi
2253                         if (( $cntr % 3 == 1));then
2254                                 heading=$p
2255                                 heading_len=$tab_heading2_len
2256                         fi
2257                         if (( $cntr % 3 == 2));then
2258                                 contr=$p
2259                                 heading=$p
2260                                 heading_len=$tab_heading3_len
2261                         fi
2262                         while (( ${#heading} < $heading_len)); do
2263                                 heading="$heading"" "
2264                         done
2265                         row=$row$heading
2266                         if (( $cntr % 3 == 2));then
2267                                 echo -ne $row$SAMELINE
2268                                 echo -ne " $row ${GREEN}stopping...${EGREEN}${SAMELINE}"
2269                                 docker stop $(docker ps -qa --filter name=${contr} --filter network=$DOCKER_SIM_NWNAME) &> /dev/null
2270                                 echo -ne " $row ${GREEN}stopped removing...${EGREEN}${SAMELINE}"
2271                                 docker rm --force $(docker ps -qa --filter name=${contr} --filter network=$DOCKER_SIM_NWNAME) &> /dev/null
2272                                 echo -e  " $row ${GREEN}stopped removed     ${EGREEN}"
2273                         fi
2274                         let cntr=cntr+1
2275                 done <$running_contr_file
2276         fi
2277
2278         echo ""
2279
2280         echo -e $BOLD" Removing docker network"$EBOLD
2281         TMP=$(docker network ls -q --filter name=$DOCKER_SIM_NWNAME)
2282         if [ "$TMP" ==  $DOCKER_SIM_NWNAME ]; then
2283                 docker network rm $DOCKER_SIM_NWNAME | indent2
2284                 if [ $? -ne 0 ];  then
2285                         echo -e $RED" Cannot remove docker network. Manually remove or disconnect containers from $DOCKER_SIM_NWNAME"$ERED
2286                         exit 1
2287                 fi
2288         fi
2289         echo -e "$GREEN  Done$EGREEN"
2290
2291         echo -e $BOLD" Removing all unused docker neworks"$EBOLD
2292         docker network prune --force | indent2
2293         echo -e "$GREEN  Done$EGREEN"
2294
2295         echo -e $BOLD" Removing all unused docker volumes"$EBOLD
2296         docker volume prune --force | indent2
2297         echo -e "$GREEN  Done$EGREEN"
2298
2299         echo -e $BOLD" Removing all dangling/untagged docker images"$EBOLD
2300     docker rmi --force $(docker images -q -f dangling=true) &> /dev/null
2301         echo -e "$GREEN  Done$EGREEN"
2302         echo ""
2303
2304         CONTRS=$(docker ps | awk '$1 != "CONTAINER" { n++ }; END { print n+0 }')
2305         if [ $? -eq 0 ]; then
2306                 if [ $CONTRS -ne 0 ]; then
2307                         echo -e $RED"Containers running, may cause distubance to the test case"$ERED
2308                         docker ps -a | indent1
2309                         echo ""
2310                 fi
2311         fi
2312 }
2313
2314 ###################################
2315 ### Functions for kube management
2316 ###################################
2317
2318 # Get resource type for scaling
2319 # args: <resource-name> <namespace>
2320 __kube_get_resource_type() {
2321         kubectl $KUBECONF get deployment $1 -n $2 1> /dev/null 2> ./tmp/kubeerr
2322         if [ $? -eq 0 ]; then
2323                 echo "deployment"
2324                 return 0
2325         fi
2326         kubectl $KUBECONF get sts $1 -n $2 1> /dev/null 2> ./tmp/kubeerr
2327         if [ $? -eq 0 ]; then
2328                 echo "sts"
2329                 return 0
2330         fi
2331         echo "unknown-resource-type"
2332         return 1
2333 }
2334
2335 # Scale a kube resource to a specific count
2336 # args: <resource-type> <resource-name> <namespace> <target-count>
2337 # (Not for test scripts)
2338 __kube_scale() {
2339         echo -ne "  Setting $1 $2 replicas=$4 in namespace $3"$SAMELINE
2340         kubectl $KUBECONF scale  $1 $2  -n $3 --replicas=$4 1> /dev/null 2> ./tmp/kubeerr
2341         if [ $? -ne 0 ]; then
2342                 echo -e "  Setting $1 $2 replicas=$4 in namespace $3 $RED Failed $ERED"
2343                 ((RES_CONF_FAIL++))
2344                 echo "  Message: $(<./tmp/kubeerr)"
2345                 return 1
2346         else
2347                 echo -e "  Setting $1 $2 replicas=$4 in namespace $3 $GREEN OK $EGREEN"
2348         fi
2349
2350         TSTART=$SECONDS
2351
2352         for i in {1..500}; do
2353                 count=$(kubectl $KUBECONF get $1/$2  -n $3 -o jsonpath='{.status.replicas}' 2> /dev/null)
2354                 retcode=$?
2355                 if [ -z "$count" ]; then
2356                         #No value is sometimes returned for some reason, in case the resource has replica 0
2357                         count=0
2358                 fi
2359                 if [ $retcode -ne 0 ]; then
2360                         echo -e "$RED  Cannot fetch current replica count for $1 $2 in namespace $3 $ERED"
2361                         ((RES_CONF_FAIL++))
2362                         return 1
2363                 fi
2364                 #echo ""
2365                 if [ $count -ne $4 ]; then
2366                         echo -ne "  Waiting for $1 $2 replicas=$4 in namespace $3. Replicas=$count after $(($SECONDS-$TSTART)) seconds $SAMELINE"
2367                         sleep $i
2368                 else
2369                         echo -e "  Waiting for $1 $2 replicas=$4 in namespace $3. Replicas=$count after $(($SECONDS-$TSTART)) seconds"
2370                         echo -e "  Replicas=$4 after $(($SECONDS-$TSTART)) seconds $GREEN OK $EGREEN"
2371                         echo ""
2372                         return 0
2373                 fi
2374         done
2375         echo ""
2376         echo -e "$RED  Replica count did not reach target replicas=$4. Failed with replicas=$count $ERED"
2377         ((RES_CONF_FAIL++))
2378         return 0
2379 }
2380
2381 # Scale all kube resource sets to 0 in a namespace for resources having a certain lable and label-id
2382 # This function does not wait for the resource to reach 0
2383 # args: <namespace> <label-name> <label-id>
2384 # (Not for test scripts)
2385 __kube_scale_all_resources() {
2386         namespace=$1
2387         labelname=$2
2388         labelid=$3
2389         resources="deployment replicaset statefulset"
2390         for restype in $resources; do
2391                 result=$(kubectl $KUBECONF get $restype -n $namespace -o jsonpath='{.items[?(@.metadata.labels.'$labelname'=="'$labelid'")].metadata.name}')
2392                 if [ $? -eq 0 ] && [ ! -z "$result" ]; then
2393                         for resid in $result; do
2394                                 echo -ne "  Ordered scaling $restype $resid in namespace $namespace with label $labelname=$labelid to 0"$SAMELINE
2395                                 kubectl $KUBECONF scale  $restype $resid  -n $namespace --replicas=0 1> /dev/null 2> ./tmp/kubeerr
2396                                 echo -e "  Ordered scaling $restype $resid in namespace $namespace with label $labelname=$labelid to 0 $GREEN OK $EGREEN"
2397                         done
2398                 fi
2399         done
2400 }
2401
2402 # Scale all kube resource sets to 0 in a namespace for resources having a certain lable and an optional label-id
2403 # This function do wait for the resource to reach 0
2404 # args: <namespace> <label-name> [ <label-id> ]
2405 # (Not for test scripts)
2406 __kube_scale_and_wait_all_resources() {
2407         namespace=$1
2408         labelname=$2
2409         labelid=$3
2410         if [ -z "$3" ]; then
2411                 echo "  Attempt to scale - deployment replicaset statefulset - in namespace $namespace with label $labelname"
2412         else
2413                 echo "  Attempt to scale - deployment replicaset statefulset - in namespace $namespace with label $labelname=$labelid"
2414         fi
2415         resources="deployment replicaset statefulset"
2416         scaled_all=1
2417         while [ $scaled_all -ne 0 ]; do
2418                 scaled_all=0
2419                 for restype in $resources; do
2420                     if [ -z "$3" ]; then
2421                                 result=$(kubectl $KUBECONF get $restype -n $namespace -o jsonpath='{.items[?(@.metadata.labels.'$labelname')].metadata.name}')
2422                         else
2423                                 result=$(kubectl $KUBECONF get $restype -n $namespace -o jsonpath='{.items[?(@.metadata.labels.'$labelname'=="'$labelid'")].metadata.name}')
2424                         fi
2425                         if [ $? -eq 0 ] && [ ! -z "$result" ]; then
2426                                 for resid in $result; do
2427                                         echo -e "   Ordered scaling $restype $resid in namespace $namespace with label $labelname=$labelid to 0"
2428                                         kubectl $KUBECONF scale  $restype $resid  -n $namespace --replicas=0 1> /dev/null 2> ./tmp/kubeerr
2429                                         count=1
2430                                         T_START=$SECONDS
2431                                         while [ $count -ne 0 ]; do
2432                                                 count=$(kubectl $KUBECONF get $restype $resid  -n $namespace -o jsonpath='{.status.replicas}' 2> /dev/null)
2433                                                 echo -ne "    Scaling $restype $resid in namespace $namespace with label $labelname=$labelid to 0, current count=$count"$SAMELINE
2434                                                 if [ $? -eq 0 ] && [ ! -z "$count" ]; then
2435                                                         sleep 0.5
2436                                                 else
2437                                                         count=0
2438                                                 fi
2439                                                 duration=$(($SECONDS-$T_START))
2440                                                 if [ $duration -gt 100 ]; then
2441                                                         #Forcring count 0, to avoid hanging for failed scaling
2442                                                         scaled_all=1
2443                                                         count=0
2444                                                 fi
2445                                         done
2446                                         echo -e "    Scaled $restype $resid in namespace $namespace with label $labelname=$labelid to 0, current count=$count $GREEN OK $EGREEN"
2447                                 done
2448                         fi
2449                 done
2450         done
2451 }
2452
2453 # Remove all kube resources in a namespace for resources having a certain label and label-id
2454 # This function wait until the resources are gone. Scaling to 0 must have been ordered previously
2455 # args: <namespace> <label-name> <label-id>
2456 # (Not for test scripts)
2457 __kube_delete_all_resources() {
2458         namespace=$1
2459         labelname=$2
2460         labelid=$3
2461         resources="deployments replicaset statefulset services pods configmaps persistentvolumeclaims persistentvolumes serviceaccounts clusterrolebindings secrets authorizationpolicies requestauthentications"
2462         deleted_resourcetypes=""
2463         for restype in $resources; do
2464                 ns_flag="-n $namespace"
2465                 ns_text="in namespace $namespace"
2466                 if [ $restype == "persistentvolumes" ]; then
2467                         ns_flag=""
2468                         ns_text=""
2469                 fi
2470                 if [ $restype == "clusterrolebindings" ]; then
2471                         ns_flag=""
2472                         ns_text=""
2473                 fi
2474                 result=$(kubectl $KUBECONF get $restype $ns_flag -o jsonpath='{.items[?(@.metadata.labels.'$labelname'=="'$labelid'")].metadata.name}' 2> /dev/null)
2475                 if [ $? -eq 0 ] && [ ! -z "$result" ]; then
2476                         deleted_resourcetypes=$deleted_resourcetypes" "$restype
2477                         for resid in $result; do
2478                                 if [ $restype == "replicaset" ] || [ $restype == "statefulset" ]; then
2479                                         count=1
2480                                         while [ $count -ne 0 ]; do
2481                                                 count=$(kubectl $KUBECONF get $restype $resid  $ns_flag -o jsonpath='{.status.replicas}' 2> /dev/null)
2482                                                 echo -ne "  Scaling $restype $resid $ns_text with label $labelname=$labelid to 0, current count=$count"$SAMELINE
2483                                                 if [ $? -eq 0 ] && [ ! -z "$count" ]; then
2484                                                         sleep 0.5
2485                                                 else
2486                                                         count=0
2487                                                 fi
2488                                         done
2489                                         echo -e "  Scaled $restype $resid $ns_text with label $labelname=$labelid to 0, current count=$count $GREEN OK $EGREEN"
2490                                 fi
2491                                 echo -ne "  Deleting $restype $resid $ns_text with label $labelname=$labelid "$SAMELINE
2492                                 kubectl $KUBECONF delete --grace-period=1 $restype $resid $ns_flag 1> /dev/null 2> ./tmp/kubeerr
2493                                 if [ $? -eq 0 ]; then
2494                                         echo -e "  Deleted $restype $resid $ns_text with label $labelname=$labelid $GREEN OK $EGREEN"
2495                                 else
2496                                         echo -e "  Deleted $restype $resid $ns_text with label $labelname=$labelid $GREEN Does not exist - OK $EGREEN"
2497                                 fi
2498                                 #fi
2499                         done
2500                 fi
2501         done
2502         if [ ! -z "$deleted_resourcetypes" ]; then
2503                 for restype in $deleted_resources; do
2504                         ns_flag="-n $namespace"
2505                         ns_text="in namespace $namespace"
2506                         if [ $restype == "persistentvolumes" ]; then
2507                                 ns_flag=""
2508                                 ns_text=""
2509                         fi
2510                         echo -ne "  Waiting for $restype $ns_text with label $labelname=$labelid to be deleted..."$SAMELINE
2511                         T_START=$SECONDS
2512                         result="dummy"
2513                         while [ ! -z "$result" ]; do
2514                                 sleep 0.5
2515                                 result=$(kubectl $KUBECONF get $restype $ns_flag -o jsonpath='{.items[?(@.metadata.labels.'$labelname'=="'$labelid'")].metadata.name}')
2516                                 echo -ne "  Waiting for $restype $ns_text with label $labelname=$labelid to be deleted...$(($SECONDS-$T_START)) seconds "$SAMELINE
2517                                 if [ -z "$result" ]; then
2518                                         echo -e " Waiting for $restype $ns_text with label $labelname=$labelid to be deleted...$(($SECONDS-$T_START)) seconds $GREEN OK $EGREEN"
2519                                 elif [ $(($SECONDS-$T_START)) -gt 300 ]; then
2520                                         echo -e " Waiting for $restype $ns_text with label $labelname=$labelid to be deleted...$(($SECONDS-$T_START)) seconds $RED Failed $ERED"
2521                                         result=""
2522                                 fi
2523                         done
2524                 done
2525         fi
2526 }
2527
2528 # Creates a namespace if it does not exists
2529 # args: <namespace>
2530 # (Not for test scripts)
2531 __kube_create_namespace() {
2532
2533         #Check if test namespace exists, if not create it
2534         kubectl $KUBECONF get namespace $1 1> /dev/null 2> ./tmp/kubeerr
2535         if [ $? -ne 0 ]; then
2536                 echo -ne " Creating namespace "$1 $SAMELINE
2537                 kubectl $KUBECONF create namespace $1 1> /dev/null 2> ./tmp/kubeerr
2538                 if [ $? -ne 0 ]; then
2539                         echo -e " Creating namespace $1 $RED$BOLD FAILED $EBOLD$ERED"
2540                         ((RES_CONF_FAIL++))
2541                         echo "  Message: $(<./tmp/kubeerr)"
2542                         return 1
2543                 else
2544                         kubectl $KUBECONF label ns $1 autotest=engine > /dev/null
2545                         echo -e " Creating namespace $1 $GREEN$BOLD OK $EBOLD$EGREEN"
2546                 fi
2547         else
2548                 echo -e " Creating namespace $1 $GREEN$BOLD Already exists, OK $EBOLD$EGREEN"
2549         fi
2550         return 0
2551 }
2552
2553 # Removes a namespace if it exists
2554 # args: <namespace>
2555 # (Not for test scripts)
2556 __kube_delete_namespace() {
2557
2558         #Check if test namespace exists, if so remove it
2559         kubectl $KUBECONF get namespace $1 1> /dev/null 2> ./tmp/kubeerr
2560         if [ $? -eq 0 ]; then
2561                 echo -ne " Removing namespace "$1 $SAMELINE
2562                 kubectl $KUBECONF delete namespace $1 1> /dev/null 2> ./tmp/kubeerr
2563                 if [ $? -ne 0 ]; then
2564                         echo -e " Removing namespace $1 $RED$BOLD FAILED $EBOLD$ERED"
2565                         ((RES_CONF_FAIL++))
2566                         echo "  Message: $(<./tmp/kubeerr)"
2567                         return 1
2568                 else
2569                         echo -e " Removing namespace $1 $GREEN$BOLD OK $EBOLD$EGREEN"
2570                 fi
2571         else
2572                 echo -e " Namespace $1 $GREEN$BOLD does not exist, OK $EBOLD$EGREEN"
2573         fi
2574         return 0
2575 }
2576
2577 # Removes and re-create a namespace
2578 # args: <namespace>
2579 # (Not for test scripts)
2580 clean_and_create_namespace() {
2581         __log_conf_start $@
2582
2583     if [ $# -ne 1 ]; then
2584                 __print_err "<namespace>" $@
2585                 return 1
2586         fi
2587         __kube_delete_namespace $1
2588         if [ $? -ne 0 ]; then
2589                 return 1
2590         fi
2591         __kube_create_namespace $1
2592         if [ $? -ne 0 ]; then
2593                 return 1
2594         fi
2595 }
2596
2597 # Add/remove label on non-namespaced kube object
2598 # args: <api> <instance> <label>
2599 # (Not for test scripts)
2600 __kube_label_non_ns_instance() {
2601         kubectl $KUBECONF label $1 $2 "$3" 1> /dev/null 2> ./tmp/kubeerr
2602         return $?
2603 }
2604
2605 # Add/remove label on namespaced kube object
2606 # args: <api> <instance> <namespace> <label>
2607 # (Not for test scripts)
2608 __kube_label_ns_instance() {
2609         kubectl $KUBECONF label $1 $2 -n $3 "$4" 1> /dev/null 2> ./tmp/kubeerr
2610         return $?
2611 }
2612
2613 # Find the host ip of an app (using the service resource)
2614 # args: <app-name> <namespace>
2615 # (Not for test scripts)
2616 __kube_get_service_host() {
2617         if [ $# -ne 2 ]; then
2618                 ((RES_CONF_FAIL++))
2619         __print_err "need 2 args, <app-name> <namespace>" $@
2620                 exit 1
2621         fi
2622         for timeout in {1..60}; do
2623                 host=$(kubectl $KUBECONF get svc $1  -n $2 -o jsonpath='{.spec.clusterIP}')
2624                 if [ $? -eq 0 ]; then
2625                         if [ ! -z "$host" ]; then
2626                                 echo $host
2627                                 return 0
2628                         fi
2629                 fi
2630                 sleep 0.5
2631         done
2632         ((RES_CONF_FAIL++))
2633         echo "host-not-found-fatal-error"
2634         return 1
2635 }
2636
2637 # Find the named port to an app (using the service resource)
2638 # args: <app-name> <namespace> <port-name>
2639 # (Not for test scripts)
2640 __kube_get_service_port() {
2641         if [ $# -ne 3 ]; then
2642                 ((RES_CONF_FAIL++))
2643         __print_err "need 3 args, <app-name> <namespace> <port-name>" $@
2644                 exit 1
2645         fi
2646
2647         for timeout in {1..60}; do
2648                 port=$(kubectl $KUBECONF get svc $1  -n $2 -o jsonpath='{...ports[?(@.name=="'$3'")].port}')
2649                 if [ $? -eq 0 ]; then
2650                         if [ ! -z "$port" ]; then
2651                                 echo $port
2652                                 return 0
2653                         fi
2654                 fi
2655                 sleep 0.5
2656         done
2657         ((RES_CONF_FAIL++))
2658         echo "0"
2659         return 1
2660 }
2661
2662 # Find the named node port to an app (using the service resource)
2663 # args: <app-name> <namespace> <port-name>
2664 # (Not for test scripts)
2665 __kube_get_service_nodeport() {
2666         if [ $# -ne 3 ]; then
2667                 ((RES_CONF_FAIL++))
2668         __print_err "need 3 args, <app-name> <namespace> <port-name>" $@
2669                 exit 1
2670         fi
2671
2672         for timeout in {1..60}; do
2673                 port=$(kubectl $KUBECONF get svc $1  -n $2 -o jsonpath='{...ports[?(@.name=="'$3'")].nodePort}')
2674                 if [ $? -eq 0 ]; then
2675                         if [ ! -z "$port" ]; then
2676                                 echo $port
2677                                 return 0
2678                         fi
2679                 fi
2680                 sleep 0.5
2681         done
2682         ((RES_CONF_FAIL++))
2683         echo "0"
2684         return 1
2685 }
2686
2687 # Create a kube resource from a yaml template
2688 # args: <resource-type> <resource-name> <template-yaml> <output-yaml>
2689 # (Not for test scripts)
2690 __kube_create_instance() {
2691         echo -ne " Creating $1 $2"$SAMELINE
2692         envsubst < $3 > $4
2693         kubectl $KUBECONF apply -f $4 1> /dev/null 2> ./tmp/kubeerr
2694         if [ $? -ne 0 ]; then
2695                 ((RES_CONF_FAIL++))
2696                 echo -e " Creating $1 $2 $RED Failed $ERED"
2697                 echo "  Message: $(<./tmp/kubeerr)"
2698                 return 1
2699         else
2700                 echo -e " Creating $1 $2 $GREEN OK $EGREEN"
2701         fi
2702 }
2703
2704 # Function to create a configmap in kubernetes
2705 # args: <configmap-name> <namespace> <labelname> <labelid> <path-to-data-file> <path-to-output-yaml>
2706 # (Not for test scripts)
2707 __kube_create_configmap() {
2708         echo -ne " Creating configmap $1 "$SAMELINE
2709         envsubst < $5 > $5"_tmp"
2710         cp $5"_tmp" $5  #Need to copy back to orig file name since create configmap neeed the original file name
2711         kubectl $KUBECONF create configmap $1  -n $2 --from-file=$5 --dry-run=client -o yaml > $6
2712         if [ $? -ne 0 ]; then
2713                 echo -e " Creating configmap $1 $RED Failed $ERED"
2714                 ((RES_CONF_FAIL++))
2715                 return 1
2716         fi
2717
2718         kubectl $KUBECONF apply -f $6 1> /dev/null 2> ./tmp/kubeerr
2719         if [ $? -ne 0 ]; then
2720                 echo -e " Creating configmap $1 $RED Apply failed $ERED"
2721                 echo "  Message: $(<./tmp/kubeerr)"
2722                 ((RES_CONF_FAIL++))
2723                 return 1
2724         fi
2725         kubectl $KUBECONF label configmap $1 -n $2 $3"="$4 --overwrite 1> /dev/null 2> ./tmp/kubeerr
2726         if [ $? -ne 0 ]; then
2727                 echo -e " Creating configmap $1 $RED Labeling failed $ERED"
2728                 echo "  Message: $(<./tmp/kubeerr)"
2729                 ((RES_CONF_FAIL++))
2730                 return 1
2731         fi
2732         # Log the resulting map
2733         kubectl $KUBECONF get configmap $1 -n $2 -o yaml > $6
2734
2735         echo -e " Creating configmap $1 $GREEN OK $EGREEN"
2736         return 0
2737 }
2738
2739 # This function runs a kubectl cmd where a single output value is expected, for example get ip with jsonpath filter.
2740 # The function retries up to the timeout given in the cmd flag '--cluster-timeout'
2741 # args: <full kubectl cmd with parameters>
2742 # (Not for test scripts)
2743 __kube_cmd_with_timeout() {
2744         TS_TMP=$(($SECONDS+$CLUSTER_TIME_OUT))
2745
2746         while true; do
2747                 kube_cmd_result=$($@)
2748                 if [ $? -ne 0 ]; then
2749                         kube_cmd_result=""
2750                 fi
2751                 if [ $SECONDS -ge $TS_TMP ] || [ ! -z "$kube_cmd_result" ] ; then
2752                         echo $kube_cmd_result
2753                         return 0
2754                 fi
2755                 sleep 1
2756         done
2757 }
2758
2759 # This function starts a pod that cleans a the contents of a path mounted as a pvc
2760 # After this action the pod should terminate
2761 # This should only be executed when the pod owning the pvc is not running
2762 # args: <appname> <namespace> <pvc-name> <path-to remove>
2763 # (Not for test scripts)
2764 __kube_clean_pvc() {
2765
2766         #using env vars setup in pvccleaner_api_functions.sh
2767
2768         export PVC_CLEANER_NAMESPACE=$2
2769         export PVC_CLEANER_CLAIMNAME=$3
2770         export PVC_CLEANER_RM_PATH=$4
2771         export PVC_CLEANER_APP_NAME
2772         input_yaml=$SIM_GROUP"/"$PVC_CLEANER_COMPOSE_DIR"/"pvc-cleaner.yaml
2773         output_yaml=$PWD/tmp/$2-pvc-cleaner.yaml
2774
2775         envsubst < $input_yaml > $output_yaml
2776
2777         kubectl $KUBECONF delete -f $output_yaml 1> /dev/null 2> /dev/null   # Delete the previous terminated pod - if existing
2778
2779         __kube_create_instance pod $PVC_CLEANER_APP_NAME $input_yaml $output_yaml
2780         if [ $? -ne 0 ]; then
2781                 echo $YELLOW" Could not clean pvc for app: $1 - persistent storage not clean - tests may not work"
2782                 return 1
2783         fi
2784
2785         term_ts=$(($SECONDS+30))
2786         while [ $term_ts -gt $SECONDS ]; do
2787                 pod_status=$(kubectl $KUBECONF get pod pvc-cleaner -n $PVC_CLEANER_NAMESPACE --no-headers -o custom-columns=":status.phase")
2788                 if [ "$pod_status" == "Succeeded" ]; then
2789                         return 0
2790                 fi
2791         done
2792         return 1
2793 }
2794
2795 # This function scales or deletes all resources for app selected by the testcase.
2796 # args: -
2797 # (Not for test scripts)
2798 __clean_kube() {
2799         echo -e $BOLD"Initialize kube pods/statefulsets/replicaset to initial state"$EBOLD
2800
2801         # Scale prestarted or managed apps
2802         for imagename in $APP_SHORT_NAMES; do
2803                 # A function name is created from the app short name
2804                 # for example app short name 'RICMSIM' -> produce the function
2805                 # name __RICSIM_kube_scale_zero or __RICSIM_kube_scale_zero_and_wait
2806                 # This function is called and is expected to exist in the imported
2807                 # file for the ricsim test functions
2808                 # The resulting function impl shall scale the resources to 0
2809                 # For pre-started apps, the function waits until the resources are 0
2810                 # For included (not prestated) apps, the scaling is just ordered
2811                 __check_prestarted_image $imagename
2812                 if [ $? -eq 0 ]; then
2813                         function_pointer="__"$imagename"_kube_scale_zero_and_wait"
2814                         echo -e " Scaling all kube resources for app $BOLD $imagename $EBOLD to 0"
2815                         $function_pointer
2816                 else
2817                         __check_included_image $imagename
2818                         if [ $? -eq 0 ]; then
2819                                 function_pointer="__"$imagename"_kube_scale_zero"
2820                                 echo -e " Scaling all kube resources for app $BOLD $imagename $EBOLD to 0"
2821                                 $function_pointer
2822                         fi
2823                 fi
2824         done
2825
2826         # Delete managed apps
2827         for imagename in $APP_SHORT_NAMES; do
2828                 __check_included_image $imagename
2829                 if [ $? -eq 0 ]; then
2830                         __check_prestarted_image $imagename
2831                         if [ $? -ne 0 ]; then
2832                                 # A function name is created from the app short name
2833                                 # for example app short name 'RICMSIM' -> produce the function
2834                                 # name __RICSIM__kube_delete_all
2835                                 # This function is called and is expected to exist in the imported
2836                                 # file for the ricsim test functions
2837                                 # The resulting function impl shall delete all its resources
2838                                 function_pointer="__"$imagename"_kube_delete_all"
2839                                 echo -e " Deleting all kube resources for app $BOLD $imagename $EBOLD"
2840                                 $function_pointer
2841                         fi
2842                 fi
2843         done
2844
2845         # Remove istio label on namespaces
2846         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
2847         if [ $? -ne 0 ]; then
2848                 echo " Cannot get list of namespaces...continues.."
2849         else
2850                 for test_env_ns in $test_env_namespaces; do
2851                         echo " Removing istio label on ns: "$test_env_ns
2852                         __kube_label_non_ns_instance ns $test_env_ns "istio-injection-"
2853                 done
2854         fi
2855
2856         echo ""
2857 }
2858
2859 # Function stop and remove all containers (docker) and services/deployments etc(kube)
2860 # args: -
2861 # Function for test script
2862 clean_environment() {
2863         if [ $RUNMODE == "KUBE" ]; then
2864                 __clean_kube
2865                 if [ $PRE_CLEAN -eq 1 ]; then
2866                         echo " Cleaning docker resouces to free up resources, may take time..."
2867                         ../common/clean_docker.sh 2>&1 > /dev/null
2868                         echo ""
2869                 fi
2870         else
2871                 __clean_containers
2872                 if [ $PRE_CLEAN -eq 1 ]; then
2873                         echo " Cleaning kubernetes resouces to free up resources, may take time..."
2874                         ../common/clean_kube.sh $KUBECONF 2>&1 > /dev/null
2875                         echo ""
2876                 fi
2877         fi
2878 }
2879
2880 # 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
2881 # args: -
2882 # (Function for test scripts)
2883 auto_clean_environment() {
2884         echo
2885         if [ "$AUTO_CLEAN" == "auto" ]; then
2886                 echo -e $BOLD"Initiating automatic cleaning of environment"$EBOLD
2887                 clean_environment
2888         fi
2889 }
2890
2891 # Function to sleep a test case for a numner of seconds. Prints the optional text args as info
2892 # args: <sleep-time-in-sec> [any-text-in-quotes-to-be-printed]
2893 # (Function for test scripts)
2894 sleep_wait() {
2895
2896         echo -e $BOLD"INFO(${BASH_LINENO[0]}): "${FUNCNAME[0]}"," $@ $EBOLD
2897         if [ $# -lt 1 ]; then
2898                 ((RES_CONF_FAIL++))
2899                 __print_err "need at least one arg, <sleep-time-in-sec> [any-text-to-printed]" $@
2900                 exit 1
2901         fi
2902         #echo "---- Sleep for " $1 " seconds ---- "$2
2903         start=$SECONDS
2904         duration=$((SECONDS-start))
2905         while [ $duration -lt $1 ]; do
2906                 echo -ne "  Slept for ${duration} seconds${SAMELINE}"
2907                 sleep 1
2908                 duration=$((SECONDS-start))
2909         done
2910         echo -ne "  Slept for ${duration} seconds${SAMELINE}"
2911         echo ""
2912 }
2913
2914 # Print error info for the call in the parent script (test case). Arg: <error-message-to-print>
2915 # Not to be called from the test script itself.
2916 __print_err() {
2917     echo -e $RED ${FUNCNAME[1]} " "$1" " ${BASH_SOURCE[2]} " line" ${BASH_LINENO[1]} $ERED
2918         if [ $# -gt 1 ]; then
2919                 echo -e $RED" Got: "${FUNCNAME[1]} ${@:2} $ERED
2920         fi
2921         ((RES_CONF_FAIL++))
2922         __check_stop_at_error
2923 }
2924
2925 # Function to create the docker network for the test
2926 # Not to be called from the test script itself.
2927 __create_docker_network() {
2928         tmp=$(docker network ls --format={{.Name}} --filter name=$DOCKER_SIM_NWNAME)
2929         if [ $? -ne 0 ]; then
2930                 echo -e $RED" Could not check if docker network $DOCKER_SIM_NWNAME exists"$ERED
2931                 return 1
2932         fi
2933         if [ "$tmp" != $DOCKER_SIM_NWNAME ]; then
2934                 echo -e " Creating docker network:$BOLD $DOCKER_SIM_NWNAME $EBOLD"
2935                 docker network create $DOCKER_SIM_NWNAME | indent2
2936                 if [ $? -ne 0 ]; then
2937                         echo -e $RED" Could not create docker network $DOCKER_SIM_NWNAME"$ERED
2938                         return 1
2939                 else
2940                         echo -e "$GREEN  Done$EGREEN"
2941                 fi
2942         else
2943                 echo -e " Docker network $DOCKER_SIM_NWNAME already exists$GREEN OK $EGREEN"
2944         fi
2945 }
2946
2947 # Function to start container with docker-compose and wait until all are in state running.
2948 # If the <docker-compose-file> is empty, the default 'docker-compose.yml' is assumed.
2949 #args: <docker-compose-dir> <docker-compose-file> <docker-compose-arg>|NODOCKERARGS <count> <app-name>+
2950 # (Not for test scripts)
2951 __start_container() {
2952
2953         if [ $# -lt 5 ]; then
2954                 ((RES_CONF_FAIL++))
2955         __print_err "need 5 or more args, <docker-compose-dir> <docker-compose-file> <docker-compose-arg>|NODOCKERARGS <count> <app-name>+" $@
2956                 exit 1
2957         fi
2958
2959         __create_docker_network
2960
2961         curdir=$PWD
2962         cd $SIM_GROUP
2963         compose_dir=$1
2964         cd $1
2965         shift
2966         compose_file=$1
2967         if [ -z "$compose_file" ]; then
2968                 compose_file="docker-compose.yml"
2969         fi
2970         shift
2971         compose_args=$1
2972         shift
2973         appcount=$1
2974         shift
2975
2976         envsubst < $compose_file > "gen_"$compose_file
2977         compose_file="gen_"$compose_file
2978         docker_compose_cmd="docker compose"
2979
2980         if [ "$compose_args" == "NODOCKERARGS" ]; then
2981                 $docker_compose_cmd -f $compose_file up -d &> .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         else
2989                 $docker_compose_cmd -f $compose_file up -d $compose_args &> .dockererr
2990                 if [ $? -ne 0 ]; then
2991                         echo -e $RED"Problem to launch container(s) with docker-compose"$ERED
2992                         cat .dockererr
2993                         echo -e $RED"Stopping script...."$ERED
2994                         exit 1
2995                 fi
2996         fi
2997
2998         cd $curdir
2999
3000         appindex=0
3001         while [ $appindex -lt $appcount ]; do
3002                 appname=$1
3003                 shift
3004                 app_started=0
3005                 for i in {1..10}; do
3006                         if [ "$(docker inspect --format '{{ .State.Running }}' $appname)" == "true" ]; then
3007                                         echo -e " Container $BOLD${appname}$EBOLD$GREEN running$EGREEN on$BOLD image $(docker inspect --format '{{ .Config.Image }}' ${appname}) $EBOLD"
3008                                         app_started=1
3009                                         break
3010                                 else
3011                                         sleep $i
3012                         fi
3013                 done
3014                 if [ $app_started -eq 0 ]; then
3015                         ((RES_CONF_FAIL++))
3016                         echo ""
3017                         echo -e $RED" Container $BOLD${appname}$EBOLD could not be started"$ERED
3018                         echo -e $RED" Stopping script..."$ERED
3019                         exit 1
3020                 fi
3021                 let appindex=appindex+1
3022         done
3023         return 0
3024 }
3025
3026 # Function to check if container/service is responding to http/https
3027 # args: <container-name>|<service-name> url
3028 # (Not for test scripts)
3029 __check_service_start() {
3030
3031         if [ $# -ne 2 ]; then
3032                 ((RES_CONF_FAIL++))
3033                 __print_err "need 2 args, <container-name>|<service-name> url" $@
3034                 return 1
3035         fi
3036
3037         if [ $RUNMODE == "KUBE" ]; then
3038                 ENTITY="service/set/deployment"
3039         else
3040                 ENTITY="container"
3041         fi
3042         appname=$1
3043         url=$2
3044         echo -ne " Container $BOLD${appname}$EBOLD starting${SAMELINE}"
3045
3046
3047         a1pmsst=false
3048         echo -ne " Waiting for ${ENTITY} ${appname} service status...${SAMELINE}"
3049         TSTART=$SECONDS
3050         loop_ctr=0
3051         while (( $TSTART+600 > $SECONDS )); do
3052                 result="$(__do_curl -m 10 $url)"
3053                 if [ $? -eq 0 ]; then
3054                         if [ ${#result} -gt 15 ]; then
3055                                 #If response is too long, truncate
3056                                 result="...response text too long, omitted"
3057                         fi
3058                         echo -ne " Waiting for {ENTITY} $BOLD${appname}$EBOLD service status on ${3}, result: $result${SAMELINE}"
3059                         echo -ne " The ${ENTITY} $BOLD${appname}$EBOLD$GREEN is alive$EGREEN, responds to service status:$GREEN $result $EGREEN on ${url} after $(($SECONDS-$TSTART)) seconds"
3060                         a1pmsst=true
3061                         break
3062                 else
3063                         TS_TMP=$SECONDS
3064                         TS_OFFSET=$loop_ctr
3065                         if (( $TS_OFFSET > 5 )); then
3066                                 TS_OFFSET=5
3067                         fi
3068                         while [ $(($TS_TMP+$TS_OFFSET)) -gt $SECONDS ]; do
3069                                 echo -ne " Waiting for ${ENTITY} ${appname} service status on ${url}...$(($SECONDS-$TSTART)) seconds, retrying in $(($TS_TMP+$TS_OFFSET-$SECONDS)) seconds   ${SAMELINE}"
3070                                 sleep 1
3071                         done
3072                 fi
3073                 let loop_ctr=loop_ctr+1
3074         done
3075
3076         if [ "$a1pmsst" = "false"  ]; then
3077                 ((RES_CONF_FAIL++))
3078                 echo -e $RED" The ${ENTITY} ${appname} did not respond to service status on ${url} in $(($SECONDS-$TSTART)) seconds"$ERED
3079                 return 1
3080         fi
3081
3082         echo ""
3083         return 0
3084 }
3085
3086
3087 #################
3088 ### Log functions
3089 #################
3090
3091 __check_container_logs() {
3092
3093         dispname=$1
3094         appname=$2
3095         logpath=$3
3096         warning=$4
3097         error=$5
3098
3099         echo -e $BOLD"Checking $dispname container $appname log ($logpath) for WARNINGs and ERRORs"$EBOLD
3100
3101         if [ $RUNMODE == "KUBE" ]; then
3102                 echo -e $YELLOW" Internal log for $dispname not checked in kube"$EYELLOW
3103                 return
3104         fi
3105
3106         #tmp=$(docker ps | grep $appname)
3107         tmp=$(docker ps -q --filter name=$appname) #get the container id
3108         if [ -z "$tmp" ]; then  #Only check logs for running A1PMS apps
3109                 echo " "$dispname" is not running, no check made"
3110                 return
3111         fi
3112         foundentries="$(docker exec -t $tmp grep $warning $logpath | wc -l)"
3113         if [ $? -ne  0 ];then
3114                 echo "  Problem to search $appname log $logpath"
3115         else
3116                 if [ $foundentries -eq 0 ]; then
3117                         echo "  No WARN entries found in $appname log $logpath"
3118                 else
3119                         echo -e "  Found \033[1m"$foundentries"\033[0m WARN entries in $appname log $logpath"
3120                 fi
3121         fi
3122         foundentries="$(docker exec -t $tmp grep $error $logpath | wc -l)"
3123         if [ $? -ne  0 ];then
3124                 echo "  Problem to search $appname log $logpath"
3125         else
3126                 if [ $foundentries -eq 0 ]; then
3127                         echo "  No ERR entries found in $appname log $logpath"
3128                 else
3129                         echo -e $RED"  Found \033[1m"$foundentries"\033[0m"$RED" ERR entries in $appname log $logpath"$ERED
3130                 fi
3131         fi
3132         echo ""
3133 }
3134
3135 # Store all container logs and other logs in the log dir for the script
3136 # Logs are stored with a prefix in case logs should be stored several times during a test
3137 # args: <logfile-prefix>
3138 # (Function for test scripts)
3139 store_logs() {
3140         if [ $# != 1 ]; then
3141                 ((RES_CONF_FAIL++))
3142         __print_err "need one arg, <file-prefix>" $@
3143                 exit 1
3144         fi
3145         echo -e $BOLD"Storing all docker/kube container logs and other test logs in $TESTLOGS/$ATC using prefix: "$1$EBOLD
3146
3147         docker stats --no-stream > $TESTLOGS/$ATC/$1_docker_stats.log 2>&1
3148
3149         docker ps -a  > $TESTLOGS/$ATC/$1_docker_ps.log 2>&1
3150
3151         cp .httplog_${ATC}.txt $TESTLOGS/$ATC/$1_httplog_${ATC}.txt 2>&1
3152
3153         if [ $RUNMODE == "DOCKER" ]; then
3154
3155                 # Store docker logs for all container
3156                 for imagename in $APP_SHORT_NAMES; do
3157                         __check_included_image $imagename
3158                         if [ $? -eq 0 ]; then
3159                                 # A function name is created from the app short name
3160                                 # for example app short name 'RICMSIM' -> produce the function
3161                                 # name __RICSIM__store_docker_logs
3162                                 # This function is called and is expected to exist in the imported
3163                                 # file for the ricsim test functions
3164                                 # The resulting function impl shall store the docker logs for each container
3165                                 function_pointer="__"$imagename"_store_docker_logs"
3166                                 $function_pointer "$TESTLOGS/$ATC/" $1
3167                         fi
3168                 done
3169         fi
3170         if [ $RUNMODE == "KUBE" ]; then
3171                 namespaces=$(kubectl $KUBECONF  get namespaces -o jsonpath='{.items[?(@.metadata.name)].metadata.name}')
3172                 for nsid in $namespaces; do
3173                         pods=$(kubectl $KUBECONF get pods -n $nsid -o jsonpath='{.items[?(@.metadata.labels.autotest)].metadata.name}')
3174                         for podid in $pods; do
3175                                 kubectl $KUBECONF logs -n $nsid $podid > $TESTLOGS/$ATC/$1_${podid}.log
3176                         done
3177                 done
3178         fi
3179         echo ""
3180 }
3181
3182 ###############
3183 ## Generic curl
3184 ###############
3185 # Generic curl function, assumes all 200-codes are ok
3186 # Used proxy, set
3187 # args: <valid-curl-args-including full url>
3188 # returns: <returned response (without respose code)>  or "<no-response-from-server>" or "<not found, <http-code>>""
3189 # returns: The return code is 0 for ok and 1 for not ok
3190 __do_curl() {
3191         echo ${FUNCNAME[1]} "line: "${BASH_LINENO[1]} >> $HTTPLOG
3192         proxyflag=""
3193         if [ ! -z "$KUBE_PROXY_PATH" ]; then
3194                 if [ $KUBE_PROXY_HTTPX == "http" ]; then
3195                         proxyflag=" --proxy $KUBE_PROXY_PATH"
3196                 else
3197                         proxyflag=" --proxy-insecure --proxy $KUBE_PROXY_PATH"
3198                 fi
3199         fi
3200
3201         if [ ! -z "$KUBE_PROXY_CURL_JWT" ]; then
3202                 jwt="-H "\""Authorization: Bearer $KUBE_PROXY_CURL_JWT"\"
3203                 curlString="curl -skw %{http_code} $proxyflag $@"
3204                 echo " CMD: $curlString $jwt" >> $HTTPLOG
3205                 res=$($curlString -H "Authorization: Bearer $KUBE_PROXY_CURL_JWT")
3206                 retcode=$?
3207         else
3208                 curlString="curl -skw %{http_code} $proxyflag $@"
3209                 echo " CMD: $curlString" >> $HTTPLOG
3210                 res=$($curlString)
3211                 retcode=$?
3212         fi
3213         echo " RESP: $res" >> $HTTPLOG
3214         echo " RETCODE: $retcode" >> $HTTPLOG
3215         if [ $retcode -ne 0 ]; then
3216                 echo "<no-response-from-server>"
3217                 return 1
3218         fi
3219         http_code="${res:${#res}-3}"
3220         if [ ${#res} -eq 3 ]; then
3221                 if [ $http_code -lt 200 ] || [ $http_code -gt 299 ]; then
3222                         echo "<no-response-from-server>"
3223                         return 1
3224                 else
3225                         return 0
3226                 fi
3227         else
3228                 if [ $http_code -lt 200 ] || [ $http_code -gt 299 ]; then
3229                         echo "<not found, resp:${http_code}>"
3230                         return 1
3231                 fi
3232                 if [ $# -eq 2 ]; then
3233                         echo "${res:0:${#res}-3}" | xargs
3234                 else
3235                         echo "${res:0:${#res}-3}"
3236                 fi
3237
3238                 return 0
3239         fi
3240
3241 }
3242
3243 # Generic curl function, assumes all 200-codes are ok
3244 # Uses no proxy, even if it is set
3245 # args: <valid-curl-args-including full url>
3246 # returns: <returned response (without respose code)>  or "<no-response-from-server>" or "<not found, <http-code>>""
3247 # returns: The return code is 0 for ok and 1 for not ok
3248 __do_curl_no_proxy() {
3249         echo ${FUNCNAME[1]} "line: "${BASH_LINENO[1]} >> $HTTPLOG
3250         curlString="curl -skw %{http_code} $@"
3251         echo " CMD: $curlString" >> $HTTPLOG
3252         res=$($curlString)
3253         retcode=$?
3254         echo " RESP: $res" >> $HTTPLOG
3255         echo " RETCODE: $retcode" >> $HTTPLOG
3256         if [ $retcode -ne 0 ]; then
3257                 echo "<no-response-from-server>"
3258                 return 1
3259         fi
3260         http_code="${res:${#res}-3}"
3261         if [ ${#res} -eq 3 ]; then
3262                 if [ $http_code -lt 200 ] || [ $http_code -gt 299 ]; then
3263                         echo "<no-response-from-server>"
3264                         return 1
3265                 else
3266                         return 0
3267                 fi
3268         else
3269                 if [ $http_code -lt 200 ] || [ $http_code -gt 299 ]; then
3270                         echo "<not found, resp:${http_code}>"
3271                         return 1
3272                 fi
3273                 if [ $# -eq 2 ]; then
3274                         echo "${res:0:${#res}-3}" | xargs
3275                 else
3276                         echo "${res:0:${#res}-3}"
3277                 fi
3278
3279                 return 0
3280         fi
3281 }
3282
3283 #######################################
3284 ### Basic helper function for test cases
3285 #######################################
3286
3287 # Test a simulator container variable value towards target value using an condition operator with an optional timeout.
3288 # Arg: <simulator-name> <host> <variable-name> <condition-operator> <target-value>  - This test is done
3289 # immediately and sets pass or fail depending on the result of comparing variable and target using the operator.
3290 # Arg: <simulator-name> <host> <variable-name> <condition-operator> <target-value> <timeout>  - This test waits up to the timeout
3291 # before setting pass or fail depending on the result of comparing variable and target using the operator.
3292 # 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.
3293 # Not to be called from test script.
3294
3295 __var_test() {
3296         checkjsonarraycount=0
3297         TIMESTAMP=$(date "+%Y-%m-%d %H:%M:%S")
3298         if [ $# -eq 6 ]; then
3299                 if [[ $3 == "json:"* ]]; then
3300                         checkjsonarraycount=1
3301                 fi
3302
3303                 echo -e $BOLD"TEST $TEST_SEQUENCE_NR - (${BASH_LINENO[1]}) - ${TIMESTAMP}: ${1}, ${3} ${4} ${5} within ${6} seconds"$EBOLD
3304         echo "TEST $TEST_SEQUENCE_NR - (${BASH_LINENO[1]}) - ${TIMESTAMP}: ${1}, ${3} ${4} ${5} within ${6} seconds" >> $HTTPLOG
3305
3306                 ((RES_TEST++))
3307                 ((TEST_SEQUENCE_NR++))
3308                 start=$SECONDS
3309                 ctr=0
3310                 for (( ; ; )); do
3311                         if [ $checkjsonarraycount -eq 0 ]; then
3312                                 result="$(__do_curl $2$3)"
3313                                 retcode=$?
3314                                 result=${result//[[:blank:]]/} #Strip blanks
3315                         else
3316                                 path=${3:5}
3317                                 result="$(__do_curl $2$path)"
3318                                 retcode=$?
3319                                 echo "$result" > ./tmp/.tmp.curl.json
3320                                 result=$(python3 ../common/count_json_elements.py "./tmp/.tmp.curl.json")
3321                         fi
3322                         duration=$((SECONDS-start))
3323                         echo -ne " Result=${result} after ${duration} seconds${SAMELINE}"
3324                         let ctr=ctr+1
3325                         if [ $retcode -ne 0 ]; then
3326                                 if [ $duration -gt $6 ]; then
3327                                         ((RES_FAIL++))
3328                                         echo -e $RED" FAIL${ERED} - ${3} ${4} ${5} not reached in ${6} seconds, result = ${result}"
3329                                         __print_current_stats
3330                                         __check_stop_at_error
3331                                         return
3332                                 fi
3333                         elif [ "$4" == "=" ] && [ "$result" -eq $5 ]; then
3334                                 ((RES_PASS++))
3335                                 echo -e " Result=${result} after ${duration} seconds${SAMELINE}"
3336                                 echo -e $GREEN" PASS${EGREEN} - Result=${result} after ${duration} seconds"
3337                                 __print_current_stats
3338                                 return
3339                         elif [ "$4" == ">" ] && [ "$result" -gt $5 ]; then
3340                                 ((RES_PASS++))
3341                                 echo -e " Result=${result} after ${duration} seconds${SAMELINE}"
3342                                 echo -e $GREEN" PASS${EGREEN} - Result=${result} after ${duration} seconds"
3343                                 __print_current_stats
3344                                 return
3345                         elif [ "$4" == "<" ] && [ "$result" -lt $5 ]; then
3346                                 ((RES_PASS++))
3347                                 echo -e " Result=${result} after ${duration} seconds${SAMELINE}"
3348                                 echo -e $GREEN" PASS${EGREEN} - Result=${result} after ${duration} seconds"
3349                                 __print_current_stats
3350                                 return
3351                         elif [ "$4" == ">=" ] && [ "$result" -ge $5 ]; then
3352                                 ((RES_PASS++))
3353                                 echo -e " Result=${result} after ${duration} seconds${SAMELINE}"
3354                                 echo -e $GREEN" PASS${EGREEN} - Result=${result} after ${duration} seconds"
3355                                 __print_current_stats
3356                                 return
3357                         elif [ "$4" == "contain_str" ] && [[ $result =~ $5 ]]; then
3358                                 ((RES_PASS++))
3359                                 echo -e " Result=${result} after ${duration} seconds${SAMELINE}"
3360                                 echo -e $GREEN" PASS${EGREEN} - Result=${result} after ${duration} seconds"
3361                                 __print_current_stats
3362                                 return
3363                         else
3364                                 if [ $duration -gt $6 ]; then
3365                                         ((RES_FAIL++))
3366                                         echo -e $RED" FAIL${ERED} - ${3} ${4} ${5} not reached in ${6} seconds, result = ${result}"
3367                                         __print_current_stats
3368                                         __check_stop_at_error
3369                                         return
3370                                 fi
3371                         fi
3372                         sleep 1
3373                 done
3374         elif [ $# -eq 5 ]; then
3375                 if [[ $3 == "json:"* ]]; then
3376                         checkjsonarraycount=1
3377                 fi
3378
3379                 echo -e $BOLD"TEST $TEST_SEQUENCE_NR - (${BASH_LINENO[1]}) - ${TIMESTAMP}: ${1}, ${3} ${4} ${5}"$EBOLD
3380                 echo "TEST $TEST_SEQUENCE_NR - (${BASH_LINENO[1]}) - ${TIMESTAMP}:  ${1}, ${3} ${4} ${5}" >> $HTTPLOG
3381                 ((RES_TEST++))
3382                 ((TEST_SEQUENCE_NR++))
3383                 if [ $checkjsonarraycount -eq 0 ]; then
3384                         result="$(__do_curl $2$3)"
3385                         retcode=$?
3386                         result=${result//[[:blank:]]/} #Strip blanks
3387                 else
3388                         path=${3:5}
3389                         result="$(__do_curl $2$path)"
3390                         retcode=$?
3391                         echo "$result" > ./tmp/.tmp.curl.json
3392                         result=$(python3 ../common/count_json_elements.py "./tmp/.tmp.curl.json")
3393                 fi
3394                 if [ $retcode -ne 0 ]; then
3395                         ((RES_FAIL++))
3396                         echo -e $RED" FAIL ${ERED}- ${3} ${4} ${5} not reached, result = ${result}"
3397                         __print_current_stats
3398                         __check_stop_at_error
3399                 elif [ "$4" == "=" ] && [ "$result" -eq $5 ]; then
3400                         ((RES_PASS++))
3401                         echo -e $GREEN" PASS${EGREEN} - Result=${result}"
3402                         __print_current_stats
3403                 elif [ "$4" == ">" ] && [ "$result" -gt $5 ]; then
3404                         ((RES_PASS++))
3405                         echo -e $GREEN" PASS${EGREEN} - Result=${result}"
3406                         __print_current_stats
3407                 elif [ "$4" == "<" ] && [ "$result" -lt $5 ]; then
3408                         ((RES_PASS++))
3409                         echo -e $GREEN" PASS${EGREEN} - Result=${result}"
3410                         __print_current_stats
3411                 elif [ "$4" == ">=" ] && [ "$result" -ge $5 ]; then
3412                         ((RES_PASS++))
3413                         echo -e $GREEN" PASS${EGREEN} - Result=${result}"
3414                         __print_current_stats
3415                 elif [ "$4" == "contain_str" ] && [[ $result =~ $5 ]]; then
3416                         ((RES_PASS++))
3417                         echo -e $GREEN" PASS${EGREEN} - Result=${result}"
3418                         __print_current_stats
3419                 else
3420                         ((RES_FAIL++))
3421                         echo -e $RED" FAIL${ERED} - ${3} ${4} ${5} not reached, result = ${result}"
3422                         __print_current_stats
3423                         __check_stop_at_error
3424                 fi
3425         else
3426                 echo "Wrong args to __var_test, needs five or six args: <simulator-name> <host> <variable-name> <condition-operator> <target-value> [ <timeout> ]"
3427                 echo "Got:" $@
3428                 exit 1
3429         fi
3430 }