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