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