ea940a18c38036804ca884a2a717ceef47ba1412
[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 functions needed for auto test
21 # Arg: local|remote|remote-remove [auto-clean] [--stop-at-error] [--ricsim-prefix <prefix> ] [ --env-file <environment-filename> ] [--use-local-image <app-nam> [<app-name>]*]
22
23
24 # Create a test case id, ATC (Auto Test Case), from the name of the test case script.
25 # FTC1.sh -> ATC == FTC1
26 ATC=$(basename "${BASH_SOURCE[$i+1]}" .sh)
27
28 #Create result file (containing '1' for error) for this test case
29 #Will be replaced with a file containing '0' if all test cases pass
30 echo "1" > "$PWD/.result$ATC.txt"
31
32 #Formatting for 'echo' cmd
33 BOLD="\033[1m"
34 EBOLD="\033[0m"
35 RED="\033[31m\033[1m"
36 ERED="\033[0m"
37 GREEN="\033[32m\033[1m"
38 EGREEN="\033[0m"
39 YELLOW="\033[33m\033[1m"
40 EYELLOW="\033[0m"
41 SAMELINE="\033[0K\r"
42
43 tmp=$(which python3)
44 if [ $? -ne 0 ] || [ -z tmp ]; then
45         echo -e $RED"python3 is required to run the test environment, pls install"$ERED
46         exit 1
47 fi
48 tmp=$(which docker)
49 if [ $? -ne 0 ] || [ -z tmp ]; then
50         echo -e $RED"docker is required to run the test environment, pls install"$ERED
51         exit 1
52 fi
53
54 tmp=$(which docker-compose)
55 if [ $? -ne 0 ] || [ -z tmp ]; then
56         echo -e $RED"docker-compose is required to run the test environment, pls install"$ERED
57         exit 1
58 fi
59
60 # Just resetting any previous echo formatting...
61 echo -ne $EBOLD
62
63 # default test environment variables
64 TEST_ENV_VAR_FILE=""
65
66 echo "Test case started as: ${BASH_SOURCE[$i+1]} "$@
67
68 #Localhost constant
69 LOCALHOST="http://localhost:"
70
71 # Make curl retries towards ECS for http response codes set in this env var, space separated list of codes
72 ECS_RETRY_CODES=""
73
74 # Make curl retries towards the agent for http response codes set in this env var, space separated list of codes
75 AGENT_RETRY_CODES=""
76
77 # Var to contol if the agent runs in a container (normal = 0) or as application on the local machine ( = 1)
78 AGENT_STAND_ALONE=0
79
80 # Var to hold 'auto' in case containers shall be stopped when test case ends
81 AUTO_CLEAN=""
82
83 # Var to hold the app names to use local image for when running 'remote' or 'remote-remove'
84 USE_LOCAL_IMAGES=""
85
86 # List of available apps to override with local image
87 AVAILABLE_LOCAL_IMAGES_OVERRIDE="PA ECS CP SDNC RICSIM"
88
89 # 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
90 STOP_AT_ERROR=0
91
92 # Function to indent cmd output with one space
93 indent1() { sed 's/^/ /'; }
94
95 # Function to indent cmd output with two spaces
96 indent2() { sed 's/^/  /'; }
97
98 # Set a description string for the test case
99 if [ -z "$TC_ONELINE_DESCR" ]; then
100         TC_ONELINE_DESCR="<no-description>"
101         echo "No test case description found, TC_ONELINE_DESCR should be set on in the test script , using "$TC_ONELINE_DESCR
102 fi
103
104 # Counter for test suites
105 if [ -f .tmp_tcsuite_ctr ]; then
106         tmpval=$(< .tmp_tcsuite_ctr)
107         ((tmpval++))
108         echo $tmpval > .tmp_tcsuite_ctr
109 fi
110
111 # Create the logs dir if not already created in the current dir
112 if [ ! -d "logs" ]; then
113     mkdir logs
114 fi
115 TESTLOGS=$PWD/logs
116
117 # Create the tmp dir for temporary files that is not needed after the test
118 # hidden files for the test env is still stored in the current dir
119 if [ ! -d "tmp" ]; then
120     mkdir tmp
121 fi
122
123 # Create a http message log for this testcase
124 HTTPLOG=$PWD"/.httplog_"$ATC".txt"
125 echo "" > $HTTPLOG
126
127
128 # Create a log dir for the test case
129 mkdir -p $TESTLOGS/$ATC
130
131 # Clear the log dir for the test case
132 rm $TESTLOGS/$ATC/*.log &> /dev/null
133 rm $TESTLOGS/$ATC/*.txt &> /dev/null
134 rm $TESTLOGS/$ATC/*.json &> /dev/null
135
136 # Log all output from the test case to a TC log
137 TCLOG=$TESTLOGS/$ATC/TC.log
138 exec &>  >(tee ${TCLOG})
139
140 #Variables for counting tests as well as passed and failed tests
141 RES_TEST=0
142 RES_PASS=0
143 RES_FAIL=0
144 RES_CONF_FAIL=0
145 RES_DEVIATION=0
146
147 #File to keep deviation messages
148 DEVIATION_FILE=".tmp_deviations"
149 rm $DEVIATION_FILE &> /dev/null
150
151 #Var for measuring execution time
152 TCTEST_START=$SECONDS
153
154 #File to save timer measurement results
155 TIMER_MEASUREMENTS=".timer_measurement.txt"
156 echo -e "Activity \t Duration" > $TIMER_MEASUREMENTS
157
158
159 echo "-------------------------------------------------------------------------------------------------"
160 echo "-----------------------------------      Test case: "$ATC
161 echo "-----------------------------------      Started:   "$(date)
162 echo "-------------------------------------------------------------------------------------------------"
163 echo "-- Description: "$TC_ONELINE_DESCR
164 echo "-------------------------------------------------------------------------------------------------"
165 echo "-----------------------------------      Test case setup      -----------------------------------"
166
167 START_ARG=$1
168 paramerror=0
169 if [ $# -lt 1 ]; then
170         paramerror=1
171 fi
172 if [ $paramerror -eq 0 ]; then
173         if [ "$1" != "remote" ] && [ "$1" != "remote-remove" ] && [ "$1" != "local" ]; then
174                 paramerror=1
175         else
176                 shift;
177         fi
178 fi
179 foundparm=0
180 while [ $paramerror -eq 0 ] && [ $foundparm -eq 0 ]; do
181         foundparm=1
182         if [ $paramerror -eq 0 ]; then
183                 if [ "$1" == "auto-clean" ]; then
184                         AUTO_CLEAN="auto"
185                         echo "Option set - Auto clean at end of test script"
186                         shift;
187                         foundparm=0
188                 fi
189         fi
190         if [ $paramerror -eq 0 ]; then
191                 if [ "$1" == "--stop-at-error" ]; then
192                         STOP_AT_ERROR=1
193                         echo "Option set - Stop at first error"
194                         shift;
195                         foundparm=0
196                 fi
197         fi
198         if [ $paramerror -eq 0 ]; then
199                 if [ "$1" == "--ricsim-prefix" ]; then
200                         shift;
201                         RIC_SIM_PREFIX=$1
202                         if [ -z "$1" ]; then
203                                 paramerror=1
204                         else
205                                 echo "Option set - Overriding RIC_SIM_PREFIX with: "$1
206                                 shift;
207                                 foundparm=0
208                         fi
209                 fi
210         fi
211         if [ $paramerror -eq 0 ]; then
212                 if [ "$1" == "--env-file" ]; then
213                         shift;
214                         TEST_ENV_VAR_FILE=$1
215                         if [ -z "$1" ]; then
216                                 paramerror=1
217                         else
218                                 echo "Option set - Reading test env from: "$1
219                                 shift;
220                                 foundparm=0
221                         fi
222                 fi
223         fi
224         if [ $paramerror -eq 0 ]; then
225                 if [ "$1" == "--use-local-image" ]; then
226                         USE_LOCAL_IMAGES=""
227                         shift
228                         while [ $# -gt 0 ] && [[ "$1" != "--"* ]]; do
229                                 USE_LOCAL_IMAGES=$USE_LOCAL_IMAGES" "$1
230                                 if [[ "$AVAILABLE_LOCAL_IMAGES_OVERRIDE" != *"$1"* ]]; then
231                                         paramerror=1
232                                 fi
233                                 shift;
234                         done
235                         foundparm=0
236                         if [ -z "$USE_LOCAL_IMAGES" ]; then
237                                 paramerror=1
238                         else
239                                 echo "Option set - Override remote images for app(s):"$USE_LOCAL_IMAGES
240                         fi
241                 fi
242         fi
243 done
244 echo ""
245
246 #Still params left?
247 if [ $paramerror -eq 0 ] && [ $# -gt 0 ]; then
248         paramerror=1
249 fi
250
251 if [ $paramerror -eq 1 ]; then
252         echo -e $RED"Expected arg: local|remote|remote-remove [auto-clean] [--stop-at-error] [--ricsim-prefix <prefix> ] [ --env-file <environment-filename> ] [--use-local-image <app-nam> [<app-name>]*]"$ERED
253         exit 1
254 fi
255
256 # sourcing the selected env variables for the test case
257 if [ -f "$TEST_ENV_VAR_FILE" ]; then
258         echo -e $BOLD"Sourcing env vars from: "$TEST_ENV_VAR_FILE$EBOLD
259         . $TEST_ENV_VAR_FILE
260 else
261         echo -e $RED"Selected env var file does not exist: "$TEST_ENV_VAR_FILE$ERED
262         echo " Select one of following env var file matching the intended target of the test"
263         echo " Restart the test using the flag '--env-file <path-to-env-file>"
264         ls ../common/test_env* | indent1
265         exit 1
266 fi
267
268 #Vars for A1 interface version and container count
269 G1_A1_VERSION=""
270 G2_A1_VERSION=""
271 G3_A1_VERSION=""
272 G4_A1_VERSION=""
273 G5_A1_VERSION=""
274 G1_COUNT=0
275 G2_COUNT=0
276 G3_COUNT=0
277 G4_COUNT=0
278 G5_COUNT=0
279
280 # Vars to switch between http and https. Extra curl flag needed for https
281 export RIC_SIM_HTTPX="http"
282 export RIC_SIM_LOCALHOST=$RIC_SIM_HTTPX"://localhost:"
283 export RIC_SIM_PORT=$RIC_SIM_INTERNAL_PORT
284 export RIC_SIM_CERT_MOUNT_DIR="./cert"
285
286 export MR_HTTPX="http"
287 export MR_PORT=$MR_INTERNAL_PORT
288 export MR_LOCAL_PORT=$MR_EXTERNAL_PORT #When agent is running outside the docker net
289
290 export CR_HTTPX="http"
291 export CR_PORT=$CR_INTERNAL_PORT
292 export CR_LOCAL_PORT=$CR_EXTERNAL_PORT #When CR is running outside the docker net
293
294 export PROD_STUB_HTTPX="http"
295 export PROD_STUB_PORT=$PROD_STUB_INTERNAL_PORT
296 export PROD_STUB_LOCAL_PORT=$PROD_STUB_EXTERNAL_PORT #When CR is running outside the docker net
297 export PROD_STUB_LOCALHOST=$PROD_STUB_HTTPX"://localhost:"$PROD_STUB_LOCAL_PORT
298
299 export SDNC_HTTPX="http"
300 export SDNC_PORT=$SDNC_INTERNAL_PORT
301 export SDNC_LOCAL_PORT=$SDNC_EXTERNAL_PORT #When agent is running outside the docker net
302
303 echo -e $BOLD"Checking configured image setting for this test case"$EBOLD
304
305 #Temp var to check for image variable name errors
306 IMAGE_ERR=0
307 #Create a file with image info for later printing as a table
308 image_list_file="./tmp/.image-list"
309 echo -e " Container\tImage\ttag" > $image_list_file
310
311 # Check if image env var is set and if so export the env var with image to use (used by docker compose files)
312 # arg: <image name> <script start-arg> <target-variable-name> <image-variable-name> <image-tag-variable-name> <app-short-name>
313 __check_image_var() {
314         if [ $# -ne 6 ]; then
315                 echo "Expected arg: <image name> <script start-arg> <target-variable-name> <image-variable-name> <image-tag-variable-name> <app-short-name>"
316                 ((IMAGE_ERR++))
317                 return
318         fi
319         __check_included_image $6
320         if [ $? -ne 0 ]; then
321                 echo -e "$1\t<image-excluded>\t<no-tag>"  >> $image_list_file
322                 # Image is excluded since the corresponding app is not used in this test
323                 return
324         fi
325         tmp=${1}"\t"
326         #Create var from the input var names
327         image="${!4}"
328         tag="${!5}"
329
330         if [ -z $image ]; then
331                 echo -e $RED"\$"$4" not set in $TEST_ENV_VAR_FILE"$ERED
332                 ((IMAGE_ERR++))
333                 echo ""
334                 tmp=$tmp"<no-image>\t"
335         else
336                 tmp=$tmp$image"\t"
337         fi
338         if [ -z $tag ]; then
339                 echo -e $RED"\$"$5" not set in $TEST_ENV_VAR_FILE"$ERED
340                 ((IMAGE_ERR++))
341                 echo ""
342                 tmp=$tmp"<no-tag>\t"
343         else
344                 tmp=$tmp$tag
345         fi
346         echo -e "$tmp" >> $image_list_file
347         #Export the env var
348         export "${3}"=$image":"$tag
349
350         #echo " Configured image for ${1} (script start arg=${2}): "$image":"$tag
351 }
352
353
354 #Check if app local image shall override remote image
355 # Possible IDs for local image override: PA, CP, SDNC, RICSIM, ECS
356 __check_image_local_override() {
357         for im in $USE_LOCAL_IMAGES; do
358                 if [ "$1" == "$im" ]; then
359                         return 1
360                 fi
361         done
362         return 0
363 }
364
365 # Check if app uses image included in this test run
366 # Returns 0 if image is included, 1 if not
367 # Possible IDs for image inclusion: CBS, CONSUL, CP, CR, ECS, MR, PA, PRODSTUB, RICSIM, SDNC
368 __check_included_image() {
369         for im in $INCLUDED_IMAGES; do
370                 if [ "$1" == "$im" ]; then
371                         return 0
372                 fi
373         done
374         return 1
375 }
376
377 # Check that image env setting are available
378 echo ""
379
380 if [ $START_ARG == "local" ]; then
381
382         #Local agent image
383         __check_image_var " Policy Agent" $START_ARG "POLICY_AGENT_IMAGE" "POLICY_AGENT_LOCAL_IMAGE" "POLICY_AGENT_LOCAL_IMAGE_TAG" PA
384
385         #Local Control Panel image
386         __check_image_var " Control Panel" $START_ARG "CONTROL_PANEL_IMAGE" "CONTROL_PANEL_LOCAL_IMAGE" "CONTROL_PANEL_LOCAL_IMAGE_TAG" CP
387
388         #Local SNDC image
389         __check_image_var " SDNC A1 Controller" $START_ARG "SDNC_A1_CONTROLLER_IMAGE" "SDNC_A1_CONTROLLER_LOCAL_IMAGE" "SDNC_A1_CONTROLLER_LOCAL_IMAGE_TAG" SDNC
390
391         #Local ric sim image
392         __check_image_var " RIC Simulator" $START_ARG "RIC_SIM_IMAGE" "RIC_SIM_LOCAL_IMAGE" "RIC_SIM_LOCAL_IMAGE_TAG" RICSIM
393
394 elif [ $START_ARG == "remote" ] || [ $START_ARG == "remote-remove" ]; then
395
396         __check_image_local_override 'PA'
397         if [ $? -eq 0 ]; then
398                 #Remote agent image
399                 __check_image_var " Policy Agent" $START_ARG "POLICY_AGENT_IMAGE" "POLICY_AGENT_REMOTE_IMAGE" "POLICY_AGENT_REMOTE_IMAGE_TAG" PA
400         else
401                 #Local agent image
402                 __check_image_var " Policy Agent" $START_ARG "POLICY_AGENT_IMAGE" "POLICY_AGENT_LOCAL_IMAGE" "POLICY_AGENT_LOCAL_IMAGE_TAG" PA
403         fi
404
405         __check_image_local_override 'CP'
406         if [ $? -eq 0 ]; then
407                 #Remote Control Panel image
408                 __check_image_var " Control Panel" $START_ARG "CONTROL_PANEL_IMAGE" "CONTROL_PANEL_REMOTE_IMAGE" "CONTROL_PANEL_REMOTE_IMAGE_TAG" CP
409         else
410                 #Local Control Panel image
411                 __check_image_var " Control Panel" $START_ARG "CONTROL_PANEL_IMAGE" "CONTROL_PANEL_LOCAL_IMAGE" "CONTROL_PANEL_LOCAL_IMAGE_TAG" CP
412         fi
413
414         __check_image_local_override 'SDNC'
415         if [ $? -eq 0 ]; then
416                 #Remote SDNC image
417                 __check_image_var " SDNC A1 Controller" $START_ARG "SDNC_A1_CONTROLLER_IMAGE" "SDNC_A1_CONTROLLER_REMOTE_IMAGE" "SDNC_A1_CONTROLLER_REMOTE_IMAGE_TAG" SDNC
418         else
419                 #Local SNDC image
420                 __check_image_var " SDNC A1 Controller" $START_ARG "SDNC_A1_CONTROLLER_IMAGE" "SDNC_A1_CONTROLLER_LOCAL_IMAGE" "SDNC_A1_CONTROLLER_LOCAL_IMAGE_TAG" SDNC
421         fi
422
423         __check_image_local_override 'RICSIM'
424         if [ $? -eq 0 ]; then
425                 #Remote ric sim image
426                 __check_image_var " RIC Simulator" $START_ARG "RIC_SIM_IMAGE" "RIC_SIM_REMOTE_IMAGE" "RIC_SIM_REMOTE_IMAGE_TAG" RICSIM
427         else
428                 #Local ric sim image
429                 __check_image_var " RIC Simulator" $START_ARG "RIC_SIM_IMAGE" "RIC_SIM_LOCAL_IMAGE" "RIC_SIM_LOCAL_IMAGE_TAG" RICSIM
430         fi
431
432         __check_image_local_override 'ECS'
433         if [ $? -eq 0 ]; then
434                 #Remote ecs image
435                 __check_image_var " ECS" $START_ARG "ECS_IMAGE" "ECS_REMOTE_IMAGE" "ECS_REMOTE_IMAGE_TAG" ECS
436         else
437                 #Local ecs image
438                 __check_image_var " ECS" $START_ARG "ECS_IMAGE" "ECS_LOCAL_IMAGE" "ECS_LOCAL_IMAGE_TAG" ECS
439         fi
440
441 else
442         #Should never get here....
443         echo "Unknow args: "$@
444         exit 1
445 fi
446
447
448 # These images are not built as part of this project official images, just check that env vars are set correctly
449 __check_image_var " Message Router" $START_ARG "MRSTUB_IMAGE" "MRSTUB_LOCAL_IMAGE" "MRSTUB_LOCAL_IMAGE_TAG" MR
450 __check_image_var " Callback Receiver" $START_ARG "CR_IMAGE" "CR_LOCAL_IMAGE" "CR_LOCAL_IMAGE_TAG" CR
451 __check_image_var " Producer stub" $START_ARG "PROD_STUB_IMAGE" "PROD_STUB_LOCAL_IMAGE" "PROD_STUB_LOCAL_IMAGE_TAG" PRODSTUB
452 __check_image_var " Consul" $START_ARG "CONSUL_IMAGE" "CONSUL_REMOTE_IMAGE" "CONSUL_REMOTE_IMAGE_TAG" CONSUL
453 __check_image_var " CBS" $START_ARG "CBS_IMAGE" "CBS_REMOTE_IMAGE" "CBS_REMOTE_IMAGE_TAG" CBS
454 __check_image_var " SDNC DB" $START_ARG "SDNC_DB_IMAGE" "SDNC_DB_REMOTE_IMAGE" "SDNC_DB_REMOTE_IMAGE_TAG" SDNC #Uses sdnc app name
455
456 #Errors in image setting - exit
457 if [ $IMAGE_ERR -ne 0 ]; then
458         exit 1
459 fi
460
461 #Print a tables of the image settings
462 echo -e $BOLD"Images configured for start arg: "$START $EBOLD
463 column -t -s $'\t' $image_list_file
464
465 echo ""
466
467
468 #Set the SIM_GROUP var
469 echo -e $BOLD"Setting var to main dir of all container/simulator scripts"$EBOLD
470 if [ -z "$SIM_GROUP" ]; then
471         SIM_GROUP=$PWD/../simulator-group
472         if [ ! -d  $SIM_GROUP ]; then
473                 echo "Trying to set env var SIM_GROUP to dir 'simulator-group' in the nontrtric repo, but failed."
474                 echo -e $RED"Please set the SIM_GROUP manually in the applicable $TEST_ENV_VAR_FILE"$ERED
475                 exit 1
476         else
477                 echo " SIM_GROUP auto set to: " $SIM_GROUP
478         fi
479 elif [ $SIM_GROUP = *simulator_group ]; then
480         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
481         exit 1
482 else
483         echo " SIM_GROUP env var already set to: " $SIM_GROUP
484 fi
485
486 echo ""
487
488 #Temp var to check for image pull errors
489 IMAGE_ERR=0
490
491 #Function to check if image exist and stop+remove the container+pull new images as needed
492 #args <script-start-arg> <descriptive-image-name> <container-base-name> <image-with-tag>
493 __check_and_pull_image() {
494
495         echo -e " Checking $BOLD$2$EBOLD container(s) with basename: $BOLD$3$EBOLD using image: $BOLD$4$EBOLD"
496         format_string="\"{{.Repository}}\\t{{.Tag}}\\t{{.CreatedSince}}\\t{{.Size}}\""
497         tmp_im=$(docker images --format $format_string ${4})
498
499         if [ $1 == "local" ]; then
500                 if [ -z "$tmp_im" ]; then
501                         echo -e "  "$2" (local image): \033[1m"$4"\033[0m $RED does not exist in local registry, need to be built (or manually pulled)"$ERED
502                         ((IMAGE_ERR++))
503                         return 1
504                 else
505                         echo -e "  "$2" (local image): \033[1m"$4"\033[0m "$GREEN"OK"$EGREEN
506                 fi
507         elif [ $1 == "remote" ] || [ $1 == "remote-remove" ]; then
508                 if [ $1 == "remote-remove" ]; then
509                         echo -ne "  Attempt to stop and remove container(s), if running - ${SAMELINE}"
510                         tmp="$(docker ps -aq --filter name=${3})"
511                         if [ $? -eq 0 ] && [ ! -z "$tmp" ]; then
512                                 docker stop $tmp &> ./tmp/.dockererr
513                                 if [ $? -ne 0 ]; then
514                                         ((IMAGE_ERR++))
515                                         echo ""
516                                         echo -e $RED"  Container(s) could not be stopped - try manual stopping the container(s)"$ERED
517                                         cat ./tmp/.dockererr
518                                         return 1
519                                 fi
520                         fi
521                         echo -ne "  Attempt to stop and remove container(s), if running - "$GREEN"stopped"$EGREEN"${SAMELINE}"
522                         tmp="$(docker ps -aq --filter name=${3})" &> /dev/null
523                         if [ $? -eq 0 ] && [ ! -z "$tmp" ]; then
524                                 docker rm $tmp &> ./tmp/.dockererr
525                                 if [ $? -ne 0 ]; then
526                                         ((IMAGE_ERR++))
527                                         echo ""
528                                         echo -e $RED"  Container(s) could not be removed - try manual removal of the container(s)"$ERED
529                                         cat ./tmp/.dockererr
530                                         return 1
531                                 fi
532                         fi
533                         echo -e "  Attempt to stop and remove container(s), if running - "$GREEN"stopped removed"$EGREEN
534                         echo -ne "  Removing image - ${SAMELINE}"
535                         tmp="$(docker images -q ${4})" &> /dev/null
536                         if [ $? -eq 0 ] && [ ! -z "$tmp" ]; then
537                                 docker rmi --force $4 &> ./tmp/.dockererr
538                                 if [ $? -ne 0 ]; then
539                                         ((IMAGE_ERR++))
540                                         echo ""
541                                         echo -e $RED"  Image could not be removed - try manual removal of the image"$ERED
542                                         cat ./tmp/.dockererr
543                                         return 1
544                                 fi
545                                 echo -e "  Removing image - "$GREEN"removed"$EGREEN
546                         else
547                                 echo -e "  Removing image - "$GREEN"image not in repository"$EGREEN
548                         fi
549                         tmp_im=""
550                 fi
551                 if [ -z "$tmp_im" ]; then
552                         echo -ne "  Pulling image${SAMELINE}"
553                         docker pull $4  &> ./tmp/.dockererr
554                         tmp_im=$(docker images ${4} | grep -v REPOSITORY)
555                         if [ -z "$tmp_im" ]; then
556                                 echo ""
557                                 echo -e "  Pulling image -$RED could not be pulled"$ERED
558                                 ((IMAGE_ERR++))
559                                 cat ./tmp/.dockererr
560                                 return 1
561                         fi
562                         echo -e "  Pulling image -$GREEN Pulled $EGREEN"
563                 else
564                         echo -e "  Pulling image -$GREEN OK $EGREEN(exists in local repository)"
565                 fi
566         fi
567         return 0
568 }
569
570
571 echo -e $BOLD"Pulling configured images, if needed"$EBOLD
572
573 __check_included_image 'PA'
574 if [ $? -eq 0 ]; then
575         START_ARG_MOD=$START_ARG
576         __check_image_local_override 'PA'
577         if [ $? -eq 1 ]; then
578                 START_ARG_MOD="local"
579         fi
580         app="Policy Agent";             __check_and_pull_image $START_ARG_MOD "$app" $POLICY_AGENT_APP_NAME $POLICY_AGENT_IMAGE
581 else
582         echo -e $YELLOW" Excluding PA image from image check/pull"$EYELLOW
583 fi
584
585 __check_included_image 'ECS'
586 if [ $? -eq 0 ]; then
587         START_ARG_MOD=$START_ARG
588         __check_image_local_override 'ECS'
589         if [ $? -eq 1 ]; then
590                 START_ARG_MOD="local"
591         fi
592         app="ECS";             __check_and_pull_image $START_ARG_MOD "$app" $ECS_APP_NAME $ECS_IMAGE
593 else
594         echo -e $YELLOW" Excluding ECS image from image check/pull"$EYELLOW
595 fi
596
597 __check_included_image 'CP'
598 if [ $? -eq 0 ]; then
599         START_ARG_MOD=$START_ARG
600         __check_image_local_override 'CP'
601         if [ $? -eq 1 ]; then
602                 START_ARG_MOD="local"
603         fi
604         app="Non-RT RIC Control Panel"; __check_and_pull_image $START_ARG_MOD "$app" $CONTROL_PANEL_APP_NAME $CONTROL_PANEL_IMAGE
605 else
606         echo -e $YELLOW" Excluding Non-RT RIC Control Panel image from image check/pull"$EYELLOW
607 fi
608
609 __check_included_image 'RICSIM'
610 if [ $? -eq 0 ]; then
611         START_ARG_MOD=$START_ARG
612         __check_image_local_override 'RICSIM'
613         if [ $? -eq 1 ]; then
614                 START_ARG_MOD="local"
615         fi
616         app="Near-RT RIC Simulator";    __check_and_pull_image $START_ARG_MOD "$app" $RIC_SIM_PREFIX"_"$RIC_SIM_BASE $RIC_SIM_IMAGE
617 else
618         echo -e $YELLOW" Excluding Near-RT RIC Simulator image from image check/pull"$EYELLOW
619 fi
620
621
622 __check_included_image 'CONSUL'
623 if [ $? -eq 0 ]; then
624         app="Consul";                   __check_and_pull_image $START_ARG "$app" $CONSUL_APP_NAME $CONSUL_IMAGE
625 else
626         echo -e $YELLOW" Excluding Consul image from image check/pull"$EYELLOW
627 fi
628
629 __check_included_image 'CBS'
630 if [ $? -eq 0 ]; then
631         app="CBS";                      __check_and_pull_image $START_ARG "$app" $CBS_APP_NAME $CBS_IMAGE
632 else
633         echo -e $YELLOW" Excluding CBS image from image check/pull"$EYELLOW
634 fi
635
636 __check_included_image 'SDNC'
637 if [ $? -eq 0 ]; then
638         START_ARG_MOD=$START_ARG
639         __check_image_local_override 'SDNC'
640         if [ $? -eq 1 ]; then
641                 START_ARG_MOD="local"
642         fi
643         app="SDNC A1 Controller";       __check_and_pull_image $START_ARG_MOD "$app" $SDNC_APP_NAME $SDNC_A1_CONTROLLER_IMAGE
644         app="SDNC DB";                  __check_and_pull_image $START_ARG "$app" $SDNC_APP_NAME $SDNC_DB_IMAGE
645 else
646         echo -e $YELLOW" Excluding SDNC image and related DB image from image check/pull"$EYELLOW
647 fi
648
649 #Errors in image setting - exit
650 if [ $IMAGE_ERR -ne 0 ]; then
651         echo ""
652         echo "#################################################################################################"
653         echo -e $RED"One or more images could not be pulled or containers using the images could not be stopped/removed"$ERED
654         echo -e $RED"Or local image, overriding remote image, does not exist"$ERED
655         echo "#################################################################################################"
656         echo ""
657         exit 1
658 fi
659
660 echo ""
661
662 echo -e $BOLD"Building images needed for test"$EBOLD
663
664 curdir=$PWD
665 __check_included_image 'MR'
666 if [ $? -eq 0 ]; then
667         cd $curdir
668         cd ../mrstub
669         echo " Building mrstub image: $MRSTUB_LOCAL_IMAGE:$MRSTUB_LOCAL_IMAGE_TAG"
670         docker build -t $MRSTUB_LOCAL_IMAGE . &> .dockererr
671         if [ $? -eq 0 ]; then
672                 echo -e  $GREEN" Build Ok"$EGREEN
673         else
674                 echo -e $RED" Build Failed"$ERED
675                 ((RES_CONF_FAIL++))
676                 cat .dockererr
677         fi
678         cd $curdir
679 else
680         echo -e $YELLOW" Excluding mrstub from image build"$EYELLOW
681 fi
682
683 __check_included_image 'CR'
684 if [ $? -eq 0 ]; then
685         cd ../cr
686         echo " Building Callback Receiver image: $CR_LOCAL_IMAGE:$CR_IMAGE_TAG"
687         docker build -t $CR_LOCAL_IMAGE . &> .dockererr
688         if [ $? -eq 0 ]; then
689                 echo -e  $GREEN" Build Ok"$EGREEN
690         else
691                 echo -e $RED" Build Failed"$ERED
692                 ((RES_CONF_FAIL++))
693                 cat .dockererr
694         fi
695         cd $curdir
696 else
697         echo -e $YELLOW" Excluding Callback Receiver from image build"$EYELLOW
698 fi
699
700 __check_included_image 'PRODSTUB'
701 if [ $? -eq 0 ]; then
702         cd ../prodstub
703         echo " Building Producer stub image: $PROD_STUB_LOCAL_IMAGE:$PROD_STUB_LOCAL_IMAGE_TAG"
704         docker build -t $PROD_STUB_LOCAL_IMAGE . &> .dockererr
705         if [ $? -eq 0 ]; then
706                 echo -e  $GREEN" Build Ok"$EGREEN
707         else
708                 echo -e $RED" Build Failed"$ERED
709                 ((RES_CONF_FAIL++))
710                 cat .dockererr
711         fi
712         cd $curdir
713 else
714         echo -e $YELLOW" Excluding Producer stub from image build"$EYELLOW
715 fi
716
717 echo ""
718
719 # Create a table of the images used in the script
720 echo -e $BOLD"Local docker registry images used in the this test script"$EBOLD
721
722 docker_tmp_file=./tmp/.docker-images-table
723 format_string="{{.Repository}}\\t{{.Tag}}\\t{{.CreatedSince}}\\t{{.Size}}\\t{{.CreatedAt}}"
724 echo -e " Application\tRepository\tTag\tCreated since\tSize\tCreated at" > $docker_tmp_file
725 __check_included_image 'PA'
726 if [ $? -eq 0 ]; then
727         echo -e " Policy Agent\t$(docker images --format $format_string $POLICY_AGENT_IMAGE)" >>   $docker_tmp_file
728 fi
729 __check_included_image 'ECS'
730 if [ $? -eq 0 ]; then
731         echo -e " ECS\t$(docker images --format $format_string $ECS_IMAGE)" >>   $docker_tmp_file
732 fi
733 __check_included_image 'CP'
734 if [ $? -eq 0 ]; then
735         echo -e " Control Panel\t$(docker images --format $format_string $CONTROL_PANEL_IMAGE)" >>   $docker_tmp_file
736 fi
737 __check_included_image 'RICSIM'
738 if [ $? -eq 0 ]; then
739         echo -e " RIC Simulator\t$(docker images --format $format_string $RIC_SIM_IMAGE)" >>   $docker_tmp_file
740 fi
741 __check_included_image 'MR'
742 if [ $? -eq 0 ]; then
743         echo -e " Message Router\t$(docker images --format $format_string $MRSTUB_IMAGE)" >>   $docker_tmp_file
744 fi
745 __check_included_image 'CR'
746 if [ $? -eq 0 ]; then
747         echo -e " Callback Receiver\t$(docker images --format $format_string $CR_IMAGE)" >>   $docker_tmp_file
748 fi
749 __check_included_image 'PRODSTUB'
750 if [ $? -eq 0 ]; then
751         echo -e " Produccer stub\t$(docker images --format $format_string $PROD_STUB_IMAGE)" >>   $docker_tmp_file
752 fi
753 __check_included_image 'CONSUL'
754 if [ $? -eq 0 ]; then
755         echo -e " Consul\t$(docker images --format $format_string $CONSUL_IMAGE)" >>   $docker_tmp_file
756 fi
757 __check_included_image 'CBS'
758 if [ $? -eq 0 ]; then
759         echo -e " CBS\t$(docker images --format $format_string $CBS_IMAGE)" >>   $docker_tmp_file
760 fi
761 __check_included_image 'SDNC'
762 if [ $? -eq 0 ]; then
763         echo -e " SDNC A1 Controller\t$(docker images --format $format_string $SDNC_A1_CONTROLLER_IMAGE)" >>   $docker_tmp_file
764         echo -e " SDNC DB\t$(docker images --format $format_string $SDNC_DB_IMAGE)" >>   $docker_tmp_file
765 fi
766
767 column -t -s $'\t' $docker_tmp_file
768
769 echo ""
770
771 echo -e $BOLD"======================================================="$EBOLD
772 echo -e $BOLD"== Common test setup completed -  test script begins =="$EBOLD
773 echo -e $BOLD"======================================================="$EBOLD
774 echo ""
775
776 # Function to print the test result, shall be the last cmd in a test script
777 # args: -
778 # (Function for test scripts)
779 print_result() {
780
781         TCTEST_END=$SECONDS
782         duration=$((TCTEST_END-TCTEST_START))
783
784         echo "-------------------------------------------------------------------------------------------------"
785         echo "-------------------------------------     Test case: "$ATC
786         echo "-------------------------------------     Ended:     "$(date)
787         echo "-------------------------------------------------------------------------------------------------"
788         echo "-- Description: "$TC_ONELINE_DESCR
789         echo "-- Execution time: " $duration " seconds"
790         echo "-------------------------------------------------------------------------------------------------"
791         echo "-------------------------------------     RESULTS"
792         echo ""
793
794
795         if [ $RES_DEVIATION -gt 0 ]; then
796                 echo "Test case deviations"
797                 echo "===================================="
798                 cat $DEVIATION_FILE
799         fi
800         echo ""
801         echo "Timer measurement in the test script"
802         echo "===================================="
803         column -t -s $'\t' $TIMER_MEASUREMENTS
804         echo ""
805
806         total=$((RES_PASS+RES_FAIL))
807         if [ $RES_TEST -eq 0 ]; then
808                 echo -e "\033[1mNo tests seem to have been executed. Check the script....\033[0m"
809                 echo -e "\033[31m\033[1m ___  ___ ___ ___ ___ _____   ___ _   ___ _   _   _ ___ ___ \033[0m"
810                 echo -e "\033[31m\033[1m/ __|/ __| _ \_ _| _ \_   _| | __/_\ |_ _| | | | | | _ \ __|\033[0m"
811                 echo -e "\033[31m\033[1m\__ \ (__|   /| ||  _/ | |   | _/ _ \ | || |_| |_| |   / _| \033[0m"
812                 echo -e "\033[31m\033[1m|___/\___|_|_\___|_|   |_|   |_/_/ \_\___|____\___/|_|_\___|\033[0m"
813         elif [ $total != $RES_TEST ]; then
814                 echo -e "\033[1mTotal number of tests does not match the sum of passed and failed tests. Check the script....\033[0m"
815                 echo -e "\033[31m\033[1m ___  ___ ___ ___ ___ _____   ___ _   ___ _   _   _ ___ ___ \033[0m"
816                 echo -e "\033[31m\033[1m/ __|/ __| _ \_ _| _ \_   _| | __/_\ |_ _| | | | | | _ \ __|\033[0m"
817                 echo -e "\033[31m\033[1m\__ \ (__|   /| ||  _/ | |   | _/ _ \ | || |_| |_| |   / _| \033[0m"
818                 echo -e "\033[31m\033[1m|___/\___|_|_\___|_|   |_|   |_/_/ \_\___|____\___/|_|_\___|\033[0m"
819         elif [ $RES_CONF_FAIL -ne 0 ]; then
820                 echo -e "\033[1mOne or more configure regest has failed. Check the script log....\033[0m"
821                 echo -e "\033[31m\033[1m ___  ___ ___ ___ ___ _____   ___ _   ___ _   _   _ ___ ___ \033[0m"
822                 echo -e "\033[31m\033[1m/ __|/ __| _ \_ _| _ \_   _| | __/_\ |_ _| | | | | | _ \ __|\033[0m"
823                 echo -e "\033[31m\033[1m\__ \ (__|   /| ||  _/ | |   | _/ _ \ | || |_| |_| |   / _| \033[0m"
824                 echo -e "\033[31m\033[1m|___/\___|_|_\___|_|   |_|   |_/_/ \_\___|____\___/|_|_\___|\033[0m"
825         elif [ $RES_PASS = $RES_TEST ]; then
826                 echo -e "All tests \033[32m\033[1mPASS\033[0m"
827                 echo -e "\033[32m\033[1m  ___  _   ___ ___ \033[0m"
828                 echo -e "\033[32m\033[1m | _ \/_\ / __/ __| \033[0m"
829                 echo -e "\033[32m\033[1m |  _/ _ \\__ \__ \\ \033[0m"
830                 echo -e "\033[32m\033[1m |_|/_/ \_\___/___/ \033[0m"
831                 echo ""
832
833                 # Update test suite counter
834                 if [ -f .tmp_tcsuite_pass_ctr ]; then
835                         tmpval=$(< .tmp_tcsuite_pass_ctr)
836                         ((tmpval++))
837                         echo $tmpval > .tmp_tcsuite_pass_ctr
838                 fi
839                 if [ -f .tmp_tcsuite_pass ]; then
840                         echo " - "$ATC " -- "$TC_ONELINE_DESCR"  Execution time: "$duration" seconds" >> .tmp_tcsuite_pass
841                 fi
842                 #Create file with OK exit code
843                 echo "0" > "$PWD/.result$ATC.txt"
844         else
845                 echo -e "One or more tests with status  \033[31m\033[1mFAIL\033[0m "
846                 echo -e "\033[31m\033[1m  ___ _   ___ _    \033[0m"
847                 echo -e "\033[31m\033[1m | __/_\ |_ _| |   \033[0m"
848                 echo -e "\033[31m\033[1m | _/ _ \ | || |__ \033[0m"
849                 echo -e "\033[31m\033[1m |_/_/ \_\___|____|\033[0m"
850                 echo ""
851                 # Update test suite counter
852                 if [ -f .tmp_tcsuite_fail_ctr ]; then
853                         tmpval=$(< .tmp_tcsuite_fail_ctr)
854                         ((tmpval++))
855                         echo $tmpval > .tmp_tcsuite_fail_ctr
856                 fi
857                 if [ -f .tmp_tcsuite_fail ]; then
858                         echo " - "$ATC " -- "$TC_ONELINE_DESCR"  Execution time: "$duration" seconds" >> .tmp_tcsuite_fail
859                 fi
860         fi
861
862         echo "++++ Number of tests:          "$RES_TEST
863         echo "++++ Number of passed tests:   "$RES_PASS
864         echo "++++ Number of failed tests:   "$RES_FAIL
865         echo ""
866         echo "++++ Number of failed configs: "$RES_CONF_FAIL
867         echo ""
868         echo "++++ Number of test case deviations: "$RES_DEVIATION
869         echo ""
870         echo "-------------------------------------     Test case complete    ---------------------------------"
871         echo "-------------------------------------------------------------------------------------------------"
872         echo ""
873 }
874
875 #####################################################################
876 ###### Functions for start, configuring, stoping, cleaning etc ######
877 #####################################################################
878
879 # Start timer for time measurement
880 # args - (any args will be printed though)
881 start_timer() {
882         echo -e $BOLD"INFO(${BASH_LINENO[0]}): "${FUNCNAME[0]}"," $@ $EBOLD
883         TC_TIMER=$SECONDS
884         echo " Timer started"
885 }
886
887 # Print the value of the time (in seconds)
888 # args - <timer message to print>  -  timer value and message will be printed both on screen
889 #                                     and in the timer measurement report
890 print_timer() {
891         echo -e $BOLD"INFO(${BASH_LINENO[0]}): "${FUNCNAME[0]}"," $@ $EBOLD
892         if [ $# -lt 1 ]; then
893                 ((RES_CONF_FAIL++))
894         __print_err "need 1 or more args,  <timer message to print>" $@
895                 exit 1
896         fi
897         duration=$(($SECONDS-$TC_TIMER))
898         if [ $duration -eq 0 ]; then
899                 duration="<1 second"
900         else
901                 duration=$duration" seconds"
902         fi
903         echo " Timer duration :" $duration
904
905         echo -e "${@:1} \t $duration" >> $TIMER_MEASUREMENTS
906 }
907
908 # Print the value of the time (in seconds) and reset the timer
909 # args - <timer message to print>  -  timer value and message will be printed both on screen
910 #                                     and in the timer measurement report
911 print_and_reset_timer() {
912         echo -e $BOLD"INFO(${BASH_LINENO[0]}): "${FUNCNAME[0]}"," $@ $EBOLD
913         if [ $# -lt 1 ]; then
914                 ((RES_CONF_FAIL++))
915         __print_err "need 1 or more args,  <timer message to print>" $@
916                 exit 1
917         fi
918         duration=$(($SECONDS-$TC_TIMER))" seconds"
919         if [ $duration -eq 0 ]; then
920                 duration="<1 second"
921         else
922                 duration=$duration" seconds"
923         fi
924         echo " Timer duration :" $duration
925         TC_TIMER=$SECONDS
926         echo " Timer reset"
927
928         echo -e "${@:1} \t $duration" >> $TIMER_MEASUREMENTS
929
930 }
931 # Print info about a deviations from intended tests
932 # Each deviation counted is also printed in the testreport
933 # args <deviation message to print>
934 deviation() {
935         echo -e $BOLD"DEVIATION(${BASH_LINENO[0]}): "${FUNCNAME[0]} $EBOLD
936         if [ $# -lt 1 ]; then
937                 ((RES_CONF_FAIL++))
938                 __print_err "need 1 or more args,  <deviation message to print>" $@
939                 exit 1
940         fi
941         ((RES_DEVIATION++))
942         echo -e $BOLD$YELLOW" Test case deviation: ${@:1}"$EYELLOW$EBOLD
943         echo "Line: ${BASH_LINENO[0]} - ${@:1}" >> $DEVIATION_FILE
944         echo ""
945 }
946
947 # Stop at first FAIL test case and take all logs - only for debugging/trouble shooting
948 __check_stop_at_error() {
949         if [ $STOP_AT_ERROR -eq 1 ]; then
950                 echo -e $RED"Test script configured to stop at first FAIL, taking all logs and stops"$ERED
951                 store_logs "STOP_AT_ERROR"
952                 exit 1
953         fi
954         return 0
955 }
956
957 # Check if app name var is set. If so return the app name otherwise return "NOTSET"
958 __check_app_name() {
959         if [ $# -eq 1 ]; then
960                 echo $1
961         else
962                 echo "NOTSET"
963         fi
964 }
965
966 # Stop and remove all containers
967 # args: -
968 # (Function for test scripts)
969 clean_containers() {
970
971         echo -e $BOLD"Stopping and removing all running containers, by container name"$EBOLD
972
973         CONTAINTER_NAMES=("Policy Agent           " $(__check_app_name $POLICY_AGENT_APP_NAME)\
974                                           "ECS                    " $(__check_app_name $ECS_APP_NAME)\
975                                           "Non-RT RIC Simulator(s)" $(__check_app_name $RIC_SIM_PREFIX)\
976                                           "Message Router         " $(__check_app_name $MR_APP_NAME)\
977                                           "Callback Receiver      " $(__check_app_name $CR_APP_NAME)\
978                                           "Producer stub          " $(__check_app_name $PROD_STUB_APP_NAME)\
979                                           "Control Panel          " $(__check_app_name $CONTROL_PANEL_APP_NAME)\
980                                           "SDNC A1 Controller     " $(__check_app_name $SDNC_APP_NAME)\
981                                           "SDNC DB                " $(__check_app_name $SDNC_DB_APP_NAME)\
982                                           "CBS                    " $(__check_app_name $CBS_APP_NAME)\
983                                           "Consul                 " $(__check_app_name $CONSUL_APP_NAME))
984
985         nw=0 # Calc max width of container name, to make a nice table
986         for (( i=1; i<${#CONTAINTER_NAMES[@]} ; i+=2 )) ; do
987
988                 if [ ${#CONTAINTER_NAMES[i]} -gt $nw ]; then
989                         nw=${#CONTAINTER_NAMES[i]}
990                 fi
991         done
992
993         for (( i=0; i<${#CONTAINTER_NAMES[@]} ; i+=2 )) ; do
994                 APP="${CONTAINTER_NAMES[i]}"
995                 CONTR="${CONTAINTER_NAMES[i+1]}"
996                 if [ $CONTR != "NOTSET" ]; then
997                         for((w=${#CONTR}; w<$nw; w=w+1)); do
998                                 CONTR="$CONTR "
999                         done
1000                         echo -ne " $APP: $CONTR - ${GREEN}stopping${EGREEN}${SAMELINE}"
1001                         docker stop $(docker ps -qa --filter name=${CONTR}) &> /dev/null
1002                         echo -ne " $APP: $CONTR - ${GREEN}stopped${EGREEN}${SAMELINE}"
1003                         docker rm --force $(docker ps -qa --filter name=${CONTR}) &> /dev/null
1004                         echo -e  " $APP: $CONTR - ${GREEN}stopped removed${EGREEN}"
1005                 fi
1006         done
1007
1008         echo ""
1009
1010         echo -e $BOLD" Removing docker network"$EBOLD
1011         TMP=$(docker network ls -q --filter name=$DOCKER_SIM_NWNAME)
1012         if [ "$TMP" ==  $DOCKER_SIM_NWNAME ]; then
1013                 docker network rm $DOCKER_SIM_NWNAME | indent2
1014                 if [ $? -ne 0 ];  then
1015                         echo -e $RED" Cannot remove docker network. Manually remove or disconnect containers from $DOCKER_SIM_NWNAME"$ERED
1016                         exit 1
1017                 fi
1018         fi
1019         echo -e "$GREEN  Done$EGREEN"
1020
1021         echo -e $BOLD" Removing all unused docker neworks"$EBOLD
1022         docker network prune --force | indent2
1023         echo -e "$GREEN  Done$EGREEN"
1024
1025         echo -e $BOLD" Removing all unused docker volumes"$EBOLD
1026         docker volume prune --force | indent2
1027         echo -e "$GREEN  Done$EGREEN"
1028
1029         echo -e $BOLD" Removing all dangling/untagged docker images"$EBOLD
1030     docker rmi --force $(docker images -q -f dangling=true) &> /dev/null
1031         echo -e "$GREEN  Done$EGREEN"
1032         echo ""
1033
1034         CONTRS=$(docker ps | awk '$1 != "CONTAINER" { n++ }; END { print n+0 }')
1035         if [ $? -eq 0 ]; then
1036                 if [ $CONTRS -ne 0 ]; then
1037                         echo -e $RED"Containers running, may cause distubance to the test case"$ERED
1038                         docker ps -a
1039                 fi
1040         fi
1041 }
1042
1043 # Function stop and remove all container in the end of the test script, if the arg 'auto-clean' is given at test script start
1044 # args: -
1045 # (Function for test scripts)
1046 auto_clean_containers() {
1047         echo
1048         if [ "$AUTO_CLEAN" == "auto" ]; then
1049                 echo -e $BOLD"Initiating automatic cleaning of started containers"$EBOLD
1050                 clean_containers
1051         fi
1052 }
1053
1054 # Function to sleep a test case for a numner of seconds. Prints the optional text args as info
1055 # args: <sleep-time-in-sec> [any-text-in-quotes-to-be-printed]
1056 # (Function for test scripts)
1057 sleep_wait() {
1058
1059         echo -e $BOLD"INFO(${BASH_LINENO[0]}): "${FUNCNAME[0]}"," $@ $EBOLD
1060         if [ $# -lt 1 ]; then
1061                 ((RES_CONF_FAIL++))
1062                 __print_err "need at least one arg, <sleep-time-in-sec> [any-text-to-printed]" $@
1063                 exit 1
1064         fi
1065         #echo "---- Sleep for " $1 " seconds ---- "$2
1066         start=$SECONDS
1067         duration=$((SECONDS-start))
1068         while [ $duration -lt $1 ]; do
1069                 echo -ne "  Slept for ${duration} seconds${SAMELINE}"
1070                 sleep 1
1071                 duration=$((SECONDS-start))
1072         done
1073         echo -ne "  Slept for ${duration} seconds${SAMELINE}"
1074         echo ""
1075 }
1076
1077 # Print error info for the call in the parent script (test case). Arg: <error-message-to-print>
1078 # Not to be called from the test script itself.
1079 __print_err() {
1080     echo -e $RED ${FUNCNAME[1]} " "$1" " ${BASH_SOURCE[2]} " line" ${BASH_LINENO[1]} $ERED
1081         if [ $# -gt 1 ]; then
1082                 echo -e $RED" Got: "${FUNCNAME[1]} ${@:2} $ERED
1083         fi
1084 }
1085
1086
1087 # Helper function to get a the port of a specific ric simulatpor
1088 # args: <ric-id>
1089 # (Not for test scripts)
1090 __find_sim_port() {
1091     name=$1" " #Space appended to prevent matching 10 if 1 is desired....
1092     cmdstr="docker inspect --format='{{(index (index .NetworkSettings.Ports \"$RIC_SIM_PORT/tcp\") 0).HostPort}}' ${name}"
1093     res=$(eval $cmdstr)
1094         if [[ "$res" =~ ^[0-9]+$ ]]; then
1095                 echo $res
1096         else
1097                 echo "0"
1098     fi
1099 }
1100
1101 # Function to create the docker network for the test
1102 # Not to be called from the test script itself.
1103 __create_docker_network() {
1104         tmp=$(docker network ls --format={{.Name}} --filter name=$DOCKER_SIM_NWNAME)
1105         if [ $? -ne 0 ]; then
1106                 echo -e $RED" Could not check if docker network $DOCKER_SIM_NWNAME exists"$ERED
1107                 return 1
1108         fi
1109         if [ "$tmp" != $DOCKER_SIM_NWNAME ]; then
1110                 echo -e " Creating docker network:$BOLD $DOCKER_SIM_NWNAME $EBOLD"
1111                 docker network create $DOCKER_SIM_NWNAME | indent2
1112                 if [ $? -ne 0 ]; then
1113                         echo -e $RED" Could not create docker network $DOCKER_SIM_NWNAME"$ERED
1114                         return 1
1115                 else
1116                         echo -e "$GREEN  Done$EGREEN"
1117                 fi
1118         else
1119                 echo -e " Docker network $DOCKER_SIM_NWNAME already exists$GREEN OK $EGREEN"
1120         fi
1121 }
1122
1123 # Check if container is started by calling url on localhost using a port, expects response code 2XX
1124 # args: <container-name> <port> <url> https|https
1125 # Not to be called from the test script itself.
1126 __check_container_start() {
1127         paramError=0
1128         if [ $# -ne 4 ]; then
1129                 paramError=1
1130         elif [ $4 != "http" ] && [ $4 != "https" ]; then
1131                 paramError=1
1132         fi
1133         if [ $paramError -ne 0 ]; then
1134                 ((RES_CONF_FAIL++))
1135                 __print_err "need 3 args, <container-name> <port> <url> https|https" $@
1136                 return 1
1137         fi
1138         echo -ne " Container $BOLD$1$EBOLD starting${SAMELINE}"
1139         appname=$1
1140         localport=$2
1141         url=$3
1142         if [[ $appname != "STANDALONE_"* ]]     ; then
1143                 app_started=0
1144                 for i in {1..10}; do
1145                         if [ "$(docker inspect --format '{{ .State.Running }}' $appname)" == "true" ]; then
1146                                         echo -e " Container $BOLD$1$EBOLD$GREEN running$EGREEN on$BOLD image $(docker inspect --format '{{ .Config.Image }}' ${appname}) $EBOLD"
1147                                         app_started=1
1148                                         break
1149                                 else
1150                                         sleep $i
1151                         fi
1152                 done
1153                 if [ $app_started -eq 0 ]; then
1154                         ((RES_CONF_FAIL++))
1155                         echo ""
1156                         echo -e $RED" Container $BOLD${appname}$EBOLD could not be started"$ERED
1157                         return 1
1158                 fi
1159                 if [ $localport -eq 0 ]; then
1160                         while [ $localport -eq 0 ]; do
1161                                 echo -ne " Waiting for container ${appname} to publish its ports...${SAMELINE}"
1162                                 localport=$(__find_sim_port $appname)
1163                                 sleep 1
1164                                 echo -ne " Waiting for container ${appname} to publish its ports...retrying....${SAMELINE}"
1165                         done
1166                         echo -ne " Waiting for container ${appname} to publish its ports...retrying....$GREEN OK $EGREEN"
1167                         echo ""
1168                 fi
1169         fi
1170
1171         pa_st=false
1172         echo -ne " Waiting for container ${appname} service status...${SAMELINE}"
1173         TSTART=$SECONDS
1174         for i in {1..50}; do
1175                 if [ $4 == "https" ]; then
1176                         result="$(__do_curl "-k https://localhost:"${localport}${url})"
1177                 else
1178                         result="$(__do_curl $LOCALHOST${localport}${url})"
1179                 fi
1180                 if [ $? -eq 0 ]; then
1181                         if [ ${#result} -gt 15 ]; then
1182                                 #If response is too long, truncate
1183                                 result="...response text too long, omitted"
1184                         fi
1185                         echo -ne " Waiting for container $BOLD${appname}$EBOLD service status, result: $result${SAMELINE}"
1186                         echo -ne " Container $BOLD${appname}$EBOLD$GREEN is alive$EGREEN, responds to service status:$GREEN $result $EGREEN after $(($SECONDS-$TSTART)) seconds"
1187                         pa_st=true
1188                         break
1189                 else
1190                         TS_TMP=$SECONDS
1191                         while [ $(($TS_TMP+$i)) -gt $SECONDS ]; do
1192                                 echo -ne " Waiting for container ${appname} service status...retrying in $(($TS_TMP+$i-$SECONDS)) seconds   ${SAMELINE}"
1193                                 sleep 1
1194                         done
1195                 fi
1196         done
1197
1198         if [ "$pa_st" = "false"  ]; then
1199                 ((RES_CONF_FAIL++))
1200                 echo -e $RED" Container ${appname} did not respond to service status"$ERED
1201                 return 0
1202         fi
1203
1204         echo ""
1205         return 0
1206 }
1207
1208
1209 # Function to start a container and wait until it responds on the given port and url.
1210 #args: <docker-compose-dir> NODOCKERARGS|<docker-compose-arg> <app-name> <port-number> <alive-url> [<app-name> <port-number> <alive-url>]*
1211 __start_container() {
1212
1213         variableArgCount=$(($#-2))
1214         if [ $# -lt 6 ] && [ [ $(($variableArgCount%4)) -ne 0 ]; then
1215                 ((RES_CONF_FAIL++))
1216         __print_err "need 6 or more args,  <docker-compose-dir> NODOCKERARGS|<docker-compose-arg> <app-name> <port-number> <alive-url> http|https [<app-name> <port-number> <alive-url> http|https ]*" $@
1217                 exit 1
1218         fi
1219
1220         __create_docker_network
1221
1222         curdir=$PWD
1223         cd $SIM_GROUP
1224         cd $1
1225
1226         if [ "$2" == "NODOCKERARGS" ]; then
1227                 docker-compose up -d &> .dockererr
1228                 if [ $? -ne 0 ]; then
1229                         echo -e $RED"Problem to launch container(s) with docker-compose"$ERED
1230                         cat .dockererr
1231                 fi
1232         elif [ "$2" == "STANDALONE" ]; then
1233                 echo "Skipping docker-compose"
1234         else
1235                 docker-compose up -d $2 &> .dockererr
1236                 if [ $? -ne 0 ]; then
1237                         echo -e $RED"Problem to launch container(s) with docker-compose"$ERED
1238                         cat .dockererr
1239                 fi
1240         fi
1241         app_prefix=""
1242         if [ "$2" == "STANDALONE" ]; then
1243                 app_prefix="STANDALONE_"
1244         fi
1245         shift; shift;
1246         cntr=0
1247         while [ $cntr -lt $variableArgCount ]; do
1248                 app=$app_prefix$1; shift;
1249                 port=$1; shift;
1250                 url=$1; shift;
1251                 httpx=$1; shift;
1252                 let cntr=cntr+4
1253
1254                 __check_container_start "$app" "$port" "$url" $httpx
1255         done
1256
1257         cd $curdir
1258         echo ""
1259         return 0
1260 }
1261
1262 # Generate a UUID to use as prefix for policy ids
1263 generate_uuid() {
1264         UUID=$(python3 -c 'import sys,uuid; sys.stdout.write(uuid.uuid4().hex)')
1265         #Reduce length to make space for serial id, us 'a' as marker where the serial id is added
1266         UUID=${UUID:0:${#UUID}-4}"a"
1267 }
1268
1269 ####################
1270 ### Consul functions
1271 ####################
1272
1273 # Function to load config from a file into consul for the Policy Agent
1274 # arg: <json-config-file>
1275 # (Function for test scripts)
1276 consul_config_app() {
1277
1278         echo -e $BOLD"Configuring Consul"$EBOLD
1279
1280         if [ $# -ne 1 ]; then
1281                 ((RES_CONF_FAIL++))
1282         __print_err "need one arg,  <json-config-file>" $@
1283                 exit 1
1284         fi
1285
1286         echo " Loading config for "$POLICY_AGENT_APP_NAME" from "$1
1287
1288         curlString="$LOCALHOST${CONSUL_EXTERNAL_PORT}/v1/kv/${POLICY_AGENT_APP_NAME}?dc=dc1 -X PUT -H Accept:application/json -H Content-Type:application/json -H X-Requested-With:XMLHttpRequest --data-binary @"$1
1289         result=$(__do_curl "$curlString")
1290         if [ $? -ne 0 ]; then
1291                 echo -e $RED" FAIL - json config could not be loaded to consul" $ERED
1292                 ((RES_CONF_FAIL++))
1293                 return 1
1294         fi
1295         body="$(__do_curl $LOCALHOST$CBS_EXTERNAL_PORT/service_component_all/$POLICY_AGENT_APP_NAME)"
1296         echo $body > "./tmp/.output"$1
1297
1298         if [ $? -ne 0 ]; then
1299                 echo -e $RED" FAIL - json config could not be loaded from consul/cbs, contents cannot be checked." $ERED
1300                 ((RES_CONF_FAIL++))
1301                 return 1
1302         else
1303                 targetJson=$(< $1)
1304                 targetJson="{\"config\":"$targetJson"}"
1305                 echo "TARGET JSON: $targetJson" >> $HTTPLOG
1306                 res=$(python3 ../common/compare_json.py "$targetJson" "$body")
1307                 if [ $res -ne 0 ]; then
1308                         echo -e $RED" FAIL - policy json config read from consul/cbs is not equal to the intended json config...." $ERED
1309                         ((RES_CONF_FAIL++))
1310                         return 1
1311                 else
1312                         echo -e $GREEN" Config loaded ok to consul"$EGREEN
1313                 fi
1314         fi
1315
1316         echo ""
1317
1318 }
1319
1320 # Function to perpare the consul configuration according to the current simulator configuration
1321 # args: SDNC|NOSDNC <output-file>
1322 # (Function for test scripts)
1323 prepare_consul_config() {
1324         echo -e $BOLD"Prepare Consul config"$EBOLD
1325
1326         echo " Writing consul config for "$POLICY_AGENT_APP_NAME" to file: "$2
1327
1328         if [ $# != 2 ];  then
1329                 ((RES_CONF_FAIL++))
1330         __print_err "need two args,  SDNC|NOSDNC <output-file>" $@
1331                 exit 1
1332         fi
1333
1334         if [ $1 == "SDNC" ]; then
1335                 echo -e " Config$BOLD including SDNC$EBOLD configuration"
1336         elif [ $1 == "NOSDNC" ];  then
1337                 echo -e " Config$BOLD excluding SDNC$EBOLD configuration"
1338         else
1339                 ((RES_CONF_FAIL++))
1340         __print_err "need two args,  SDNC|NOSDNC <output-file>" $@
1341                 exit 1
1342         fi
1343
1344         config_json="\n            {"
1345         if [ $1 == "SDNC" ]; then
1346                 config_json=$config_json"\n   \"controller\": ["
1347                 config_json=$config_json"\n                     {"
1348                 config_json=$config_json"\n                       \"name\": \"$SDNC_APP_NAME\","
1349                 if [ $AGENT_STAND_ALONE -eq 0 ]; then
1350                         config_json=$config_json"\n                       \"baseUrl\": \"$SDNC_HTTPX://$SDNC_APP_NAME:$SDNC_PORT\","
1351                 else
1352                         config_json=$config_json"\n                       \"baseUrl\": \"$SDNC_HTTPX://localhost:$SDNC_LOCAL_PORT\","
1353                 fi
1354                 config_json=$config_json"\n                       \"userName\": \"$SDNC_USER\","
1355                 config_json=$config_json"\n                       \"password\": \"$SDNC_PWD\""
1356                 config_json=$config_json"\n                     }"
1357                 config_json=$config_json"\n   ],"
1358         fi
1359
1360         config_json=$config_json"\n   \"streams_publishes\": {"
1361         config_json=$config_json"\n                            \"dmaap_publisher\": {"
1362         config_json=$config_json"\n                              \"type\": \"$MR_APP_NAME\","
1363         config_json=$config_json"\n                              \"dmaap_info\": {"
1364         if [ $AGENT_STAND_ALONE -eq 0 ]; then
1365                 config_json=$config_json"\n                                \"topic_url\": \"$MR_HTTPX://$MR_APP_NAME:$MR_PORT$MR_WRITE_URL\""
1366         else
1367                 config_json=$config_json"\n                                \"topic_url\": \"$MR_HTTPX://localhost:$MR_LOCAL_PORT$MR_WRITE_URL\""
1368         fi
1369         config_json=$config_json"\n                              }"
1370         config_json=$config_json"\n                            }"
1371         config_json=$config_json"\n   },"
1372         config_json=$config_json"\n   \"streams_subscribes\": {"
1373         config_json=$config_json"\n                             \"dmaap_subscriber\": {"
1374         config_json=$config_json"\n                               \"type\": \"$MR_APP_NAME\","
1375         config_json=$config_json"\n                               \"dmaap_info\": {"
1376         if [ $AGENT_STAND_ALONE -eq 0 ]; then
1377                 config_json=$config_json"\n                                   \"topic_url\": \"$MR_HTTPX://$MR_APP_NAME:$MR_PORT$MR_READ_URL\""
1378         else
1379                 config_json=$config_json"\n                                   \"topic_url\": \"$MR_HTTPX://localhost:$MR_LOCAL_PORT$MR_READ_URL\""
1380         fi
1381         config_json=$config_json"\n                                 }"
1382         config_json=$config_json"\n                               }"
1383         config_json=$config_json"\n   },"
1384
1385         config_json=$config_json"\n   \"ric\": ["
1386
1387         rics=$(docker ps | grep $RIC_SIM_PREFIX | awk '{print $NF}')
1388
1389         if [ $? -ne 0 ] || [ -z "$rics" ]; then
1390                 echo -e $RED" FAIL - the names of the running RIC Simulator cannot be retrieved." $ERED
1391                 ((RES_CONF_FAIL++))
1392                 return 1
1393         fi
1394
1395         cntr=0
1396         for ric in $rics; do
1397                 if [ $cntr -gt 0 ]; then
1398                         config_json=$config_json"\n          ,"
1399                 fi
1400                 config_json=$config_json"\n          {"
1401                 config_json=$config_json"\n            \"name\": \"$ric\","
1402                 if [ $AGENT_STAND_ALONE -eq 0 ]; then
1403                         config_json=$config_json"\n            \"baseUrl\": \"$RIC_SIM_HTTPX://$ric:$RIC_SIM_PORT\","
1404                 else
1405                         config_json=$config_json"\n            \"baseUrl\": \"$RIC_SIM_HTTPX://localhost:$(__find_sim_port $ric)\","
1406                 fi
1407                 if [ $1 == "SDNC" ]; then
1408                         config_json=$config_json"\n            \"controller\": \"$SDNC_APP_NAME\","
1409                 fi
1410                 config_json=$config_json"\n            \"managedElementIds\": ["
1411                 config_json=$config_json"\n              \"me1_$ric\","
1412                 config_json=$config_json"\n              \"me2_$ric\""
1413                 config_json=$config_json"\n            ]"
1414                 config_json=$config_json"\n          }"
1415                 let cntr=cntr+1
1416         done
1417
1418         config_json=$config_json"\n           ]"
1419         config_json=$config_json"\n}"
1420
1421
1422         printf "$config_json">$2
1423
1424         echo ""
1425 }
1426
1427
1428 # Start Consul and CBS
1429 # args: -
1430 # (Function for test scripts)
1431 start_consul_cbs() {
1432
1433         echo -e $BOLD"Starting Consul and CBS"$EBOLD
1434         __check_included_image 'CONSUL'
1435         if [ $? -eq 1 ]; then
1436                 echo -e $RED"The Consul image has not been checked for this test run due to arg to the test script"$ERED
1437                 echo -e $RED"Consul will not be started"$ERED
1438                 exit
1439         fi
1440         __start_container consul_cbs NODOCKERARGS  "$CONSUL_APP_NAME" "$CONSUL_EXTERNAL_PORT" "/ui/dc1/kv" "http" \
1441                                                      "$CBS_APP_NAME" "$CBS_EXTERNAL_PORT" "/healthcheck" "http"
1442 }
1443
1444 ###########################
1445 ### RIC Simulator functions
1446 ###########################
1447
1448 use_simulator_http() {
1449         echo -e "Using $BOLD http $EBOLD towards the simulators"
1450         export RIC_SIM_HTTPX="http"
1451         export RIC_SIM_LOCALHOST=$RIC_SIM_HTTPX"://localhost:"
1452         export RIC_SIM_PORT=$RIC_SIM_INTERNAL_PORT
1453         echo ""
1454 }
1455
1456 use_simulator_https() {
1457         echo -e "Using $BOLD https $EBOLD towards the simulators"
1458         export RIC_SIM_HTTPX="https"
1459         export RIC_SIM_LOCALHOST=$RIC_SIM_HTTPX"://localhost:"
1460         export RIC_SIM_PORT=$RIC_SIM_INTERNAL_SECURE_PORT
1461         echo ""
1462 }
1463
1464 # Start one group (ricsim_g1, ricsim_g2 .. ricsim_g5) with a number of RIC Simulators using a given A interface
1465 # 'ricsim' may be set on command line to other prefix
1466 # args:  ricsim_g1|ricsim_g2|ricsim_g3|ricsim_g4|ricsim_g5 <count> <interface-id>
1467 # (Function for test scripts)
1468 start_ric_simulators() {
1469
1470         echo -e $BOLD"Starting RIC Simulators"$EBOLD
1471
1472         __check_included_image 'RICSIM'
1473         if [ $? -eq 1 ]; then
1474                 echo -e $RED"The Near-RT RIC Simulator image has not been checked for this test run due to arg to the test script"$ERED
1475                 echo -e $RED"The Near-RT RIC Simulartor(s) will not be started"$ERED
1476                 exit
1477         fi
1478
1479         RIC1=$RIC_SIM_PREFIX"_g1"
1480         RIC2=$RIC_SIM_PREFIX"_g2"
1481         RIC3=$RIC_SIM_PREFIX"_g3"
1482         RIC4=$RIC_SIM_PREFIX"_g4"
1483         RIC5=$RIC_SIM_PREFIX"_g5"
1484
1485         if [ $# != 3 ]; then
1486                 ((RES_CONF_FAIL++))
1487         __print_err "need three args,  $RIC1|$RIC2|$RIC3|$RIC4|$RIC5 <count> <interface-id>" $@
1488                 exit 1
1489         fi
1490         echo " $2 simulators using basename: $1 on interface: $3"
1491         #Set env var for simulator count and A1 interface vesion for the given group
1492         if [ $1 == "$RIC1" ]; then
1493                 G1_COUNT=$2
1494                 G1_A1_VERSION=$3
1495         elif [ $1 == "$RIC2" ]; then
1496                 G2_COUNT=$2
1497                 G2_A1_VERSION=$3
1498         elif [ $1 == "$RIC3" ]; then
1499                 G3_COUNT=$2
1500                 G3_A1_VERSION=$3
1501         elif [ $1 == "$RIC4" ]; then
1502                 G4_COUNT=$2
1503                 G4_A1_VERSION=$3
1504         elif [ $1 == "$RIC5" ]; then
1505                 G5_COUNT=$2
1506                 G5_A1_VERSION=$3
1507         else
1508                 ((RES_CONF_FAIL++))
1509         __print_err "need three args, $RIC1|$RIC2|$RIC3|$RIC4|$RIC5 <count> <interface-id>" $@
1510                 exit 1
1511         fi
1512
1513         # Create .env file to compose project, all ric container will get this prefix
1514         echo "COMPOSE_PROJECT_NAME="$RIC_SIM_PREFIX > $SIM_GROUP/ric/.env
1515
1516         export G1_A1_VERSION
1517         export G2_A1_VERSION
1518         export G3_A1_VERSION
1519         export G4_A1_VERSION
1520         export G5_A1_VERSION
1521
1522         docker_args="--scale g1=$G1_COUNT --scale g2=$G2_COUNT --scale g3=$G3_COUNT --scale g4=$G4_COUNT --scale g5=$G5_COUNT"
1523         app_data=""
1524         cntr=1
1525         while [ $cntr -le $2 ]; do
1526                 app=$1"_"$cntr
1527                 port=0
1528                 app_data="$app_data $app $port / "$RIC_SIM_HTTPX
1529                 let cntr=cntr+1
1530         done
1531         __start_container ric "$docker_args" $app_data
1532
1533 }
1534
1535 ###########################
1536 ### Control Panel functions
1537 ###########################
1538
1539 # Start the Control Panel container
1540 # args: -
1541 # (Function for test scripts)
1542 start_control_panel() {
1543
1544         echo -e $BOLD"Starting Control Panel"$EBOLD
1545         __check_included_image 'CP'
1546         if [ $? -eq 1 ]; then
1547                 echo -e $RED"The Control Panel image has not been checked for this test run due to arg to the test script"$ERED
1548                 echo -e $RED"The Control Panel will not be started"$ERED
1549                 exit
1550         fi
1551         __start_container control_panel NODOCKERARGS $CONTROL_PANEL_APP_NAME $CONTROL_PANEL_EXTERNAL_PORT "/" "http"
1552
1553 }
1554
1555 ##################
1556 ### SDNC functions
1557 ##################
1558
1559 # Start the SDNC A1 Controller
1560 # args: -
1561 # (Function for test scripts)
1562 start_sdnc() {
1563
1564         echo -e $BOLD"Starting SDNC A1 Controller"$EBOLD
1565
1566         __check_included_image 'SDNC'
1567         if [ $? -eq 1 ]; then
1568                 echo -e $RED"The image for SDNC and the related DB has not been checked for this test run due to arg to the test script"$ERED
1569                 echo -e $RED"SDNC will not be started"$ERED
1570                 exit
1571         fi
1572
1573         __start_container sdnc NODOCKERARGS $SDNC_APP_NAME $SDNC_EXTERNAL_PORT $SDNC_ALIVE_URL "http"
1574
1575 }
1576
1577 use_sdnc_http() {
1578         echo -e "Using $BOLD http $EBOLD towards SDNC"
1579         export SDNC_HTTPX="http"
1580         export SDNC_PORT=$SDNC_INTERNAL_PORT
1581         export SDNC_LOCAL_PORT=$SDNC_EXTERNAL_PORT
1582         echo ""
1583 }
1584
1585 use_sdnc_https() {
1586         echo -e "Using $BOLD https $EBOLD towards SDNC"
1587         export SDNC_HTTPX="https"
1588         export SDNC_PORT=$SDNC_INTERNAL_SECURE_PORT
1589         export SDNC_LOCAL_PORT=$SDNC_EXTERNAL_SECURE_PORT
1590         echo ""
1591 }
1592
1593 #####################
1594 ### MR stub functions
1595 #####################
1596
1597 # Start the Message Router stub interface in the simulator group
1598 # args: -
1599 # (Function for test scripts)
1600 start_mr() {
1601
1602         echo -e $BOLD"Starting Message Router 'mrstub'"$EBOLD
1603         __check_included_image 'MR'
1604         if [ $? -eq 1 ]; then
1605                 echo -e $RED"The Message Router image has not been checked for this test run due to arg to the test script"$ERED
1606                 echo -e $RED"The Message Router will not be started"$ERED
1607                 exit
1608         fi
1609         export MR_CERT_MOUNT_DIR="./cert"
1610         __start_container mr NODOCKERARGS $MR_APP_NAME $MR_EXTERNAL_PORT "/" "http"
1611 }
1612
1613 use_mr_http() {
1614         echo -e "Using $BOLD http $EBOLD towards MR"
1615         export MR_HTTPX="http"
1616         export MR_PORT=$MR_INTERNAL_PORT
1617         export MR_LOCAL_PORT=$MR_EXTERNAL_PORT
1618         echo ""
1619 }
1620
1621 use_mr_https() {
1622         echo -e "Using $BOLD https $EBOLD towards MR"
1623         export MR_HTTPX="https"
1624         export MR_PORT=$MR_INTERNAL_SECURE_PORT
1625         export MR_LOCAL_PORT=$MR_EXTERNAL_SECURE_PORT
1626         echo ""
1627 }
1628
1629
1630 ################
1631 ### CR functions
1632 ################
1633
1634 # Start the Callback reciver in the simulator group
1635 # args: -
1636 # (Function for test scripts)
1637 start_cr() {
1638
1639         echo -e $BOLD"Starting Callback Receiver"$EBOLD
1640         __check_included_image 'CR'
1641         if [ $? -eq 1 ]; then
1642                 echo -e $RED"The Callback Receiver image has not been checked for this test run due to arg to the test script"$ERED
1643                 echo -e $RED"The Callback Receiver will not be started"$ERED
1644                 exit
1645         fi
1646         __start_container cr NODOCKERARGS $CR_APP_NAME $CR_EXTERNAL_PORT "/" "http"
1647
1648 }
1649
1650 use_cr_http() {
1651         echo -e "Using $BOLD http $EBOLD towards CR"
1652         export CR_HTTPX="http"
1653         export CR_PORT=$CR_INTERNAL_PORT
1654         export CR_LOCAL_PORT=$CR_EXTERNAL_PORT
1655         echo ""
1656 }
1657
1658 use_cr_https() {
1659         echo -e "Using $BOLD https $EBOLD towards CR"
1660         export CR_HTTPX="https"
1661         export CR_PORT=$CR_INTERNAL_SECURE_PORT
1662         export CR_LOCAL_PORT=$CR_EXTERNAL_SECURE_PORT
1663         echo ""
1664 }
1665
1666 ###########################
1667 ### Producer stub functions
1668 ###########################
1669
1670 # Start the Producer stub in the simulator group
1671 # args: -
1672 # (Function for test scripts)
1673 start_prod_stub() {
1674
1675         echo -e $BOLD"Starting Producer stub"$EBOLD
1676         __check_included_image 'PRODSTUB'
1677         if [ $? -eq 1 ]; then
1678                 echo -e $RED"The Producer stub image has not been checked for this test run due to arg to the test script"$ERED
1679                 echo -e $RED"The Producer stub will not be started"$ERED
1680                 exit
1681         fi
1682         __start_container prodstub NODOCKERARGS $PROD_STUB_APP_NAME $PROD_STUB_EXTERNAL_PORT "/" "http"
1683
1684 }
1685
1686 use_prod_stub_http() {
1687         echo -e "Using $BOLD http $EBOLD towards Producer stub"
1688         export PROD_STUB_HTTPX="http"
1689         export PROD_STUB_PORT=$PROD_STUB_INTERNAL_PORT
1690         export PROD_STUB_LOCAL_PORT=$PROD_STUB_EXTERNAL_PORT
1691         export PROD_STUB_LOCALHOST=$PROD_STUB_HTTPX"://localhost:"$PROD_STUB_LOCAL_PORT
1692         echo ""
1693 }
1694
1695 use_prod_stub_https() {
1696         echo -e "Using $BOLD https $EBOLD towards Producer stub"
1697         export PROD_STUB_HTTPX="https"
1698         export PROD_STUB_PORT=$PROD_STUB_INTERNAL_SECURE_PORT
1699         export PROD_STUB_LOCAL_PORT=$PROD_STUB_EXTERNAL_SECURE_PORT
1700         export PROD_STUB_LOCALHOST=$PROD_STUB_HTTPX"://localhost:"$PROD_STUB_LOCAL_PORT
1701         echo ""
1702 }
1703
1704 ###########################
1705 ### Policy Agents functions
1706 ###########################
1707
1708 # Use an agent on the local machine instead of container
1709 use_agent_stand_alone() {
1710         AGENT_STAND_ALONE=1
1711 }
1712
1713 # Start the policy agent
1714 # args: -
1715 # (Function for test scripts)
1716 start_policy_agent() {
1717
1718         echo -e $BOLD"Starting Policy Agent"$EBOLD
1719
1720         if [ $AGENT_STAND_ALONE -eq 0 ]; then
1721                 __check_included_image 'PA'
1722                 if [ $? -eq 1 ]; then
1723                         echo -e $RED"The Policy Agent image has not been checked for this test run due to arg to the test script"$ERED
1724                         echo -e $RED"The Policy Agent will not be started"$ERED
1725                         exit
1726                 fi
1727                 __start_container policy_agent NODOCKERARGS $POLICY_AGENT_APP_NAME $POLICY_AGENT_EXTERNAL_PORT "/status" "http"
1728         else
1729                 echo -e $RED"The consul config produced by this test script (filename '<fullpath-to-autotest-dir>.output<file-name>"$ERED
1730                 echo -e $RED"where the file name is the file in the consul_config_app command in this script) must be pointed out by the agent "$ERED
1731                 echo -e $RED"application.yaml"$ERED
1732                 echo -e $RED"The application jar may need to be built before continuing"$ERED
1733                 echo -e $RED"The agent shall now be running on port $POLICY_AGENT_EXTERNAL_PORT for http"$ERED
1734
1735                 read -p "<press any key to continue>"
1736                 __start_container policy_agent "STANDALONE" $POLICY_AGENT_APP_NAME $POLICY_AGENT_EXTERNAL_PORT "/status" "http"
1737         fi
1738
1739 }
1740
1741 # All calls to the agent will be directed to the agent REST interface from now on
1742 # args: -
1743 # (Function for test scripts)
1744 use_agent_rest_http() {
1745         echo -e "Using $BOLD http $EBOLD and $BOLD REST $EBOLD towards the agent"
1746         export ADAPTER=$RESTBASE
1747         echo ""
1748 }
1749
1750 # All calls to the agent will be directed to the agent REST interface from now on
1751 # args: -
1752 # (Function for test scripts)
1753 use_agent_rest_https() {
1754         echo -e "Using $BOLD https $EBOLD and $BOLD REST $EBOLD towards the agent"
1755         export ADAPTER=$RESTBASE_SECURE
1756         echo ""
1757         return 0
1758 }
1759
1760 # All calls to the agent will be directed to the agent dmaap interface over http from now on
1761 # args: -
1762 # (Function for test scripts)
1763 use_agent_dmaap_http() {
1764         echo -e "Using $BOLD http $EBOLD and $BOLD DMAAP $EBOLD towards the agent"
1765         export ADAPTER=$DMAAPBASE
1766         echo ""
1767         return 0
1768 }
1769
1770 # All calls to the agent will be directed to the agent dmaap interface over https from now on
1771 # args: -
1772 # (Function for test scripts)
1773 use_agent_dmaap_https() {
1774         echo -e "Using $BOLD https $EBOLD and $BOLD REST $EBOLD towards the agent"
1775         export ADAPTER=$DMAAPBASE_SECURE
1776         echo ""
1777         return 0
1778 }
1779
1780 # Turn on debug level tracing in the agent
1781 # args: -
1782 # (Function for test scripts)
1783 set_agent_debug() {
1784         echo -e $BOLD"Setting agent debug"$EBOLD
1785         actuator="/actuator/loggers/org.oransc.policyagent"
1786         if [[ $POLICY_AGENT_IMAGE = *"onap"* ]]; then
1787                 actuator="/actuator/loggers/org.onap.ccsdk.oran.a1policymanagementservice"
1788         fi
1789         curlString="$LOCALHOST$POLICY_AGENT_EXTERNAL_PORT$actuator -X POST  -H Content-Type:application/json -d {\"configuredLevel\":\"debug\"}"
1790         result=$(__do_curl "$curlString")
1791         if [ $? -ne 0 ]; then
1792                 __print_err "could not set debug mode" $@
1793                 ((RES_CONF_FAIL++))
1794                 return 1
1795         fi
1796         echo ""
1797         return 0
1798 }
1799
1800 # Turn on trace level tracing in the agent
1801 # args: -
1802 # (Function for test scripts)
1803 set_agent_trace() {
1804         echo -e $BOLD"Setting agent trace"$EBOLD
1805         actuator="/actuator/loggers/org.oransc.policyagent"
1806         if [[ $POLICY_AGENT_IMAGE = *"onap"* ]]; then
1807                 actuator="/actuator/loggers/org.onap.ccsdk.oran.a1policymanagementservice"
1808         fi
1809         curlString="$LOCALHOST$POLICY_AGENT_EXTERNAL_PORT$actuator -X POST  -H Content-Type:application/json -d {\"configuredLevel\":\"trace\"}"
1810         result=$(__do_curl "$curlString")
1811         if [ $? -ne 0 ]; then
1812                 __print_err "could not set trace mode" $@
1813                 ((RES_CONF_FAIL++))
1814                 return 1
1815         fi
1816         echo ""
1817         return 0
1818 }
1819
1820 # Perform curl retries when making direct call to the agent for the specified http response codes
1821 # Speace separated list of http response codes
1822 # args: [<response-code>]*
1823 use_agent_retries() {
1824         echo -e $BOLD"Do curl retries to the agent REST inteface for these response codes:$@"$EBOLD
1825         AGENT_RETRY_CODES=$@
1826         echo ""
1827         return
1828 }
1829
1830 ###########################
1831 ### ECS functions
1832 ###########################
1833
1834 # Start the ECS
1835 # args: -
1836 # (Function for test scripts)
1837 start_ecs() {
1838
1839         echo -e $BOLD"Starting ECS"$EBOLD
1840         __check_included_image 'ECS'
1841         if [ $? -eq 1 ]; then
1842                 echo -e $RED"The ECS image has not been checked for this test run due to arg to the test script"$ERED
1843                 echo -e $RED"ECS will not be started"$ERED
1844                 exit
1845         fi
1846         export ECS_CERT_MOUNT_DIR="./cert"
1847         __start_container ecs NODOCKERARGS $ECS_APP_NAME $ECS_EXTERNAL_PORT "/status" "http"
1848 }
1849
1850 # All calls to ECS will be directed to the ECS REST interface from now on
1851 # args: -
1852 # (Function for test scripts)
1853 use_ecs_rest_http() {
1854         echo -e "Using $BOLD http $EBOLD and $BOLD REST $EBOLD towards ECS"
1855         export ECS_ADAPTER=$ECS_RESTBASE
1856         echo ""
1857 }
1858
1859 # All calls to ECS will be directed to the ECS REST interface from now on
1860 # args: -
1861 # (Function for test scripts)
1862 use_ecs_rest_https() {
1863         echo -e "Using $BOLD https $EBOLD and $BOLD REST $EBOLD towards ECS"
1864         export ECS_ADAPTER=$ECS_RESTBASE_SECURE
1865         echo ""
1866         return 0
1867 }
1868
1869 # All calls to ECS will be directed to the ECS dmaap interface over http from now on
1870 # args: -
1871 # (Function for test scripts)
1872 use_ecs_dmaap_http() {
1873         echo -e "Using $BOLD http $EBOLD and $BOLD DMAAP $EBOLD towards ECS"
1874         export ECS_ADAPTER=$ECS_DMAAPBASE
1875         echo ""
1876         return 0
1877 }
1878
1879 # All calls to ECS will be directed to the ECS dmaap interface over https from now on
1880 # args: -
1881 # (Function for test scripts)
1882 use_ecs_dmaap_https() {
1883         echo -e "Using $BOLD https $EBOLD and $BOLD REST $EBOLD towards ECS"
1884         export ECS_ADAPTER=$ECS_DMAAPBASE_SECURE
1885         echo ""
1886         return 0
1887 }
1888
1889 # Turn on debug level tracing in ECS
1890 # args: -
1891 # (Function for test scripts)
1892 set_ecs_debug() {
1893         echo -e $BOLD"Setting ecs debug"$EBOLD
1894         curlString="$LOCALHOST$ECS_EXTERNAL_PORT/actuator/loggers/org.oransc.enrichment -X POST  -H Content-Type:application/json -d {\"configuredLevel\":\"debug\"}"
1895         result=$(__do_curl "$curlString")
1896         if [ $? -ne 0 ]; then
1897                 __print_err "Could not set debug mode" $@
1898                 ((RES_CONF_FAIL++))
1899                 return 1
1900         fi
1901         echo ""
1902         return 0
1903 }
1904
1905 # Turn on trace level tracing in ECS
1906 # args: -
1907 # (Function for test scripts)
1908 set_ecs_trace() {
1909         echo -e $BOLD"Setting ecs trace"$EBOLD
1910         curlString="$LOCALHOST$ECS_EXTERNAL_PORT/actuator/loggers/org.oransc.enrichment -X POST  -H Content-Type:application/json -d {\"configuredLevel\":\"trace\"}"
1911         result=$(__do_curl "$curlString")
1912         if [ $? -ne 0 ]; then
1913                 __print_err "Could not set trace mode" $@
1914                 ((RES_CONF_FAIL++))
1915                 return 1
1916         fi
1917         echo ""
1918         return 0
1919 }
1920
1921 # Perform curl retries when making direct call to ECS for the specified http response codes
1922 # Speace separated list of http response codes
1923 # args: [<response-code>]*
1924 use_agent_retries() {
1925         echo -e $BOLD"Do curl retries to the ECS REST inteface for these response codes:$@"$EBOLD
1926         ECS_AGENT_RETRY_CODES=$@
1927         echo ""
1928         return
1929 }
1930
1931 #################
1932 ### Log functions
1933 #################
1934
1935 # Check the agent logs for WARNINGs and ERRORs
1936 # args: -
1937 # (Function for test scripts)
1938
1939 check_policy_agent_logs() {
1940         __check_container_logs "Policy Agent" $POLICY_AGENT_APP_NAME $POLICY_AGENT_LOGPATH WARN ERR
1941 }
1942
1943 check_ecs_logs() {
1944         __check_container_logs "ECS" $ECS_APP_NAME $ECS_LOGPATH WARN ERR
1945 }
1946
1947 check_control_panel_logs() {
1948         __check_container_logs "Control Panel" $CONTROL_PANEL_APP_NAME $CONTROL_PANEL_LOGPATH WARN ERR
1949 }
1950
1951 check_sdnc_logs() {
1952         __check_container_logs "SDNC A1 Controller" $SDNC_APP_NAME $SDNC_KARAF_LOG WARN ERROR
1953 }
1954
1955 __check_container_logs() {
1956         dispname=$1
1957         appname=$2
1958         logpath=$3
1959         warning=$4
1960         error=$5
1961
1962         echo -e $BOLD"Checking $dispname container $appname log ($logpath) for WARNINGs and ERRORs"$EBOLD
1963
1964         #tmp=$(docker ps | grep $appname)
1965         tmp=$(docker ps -q --filter name=$appname) #get the container id
1966         if [ -z "$tmp" ]; then  #Only check logs for running Policy Agent apps
1967                 echo $dispname" is not running, no check made"
1968                 return
1969         fi
1970         foundentries="$(docker exec -t $tmp grep $warning $logpath | wc -l)"
1971         if [ $? -ne  0 ];then
1972                 echo "  Problem to search $appname log $logpath"
1973         else
1974                 if [ $foundentries -eq 0 ]; then
1975                         echo "  No WARN entries found in $appname log $logpath"
1976                 else
1977                         echo -e "  Found \033[1m"$foundentries"\033[0m WARN entries in $appname log $logpath"
1978                 fi
1979         fi
1980         foundentries="$(docker exec -t $tmp grep $error $logpath | wc -l)"
1981         if [ $? -ne  0 ];then
1982                 echo "  Problem to search $appname log $logpath"
1983         else
1984                 if [ $foundentries -eq 0 ]; then
1985                         echo "  No ERR entries found in $appname log $logpath"
1986                 else
1987                         echo -e $RED"  Found \033[1m"$foundentries"\033[0m"$RED" ERR entries in $appname log $logpath"$ERED
1988                 fi
1989         fi
1990         echo ""
1991 }
1992
1993 # Store all container logs and other logs in the log dir for the script
1994 # Logs are stored with a prefix in case logs should be stored several times during a test
1995 # args: <logfile-prefix>
1996 # (Function for test scripts)
1997 store_logs() {
1998         if [ $# != 1 ]; then
1999                 ((RES_CONF_FAIL++))
2000         __print_err "need one arg, <file-prefix>" $@
2001                 exit 1
2002         fi
2003         echo -e $BOLD"Storing all container logs using prefix: "$1$EBOLD
2004
2005         docker stats --no-stream > $TESTLOGS/$ATC/$1_docker_stats.log 2>&1
2006
2007         __check_included_image 'CONSUL'
2008         if [ $? -eq 0 ]; then
2009                 docker logs $CONSUL_APP_NAME > $TESTLOGS/$ATC/$1_consul.log 2>&1
2010         fi
2011
2012         __check_included_image 'CBS'
2013         if [ $? -eq 0 ]; then
2014                 docker logs $CBS_APP_NAME > $TESTLOGS/$ATC/$1_cbs.log 2>&1
2015                 body="$(__do_curl $LOCALHOST$CBS_EXTERNAL_PORT/service_component_all/$POLICY_AGENT_APP_NAME)"
2016                 echo "$body" > $TESTLOGS/$ATC/$1_consul_config.json 2>&1
2017         fi
2018
2019         __check_included_image 'PA'
2020         if [ $? -eq 0 ]; then
2021                 docker logs $POLICY_AGENT_APP_NAME > $TESTLOGS/$ATC/$1_policy-agent.log 2>&1
2022         fi
2023
2024         __check_included_image 'ECS'
2025         if [ $? -eq 0 ]; then
2026                 docker logs $ECS_APP_NAME > $TESTLOGS/$ATC/$1_ecs.log 2>&1
2027         fi
2028
2029         __check_included_image 'CP'
2030         if [ $? -eq 0 ]; then
2031                 docker logs $CONTROL_PANEL_APP_NAME > $TESTLOGS/$ATC/$1_control-panel.log 2>&1
2032         fi
2033
2034         __check_included_image 'MR'
2035         if [ $? -eq 0 ]; then
2036                 docker logs $MR_APP_NAME > $TESTLOGS/$ATC/$1_mr.log 2>&1
2037         fi
2038
2039         __check_included_image 'CR'
2040         if [ $? -eq 0 ]; then
2041                 docker logs $CR_APP_NAME > $TESTLOGS/$ATC/$1_cr.log 2>&1
2042         fi
2043
2044         cp .httplog_${ATC}.txt $TESTLOGS/$ATC/$1_httplog_${ATC}.txt 2>&1
2045
2046         __check_included_image 'SDNC'
2047         if [ $? -eq 0 ]; then
2048                 docker exec -t $SDNC_APP_NAME cat $SDNC_KARAF_LOG> $TESTLOGS/$ATC/$1_SDNC_karaf.log 2>&1
2049         fi
2050
2051         __check_included_image 'RICSIM'
2052         if [ $? -eq 0 ]; then
2053                 rics=$(docker ps -f "name=$RIC_SIM_PREFIX" --format "{{.Names}}")
2054                 for ric in $rics; do
2055                         docker logs $ric > $TESTLOGS/$ATC/$1_$ric.log 2>&1
2056                 done
2057         fi
2058
2059         __check_included_image 'PRODSTUB'
2060         if [ $? -eq 0 ]; then
2061                 docker logs $PROD_STUB_APP_NAME > $TESTLOGS/$ATC/$1_prodstub.log 2>&1
2062         fi
2063
2064         echo ""
2065 }
2066
2067 ###############
2068 ## Generic curl
2069 ###############
2070 # Generic curl function, assumes all 200-codes are ok
2071 # args: <valid-curl-args-including full url>
2072 # returns: <returned response (without respose code)>  or "<no-response-from-server>" or "<not found, <http-code>>""
2073 # returns: The return code is 0 for ok and 1 for not ok
2074 __do_curl() {
2075         echo ${FUNCNAME[1]} "line: "${BASH_LINENO[1]} >> $HTTPLOG
2076         curlString="curl -skw %{http_code} $@"
2077         echo " CMD: $curlString" >> $HTTPLOG
2078         res=$($curlString)
2079         echo " RESP: $res" >> $HTTPLOG
2080         http_code="${res:${#res}-3}"
2081         if [ ${#res} -eq 3 ]; then
2082                 if [ $http_code -lt 200 ] || [ $http_code -gt 299 ]; then
2083                         echo "<no-response-from-server>"
2084                         return 1
2085                 else
2086                         echo "X2" >> $HTTPLOG
2087                         return 0
2088                 fi
2089         else
2090                 if [ $http_code -lt 200 ] || [ $http_code -gt 299 ]; then
2091                         echo "<not found, resp:${http_code}>"
2092                         return 1
2093                 fi
2094                 if [ $# -eq 2 ]; then
2095                         echo "${res:0:${#res}-3}" | xargs
2096                 else
2097                         echo "${res:0:${#res}-3}"
2098                 fi
2099
2100                 return 0
2101         fi
2102 }
2103
2104 #######################################
2105 ### Basic helper function for test cases
2106 #######################################
2107
2108 # Test a simulator container variable value towards target value using an condition operator with an optional timeout.
2109 # Arg: <simulator-name> <host> <variable-name> <condition-operator> <target-value>  - This test is done
2110 # immediately and sets pass or fail depending on the result of comparing variable and target using the operator.
2111 # Arg: <simulator-name> <host> <variable-name> <condition-operator> <target-value> <timeout>  - This test waits up to the timeout
2112 # before setting pass or fail depending on the result of comparing variable and target using the operator.
2113 # 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.
2114 # Not to be called from test script.
2115
2116 __var_test() {
2117         checkjsonarraycount=0
2118
2119         if [ $# -eq 6 ]; then
2120                 if [[ $3 == "json:"* ]]; then
2121                         checkjsonarraycount=1
2122                 fi
2123
2124                 echo -e $BOLD"TEST(${BASH_LINENO[1]}): ${1}, ${3} ${4} ${5} within ${6} seconds"$EBOLD
2125                 ((RES_TEST++))
2126                 start=$SECONDS
2127                 ctr=0
2128                 for (( ; ; )); do
2129                         if [ $checkjsonarraycount -eq 0 ]; then
2130                                 result="$(__do_curl $2$3)"
2131                                 retcode=$?
2132                                 result=${result//[[:blank:]]/} #Strip blanks
2133                         else
2134                                 path=${3:5}
2135                                 result="$(__do_curl $2$path)"
2136                                 retcode=$?
2137                                 echo "$result" > ./tmp/.tmp.curl.json
2138                                 result=$(python3 ../common/count_json_elements.py "./tmp/.tmp.curl.json")
2139                         fi
2140                         duration=$((SECONDS-start))
2141                         echo -ne " Result=${result} after ${duration} seconds${SAMELINE}"
2142                         let ctr=ctr+1
2143                         if [ $retcode -ne 0 ]; then
2144                                 if [ $duration -gt $6 ]; then
2145                                         ((RES_FAIL++))
2146                                         echo -e $RED" FAIL${ERED} - ${3} ${4} ${5} not reached in ${6} seconds, result = ${result}"
2147                                         __check_stop_at_error
2148                                         return
2149                                 fi
2150                         elif [ $4 = "=" ] && [ "$result" -eq $5 ]; then
2151                                 ((RES_PASS++))
2152                                 echo -e " Result=${result} after ${duration} seconds${SAMELINE}"
2153                                 echo -e $GREEN" PASS${EGREEN} - Result=${result} after ${duration} seconds"
2154                                 return
2155                         elif [ $4 = ">" ] && [ "$result" -gt $5 ]; then
2156                                 ((RES_PASS++))
2157                                 echo -e " Result=${result} after ${duration} seconds${SAMELINE}"
2158                                 echo -e $GREEN" PASS${EGREEN} - Result=${result} after ${duration} seconds"
2159                                 return
2160                         elif [ $4 = "<" ] && [ "$result" -lt $5 ]; then
2161                                 ((RES_PASS++))
2162                                 echo -e " Result=${result} after ${duration} seconds${SAMELINE}"
2163                                 echo -e $GREEN" PASS${EGREEN} - Result=${result} after ${duration} seconds"
2164                                 return
2165                         elif [ $4 = "contain_str" ] && [[ $result =~ $5 ]]; then
2166                                 ((RES_PASS++))
2167                                 echo -e " Result=${result} after ${duration} seconds${SAMELINE}"
2168                                 echo -e $GREEN" PASS${EGREEN} - Result=${result} after ${duration} seconds"
2169                                 return
2170                         else
2171                                 if [ $duration -gt $6 ]; then
2172                                         ((RES_FAIL++))
2173                                         echo -e $RED" FAIL${ERED} - ${3} ${4} ${5} not reached in ${6} seconds, result = ${result}"
2174                                         __check_stop_at_error
2175                                         return
2176                                 fi
2177                         fi
2178                         sleep 1
2179                 done
2180         elif [ $# -eq 5 ]; then
2181                 if [[ $3 == "json:"* ]]; then
2182                         checkjsonarraycount=1
2183                 fi
2184
2185                 echo -e $BOLD"TEST(${BASH_LINENO[1]}): ${1}, ${3} ${4} ${5}"$EBOLD
2186                 ((RES_TEST++))
2187                 if [ $checkjsonarraycount -eq 0 ]; then
2188                         result="$(__do_curl $2$3)"
2189                         retcode=$?
2190                         result=${result//[[:blank:]]/} #Strip blanks
2191                 else
2192                         path=${3:5}
2193                         result="$(__do_curl $2$path)"
2194                         retcode=$?
2195                         echo "$result" > ./tmp/.tmp.curl.json
2196                         result=$(python3 ../common/count_json_elements.py "./tmp/.tmp.curl.json")
2197                 fi
2198                 if [ $retcode -ne 0 ]; then
2199                         ((RES_FAIL++))
2200                         echo -e $RED" FAIL ${ERED}- ${3} ${4} ${5} not reached, result = ${result}"
2201                         __check_stop_at_error
2202                 elif [ $4 = "=" ] && [ "$result" -eq $5 ]; then
2203                         ((RES_PASS++))
2204                         echo -e $GREEN" PASS${EGREEN} - Result=${result}"
2205                 elif [ $4 = ">" ] && [ "$result" -gt $5 ]; then
2206                         ((RES_PASS++))
2207                         echo -e $GREEN" PASS${EGREEN} - Result=${result}"
2208                 elif [ $4 = "<" ] && [ "$result" -lt $5 ]; then
2209                         ((RES_PASS++))
2210                         echo -e $GREEN" PASS${EGREEN} - Result=${result}"
2211                 elif [ $4 = "contain_str" ] && [[ $result =~ $5 ]]; then
2212                         ((RES_PASS++))
2213                         echo -e $GREEN" PASS${EGREEN} - Result=${result}"
2214                 else
2215                         ((RES_FAIL++))
2216                         echo -e $RED" FAIL${ERED} - ${3} ${4} ${5} not reached, result = ${result}"
2217                         __check_stop_at_error
2218                 fi
2219         else
2220                 echo "Wrong args to __var_test, needs five or six args: <simulator-name> <host> <variable-name> <condition-operator> <target-value> [ <timeout> ]"
2221                 echo "Got:" $@
2222                 exit 1
2223         fi
2224 }
2225
2226
2227 ### Generic test cases for varaible checking
2228
2229 # Tests if a variable value in the CR is equal to a target value and and optional timeout.
2230 # Arg: <variable-name> <target-value> - This test set pass or fail depending on if the variable is
2231 # equal to the target or not.
2232 # Arg: <variable-name> <target-value> <timeout-in-sec>  - This test waits up to the timeout seconds
2233 # before setting pass or fail depending on if the variable value becomes equal to the target
2234 # value or not.
2235 # (Function for test scripts)
2236 cr_equal() {
2237         if [ $# -eq 2 ] || [ $# -eq 3 ]; then
2238                 __var_test "CR" "$LOCALHOST$CR_EXTERNAL_PORT/counter/" $1 "=" $2 $3
2239         else
2240                 ((RES_CONF_FAIL++))
2241                 __print_err "Wrong args to cr_equal, needs two or three args: <sim-param> <target-value> [ timeout ]" $@
2242         fi
2243 }
2244
2245 # Tests if a variable value in the MR stub is equal to a target value and and optional timeout.
2246 # Arg: <variable-name> <target-value> - This test set pass or fail depending on if the variable is
2247 # equal to the target or not.
2248 # Arg: <variable-name> <target-value> <timeout-in-sec>  - This test waits up to the timeout seconds
2249 # before setting pass or fail depending on if the variable value becomes equal to the target
2250 # value or not.
2251 # (Function for test scripts)
2252 mr_equal() {
2253         if [ $# -eq 2 ] || [ $# -eq 3 ]; then
2254                 __var_test "MR" "$LOCALHOST$MR_EXTERNAL_PORT/counter/" $1 "=" $2 $3
2255         else
2256                 ((RES_CONF_FAIL++))
2257                 __print_err "Wrong args to mr_equal, needs two or three args: <sim-param> <target-value> [ timeout ]" $@
2258         fi
2259 }
2260
2261 # Tests if a variable value in the MR stub is greater than a target value and and optional timeout.
2262 # Arg: <variable-name> <target-value> - This test set pass or fail depending on if the variable is
2263 # greater than the target or not.
2264 # Arg: <variable-name> <target-value> <timeout-in-sec>  - This test waits up to the timeout seconds
2265 # before setting pass or fail depending on if the variable value becomes greater than the target
2266 # value or not.
2267 # (Function for test scripts)
2268 mr_greater() {
2269         if [ $# -eq 2 ] || [ $# -eq 3 ]; then
2270                 __var_test "MR" "$LOCALHOST$MR_EXTERNAL_PORT/counter/" $1 ">" $2 $3
2271         else
2272                 ((RES_CONF_FAIL++))
2273                 __print_err "Wrong args to mr_greater, needs two or three args: <sim-param> <target-value> [ timeout ]" $@
2274         fi
2275 }
2276
2277 # Read a variable value from MR sim and send to stdout. Arg: <variable-name>
2278 mr_read() {
2279         echo "$(__do_curl $LOCALHOST$MR_EXTERNAL_PORT/counter/$1)"
2280 }
2281
2282 # Print a variable value from the MR stub.
2283 # arg: <variable-name>
2284 # (Function for test scripts)
2285 mr_print() {
2286         if [ $# != 1 ]; then
2287                 ((RES_CONF_FAIL++))
2288         __print_err "need one arg, <mr-param>" $@
2289                 exit 1
2290         fi
2291         echo -e $BOLD"INFO(${BASH_LINENO[0]}): mrstub, $1 = $(__do_curl $LOCALHOST$MR_EXTERNAL_PORT/counter/$1)"$EBOLD
2292 }