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