39f6284eb4d9585193eb769bd7135e3df3da15ab
[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 __added_apps=""
760 echo -e $BOLD"Auto adding system apps"$EBOLD
761 if [ $RUNMODE == "KUBE" ]; then
762         INCLUDED_IMAGES=$INCLUDED_IMAGES" "$TESTENV_KUBE_SYSTEM_APPS
763         TMP_APPS=$TESTENV_KUBE_SYSTEM_APPS
764 else
765         INCLUDED_IMAGES=$INCLUDED_IMAGES" "$TESTENV_DOCKER_SYSTEM_APPS
766         TMP_APPS=$TESTENV_DOCKER_SYSTEM_APPS
767 fi
768 if [ ! -z "$TMP_APPS" ]; then
769         for iapp in "$TMP_APPS"; do
770                 file_pointer=$(echo $iapp | tr '[:upper:]' '[:lower:]')
771                 file_pointer="../common/"$file_pointer"_api_functions.sh"
772             padded_iapp=$iapp
773                 while [ ${#padded_iapp} -lt 16 ]; do
774                         padded_iapp=$padded_iapp" "
775                 done
776                 echo " Auto-adding system app   $padded_iapp  Sourcing $file_pointer"
777                 . $file_pointer
778                 __added_apps=" $iapp "$__added_apps
779         done
780 else
781         echo " None"
782 fi
783
784 if [ $RUNMODE == "KUBE" ]; then
785         TMP_APPS=$INCLUDED_IMAGES" "$KUBE_PRESTARTED_IMAGES
786 else
787         TMP_APPS=$INCLUDED_IMAGES
788 fi
789
790 echo -e $BOLD"Auto adding included apps"$EBOLD
791         for iapp in $TMP_APPS; do
792                 if [[ "$__added_apps" != *"$iapp"* ]]; then
793                         file_pointer=$(echo $iapp | tr '[:upper:]' '[:lower:]')
794                         file_pointer="../common/"$file_pointer"_api_functions.sh"
795                         padded_iapp=$iapp
796                         while [ ${#padded_iapp} -lt 16 ]; do
797                                 padded_iapp=$padded_iapp" "
798                         done
799                         echo " Auto-adding included app $padded_iapp  Sourcing $file_pointer"
800                         . $file_pointer
801                         if [ ! -f "$file_pointer" ]; then
802                                 echo " Include file $file_pointer for app $iapp does not exist"
803                                 exit 1
804                         fi
805                 fi
806         done
807 echo ""
808
809 echo -e $BOLD"Test environment info"$EBOLD
810
811 # Check needed installed sw
812
813 tmp=$(which bash)
814 if [ $? -ne 0 ] || [ -z "$tmp" ]; then
815         echo -e $RED"bash is required to run the test environment, pls install"$ERED
816         exit 1
817 fi
818 echo " bash is installed and using version:"
819 echo "$(bash --version)" | indent2
820
821 tmp=$(which python3)
822 if [ $? -ne 0 ] || [ -z "$tmp" ]; then
823         echo -e $RED"python3 is required to run the test environment, pls install"$ERED
824         exit 1
825 fi
826 echo " python3 is installed and using version: $(python3 --version)"
827
828 tmp=$(which docker)
829 if [ $? -ne 0 ] || [ -z "$tmp" ]; then
830         echo -e $RED"docker is required to run the test environment, pls install"$ERED
831         exit 1
832 fi
833 echo " docker is installed and using versions:"
834 echo  "  $(docker version --format 'Client version {{.Client.Version}} Server version {{.Server.Version}}')"
835
836 tmp=$(which docker-compose)
837 if [ $? -ne 0 ] || [ -z "$tmp" ]; then
838         if [ $RUNMODE == "DOCKER" ]; then
839                 echo -e $RED"docker-compose is required to run the test environment, pls install"$ERED
840                 exit 1
841         fi
842 fi
843 tmp=$(docker-compose version --short)
844 echo " docker-compose installed and using version $tmp"
845 if [[ "$tmp" == *'v2'* ]]; then
846         DOCKER_COMPOSE_VERION="V2"
847 fi
848
849 tmp=$(which kubectl)
850 if [ $? -ne 0 ] || [ -z tmp ]; then
851         if [ $RUNMODE == "KUBE" ]; then
852                 echo -e $RED"kubectl is required to run the test environment in kubernetes mode, pls install"$ERED
853                 exit 1
854         fi
855 else
856         if [ $RUNMODE == "KUBE" ]; then
857                 echo " kubectl is installed and using versions:"
858                 echo $(kubectl version --short=true) | indent2
859                 res=$(kubectl cluster-info 2>&1)
860                 if [ $? -ne 0 ]; then
861                         echo -e "$BOLD$RED############################################# $ERED$EBOLD"
862                         echo -e  $BOLD$RED"Command 'kubectl cluster-info' returned error $ERED$EBOLD"
863                         echo -e "$BOLD$RED############################################# $ERED$EBOLD"
864                         echo " "
865                         echo "kubectl response:"
866                         echo $res
867                         echo " "
868                         echo "This script may have been started with user with no permission to run kubectl"
869                         echo "Try running with 'sudo' or set 'KUBECONFIG'"
870                         echo "Do either 1, 2 or 3 "
871                         echo " "
872                         echo "1"
873                         echo "Run with sudo"
874                         echo -e $BOLD"sudo <test-script-and-parameters>"$EBOLD
875                         echo " "
876                         echo "2"
877                         echo "Export KUBECONFIG and pass env to sudo - (replace user)"
878                         echo -e $BOLD"export KUBECONFIG='/home/<user>/.kube/config'"$EBOLD
879                         echo -e $BOLD"sudo -E <test-script-and-parameters>"$EBOLD
880                         echo " "
881                         echo "3"
882                         echo "Set KUBECONFIG inline (replace user)"
883                         echo -e $BOLD"sudo  KUBECONFIG='/home/<user>/.kube/config' <test-script-and-parameters>"$EBOLD
884
885                         exit 1
886                 fi
887                 echo " Node(s) and container container runtime config"
888                 kubectl get nodes -o wide | indent2
889         fi
890 fi
891
892 echo ""
893
894 echo -e $BOLD"Checking configured image setting for this test case"$EBOLD
895
896 #Temp var to check for image variable name errors
897 IMAGE_ERR=0
898 #Create a file with image info for later printing as a table
899 image_list_file="./tmp/.image-list"
900 echo -e "Application\tApp short name\tImage\ttag\ttag-switch" > $image_list_file
901
902 # Check if image env var is set and if so export the env var with image to use (used by docker compose files)
903 # arg: <app-short-name> <target-variable-name> <image-variable-name> <image-tag-variable-name> <tag-suffix> <image name>
904 __check_and_create_image_var() {
905
906         if [ $# -ne 6 ]; then
907                 echo "Expected arg: <app-short-name> <target-variable-name> <image-variable-name> <image-tag-variable-name> <tag-suffix> <image name>"
908                 ((IMAGE_ERR++))
909                 return
910         fi
911
912         __check_included_image $1
913         if [ $? -ne 0 ]; then
914                 echo -e "$6\t$1\t<image-excluded>\t<no-tag>"  >> $image_list_file
915                 # Image is excluded since the corresponding app is not used in this test
916                 return
917         fi
918         tmp=${6}"\t"${1}"\t"
919         #Create var from the input var names
920         image="${!3}"
921         tmptag=$4"_"$5
922         tag="${!tmptag}"
923
924         optional_image_repo_target=""
925
926         if [ -z $image ]; then
927                 __check_ignore_image $1
928                 if [ $? -eq 0 ]; then
929                         app_ds=$6
930                         if [ -z "$6" ]; then
931                                 app_ds="<app ignored>"
932                         fi
933                         echo -e "$app_ds\t$1\t<image-ignored>\t<no-tag>"  >> $image_list_file
934                         # Image is ignored since the corresponding the images is not set in the env file
935                         __remove_included_image $1   # Remove the image from the list of included images
936                         return
937                 fi
938                 echo -e $RED"\$"$3" not set in $TEST_ENV_VAR_FILE"$ERED
939                 ((IMAGE_ERR++))
940                 echo ""
941                 tmp=$tmp"<no-image>\t"
942         else
943
944                 optional_image_repo_target=$image
945
946                 #Add repo depending on image type
947                 if [ "$5" == "REMOTE_RELEASE" ]; then
948                         image=$NEXUS_RELEASE_REPO$image
949                 fi
950                 if [ "$5" == "REMOTE" ]; then
951                         image=$NEXUS_STAGING_REPO$image
952                 fi
953                 if [ "$5" == "REMOTE_SNAPSHOT" ]; then
954                         image=$NEXUS_SNAPSHOT_REPO$image
955                 fi
956                 if [ "$5" == "REMOTE_PROXY" ]; then
957                         image=$NEXUS_PROXY_REPO$image
958                 fi
959                 if [ "$5" == "REMOTE_RELEASE_ONAP" ]; then
960                         image=$NEXUS_RELEASE_REPO_ONAP$image
961                 fi
962                 if [ "$5" == "REMOTE_RELEASE_ORAN" ]; then
963                         image=$NEXUS_RELEASE_REPO_ORAN$image
964                 fi
965                 #No nexus repo added for local images, tag: LOCAL
966                 tmp=$tmp$image"\t"
967         fi
968         if [ -z $tag ]; then
969                 echo -e $RED"\$"$tmptag" not set in $TEST_ENV_VAR_FILE"$ERED
970                 ((IMAGE_ERR++))
971                 echo ""
972                 tmp=$tmp"<no-tag>\t"
973         else
974                 tmp=$tmp$tag
975         fi
976         tmp=$tmp"\t"$5
977         echo -e "$tmp" >> $image_list_file
978         #Export the env var
979         export "${2}"=$image":"$tag  #Note, this var may be set to the value of the target value below in __check_and_pull_image
980
981         remote_or_local_push=false
982         if [ ! -z "$IMAGE_REPO_ADR" ] && [[ $5 != *"PROXY"* ]]; then
983                 if [ $5 == "LOCAL" ]; then
984                         remote_or_local_push=true
985                 fi
986                 if [[ $5 == *"REMOTE"* ]]; then
987                         if [ "$IMAGE_REPO_POLICY" == "remote" ]; then
988                                 remote_or_local_push=true
989                         fi
990                 fi
991         fi
992         if $remote_or_local_push; then    # Only re-tag and push images according to policy, if repo is given
993                 export "${2}_SOURCE"=$image":"$tag  #Var to keep the actual source image
994                 if [[ $optional_image_repo_target == *"/"* ]]; then # Replace all / with _ for images to push to external repo
995                         optional_image_repo_target_tmp=${optional_image_repo_target//\//_}
996                         optional_image_repo_target=$optional_image_repo_target_tmp
997                 fi
998                 export "${2}_TARGET"=$IMAGE_REPO_ADR"/"$optional_image_repo_target":"$tag  #Create image + tag for optional image repo - pushed later if needed
999         else
1000                 export "${2}_SOURCE"=""
1001                 export "${2}_TARGET"=""
1002         fi
1003 }
1004
1005 # Check if app uses image included in this test run
1006 # Returns 0 if image is included, 1 if not
1007 __check_included_image() {
1008         for im in $INCLUDED_IMAGES; do
1009                 if [ "$1" == "$im" ]; then
1010                         return 0
1011                 fi
1012         done
1013         return 1
1014 }
1015
1016 # Check if app uses a project image
1017 # Returns 0 if image is included, 1 if not
1018 __check_project_image() {
1019         for im in $PROJECT_IMAGES; do
1020                 if [ "$1" == "$im" ]; then
1021                         return 0
1022                 fi
1023         done
1024         return 1
1025 }
1026
1027 # Check if app uses image built by the test script
1028 # Returns 0 if image is included, 1 if not
1029 __check_image_local_build() {
1030         for im in $LOCAL_IMAGE_BUILD; do
1031                 if [ "$1" == "$im" ]; then
1032                         return 0
1033                 fi
1034         done
1035         return 1
1036 }
1037
1038 # Check if app image is conditionally ignored in this test run
1039 # Returns 0 if image is conditionally ignored, 1 if not
1040 __check_ignore_image() {
1041         for im in $CONDITIONALLY_IGNORED_IMAGES; do
1042                 if [ "$1" == "$im" ]; then
1043                         return 0
1044                 fi
1045         done
1046         return 1
1047 }
1048
1049 # Removed image from included list of included images
1050 # Used when an image is marked as conditionally ignored
1051 __remove_included_image() {
1052         tmp_img_rem_list=""
1053         for im in $INCLUDED_IMAGES; do
1054                 if [ "$1" != "$im" ]; then
1055                         tmp_img_rem_list=$tmp_img_rem_list" "$im
1056                 fi
1057         done
1058         INCLUDED_IMAGES=$tmp_img_rem_list
1059         return 0
1060 }
1061
1062 # Check if app is included in the prestarted set of apps
1063 # Returns 0 if image is included, 1 if not
1064 __check_prestarted_image() {
1065         for im in $KUBE_PRESTARTED_IMAGES; do
1066                 if [ "$1" == "$im" ]; then
1067                         return 0
1068                 fi
1069         done
1070         return 1
1071 }
1072
1073 # Check if an app shall use a local image, based on the cmd parameters
1074 __check_image_local_override() {
1075         for im in $USE_LOCAL_IMAGES; do
1076                 if [ "$1" == "$im" ]; then
1077                         return 1
1078                 fi
1079         done
1080         return 0
1081 }
1082
1083 # Check if app uses image override
1084 # Returns the image/tag suffix LOCAL for local image or REMOTE/REMOTE_RELEASE/REMOTE_SNAPSHOT for staging/release/snapshot image
1085 __check_image_override() {
1086
1087         for im in $ORAN_IMAGES_APP_NAMES; do
1088                 if [ "$1" == "$im" ]; then
1089                         echo "REMOTE_RELEASE_ORAN"
1090                         return 0
1091                 fi
1092         done
1093
1094         for im in $ONAP_IMAGES_APP_NAMES; do
1095                 if [ "$1" == "$im" ]; then
1096                         echo "REMOTE_RELEASE_ONAP"
1097                         return 0
1098                 fi
1099         done
1100
1101         found=0
1102         for im in $PROJECT_IMAGES_APP_NAMES; do
1103                 if [ "$1" == "$im" ]; then
1104                         found=1
1105                 fi
1106         done
1107
1108         if [ $found -eq 0 ]; then
1109                 echo "REMOTE_PROXY"
1110                 return 0
1111         fi
1112
1113         suffix=""
1114         if [ $IMAGE_CATEGORY == "RELEASE" ]; then
1115                 suffix="REMOTE_RELEASE"
1116         fi
1117         if [ $IMAGE_CATEGORY == "DEV" ]; then
1118                 suffix="REMOTE"
1119         fi
1120         CTR=0
1121         for im in $USE_STAGING_IMAGES; do
1122                 if [ "$1" == "$im" ]; then
1123                         suffix="REMOTE"
1124                         ((CTR++))
1125                 fi
1126         done
1127         for im in $USE_RELEASE_IMAGES; do
1128                 if [ "$1" == "$im" ]; then
1129                         suffix="REMOTE_RELEASE"
1130                         ((CTR++))
1131                 fi
1132         done
1133         for im in $USE_SNAPSHOT_IMAGES; do
1134                 if [ "$1" == "$im" ]; then
1135                         suffix="REMOTE_SNAPSHOT"
1136                         ((CTR++))
1137                 fi
1138         done
1139         for im in $USE_LOCAL_IMAGES; do
1140                 if [ "$1" == "$im" ]; then
1141                         suffix="LOCAL"
1142                         ((CTR++))
1143                 fi
1144         done
1145         echo $suffix
1146         if [ $CTR -gt 1 ]; then
1147                 exit 1
1148         fi
1149         return 0
1150 }
1151
1152 # Function to re-tag and image and push to another image repo
1153 __retag_and_push_image() {
1154         if [ ! -z "$IMAGE_REPO_ADR" ]; then
1155                 source_image="${!1}"
1156                 trg_var_name=$1_"TARGET" # This var is created in func __check_and_create_image_var
1157                 target_image="${!trg_var_name}"
1158
1159                 if [ -z $target_image ]; then
1160                         return 0  # Image with no target shall not be pushed
1161                 fi
1162
1163                 echo -ne "  Attempt to re-tag image to: ${BOLD}${target_image}${EBOLD}${SAMELINE}"
1164                 tmp=$(docker image tag $source_image ${target_image} )
1165                 if [ $? -ne 0 ]; then
1166                         docker stop $tmp &> ./tmp/.dockererr
1167                         ((IMAGE_ERR++))
1168                         echo ""
1169                         echo -e "  Attempt to re-tag image to: ${BOLD}${target_image}${EBOLD} - ${RED}Failed${ERED}"
1170                         cat ./tmp/.dockererr
1171                         return 1
1172                 else
1173                         echo -e "  Attempt to re-tag image to: ${BOLD}${target_image}${EBOLD} - ${GREEN}OK${EGREEN}"
1174                 fi
1175                 echo -ne "  Attempt to push re-tagged image: ${BOLD}${target_image}${EBOLD}${SAMELINE}"
1176                 tmp=$(docker push ${target_image} )
1177                 if [ $? -ne 0 ]; then
1178                         docker stop $tmp &> ./tmp/.dockererr
1179                         ((IMAGE_ERR++))
1180                         echo ""
1181                         echo -e "  Attempt to push re-tagged image: ${BOLD}${target_image}${EBOLD} - ${RED}Failed${ERED}"
1182                         cat ./tmp/.dockererr
1183                         return 1
1184                 else
1185                         echo -e "  Attempt to push re-tagged image: ${BOLD}${target_image}${EBOLD} - ${GREEN}OK${EGREEN}"
1186                 fi
1187                 export "${1}"=$target_image
1188         fi
1189         return 0
1190 }
1191
1192 #Function to check if image exist and stop+remove the container+pull new images as needed
1193 #args <script-start-arg> <descriptive-image-name> <container-base-name> <image-with-tag-var-name>
1194 __check_and_pull_image() {
1195
1196         source_image="${!4}"
1197
1198         echo -e " Checking $BOLD$2$EBOLD container(s) with basename: $BOLD$3$EBOLD using image: $BOLD$source_image$EBOLD"
1199         format_string="\"{{.Repository}}\\t{{.Tag}}\\t{{.CreatedSince}}\\t{{.Size}}\""
1200         tmp_im=$(docker images --format $format_string $source_image)
1201
1202         if [ $1 == "local" ]; then
1203                 if [ -z "$tmp_im" ]; then
1204                         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
1205                         ((IMAGE_ERR++))
1206                         return 1
1207                 else
1208                         echo -e "  "$2" (local image): \033[1m"$source_image"\033[0m "$GREEN"OK"$EGREEN
1209                 fi
1210         elif [ $1 == "remote" ] || [ $1 == "remote-remove" ]; then
1211                 if [ $1 == "remote-remove" ]; then
1212                         if [ $RUNMODE == "DOCKER" ]; then
1213                                 echo -ne "  Attempt to stop and remove container(s), if running - ${SAMELINE}"
1214                                 tmp=$(docker ps -aq --filter name=${3} --filter network=${DOCKER_SIM_NWNAME})
1215                                 if [ $? -eq 0 ] && [ ! -z "$tmp" ]; then
1216                                         docker stop $tmp &> ./tmp/.dockererr
1217                                         if [ $? -ne 0 ]; then
1218                                                 ((IMAGE_ERR++))
1219                                                 echo ""
1220                                                 echo -e $RED"  Container(s) could not be stopped - try manual stopping the container(s)"$ERED
1221                                                 cat ./tmp/.dockererr
1222                                                 return 1
1223                                         fi
1224                                 fi
1225                                 echo -ne "  Attempt to stop and remove container(s), if running - "$GREEN"stopped"$EGREEN"${SAMELINE}"
1226                                 tmp=$(docker ps -aq --filter name=${3} --filter network=${DOCKER_SIM_NWNAME}) &> /dev/null
1227                                 if [ $? -eq 0 ] && [ ! -z "$tmp" ]; then
1228                                         docker rm $tmp &> ./tmp/.dockererr
1229                                         if [ $? -ne 0 ]; then
1230                                                 ((IMAGE_ERR++))
1231                                                 echo ""
1232                                                 echo -e $RED"  Container(s) could not be removed - try manual removal of the container(s)"$ERED
1233                                                 cat ./tmp/.dockererr
1234                                                 return 1
1235                                         fi
1236                                 fi
1237                                 echo -e "  Attempt to stop and remove container(s), if running - "$GREEN"stopped removed"$EGREEN
1238                                 tmp_im=""
1239                         else
1240                                 tmp_im=""
1241                         fi
1242                 fi
1243                 if [ -z "$tmp_im" ]; then
1244                         echo -ne "  Pulling image${SAMELINE}"
1245                         out=$(docker pull $source_image)
1246                         if [ $? -ne 0 ]; then
1247                                 echo ""
1248                                 echo -e "  Pulling image -$RED could not be pulled"$ERED
1249                                 ((IMAGE_ERR++))
1250                                 echo $out > ./tmp/.dockererr
1251                                 echo $out
1252                                 return 1
1253                         fi
1254                         echo $out > ./tmp/.dockererr
1255                         if [[ $out == *"up to date"* ]]; then
1256                                 echo -e "  Pulling image -$GREEN Image is up to date $EGREEN"
1257                         elif [[ $out == *"Downloaded newer image"* ]]; then
1258                                 echo -e "  Pulling image -$GREEN Newer image pulled $EGREEN"
1259                         else
1260                                 echo -e "  Pulling image -$GREEN Pulled $EGREEN"
1261                         fi
1262                 else
1263                         echo -e "  Pulling image -$GREEN OK $EGREEN(exists in local repository)"
1264                 fi
1265         fi
1266
1267         __retag_and_push_image $4
1268
1269         return $?
1270 }
1271
1272 setup_testenvironment() {
1273         # Check that image env setting are available
1274         echo ""
1275
1276         # Image var setup for all project images included in the test
1277         for imagename in $APP_SHORT_NAMES; do
1278                 __check_included_image $imagename
1279                 incl=$?
1280                 __check_project_image $imagename
1281                 proj=$?
1282                 if [ $incl -eq 0 ]; then
1283                         if [ $proj -eq 0 ]; then
1284                                 IMAGE_SUFFIX=$(__check_image_override $imagename)
1285                                 if [ $? -ne 0 ]; then
1286                                         echo -e $RED"Image setting from cmd line not consistent for $imagename."$ERED
1287                                         ((IMAGE_ERR++))
1288                                 fi
1289                         else
1290                                 IMAGE_SUFFIX="none"
1291                         fi
1292                         # A function name is created from the app short name
1293                         # for example app short name 'ICS' -> produce the function
1294                         # name __ICS_imagesetup
1295                         # This function is called and is expected to exist in the imported
1296                         # file for the ics test functions
1297                         # The resulting function impl will call '__check_and_create_image_var' function
1298                         # with appropriate parameters
1299                         # If the image suffix is none, then the component decides the suffix
1300                         function_pointer="__"$imagename"_imagesetup"
1301                         $function_pointer $IMAGE_SUFFIX
1302                 fi
1303         done
1304
1305         #Errors in image setting - exit
1306         if [ $IMAGE_ERR -ne 0 ]; then
1307                 exit 1
1308         fi
1309
1310         #Print a tables of the image settings
1311         echo -e $BOLD"Images configured for start arg: "$START_ARG $EBOLD
1312         column -t -s $'\t' $image_list_file | indent1
1313
1314         echo ""
1315
1316         #Set the SIM_GROUP var
1317         echo -e $BOLD"Setting var to main dir of all container/simulator scripts"$EBOLD
1318         if [ -z "$SIM_GROUP" ]; then
1319                 SIM_GROUP=$AUTOTEST_HOME/../simulator-group
1320                 if [ ! -d  $SIM_GROUP ]; then
1321                         echo "Trying to set env var SIM_GROUP to dir 'simulator-group' in the nontrtric repo, but failed."
1322                         echo -e $RED"Please set the SIM_GROUP manually in the applicable $TEST_ENV_VAR_FILE"$ERED
1323                         exit 1
1324                 else
1325                         echo " SIM_GROUP auto set to: " $SIM_GROUP
1326                 fi
1327         elif [ $SIM_GROUP = *simulator_group ]; then
1328                 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
1329                 exit 1
1330         else
1331                 echo " SIM_GROUP env var already set to: " $SIM_GROUP
1332         fi
1333
1334         echo ""
1335
1336         #Temp var to check for image pull errors
1337         IMAGE_ERR=0
1338
1339         # The following sequence pull the configured images
1340
1341
1342         echo -e $BOLD"Pulling configured images, if needed"$EBOLD
1343         if [ ! -z "$IMAGE_REPO_ADR" ] && [ $IMAGE_REPO_POLICY == "local" ]; then
1344                 echo -e $YELLOW" Excluding all remote image check/pull when running with image repo: $IMAGE_REPO_ADR and image policy $IMAGE_REPO_POLICY"$EYELLOW
1345         else
1346                 for imagename in $APP_SHORT_NAMES; do
1347                         __check_included_image $imagename
1348                         incl=$?
1349                         __check_project_image $imagename
1350                         proj=$?
1351                         if [ $incl -eq 0 ]; then
1352                                 if [ $proj -eq 0 ]; then
1353                                         START_ARG_MOD=$START_ARG
1354                                         __check_image_local_override $imagename
1355                                         if [ $? -eq 1 ]; then
1356                                                 START_ARG_MOD="local"
1357                                         fi
1358                                 else
1359                                         START_ARG_MOD=$START_ARG
1360                                 fi
1361                                 __check_image_local_build $imagename
1362                                 #No pull of images built locally
1363                                 if [ $? -ne 0 ]; then
1364                                         # A function name is created from the app short name
1365                                         # for example app short name 'HTTPPROXY' -> produce the function
1366                                         # name __HTTPPROXY_imagesetup
1367                                         # This function is called and is expected to exist in the imported
1368                                         # file for the httpproxy test functions
1369                                         # The resulting function impl will call '__check_and_pull_image' function
1370                                         # with appropriate parameters
1371                                         function_pointer="__"$imagename"_imagepull"
1372                                         $function_pointer $START_ARG_MOD $START_ARG
1373                                 fi
1374                         else
1375                                 echo -e $YELLOW" Excluding $imagename image from image check/pull"$EYELLOW
1376                         fi
1377                 done
1378         fi
1379
1380         #Errors in image setting - exit
1381         if [ $IMAGE_ERR -ne 0 ]; then
1382                 echo ""
1383                 echo "#################################################################################################"
1384                 echo -e $RED"One or more images could not be pulled or containers using the images could not be stopped/removed"$ERED
1385                 echo -e $RED"Or local image, overriding remote image, does not exist"$ERED
1386                 if [ $IMAGE_CATEGORY == "DEV" ]; then
1387                     echo ""
1388                         echo -e $RED"Note that SNAPSHOT and staging images may be purged from nexus after a certain period."$ERED
1389                         echo -e $RED"In addition, the image may not have been updated in the current release so no SNAPSHOT or staging image exists"$ERED
1390                         echo -e $RED"In these cases, switch to use a released image instead, use the flag '--use-release-image <App-short-name>'"$ERED
1391                         echo -e $RED"Use the 'App-short-name' for the applicable image from the above table: 'Images configured for start arg'."$ERED
1392                 fi
1393                 echo "#################################################################################################"
1394                 echo ""
1395                 exit 1
1396         fi
1397
1398         echo ""
1399
1400         echo -e $BOLD"Building images needed for test"$EBOLD
1401
1402         for imagename in $APP_SHORT_NAMES; do
1403                 cd $AUTOTEST_HOME #Always reset to orig dir
1404                 __check_image_local_build $imagename
1405                 if [ $? -eq 0 ]; then
1406                         __check_included_image $imagename
1407                         if [ $? -eq 0 ]; then
1408                                 # A function name is created from the app short name
1409                                 # for example app short name 'MR' -> produce the function
1410                                 # name __MR_imagebuild
1411                                 # This function is called and is expected to exist in the imported
1412                                 # file for the mr test functions
1413                                 # The resulting function impl shall build the imagee
1414                                 function_pointer="__"$imagename"_imagebuild"
1415                                 $function_pointer
1416
1417                         else
1418                                 echo -e $YELLOW" Excluding image for app $imagename from image build"$EYELLOW
1419                         fi
1420                 fi
1421         done
1422
1423         cd $AUTOTEST_HOME # Just to make sure...
1424
1425         echo ""
1426
1427         # Create a table of the images used in the script - from local repo
1428         echo -e $BOLD"Local docker registry images used in this test script"$EBOLD
1429
1430         docker_tmp_file=./tmp/.docker-images-table
1431         format_string="{{.Repository}}\\t{{.Tag}}\\t{{.CreatedSince}}\\t{{.Size}}\\t{{.CreatedAt}}"
1432         echo -e "Application\tRepository\tTag\tCreated since\tSize\tCreated at" > $docker_tmp_file
1433
1434         for imagename in $APP_SHORT_NAMES; do
1435                 __check_included_image $imagename
1436                 if [ $? -eq 0 ]; then
1437                         # Only print image data if image repo is null, or if image repo is set and image is local
1438                         print_image_data=0
1439                         if [ -z "$IMAGE_REPO_ADR" ]; then
1440                                 print_image_data=1
1441                         else
1442                                 __check_image_local_build $imagename
1443                                 if [ $? -eq 0 ]; then
1444                                         print_image_data=1
1445                                 fi
1446                         fi
1447                         if [ $print_image_data -eq 1 ]; then
1448                                 # A function name is created from the app short name
1449                                 # for example app short name 'MR' -> produce the function
1450                                 # name __MR_imagebuild
1451                                 # This function is called and is expected to exist in the imported
1452                                 # file for the mr test functions
1453                                 # The resulting function impl shall build the imagee
1454                                 function_pointer="__"$imagename"_image_data"
1455                                 $function_pointer "$format_string" $docker_tmp_file
1456                         fi
1457                 fi
1458         done
1459
1460         column -t -s $'\t' $docker_tmp_file | indent1
1461
1462         echo ""
1463
1464         if [ ! -z "$IMAGE_REPO_ADR" ]; then
1465
1466                 # Create a table of the images used in the script - from remote repo
1467                 echo -e $BOLD"Remote repo images used in this test script"$EBOLD
1468                 echo -e $YELLOW"-- Note: These image will be pulled when the container starts. Images not managed by the test engine --"$EYELLOW
1469
1470                 docker_tmp_file=./tmp/.docker-images-table
1471                 format_string="{{.Repository}}\\t{{.Tag}}"
1472                 echo -e "Application\tRepository\tTag" > $docker_tmp_file
1473
1474                 for imagename in $APP_SHORT_NAMES; do
1475                         __check_included_image $imagename
1476                         if [ $? -eq 0 ]; then
1477                                 # Only print image data if image repo is null, or if image repo is set and image is local
1478                                 __check_image_local_build $imagename
1479                                 if [ $? -ne 0 ]; then
1480                                         # A function name is created from the app short name
1481                                         # for example app short name 'MR' -> produce the function
1482                                         # name __MR_imagebuild
1483                                         # This function is called and is expected to exist in the imported
1484                                         # file for the mr test functions
1485                                         # The resulting function impl shall build the imagee
1486                                         function_pointer="__"$imagename"_image_data"
1487                                         $function_pointer "$format_string" $docker_tmp_file
1488                                 fi
1489                         fi
1490                 done
1491
1492                 column -t -s $'\t' $docker_tmp_file | indent1
1493
1494                 echo ""
1495         fi
1496
1497         if [ $RUNMODE == "KUBE" ]; then
1498
1499                 echo "================================================================================="
1500                 echo "================================================================================="
1501
1502                 if [ -z "$IMAGE_REPO_ADR" ]; then
1503                         echo -e $YELLOW" The image pull policy is set to 'Never' - assuming a local image repo is available for all images"$EYELLOW
1504                         echo -e " This setting only works on single node clusters on the local machine"
1505                         echo -e " It does not work with multi-node clusters or remote clusters. "
1506                         export KUBE_IMAGE_PULL_POLICY="Never"
1507                 else
1508                         echo -e $YELLOW" The image pull policy is set to 'Always'"$EYELLOW
1509                         echo -e " This setting work on local clusters, multi-node clusters and remote cluster. "
1510                         echo -e " Only locally built images are managed. Remote images are always pulled from remote repos"
1511                         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"
1512                         export KUBE_IMAGE_PULL_POLICY="Always"
1513                 fi
1514                 CLUSTER_IP=$(kubectl config view -o jsonpath={.clusters[0].cluster.server} | awk -F[/:] '{print $4}')
1515                 echo -e $YELLOW" The cluster hostname/ip is: $CLUSTER_IP"$EYELLOW
1516
1517                 echo "================================================================================="
1518                 echo "================================================================================="
1519                 echo ""
1520         fi
1521
1522         echo -e $BOLD"======================================================="$EBOLD
1523         echo -e $BOLD"== Common test setup completed -  test script begins =="$EBOLD
1524         echo -e $BOLD"======================================================="$EBOLD
1525         echo ""
1526
1527         LOG_STAT_ARGS=""
1528
1529         for imagename in $APP_SHORT_NAMES; do
1530                 __check_included_image $imagename
1531                 retcode_i=$?
1532                 __check_prestarted_image $imagename
1533                 retcode_p=$?
1534                 if [ $retcode_i -eq 0 ] || [ $retcode_p -eq 0 ]; then
1535                         # A function name is created from the app short name
1536                         # for example app short name 'RICMSIM' -> produce the function
1537                         # name __RICSIM__initial_setup
1538                         # This function is called and is expected to exist in the imported
1539                         # file for the ricsim test functions
1540                         # The resulting function impl shall perform initial setup of port, host etc
1541
1542                         function_pointer="__"$imagename"_initial_setup"
1543                         $function_pointer
1544
1545                         function_pointer="__"$imagename"_statisics_setup"
1546                         LOG_STAT_ARGS=$LOG_STAT_ARGS" "$($function_pointer)
1547                 fi
1548         done
1549
1550         if [ $COLLECT_RUNTIME_STATS -eq 1 ]; then
1551                 ../common/genstat.sh $RUNMODE $SECONDS $TESTLOGS/$ATC/stat_data.csv $LOG_STAT_ARGS &
1552         fi
1553
1554 }
1555
1556 # Function to print the test result, shall be the last cmd in a test script
1557 # args: -
1558 # (Function for test scripts)
1559 print_result() {
1560
1561         TCTEST_END=$SECONDS
1562         duration=$((TCTEST_END-TCTEST_START))
1563
1564         echo "-------------------------------------------------------------------------------------------------"
1565         echo "-------------------------------------     Test case: "$ATC
1566         echo "-------------------------------------     Ended:     "$(date)
1567         echo "-------------------------------------------------------------------------------------------------"
1568         echo "-- Description: "$TC_ONELINE_DESCR
1569         echo "-- Execution time: " $duration " seconds"
1570         echo "-- Used env file: "$TEST_ENV_VAR_FILE
1571         echo "-------------------------------------------------------------------------------------------------"
1572         echo "-------------------------------------     RESULTS"
1573         echo ""
1574
1575
1576         if [ $RES_DEVIATION -gt 0 ]; then
1577                 echo "Test case deviations"
1578                 echo "===================================="
1579                 cat $DEVIATION_FILE
1580         fi
1581         echo ""
1582         echo "Timer measurement in the test script"
1583         echo "===================================="
1584         column -t -s $'\t' $TIMER_MEASUREMENTS
1585         if [ $RES_PASS != $RES_TEST ]; then
1586                 echo -e $RED"Measurement may not be reliable when there are failed test - failures may cause long measurement values due to timeouts etc."$ERED
1587         fi
1588         echo ""
1589
1590         if [ $COLLECT_RUNTIME_STATS -eq 1 ]; then
1591                 echo "Runtime statistics collected in file: "$TESTLOGS/$ATC/stat_data.csv
1592                 echo ""
1593         fi
1594
1595         total=$((RES_PASS+RES_FAIL))
1596         if [ $RES_TEST -eq 0 ]; then
1597                 echo -e "\033[1mNo tests seem to have been executed. Check the script....\033[0m"
1598                 echo -e "\033[31m\033[1m ___  ___ ___ ___ ___ _____   ___ _   ___ _   _   _ ___ ___ \033[0m"
1599                 echo -e "\033[31m\033[1m/ __|/ __| _ \_ _| _ \_   _| | __/_\ |_ _| | | | | | _ \ __|\033[0m"
1600                 echo -e "\033[31m\033[1m\__ \ (__|   /| ||  _/ | |   | _/ _ \ | || |_| |_| |   / _| \033[0m"
1601                 echo -e "\033[31m\033[1m|___/\___|_|_\___|_|   |_|   |_/_/ \_\___|____\___/|_|_\___|\033[0m"
1602         elif [ $total != $RES_TEST ]; then
1603                 echo -e "\033[1mTotal number of tests does not match the sum of passed and failed tests. Check the script....\033[0m"
1604                 echo -e "\033[31m\033[1m ___  ___ ___ ___ ___ _____   ___ _   ___ _   _   _ ___ ___ \033[0m"
1605                 echo -e "\033[31m\033[1m/ __|/ __| _ \_ _| _ \_   _| | __/_\ |_ _| | | | | | _ \ __|\033[0m"
1606                 echo -e "\033[31m\033[1m\__ \ (__|   /| ||  _/ | |   | _/ _ \ | || |_| |_| |   / _| \033[0m"
1607                 echo -e "\033[31m\033[1m|___/\___|_|_\___|_|   |_|   |_/_/ \_\___|____\___/|_|_\___|\033[0m"
1608         elif [ $RES_CONF_FAIL -ne 0 ]; then
1609                 echo -e "\033[1mOne or more configurations has failed. Check the script log....\033[0m"
1610                 echo -e "\033[31m\033[1m ___  ___ ___ ___ ___ _____   ___ _   ___ _   _   _ ___ ___ \033[0m"
1611                 echo -e "\033[31m\033[1m/ __|/ __| _ \_ _| _ \_   _| | __/_\ |_ _| | | | | | _ \ __|\033[0m"
1612                 echo -e "\033[31m\033[1m\__ \ (__|   /| ||  _/ | |   | _/ _ \ | || |_| |_| |   / _| \033[0m"
1613                 echo -e "\033[31m\033[1m|___/\___|_|_\___|_|   |_|   |_/_/ \_\___|____\___/|_|_\___|\033[0m"
1614         elif [ $RES_PASS = $RES_TEST ]; then
1615                 echo -e "All tests \033[32m\033[1mPASS\033[0m"
1616                 echo -e "\033[32m\033[1m  ___  _   ___ ___ \033[0m"
1617                 echo -e "\033[32m\033[1m | _ \/_\ / __/ __| \033[0m"
1618                 echo -e "\033[32m\033[1m |  _/ _ \\__ \__ \\ \033[0m"
1619                 echo -e "\033[32m\033[1m |_|/_/ \_\___/___/ \033[0m"
1620                 echo ""
1621
1622                 # Update test suite counter
1623                 if [ -f .tmp_tcsuite_pass_ctr ]; then
1624                         tmpval=$(< .tmp_tcsuite_pass_ctr)
1625                         ((tmpval++))
1626                         echo $tmpval > .tmp_tcsuite_pass_ctr
1627                 fi
1628                 if [ -f .tmp_tcsuite_pass ]; then
1629                         echo " - "$ATC " -- "$TC_ONELINE_DESCR"  Execution time: "$duration" seconds" >> .tmp_tcsuite_pass
1630                 fi
1631                 #Create file with OK exit code
1632                 echo "0" > "$AUTOTEST_HOME/.result$ATC.txt"
1633         else
1634                 echo -e "One or more tests with status  \033[31m\033[1mFAIL\033[0m "
1635                 echo -e "\033[31m\033[1m  ___ _   ___ _    \033[0m"
1636                 echo -e "\033[31m\033[1m | __/_\ |_ _| |   \033[0m"
1637                 echo -e "\033[31m\033[1m | _/ _ \ | || |__ \033[0m"
1638                 echo -e "\033[31m\033[1m |_/_/ \_\___|____|\033[0m"
1639                 echo ""
1640                 # Update test suite counter
1641                 if [ -f .tmp_tcsuite_fail_ctr ]; then
1642                         tmpval=$(< .tmp_tcsuite_fail_ctr)
1643                         ((tmpval++))
1644                         echo $tmpval > .tmp_tcsuite_fail_ctr
1645                 fi
1646                 if [ -f .tmp_tcsuite_fail ]; then
1647                         echo " - "$ATC " -- "$TC_ONELINE_DESCR"  Execution time: "$duration" seconds" >> .tmp_tcsuite_fail
1648                 fi
1649         fi
1650
1651         echo "++++ Number of tests:          "$RES_TEST
1652         echo "++++ Number of passed tests:   "$RES_PASS
1653         echo "++++ Number of failed tests:   "$RES_FAIL
1654         echo ""
1655         echo "++++ Number of failed configs: "$RES_CONF_FAIL
1656         echo ""
1657         echo "++++ Number of test case deviations: "$RES_DEVIATION
1658         echo ""
1659         echo "-------------------------------------     Test case complete    ---------------------------------"
1660         echo "-------------------------------------------------------------------------------------------------"
1661         echo ""
1662 }
1663
1664 #####################################################################
1665 ###### Functions for start, configuring, stoping, cleaning etc ######
1666 #####################################################################
1667
1668 # Start timer for time measurement
1669 # args:  <timer message to print>  -  timer value and message will be printed both on screen
1670 #                                     and in the timer measurement report - if at least one "print_timer is called"
1671 start_timer() {
1672         echo -e $BOLD"INFO(${BASH_LINENO[0]}): "${FUNCNAME[0]}"," $@ $EBOLD
1673         TC_TIMER_STARTTIME=$SECONDS
1674         TC_TIMER_TIMER_TEXT="${@:1}"
1675         if [ $# -ne 1 ]; then
1676                 __print_err "need 1 arg,  <timer message to print>" $@
1677                 TC_TIMER_TIMER_TEXT=${FUNCNAME[0]}":"${BASH_LINENO[0]}
1678                 echo " Assigning timer name: "$TC_TIMER_TIMER_TEXT
1679         fi
1680         TC_TIMER_CURRENT_FAILS=$(($RES_FAIL+$RES_CONF_FAIL))
1681         echo " Timer started: $(date)"
1682 }
1683
1684 # Print the running timer  the value of the time (in seconds)
1685 # Timer value and message will be printed both on screen and in the timer measurement report
1686 print_timer() {
1687         echo -e $BOLD"INFO(${BASH_LINENO[0]}): "${FUNCNAME[0]}"," $TC_TIMER_TIMER_TEXT $EBOLD
1688         if [ -z  "$TC_TIMER_STARTTIME" ]; then
1689                 __print_err "timer not started" $@
1690                 return 1
1691         fi
1692         duration=$(($SECONDS-$TC_TIMER_STARTTIME))
1693         if [ $duration -eq 0 ]; then
1694                 duration="<1 second"
1695         else
1696                 duration=$duration" seconds"
1697         fi
1698         echo " Timer duration :" $duration
1699         res="-"
1700         if [ $(($RES_FAIL+$RES_CONF_FAIL)) -ne $TC_TIMER_CURRENT_FAILS ]; then
1701                 res="Failures occured during test - timer not reliabled"
1702         fi
1703
1704         echo -e "$TC_TIMER_TIMER_TEXT \t $duration \t $res" >> $TIMER_MEASUREMENTS
1705 }
1706
1707 # Print info about a deviations from intended tests
1708 # Each deviation counted is also printed in the testreport
1709 # args <deviation message to print>
1710 deviation() {
1711         echo -e $BOLD"DEVIATION(${BASH_LINENO[0]}): "${FUNCNAME[0]} $EBOLD
1712         if [ $# -lt 1 ]; then
1713                 ((RES_CONF_FAIL++))
1714                 __print_err "need 1 or more args,  <deviation message to print>" $@
1715                 exit 1
1716         fi
1717         ((RES_DEVIATION++))
1718         echo -e $BOLD$YELLOW" Test case deviation: ${@:1}"$EYELLOW$EBOLD
1719         echo "Line: ${BASH_LINENO[0]} - ${@:1}" >> $DEVIATION_FILE
1720         __print_current_stats
1721         echo ""
1722 }
1723
1724 # Stop at first FAIL test case and take all logs - only for debugging/trouble shooting
1725 __check_stop_at_error() {
1726         if [ $STOP_AT_ERROR -eq 1 ]; then
1727                 echo -e $RED"Test script configured to stop at first FAIL, taking all logs and stops"$ERED
1728                 store_logs "STOP_AT_ERROR"
1729                 exit 1
1730         fi
1731         return 0
1732 }
1733
1734 # Stop and remove all containers
1735 # args: -
1736 # (Not for test scripts)
1737 __clean_containers() {
1738
1739         echo -e $BOLD"Docker clean and stopping and removing all running containers, by container name"$EBOLD
1740
1741         #Create empty file
1742         running_contr_file="./tmp/running_contr.txt"
1743         > $running_contr_file
1744
1745         # Get list of all containers started by the test script
1746         for imagename in $APP_SHORT_NAMES; do
1747                 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
1748         done
1749         running_contr_file_empty="No docker containers running, started by previous test execution"
1750         if [ -s $running_contr_file ]; then
1751                 running_contr_file_empty=""
1752         fi
1753
1754         # Kill all containers started by the test env - to speed up shut down
1755     docker kill $(docker ps -a  --filter "label=nrttest_app" --format '{{.Names}}') &> /dev/null
1756
1757         tab_heading1="App display name"
1758         tab_heading2="App short name"
1759         tab_heading3="Container name"
1760
1761         tab_heading1_len=${#tab_heading1}
1762         tab_heading2_len=${#tab_heading2}
1763         tab_heading3_len=${#tab_heading3}
1764         cntr=0
1765         #Calc field lengths of each item in the list of containers
1766         while read p; do
1767                 if (( $cntr % 3 == 0 ));then
1768                         if [ ${#p} -gt $tab_heading1_len ]; then
1769                                 tab_heading1_len=${#p}
1770                         fi
1771                 fi
1772                 if (( $cntr % 3 == 1));then
1773                         if [ ${#p} -gt $tab_heading2_len ]; then
1774                                 tab_heading2_len=${#p}
1775                         fi
1776                 fi
1777                 if (( $cntr % 3 == 2));then
1778                         if [ ${#p} -gt $tab_heading3_len ]; then
1779                                 tab_heading3_len=${#p}
1780                         fi
1781                 fi
1782                 let cntr=cntr+1
1783         done <$running_contr_file
1784
1785         let tab_heading1_len=tab_heading1_len+2
1786         while (( ${#tab_heading1} < $tab_heading1_len)); do
1787                 tab_heading1="$tab_heading1"" "
1788         done
1789
1790         let tab_heading2_len=tab_heading2_len+2
1791         while (( ${#tab_heading2} < $tab_heading2_len)); do
1792                 tab_heading2="$tab_heading2"" "
1793         done
1794
1795         let tab_heading3_len=tab_heading3_len+2
1796         while (( ${#tab_heading3} < $tab_heading3_len)); do
1797                 tab_heading3="$tab_heading3"" "
1798         done
1799
1800         if [ ! -z "$running_contr_file_empty" ]; then
1801                 echo $running_contr_file_empty | indent1
1802         else
1803                 echo " $tab_heading1$tab_heading2$tab_heading3"" Actions"
1804                 cntr=0
1805                 while read p; do
1806                         if (( $cntr % 3 == 0 ));then
1807                                 row=""
1808                                 heading=$p
1809                                 heading_len=$tab_heading1_len
1810                         fi
1811                         if (( $cntr % 3 == 1));then
1812                                 heading=$p
1813                                 heading_len=$tab_heading2_len
1814                         fi
1815                         if (( $cntr % 3 == 2));then
1816                                 contr=$p
1817                                 heading=$p
1818                                 heading_len=$tab_heading3_len
1819                         fi
1820                         while (( ${#heading} < $heading_len)); do
1821                                 heading="$heading"" "
1822                         done
1823                         row=$row$heading
1824                         if (( $cntr % 3 == 2));then
1825                                 echo -ne $row$SAMELINE
1826                                 echo -ne " $row ${GREEN}stopping...${EGREEN}${SAMELINE}"
1827                                 docker stop $(docker ps -qa --filter name=${contr} --filter network=$DOCKER_SIM_NWNAME) &> /dev/null
1828                                 echo -ne " $row ${GREEN}stopped removing...${EGREEN}${SAMELINE}"
1829                                 docker rm --force $(docker ps -qa --filter name=${contr} --filter network=$DOCKER_SIM_NWNAME) &> /dev/null
1830                                 echo -e  " $row ${GREEN}stopped removed     ${EGREEN}"
1831                         fi
1832                         let cntr=cntr+1
1833                 done <$running_contr_file
1834         fi
1835
1836         echo ""
1837
1838         echo -e $BOLD" Removing docker network"$EBOLD
1839         TMP=$(docker network ls -q --filter name=$DOCKER_SIM_NWNAME)
1840         if [ "$TMP" ==  $DOCKER_SIM_NWNAME ]; then
1841                 docker network rm $DOCKER_SIM_NWNAME | indent2
1842                 if [ $? -ne 0 ];  then
1843                         echo -e $RED" Cannot remove docker network. Manually remove or disconnect containers from $DOCKER_SIM_NWNAME"$ERED
1844                         exit 1
1845                 fi
1846         fi
1847         echo -e "$GREEN  Done$EGREEN"
1848
1849         echo -e $BOLD" Removing all unused docker neworks"$EBOLD
1850         docker network prune --force | indent2
1851         echo -e "$GREEN  Done$EGREEN"
1852
1853         echo -e $BOLD" Removing all unused docker volumes"$EBOLD
1854         docker volume prune --force | indent2
1855         echo -e "$GREEN  Done$EGREEN"
1856
1857         echo -e $BOLD" Removing all dangling/untagged docker images"$EBOLD
1858     docker rmi --force $(docker images -q -f dangling=true) &> /dev/null
1859         echo -e "$GREEN  Done$EGREEN"
1860         echo ""
1861
1862         CONTRS=$(docker ps | awk '$1 != "CONTAINER" { n++ }; END { print n+0 }')
1863         if [ $? -eq 0 ]; then
1864                 if [ $CONTRS -ne 0 ]; then
1865                         echo -e $RED"Containers running, may cause distubance to the test case"$ERED
1866                         docker ps -a | indent1
1867                         echo ""
1868                 fi
1869         fi
1870 }
1871
1872 ###################################
1873 ### Functions for kube management
1874 ###################################
1875
1876 # Get resource type for scaling
1877 # args: <resource-name> <namespace>
1878 __kube_get_resource_type() {
1879         kubectl get deployment $1 -n $2 1> /dev/null 2> ./tmp/kubeerr
1880         if [ $? -eq 0 ]; then
1881                 echo "deployment"
1882                 return 0
1883         fi
1884         kubectl get sts $1 -n $2 1> /dev/null 2> ./tmp/kubeerr
1885         if [ $? -eq 0 ]; then
1886                 echo "sts"
1887                 return 0
1888         fi
1889         echo "unknown-resource-type"
1890         return 1
1891 }
1892
1893 # Scale a kube resource to a specific count
1894 # args: <resource-type> <resource-name> <namespace> <target-count>
1895 # (Not for test scripts)
1896 __kube_scale() {
1897         echo -ne "  Setting $1 $2 replicas=$4 in namespace $3"$SAMELINE
1898         kubectl scale  $1 $2  -n $3 --replicas=$4 1> /dev/null 2> ./tmp/kubeerr
1899         if [ $? -ne 0 ]; then
1900                 echo -e "  Setting $1 $2 replicas=$4 in namespace $3 $RED Failed $ERED"
1901                 ((RES_CONF_FAIL++))
1902                 echo "  Message: $(<./tmp/kubeerr)"
1903                 return 1
1904         else
1905                 echo -e "  Setting $1 $2 replicas=$4 in namespace $3 $GREEN OK $EGREEN"
1906         fi
1907
1908         TSTART=$SECONDS
1909
1910         for i in {1..500}; do
1911                 count=$(kubectl get $1/$2  -n $3 -o jsonpath='{.status.replicas}' 2> /dev/null)
1912                 retcode=$?
1913                 if [ -z "$count" ]; then
1914                         #No value is sometimes returned for some reason, in case the resource has replica 0
1915                         count=0
1916                 fi
1917                 if [ $retcode -ne 0 ]; then
1918                         echo -e "$RED  Cannot fetch current replica count for $1 $2 in namespace $3 $ERED"
1919                         ((RES_CONF_FAIL++))
1920                         return 1
1921                 fi
1922                 #echo ""
1923                 if [ $count -ne $4 ]; then
1924                         echo -ne "  Waiting for $1 $2 replicas=$4 in namespace $3. Replicas=$count after $(($SECONDS-$TSTART)) seconds $SAMELINE"
1925                         sleep $i
1926                 else
1927                         echo -e "  Waiting for $1 $2 replicas=$4 in namespace $3. Replicas=$count after $(($SECONDS-$TSTART)) seconds"
1928                         echo -e "  Replicas=$4 after $(($SECONDS-$TSTART)) seconds $GREEN OK $EGREEN"
1929                         echo ""
1930                         return 0
1931                 fi
1932         done
1933         echo ""
1934         echo -e "$RED  Replica count did not reach target replicas=$4. Failed with replicas=$count $ERED"
1935         ((RES_CONF_FAIL++))
1936         return 0
1937 }
1938
1939 # Scale all kube resource sets to 0 in a namespace for resources having a certain lable and label-id
1940 # This function does not wait for the resource to reach 0
1941 # args: <namespace> <label-name> <label-id>
1942 # (Not for test scripts)
1943 __kube_scale_all_resources() {
1944         namespace=$1
1945         labelname=$2
1946         labelid=$3
1947         resources="deployment replicaset statefulset"
1948         for restype in $resources; do
1949                 result=$(kubectl get $restype -n $namespace -o jsonpath='{.items[?(@.metadata.labels.'$labelname'=="'$labelid'")].metadata.name}')
1950                 if [ $? -eq 0 ] && [ ! -z "$result" ]; then
1951                         for resid in $result; do
1952                                 echo -ne "  Ordered caling $restype $resid in namespace $namespace with label $labelname=$labelid to 0"$SAMELINE
1953                                 kubectl scale  $restype $resid  -n $namespace --replicas=0 1> /dev/null 2> ./tmp/kubeerr
1954                                 echo -e "  Ordered scaling $restype $resid in namespace $namespace with label $labelname=$labelid to 0 $GREEN OK $EGREEN"
1955                         done
1956                 fi
1957         done
1958 }
1959
1960 # Scale all kube resource sets to 0 in a namespace for resources having a certain lable and an optional label-id
1961 # This function do wait for the resource to reach 0
1962 # args: <namespace> <label-name> [ <label-id> ]
1963 # (Not for test scripts)
1964 __kube_scale_and_wait_all_resources() {
1965         namespace=$1
1966         labelname=$2
1967         labelid=$3
1968         if [ -z "$3" ]; then
1969                 echo "  Attempt to scale - deployment replicaset statefulset - in namespace $namespace with label $labelname"
1970         else
1971                 echo "  Attempt to scale - deployment replicaset statefulset - in namespace $namespace with label $labelname=$labelid"
1972         fi
1973         resources="deployment replicaset statefulset"
1974         scaled_all=1
1975         while [ $scaled_all -ne 0 ]; do
1976                 scaled_all=0
1977                 for restype in $resources; do
1978                     if [ -z "$3" ]; then
1979                                 result=$(kubectl get $restype -n $namespace -o jsonpath='{.items[?(@.metadata.labels.'$labelname')].metadata.name}')
1980                         else
1981                                 result=$(kubectl get $restype -n $namespace -o jsonpath='{.items[?(@.metadata.labels.'$labelname'=="'$labelid'")].metadata.name}')
1982                         fi
1983                         if [ $? -eq 0 ] && [ ! -z "$result" ]; then
1984                                 for resid in $result; do
1985                                         echo -e "   Ordered scaling $restype $resid in namespace $namespace with label $labelname=$labelid to 0"
1986                                         kubectl scale  $restype $resid  -n $namespace --replicas=0 1> /dev/null 2> ./tmp/kubeerr
1987                                         count=1
1988                                         T_START=$SECONDS
1989                                         while [ $count -ne 0 ]; do
1990                                                 count=$(kubectl get $restype $resid  -n $namespace -o jsonpath='{.status.replicas}' 2> /dev/null)
1991                                                 echo -ne "    Scaling $restype $resid in namespace $namespace with label $labelname=$labelid to 0, current count=$count"$SAMELINE
1992                                                 if [ $? -eq 0 ] && [ ! -z "$count" ]; then
1993                                                         sleep 0.5
1994                                                 else
1995                                                         count=0
1996                                                 fi
1997                                                 duration=$(($SECONDS-$T_START))
1998                                                 if [ $duration -gt 100 ]; then
1999                                                         #Forcring count 0, to avoid hanging for failed scaling
2000                                                         scaled_all=1
2001                                                         count=0
2002                                                 fi
2003                                         done
2004                                         echo -e "    Scaled $restype $resid in namespace $namespace with label $labelname=$labelid to 0, current count=$count $GREEN OK $EGREEN"
2005                                 done
2006                         fi
2007                 done
2008         done
2009 }
2010
2011 # Remove all kube resources in a namespace for resources having a certain label and label-id
2012 # This function wait until the resources are gone. Scaling to 0 must have been ordered previously
2013 # args: <namespace> <label-name> <label-id>
2014 # (Not for test scripts)
2015 __kube_delete_all_resources() {
2016         namespace=$1
2017         labelname=$2
2018         labelid=$3
2019         resources="deployments replicaset statefulset services pods configmaps persistentvolumeclaims persistentvolumes"
2020         deleted_resourcetypes=""
2021         for restype in $resources; do
2022                 ns_flag="-n $namespace"
2023                 ns_text="in namespace $namespace"
2024                 if [ $restype == "persistentvolumes" ]; then
2025                         ns_flag=""
2026                         ns_text=""
2027                 fi
2028                 result=$(kubectl get $restype $ns_flag -o jsonpath='{.items[?(@.metadata.labels.'$labelname'=="'$labelid'")].metadata.name}')
2029                 if [ $? -eq 0 ] && [ ! -z "$result" ]; then
2030                         deleted_resourcetypes=$deleted_resourcetypes" "$restype
2031                         for resid in $result; do
2032                                 if [ $restype == "replicaset" ] || [ $restype == "statefulset" ]; then
2033                                         count=1
2034                                         while [ $count -ne 0 ]; do
2035                                                 count=$(kubectl get $restype $resid  $ns_flag -o jsonpath='{.status.replicas}' 2> /dev/null)
2036                                                 echo -ne "  Scaling $restype $resid $ns_text with label $labelname=$labelid to 0, current count=$count"$SAMELINE
2037                                                 if [ $? -eq 0 ] && [ ! -z "$count" ]; then
2038                                                         sleep 0.5
2039                                                 else
2040                                                         count=0
2041                                                 fi
2042                                         done
2043                                         echo -e "  Scaled $restype $resid $ns_text with label $labelname=$labelid to 0, current count=$count $GREEN OK $EGREEN"
2044                                 fi
2045                                 echo -ne "  Deleting $restype $resid $ns_text with label $labelname=$labelid "$SAMELINE
2046                                 kubectl delete --grace-period=1 $restype $resid $ns_flag 1> /dev/null 2> ./tmp/kubeerr
2047                                 if [ $? -eq 0 ]; then
2048                                         echo -e "  Deleted $restype $resid $ns_text with label $labelname=$labelid $GREEN OK $EGREEN"
2049                                 else
2050                                         echo -e "  Deleted $restype $resid $ns_text with label $labelname=$labelid $GREEN Does not exist - OK $EGREEN"
2051                                 fi
2052                                 #fi
2053                         done
2054                 fi
2055         done
2056         if [ ! -z "$deleted_resourcetypes" ]; then
2057                 for restype in $deleted_resources; do
2058                         ns_flag="-n $namespace"
2059                         ns_text="in namespace $namespace"
2060                         if [ $restype == "persistentvolumes" ]; then
2061                                 ns_flag=""
2062                                 ns_text=""
2063                         fi
2064                         echo -ne "  Waiting for $restype $ns_text with label $labelname=$labelid to be deleted..."$SAMELINE
2065                         T_START=$SECONDS
2066                         result="dummy"
2067                         while [ ! -z "$result" ]; do
2068                                 sleep 0.5
2069                                 result=$(kubectl get $restype $ns_flag -o jsonpath='{.items[?(@.metadata.labels.'$labelname'=="'$labelid'")].metadata.name}')
2070                                 echo -ne "  Waiting for $restype $ns_text with label $labelname=$labelid to be deleted...$(($SECONDS-$T_START)) seconds "$SAMELINE
2071                                 if [ -z "$result" ]; then
2072                                         echo -e " Waiting for $restype $ns_text with label $labelname=$labelid to be deleted...$(($SECONDS-$T_START)) seconds $GREEN OK $EGREEN"
2073                                 elif [ $(($SECONDS-$T_START)) -gt 300 ]; then
2074                                         echo -e " Waiting for $restype $ns_text with label $labelname=$labelid to be deleted...$(($SECONDS-$T_START)) seconds $RED Failed $ERED"
2075                                         result=""
2076                                 fi
2077                         done
2078                 done
2079         fi
2080 }
2081
2082 # Creates a namespace if it does not exists
2083 # args: <namespace>
2084 # (Not for test scripts)
2085 __kube_create_namespace() {
2086
2087         #Check if test namespace exists, if not create it
2088         kubectl get namespace $1 1> /dev/null 2> ./tmp/kubeerr
2089         if [ $? -ne 0 ]; then
2090                 echo -ne " Creating namespace "$1 $SAMELINE
2091                 kubectl create namespace $1 1> /dev/null 2> ./tmp/kubeerr
2092                 if [ $? -ne 0 ]; then
2093                         echo -e " Creating namespace $1 $RED$BOLD FAILED $EBOLD$ERED"
2094                         ((RES_CONF_FAIL++))
2095                         echo "  Message: $(<./tmp/kubeerr)"
2096                         return 1
2097                 else
2098                         echo -e " Creating namespace $1 $GREEN$BOLD OK $EBOLD$EGREEN"
2099                 fi
2100         else
2101                 echo -e " Creating namespace $1 $GREEN$BOLD Already exists, OK $EBOLD$EGREEN"
2102         fi
2103         return 0
2104 }
2105
2106 # Find the host ip of an app (using the service resource)
2107 # args: <app-name> <namespace>
2108 # (Not for test scripts)
2109 __kube_get_service_host() {
2110         if [ $# -ne 2 ]; then
2111                 ((RES_CONF_FAIL++))
2112         __print_err "need 2 args, <app-name> <namespace>" $@
2113                 exit 1
2114         fi
2115         for timeout in {1..60}; do
2116                 host=$(kubectl get svc $1  -n $2 -o jsonpath='{.spec.clusterIP}')
2117                 if [ $? -eq 0 ]; then
2118                         if [ ! -z "$host" ]; then
2119                                 echo $host
2120                                 return 0
2121                         fi
2122                 fi
2123                 sleep 0.5
2124         done
2125         ((RES_CONF_FAIL++))
2126         echo "host-not-found-fatal-error"
2127         return 1
2128 }
2129
2130 # Find the named port to an app (using the service resource)
2131 # args: <app-name> <namespace> <port-name>
2132 # (Not for test scripts)
2133 __kube_get_service_port() {
2134         if [ $# -ne 3 ]; then
2135                 ((RES_CONF_FAIL++))
2136         __print_err "need 3 args, <app-name> <namespace> <port-name>" $@
2137                 exit 1
2138         fi
2139
2140         for timeout in {1..60}; do
2141                 port=$(kubectl get svc $1  -n $2 -o jsonpath='{...ports[?(@.name=="'$3'")].port}')
2142                 if [ $? -eq 0 ]; then
2143                         if [ ! -z "$port" ]; then
2144                                 echo $port
2145                                 return 0
2146                         fi
2147                 fi
2148                 sleep 0.5
2149         done
2150         ((RES_CONF_FAIL++))
2151         echo "0"
2152         return 1
2153 }
2154
2155 # Find the named node port to an app (using the service resource)
2156 # args: <app-name> <namespace> <port-name>
2157 # (Not for test scripts)
2158 __kube_get_service_nodeport() {
2159         if [ $# -ne 3 ]; then
2160                 ((RES_CONF_FAIL++))
2161         __print_err "need 3 args, <app-name> <namespace> <port-name>" $@
2162                 exit 1
2163         fi
2164
2165         for timeout in {1..60}; do
2166                 port=$(kubectl get svc $1  -n $2 -o jsonpath='{...ports[?(@.name=="'$3'")].nodePort}')
2167                 if [ $? -eq 0 ]; then
2168                         if [ ! -z "$port" ]; then
2169                                 echo $port
2170                                 return 0
2171                         fi
2172                 fi
2173                 sleep 0.5
2174         done
2175         ((RES_CONF_FAIL++))
2176         echo "0"
2177         return 1
2178 }
2179
2180 # Create a kube resource from a yaml template
2181 # args: <resource-type> <resource-name> <template-yaml> <output-yaml>
2182 # (Not for test scripts)
2183 __kube_create_instance() {
2184         echo -ne " Creating $1 $2"$SAMELINE
2185         envsubst < $3 > $4
2186         kubectl apply -f $4 1> /dev/null 2> ./tmp/kubeerr
2187         if [ $? -ne 0 ]; then
2188                 ((RES_CONF_FAIL++))
2189                 echo -e " Creating $1 $2 $RED Failed $ERED"
2190                 echo "  Message: $(<./tmp/kubeerr)"
2191                 return 1
2192         else
2193                 echo -e " Creating $1 $2 $GREEN OK $EGREEN"
2194         fi
2195 }
2196
2197 # Function to create a configmap in kubernetes
2198 # args: <configmap-name> <namespace> <labelname> <labelid> <path-to-data-file> <path-to-output-yaml>
2199 # (Not for test scripts)
2200 __kube_create_configmap() {
2201         echo -ne " Creating configmap $1 "$SAMELINE
2202         envsubst < $5 > $5"_tmp"
2203         cp $5"_tmp" $5  #Need to copy back to orig file name since create configmap neeed the original file name
2204         kubectl create configmap $1  -n $2 --from-file=$5 --dry-run=client -o yaml > $6
2205         if [ $? -ne 0 ]; then
2206                 echo -e " Creating configmap $1 $RED Failed $ERED"
2207                 ((RES_CONF_FAIL++))
2208                 return 1
2209         fi
2210
2211         kubectl apply -f $6 1> /dev/null 2> ./tmp/kubeerr
2212         if [ $? -ne 0 ]; then
2213                 echo -e " Creating configmap $1 $RED Apply failed $ERED"
2214                 echo "  Message: $(<./tmp/kubeerr)"
2215                 ((RES_CONF_FAIL++))
2216                 return 1
2217         fi
2218         kubectl label configmap $1 -n $2 $3"="$4 --overwrite 1> /dev/null 2> ./tmp/kubeerr
2219         if [ $? -ne 0 ]; then
2220                 echo -e " Creating configmap $1 $RED Labeling failed $ERED"
2221                 echo "  Message: $(<./tmp/kubeerr)"
2222                 ((RES_CONF_FAIL++))
2223                 return 1
2224         fi
2225         # Log the resulting map
2226         kubectl get configmap $1 -n $2 -o yaml > $6
2227
2228         echo -e " Creating configmap $1 $GREEN OK $EGREEN"
2229         return 0
2230 }
2231
2232 # This function runs a kubectl cmd where a single output value is expected, for example get ip with jsonpath filter.
2233 # The function retries up to the timeout given in the cmd flag '--cluster-timeout'
2234 # args: <full kubectl cmd with parameters>
2235 # (Not for test scripts)
2236 __kube_cmd_with_timeout() {
2237         TS_TMP=$(($SECONDS+$CLUSTER_TIME_OUT))
2238
2239         while true; do
2240                 kube_cmd_result=$($@)
2241                 if [ $? -ne 0 ]; then
2242                         kube_cmd_result=""
2243                 fi
2244                 if [ $SECONDS -ge $TS_TMP ] || [ ! -z "$kube_cmd_result" ] ; then
2245                         echo $kube_cmd_result
2246                         return 0
2247                 fi
2248                 sleep 1
2249         done
2250 }
2251
2252 # This function starts a pod that cleans a the contents of a path mounted as a pvc
2253 # After this action the pod should terminate
2254 # This should only be executed when the pod owning the pvc is not running
2255 # args: <appname> <namespace> <pvc-name> <path-to remove>
2256 # (Not for test scripts)
2257 __kube_clean_pvc() {
2258
2259         #using env vars setup in pvccleaner_api_functions.sh
2260
2261         export PVC_CLEANER_NAMESPACE=$2
2262         export PVC_CLEANER_CLAIMNAME=$3
2263         export PVC_CLEANER_RM_PATH=$4
2264         export PVC_CLEANER_APP_NAME
2265         input_yaml=$SIM_GROUP"/"$PVC_CLEANER_COMPOSE_DIR"/"pvc-cleaner.yaml
2266         output_yaml=$PWD/tmp/$2-pvc-cleaner.yaml
2267
2268         envsubst < $input_yaml > $output_yaml
2269
2270         kubectl delete -f $output_yaml 1> /dev/null 2> /dev/null   # Delete the previous terminated pod - if existing
2271
2272         __kube_create_instance pod $PVC_CLEANER_APP_NAME $input_yaml $output_yaml
2273         if [ $? -ne 0 ]; then
2274                 echo $YELLOW" Could not clean pvc for app: $1 - persistent storage not clean - tests may not work"
2275                 return 1
2276         fi
2277
2278         term_ts=$(($SECONDS+30))
2279         while [ $term_ts -gt $SECONDS ]; do
2280                 pod_status=$(kubectl get pod pvc-cleaner -n $PVC_CLEANER_NAMESPACE --no-headers -o custom-columns=":status.phase")
2281                 if [ "$pod_status" == "Succeeded" ]; then
2282                         return 0
2283                 fi
2284         done
2285         return 1
2286 }
2287
2288 # This function scales or deletes all resources for app selected by the testcase.
2289 # args: -
2290 # (Not for test scripts)
2291 __clean_kube() {
2292         echo -e $BOLD"Initialize kube pods/statefulsets/replicaset to initial state"$EBOLD
2293
2294         # Scale prestarted or managed apps
2295         for imagename in $APP_SHORT_NAMES; do
2296                 # A function name is created from the app short name
2297                 # for example app short name 'RICMSIM' -> produce the function
2298                 # name __RICSIM_kube_scale_zero or __RICSIM_kube_scale_zero_and_wait
2299                 # This function is called and is expected to exist in the imported
2300                 # file for the ricsim test functions
2301                 # The resulting function impl shall scale the resources to 0
2302                 # For prestarted apps, the function waits until the resources are 0
2303                 # For included (not prestated) apps, the scaling is just ordered
2304                 __check_prestarted_image $imagename
2305                 if [ $? -eq 0 ]; then
2306                         function_pointer="__"$imagename"_kube_scale_zero_and_wait"
2307                         echo -e " Scaling all kube resources for app $BOLD $imagename $EBOLD to 0"
2308                         $function_pointer
2309                 else
2310                         __check_included_image $imagename
2311                         if [ $? -eq 0 ]; then
2312                                 function_pointer="__"$imagename"_kube_scale_zero"
2313                                 echo -e " Scaling all kube resources for app $BOLD $imagename $EBOLD to 0"
2314                                 $function_pointer
2315                         fi
2316                 fi
2317         done
2318
2319         # Delete managed apps
2320         for imagename in $APP_SHORT_NAMES; do
2321                 __check_included_image $imagename
2322                 if [ $? -eq 0 ]; then
2323                         __check_prestarted_image $imagename
2324                         if [ $? -ne 0 ]; then
2325                                 # A function name is created from the app short name
2326                                 # for example app short name 'RICMSIM' -> produce the function
2327                                 # name __RICSIM__kube_delete_all
2328                                 # This function is called and is expected to exist in the imported
2329                                 # file for the ricsim test functions
2330                                 # The resulting function impl shall delete all its resources
2331                                 function_pointer="__"$imagename"_kube_delete_all"
2332                                 echo -e " Deleting all kube resources for app $BOLD $imagename $EBOLD"
2333                                 $function_pointer
2334                         fi
2335                 fi
2336         done
2337
2338         echo ""
2339 }
2340
2341 # Function stop and remove all containers (docker) and services/deployments etc(kube)
2342 # args: -
2343 # Function for test script
2344 clean_environment() {
2345         if [ $RUNMODE == "KUBE" ]; then
2346                 __clean_kube
2347                 if [ $PRE_CLEAN -eq 1 ]; then
2348                         echo " Cleaning docker resouces to free up resources, may take time..."
2349                         ../common/clean_docker.sh 2&>1 /dev/null
2350                         echo ""
2351                 fi
2352         else
2353                 __clean_containers
2354                 if [ $PRE_CLEAN -eq 1 ]; then
2355                         echo " Cleaning kubernetes resouces to free up resources, may take time..."
2356                         ../common/clean_kube.sh 2&>1 /dev/null
2357                         echo ""
2358                 fi
2359         fi
2360 }
2361
2362 # 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
2363 # args: -
2364 # (Function for test scripts)
2365 auto_clean_environment() {
2366         echo
2367         if [ "$AUTO_CLEAN" == "auto" ]; then
2368                 echo -e $BOLD"Initiating automatic cleaning of environment"$EBOLD
2369                 clean_environment
2370         fi
2371 }
2372
2373 # Function to sleep a test case for a numner of seconds. Prints the optional text args as info
2374 # args: <sleep-time-in-sec> [any-text-in-quotes-to-be-printed]
2375 # (Function for test scripts)
2376 sleep_wait() {
2377
2378         echo -e $BOLD"INFO(${BASH_LINENO[0]}): "${FUNCNAME[0]}"," $@ $EBOLD
2379         if [ $# -lt 1 ]; then
2380                 ((RES_CONF_FAIL++))
2381                 __print_err "need at least one arg, <sleep-time-in-sec> [any-text-to-printed]" $@
2382                 exit 1
2383         fi
2384         #echo "---- Sleep for " $1 " seconds ---- "$2
2385         start=$SECONDS
2386         duration=$((SECONDS-start))
2387         while [ $duration -lt $1 ]; do
2388                 echo -ne "  Slept for ${duration} seconds${SAMELINE}"
2389                 sleep 1
2390                 duration=$((SECONDS-start))
2391         done
2392         echo -ne "  Slept for ${duration} seconds${SAMELINE}"
2393         echo ""
2394 }
2395
2396 # Print error info for the call in the parent script (test case). Arg: <error-message-to-print>
2397 # Not to be called from the test script itself.
2398 __print_err() {
2399     echo -e $RED ${FUNCNAME[1]} " "$1" " ${BASH_SOURCE[2]} " line" ${BASH_LINENO[1]} $ERED
2400         if [ $# -gt 1 ]; then
2401                 echo -e $RED" Got: "${FUNCNAME[1]} ${@:2} $ERED
2402         fi
2403         ((RES_CONF_FAIL++))
2404 }
2405
2406 # Function to create the docker network for the test
2407 # Not to be called from the test script itself.
2408 __create_docker_network() {
2409         tmp=$(docker network ls --format={{.Name}} --filter name=$DOCKER_SIM_NWNAME)
2410         if [ $? -ne 0 ]; then
2411                 echo -e $RED" Could not check if docker network $DOCKER_SIM_NWNAME exists"$ERED
2412                 return 1
2413         fi
2414         if [ "$tmp" != $DOCKER_SIM_NWNAME ]; then
2415                 echo -e " Creating docker network:$BOLD $DOCKER_SIM_NWNAME $EBOLD"
2416                 docker network create $DOCKER_SIM_NWNAME | indent2
2417                 if [ $? -ne 0 ]; then
2418                         echo -e $RED" Could not create docker network $DOCKER_SIM_NWNAME"$ERED
2419                         return 1
2420                 else
2421                         echo -e "$GREEN  Done$EGREEN"
2422                 fi
2423         else
2424                 echo -e " Docker network $DOCKER_SIM_NWNAME already exists$GREEN OK $EGREEN"
2425         fi
2426 }
2427
2428 # Function to start container with docker-compose and wait until all are in state running.
2429 # If the <docker-compose-file> is empty, the default 'docker-compose.yml' is assumed.
2430 #args: <docker-compose-dir> <docker-compose-file> <docker-compose-arg>|NODOCKERARGS <count> <app-name>+
2431 # (Not for test scripts)
2432 __start_container() {
2433
2434         if [ $# -lt 5 ]; then
2435                 ((RES_CONF_FAIL++))
2436         __print_err "need 5 or more args, <docker-compose-dir> <docker-compose-file> <docker-compose-arg>|NODOCKERARGS <count> <app-name>+" $@
2437                 exit 1
2438         fi
2439
2440         __create_docker_network
2441
2442         curdir=$PWD
2443         cd $SIM_GROUP
2444         compose_dir=$1
2445         cd $1
2446         shift
2447         compose_file=$1
2448         if [ -z "$compose_file" ]; then
2449                 compose_file="docker-compose.yml"
2450         fi
2451         shift
2452         compose_args=$1
2453         shift
2454         appcount=$1
2455         shift
2456
2457         envsubst < $compose_file > "gen_"$compose_file
2458         compose_file="gen_"$compose_file
2459
2460         if [ "$compose_args" == "NODOCKERARGS" ]; then
2461                 docker-compose -f $compose_file up -d &> .dockererr
2462                 if [ $? -ne 0 ]; then
2463                         echo -e $RED"Problem to launch container(s) with docker-compose"$ERED
2464                         cat .dockererr
2465                         echo -e $RED"Stopping script...."$ERED
2466                         exit 1
2467                 fi
2468         else
2469                 docker-compose -f $compose_file up -d $compose_args &> .dockererr
2470                 if [ $? -ne 0 ]; then
2471                         echo -e $RED"Problem to launch container(s) with docker-compose"$ERED
2472                         cat .dockererr
2473                         echo -e $RED"Stopping script...."$ERED
2474                         exit 1
2475                 fi
2476         fi
2477
2478         cd $curdir
2479
2480         appindex=0
2481         while [ $appindex -lt $appcount ]; do
2482                 appname=$1
2483                 shift
2484                 app_started=0
2485                 for i in {1..10}; do
2486                         if [ "$(docker inspect --format '{{ .State.Running }}' $appname)" == "true" ]; then
2487                                         echo -e " Container $BOLD${appname}$EBOLD$GREEN running$EGREEN on$BOLD image $(docker inspect --format '{{ .Config.Image }}' ${appname}) $EBOLD"
2488                                         app_started=1
2489                                         break
2490                                 else
2491                                         sleep $i
2492                         fi
2493                 done
2494                 if [ $app_started -eq 0 ]; then
2495                         ((RES_CONF_FAIL++))
2496                         echo ""
2497                         echo -e $RED" Container $BOLD${appname}$EBOLD could not be started"$ERED
2498                         echo -e $RED" Stopping script..."$ERED
2499                         exit 1
2500                 fi
2501                 let appindex=appindex+1
2502         done
2503         return 0
2504 }
2505
2506 # Function to check if container/service is responding to http/https
2507 # args: <container-name>|<service-name> url
2508 # (Not for test scripts)
2509 __check_service_start() {
2510
2511         if [ $# -ne 2 ]; then
2512                 ((RES_CONF_FAIL++))
2513                 __print_err "need 2 args, <container-name>|<service-name> url" $@
2514                 return 1
2515         fi
2516
2517         if [ $RUNMODE == "KUBE" ]; then
2518                 ENTITY="service/set/deployment"
2519         else
2520                 ENTITY="container"
2521         fi
2522         appname=$1
2523         url=$2
2524         echo -ne " Container $BOLD${appname}$EBOLD starting${SAMELINE}"
2525
2526
2527         pa_st=false
2528         echo -ne " Waiting for ${ENTITY} ${appname} service status...${SAMELINE}"
2529         TSTART=$SECONDS
2530         loop_ctr=0
2531         while (( $TSTART+600 > $SECONDS )); do
2532                 result="$(__do_curl -m 10 $url)"
2533                 if [ $? -eq 0 ]; then
2534                         if [ ${#result} -gt 15 ]; then
2535                                 #If response is too long, truncate
2536                                 result="...response text too long, omitted"
2537                         fi
2538                         echo -ne " Waiting for {ENTITY} $BOLD${appname}$EBOLD service status on ${3}, result: $result${SAMELINE}"
2539                         echo -ne " The ${ENTITY} $BOLD${appname}$EBOLD$GREEN is alive$EGREEN, responds to service status:$GREEN $result $EGREEN on ${url} after $(($SECONDS-$TSTART)) seconds"
2540                         pa_st=true
2541                         break
2542                 else
2543                         TS_TMP=$SECONDS
2544                         TS_OFFSET=$loop_ctr
2545                         if (( $TS_OFFSET > 5 )); then
2546                                 TS_OFFSET=5
2547                         fi
2548                         while [ $(($TS_TMP+$TS_OFFSET)) -gt $SECONDS ]; do
2549                                 echo -ne " Waiting for ${ENTITY} ${appname} service status on ${url}...$(($SECONDS-$TSTART)) seconds, retrying in $(($TS_TMP+$TS_OFFSET-$SECONDS)) seconds   ${SAMELINE}"
2550                                 sleep 1
2551                         done
2552                 fi
2553                 let loop_ctr=loop_ctr+1
2554         done
2555
2556         if [ "$pa_st" = "false"  ]; then
2557                 ((RES_CONF_FAIL++))
2558                 echo -e $RED" The ${ENTITY} ${appname} did not respond to service status on ${url} in $(($SECONDS-$TSTART)) seconds"$ERED
2559                 return 1
2560         fi
2561
2562         echo ""
2563         return 0
2564 }
2565
2566
2567 #################
2568 ### Log functions
2569 #################
2570
2571 __check_container_logs() {
2572
2573         dispname=$1
2574         appname=$2
2575         logpath=$3
2576         warning=$4
2577         error=$5
2578
2579         echo -e $BOLD"Checking $dispname container $appname log ($logpath) for WARNINGs and ERRORs"$EBOLD
2580
2581         if [ $RUNMODE == "KUBE" ]; then
2582                 echo -e $YELLOW" Internal log for $dispname not checked in kube"$EYELLOW
2583                 return
2584         fi
2585
2586         #tmp=$(docker ps | grep $appname)
2587         tmp=$(docker ps -q --filter name=$appname) #get the container id
2588         if [ -z "$tmp" ]; then  #Only check logs for running Policy Agent apps
2589                 echo " "$dispname" is not running, no check made"
2590                 return
2591         fi
2592         foundentries="$(docker exec -t $tmp grep $warning $logpath | wc -l)"
2593         if [ $? -ne  0 ];then
2594                 echo "  Problem to search $appname log $logpath"
2595         else
2596                 if [ $foundentries -eq 0 ]; then
2597                         echo "  No WARN entries found in $appname log $logpath"
2598                 else
2599                         echo -e "  Found \033[1m"$foundentries"\033[0m WARN entries in $appname log $logpath"
2600                 fi
2601         fi
2602         foundentries="$(docker exec -t $tmp grep $error $logpath | wc -l)"
2603         if [ $? -ne  0 ];then
2604                 echo "  Problem to search $appname log $logpath"
2605         else
2606                 if [ $foundentries -eq 0 ]; then
2607                         echo "  No ERR entries found in $appname log $logpath"
2608                 else
2609                         echo -e $RED"  Found \033[1m"$foundentries"\033[0m"$RED" ERR entries in $appname log $logpath"$ERED
2610                 fi
2611         fi
2612         echo ""
2613 }
2614
2615 # Store all container logs and other logs in the log dir for the script
2616 # Logs are stored with a prefix in case logs should be stored several times during a test
2617 # args: <logfile-prefix>
2618 # (Function for test scripts)
2619 store_logs() {
2620         if [ $# != 1 ]; then
2621                 ((RES_CONF_FAIL++))
2622         __print_err "need one arg, <file-prefix>" $@
2623                 exit 1
2624         fi
2625         echo -e $BOLD"Storing all docker/kube container logs and other test logs in $TESTLOGS/$ATC using prefix: "$1$EBOLD
2626
2627         docker stats --no-stream > $TESTLOGS/$ATC/$1_docker_stats.log 2>&1
2628
2629         docker ps -a  > $TESTLOGS/$ATC/$1_docker_ps.log 2>&1
2630
2631         cp .httplog_${ATC}.txt $TESTLOGS/$ATC/$1_httplog_${ATC}.txt 2>&1
2632
2633         if [ $RUNMODE == "DOCKER" ]; then
2634
2635                 # Store docker logs for all container
2636                 for imagename in $APP_SHORT_NAMES; do
2637                         __check_included_image $imagename
2638                         if [ $? -eq 0 ]; then
2639                                 # A function name is created from the app short name
2640                                 # for example app short name 'RICMSIM' -> produce the function
2641                                 # name __RICSIM__store_docker_logs
2642                                 # This function is called and is expected to exist in the imported
2643                                 # file for the ricsim test functions
2644                                 # The resulting function impl shall store the docker logs for each container
2645                                 function_pointer="__"$imagename"_store_docker_logs"
2646                                 $function_pointer "$TESTLOGS/$ATC/" $1
2647                         fi
2648                 done
2649         fi
2650         if [ $RUNMODE == "KUBE" ]; then
2651                 namespaces=$(kubectl  get namespaces -o jsonpath='{.items[?(@.metadata.name)].metadata.name}')
2652                 for nsid in $namespaces; do
2653                         pods=$(kubectl get pods -n $nsid -o jsonpath='{.items[?(@.metadata.labels.autotest)].metadata.name}')
2654                         for podid in $pods; do
2655                                 kubectl logs -n $nsid $podid > $TESTLOGS/$ATC/$1_${podid}.log
2656                         done
2657                 done
2658         fi
2659         echo ""
2660 }
2661
2662 ###############
2663 ## Generic curl
2664 ###############
2665 # Generic curl function, assumes all 200-codes are ok
2666 # args: <valid-curl-args-including full url>
2667 # returns: <returned response (without respose code)>  or "<no-response-from-server>" or "<not found, <http-code>>""
2668 # returns: The return code is 0 for ok and 1 for not ok
2669 __do_curl() {
2670         echo ${FUNCNAME[1]} "line: "${BASH_LINENO[1]} >> $HTTPLOG
2671         proxyflag=""
2672         if [ ! -z "$KUBE_PROXY_PATH" ]; then
2673                 if [ $KUBE_PROXY_HTTPX == "http" ]; then
2674                         proxyflag=" --proxy $KUBE_PROXY_PATH"
2675                 else
2676                         proxyflag=" --proxy-insecure --proxy $KUBE_PROXY_PATH"
2677                 fi
2678         fi
2679         curlString="curl -skw %{http_code} $proxyflag $@"
2680         echo " CMD: $curlString" >> $HTTPLOG
2681         res=$($curlString)
2682         retcode=$?
2683         echo " RESP: $res" >> $HTTPLOG
2684         echo " RETCODE: $retcode" >> $HTTPLOG
2685         if [ $retcode -ne 0 ]; then
2686                 echo "<no-response-from-server>"
2687                 return 1
2688         fi
2689         http_code="${res:${#res}-3}"
2690         if [ ${#res} -eq 3 ]; then
2691                 if [ $http_code -lt 200 ] || [ $http_code -gt 299 ]; then
2692                         echo "<no-response-from-server>"
2693                         return 1
2694                 else
2695                         return 0
2696                 fi
2697         else
2698                 if [ $http_code -lt 200 ] || [ $http_code -gt 299 ]; then
2699                         echo "<not found, resp:${http_code}>"
2700                         return 1
2701                 fi
2702                 if [ $# -eq 2 ]; then
2703                         echo "${res:0:${#res}-3}" | xargs
2704                 else
2705                         echo "${res:0:${#res}-3}"
2706                 fi
2707
2708                 return 0
2709         fi
2710 }
2711
2712 #######################################
2713 ### Basic helper function for test cases
2714 #######################################
2715
2716 # Test a simulator container variable value towards target value using an condition operator with an optional timeout.
2717 # Arg: <simulator-name> <host> <variable-name> <condition-operator> <target-value>  - This test is done
2718 # immediately and sets pass or fail depending on the result of comparing variable and target using the operator.
2719 # Arg: <simulator-name> <host> <variable-name> <condition-operator> <target-value> <timeout>  - This test waits up to the timeout
2720 # before setting pass or fail depending on the result of comparing variable and target using the operator.
2721 # 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.
2722 # Not to be called from test script.
2723
2724 __var_test() {
2725         checkjsonarraycount=0
2726         TIMESTAMP=$(date "+%Y-%m-%d %H:%M:%S")
2727         if [ $# -eq 6 ]; then
2728                 if [[ $3 == "json:"* ]]; then
2729                         checkjsonarraycount=1
2730                 fi
2731
2732                 echo -e $BOLD"TEST $TEST_SEQUENCE_NR (${BASH_LINENO[1]}): ${1}, ${3} ${4} ${5} within ${6} seconds"$EBOLD
2733         echo "TEST $TEST_SEQUENCE_NR - ${TIMESTAMP}: (${BASH_LINENO[1]}): ${1}, ${3} ${4} ${5} within ${6} seconds" >> $HTTPLOG
2734
2735                 ((RES_TEST++))
2736                 ((TEST_SEQUENCE_NR++))
2737                 start=$SECONDS
2738                 ctr=0
2739                 for (( ; ; )); do
2740                         if [ $checkjsonarraycount -eq 0 ]; then
2741                                 result="$(__do_curl $2$3)"
2742                                 retcode=$?
2743                                 result=${result//[[:blank:]]/} #Strip blanks
2744                         else
2745                                 path=${3:5}
2746                                 result="$(__do_curl $2$path)"
2747                                 retcode=$?
2748                                 echo "$result" > ./tmp/.tmp.curl.json
2749                                 result=$(python3 ../common/count_json_elements.py "./tmp/.tmp.curl.json")
2750                         fi
2751                         duration=$((SECONDS-start))
2752                         echo -ne " Result=${result} after ${duration} seconds${SAMELINE}"
2753                         let ctr=ctr+1
2754                         if [ $retcode -ne 0 ]; then
2755                                 if [ $duration -gt $6 ]; then
2756                                         ((RES_FAIL++))
2757                                         echo -e $RED" FAIL${ERED} - ${3} ${4} ${5} not reached in ${6} seconds, result = ${result}"
2758                                         __print_current_stats
2759                                         __check_stop_at_error
2760                                         return
2761                                 fi
2762                         elif [ $4 = "=" ] && [ "$result" -eq $5 ]; then
2763                                 ((RES_PASS++))
2764                                 echo -e " Result=${result} after ${duration} seconds${SAMELINE}"
2765                                 echo -e $GREEN" PASS${EGREEN} - Result=${result} after ${duration} seconds"
2766                                 __print_current_stats
2767                                 return
2768                         elif [ $4 = ">" ] && [ "$result" -gt $5 ]; then
2769                                 ((RES_PASS++))
2770                                 echo -e " Result=${result} after ${duration} seconds${SAMELINE}"
2771                                 echo -e $GREEN" PASS${EGREEN} - Result=${result} after ${duration} seconds"
2772                                 __print_current_stats
2773                                 return
2774                         elif [ $4 = "<" ] && [ "$result" -lt $5 ]; then
2775                                 ((RES_PASS++))
2776                                 echo -e " Result=${result} after ${duration} seconds${SAMELINE}"
2777                                 echo -e $GREEN" PASS${EGREEN} - Result=${result} after ${duration} seconds"
2778                                 __print_current_stats
2779                                 return
2780                         elif [ $4 = "contain_str" ] && [[ $result =~ $5 ]]; then
2781                                 ((RES_PASS++))
2782                                 echo -e " Result=${result} after ${duration} seconds${SAMELINE}"
2783                                 echo -e $GREEN" PASS${EGREEN} - Result=${result} after ${duration} seconds"
2784                                 __print_current_stats
2785                                 return
2786                         else
2787                                 if [ $duration -gt $6 ]; then
2788                                         ((RES_FAIL++))
2789                                         echo -e $RED" FAIL${ERED} - ${3} ${4} ${5} not reached in ${6} seconds, result = ${result}"
2790                                         __print_current_stats
2791                                         __check_stop_at_error
2792                                         return
2793                                 fi
2794                         fi
2795                         sleep 1
2796                 done
2797         elif [ $# -eq 5 ]; then
2798                 if [[ $3 == "json:"* ]]; then
2799                         checkjsonarraycount=1
2800                 fi
2801
2802                 echo -e $BOLD"TEST $TEST_SEQUENCE_NR (${BASH_LINENO[1]}): ${1}, ${3} ${4} ${5}"$EBOLD
2803                 echo "TEST $TEST_SEQUENCE_NR - ${TIMESTAMP}: (${BASH_LINENO[1]}): ${1}, ${3} ${4} ${5}" >> $HTTPLOG
2804                 ((RES_TEST++))
2805                 ((TEST_SEQUENCE_NR++))
2806                 if [ $checkjsonarraycount -eq 0 ]; then
2807                         result="$(__do_curl $2$3)"
2808                         retcode=$?
2809                         result=${result//[[:blank:]]/} #Strip blanks
2810                 else
2811                         path=${3:5}
2812                         result="$(__do_curl $2$path)"
2813                         retcode=$?
2814                         echo "$result" > ./tmp/.tmp.curl.json
2815                         result=$(python3 ../common/count_json_elements.py "./tmp/.tmp.curl.json")
2816                 fi
2817                 if [ $retcode -ne 0 ]; then
2818                         ((RES_FAIL++))
2819                         echo -e $RED" FAIL ${ERED}- ${3} ${4} ${5} not reached, result = ${result}"
2820                         __print_current_stats
2821                         __check_stop_at_error
2822                 elif [ $4 = "=" ] && [ "$result" -eq $5 ]; then
2823                         ((RES_PASS++))
2824                         echo -e $GREEN" PASS${EGREEN} - Result=${result}"
2825                         __print_current_stats
2826                 elif [ $4 = ">" ] && [ "$result" -gt $5 ]; then
2827                         ((RES_PASS++))
2828                         echo -e $GREEN" PASS${EGREEN} - Result=${result}"
2829                         __print_current_stats
2830                 elif [ $4 = "<" ] && [ "$result" -lt $5 ]; then
2831                         ((RES_PASS++))
2832                         echo -e $GREEN" PASS${EGREEN} - Result=${result}"
2833                         __print_current_stats
2834                 elif [ $4 = "contain_str" ] && [[ $result =~ $5 ]]; then
2835                         ((RES_PASS++))
2836                         echo -e $GREEN" PASS${EGREEN} - Result=${result}"
2837                         __print_current_stats
2838                 else
2839                         ((RES_FAIL++))
2840                         echo -e $RED" FAIL${ERED} - ${3} ${4} ${5} not reached, result = ${result}"
2841                         __print_current_stats
2842                         __check_stop_at_error
2843                 fi
2844         else
2845                 echo "Wrong args to __var_test, needs five or six args: <simulator-name> <host> <variable-name> <condition-operator> <target-value> [ <timeout> ]"
2846                 echo "Got:" $@
2847                 exit 1
2848         fi
2849 }