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