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