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