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