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