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