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