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