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