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