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