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