Clean autotest folder
[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]
22
23 #Formatting for 'echo' cmd
24 BOLD="\033[1m"
25 EBOLD="\033[0m"
26 RED="\033[31m\033[1m"
27 ERED="\033[0m"
28 GREEN="\033[32m\033[1m"
29 EGREEN="\033[0m"
30 YELLOW="\033[33m\033[1m"
31 EYELLOW="\033[0m"
32
33 # Just resetting any previous echo formatting...
34 echo -ne $EBOLD$ERED$EGREEN
35
36 # source test environment variables
37 . ../common/test_env.sh
38
39 echo "Test case started as: ${BASH_SOURCE[$i+1]} "$@
40
41 #Vars for A1 interface version and container count
42 G1_A1_VERSION=""
43 G2_A1_VERSION=""
44 G3_A1_VERSION=""
45 G1_COUNT=0
46 G2_COUNT=0
47 G3_COUNT=0
48
49 #Localhost constant
50 LOCALHOST="http://localhost:"
51
52 # Make curl retries for http response codes set in this env var, space separated list of codes
53 AGENT_RETRY_CODES=""
54
55 # Var to hold 'auto' in case containers shall be stopped when test case ends
56 AUTO_CLEAN=""
57
58 # Set a description string for the test case
59 if [ -z "$TC_ONELINE_DESCR" ]; then
60         TC_ONELINE_DESCR="<no-description>"
61         echo "No test case description found, TC_ONELINE_DESCR should be set on in the test script , using "$TC_ONELINE_DESCR
62 fi
63
64 # Counter for test suites
65 if [ -f .tmp_tcsuite_ctr ]; then
66         tmpval=$(< .tmp_tcsuite_ctr)
67         ((tmpval++))
68         echo $tmpval > .tmp_tcsuite_ctr
69 fi
70
71 # Create a test case id, ATC (Auto Test Case), from the name of the test case script.
72 # FTC1.sh -> ATC == FTC1
73 ATC=$(basename "${BASH_SOURCE[$i+1]}" .sh)
74
75 # Create the logs dir if not already created in the current dir
76 if [ ! -d "logs" ]; then
77     mkdir logs
78 fi
79 TESTLOGS=$PWD/logs
80
81 # Create a http message log for this testcase
82 HTTPLOG=$PWD"/.httplog_"$ATC".txt"
83 echo "" > $HTTPLOG
84
85 # Create a log dir for the test case
86 mkdir -p $TESTLOGS/$ATC
87
88 # Clear the log dir for the test case
89 rm $TESTLOGS/$ATC/*.log &> /dev/null
90 rm $TESTLOGS/$ATC/*.txt &> /dev/null
91 rm $TESTLOGS/$ATC/*.json &> /dev/null
92
93 # Log all output from the test case to a TC log
94 TCLOG=$TESTLOGS/$ATC/TC.log
95 exec &>  >(tee ${TCLOG})
96
97 #Variables for counting tests as well as passed and failed tests
98 RES_TEST=0
99 RES_PASS=0
100 RES_FAIL=0
101 RES_CONF_FAIL=0
102
103 #Var for measuring execution time
104 TCTEST_START=$SECONDS
105
106 echo "-------------------------------------------------------------------------------------------------"
107 echo "-----------------------------------      Test case: "$ATC
108 echo "-----------------------------------      Started:   "$(date)
109 echo "-------------------------------------------------------------------------------------------------"
110 echo "-- Description: "$TC_ONELINE_DESCR
111 echo "-------------------------------------------------------------------------------------------------"
112 echo "-----------------------------------      Test case setup      -----------------------------------"
113
114 echo -e $BOLD"Checking configured image setting for this test case"$EBOLD
115
116 #Temp var to check for image variable name errors
117 IMAGE_ERR=0
118 #Create a file with image info for later printing as a table
119 image_list_file=".image-list"
120 echo -e " Container\tImage\ttag" > $image_list_file
121
122 # Check if image env var is set and if so export the env var with image to use (used by docker compose files)
123 # arg: <image name> <script start-arg> <target-variable-name> <image-variable-name> <image-tag-variable-name>
124 __check_image_var() {
125         if [ $# -ne 5 ]; then
126                 echo "Expected arg: <image name> <script start-arg> <target-variable-name> <image-variable-name> <image-tag-variable-name>"
127                 ((IMAGE_ERR++))
128                 return
129         fi
130         tmp=${1}"\t"
131         #Create var from the input var names
132         image="${!4}"
133         tag="${!5}"
134
135         if [ -z $image ]; then
136                 echo -e $RED"\$"$4" not set in test_env"$ERED
137                 ((IMAGE_ERR++))
138                 echo ""
139                 tmp=$tmp"<no-image>\t"
140         else
141                 tmp=$tmp$image"\t"
142         fi
143         if [ -z $tag ]; then
144                 echo -e $RED"\$"$5" not set in test_env"$ERED
145                 ((IMAGE_ERR++))
146                 echo ""
147                 tmp=$tmp"<no-tag>\t"
148         else
149                 tmp=$tmp$tag
150         fi
151         echo -e "$tmp" >> $image_list_file
152         #Export the env var
153         export "${3}"=$image":"$tag
154
155         #echo " Configured image for ${1} (script start arg=${2}): "$image":"$tag
156 }
157
158 # Check that image env setting are available
159 echo ""
160 if [ $# -lt 1 ] || [ $# -gt 2 ]; then
161         echo "Expected arg: local|remote|remote-remove [auto-clean]"
162         exit 1
163 elif [ $1 == "local" ]; then
164
165         #Local agent image
166         __check_image_var " Policy Agent" $1 "POLICY_AGENT_IMAGE" "POLICY_AGENT_LOCAL_IMAGE" "POLICY_AGENT_LOCAL_IMAGE_TAG"
167
168         #Local Control Panel image
169         __check_image_var " Control Panel" $1 "CONTROL_PANEL_IMAGE" "CONTROL_PANEL_LOCAL_IMAGE" "CONTROL_PANEL_LOCAL_IMAGE_TAG"
170
171         #Local SNDC image
172         __check_image_var " SDNC A1 Controller" $1 "SDNC_A1_CONTROLLER_IMAGE" "SDNC_A1_CONTROLLER_LOCAL_IMAGE" "SDNC_A1_CONTROLLER_LOCAL_IMAGE_TAG"
173
174         #Local ric sim image
175         __check_image_var " RIC Simulator" $1 "RIC_SIM_IMAGE" "RIC_SIM_LOCAL_IMAGE" "RIC_SIM_LOCAL_IMAGE_TAG"
176
177 elif [ $1 == "remote" ] || [ $1 == "remote-remove" ]; then
178
179         #Remote agent image
180         __check_image_var " Policy Agent" $1 "POLICY_AGENT_IMAGE" "POLICY_AGENT_REMOTE_IMAGE" "POLICY_AGENT_REMOTE_IMAGE_TAG"
181
182         #Remote Control Panel image
183         __check_image_var " Control Panel" $1 "CONTROL_PANEL_IMAGE" "CONTROL_PANEL_REMOTE_IMAGE" "CONTROL_PANEL_REMOTE_IMAGE_TAG"
184
185         #Remote SDNC image
186         __check_image_var " SDNC A1 Controller" $1 "SDNC_A1_CONTROLLER_IMAGE" "SDNC_A1_CONTROLLER_REMOTE_IMAGE" "SDNC_A1_CONTROLLER_REMOTE_IMAGE_TAG"
187
188         #Remote ric sim image
189         __check_image_var " RIC Simulator" $1 "RIC_SIM_IMAGE" "RIC_SIM_REMOTE_IMAGE" "RIC_SIM_REMOTE_IMAGE_TAG"
190
191 else
192         echo "Expected arg: local|remote|remote-remove [auto-clean]"
193         exit 1
194 fi
195
196 if [ $# -eq 2 ]; then
197         if [ $2 == "auto-clean" ]; then
198                 echo "Stting automatic cleaning of container when test case ends"
199                 AUTO_CLEAN="auto"
200         else
201                 echo "Expected arg: local|remote|remote-remove [auto-clean]"
202                 exit 1
203         fi
204 fi
205
206 # These images are not built as part of this project official images, just check that env vars are set correctly
207 __check_image_var " Message Router" $1 "MRSTUB_IMAGE" "MRSTUB_LOCAL_IMAGE" "MRSTUB_LOCAL_IMAGE_TAG"
208 __check_image_var " Callback Receiver" $1 "CR_IMAGE" "CR_LOCAL_IMAGE" "CR_LOCAL_IMAGE_TAG"
209 __check_image_var " Consul" $1 "CONSUL_IMAGE" "CONSUL_REMOTE_IMAGE" "CONSUL_REMOTE_IMAGE_TAG"
210 __check_image_var " CBS" $1 "CBS_IMAGE" "CBS_REMOTE_IMAGE" "CBS_REMOTE_IMAGE_TAG"
211 __check_image_var " SDNC DB" $1 "SDNC_DB_IMAGE" "SDNC_DB_REMOTE_IMAGE" "SDNC_DB_REMOTE_IMAGE_TAG"
212
213 #Errors in image setting - exit
214 if [ $IMAGE_ERR -ne 0 ]; then
215         exit 1
216 fi
217
218 #Print a tables of the image settings
219 echo -e $BOLD"Images configured for start arg: "$1 $EBOLD
220 column -t -s $'\t' $image_list_file
221
222 echo ""
223
224
225 #Set the SIM_GROUP var
226 echo -e $BOLD"Setting var to main dir of all container/simulator scripts"$EBOLD
227 if [ -z "$SIM_GROUP" ]; then
228         SIM_GROUP=$PWD/../simulator-group
229         if [ ! -d  $SIM_GROUP ]; then
230                 echo "Trying to set env var SIM_GROUP to dir 'simulator-group' in the nontrtric repo, but failed."
231                 echo -e $RED"Please set the SIM_GROUP manually in the test_env.sh"$ERED
232                 exit 1
233         else
234                 echo " SIM_GROUP auto set to: " $SIM_GROUP
235         fi
236 elif [ $SIM_GROUP = *simulator_group ]; then
237         echo -e $RED"Env var SIM_GROUP does not seem to point to dir 'simulator-group' in the repo, check common/test_env.sh"$ERED
238         exit 1
239 else
240         echo " SIM_GROUP env var already set to: " $SIM_GROUP
241 fi
242
243 echo ""
244
245 #Temp var to check for image pull errors
246 IMAGE_ERR=0
247
248 #Function to check if image exist and stop+remove the container+pull new images as needed
249 #args <script-start-arg> <descriptive-image-name> <container-base-name> <image-with-tag>
250 __check_and_pull_image() {
251
252         echo -e " Checking $BOLD$2$EBOLD container(s) with basename: $BOLD$3$EBOLD using image: $BOLD$4$EBOLD"
253         format_string="\"{{.Repository}}\\t{{.Tag}}\\t{{.CreatedSince}}\\t{{.Size}}\""
254         tmp_im=$(docker images --format $format_string ${4})
255
256         if [ $1 == "local" ]; then
257                 if [ -z "$tmp_im" ]; then
258                         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
259                         ((IMAGE_ERR++))
260                         return 1
261                 else
262                         echo -e "  "$2" (local image): \033[1m"$4"\033[0m "$GREEN"OK"$EGREEN
263                 fi
264         elif [ $1 == "remote" ] || [ $1 == "remote-remove" ]; then
265                 if [ $1 == "remote-remove" ]; then
266                         echo -ne "  Attempt to stop and remove container(s), if running - \033[0K\r"
267                         tmp="$(docker ps -aq --filter name=${3})"
268                         if [ $? -eq 0 ] && [ ! -z "$tmp" ]; then
269                                 docker stop $tmp &> /dev/null
270                                 if [ $? -ne 0 ]; then
271                                         ((IMAGE_ERR++))
272                                         echo ""
273                                         echo -e $RED"  Container(s) could not be stopped - try manual stopping the container(s)"$ERED
274                                         return 1
275                                 fi
276                         fi
277                         echo -ne "  Attempt to stop and remove container(s), if running - "$GREEN"stopped"$EGREEN"\033[0K\r"
278                         tmp="$(docker ps -aq --filter name=${3})" &> /dev/null
279                         if [ $? -eq 0 ] && [ ! -z "$tmp" ]; then
280                                 docker rm $tmp &> /dev/null
281                                 if [ $? -ne 0 ]; then
282                                         ((IMAGE_ERR++))
283                                         echo ""
284                                         echo -e $RED"  Container(s) could not be removed - try manual removal of the container(s)"$ERED
285                                         return 1
286                                 fi
287                         fi
288                         echo -e "  Attempt to stop and remove container(s), if running - "$GREEN"stopped removed"$EGREEN
289                         echo -ne "  Removing image - \033[0K\r"
290                         tmp="$(docker images -q ${4})" &> /dev/null
291                         if [ $? -eq 0 ] && [ ! -z "$tmp" ]; then
292                                 docker rmi $4 &> /dev/null
293                                 if [ $? -ne 0 ]; then
294                                         ((IMAGE_ERR++))
295                                         echo ""
296                                         echo -e $RED"  Image could not be removed - try manual removal of the image"$ERED
297                                         return 1
298                                 fi
299                                 echo -e "  Removing image - "$GREEN"removed"$EGREEN
300                         else
301                                 echo -e "  Removing image - "$GREEN"image not in repository"$EGREEN
302                         fi
303                         tmp_im=""
304                 fi
305                 if [ -z "$tmp_im" ]; then
306                         echo -ne "  Pulling image\033[0K\r"
307                         docker pull $4   > /dev/null
308                         tmp_im=$(docker images ${4} | grep -v REPOSITORY)
309                         if [ -z "$tmp_im" ]; then
310                                 echo ""
311                                 echo -e "  Pulling image -$RED could not be pulled"$ERED
312                                 ((IMAGE_ERR++))
313                                 return 1
314                         fi
315                         echo -e "  Pulling image -$GREEN Pulled $EGREEN"
316                 else
317                         echo -e "  Pulling image -$GREEN OK $EGREEN(exists in local repository)"
318                 fi
319         fi
320         return 0
321 }
322
323
324 echo -e $BOLD"Pulling configured images, if needed"$EBOLD
325
326 app="Policy Agent";             __check_and_pull_image $1 "$app" $POLICY_AGENT_APP_NAME $POLICY_AGENT_IMAGE
327 app="Non-RT RIC Control Panel"; __check_and_pull_image $1 "$app" $CONTROL_PANEL_APP_NAME $CONTROL_PANEL_IMAGE
328 app="SDNC A1 Controller";       __check_and_pull_image $1 "$app" $SDNC_APP_NAME $SDNC_A1_CONTROLLER_IMAGE
329 app="Near-RT RIC Simulator";    __check_and_pull_image $1 "$app" $RIC_SIM_PREFIX"_"$RIC_SIM_BASE $RIC_SIM_IMAGE
330
331 app="Consul";                   __check_and_pull_image $1 "$app" $CONSUL_APP_NAME $CONSUL_IMAGE
332 app="CBS";                      __check_and_pull_image $1 "$app" $CBS_APP_NAME $CBS_IMAGE
333 app="SDNC DB";                  __check_and_pull_image $1 "$app" $SDNC_APP_NAME $SDNC_DB_IMAGE
334
335 # MR stub image not checked, will be built by this script - only local image
336 # CR stub image not checked, will be built by this script - only local image
337
338
339 #Errors in image setting - exit
340 if [ $IMAGE_ERR -ne 0 ]; then
341         echo ""
342         echo "#################################################################################################"
343         echo -e $RED"One or more images could not be pulled or containers using the images could not be stopped/removed"$ERED
344         echo "#################################################################################################"
345         echo ""
346         exit 1
347 fi
348
349 echo ""
350
351 echo -e $BOLD"Building images needed for test"$EBOLD
352
353 curdir=$PWD
354 cd $curdir
355 cd ../mrstub
356 echo " Building mrstub image: mrstub:latest"
357 docker build -t mrstub . &> /dev/null
358 if [ $? -eq 0 ]; then
359         echo -e  $GREEN" Build Ok"$EGREEN
360 else
361         echo -e $RED" Build Failed"$ERED
362         ((RES_CONF_FAIL++))
363 fi
364 cd $curdir
365
366 cd ../cr
367 echo " Building Callback Receiver image: callback-receiver:latest"
368 docker build -t callback-receiver . &> /dev/null
369 if [ $? -eq 0 ]; then
370         echo -e  $GREEN" Build Ok"$EGREEN
371 else
372         echo -e $RED" Build Failed"$ERED
373         ((RES_CONF_FAIL++))
374 fi
375 cd $curdir
376
377 echo ""
378
379 # Create a table of the images used in the script
380 echo -e $BOLD"Local docker registry images used in the this test script"$EBOLD
381
382 docker_tmp_file=.docker-images-table
383 format_string="{{.Repository}}\\t{{.Tag}}\\t{{.CreatedSince}}\\t{{.Size}}"
384 echo -e " Application\tRepository\tTag\tCreated Since\tSize" > $docker_tmp_file
385 echo -e " Policy Agent\t$(docker images --format $format_string $POLICY_AGENT_IMAGE)" >>   $docker_tmp_file
386 echo -e " Control Panel\t$(docker images --format $format_string $CONTROL_PANEL_IMAGE)" >>   $docker_tmp_file
387 echo -e " SDNC A1 Controller\t$(docker images --format $format_string $SDNC_A1_CONTROLLER_IMAGE)" >>   $docker_tmp_file
388 echo -e " RIC Simulator\t$(docker images --format $format_string $RIC_SIM_IMAGE)" >>   $docker_tmp_file
389 echo -e " Message Router\t$(docker images --format $format_string $MRSTUB_IMAGE)" >>   $docker_tmp_file
390 echo -e " Callback Receiver\t$(docker images --format $format_string $CR_IMAGE)" >>   $docker_tmp_file
391 echo -e " Consul\t$(docker images --format $format_string $CONSUL_IMAGE)" >>   $docker_tmp_file
392 echo -e " CBS\t$(docker images --format $format_string $CBS_IMAGE)" >>   $docker_tmp_file
393 echo -e " SDNC DB\t$(docker images --format $format_string $SDNC_DB_IMAGE)" >>   $docker_tmp_file
394
395 column -t -s $'\t' $docker_tmp_file
396
397 echo ""
398
399 echo -e $BOLD"======================================================="$EBOLD
400 echo -e $BOLD"== Common test setup completed -  test script begins =="$EBOLD
401 echo -e $BOLD"======================================================="$EBOLD
402 echo ""
403
404 # Function to print the test result, shall be the last cmd in a test script
405 # args: -
406 # (Function for test scripts)
407 print_result() {
408
409         TCTEST_END=$SECONDS
410         duration=$((TCTEST_END-TCTEST_START))
411
412         echo "-------------------------------------------------------------------------------------------------"
413         echo "-------------------------------------     Test case: "$ATC
414         echo "-------------------------------------     Ended:     "$(date)
415         echo "-------------------------------------------------------------------------------------------------"
416         echo "-- Description: "$TC_ONELINE_DESCR
417         echo "-- Execution time: " $duration " seconds"
418         echo "-------------------------------------------------------------------------------------------------"
419         echo "-------------------------------------     RESULTS"
420         echo ""
421
422
423         total=$((RES_PASS+RES_FAIL))
424         if [ $RES_TEST -eq 0 ]; then
425                 echo -e "\033[1mNo tests seem to have been executed. Check the script....\033[0m"
426                 echo -e "\033[31m\033[1m ___  ___ ___ ___ ___ _____   ___ _   ___ _   _   _ ___ ___ \033[0m"
427                 echo -e "\033[31m\033[1m/ __|/ __| _ \_ _| _ \_   _| | __/_\ |_ _| | | | | | _ \ __|\033[0m"
428                 echo -e "\033[31m\033[1m\__ \ (__|   /| ||  _/ | |   | _/ _ \ | || |_| |_| |   / _| \033[0m"
429                 echo -e "\033[31m\033[1m|___/\___|_|_\___|_|   |_|   |_/_/ \_\___|____\___/|_|_\___|\033[0m"
430         elif [ $total != $RES_TEST ]; then
431                 echo -e "\033[1mTotal number of tests does not match the sum of passed and failed tests. Check the script....\033[0m"
432                 echo -e "\033[31m\033[1m ___  ___ ___ ___ ___ _____   ___ _   ___ _   _   _ ___ ___ \033[0m"
433                 echo -e "\033[31m\033[1m/ __|/ __| _ \_ _| _ \_   _| | __/_\ |_ _| | | | | | _ \ __|\033[0m"
434                 echo -e "\033[31m\033[1m\__ \ (__|   /| ||  _/ | |   | _/ _ \ | || |_| |_| |   / _| \033[0m"
435                 echo -e "\033[31m\033[1m|___/\___|_|_\___|_|   |_|   |_/_/ \_\___|____\___/|_|_\___|\033[0m"
436         elif [ $RES_CONF_FAIL -ne 0 ]; then
437                 echo -e "\033[1mOne or more configure regest has failed. Check the script log....\033[0m"
438                 echo -e "\033[31m\033[1m ___  ___ ___ ___ ___ _____   ___ _   ___ _   _   _ ___ ___ \033[0m"
439                 echo -e "\033[31m\033[1m/ __|/ __| _ \_ _| _ \_   _| | __/_\ |_ _| | | | | | _ \ __|\033[0m"
440                 echo -e "\033[31m\033[1m\__ \ (__|   /| ||  _/ | |   | _/ _ \ | || |_| |_| |   / _| \033[0m"
441                 echo -e "\033[31m\033[1m|___/\___|_|_\___|_|   |_|   |_/_/ \_\___|____\___/|_|_\___|\033[0m"
442         elif [ $RES_PASS = $RES_TEST ]; then
443                 echo -e "All tests \033[32m\033[1mPASS\033[0m"
444                 echo -e "\033[32m\033[1m  ___  _   ___ ___ \033[0m"
445                 echo -e "\033[32m\033[1m | _ \/_\ / __/ __| \033[0m"
446                 echo -e "\033[32m\033[1m |  _/ _ \\__ \__ \\ \033[0m"
447                 echo -e "\033[32m\033[1m |_|/_/ \_\___/___/ \033[0m"
448                 echo ""
449
450                 # Update test suite counter
451                 if [ -f .tmp_tcsuite_pass_ctr ]; then
452                         tmpval=$(< .tmp_tcsuite_pass_ctr)
453                         ((tmpval++))
454                         echo $tmpval > .tmp_tcsuite_pass_ctr
455                 fi
456                 if [ -f .tmp_tcsuite_pass ]; then
457                         echo " - "$ATC " -- "$TC_ONELINE_DESCR"  Execution time: "$duration" seconds" >> .tmp_tcsuite_pass
458                 fi
459         else
460                 echo -e "One or more tests with status  \033[31m\033[1mFAIL\033[0m "
461                 echo -e "\033[31m\033[1m  ___ _   ___ _    \033[0m"
462                 echo -e "\033[31m\033[1m | __/_\ |_ _| |   \033[0m"
463                 echo -e "\033[31m\033[1m | _/ _ \ | || |__ \033[0m"
464                 echo -e "\033[31m\033[1m |_/_/ \_\___|____|\033[0m"
465                 echo ""
466                 # Update test suite counter
467                 if [ -f .tmp_tcsuite_fail_ctr ]; then
468                         tmpval=$(< .tmp_tcsuite_fail_ctr)
469                         ((tmpval++))
470                         echo $tmpval > .tmp_tcsuite_fail_ctr
471                 fi
472                 if [ -f .tmp_tcsuite_fail ]; then
473                         echo " - "$ATC " -- "$TC_ONELINE_DESCR"  Execution time: "$duration" seconds" >> .tmp_tcsuite_fail
474                 fi
475         fi
476
477         echo "++++ Number of tests:          "$RES_TEST
478         echo "++++ Number of passed tests:   "$RES_PASS
479         echo "++++ Number of failed tests:   "$RES_FAIL
480         echo ""
481         echo "++++ Number of failed configs: "$RES_CONF_FAIL
482         echo "-------------------------------------     Test case complete    ---------------------------------"
483         echo "-------------------------------------------------------------------------------------------------"
484         echo ""
485 }
486
487 #####################################################################
488 ###### Functions for start, configuring, stoping, cleaning etc ######
489 #####################################################################
490
491
492 # Stop and remove all containers
493 # args: -
494 # (Function for test scripts)
495 clean_containers() {
496
497         echo -e $BOLD"Stopping and removing all running containers, by container name"$EBOLD
498
499         CONTAINTER_NAMES=("Policy Agent           " $POLICY_AGENT_APP_NAME\
500                                           "Non-RT RIC Simulator(s)" $RIC_SIM_PREFIX\
501                                           "Message Router         " $MR_APP_NAME\
502                                           "Callback Receiver      " $CR_APP_NAME\
503                                           "Control Panel          " $CONTROL_PANEL_APP_NAME\
504                                           "SDNC A1 Controller     " $SDNC_APP_NAME\
505                                           "SDNC DB                " $SDNC_DB_APP_NAME\
506                                           "CBS                    " $CBS_APP_NAME\
507                                           "Consul                 " $CONSUL_APP_NAME)
508
509         nw=0 # Calc max width of container name, to make a nice table
510         for (( i=1; i<${#CONTAINTER_NAMES[@]} ; i+=2 )) ; do
511                 if [ ${#CONTAINTER_NAMES[i]} -gt $nw ]; then
512                         nw=${#CONTAINTER_NAMES[i]}
513                 fi
514         done
515
516         for (( i=0; i<${#CONTAINTER_NAMES[@]} ; i+=2 )) ; do
517                 APP="${CONTAINTER_NAMES[i]}"
518                 CONTR="${CONTAINTER_NAMES[i+1]}"
519                 for((w=${#CONTR}; w<$nw; w=w+1)); do
520                         CONTR="$CONTR "
521                 done
522                 echo -ne " $APP: $CONTR - ${GREEN}stopping${EGREEN}\033[0K\r"
523                 docker stop $(docker ps -qa --filter name=${CONTR}) &> /dev/null
524                 echo -ne " $APP: $CONTR - ${GREEN}stopped${EGREEN}\033[0K\r"
525                 docker rm $(docker ps -qa --filter name=${CONTR}) &> /dev/null
526                 echo -e  " $APP: $CONTR - ${GREEN}stopped removed${EGREEN}"
527         done
528
529         echo ""
530 }
531
532 # Function stop and remove all container in the end of the test script, if the arg 'auto-clean' is given at test script start
533 # args: -
534 # (Function for test scripts)
535 auto_clean_containers() {
536         echo
537         if [ "$AUTO_CLEAN" == "auto" ]; then
538                 echo -e $BOLD"Initiating automatic cleaning of started containers"$EBOLD
539                 clean_containers
540         fi
541 }
542
543 # Function to sleep a test case for a numner of seconds. Prints the optional text args as info
544 # args: <sleep-time-in-sec> [any-text-in-quoteds-to-printed]
545 # (Function for test scripts)
546 sleep_wait() {
547
548         echo -e $BOLD"INFO(${BASH_LINENO[0]}): "${FUNCNAME[0]}"," $@ $EBOLD
549         if [ $# -lt 1 ]; then
550                 ((RES_CONF_FAIL++))
551                 __print_err "need at least one arg, <sleep-time-in-sec> [any-text-to-printed]" $@
552                 exit 1
553         fi
554         #echo "---- Sleep for " $1 " seconds ---- "$2
555         start=$SECONDS
556         duration=$((SECONDS-start))
557         while [ $duration -lt $1 ]; do
558                 echo -ne "  Slept for ${duration} seconds\033[0K\r"
559                 sleep 1
560                 duration=$((SECONDS-start))
561         done
562         echo -ne "  Slept for ${duration} seconds\033[0K\r"
563         echo ""
564 }
565
566 # Print error info for the call in the parent script (test case). Arg: <error-message-to-print>
567 # Not to be called from the test script itself.
568 __print_err() {
569     echo -e $RED ${FUNCNAME[1]} " "$1" " ${BASH_SOURCE[2]} " line" ${BASH_LINENO[1]} $ERED
570         if [ $# -gt 1 ]; then
571                 echo -e $RED" Got: "${FUNCNAME[1]} ${@:2} $ERED
572         fi
573 }
574
575
576 # Helper function to get a the port of a specific ric simulatpor
577 # args: <ric-id>
578 # (Not for test scripts)
579 __find_sim_port() {
580     name=$1" " #Space appended to prevent matching 10 if 1 is desired....
581     cmdstr="docker ps --filter name=${name} --format \"{{.Names}} {{.Ports}}\" | grep '${name}' | sed s/0.0.0.0:// | cut -f 2 -d ' ' | cut -f 1 -d '-'"
582         res=$(eval $cmdstr)
583         if [[ "$res" =~ ^[0-9]+$ ]]; then
584                 echo $res
585         else
586                 echo "0"
587     fi
588 }
589
590 # Function to create the docker network for the test
591 # Not to be called from the test script itself.
592 __create_docker_network() {
593         tmp=$(docker network ls -q --filter name=$DOCKER_SIM_NWNAME)
594         if [ $? -ne 0 ]; then
595                 echo -e $RED" Could not check if docker network $DOCKER_SIM_NWNAME exists"$ERED
596                 return 1
597         fi
598         if [ -z tmp ]; then
599                 echo -e "Creating docker network:$BOLD $DOCKER_SIM_NWNAME $EBOLD"
600                 docker network create $DOCKER_SIM_NWNAME
601                 if [ $? -ne 0 ]; then
602                         echo -e $RED" Could not create docker network $DOCKER_SIM_NWNAME"$ERED
603                         return 1
604                 fi
605         else
606                 echo -e " Docker network $DOCKER_SIM_NWNAME already exists$GREEN OK $EGREEN"
607         fi
608 }
609
610 # Check if container is started by calling url on localhost using a port, expects response code 2XX
611 # args: <container-name> <port> <url>
612 # Not to be called from the test script itself.
613 __check_container_start() {
614         if [ $# -ne 3 ]; then
615                 ((RES_CONF_FAIL++))
616                 __print_err "need 3 args, <container-name> <port> <url>" $@
617                 return 1
618         fi
619         echo -ne " Container $BOLD$1$EBOLD starting\033[0K\r"
620         appname=$1
621         localport=$2
622         url=$3
623         pa_started=false
624         for i in {1..10}; do
625                 if [ $(docker inspect --format '{{ .State.Running }}' $appname) ]; then
626                                 echo -e " Container $BOLD$1$EBOLD$GREEN running$EGREEN on$BOLD image $(docker inspect --format '{{ .Config.Image }}' ${appname}) $EBOLD"
627                                 pa_started=true
628                                 break
629                         else
630                                 sleep $i
631                 fi
632         done
633         if ! [ $pa_started  ]; then
634                 ((RES_CONF_FAIL++))
635                 echo ""
636                 echo -e $RED" Container $BOLD${appname}$EBOLD could not be started"$ERED
637                 return 1
638         fi
639         if [ $localport -eq 0 ]; then
640                 while [ $localport -eq 0 ]; do
641                         echo -ne " Waiting for container ${appname} to publish its ports...\033[0K\r"
642                         localport=$(__find_sim_port $appname)
643                         sleep 1
644                         echo -ne " Waiting for container ${appname} to publish its ports...retrying....\033[0K\r"
645                 done
646                 echo -ne " Waiting for container ${appname} to publish its ports...retrying....$GREEN OK $EGREEN"
647                 echo ""
648         fi
649
650         pa_st=false
651         echo -ne " Waiting for container ${appname} service status...\033[0K\r"
652         for i in {1..20}; do
653                 result="$(__do_curl $LOCALHOST${localport}${url})"
654                 if [ $? -eq 0 ]; then
655                         if [ ${#result} -gt 15 ]; then
656                                 #If response is too long, truncate
657                                 result="...response text too long, omitted"
658                         fi
659                         echo -ne " Waiting for container $BOLD${appname}$EBOLD service status, result: $result\033[0K\r"
660                         echo -ne " Container $BOLD${appname}$EBOLD$GREEN is alive$EGREEN, responds to service status:$GREEN $result $EGREEN"
661                         pa_st=true
662                         break
663                 else
664                         #echo " Retrying in $i seconds"
665                         echo -ne " Waiting for container ${appname} service status...retrying in $i seconds\033[0K\r"
666                         sleep $i
667                 fi
668         done
669
670         if [ "$pa_st" = "false"  ]; then
671                 ((RES_CONF_FAIL++))
672                 echo -e $RED" Container ${appname} did not respond to service status"$ERED
673                 return 0
674         fi
675
676         echo ""
677         return 0
678 }
679
680
681 # Function to start a container and wait until it responds on the given port and url.
682 #args: <docker-compose-dir> NODOCKERARGS|<docker-compose-arg> <app-name> <port-number> <alive-url> [<app-name> <port-number> <alive-url>]*
683 __start_container() {
684
685         variableArgCount=$(($#-2))
686         if [ $# -lt 5 ] && [ [ $(($variableArgCount%3)) -ne 0 ]; then
687                 ((RES_CONF_FAIL++))
688         __print_err "need 5 or more args,  <docker-compose-dir> NODOCKERARGS|<docker-compose-arg> <app-name> <port-number> <alive-url> [<app-name> <port-number> <alive-url>]*" $@
689                 exit 1
690         fi
691
692         __create_docker_network
693
694         curdir=$PWD
695         cd $SIM_GROUP
696         cd $1
697
698         if [ "$2" == "NODOCKERARGS" ]; then
699                 docker-compose up -d &> /dev/null
700         else
701                 docker-compose up -d $2 &> /dev/null
702         fi
703
704         shift; shift;
705         cntr=0
706         while [ $cntr -lt $variableArgCount ]; do
707                 app=$1; shift;
708                 port=$1; shift;
709                 url=$1; shift;
710                 let cntr=cntr+3
711
712                 __check_container_start "$app" "$port" "$url"
713         done
714
715         cd $curdir
716         echo ""
717         return 0
718 }
719
720 ####################
721 ### Consul functions
722 ####################
723
724 # Function to load config from a file into consul for the Policy Agent
725 # arg: <json-config-file>
726 # (Function for test scripts)
727 consul_config_app() {
728
729         echo -e $BOLD"Configuring Consul"$EBOLD
730
731         if [ $# -ne 1 ]; then
732                 ((RES_CONF_FAIL++))
733         __print_err "need one arg,  <json-config-file>" $@
734                 exit 1
735         fi
736
737         echo " Loading config for "$POLICY_AGENT_APP_NAME" from "$1
738
739         curl -s $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 >/dev/null
740         if [ $? -ne 0 ]; then
741                 echo -e $RED" FAIL - json config could not be loaded to consul" $ERED
742                 ((RES_CONF_FAIL++))
743                 return 1
744         fi
745         body="$(__do_curl $LOCALHOST$CBS_EXTERNAL_PORT/service_component_all/$POLICY_AGENT_APP_NAME)"
746
747         if [ $? -ne 0 ]; then
748                 echo -e $RED" FAIL - json config could not be loaded from consul/cbs, contents cannot be checked." $ERED
749                 ((RES_CONF_FAIL++))
750                 return 1
751         else
752                 targetJson=$(< $1)
753                 targetJson="{\"config\":"$targetJson"}"
754                 echo "TARGET JSON: $targetJson" >> $HTTPLOG
755                 res=$(python ../common/compare_json.py "$targetJson" "$body")
756                 if [ $res -ne 0 ]; then
757                         echo -e $RED" FAIL - policy json config read from consul/cbs is not equal to the intended json config...." $ERED
758                         ((RES_CONF_FAIL++))
759                         return 1
760                 else
761                         echo -e $GREEN" Config loaded ok to consul"$EGREEN
762                 fi
763         fi
764
765         echo ""
766
767 }
768
769 # Function to perpare the consul configuration according to the current simulator configuration
770 # args: SDNC|NOSDNC <output-file>
771 # (Function for test scripts)
772 prepare_consul_config() {
773         echo -e $BOLD"Prepare Consul config"$EBOLD
774
775         echo " Writing consul config for "$POLICY_AGENT_APP_NAME" to file: "$2
776
777         if [ $# != 2 ];  then
778                 ((RES_CONF_FAIL++))
779         __print_err "need two args,  SDNC|NOSDNC <output-file>" $@
780                 exit 1
781         fi
782
783         if [ $1 == "SDNC" ]; then
784                 echo -e " Config$BOLD including SDNC$EBOLD configuration"
785         elif [ $1 == "NOSDNC" ];  then
786                 echo -e " Config$BOLD excluding SDNC$EBOLD configuration"
787         else
788                 ((RES_CONF_FAIL++))
789         __print_err "need two args,  SDNC|NOSDNC <output-file>" $@
790                 exit 1
791         fi
792
793         config_json="\n            {"
794         if [ $1 == "SDNC" ]; then
795                 config_json=$config_json"\n   \"controller\": ["
796                 config_json=$config_json"\n                     {"
797                 config_json=$config_json"\n                       \"name\": \"$SDNC_APP_NAME\","
798                 config_json=$config_json"\n                       \"baseUrl\": \"http://$SDNC_APP_NAME:$SDNC_INTERNAL_PORT\","
799                 config_json=$config_json"\n                       \"userName\": \"$SDNC_USER\","
800                 config_json=$config_json"\n                       \"password\": \"$SDNC_PWD\""
801                 config_json=$config_json"\n                     }"
802                 config_json=$config_json"\n   ],"
803         fi
804
805
806         config_json=$config_json"\n   \"streams_publishes\": {"
807         config_json=$config_json"\n                            \"dmaap_publisher\": {"
808         config_json=$config_json"\n                              \"type\": \"$MR_APP_NAME\","
809         config_json=$config_json"\n                              \"dmaap_info\": {"
810         config_json=$config_json"\n                                \"topic_url\": \"http://$MR_APP_NAME:$MR_INTERNAL_PORT/events/A1-POLICY-AGENT-WRITE\""
811         config_json=$config_json"\n                              }"
812         config_json=$config_json"\n                            }"
813         config_json=$config_json"\n   },"
814         config_json=$config_json"\n   \"streams_subscribes\": {"
815         config_json=$config_json"\n                             \"dmaap_subscriber\": {"
816         config_json=$config_json"\n                               \"type\": \"$MR_APP_NAME\","
817         config_json=$config_json"\n                               \"dmaap_info\": {"
818         config_json=$config_json"\n                                   \"topic_url\": \"http://$MR_APP_NAME:$MR_INTERNAL_PORT/events/A1-POLICY-AGENT-READ/users/policy-agent\""
819         config_json=$config_json"\n                                 }"
820         config_json=$config_json"\n                               }"
821         config_json=$config_json"\n   },"
822
823         config_json=$config_json"\n   \"ric\": ["
824
825         rics=$(docker ps | grep ricsim | awk '{print $NF}')
826
827         if [ $? -ne 0 ] || [ -z "$rics" ]; then
828                 echo -e $RED" FAIL - the names of the running RIC Simulator cannot be retrieved." $ERED
829                 ((RES_CONF_FAIL++))
830                 return 1
831         fi
832
833         cntr=0
834         for ric in $rics; do
835                 if [ $cntr -gt 0 ]; then
836                         config_json=$config_json"\n          ,"
837                 fi
838                 config_json=$config_json"\n          {"
839                 config_json=$config_json"\n            \"name\": \"$ric\","
840                 config_json=$config_json"\n            \"baseUrl\": \"http://$ric:$RIC_SIM_INTERNAL_PORT\","
841                 if [ $1 == "SDNC" ]; then
842                         config_json=$config_json"\n            \"controller\": \"$SDNC_APP_NAME\","
843                 fi
844                 config_json=$config_json"\n            \"managedElementIds\": ["
845                 config_json=$config_json"\n              \"me1_$ric\","
846                 config_json=$config_json"\n              \"me2_$ric\""
847                 config_json=$config_json"\n            ]"
848                 config_json=$config_json"\n          }"
849                 let cntr=cntr+1
850         done
851
852         config_json=$config_json"\n           ]"
853         config_json=$config_json"\n}"
854
855
856         printf "$config_json">$2
857
858         echo ""
859 }
860
861
862 # Start Consul and CBS
863 # args: -
864 # (Function for test scripts)
865 start_consul_cbs() {
866
867         echo -e $BOLD"Starting Consul and CBS"$EBOLD
868
869         __start_container consul_cbs NODOCKERARGS  "$CONSUL_APP_NAME" "$CONSUL_EXTERNAL_PORT" "/ui/dc1/kv" \
870                                                      "$CBS_APP_NAME" "$CBS_EXTERNAL_PORT" "/healthcheck"
871 }
872
873 ###########################
874 ### RIC Simulator functions
875 ###########################
876
877 # Start one group (ricsim_g1, ricsim_g2 or ricsim_g3) with a number of RIC Simulators using a given A interface
878 # args:  ricsim_g1|ricsim_g2|ricsim_g3 <count> <interface-id>
879 # (Function for test scripts)
880 start_ric_simulators() {
881
882         echo -e $BOLD"Starting RIC Simulators"$EBOLD
883
884         if [ $# != 3 ]; then
885                 ((RES_CONF_FAIL++))
886         __print_err "need three args,  ricsim_g1|ricsim_g2|ricsim_g3 <count> <interface-id>" $@
887                 exit 1
888         fi
889         echo " $2 simulators using basename: $1 on interface: $3"
890         #Set env var for simulator count and A1 interface vesion for the given group
891         if [ $1 == "ricsim_g1" ]; then
892                 G1_COUNT=$2
893                 G1_A1_VERSION=$3
894         elif [ $1 == "ricsim_g2" ]; then
895                 G2_COUNT=$2
896                 G2_A1_VERSION=$3
897         elif [ $1 == "ricsim_g3" ]; then
898                 G3_COUNT=$2
899                 G3_A1_VERSION=$3
900         else
901                 ((RES_CONF_FAIL++))
902         __print_err "need three args, gricsim_g1|ricsim_g2|ricsim_g3 <count> <interface-id>" $@
903                 exit 1
904         fi
905
906         # Create .env file to compose project, all ric container will get this prefix
907         echo "COMPOSE_PROJECT_NAME="$RIC_SIM_PREFIX > $SIM_GROUP/ric/.env
908
909         export G1_A1_VERSION
910         export G2_A1_VERSION
911         export G3_A1_VERSION
912
913         docker_args="--scale g1=$G1_COUNT --scale g2=$G2_COUNT --scale g3=$G3_COUNT"
914         app_data=""
915         cntr=1
916         while [ $cntr -le $2 ]; do
917                 app=$1"_"$cntr
918                 port=0
919                 app_data="$app_data $app $port /"
920                 let cntr=cntr+1
921         done
922
923         __start_container ric "$docker_args" $app_data
924
925 }
926
927 ###########################
928 ### Control Panel functions
929 ###########################
930
931 # Start the Control Panel container
932 # args: -
933 # (Function for test scripts)
934 start_control_panel() {
935
936         echo -e $BOLD"Starting Control Panel"$EBOLD
937
938         __start_container control_panel NODOCKERARGS $CONTROL_PANEL_APP_NAME $CONTROL_PANEL_EXTERNAL_PORT "/"
939
940 }
941
942 ##################
943 ### SDNC functions
944 ##################
945
946 # Start the SDNC A1 Controller
947 # args: -
948 # (Function for test scripts)
949 start_sdnc() {
950
951         echo -e $BOLD"Starting SDNC A1 Controller"$EBOLD
952
953         __start_container sdnc NODOCKERARGS $SDNC_APP_NAME $SDNC_EXTERNAL_PORT "/apidoc/explorer"
954
955 }
956
957 #####################
958 ### MR stub functions
959 #####################
960
961 # Start the Message Router stub interface in the simulator group
962 # args: -
963 # (Function for test scripts)
964 start_mr() {
965
966         echo -e $BOLD"Starting Message Router 'mrstub'"$EBOLD
967
968         __start_container mr NODOCKERARGS $MR_APP_NAME $MR_EXTERNAL_PORT "/"
969
970 }
971
972 ################
973 ### CR functions
974 ################
975
976 # Start the Callback reciver in the simulator group
977 # args: -
978 # (Function for test scripts)
979 start_cr() {
980
981         echo -e $BOLD"Starting Callback Receiver"$EBOLD
982
983         __start_container cr NODOCKERARGS $CR_APP_NAME $CR_EXTERNAL_PORT "/"
984
985 }
986
987 ###########################
988 ### Policy Agents functions
989 ###########################
990
991 # Start the policy agwent
992 # args: -
993 # (Function for test scripts)
994 start_policy_agent() {
995
996         echo -e $BOLD"Starting Policy Agent"$EBOLD
997
998         __start_container policy_agent NODOCKERARGS $POLICY_AGENT_APP_NAME $POLICY_AGENT_EXTERNAL_PORT "/status"
999
1000 }
1001
1002 # All calls to the agent will be directed to the agent REST interface from now on
1003 # args: -
1004 # (Function for test scripts)
1005 use_agent_rest() {
1006         echo -e $BOLD"Using agent REST interface"$EBOLD
1007         export ADAPTER=$RESTBASE
1008         echo ""
1009 }
1010
1011 # All calls to the agent will be directed to the agent dmaap interface from now on
1012 # args: -
1013 # (Function for test scripts)
1014 use_agent_dmaap() {
1015         echo -e $BOLD"Using agent DMAAP interface"$EBOLD
1016         export ADAPTER=$DMAAPBASE
1017         echo ""
1018
1019 }
1020
1021 # Turn on debug level tracing in the agent
1022 # args: -
1023 # (Function for test scripts)
1024 set_agent_debug() {
1025         echo -e $BOLD"Setting agent debug"$EBOLD
1026         curl $LOCALHOST$POLICY_AGENT_EXTERNAL_PORT/actuator/loggers/org.oransc.policyagent -X POST  -H 'Content-Type: application/json' -d '{"configuredLevel":"debug"}' &> /dev/null
1027         if [ $? -ne 0 ]; then
1028                 __print_err "could not set debug mode" $@
1029                 return 1
1030         fi
1031         return 0
1032         echo ""
1033 }
1034
1035 # Perform curl retries when making direct call to the agent for the specified http response codes
1036 # Speace separated list of http response codes
1037 # args: [<response-code>]*
1038 use_agent_retries() {
1039         echo -e $BOLD"Do curl retries to the agent REST inteface for these response codes:$@"$EBOLD
1040         AGENT_RETRY_CODES=$@
1041         echo ""
1042 }
1043
1044 #################
1045 ### Log functions
1046 #################
1047
1048 # Check the agent logs for WARNINGs and ERRORs
1049 # args: -
1050 # (Function for test scripts)
1051
1052 check_policy_agent_logs() {
1053         __check_container_logs "Policy Agent" $POLICY_AGENT_APP_NAME $POLICY_AGENT_LOGPATH
1054 }
1055
1056 check_control_panel_logs() {
1057         __check_container_logs "Control Panel" $CONTROL_PANEL_APP_NAME $CONTROL_PANEL_LOGPATH
1058 }
1059
1060 __check_container_logs() {
1061         dispname=$1
1062         appname=$2
1063         logpath=$3
1064         echo -e $BOLD"Checking $dispname container $appname log ($logpath) for WARNINGs and ERRORs"$EBOLD
1065
1066         #tmp=$(docker ps | grep $appname)
1067         tmp=$(docker ps -q --filter name=$appname) #get the container id
1068         if [ -z "$tmp" ]; then  #Only check logs for running Policy Agent apps
1069                 echo $dispname" is not running, no check made"
1070                 return
1071         fi
1072         foundentries="$(docker exec -it $tmp grep WARN $logpath | wc -l)"
1073         if [ $? -ne  0 ];then
1074                 echo "  Problem to search $appname log $logpath"
1075         else
1076                 if [ $foundentries -eq 0 ]; then
1077                         echo "  No WARN entries found in $appname log $logpath"
1078                 else
1079                         echo -e "  Found \033[1m"$foundentries"\033[0m WARN entries in $appname log $logpath"
1080                 fi
1081         fi
1082         foundentries="$(docker exec -it $tmp grep ERR $logpath | wc -l)"
1083         if [ $? -ne  0 ];then
1084                 echo "  Problem to search $appname log $logpath"
1085         else
1086                 if [ $foundentries -eq 0 ]; then
1087                         echo "  No ERR entries found in $appname log $logpath"
1088                 else
1089                         echo -e $RED"  Found \033[1m"$foundentries"\033[0m"$RED" ERR entries in $appname log $logpath"$ERED
1090                 fi
1091         fi
1092         echo ""
1093 }
1094
1095 # Store all container logs and other logs in the log dir for the script
1096 # Logs are stored with a prefix in case logs should be stored several times during a test
1097 # args: <logfile-prefix>
1098 # (Function for test scripts)
1099 store_logs() {
1100         if [ $# != 1 ]; then
1101                 ((RES_CONF_FAIL++))
1102         __print_err "need one arg, <file-prefix>" $@
1103                 exit 1
1104         fi
1105         echo -e $BOLD"Storing all container logs, Policy Agent app log and consul config using prefix: "$1
1106
1107         docker logs $CONSUL_APP_NAME > $TESTLOGS/$ATC/$1_consul.log 2>&1
1108         docker logs $CBS_APP_NAME > $TESTLOGS/$ATC/$1_cbs.log 2>&1
1109         docker logs $POLICY_AGENT_APP_NAME > $TESTLOGS/$ATC/$1_policy-agent.log 2>&1
1110         docker logs $CONSUL_APP_NAME > $TESTLOGS/$ATC/$1_control-panel.log 2>&1
1111         docker logs $MR_APP_NAME > $TESTLOGS/$ATC/$1_mr.log 2>&1
1112         docker logs $CR_APP_NAME > $TESTLOGS/$ATC/$1_cr.log 2>&1
1113         cp .httplog_${ATC}.txt $TESTLOGS/$ATC/$1_httplog_${ATC}.txt 2>&1
1114
1115         docker exec -it $SDNC_APP_NAME cat /opt/opendaylight/data/log/karaf.log > $TESTLOGS/$ATC/$1_karaf.log 2>&1
1116
1117         rics=$(docker ps -f "name=$RIC_SIM_PREFIX" --format "{{.Names}}")
1118         for ric in $rics; do
1119                 docker logs $ric > $TESTLOGS/$ATC/$1_$ric.log 2>&1
1120         done
1121         body="$(__do_curl $LOCALHOST$CBS_EXTERNAL_PORT/service_component_all/$POLICY_AGENT_APP_NAME)"
1122         echo "$body" > $TESTLOGS/$ATC/$1_consul_config.json 2>&1
1123         echo ""
1124 }
1125
1126 ###############
1127 ## Generic curl
1128 ###############
1129 # Generic curl function, assumed all 200-codes are ok
1130 # args: <url>
1131 # returns: <returned response (without respose code)>  or "<no-response-from-server>" or "<not found, <http-code>>""
1132 # returns: The return code is 0 for ok and 1 for not ok
1133 __do_curl() {
1134         echo ${FUNCNAME[1]} "line: "${BASH_LINENO[1]} >> $HTTPLOG
1135         curlString="curl -skw %{http_code} $1"
1136         echo " CMD: $curlString" >> $HTTPLOG
1137         res=$($curlString)
1138         echo " RESP: $res" >> $HTTPLOG
1139         http_code="${res:${#res}-3}"
1140         if [ ${#res} -eq 3 ]; then
1141                 echo "<no-response-from-server>"
1142                 return 1
1143         else
1144                 if [ $http_code -lt 200 ] || [ $http_code -gt 299 ]; then
1145                         echo "<not found, resp:${http_code}>"
1146                         return 1
1147                 fi
1148                 if [ $# -eq 2 ]; then
1149                         echo "${res:0:${#res}-3}" | xargs
1150                 else
1151                         echo "${res:0:${#res}-3}"
1152                 fi
1153
1154                 return 0
1155         fi
1156 }
1157
1158 #######################################
1159 ### Basic helper function for test cases
1160 #######################################
1161
1162 # Test a simulator container variable value towards target value using an condition operator with an optional timeout.
1163 # Arg: <simulator-name> <host> <variable-name> <condition-operator> <target-value>  - This test is done
1164 # immediately and sets pass or fail depending on the result of comparing variable and target using the operator.
1165 # Arg: <simulator-name> <host> <variable-name> <condition-operator> <target-value> <timeout>  - This test waits up to the timeout
1166 # before setting pass or fail depending on the result of comparing variable and target using the operator.
1167 # 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.
1168 # Not to be called from test script.
1169
1170 __var_test() {
1171         checkjsonarraycount=0
1172
1173         if [ $# -eq 6 ]; then
1174                 if [[ $3 == "json:"* ]]; then
1175                         checkjsonarraycount=1
1176                 fi
1177
1178                 #echo -e "---- ${1} sim test criteria: \033[1m ${3} \033[0m ${4} ${5} within ${6} seconds ----"
1179                 echo -e $BOLD"TEST(${BASH_LINENO[1]}): ${1}, ${3} ${4} ${5} within ${6} seconds"
1180                 ((RES_TEST++))
1181                 start=$SECONDS
1182                 ctr=0
1183                 for (( ; ; )); do
1184                         if [ $checkjsonarraycount -eq 0 ]; then
1185                                 result="$(__do_curl $2$3)"
1186                                 retcode=$?
1187                                 result=${result//[[:blank:]]/} #Strip blanks
1188                         else
1189                                 path=${3:5}
1190                                 result="$(__do_curl $2$path)"
1191                                 retcode=$?
1192                                 echo "$result" > .tmp.curl.json
1193                                 result=$(python ../common/count_json_elements.py ".tmp.curl.json")
1194                         fi
1195                         duration=$((SECONDS-start))
1196                         echo -ne " Result=${result} after ${duration} seconds\033[0K\r"
1197                         let ctr=ctr+1
1198                         if [ $retcode -ne 0 ]; then
1199                                 if [ $duration -gt $6 ]; then
1200                                         ((RES_FAIL++))
1201                                         #echo -e "----  \033[31m\033[1mFAIL\033[0m - Target ${3} ${4} ${5}  not reached in ${6} seconds, result = ${result} ----"
1202                                         echo -e $RED" FAIL${ERED} - ${3} ${4} ${5} not reached in ${6} seconds, result = ${result}"
1203                                         return
1204                                 fi
1205                         elif [ $4 = "=" ] && [ "$result" -eq $5 ]; then
1206                                 ((RES_PASS++))
1207                                 echo -e " Result=${result} after ${duration} seconds\033[0K\r"
1208                                 echo -e $GREEN" PASS${EGREEN} - Result=${result} after ${duration} seconds"
1209                                 #echo -e "----  \033[32m\033[1mPASS\033[0m - Test criteria met in ${duration} seconds ----"
1210                                 return
1211                         elif [ $4 = ">" ] && [ "$result" -gt $5 ]; then
1212                                 ((RES_PASS++))
1213                                 echo -e " Result=${result} after ${duration} seconds\033[0K\r"
1214                                 echo -e $GREEN" PASS${EGREEN} - Result=${result} after ${duration} seconds"
1215                                 #echo -e "----  \033[32m\033[1mPASS\033[0m - Test criteria met in ${duration} seconds, result = ${result}  ----"
1216                                 return
1217                         elif [ $4 = "<" ] && [ "$result" -lt $5 ]; then
1218                                 ((RES_PASS++))
1219                                 echo -e " Result=${result} after ${duration} seconds\033[0K\r"
1220                                 echo -e $GREEN" PASS${EGREEN} - Result=${result} after ${duration} seconds"
1221                                 #echo -e "----  \033[32m\033[1mPASS\033[0m - Test criteria met in ${duration} seconds, result = ${result}  ----"
1222                                 return
1223                         elif [ $4 = "contain_str" ] && [[ $result =~ $5 ]]; then
1224                                 ((RES_PASS++))
1225                                 echo -e " Result=${result} after ${duration} seconds\033[0K\r"
1226                                 echo -e $GREEN" PASS${EGREEN} - Result=${result} after ${duration} seconds"
1227                                 #echo -e "----  \033[32m\033[1mPASS\033[0m - Test criteria met in ${duration} seconds, result = ${result}  ----"
1228                                 return
1229                         else
1230                                 if [ $duration -gt $6 ]; then
1231                                         ((RES_FAIL++))
1232                                         echo -e $RED" FAIL${ERED} - ${3} ${4} ${5} not reached in ${6} seconds, result = ${result}"
1233                                         #echo -e "----  \033[31m\033[1mFAIL\033[0m - Target ${3} ${4} ${5}  not reached in ${6} seconds, result = ${result} ----"
1234                                         return
1235                                 fi
1236                         fi
1237                         sleep 1
1238                 done
1239         elif [ $# -eq 5 ]; then
1240                 if [[ $3 == "json:"* ]]; then
1241                         checkjsonarraycount=1
1242                 fi
1243
1244                 #echo -e "---- ${1} sim test criteria: \033[1m ${3} \033[0m ${4} ${5} ----"
1245                 echo -e $BOLD"TEST(${BASH_LINENO[1]}): ${1}, ${3} ${4} ${5}"$EBOLD
1246                 ((RES_TEST++))
1247                 if [ $checkjsonarraycount -eq 0 ]; then
1248                         result="$(__do_curl $2$3)"
1249                         retcode=$?
1250                         result=${result//[[:blank:]]/} #Strip blanks
1251                 else
1252                         path=${3:5}
1253                         result="$(__do_curl $2$path)"
1254                         retcode=$?
1255                         echo "$result" > .tmp.curl.json
1256                         result=$(python ../common/count_json_elements.py ".tmp.curl.json")
1257                 fi
1258                 if [ $retcode -ne 0 ]; then
1259                         ((RES_FAIL++))
1260                         #echo -e "----  \033[31m\033[1mFAIL\033[0m - Target ${3} ${4} ${5} not reached, result = ${result} ----"
1261                         echo -e $RED" FAIL ${ERED}- ${3} ${4} ${5} not reached, result = ${result}"
1262                 elif [ $4 = "=" ] && [ "$result" -eq $5 ]; then
1263                         ((RES_PASS++))
1264                         echo -e $GREEN" PASS${EGREEN} - Result=${result}"
1265                         #echo -e "----  \033[32m\033[1mPASS\033[0m - Test criteria met"
1266                 elif [ $4 = ">" ] && [ "$result" -gt $5 ]; then
1267                         ((RES_PASS++))
1268                         echo -e $GREEN" PASS${EGREEN} - Result=${result}"
1269                         #echo -e "----  \033[32m\033[1mPASS\033[0m - Test criteria met, result = ${result} ----"
1270                 elif [ $4 = "<" ] && [ "$result" -lt $5 ]; then
1271                         ((RES_PASS++))
1272                         echo -e $GREEN" PASS${EGREEN} - Result=${result}"
1273                         #echo -e "----  \033[32m\033[1mPASS\033[0m - Test criteria met, result = ${result} ----"
1274                 elif [ $4 = "contain_str" ] && [[ $result =~ $5 ]]; then
1275                         ((RES_PASS++))
1276                         echo -e $GREEN" PASS${EGREEN} - Result=${result}"
1277                         #echo -e "----  \033[32m\033[1mPASS\033[0m - Test criteria met, result = ${result} ----"
1278                 else
1279                         ((RES_FAIL++))
1280                         echo -e $RED" FAIL${ERED} - ${3} ${4} ${5} not reached, result = ${result}"
1281                         #echo -e "----  \033[31m\033[1mFAIL\033[0m - Target ${3} ${4} ${5} not reached, result = ${result} ----"
1282                 fi
1283         else
1284                 echo "Wrong args to __var_test, needs five or six args: <simulator-name> <host> <variable-name> <condition-operator> <target-value> [ <timeout> ]"
1285                 echo "Got:" $@
1286                 exit 1
1287         fi
1288 }
1289
1290
1291 ### Generic test cases for varaible checking
1292
1293 # Tests if a variable value in the CR is equal to a target value and and optional timeout.
1294 # Arg: <variable-name> <target-value> - This test set pass or fail depending on if the variable is
1295 # equal to the target or not.
1296 # Arg: <variable-name> <target-value> <timeout-in-sec>  - This test waits up to the timeout seconds
1297 # before setting pass or fail depending on if the variable value becomes equal to the target
1298 # value or not.
1299 # (Function for test scripts)
1300 cr_equal() {
1301         if [ $# -eq 2 ] || [ $# -eq 3 ]; then
1302                 __var_test "CR" "$LOCALHOST$CR_EXTERNAL_PORT/counter/" $1 "=" $2 $3
1303         else
1304                 ((RES_CONF_FAIL++))
1305                 __print_err "Wrong args to cr_equal, needs two or three args: <sim-param> <target-value> [ timeout ]" $@
1306         fi
1307 }
1308
1309 # Tests if a variable value in the MR stub is equal to a target value and and optional timeout.
1310 # Arg: <variable-name> <target-value> - This test set pass or fail depending on if the variable is
1311 # equal to the target or not.
1312 # Arg: <variable-name> <target-value> <timeout-in-sec>  - This test waits up to the timeout seconds
1313 # before setting pass or fail depending on if the variable value becomes equal to the target
1314 # value or not.
1315 # (Function for test scripts)
1316 mr_equal() {
1317         if [ $# -eq 2 ] || [ $# -eq 3 ]; then
1318                 __var_test "MR" "$LOCALHOST$MR_EXTERNAL_PORT/counter/" $1 "=" $2 $3
1319         else
1320                 ((RES_CONF_FAIL++))
1321                 __print_err "Wrong args to mr_equal, needs two or three args: <sim-param> <target-value> [ timeout ]" $@
1322         fi
1323 }
1324
1325 # Tests if a variable value in the MR stub is greater than a target value and and optional timeout.
1326 # Arg: <variable-name> <target-value> - This test set pass or fail depending on if the variable is
1327 # greater than the target or not.
1328 # Arg: <variable-name> <target-value> <timeout-in-sec>  - This test waits up to the timeout seconds
1329 # before setting pass or fail depending on if the variable value becomes greater than the target
1330 # value or not.
1331 # (Function for test scripts)
1332 mr_greater() {
1333         if [ $# -eq 2 ] || [ $# -eq 3 ]; then
1334                 __var_test "MR" "$LOCALHOST$MR_EXTERNAL_PORT/counter/" $1 "=" $2 $3
1335         else
1336                 ((RES_CONF_FAIL++))
1337                 __print_err "Wrong args to mr_greater, needs two or three args: <sim-param> <target-value> [ timeout ]" $@
1338         fi
1339 }
1340
1341 # Read a variable value from MR sim and send to stdout. Arg: <variable-name>
1342 mr_read() {
1343         echo "$(__do_curl $LOCALHOST$MR_EXTERNAL_PORT/counter/$1)"
1344 }
1345
1346 # Print a variable value from the MR stub.
1347 # arg: <variable-name>
1348 # (Function for test scripts)
1349 mr_print() {
1350         if [ $# != 1 ]; then
1351                 ((RES_CONF_FAIL++))
1352         __print_err "need one arg, <mr-param>" $@
1353                 exit 1
1354         fi
1355         echo -e $BOLD"INFO(${BASH_LINENO[0]}): mrstub, $1 = $(__do_curl $LOCALHOST$MR_EXTERNAL_PORT/counter/$1)"$EBOLD
1356 }
1357
1358