From bcb124908ffd1de0c00868838bbac733b881fcb2 Mon Sep 17 00:00:00 2001 From: ss412g Date: Tue, 5 Nov 2019 10:58:10 +0200 Subject: [PATCH] sync R3 content from Azure Change-Id: I16d829baddce1921eefc940534e041422f971499 Signed-off-by: ss412g --- .gitreview | 2 +- .../ConfigurationUpdate_Verify_logs.robot | 56 ---- .../ConfigurationUpdate_prepartations_tests.robot | 33 ++- .../ENDC_Reset_RAN_TO_RIC/Reset_RAN_Found.robot | 41 ++- .../ENDC_Reset_RAN_TO_RIC/Reset_Verify_logs.robot | 50 ---- ...Lost_Connetion_CONNECTING_TO_DISCONNECTED.robot | 2 +- .../Tests/RedButton/RedButton_DISCONNECTED.robot | 2 +- Automation/Tests/Resource/Keywords.robot | 24 ++ Automation/Tests/Resource/resource.robot | 8 - Automation/Tests/Resource/scripts_variables.robot | 4 +- .../Unhappy/Reset_HttpResponse400_wrongstate.robot | 2 +- .../X2_Reset_RAN_TO_RIC/Reset_RAN_Found.robot | 23 ++ .../X2_Reset_RAN_TO_RIC/Reset_Verify_logs.robot | 49 ---- .../X2_Reset_RAN_TO_RIC_Unhappy/Reset_RNIB.robot | 32 ++- .../Reset_Verify_logs.robot | 52 ---- E2Manager/Dockerfile | 1 + E2Manager/app/main.go | 28 +- E2Manager/controllers/nodeb_controller_test.go | 30 +-- E2Manager/controllers/root_controller_test.go | 13 +- ...go => endc_setup_failure_response_converter.go} | 20 +- ... endc_setup_failure_response_converter_test.go} | 5 +- ...rotobuf.go => endc_setup_response_converter.go} | 33 ++- ...st.go => endc_setup_response_converter_test.go} | 5 +- E2Manager/e2mgr-sonar-scanner.properties | 14 + E2Manager/e2pdus/configuration_update.go | 107 ++++++++ E2Manager/e2pdus/configuration_update_test.go | 165 ++++++++++++ E2Manager/e2pdus/x2_setup_requests_test.go | 70 ----- E2Manager/go.mod | 32 ++- E2Manager/go.sum | 47 +++- .../delete_all_request_handler_test.go | 14 +- .../get_nodeb_id_list_request_handler_test.go | 7 +- .../get_nodeb_request_handler_test.go | 6 +- .../httpmsghandlers/setup_request_handler_test.go | 29 ++- .../httpmsghandlers/x2_reset_request_handler.go | 4 +- .../x2_reset_request_handler_test.go | 22 +- .../e2_term_init_notification_handler_test.go | 30 ++- .../enb_load_information_notification_handler.go | 19 +- ...b_load_information_notification_handler_test.go | 4 +- .../endc_configuration_update_handler.go | 45 +--- .../endc_configuration_update_handler_test.go | 14 +- .../rmrmsghandlers/notification_handler.go | 7 - .../setup_response_notification_handler_test.go | 22 +- .../x2_reset_request_notification_handler.go | 27 +- .../x2_reset_request_notification_handler_test.go | 35 ++- .../rmrmsghandlers/x2_reset_response_handler.go | 6 +- .../x2_reset_response_handler_test.go | 34 ++- .../x2enb_configuration_update_handler.go | 39 +-- .../x2enb_configuration_update_handler_test.go | 15 +- E2Manager/httpserver/http_server.go | 9 +- E2Manager/httpserver/http_server_test.go | 29 +++ E2Manager/logger/logger_test.go | 66 ++++- .../endc_setup_failure_response_manager.go | 13 +- .../endc_setup_failure_response_manager_test.go | 66 +++++ E2Manager/managers/endc_setup_response_manager.go | 13 +- .../managers/endc_setup_response_manager_test.go | 59 +++++ .../notificationmanager/notification_manager.go | 2 +- .../notification_manager_test.go | 24 +- .../managers/ran_reconnection_manager_test.go | 28 +- E2Manager/managers/ran_setup_manager.go | 3 +- E2Manager/managers/ran_setup_manager_test.go | 12 +- E2Manager/managers/ran_status_change_manager.go | 3 +- .../x2_setup_failure_response_manager_test.go | 57 ++++ E2Manager/mocks/rmrMessengerMock.go | 4 +- E2Manager/models/e2_request_message_test.go | 11 +- E2Manager/models/notification_request.go | 4 +- E2Manager/models/rmr_message.go | 12 +- .../incoming_request_handler_provider_test.go | 14 +- .../notification_handler_provider.go | 70 +++-- .../notification_handler_provider_test.go | 70 +++-- E2Manager/rNibWriter/rNibWriter.go | 58 ++--- E2Manager/rNibWriter/rNibWriter_test.go | 198 ++------------ E2Manager/rmrCgo/rmrCgoApi.go | 12 +- E2Manager/rmrCgo/rmrCgoApi_test.go | 166 ++++++------ E2Manager/rmrCgo/rmrCgoTypes.go | 3 +- E2Manager/router_test.txt | 3 + E2Manager/services/rmrreceiver/rmr_receiver.go | 11 +- .../services/rmrreceiver/rmr_receiver_test.go | 26 +- E2Manager/services/rmrsender/rmr_sender.go | 9 +- E2Manager/services/rmrsender/rmr_sender_test.go | 16 +- E2Manager/services/rnib_data_service.go | 37 ++- E2Manager/services/rnib_data_service_test.go | 12 +- E2Manager/tests/dataProvider.go | 2 +- E2Manager/tests/utils.go | 59 +++++ tools/xapp_mock/configuration.json | 4 - tools/xapp_mock/main/xapp_mock.go | 109 -------- tools/xapp_mock/resources/router.txt | 4 - tools/{xapp_mock => xappmock}/Dockerfile | 23 +- tools/xappmock/dispatcher/dispatcher.go | 290 +++++++++++++++++++++ tools/xappmock/enums/command_action.go | 25 ++ .../{xapp_mock => xappmock}/frontend/configfile.go | 2 +- .../frontend/jsonDecoder.go | 46 +--- tools/xappmock/go.mod | 5 + tools/xappmock/go.sum | 2 + tools/xappmock/main/xappmock.go | 102 ++++++++ tools/xappmock/models/json_command.go | 35 +++ tools/xappmock/models/process_result.go | 39 +++ tools/xappmock/resources/conf/configuration.json | 24 ++ tools/xappmock/resources/router.txt | 24 ++ tools/{xapp_mock => xappmock}/resp | 0 tools/{xapp_mock => xappmock}/rmr/rmrCgoApi.go | 13 +- tools/{xapp_mock => xappmock}/rmr/rmrCgoTypes.go | 10 +- tools/{xapp_mock => xappmock}/rmr/rmrCgoUtils.go | 24 +- tools/{xapp_mock => xappmock}/rmr/rmrEndPoint.go | 32 +-- tools/{xapp_mock => xappmock}/sender/jsonSender.go | 38 ++- 104 files changed, 2006 insertions(+), 1355 deletions(-) delete mode 100755 Automation/Tests/ConfigurationUpdate/ConfigurationUpdate_Verify_logs.robot delete mode 100644 Automation/Tests/ENDC_Reset_RAN_TO_RIC/Reset_Verify_logs.robot delete mode 100644 Automation/Tests/X2_Reset_RAN_TO_RIC/Reset_Verify_logs.robot delete mode 100644 Automation/Tests/X2_Reset_RAN_TO_RIC_Unhappy/Reset_Verify_logs.robot rename E2Manager/converters/{endc_x2setupFailureResponseToProtobuf.go => endc_setup_failure_response_converter.go} (81%) rename E2Manager/converters/{endc_x2setupFailureResponseToProtobuf_test.go => endc_setup_failure_response_converter_test.go} (93%) rename E2Manager/converters/{endc_x2setupResponseToProtobuf.go => endc_setup_response_converter.go} (93%) rename E2Manager/converters/{endc_x2setupResponseToProtobuf_test.go => endc_setup_response_converter_test.go} (99%) create mode 100644 E2Manager/e2mgr-sonar-scanner.properties create mode 100644 E2Manager/e2pdus/configuration_update.go create mode 100644 E2Manager/e2pdus/configuration_update_test.go create mode 100644 E2Manager/managers/endc_setup_failure_response_manager_test.go create mode 100644 E2Manager/managers/endc_setup_response_manager_test.go create mode 100644 E2Manager/managers/x2_setup_failure_response_manager_test.go create mode 100644 E2Manager/router_test.txt create mode 100644 E2Manager/tests/utils.go delete mode 100644 tools/xapp_mock/configuration.json delete mode 100644 tools/xapp_mock/main/xapp_mock.go delete mode 100644 tools/xapp_mock/resources/router.txt rename tools/{xapp_mock => xappmock}/Dockerfile (66%) create mode 100644 tools/xappmock/dispatcher/dispatcher.go create mode 100644 tools/xappmock/enums/command_action.go rename tools/{xapp_mock => xappmock}/frontend/configfile.go (91%) rename tools/{xapp_mock => xappmock}/frontend/jsonDecoder.go (57%) create mode 100644 tools/xappmock/go.mod create mode 100644 tools/xappmock/go.sum create mode 100644 tools/xappmock/main/xappmock.go create mode 100644 tools/xappmock/models/json_command.go create mode 100644 tools/xappmock/models/process_result.go create mode 100644 tools/xappmock/resources/conf/configuration.json create mode 100644 tools/xappmock/resources/router.txt rename tools/{xapp_mock => xappmock}/resp (100%) rename tools/{xapp_mock => xappmock}/rmr/rmrCgoApi.go (92%) rename tools/{xapp_mock => xappmock}/rmr/rmrCgoTypes.go (97%) rename tools/{xapp_mock => xappmock}/rmr/rmrCgoUtils.go (82%) rename tools/{xapp_mock => xappmock}/rmr/rmrEndPoint.go (64%) rename tools/{xapp_mock => xappmock}/sender/jsonSender.go (75%) diff --git a/.gitreview b/.gitreview index e1956af..b15e8cf 100644 --- a/.gitreview +++ b/.gitreview @@ -2,4 +2,4 @@ host=gerrit.o-ran-sc.org port=29418 project=ric-plt/e2mgr -defaultbranch=master \ No newline at end of file +defaultbranch=PI3 \ No newline at end of file diff --git a/Automation/Tests/ConfigurationUpdate/ConfigurationUpdate_Verify_logs.robot b/Automation/Tests/ConfigurationUpdate/ConfigurationUpdate_Verify_logs.robot deleted file mode 100755 index 9b209b0..0000000 --- a/Automation/Tests/ConfigurationUpdate/ConfigurationUpdate_Verify_logs.robot +++ /dev/null @@ -1,56 +0,0 @@ -############################################################################## -# -# Copyright (c) 2019 AT&T Intellectual Property. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -############################################################################## - - -*** Settings *** -Resource ../Resource/resource.robot -Resource ../Resource/scripts_variables.robot -Library String -Library OperatingSystem -Library Process -Library ../Scripts/find_rmr_message.py - - - -*** Test Cases *** -Verify logs - Confiugration update - Begin Tag Get - ${Configuration}= Grep File ./gnb.log - ${ConfigurationAfterStrip}= Strip String ${Configuration} - Should Be Equal ${ConfigurationAfterStrip} - -Verify logs - Confiugration update - End Tag Get - ${ConfigurationEnd}= Grep File ./gnb.log - ${ConfigurationEndAfterStrip}= Strip String ${ConfigurationEnd} - Should Be Equal ${ConfigurationEndAfterStrip} - -Verify logs - Confiugration update - Ack Tag Begin - ${ConfigurationAck}= Grep File ./gnb.log - ${ConfigurationAckAfter}= Strip String ${ConfigurationAck} - Should Be Equal ${ConfigurationAckAfter} - -Verify logs - Confiugration update - Ack Tag End - ${ConfigurationAckEnd}= Grep File ./gnb.log - ${ConfigurationAckEndAfterStrip}= Strip String ${ConfigurationAckEnd} - Should Be Equal ${ConfigurationAckEndAfterStrip} - -Verify logs - find RIC_ENDC_CONF_UPDATE - ${result} find_rmr_message.verify_logs ${EXECDIR} ${e2mgr_log_filename} ${configurationupdate_message_type} ${Meid_test1} - Should Be Equal As Strings ${result} True -Verify logs - find RIC_ENDC_CONF_UPDATE_ACK - ${result1} find_rmr_message.verify_logs ${EXECDIR} ${e2mgr_log_filename} ${configurationupdate_ack_message_type} ${Meid_test1} - Should Be Equal As Strings ${result1} True diff --git a/Automation/Tests/ConfigurationUpdate/ConfigurationUpdate_prepartations_tests.robot b/Automation/Tests/ConfigurationUpdate/ConfigurationUpdate_prepartations_tests.robot index 9998294..da92133 100644 --- a/Automation/Tests/ConfigurationUpdate/ConfigurationUpdate_prepartations_tests.robot +++ b/Automation/Tests/ConfigurationUpdate/ConfigurationUpdate_prepartations_tests.robot @@ -23,7 +23,10 @@ Resource ../Resource/resource.robot Resource ../Resource/Keywords.robot Library OperatingSystem Library REST ${url} - +Resource ../Resource/scripts_variables.robot +Library String +Library Process +Library ../Scripts/find_rmr_message.py *** Test Cases *** @@ -41,8 +44,32 @@ Prepare logs for tests Remove log files Save logs - - +Verify logs - Confiugration update - Begin Tag Get + ${Configuration}= Grep File ./${gnb_log_filename} + ${ConfigurationAfterStrip}= Strip String ${Configuration} + Should Be Equal ${ConfigurationAfterStrip} + +Verify logs - Confiugration update - End Tag Get + ${ConfigurationEnd}= Grep File ./${gnb_log_filename} + ${ConfigurationEndAfterStrip}= Strip String ${ConfigurationEnd} + Should Be Equal ${ConfigurationEndAfterStrip} + +Verify logs - Confiugration update - Ack Tag Begin + ${ConfigurationAck}= Grep File ./${gnb_log_filename} + ${ConfigurationAckAfter}= Strip String ${ConfigurationAck} + Should Be Equal ${ConfigurationAckAfter} + +Verify logs - Confiugration update - Ack Tag End + ${ConfigurationAckEnd}= Grep File ./${gnb_log_filename} + ${ConfigurationAckEndAfterStrip}= Strip String ${ConfigurationAckEnd} + Should Be Equal ${ConfigurationAckEndAfterStrip} + +Verify logs - find RIC_ENDC_CONF_UPDATE + ${result} find_rmr_message.verify_logs ${EXECDIR} ${e2mgr_log_filename} ${configurationupdate_message_type} ${Meid_test1} + Should Be Equal As Strings ${result} True +Verify logs - find RIC_ENDC_CONF_UPDATE_ACK + ${result1} find_rmr_message.verify_logs ${EXECDIR} ${e2mgr_log_filename} ${configurationupdate_ack_message_type} ${Meid_test1} + Should Be Equal As Strings ${result1} True diff --git a/Automation/Tests/ENDC_Reset_RAN_TO_RIC/Reset_RAN_Found.robot b/Automation/Tests/ENDC_Reset_RAN_TO_RIC/Reset_RAN_Found.robot index cb91c0d..e17b18a 100644 --- a/Automation/Tests/ENDC_Reset_RAN_TO_RIC/Reset_RAN_Found.robot +++ b/Automation/Tests/ENDC_Reset_RAN_TO_RIC/Reset_RAN_Found.robot @@ -23,19 +23,25 @@ Resource ../Resource/Keywords.robot Library OperatingSystem Library Collections Library REST ${url} - - - +Resource ../Resource/scripts_variables.robot +Library String +Library Process +Library ../Scripts/find_rmr_message.py +Library ../Scripts/find_error_script.py *** Test Cases *** Prepare Ran in Connected connectionStatus - Post Request setup node b endc-setup +# Post Request setup node b endc-setup + Set Headers ${header} + POST /v1/nodeb/endc-setup ${json} Integer response status 204 Sleep 1s - GET /v1/nodeb/test2 +# GET /v1/nodeb/test2 + GET /v1/nodeb/test1 Integer response status 200 - String response body ranName test2 +# String response body ranName test2 + String response body ranName test1 String response body connectionStatus CONNECTED Run Reset from RAN @@ -46,3 +52,26 @@ Prepare logs for tests Remove log files Save logs +#Verify logs - Reset Sent by e2adapter +# ${result} find_error_script.find_error ${EXECDIR} ${e2adapter_log_filename} ${E2ADAPTER_Setup_Resp} +# Should Be Equal As Strings ${result} True + +Verify logs - Reset Sent by simulator + ${Reset}= Grep File ./${gnb_log_filename} ResetRequest has been sent + Should Be Equal ${Reset} gnbe2_simu: ResetRequest has been sent + +Verify logs - e2mgr logs - messege sent + ${result} find_rmr_message.verify_logs ${EXECDIR} ${e2mgr_log_filename} ${RIC_X2_RESET_REQ_message_type} ${Meid_test1} + Should Be Equal As Strings ${result} True + +Verify logs - e2mgr logs - messege received + ${result} find_rmr_message.verify_logs ${EXECDIR} ${e2mgr_log_filename} ${RIC_X2_RESET_RESP_message_type} ${Meid_test1} + Should Be Equal As Strings ${result} True + +RAN Restarted messege sent + ${result} find_rmr_message.verify_logs ${EXECDIR} ${e2mgr_log_filename} ${RAN_RESTARTED_message_type} ${Meid_test1} + Should Be Equal As Strings ${result} True + +RSM RESOURCE STATUS REQUEST message not sent + ${result} find_rmr_message.verify_logs ${EXECDIR} ${rsm_log_filename} ${RIC_RES_STATUS_REQ_message_type_successfully_sent} ${RAN_NAME_test2} + Should Be Equal As Strings ${result} False diff --git a/Automation/Tests/ENDC_Reset_RAN_TO_RIC/Reset_Verify_logs.robot b/Automation/Tests/ENDC_Reset_RAN_TO_RIC/Reset_Verify_logs.robot deleted file mode 100644 index e844ccf..0000000 --- a/Automation/Tests/ENDC_Reset_RAN_TO_RIC/Reset_Verify_logs.robot +++ /dev/null @@ -1,50 +0,0 @@ -############################################################################## -# -# Copyright (c) 2019 AT&T Intellectual Property. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -############################################################################## - - -*** Settings *** -Resource ../Resource/scripts_variables.robot -Resource ../Resource/Keywords.robot -Library String -Library OperatingSystem -Library Process -Library ../Scripts/find_rmr_message.py -Library ../Scripts/find_error_script.py - - - -*** Test Cases *** -Verify logs - Reset Sent by e2adapter - ${result} find_error_script.find_error ${EXECDIR} ${e2adapter_log_filename} ${E2ADAPTER_Setup_Resp} - Should Be Equal As Strings ${result} True - -Verify logs - e2mgr logs - messege sent - ${result} find_rmr_message.verify_logs ${EXECDIR} ${e2mgr_log_filename} ${RIC_X2_RESET_REQ_message_type} ${Meid_test1} - Should Be Equal As Strings ${result} True - -Verify logs - e2mgr logs - messege received - ${result} find_rmr_message.verify_logs ${EXECDIR} ${e2mgr_log_filename} ${RIC_X2_RESET_RESP_message_type} ${Meid_test1} - Should Be Equal As Strings ${result} True - -RAN Restarted messege sent - ${result} find_rmr_message.verify_logs ${EXECDIR} ${e2mgr_log_filename} ${RAN_RESTARTED_message_type} ${Meid_test1} - Should Be Equal As Strings ${result} True - -RSM RESOURCE STATUS REQUEST message not sent - ${result} find_rmr_message.verify_logs ${EXECDIR} ${rsm_log_filename} ${RIC_RES_STATUS_REQ_message_type_successfully_sent} ${RAN_NAME_test2} - Should Be Equal As Strings ${result} False \ No newline at end of file diff --git a/Automation/Tests/Lost_Connection/Lost_Connetion_CONNECTING_TO_DISCONNECTED.robot b/Automation/Tests/Lost_Connection/Lost_Connetion_CONNECTING_TO_DISCONNECTED.robot index 02c16cf..c4321d9 100644 --- a/Automation/Tests/Lost_Connection/Lost_Connetion_CONNECTING_TO_DISCONNECTED.robot +++ b/Automation/Tests/Lost_Connection/Lost_Connetion_CONNECTING_TO_DISCONNECTED.robot @@ -48,7 +48,7 @@ Prepare Ran in Connecting connectionStatus Verfiy Disconnected ConnectionStatus - Sleep 1s + Sleep 10s GET /v1/nodeb/test1 Integer response status 200 String response body ranName test1 diff --git a/Automation/Tests/RedButton/RedButton_DISCONNECTED.robot b/Automation/Tests/RedButton/RedButton_DISCONNECTED.robot index d3d8285..ee1a443 100755 --- a/Automation/Tests/RedButton/RedButton_DISCONNECTED.robot +++ b/Automation/Tests/RedButton/RedButton_DISCONNECTED.robot @@ -39,7 +39,7 @@ Pre Condition for Connecting - no E2ADAPTER Prepare Ran in Connecting connectionStatus Post Request setup node b endc-setup Integer response status 204 - Sleep 1s + Sleep 10s GET /v1/nodeb/test2 Integer response status 200 String response body ranName test2 diff --git a/Automation/Tests/Resource/Keywords.robot b/Automation/Tests/Resource/Keywords.robot index e1d6e63..805f37a 100755 --- a/Automation/Tests/Resource/Keywords.robot +++ b/Automation/Tests/Resource/Keywords.robot @@ -46,6 +46,7 @@ Get Request node b enb test2 Remove log files Remove File ${EXECDIR}/${gnb_log_filename} Remove File ${EXECDIR}/${e2mgr_log_filename} + Remove File ${EXECDIR}/${e2t_log_filename} Remove File ${EXECDIR}/${rsm_log_filename} Remove File ${EXECDIR}/${e2adapter_log_filename} @@ -53,6 +54,7 @@ Save logs Sleep 1s Run ${Save_sim_log} Run ${Save_e2mgr_log} + Run ${Save_e2t_log} Run ${Save_rsm_log} Run ${Save_e2adapter_log} @@ -75,6 +77,28 @@ Prepare Simulator For Load Information Should Be Equal As Integers ${result[1]} ${docker_number} Prepare Enviorment + ${starting_timestamp} Evaluate datetime.datetime.now(datetime.timezone.utc).isoformat("T") modules=datetime + ${e2t_log_filename} Evaluate "e2t.${SUITE NAME}.log".replace(" ","-") + ${e2mgr_log_filename} Evaluate "e2mgr.${SUITE NAME}.log".replace(" ","-") + ${gnb_log_filename} Evaluate "gnb.${SUITE NAME}.log".replace(" ","-") + ${rsm_log_filename} Evaluate "rsm.${SUITE NAME}.log".replace(" ","-") + ${e2adapter_log_filename} Evaluate "e2adapter.${SUITE NAME}.log".replace(" ","-") + ${Save_sim_log} Evaluate 'docker logs --since ${starting_timestamp} gnbe2_simu > ${gnb_log_filename}' + ${Save_e2mgr_log} Evaluate 'docker logs --since ${starting_timestamp} e2mgr > ${e2mgr_log_filename}' + ${Save_e2t_log} Evaluate 'docker logs --since ${starting_timestamp} e2 > ${e2t_log_filename}' + ${Save_rsm_log} Evaluate 'docker logs --since ${starting_timestamp} rsm > ${rsm_log_filename}' + ${Save_e2adapter_log} Evaluate 'docker logs --since ${starting_timestamp} e2adapter > ${e2adapter_log_filename}' + Set Suite Variable ${e2t_log_filename} + Set Suite Variable ${e2mgr_log_filename} + Set Suite Variable ${gnb_log_filename} + Set Suite Variable ${rsm_log_filename} + Set Suite Variable ${e2adapter_log_filename} + Set Suite Variable ${Save_sim_log} + Set Suite Variable ${Save_e2mgr_log} + Set Suite Variable ${Save_e2t_log} + Set Suite Variable ${Save_rsm_log} + Set Suite Variable ${Save_e2adapter_log} + ${flush} cleanup_db.flush Should Be Equal As Strings ${flush} True Run And Return Rc And Output ${stop_simu} diff --git a/Automation/Tests/Resource/resource.robot b/Automation/Tests/Resource/resource.robot index 3fdee76..68262fd 100755 --- a/Automation/Tests/Resource/resource.robot +++ b/Automation/Tests/Resource/resource.robot @@ -52,15 +52,7 @@ ${restart_simu} docker restart gnbe2_simu ${start_e2} docker start e2 ${stop_docker_e2} docker stop e2 ${Run_Config} docker exec gnbe2_simu pkill gnbe2_simu -INT -${Save_sim_log} docker logs gnbe2_simu > gnb.log -${Save_e2mgr_log} docker logs e2mgr > e2mgr.log -${Save_rsm_log} docker logs rsm > rsm.log -${Save_e2adapter_log} docker logs e2adapter > e2adapter.log ${403_reset_message} "Activity X2_RESET rejected. RAN current state DISCONNECTED does not allow its execution " -${e2mgr_log_filename} e2mgr.log -${gnb_log_filename} gnb.log -${rsm_log_filename} rsm.log -${e2adapter_log_filename} e2adapter.log diff --git a/Automation/Tests/Resource/scripts_variables.robot b/Automation/Tests/Resource/scripts_variables.robot index 4839304..1d33db6 100644 --- a/Automation/Tests/Resource/scripts_variables.robot +++ b/Automation/Tests/Resource/scripts_variables.robot @@ -29,7 +29,9 @@ ${RAN_CONNECTED_message_type} MType: 1200 ${RAN_RESTARTED_message_type} MType: 1210 ${RIC_X2_RESET_REQ_message_type} MType: 10070 ${RIC_X2_RESET_RESP_message_type} MType: 10070 -${failed_to_retrieve_nodeb_message} failed to retrieve nodeB entity. RanName: test1. +#${failed_to_retrieve_nodeb_message} failed to retrieve nodeB entity. RanName: test1. +#{#RanReconnectionManager.ReconnectRan - RAN name: test1 - Failed fetching RAN from rNib. Error: dial tcp 172.17.0.2:637 #9: i/o timeout" +${failed_to_retrieve_nodeb_message} RAN name: test1 - Failed fetching RAN from rNib ${first_retry_to_retrieve_from_db} RnibDataService.retry - retrying 1 GetNodeb ${third_retry_to_retrieve_from_db} RnibDataService.retry - after 3 attempts of GetNodeb ${RIC_RES_STATUS_REQ_message_type_successfully_sent} Message type: 10090 - Successfully sent RMR message diff --git a/Automation/Tests/Unhappy/Reset_HttpResponse400_wrongstate.robot b/Automation/Tests/Unhappy/Reset_HttpResponse400_wrongstate.robot index f08eb73..ae44bc7 100644 --- a/Automation/Tests/Unhappy/Reset_HttpResponse400_wrongstate.robot +++ b/Automation/Tests/Unhappy/Reset_HttpResponse400_wrongstate.robot @@ -38,7 +38,7 @@ Pre Condition for Connecting - no simu Reset - 400 http - 403 wrong state Post Request setup node b x-2 Integer response status 204 - Sleep 1s + Sleep 10s GET /v1/nodeb/test1 String response body connectionStatus DISCONNECTED Set Headers ${header} diff --git a/Automation/Tests/X2_Reset_RAN_TO_RIC/Reset_RAN_Found.robot b/Automation/Tests/X2_Reset_RAN_TO_RIC/Reset_RAN_Found.robot index bed3ea1..bc6a588 100644 --- a/Automation/Tests/X2_Reset_RAN_TO_RIC/Reset_RAN_Found.robot +++ b/Automation/Tests/X2_Reset_RAN_TO_RIC/Reset_RAN_Found.robot @@ -23,6 +23,10 @@ Resource ../Resource/Keywords.robot Library OperatingSystem Library Collections Library REST ${url} +Resource ../Resource/scripts_variables.robot +Library String +Library Process +Library ../Scripts/find_rmr_message.py @@ -46,3 +50,22 @@ Prepare logs for tests Remove log files Save logs +Verify logs - Reset Sent by simulator + ${Reset}= Grep File ./${gnb_log_filename} ResetRequest has been sent + Should Be Equal ${Reset} gnbe2_simu: ResetRequest has been sent + +Verify logs - e2mgr logs - messege sent + ${result} find_rmr_message.verify_logs ${EXECDIR} ${e2mgr_log_filename} ${RIC_X2_RESET_REQ_message_type} ${Meid_test1} + Should Be Equal As Strings ${result} True + +Verify logs - e2mgr logs - messege received + ${result} find_rmr_message.verify_logs ${EXECDIR} ${e2mgr_log_filename} ${RIC_X2_RESET_RESP_message_type} ${Meid_test1} + Should Be Equal As Strings ${result} True + +RAN Restarted messege sent + ${result} find_rmr_message.verify_logs ${EXECDIR} ${e2mgr_log_filename} ${RAN_RESTARTED_message_type} ${Meid_test1} + Should Be Equal As Strings ${result} True + +RSM RESOURCE STATUS REQUEST message sent + ${result} find_rmr_message.verify_logs ${EXECDIR} ${rsm_log_filename} ${RIC_RES_STATUS_REQ_message_type_successfully_sent} ${RAN_NAME_test1} + Should Be Equal As Strings ${result} True diff --git a/Automation/Tests/X2_Reset_RAN_TO_RIC/Reset_Verify_logs.robot b/Automation/Tests/X2_Reset_RAN_TO_RIC/Reset_Verify_logs.robot deleted file mode 100644 index 878d3f8..0000000 --- a/Automation/Tests/X2_Reset_RAN_TO_RIC/Reset_Verify_logs.robot +++ /dev/null @@ -1,49 +0,0 @@ -############################################################################## -# -# Copyright (c) 2019 AT&T Intellectual Property. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -############################################################################## - - -*** Settings *** -Resource ../Resource/scripts_variables.robot -Resource ../Resource/Keywords.robot -Library String -Library OperatingSystem -Library Process -Library ../Scripts/find_rmr_message.py - - - -*** Test Cases *** -Verify logs - Reset Sent by simulator - ${Reset}= Grep File ./gnb.log ResetRequest has been sent - Should Be Equal ${Reset} gnbe2_simu: ResetRequest has been sent - -Verify logs - e2mgr logs - messege sent - ${result} find_rmr_message.verify_logs ${EXECDIR} ${e2mgr_log_filename} ${RIC_X2_RESET_REQ_message_type} ${Meid_test1} - Should Be Equal As Strings ${result} True - -Verify logs - e2mgr logs - messege received - ${result} find_rmr_message.verify_logs ${EXECDIR} ${e2mgr_log_filename} ${RIC_X2_RESET_RESP_message_type} ${Meid_test1} - Should Be Equal As Strings ${result} True - -RAN Restarted messege sent - ${result} find_rmr_message.verify_logs ${EXECDIR} ${e2mgr_log_filename} ${RAN_RESTARTED_message_type} ${Meid_test1} - Should Be Equal As Strings ${result} True - -RSM RESOURCE STATUS REQUEST message sent - ${result} find_rmr_message.verify_logs ${EXECDIR} ${rsm_log_filename} ${RIC_RES_STATUS_REQ_message_type_successfully_sent} ${RAN_NAME_test1} - Should Be Equal As Strings ${result} True \ No newline at end of file diff --git a/Automation/Tests/X2_Reset_RAN_TO_RIC_Unhappy/Reset_RNIB.robot b/Automation/Tests/X2_Reset_RAN_TO_RIC_Unhappy/Reset_RNIB.robot index 13ef687..69e7b98 100644 --- a/Automation/Tests/X2_Reset_RAN_TO_RIC_Unhappy/Reset_RNIB.robot +++ b/Automation/Tests/X2_Reset_RAN_TO_RIC_Unhappy/Reset_RNIB.robot @@ -23,9 +23,12 @@ Resource ../Resource/Keywords.robot Library OperatingSystem Library Collections Library REST ${url} - - - +Resource ../Resource/scripts_variables.robot +Library String +Library Process +Library ../Scripts/find_rmr_message.py +Library ../Scripts/find_error_script.py +Suite Teardown Start Dbass with 4 dockers *** Test Cases *** @@ -45,9 +48,30 @@ Stop RNIB Run Reset from RAN Run ${Run_Config} - Sleep 1s + Sleep 60s Prepare logs for tests Remove log files Save logs +Verify logs - Reset Sent by simulator + ${Reset}= Grep File ./${gnb_log_filename} ResetRequest has been sent + Should Be Equal ${Reset} gnbe2_simu: ResetRequest has been sent + +Verify logs for restart received + ${result} find_rmr_message.verify_logs ${EXECDIR} ${e2mgr_log_filename} ${RIC_X2_RESET_REQ_message_type} ${Meid_test1} + Should Be Equal As Strings ${result} True + +Verify for error on retrying + ${result} find_error_script.find_error ${EXECDIR} ${e2mgr_log_filename} ${failed_to_retrieve_nodeb_message} + Should Be Equal As Strings ${result} True + + +*** Keywords *** +Start Dbass with 4 dockers + Run And Return Rc And Output ${dbass_remove} + Run And Return Rc And Output ${dbass_start} + Sleep 5s + ${result}= Run And Return Rc And Output ${docker_command} + Should Be Equal As Integers ${result[1]} ${docker_number-1} + diff --git a/Automation/Tests/X2_Reset_RAN_TO_RIC_Unhappy/Reset_Verify_logs.robot b/Automation/Tests/X2_Reset_RAN_TO_RIC_Unhappy/Reset_Verify_logs.robot deleted file mode 100644 index eae2016..0000000 --- a/Automation/Tests/X2_Reset_RAN_TO_RIC_Unhappy/Reset_Verify_logs.robot +++ /dev/null @@ -1,52 +0,0 @@ -############################################################################## -# -# Copyright (c) 2019 AT&T Intellectual Property. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -############################################################################## - - -*** Settings *** -Resource ../Resource/scripts_variables.robot -Library String -Library OperatingSystem -Library Process -Resource ../Resource/Keywords.robot -Library ../Scripts/find_rmr_message.py -Library ../Scripts/find_error_script.py -Test Teardown Start Dbass with 4 dockers - - - -*** Test Cases *** -Verify logs - Reset Sent by simulator - ${Reset}= Grep File ./gnb.log ResetRequest has been sent - Should Be Equal ${Reset} gnbe2_simu: ResetRequest has been sent - -Verify logs for restart received - ${result} find_rmr_message.verify_logs ${EXECDIR} ${e2mgr_log_filename} ${RIC_X2_RESET_REQ_message_type} ${Meid_test1} - Should Be Equal As Strings ${result} True - -Verify for error on retrying - ${result} find_error_script.find_error ${EXECDIR} ${e2mgr_log_filename} ${failed_to_retrieve_nodeb_message} - Should Be Equal As Strings ${result} True - - -*** Keywords *** -Start Dbass with 4 dockers - Run And Return Rc And Output ${dbass_remove} - Run And Return Rc And Output ${dbass_start} - ${result}= Run And Return Rc And Output ${docker_command} - Should Be Equal As Integers ${result[1]} ${docker_number-1} - Sleep 5s diff --git a/E2Manager/Dockerfile b/E2Manager/Dockerfile index ee35ef4..10a6960 100644 --- a/E2Manager/Dockerfile +++ b/E2Manager/Dockerfile @@ -41,6 +41,7 @@ ENV LD_LIBRARY_PATH=/usr/local/lib # Setting allocfreetrace=1 causes every allocation to be profiled and a stack trace printed on each object's allocation and free. ENV GODEBUG=cgocheck=2,clobberfree=1,gcstoptheworld=2,allocfreetrace=0 ENV RIC_ID="bbbccc-abcd0e/20" +ENV RMR_SEED_RT=/opt/E2Manager/router_test.txt RUN go test ./... FROM ubuntu:16.04 diff --git a/E2Manager/app/main.go b/E2Manager/app/main.go index ce41eeb..4ac9ac6 100644 --- a/E2Manager/app/main.go +++ b/E2Manager/app/main.go @@ -20,7 +20,6 @@ package main import ( "e2mgr/configuration" "e2mgr/controllers" - "e2mgr/converters" "e2mgr/httpserver" "e2mgr/logger" "e2mgr/managers" @@ -34,12 +33,11 @@ import ( "e2mgr/services/rmrsender" "fmt" "gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/reader" + "gerrit.o-ran-sc.org/r/ric-plt/sdlgo" "os" "strconv" ) -const MAX_RNIB_POOL_INSTANCES = 4 - func main() { config := configuration.ParseConfiguration() logLevel, _ := logger.LogLevelTokenToLevel(config.Logging.LogLevel) @@ -48,32 +46,28 @@ func main() { fmt.Printf("#app.main - failed to initialize logger, error: %s", err) os.Exit(1) } - rNibWriter.Init("e2Manager", MAX_RNIB_POOL_INSTANCES) - defer rNibWriter.Close() - reader.Init("e2Manager", MAX_RNIB_POOL_INSTANCES) - defer reader.Close() - rnibDataService := services.NewRnibDataService(logger, config, reader.GetRNibReader, rNibWriter.GetRNibWriter) + db := sdlgo.NewDatabase() + sdl := sdlgo.NewSdlInstance("e2Manager", db) + defer sdl.Close() + rnibDataService := services.NewRnibDataService(logger, config, reader.GetRNibReader(sdl), rNibWriter.GetRNibWriter( sdl)) var msgImpl *rmrCgo.Context rmrMessenger := msgImpl.Init("tcp:"+strconv.Itoa(config.Rmr.Port), config.Rmr.MaxMsgSize, 0, logger) rmrSender := rmrsender.NewRmrSender(logger, rmrMessenger) ranSetupManager := managers.NewRanSetupManager(logger, rmrSender, rnibDataService) - ranReconnectionManager := managers.NewRanReconnectionManager(logger, config, rnibDataService, ranSetupManager) - ranStatusChangeManager := managers.NewRanStatusChangeManager(logger, rmrSender) - x2SetupResponseConverter := converters.NewX2SetupResponseConverter(logger) - x2SetupResponseManager := managers.NewX2SetupResponseManager(x2SetupResponseConverter) - x2SetupFailureResponseConverter := converters.NewX2SetupFailureResponseConverter(logger) - x2SetupFailureResponseManager := managers.NewX2SetupFailureResponseManager(x2SetupFailureResponseConverter) - rmrNotificationHandlerProvider := rmrmsghandlerprovider.NewNotificationHandlerProvider(logger, rnibDataService, ranReconnectionManager, ranStatusChangeManager, rmrSender, x2SetupResponseManager, x2SetupFailureResponseManager) + rmrNotificationHandlerProvider := rmrmsghandlerprovider.NewNotificationHandlerProvider() + rmrNotificationHandlerProvider.Init(logger, config, rnibDataService, rmrSender, ranSetupManager) notificationManager := notificationmanager.NewNotificationManager(logger, rmrNotificationHandlerProvider) rmrReceiver := rmrreceiver.NewRmrReceiver(logger, rmrMessenger, notificationManager) - defer (*rmrMessenger).Close() + defer rmrMessenger.Close() go rmrReceiver.ListenAndHandle() httpMsgHandlerProvider := httpmsghandlerprovider.NewIncomingRequestHandlerProvider(logger, rmrSender, config, rnibDataService, ranSetupManager) rootController := controllers.NewRootController(rnibDataService) nodebController := controllers.NewNodebController(logger, httpMsgHandlerProvider) - httpserver.Run(config.Http.Port, rootController, nodebController) + _ = httpserver.Run(logger, config.Http.Port, rootController, nodebController) } + + diff --git a/E2Manager/controllers/nodeb_controller_test.go b/E2Manager/controllers/nodeb_controller_test.go index f0c26e6..fa4eccb 100644 --- a/E2Manager/controllers/nodeb_controller_test.go +++ b/E2Manager/controllers/nodeb_controller_test.go @@ -27,7 +27,6 @@ import ( "e2mgr/mocks" "e2mgr/models" "e2mgr/providers/httpmsghandlerprovider" - "e2mgr/rNibWriter" "e2mgr/rmrCgo" "e2mgr/services" "e2mgr/services/rmrsender" @@ -36,7 +35,6 @@ import ( "fmt" "gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/common" "gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/entities" - "gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/reader" "github.com/gorilla/mux" "github.com/pkg/errors" "github.com/stretchr/testify/assert" @@ -70,14 +68,10 @@ func setupControllerTest(t *testing.T) (*NodebController, *mocks.RnibReaderMock, rmrMessengerMock := &mocks.RmrMessengerMock{} readerMock := &mocks.RnibReaderMock{} - readerProvider := func() reader.RNibReader { - return readerMock - } + writerMock := &mocks.RnibWriterMock{} - writerProvider := func() rNibWriter.RNibWriter { - return writerMock - } - rnibDataService := services.NewRnibDataService(log, config, readerProvider, writerProvider) + + rnibDataService := services.NewRnibDataService(log, config, readerMock, writerMock) rmrSender := getRmrSender(rmrMessengerMock, log) ranSetupManager := managers.NewRanSetupManager(log, rmrSender, rnibDataService) handlerProvider := httpmsghandlerprovider.NewIncomingRequestHandlerProvider(log, rmrSender, config, rnibDataService, ranSetupManager) @@ -115,8 +109,8 @@ func TestX2SetupSuccess(t *testing.T) { writerMock.On("UpdateNodebInfo", nbUpdated).Return(nil) payload := e2pdus.PackedX2setupRequest - xaction := []byte(ranName) - msg := rmrCgo.NewMBuf(rmrCgo.RIC_X2_SETUP_REQ, len(payload), ranName, &payload, &xaction) + var xAction[]byte + msg := rmrCgo.NewMBuf(rmrCgo.RIC_X2_SETUP_REQ, len(payload), ranName, &payload, &xAction) rmrMessengerMock.On("SendMsg", mock.Anything).Return(msg, nil) @@ -143,8 +137,8 @@ func TestEndcSetupSuccess(t *testing.T) { writerMock.On("UpdateNodebInfo", nbUpdated).Return(nil) payload := e2pdus.PackedEndcX2setupRequest - xaction := []byte(ranName) - msg := rmrCgo.NewMBuf(rmrCgo.RIC_ENDC_X2_SETUP_REQ, len(payload), ranName, &payload, &xaction) + var xAction[]byte + msg := rmrCgo.NewMBuf(rmrCgo.RIC_ENDC_X2_SETUP_REQ, len(payload), ranName, &payload, &xAction) rmrMessengerMock.On("SendMsg", mock.Anything).Return(msg, nil) @@ -377,8 +371,8 @@ func TestX2ResetHandleSuccessfulRequestedCause(t *testing.T) { ranName := "test1" payload := []byte{0x00, 0x07, 0x00, 0x08, 0x00, 0x00, 0x01, 0x00, 0x05, 0x40, 0x01, 0x40} - xaction := []byte(ranName) - msg := rmrCgo.NewMBuf(rmrCgo.RIC_X2_RESET, len(payload), ranName, &payload, &xaction) + var xAction[]byte + msg := rmrCgo.NewMBuf(rmrCgo.RIC_X2_RESET, len(payload), ranName, &payload, &xAction) rmrMessengerMock.On("SendMsg", msg, mock.Anything).Return(msg, nil) writer := httptest.NewRecorder() @@ -403,8 +397,8 @@ func TestX2ResetHandleSuccessfulRequestedDefault(t *testing.T) { ranName := "test1" // o&m intervention payload := []byte{0x00, 0x07, 0x00, 0x08, 0x00, 0x00, 0x01, 0x00, 0x05, 0x40, 0x01, 0x64} - xaction := []byte(ranName) - msg := rmrCgo.NewMBuf(rmrCgo.RIC_X2_RESET, len(payload), ranName, &payload, &xaction) + var xAction[]byte + msg := rmrCgo.NewMBuf(rmrCgo.RIC_X2_RESET, len(payload), ranName, &payload, &xAction) rmrMessengerMock.On("SendMsg", msg).Return(msg, nil) writer := httptest.NewRecorder() @@ -478,5 +472,5 @@ func TestHandleErrorResponse(t *testing.T) { func getRmrSender(rmrMessengerMock *mocks.RmrMessengerMock, log *logger.Logger) *rmrsender.RmrSender { rmrMessenger := rmrCgo.RmrMessenger(rmrMessengerMock) rmrMessengerMock.On("Init", tests.GetPort(), tests.MaxMsgSize, tests.Flags, log).Return(&rmrMessenger) - return rmrsender.NewRmrSender(log, &rmrMessenger) + return rmrsender.NewRmrSender(log, rmrMessenger) } diff --git a/E2Manager/controllers/root_controller_test.go b/E2Manager/controllers/root_controller_test.go index 7001eef..4945ae7 100644 --- a/E2Manager/controllers/root_controller_test.go +++ b/E2Manager/controllers/root_controller_test.go @@ -21,12 +21,10 @@ import ( "e2mgr/configuration" "e2mgr/logger" "e2mgr/mocks" - "e2mgr/rNibWriter" "e2mgr/services" "fmt" "gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/common" "gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/entities" - "gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/reader" "github.com/stretchr/testify/assert" "net" "net/http" @@ -41,13 +39,10 @@ func setupNodebControllerTest(t *testing.T) (services.RNibDataService, *mocks.Rn } config := &configuration.Configuration{RnibRetryIntervalMs: 10, MaxRnibConnectionAttempts: 3} readerMock := &mocks.RnibReaderMock{} - rnibReaderProvider := func() reader.RNibReader { - return readerMock - } - rnibWriterProvider := func() rNibWriter.RNibWriter { - return &mocks.RnibWriterMock{} - } - rnibDataService := services.NewRnibDataService(logger, config, rnibReaderProvider, rnibWriterProvider) + + writerMock := &mocks.RnibWriterMock{} + + rnibDataService := services.NewRnibDataService(logger, config, readerMock, writerMock) return rnibDataService, readerMock } diff --git a/E2Manager/converters/endc_x2setupFailureResponseToProtobuf.go b/E2Manager/converters/endc_setup_failure_response_converter.go similarity index 81% rename from E2Manager/converters/endc_x2setupFailureResponseToProtobuf.go rename to E2Manager/converters/endc_setup_failure_response_converter.go index 3283f0a..b03b67e 100644 --- a/E2Manager/converters/endc_x2setupFailureResponseToProtobuf.go +++ b/E2Manager/converters/endc_setup_failure_response_converter.go @@ -23,11 +23,27 @@ package converters // #include import "C" import ( + "e2mgr/e2pdus" "e2mgr/logger" "gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/entities" "unsafe" ) +type EndcSetupFailureResponseConverter struct { + logger *logger.Logger +} + +type IEndcSetupFailureResponseConverter interface { + UnpackEndcSetupFailureResponseAndExtract(packedBuf []byte) (*entities.SetupFailure, error) +} + +func NewEndcSetupFailureResponseConverter(logger *logger.Logger) *EndcSetupFailureResponseConverter { + return &EndcSetupFailureResponseConverter{ + logger: logger, + } +} + + // Populate and return the EN-DC/X2 setup response failure structure with data from the pdu func endcX2SetupFailureResponseToProtobuf(pdu *C.E2AP_PDU_t) (*entities.SetupFailure, error) { setupFailure := entities.SetupFailure{} @@ -68,8 +84,8 @@ func endcX2SetupFailureResponseToProtobuf(pdu *C.E2AP_PDU_t) (*entities.SetupFai return &setupFailure, nil } -func UnpackEndcX2SetupFailureResponseAndExtract(logger *logger.Logger, allocationBufferSize int, packedBufferSize int, packedBuf []byte, maxMessageBufferSize int) (*entities.SetupFailure, error) { - pdu, err := UnpackX2apPdu(logger, allocationBufferSize, packedBufferSize, packedBuf, maxMessageBufferSize) +func (c *EndcSetupFailureResponseConverter) UnpackEndcSetupFailureResponseAndExtract(packedBuf []byte) (*entities.SetupFailure, error) { + pdu, err := UnpackX2apPdu(c.logger, e2pdus.MaxAsn1CodecAllocationBufferSize, len(packedBuf), packedBuf, e2pdus.MaxAsn1CodecMessageBufferSize) if err != nil { return nil, err } diff --git a/E2Manager/converters/endc_x2setupFailureResponseToProtobuf_test.go b/E2Manager/converters/endc_setup_failure_response_converter_test.go similarity index 93% rename from E2Manager/converters/endc_x2setupFailureResponseToProtobuf_test.go rename to E2Manager/converters/endc_setup_failure_response_converter_test.go index cdd2f25..279df79 100644 --- a/E2Manager/converters/endc_x2setupFailureResponseToProtobuf_test.go +++ b/E2Manager/converters/endc_setup_failure_response_converter_test.go @@ -18,7 +18,6 @@ package converters import ( - "e2mgr/e2pdus" "e2mgr/logger" "fmt" "gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/entities" @@ -74,6 +73,8 @@ func TestUnpackEndcX2SetupFailureResponseAndExtract(t *testing.T) { /**** shares the same code with x2setup failure response to protobuf ****/ } + converter := NewEndcSetupFailureResponseConverter(logger) + for _, tc := range testCases { t.Run(tc.packedPdu, func(t *testing.T) { @@ -83,7 +84,7 @@ func TestUnpackEndcX2SetupFailureResponseAndExtract(t *testing.T) { t.Errorf("convert inputPayloadAsStr to payloadAsByte. Error: %v\n", err) } - response, err := UnpackEndcX2SetupFailureResponseAndExtract(logger, e2pdus.MaxAsn1CodecAllocationBufferSize /*allocation buffer*/, len(payload), payload, e2pdus.MaxAsn1CodecMessageBufferSize /*message buffer*/) + response, err := converter.UnpackEndcSetupFailureResponseAndExtract(payload) if err != nil { if tc.failure == nil { diff --git a/E2Manager/converters/endc_x2setupResponseToProtobuf.go b/E2Manager/converters/endc_setup_response_converter.go similarity index 93% rename from E2Manager/converters/endc_x2setupResponseToProtobuf.go rename to E2Manager/converters/endc_setup_response_converter.go index 01e901a..6cdc003 100644 --- a/E2Manager/converters/endc_x2setupResponseToProtobuf.go +++ b/E2Manager/converters/endc_setup_response_converter.go @@ -23,10 +23,10 @@ package converters // #include import "C" import ( + "e2mgr/e2pdus" "e2mgr/logger" "fmt" "gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/entities" -// "github.com/pkg/errors" "unsafe" ) @@ -36,6 +36,20 @@ const ( maxnoofNrCellBands = 32 ) +type EndcSetupResponseConverter struct { + logger *logger.Logger +} + +type IEndcSetupResponseConverter interface { + UnpackEndcSetupResponseAndExtract(packedBuf []byte) (*entities.GlobalNbId, *entities.Gnb, error) +} + +func NewEndcSetupResponseConverter(logger *logger.Logger) *EndcSetupResponseConverter { + return &EndcSetupResponseConverter{ + logger: logger, + } +} + func getNRFreqInfo(freqInfo C.NRFreqInfo_t) (*entities.NrFrequencyInfo, error) { var info *entities.NrFrequencyInfo info = &entities.NrFrequencyInfo{NrArFcn: uint64(freqInfo.nRARFCN)} @@ -57,7 +71,7 @@ func getNRFreqInfo(freqInfo C.NRFreqInfo_t) (*entities.NrFrequencyInfo, error) { frequencyBand := &entities.FrequencyBandItem{NrFrequencyBand: uint32(freqBandNrItem.freqBandIndicatorNr)} if freqBandNrItem.supportedSULBandList.list.count > 0 && freqBandNrItem.supportedSULBandList.list.count <= maxnoofNrCellBands { - count:= int(freqBandNrItem.supportedSULBandList.list.count) + count := int(freqBandNrItem.supportedSULBandList.list.count) supportedSULBandList_slice := (*[1 << 30]*C.SupportedSULFreqBandItem_t)(unsafe.Pointer(freqBandNrItem.supportedSULBandList.list.array))[:count:count] for _, supportedSULFreqBandItem := range supportedSULBandList_slice { frequencyBand.SupportedSulBands = append(frequencyBand.SupportedSulBands, uint32(supportedSULFreqBandItem.freqBandIndicatorNr)) @@ -162,7 +176,7 @@ func getnRNeighbourInfo(neighbour_Information *C.NRNeighbour_Information_t) ([]* var neighbours []*entities.NrNeighbourInformation if neighbour_Information != nil && neighbour_Information.list.count > 0 && neighbour_Information.list.count <= maxofNRNeighbours { - count:=int(neighbour_Information.list.count) + count := int(neighbour_Information.list.count) neighbour_Information_slice := (*[1 << 30]*C.NRNeighbour_Information__Member)(unsafe.Pointer(neighbour_Information.list.array))[:count:count] for _, member := range neighbour_Information_slice { info := &entities.NrNeighbourInformation{NrPci: uint32(member.nrpCI)} @@ -203,7 +217,7 @@ func getServedNRCells(servedNRcellsManagementList *C.ServedNRcellsENDCX2Manageme var servedNRCells []*entities.ServedNRCell if servedNRcellsManagementList != nil && servedNRcellsManagementList.list.count > 0 && servedNRcellsManagementList.list.count <= maxCellinengNB { - count :=int(servedNRcellsManagementList.list.count) + count := int(servedNRcellsManagementList.list.count) servedNRcellsENDCX2ManagementList__Member_slice := (*[1 << 30]*C.ServedNRcellsENDCX2ManagementList__Member)(unsafe.Pointer(servedNRcellsManagementList.list.array))[:count:count] for _, servedNRcellsENDCX2ManagementList__Member := range servedNRcellsENDCX2ManagementList__Member_slice { servedNRCellInfo := servedNRcellsENDCX2ManagementList__Member.servedNRCellInfo @@ -223,7 +237,7 @@ func getServedNRCells(servedNRcellsManagementList *C.ServedNRcellsENDCX2Manageme } if servedNRCellInfo.broadcastPLMNs.list.count > 0 && servedNRCellInfo.broadcastPLMNs.list.count <= maxnoofBPLMNs { - count:=int(servedNRCellInfo.broadcastPLMNs.list.count) + count := int(servedNRCellInfo.broadcastPLMNs.list.count) pLMN_Identity_slice := (*[1 << 30]*C.PLMN_Identity_t)(unsafe.Pointer(servedNRCellInfo.broadcastPLMNs.list.array))[:count:count] for _, pLMN_Identity := range pLMN_Identity_slice { servedNRCell.ServedNrCellInformation.ServedPlmns = append(servedNRCell.ServedNrCellInformation.ServedPlmns, fmt.Sprintf("%02x", C.GoBytes(unsafe.Pointer(pLMN_Identity.buf), C.int(pLMN_Identity.size)))) @@ -271,7 +285,7 @@ func endcX2SetupResponseToProtobuf(pdu *C.E2AP_PDU_t) (*entities.GlobalNbId, *en if successfulOutcome != nil && successfulOutcome.value.present == C.SuccessfulOutcome__value_PR_ENDCX2SetupResponse { endcX2SetupResponse := (*C.ENDCX2SetupResponse_t)(unsafe.Pointer(&successfulOutcome.value.choice[0])) if endcX2SetupResponse != nil && endcX2SetupResponse.protocolIEs.list.count > 0 { - count:=int(endcX2SetupResponse.protocolIEs.list.count) + count := int(endcX2SetupResponse.protocolIEs.list.count) endcX2SetupResponse_IEs_slice := (*[1 << 30]*C.ENDCX2SetupResponse_IEs_t)(unsafe.Pointer(endcX2SetupResponse.protocolIEs.list.array))[:count:count] for _, endcX2SetupResponse_IE := range endcX2SetupResponse_IEs_slice { if endcX2SetupResponse_IE.value.present == C.ENDCX2SetupResponse_IEs__value_PR_RespondingNodeType_EndcX2Setup { @@ -280,7 +294,7 @@ func endcX2SetupResponseToProtobuf(pdu *C.E2AP_PDU_t) (*entities.GlobalNbId, *en case C.RespondingNodeType_EndcX2Setup_PR_respond_en_gNB: en_gNB_ENDCX2SetupReqAckIEs_Container := *(**C.ProtocolIE_Container_119P89_t)(unsafe.Pointer(&respondingNodeType.choice[0])) if en_gNB_ENDCX2SetupReqAckIEs_Container != nil && en_gNB_ENDCX2SetupReqAckIEs_Container.list.count > 0 { - count:=int(en_gNB_ENDCX2SetupReqAckIEs_Container.list.count) + count := int(en_gNB_ENDCX2SetupReqAckIEs_Container.list.count) en_gNB_ENDCX2SetupReqAckIEs_slice := (*[1 << 30]*C.En_gNB_ENDCX2SetupReqAckIEs_t)(unsafe.Pointer(en_gNB_ENDCX2SetupReqAckIEs_Container.list.array))[:count:count] for _, en_gNB_ENDCX2SetupReqAckIE := range en_gNB_ENDCX2SetupReqAckIEs_slice { switch en_gNB_ENDCX2SetupReqAckIE.value.present { @@ -315,8 +329,9 @@ func endcX2SetupResponseToProtobuf(pdu *C.E2AP_PDU_t) (*entities.GlobalNbId, *en return globalNbId, gnb, nil } -func UnpackEndcX2SetupResponseAndExtract(logger *logger.Logger, allocationBufferSize int, packedBufferSize int, packedBuf []byte, maxMessageBufferSize int) (*entities.GlobalNbId, *entities.Gnb, error) { - pdu, err := UnpackX2apPdu(logger, allocationBufferSize, packedBufferSize, packedBuf, maxMessageBufferSize) +func (c *EndcSetupResponseConverter) UnpackEndcSetupResponseAndExtract(packedBuf []byte) (*entities.GlobalNbId, *entities.Gnb, error) { + pdu, err := UnpackX2apPdu(c.logger, e2pdus.MaxAsn1CodecAllocationBufferSize, len(packedBuf), packedBuf, e2pdus.MaxAsn1CodecMessageBufferSize) + if err != nil { return nil, nil, err } diff --git a/E2Manager/converters/endc_x2setupResponseToProtobuf_test.go b/E2Manager/converters/endc_setup_response_converter_test.go similarity index 99% rename from E2Manager/converters/endc_x2setupResponseToProtobuf_test.go rename to E2Manager/converters/endc_setup_response_converter_test.go index e3de6b3..62895bd 100644 --- a/E2Manager/converters/endc_x2setupResponseToProtobuf_test.go +++ b/E2Manager/converters/endc_setup_response_converter_test.go @@ -18,7 +18,6 @@ package converters import ( - "e2mgr/e2pdus" "e2mgr/logger" "fmt" "gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/entities" @@ -555,6 +554,8 @@ func TestUnpackEndcX2SetupResponseAndExtract(t *testing.T) { failure: fmt.Errorf("getList for path [successfulOutcome_t ENDCX2SetupResponse protocolIEs_t ProtocolIE_Container_elm RespondingNodeType-EndcX2Setup respond_en_gNB_t ProtocolIE_Container_elm ServedNRcellsENDCX2ManagementList ServedNRcellsENDCX2ManagementList_elm servedNRCellInfo_t nrpCI_t] failed, rc = 1" /*NO_ITEMS*/),}, } + converter := NewEndcSetupResponseConverter(logger) + for _, tc := range testCases { t.Run(tc.packedPdu, func(t *testing.T) { @@ -566,7 +567,7 @@ func TestUnpackEndcX2SetupResponseAndExtract(t *testing.T) { t.Errorf("convert inputPayloadAsStr to payloadAsByte. Error: %v\n", err) } - key, gnb, err := UnpackEndcX2SetupResponseAndExtract(logger, e2pdus.MaxAsn1CodecAllocationBufferSize, len(payload), payload, e2pdus.MaxAsn1CodecMessageBufferSize) + key, gnb, err := converter.UnpackEndcSetupResponseAndExtract(payload) if err != nil { if tc.failure == nil { diff --git a/E2Manager/e2mgr-sonar-scanner.properties b/E2Manager/e2mgr-sonar-scanner.properties new file mode 100644 index 0000000..a0c9ca9 --- /dev/null +++ b/E2Manager/e2mgr-sonar-scanner.properties @@ -0,0 +1,14 @@ +#----- Default SonarQube server +sonar.host.url=http://135.25.121.110:9000 +sonar.projectKey=oran:e2mgr +sonar.projectName=e2mgr +sonar.login=admin +sonar.password=admin +sonar.go.coverage.reportPaths=coverage.txt +#----- Default source code encoding +#sonar.sourceEncoding=UTF-8 +sonar.projectBaseDir=/home/ubuntu/oran_repo/e2mgr/E2Manager/ +sonar.sources=. +sonar.exclusions=**/*_test.go,**/generate_source.go,**/*_generated.go,**/build/**,**/.gogradle/**,**/mocks/**,**/tests/**,**/e2managererrors/**,**/enums/** +sonar.go.golangci-lint.reportPaths=sca.xml + diff --git a/E2Manager/e2pdus/configuration_update.go b/E2Manager/e2pdus/configuration_update.go new file mode 100644 index 0000000..032c6cf --- /dev/null +++ b/E2Manager/e2pdus/configuration_update.go @@ -0,0 +1,107 @@ +/******************************************************************************* + * + * Copyright (c) 2019 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + *******************************************************************************/ +package e2pdus + +// #cgo CFLAGS: -I../asn1codec/inc/ -I../asn1codec/e2ap_engine/ +// #cgo LDFLAGS: -L ../asn1codec/lib/ -L../asn1codec/e2ap_engine/ -le2ap_codec -lasncodec +// #include +import "C" +import ( + "fmt" + "unsafe" +) + +var PackedEndcConfigurationUpdateFailure []byte +var PackedEndcConfigurationUpdateAck []byte +var PackedX2EnbConfigurationUpdateFailure []byte +var PackedX2EnbConfigurationUpdateAck []byte + +func prepareEndcConfigurationUpdateFailurePDU(maxAsn1PackedBufferSize int, maxAsn1CodecMessageBufferSize int) error { + + packedBuffer := make([]C.uchar, maxAsn1PackedBufferSize) + errorBuffer := make([]C.char, maxAsn1CodecMessageBufferSize) + var payloadSize = C.ulong(maxAsn1PackedBufferSize) + + if status := C.build_pack_endc_configuration_update_failure(&payloadSize, &packedBuffer[0], C.ulong(maxAsn1CodecMessageBufferSize), &errorBuffer[0]); !status { + return fmt.Errorf("#configuration_update.prepareEndcConfigurationUpdateFailurePDU - failed to build and pack the endc configuration update failure message %s ", C.GoString(&errorBuffer[0])) + + } + PackedEndcConfigurationUpdateFailure = C.GoBytes(unsafe.Pointer(&packedBuffer[0]), C.int(payloadSize)) + + return nil +} + +func prepareX2EnbConfigurationUpdateFailurePDU(maxAsn1PackedBufferSize int, maxAsn1CodecMessageBufferSize int) error { + + packedBuffer := make([]C.uchar, maxAsn1PackedBufferSize) + errorBuffer := make([]C.char, maxAsn1CodecMessageBufferSize) + var payloadSize = C.ulong(maxAsn1PackedBufferSize) + + if status := C.build_pack_x2enb_configuration_update_failure(&payloadSize, &packedBuffer[0], C.ulong(maxAsn1CodecMessageBufferSize), &errorBuffer[0]); !status { + return fmt.Errorf("#configuration_update.prepareX2EnbConfigurationUpdateFailurePDU - failed to build and pack the x2 configuration update failure message %s ", C.GoString(&errorBuffer[0])) + + } + PackedX2EnbConfigurationUpdateFailure = C.GoBytes(unsafe.Pointer(&packedBuffer[0]), C.int(payloadSize)) + + return nil +} + +func prepareEndcConfigurationUpdateAckPDU(maxAsn1PackedBufferSize int, maxAsn1CodecMessageBufferSize int) error { + + packedBuffer := make([]C.uchar, maxAsn1PackedBufferSize) + errorBuffer := make([]C.char, maxAsn1CodecMessageBufferSize) + var payloadSize = C.ulong(maxAsn1PackedBufferSize) + + if status := C.build_pack_endc_configuration_update_ack(&payloadSize, &packedBuffer[0], C.ulong(maxAsn1CodecMessageBufferSize), &errorBuffer[0]); !status { + return fmt.Errorf("#configuration_update.prepareEndcConfigurationUpdateAckPDU - failed to build and pack the endc configuration update ack message %s ", C.GoString(&errorBuffer[0])) + + } + PackedEndcConfigurationUpdateAck = C.GoBytes(unsafe.Pointer(&packedBuffer[0]), C.int(payloadSize)) + + return nil +} + +func prepareX2EnbConfigurationUpdateAckPDU(maxAsn1PackedBufferSize int, maxAsn1CodecMessageBufferSize int) error { + + packedBuffer := make([]C.uchar, maxAsn1PackedBufferSize) + errorBuffer := make([]C.char, maxAsn1CodecMessageBufferSize) + var payloadSize = C.ulong(maxAsn1PackedBufferSize) + + if status := C.build_pack_x2enb_configuration_update_ack(&payloadSize, &packedBuffer[0], C.ulong(maxAsn1CodecMessageBufferSize), &errorBuffer[0]); !status { + return fmt.Errorf("#configuration_update.prepareX2EnbConfigurationUpdateAckPDU - failed to build and pack the x2 configuration update ack message %s ", C.GoString(&errorBuffer[0])) + + } + PackedX2EnbConfigurationUpdateAck = C.GoBytes(unsafe.Pointer(&packedBuffer[0]), C.int(payloadSize)) + + return nil +} + +func init() { + if err := prepareEndcConfigurationUpdateFailurePDU(MaxAsn1PackedBufferSize, MaxAsn1CodecMessageBufferSize); err != nil { + panic(err) + } + if err := prepareEndcConfigurationUpdateAckPDU(MaxAsn1PackedBufferSize, MaxAsn1CodecMessageBufferSize); err != nil { + panic(err) + } + if err := prepareX2EnbConfigurationUpdateFailurePDU(MaxAsn1PackedBufferSize, MaxAsn1CodecMessageBufferSize); err != nil { + panic(err) + } + if err := prepareX2EnbConfigurationUpdateAckPDU(MaxAsn1PackedBufferSize, MaxAsn1CodecMessageBufferSize); err != nil { + panic(err) + } +} diff --git a/E2Manager/e2pdus/configuration_update_test.go b/E2Manager/e2pdus/configuration_update_test.go new file mode 100644 index 0000000..a90ba13 --- /dev/null +++ b/E2Manager/e2pdus/configuration_update_test.go @@ -0,0 +1,165 @@ +/******************************************************************************* + * + * Copyright (c) 2019 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + *******************************************************************************/ +package e2pdus + +import ( + "e2mgr/logger" + "fmt" + "strings" + "testing" +) + +func TestPrepareEndcConfigurationUpdateFailurePDU(t *testing.T) { + _,err := logger.InitLogger(logger.InfoLevel) + if err!=nil{ + t.Errorf("failed to initialize logger, error: %s", err) + } + packedPdu := "402500080000010005400142" + packedEndcConfigurationUpdateFailure := PackedEndcConfigurationUpdateFailure + + tmp := fmt.Sprintf("%x", packedEndcConfigurationUpdateFailure) + if len(tmp) != len(packedPdu) { + t.Errorf("want packed len:%d, got: %d\n", len(packedPdu)/2, len(packedEndcConfigurationUpdateFailure)/2) + } + + if strings.Compare(tmp, packedPdu) != 0 { + t.Errorf("\nwant :\t[%s]\n got: \t\t[%s]\n", packedPdu, tmp) + } +} + +func TestPrepareEndcConfigurationUpdateFailurePDUFailure(t *testing.T) { + _, err := logger.InitLogger(logger.InfoLevel) + if err != nil { + t.Errorf("failed to initialize logger, error: %s", err) + } + + err = prepareEndcConfigurationUpdateFailurePDU(1, 4096) + if err == nil { + t.Errorf("want: error, got: success.\n") + } + + expected:= "#configuration_update.prepareEndcConfigurationUpdateFailurePDU - failed to build and pack the endc configuration update failure message #src/asn1codec_utils.c.pack_pdu_aux - Encoded output of E2AP-PDU, is too big" + if !strings.Contains(err.Error(), expected) { + t.Errorf("want :[%s], got: [%s]\n", expected, err) + } +} + +func TestPrepareX2EnbConfigurationUpdateFailurePDU(t *testing.T) { + _,err := logger.InitLogger(logger.InfoLevel) + if err!=nil{ + t.Errorf("failed to initialize logger, error: %s", err) + } + packedPdu := "400800080000010005400142" + packedEndcX2ConfigurationUpdateFailure := PackedX2EnbConfigurationUpdateFailure + + tmp := fmt.Sprintf("%x", packedEndcX2ConfigurationUpdateFailure) + if len(tmp) != len(packedPdu) { + t.Errorf("want packed len:%d, got: %d\n", len(packedPdu)/2, len(packedEndcX2ConfigurationUpdateFailure)/2) + } + + if strings.Compare(tmp, packedPdu) != 0 { + t.Errorf("\nwant :\t[%s]\n got: \t\t[%s]\n", packedPdu, tmp) + } +} + +func TestPrepareX2EnbConfigurationUpdateFailurePDUFailure(t *testing.T) { + _, err := logger.InitLogger(logger.InfoLevel) + if err != nil { + t.Errorf("failed to initialize logger, error: %s", err) + } + + err = prepareX2EnbConfigurationUpdateFailurePDU(1, 4096) + if err == nil { + t.Errorf("want: error, got: success.\n") + } + + expected:= "#configuration_update.prepareX2EnbConfigurationUpdateFailurePDU - failed to build and pack the x2 configuration update failure message #src/asn1codec_utils.c.pack_pdu_aux - Encoded output of E2AP-PDU, is too big" + if !strings.Contains(err.Error(), expected) { + t.Errorf("want :[%s], got: [%s]\n", expected, err) + } +} + +func TestPrepareEndcConfigurationUpdateAckPDU(t *testing.T) { + _,err := logger.InitLogger(logger.InfoLevel) + if err!=nil{ + t.Errorf("failed to initialize logger, error: %s", err) + } + packedPdu := "2025000a00000100f70003000000" + packedEndcConfigurationUpdateAck := PackedEndcConfigurationUpdateAck + + tmp := fmt.Sprintf("%x", packedEndcConfigurationUpdateAck) + if len(tmp) != len(packedPdu) { + t.Errorf("want packed len:%d, got: %d\n", len(packedPdu)/2, len(packedEndcConfigurationUpdateAck)/2) + } + + if strings.Compare(tmp, packedPdu) != 0 { + t.Errorf("\nwant :\t[%s]\n got: \t\t[%s]\n", packedPdu, tmp) + } +} + +func TestPrepareEndcConfigurationUpdateAckPDUFailure(t *testing.T) { + _, err := logger.InitLogger(logger.InfoLevel) + if err != nil { + t.Errorf("failed to initialize logger, error: %s", err) + } + + err = prepareEndcConfigurationUpdateAckPDU(1, 4096) + if err == nil { + t.Errorf("want: error, got: success.\n") + } + + expected:= "#configuration_update.prepareEndcConfigurationUpdateAckPDU - failed to build and pack the endc configuration update ack message #src/asn1codec_utils.c.pack_pdu_aux - Encoded output of E2AP-PDU, is too big" + if !strings.Contains(err.Error(), expected) { + t.Errorf("want :[%s], got: [%s]\n", expected, err) + } +} + +func TestPrepareX2EnbConfigurationUpdateAckPDU(t *testing.T) { + _,err := logger.InitLogger(logger.InfoLevel) + if err!=nil{ + t.Errorf("failed to initialize logger, error: %s", err) + } + packedPdu := "200800080000010011400100" + packedEndcX2ConfigurationUpdateAck := PackedX2EnbConfigurationUpdateAck + + tmp := fmt.Sprintf("%x", packedEndcX2ConfigurationUpdateAck) + if len(tmp) != len(packedPdu) { + t.Errorf("want packed len:%d, got: %d\n", len(packedPdu)/2, len(packedEndcX2ConfigurationUpdateAck)/2) + } + + if strings.Compare(tmp, packedPdu) != 0 { + t.Errorf("\nwant :\t[%s]\n got: \t\t[%s]\n", packedPdu, tmp) + } +} + +func TestPrepareX2EnbConfigurationUpdateAckPDUFailure(t *testing.T) { + _, err := logger.InitLogger(logger.InfoLevel) + if err != nil { + t.Errorf("failed to initialize logger, error: %s", err) + } + + err = prepareX2EnbConfigurationUpdateAckPDU(1, 4096) + if err == nil { + t.Errorf("want: error, got: success.\n") + } + + expected:= "#configuration_update.prepareX2EnbConfigurationUpdateAckPDU - failed to build and pack the x2 configuration update ack message #src/asn1codec_utils.c.pack_pdu_aux - Encoded output of E2AP-PDU, is too big" + if !strings.Contains(err.Error(), expected) { + t.Errorf("want :[%s], got: [%s]\n", expected, err) + } +} \ No newline at end of file diff --git a/E2Manager/e2pdus/x2_setup_requests_test.go b/E2Manager/e2pdus/x2_setup_requests_test.go index 3ad683c..81e70bf 100644 --- a/E2Manager/e2pdus/x2_setup_requests_test.go +++ b/E2Manager/e2pdus/x2_setup_requests_test.go @@ -19,81 +19,11 @@ package e2pdus import ( "bytes" - "e2mgr/logger" "fmt" "strings" "testing" ) -func TestPreparePackedEndcX2SetupRequest(t *testing.T) { - _,err := logger.InitLogger(logger.InfoLevel) - if err!=nil{ - t.Errorf("failed to initialize logger, error: %s", err) - } - packedPdu := "0024003100000100f4002a0000020015000800bbbccc00abcde000fa0017000001f700bbbcccabcde0000000bbbccc000000000001" - packedEndcX2setupRequest := PackedEndcX2setupRequest - - tmp := fmt.Sprintf("%x", packedEndcX2setupRequest) - if len(tmp) != len(packedPdu) { - t.Errorf("want packed len:%d, got: %d\n", len(packedPdu)/2, len(packedEndcX2setupRequest)/2) - } - - if strings.Compare(tmp, packedPdu) != 0 { - t.Errorf("\nwant :\t[%s]\n got: \t\t[%s]\n", packedPdu, tmp) - } -} - -func TestPreparePackedX2SetupRequest(t *testing.T) { - _,err := logger.InitLogger(logger.InfoLevel) - if err!=nil{ - t.Errorf("failed to initialize logger, error: %s", err) - } - packedPdu := "0006002a0000020015000800bbbccc00abcde000140017000001f700bbbcccabcde0000000bbbccc000000000001" - packedX2setupRequest := PackedX2setupRequest - - tmp := fmt.Sprintf("%x", packedX2setupRequest) - if len(tmp) != len(packedPdu) { - t.Errorf("want packed len:%d, got: %d\n", len(packedPdu)/2, len(packedX2setupRequest)/2) - } - - if strings.Compare(tmp, packedPdu) != 0 { - t.Errorf("\nwant :\t[%s]\n got: \t\t[%s]\n", packedPdu, tmp) - } -} - -func TestPreparePackedX2SetupRequestFailure(t *testing.T) { - _, err := logger.InitLogger(logger.InfoLevel) - if err != nil { - t.Errorf("failed to initialize logger, error: %s", err) - } - - _, _, err = preparePackedX2SetupRequest(1, 4096, pLMNId, eNBId, eNBIdBitqty, ricFlag) - if err == nil { - t.Errorf("want: error, got: success.\n") - } - - expected:= "packing error: #src/asn1codec_utils.c.pack_pdu_aux - Encoded output of E2AP-PDU, is too big" - if !strings.Contains(err.Error(), expected) { - t.Errorf("want :[%s], got: [%s]\n", expected, err) - } -} - -func TestPreparePackedEndcSetupRequestFailure(t *testing.T) { - _, err := logger.InitLogger(logger.InfoLevel) - if err != nil { - t.Errorf("failed to initialize logger, error: %s", err) - } - - _, _, err = preparePackedEndcX2SetupRequest(1, 4096, pLMNId, eNBId, eNBIdBitqty, ricFlag) - if err == nil { - t.Errorf("want: error, got: success.\n") - } - - expected:= "packing error: #src/asn1codec_utils.c.pack_pdu_aux - Encoded output of E2AP-PDU, is too big" - if !strings.Contains(err.Error(), expected) { - t.Errorf("want :[%s], got: [%s]\n", expected, err) - } -} func TestParseRicId(t *testing.T) { var testCases = []struct { diff --git a/E2Manager/go.mod b/E2Manager/go.mod index 6892b02..368ce17 100644 --- a/E2Manager/go.mod +++ b/E2Manager/go.mod @@ -1,20 +1,30 @@ module e2mgr require ( - gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/common v1.0.23 - gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/entities v1.0.23 - gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/reader v1.0.23 - gerrit.o-ran-sc.org/r/ric-plt/sdlgo v0.3.1 + gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/common v1.0.24 + gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/entities v1.0.24 + gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/reader v1.0.24 + gerrit.o-ran-sc.org/r/ric-plt/sdlgo v0.5.0 github.com/asaskevich/govalidator v0.0.0-20190424111038-f61b66f89f4a // indirect github.com/go-ozzo/ozzo-validation v3.5.0+incompatible - github.com/golang/protobuf v1.3.1 - github.com/gorilla/context v1.1.1 // indirect - github.com/gorilla/mux v1.6.2 + github.com/golang/protobuf v1.3.2 + github.com/gorilla/mux v1.7.0 + github.com/magiconair/properties v1.8.1 // indirect + github.com/pelletier/go-toml v1.5.0 // indirect github.com/pkg/errors v0.8.1 + github.com/spf13/afero v1.2.2 // indirect + github.com/spf13/jwalterweatherman v1.1.0 // indirect + github.com/spf13/pflag v1.0.5 // indirect github.com/spf13/viper v1.4.0 - github.com/stretchr/testify v1.3.0 - go.uber.org/zap v1.10.0 - gopkg.in/yaml.v2 v2.2.2 + github.com/stretchr/objx v0.2.0 // indirect + github.com/stretchr/testify v1.4.0 + go.uber.org/multierr v1.2.0 // indirect + go.uber.org/zap v1.11.0 + golang.org/x/net v0.0.0-20191021144547-ec77196f6094 // indirect + golang.org/x/sys v0.0.0-20191022100944-742c48ecaeb7 // indirect + golang.org/x/text v0.3.2 // indirect + gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 // indirect + gopkg.in/yaml.v2 v2.2.4 ) -replace gerrit.o-ran-sc.org/r/ric-plt/sdlgo => gerrit.o-ran-sc.org/r/ric-plt/sdlgo.git v0.3.1 +replace gerrit.o-ran-sc.org/r/ric-plt/sdlgo => gerrit.o-ran-sc.org/r/ric-plt/sdlgo.git v0.5.0 diff --git a/E2Manager/go.sum b/E2Manager/go.sum index 6576a0b..879eb02 100644 --- a/E2Manager/go.sum +++ b/E2Manager/go.sum @@ -1,12 +1,18 @@ cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/common v1.0.23 h1:JbSOhvj9fVEUF2XZg8cw5QAyeKUi5xXgpwXrrxfDgLM= gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/common v1.0.23/go.mod h1:QJ1uPPZosGbhxUWpUpeM5fLqFHdnWTrVnvW2DgyOCes= +gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/common v1.0.24 h1:tW817tat6fSSK7NuFKEDHSoSsO3z8kr7QORfbn1Hpuc= +gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/common v1.0.24/go.mod h1:QJ1uPPZosGbhxUWpUpeM5fLqFHdnWTrVnvW2DgyOCes= gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/entities v1.0.23 h1:akVZc8NWJ9oPujd7cQY3Ti3se4PF1/NoC+Dwt+YzINc= gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/entities v1.0.23/go.mod h1:GXiXLz4ORBeIr0FLIbzENRykgh3Po5uPkX2jICxnRF0= +gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/entities v1.0.24 h1:5ZnhEUygvN5PuTXS2bNt6KavT+Wtuh9Vra+EqZIvw+Q= +gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/entities v1.0.24/go.mod h1:GXiXLz4ORBeIr0FLIbzENRykgh3Po5uPkX2jICxnRF0= gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/reader v1.0.23 h1:TYV3HE2UNwGOWiA4C226/WhB94crwjuHKIFTgDDvo8I= gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/reader v1.0.23/go.mod h1:uZVjwZjfWV4JJzyQVO/O48Ykph57zfpfMB7nK+WGKX8= -gerrit.o-ran-sc.org/r/ric-plt/sdlgo.git v0.3.1 h1:ZIhABs0WLMn8lp1Y3719315/3jbV+yLcovOGScL03eM= -gerrit.o-ran-sc.org/r/ric-plt/sdlgo.git v0.3.1/go.mod h1:y2WhrCvdLkAKdH+ySdHSOSehACJkTMyZghCGVcqoZzc= +gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/reader v1.0.24 h1:Wwp36IoHwp091lXVCYLtFK6AMhoGAR4NYEgW1C42h6k= +gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/reader v1.0.24/go.mod h1:Qi0e0BsGtsMdyJQS0PBtvHBDKEimjtDjQtVUxGZqTtM= +gerrit.o-ran-sc.org/r/ric-plt/sdlgo.git v0.5.0 h1:+P3XuWKSaMbzh5PNtrW9gkZlCN0hKrZq+Cn8JetwBys= +gerrit.o-ran-sc.org/r/ric-plt/sdlgo.git v0.5.0/go.mod h1:y2WhrCvdLkAKdH+ySdHSOSehACJkTMyZghCGVcqoZzc= github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU= @@ -48,12 +54,12 @@ github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfb github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.1 h1:YF8+flBXS5eO826T4nzqPrxfhQThhXl0YzfuUPu4SBg= github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.2 h1:6nsPYzhq5kReh6QImI3k5qWzO4PEbvbIW2cwSfR/6xs= +github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= -github.com/gorilla/context v1.1.1 h1:AWwleXJkX/nhcU9bZSnZoi3h/qGYqQAGhq6zZe/aQW8= -github.com/gorilla/context v1.1.1/go.mod h1:kBGZzfjB9CEq2AlWe17Uuf7NDRt0dE0s8S51q0aT7Yg= -github.com/gorilla/mux v1.6.2 h1:Pgr17XVTNXAk3q/r4CpKzC5xBM/qW1uVLV+IhRZpIIk= -github.com/gorilla/mux v1.6.2/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs= +github.com/gorilla/mux v1.7.0 h1:tOSd0UKHQd6urX6ApfOn4XdBMY6Sh1MfxV3kmaazO+U= +github.com/gorilla/mux v1.7.0/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs= github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= github.com/grpc-ecosystem/go-grpc-middleware v1.0.0/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs= github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk= @@ -76,6 +82,8 @@ github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/magiconair/properties v1.8.0 h1:LLgXmsheXeRoUOBOjtwPQCWIYqM/LU1ayDtDePerRcY= github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= +github.com/magiconair/properties v1.8.1 h1:ZC2Vc7/ZFkGmsVC9KvOjumD+G5lXy2RtTKyzRKO2BQ4= +github.com/magiconair/properties v1.8.1/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= github.com/mitchellh/mapstructure v1.1.2 h1:fmNYVwqnSfB9mZU6OS2O6GsXM+wcskZDuKQzvN1EDeE= github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= @@ -88,6 +96,8 @@ github.com/onsi/gomega v1.5.0 h1:izbySO9zDPmjJ8rDjLvkA2zJHIo+HkYXHnf7eN7SSyo= github.com/onsi/gomega v1.5.0/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= github.com/pelletier/go-toml v1.2.0 h1:T5zMGML61Wp+FlcbWjRDT7yAxhJNAiPPLOFECq181zc= github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= +github.com/pelletier/go-toml v1.5.0 h1:5BakdOZdtKJ1FFk6QdL8iSGrMWsXgchNJcrnarjbmJQ= +github.com/pelletier/go-toml v1.5.0/go.mod h1:5N711Q9dKgbdkxHL+MEfF31hpT7l0S0s/t2kKREewys= github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I= github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= @@ -108,20 +118,30 @@ github.com/soheilhy/cmux v0.1.4/go.mod h1:IM3LyeVVIOuxMH7sFAkER9+bJ4dT7Ms6E4xg4k github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= github.com/spf13/afero v1.1.2 h1:m8/z1t7/fwjysjQRYbP0RD+bUIF/8tJwPdEZsI83ACI= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= +github.com/spf13/afero v1.2.2 h1:5jhuqJyZCZf2JRofRvN/nIFgIWNzPa3/Vz8mYylgbWc= +github.com/spf13/afero v1.2.2/go.mod h1:9ZxEEn6pIJ8Rxe320qSDBk6AsU0r9pR7Q4OcevTdifk= github.com/spf13/cast v1.3.0 h1:oget//CVOEoFewqQxwr0Ej5yjygnqGkvggSE/gB35Q8= github.com/spf13/cast v1.3.0/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= github.com/spf13/jwalterweatherman v1.0.0 h1:XHEdyB+EcvlqZamSM4ZOMGlc93t6AcsBEu9Gc1vn7yk= github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo= +github.com/spf13/jwalterweatherman v1.1.0 h1:ue6voC5bR5F8YxI5S67j9i582FU4Qvo2bmqnqMYADFk= +github.com/spf13/jwalterweatherman v1.1.0/go.mod h1:aNWZUN0dPAAO/Ljvb5BEdw96iTZ0EXowPYD95IqWIGo= github.com/spf13/pflag v1.0.3 h1:zPAT6CGy6wXeQ7NtTnaTerfKOsV6V6F8agHXFiazDkg= github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= +github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= +github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spf13/viper v1.4.0 h1:yXHLWeravcrgGyFSyCgdYpXQ9dR9c/WED3pg1RhxqEU= github.com/spf13/viper v1.4.0/go.mod h1:PTJ7Z/lr49W6bUbkmS1V3by4uWynFiR9p7+dSq/yZzE= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.1.1 h1:2vfRuCMp5sSVIDSqO8oNnWJq7mPa6KVP3iPIwFBuy8A= github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.2.0 h1:Hbg2NidpLE8veEBkEZTL3CvlkUIVzuU9jDplZO54c48= +github.com/stretchr/objx v0.2.0/go.mod h1:qt09Ya8vawLte6SNmTgCsAVtYtaKzEcn8ATUoHMkEqE= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= github.com/ugorji/go v1.1.4/go.mod h1:uQMGLiO92mf5W77hV/PUCpI3pbzQx3CRekS0kk+RGrc= github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU= @@ -131,8 +151,12 @@ go.uber.org/atomic v1.4.0 h1:cxzIVoETapQEqDhQu3QfnvXAV4AlzcvUCxkVUFw3+EU= go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= go.uber.org/multierr v1.1.0 h1:HoEmRHQPVSqub6w2z2d2EOVs2fjyFRGyofhKuyDq0QI= go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0= +go.uber.org/multierr v1.2.0 h1:6I+W7f5VwC5SV9dNrZ3qXrDB9mD0dyGOi/ZJmYw03T4= +go.uber.org/multierr v1.2.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0= go.uber.org/zap v1.10.0 h1:ORx85nbTijNz8ljznvCMR1ZBIPKFn3jQrag10X2AsuM= go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q= +go.uber.org/zap v1.11.0 h1:gSmpCfs+R47a4yQPAI4xJ0IPDLTRGXskm6UelqNXpqE= +go.uber.org/zap v1.11.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q= golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= @@ -144,6 +168,8 @@ golang.org/x/net v0.0.0-20181220203305-927f97764cc3/go.mod h1:mL1N/T3taQHkDXs73r golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190522155817-f3200d17e092 h1:4QSRKanuywn15aTZvI/mIDEgPQpswuFndXpOj3rKEco= golang.org/x/net v0.0.0-20190522155817-f3200d17e092/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= +golang.org/x/net v0.0.0-20191021144547-ec77196f6094 h1:5O4U9trLjNpuhpynaDsqwCk+Tw6seqJz1EbqbnzHrc8= +golang.org/x/net v0.0.0-20191021144547-ec77196f6094/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -156,10 +182,15 @@ golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5h golang.org/x/sys v0.0.0-20190204203706-41f3e6584952/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a h1:1BGLXjeY4akVXGgbC9HugT3Jv3hCI0z56oJR5vAMgBU= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20191022100944-742c48ecaeb7 h1:HmbHVPwrPEKPGLAcHSrMe6+hqSUlvZU0rab6x5EXfGU= +golang.org/x/sys v0.0.0-20191022100944-742c48ecaeb7/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.2 h1:tW2bmiBqwgJj/UpqtC8EpXEZVYOwU0yG4iWbprSVAcs= +golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/tools v0.0.0-20180221164845-07fd8470d635/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= @@ -170,6 +201,8 @@ gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLks gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo= +gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/fsnotify.v1 v1.4.7 h1:xOHLXZwVvI9hhs+cLKq5+I5onOuwQLhQwiu63xxlHs4= gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= gopkg.in/resty.v1 v1.12.0/go.mod h1:mDo4pnntr5jdWRML875a/NmxYqAlA73dVijT2AXvQQo= @@ -179,4 +212,6 @@ gopkg.in/yaml.v2 v2.0.0-20170812160011-eb3733d160e7/go.mod h1:JAlM8MvJe8wmxCU4Bl gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.4 h1:/eiJrUcujPVeJ3xlSWaiNi3uSVmDGBK1pDHUHAnao1I= +gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= diff --git a/E2Manager/handlers/httpmsghandlers/delete_all_request_handler_test.go b/E2Manager/handlers/httpmsghandlers/delete_all_request_handler_test.go index 3f8423d..c61f060 100644 --- a/E2Manager/handlers/httpmsghandlers/delete_all_request_handler_test.go +++ b/E2Manager/handlers/httpmsghandlers/delete_all_request_handler_test.go @@ -22,7 +22,6 @@ import ( "e2mgr/e2managererrors" "e2mgr/logger" "e2mgr/mocks" - "e2mgr/rNibWriter" "e2mgr/rmrCgo" "e2mgr/services" "e2mgr/services/rmrsender" @@ -30,7 +29,6 @@ import ( "fmt" "gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/common" "gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/entities" - "gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/reader" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" "reflect" @@ -42,14 +40,10 @@ func setupTest(t *testing.T) (*logger.Logger, *configuration.Configuration, *moc config := configuration.ParseConfiguration() readerMock := &mocks.RnibReaderMock{} - readerProvider := func() reader.RNibReader { - return readerMock - } + writerMock := &mocks.RnibWriterMock{} - writerProvider := func() rNibWriter.RNibWriter { - return writerMock - } - rnibDataService := services.NewRnibDataService(log, config, readerProvider, writerProvider) + + rnibDataService := services.NewRnibDataService(log, config, readerMock, writerMock) rmrMessengerMock := &mocks.RmrMessengerMock{} return log, config, readerMock, writerMock, rnibDataService, rmrMessengerMock } @@ -388,5 +382,5 @@ func initLog(t *testing.T) *logger.Logger { func getRmrSender(rmrMessengerMock *mocks.RmrMessengerMock, log *logger.Logger) *rmrsender.RmrSender { rmrMessenger := rmrCgo.RmrMessenger(rmrMessengerMock) rmrMessengerMock.On("Init", tests.GetPort(), tests.MaxMsgSize, tests.Flags, log).Return(&rmrMessenger) - return rmrsender.NewRmrSender(log, &rmrMessenger) + return rmrsender.NewRmrSender(log, rmrMessenger) } diff --git a/E2Manager/handlers/httpmsghandlers/get_nodeb_id_list_request_handler_test.go b/E2Manager/handlers/httpmsghandlers/get_nodeb_id_list_request_handler_test.go index f9b630c..26d7d08 100644 --- a/E2Manager/handlers/httpmsghandlers/get_nodeb_id_list_request_handler_test.go +++ b/E2Manager/handlers/httpmsghandlers/get_nodeb_id_list_request_handler_test.go @@ -24,7 +24,6 @@ import ( "e2mgr/services" "gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/common" "gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/entities" - "gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/reader" "github.com/pkg/errors" "github.com/stretchr/testify/assert" "testing" @@ -34,10 +33,8 @@ func setupGetNodebIdListRequestHandlerTest(t *testing.T) (*GetNodebIdListRequest log := initLog(t) config := &configuration.Configuration{RnibRetryIntervalMs: 10, MaxRnibConnectionAttempts: 3} readerMock := &mocks.RnibReaderMock{} - readerProvider := func() reader.RNibReader { - return readerMock - } - rnibDataService := services.NewRnibDataService(log, config, readerProvider, nil) + + rnibDataService := services.NewRnibDataService(log, config, readerMock, nil) handler := NewGetNodebIdListRequestHandler(log, rnibDataService) return handler, readerMock } diff --git a/E2Manager/handlers/httpmsghandlers/get_nodeb_request_handler_test.go b/E2Manager/handlers/httpmsghandlers/get_nodeb_request_handler_test.go index c679988..4e908b6 100644 --- a/E2Manager/handlers/httpmsghandlers/get_nodeb_request_handler_test.go +++ b/E2Manager/handlers/httpmsghandlers/get_nodeb_request_handler_test.go @@ -24,7 +24,6 @@ import ( "e2mgr/services" "gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/common" "gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/entities" - "gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/reader" "github.com/pkg/errors" "github.com/stretchr/testify/assert" "testing" @@ -34,10 +33,7 @@ func setupGetNodebRequestHandlerTest(t *testing.T) (*GetNodebRequestHandler, *mo log := initLog(t) config := &configuration.Configuration{RnibRetryIntervalMs: 10, MaxRnibConnectionAttempts: 3} readerMock := &mocks.RnibReaderMock{} - readerProvider := func() reader.RNibReader { - return readerMock - } - rnibDataService := services.NewRnibDataService(log, config, readerProvider, nil) + rnibDataService := services.NewRnibDataService(log, config, readerMock, nil) handler := NewGetNodebRequestHandler(log, rnibDataService) return handler, readerMock } diff --git a/E2Manager/handlers/httpmsghandlers/setup_request_handler_test.go b/E2Manager/handlers/httpmsghandlers/setup_request_handler_test.go index fc3d075..154ac4c 100644 --- a/E2Manager/handlers/httpmsghandlers/setup_request_handler_test.go +++ b/E2Manager/handlers/httpmsghandlers/setup_request_handler_test.go @@ -17,19 +17,17 @@ package httpmsghandlers import ( - "e2mgr/rnibBuilders" "e2mgr/configuration" "e2mgr/e2managererrors" "e2mgr/e2pdus" "e2mgr/managers" "e2mgr/mocks" "e2mgr/models" - "e2mgr/rNibWriter" "e2mgr/rmrCgo" + "e2mgr/rnibBuilders" "e2mgr/services" "gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/common" "gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/entities" - "gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/reader" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" "reflect" @@ -200,6 +198,23 @@ func TestX2SetupHandleRnibGet_Error(t *testing.T) { rmrMessengerMock.AssertNumberOfCalls(t, "SendMsg", 0) } +func TestEndcSetupHandleShuttingDownRan_Error(t *testing.T) { + readerMock, writerMock, handler, rmrMessengerMock := initSetupRequestTest(t, entities.E2ApplicationProtocol_ENDC_X2_SETUP_REQUEST) + + nb := &entities.NodebInfo{RanName: "RanName", ConnectionStatus: entities.ConnectionStatus_SHUTTING_DOWN,} + readerMock.On("GetNodeb", "RanName").Return(nb, nil) + + sr := models.SetupRequest{"127.0.0.1", 8080, "RanName",} + _, actual := handler.Handle(sr) + + expected := &e2managererrors.WrongStateError{} + if reflect.TypeOf(actual) != reflect.TypeOf(expected) { + t.Errorf("Error actual = %v, and Expected = %v.", actual, expected) + } + writerMock.AssertNumberOfCalls(t, "UpdateNodebInfo", 0) + rmrMessengerMock.AssertNumberOfCalls(t, "SendMsg", 0) +} + func TestX2SetupHandleShuttingDownRan_Error(t *testing.T) { readerMock, writerMock, handler, rmrMessengerMock := initSetupRequestTest(t, entities.E2ApplicationProtocol_X2_SETUP_REQUEST) @@ -288,18 +303,12 @@ func initSetupRequestTest(t *testing.T, protocol entities.E2ApplicationProtocol) config := &configuration.Configuration{RnibRetryIntervalMs: 10, MaxRnibConnectionAttempts: 3} readerMock := &mocks.RnibReaderMock{} - readerProvider := func() reader.RNibReader { - return readerMock - } writerMock := &mocks.RnibWriterMock{} - writerProvider := func() rNibWriter.RNibWriter { - return writerMock - } rmrMessengerMock := &mocks.RmrMessengerMock{} rmrSender := getRmrSender(rmrMessengerMock, log) - rnibDataService := services.NewRnibDataService(log, config, readerProvider, writerProvider) + rnibDataService := services.NewRnibDataService(log, config, readerMock, writerMock) ranSetupManager := managers.NewRanSetupManager(log, rmrSender, rnibDataService) handler := NewSetupRequestHandler(log, rnibDataService, ranSetupManager, protocol) diff --git a/E2Manager/handlers/httpmsghandlers/x2_reset_request_handler.go b/E2Manager/handlers/httpmsghandlers/x2_reset_request_handler.go index 755984e..6d398a4 100644 --- a/E2Manager/handlers/httpmsghandlers/x2_reset_request_handler.go +++ b/E2Manager/handlers/httpmsghandlers/x2_reset_request_handler.go @@ -78,7 +78,9 @@ func (handler *X2ResetRequestHandler) Handle(request models.Request) (models.IRe return nil, e2managererrors.NewWrongStateError(X2_RESET_ACTIVITY_NAME, entities.ConnectionStatus_name[int32(nodeb.ConnectionStatus)]) } - msg := models.NewRmrMessage(rmrCgo.RIC_X2_RESET, resetRequest.RanName, payload) + var xAction []byte + + msg := models.NewRmrMessage(rmrCgo.RIC_X2_RESET, resetRequest.RanName, payload, xAction) err = handler.rmrSender.Send(msg) diff --git a/E2Manager/handlers/httpmsghandlers/x2_reset_request_handler_test.go b/E2Manager/handlers/httpmsghandlers/x2_reset_request_handler_test.go index 870385b..53138bd 100644 --- a/E2Manager/handlers/httpmsghandlers/x2_reset_request_handler_test.go +++ b/E2Manager/handlers/httpmsghandlers/x2_reset_request_handler_test.go @@ -5,13 +5,11 @@ import ( "e2mgr/e2managererrors" "e2mgr/mocks" "e2mgr/models" - "e2mgr/rNibWriter" "e2mgr/rmrCgo" "e2mgr/services" "fmt" "gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/common" "gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/entities" - "gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/reader" "github.com/stretchr/testify/assert" "testing" ) @@ -20,14 +18,8 @@ func setupX2ResetRequestHandlerTest(t *testing.T) (*X2ResetRequestHandler, *mock log := initLog(t) config := &configuration.Configuration{RnibRetryIntervalMs: 10, MaxRnibConnectionAttempts: 3} readerMock := &mocks.RnibReaderMock{} - readerProvider := func() reader.RNibReader { - return readerMock - } writerMock := &mocks.RnibWriterMock{} - writerProvider := func() rNibWriter.RNibWriter { - return writerMock - } - rnibDataService := services.NewRnibDataService(log, config, readerProvider, writerProvider) + rnibDataService := services.NewRnibDataService(log, config, readerMock, writerMock) rmrMessengerMock := &mocks.RmrMessengerMock{} rmrSender := getRmrSender(rmrMessengerMock, log) handler := NewX2ResetRequestHandler(log, rmrSender, rnibDataService) @@ -40,8 +32,8 @@ func TestHandleSuccessfulDefaultCause(t *testing.T) { ranName := "test1" // o&m intervention payload := []byte{0x00, 0x07, 0x00, 0x08, 0x00, 0x00, 0x01, 0x00, 0x05, 0x40, 0x01, 0x64} - xaction := []byte(ranName) - msg := rmrCgo.NewMBuf(rmrCgo.RIC_X2_RESET, len(payload), ranName, &payload, &xaction) + var xAction[]byte + msg := rmrCgo.NewMBuf(rmrCgo.RIC_X2_RESET, len(payload), ranName, &payload, &xAction) rmrMessengerMock.On("SendMsg", msg).Return(msg, nil) @@ -58,8 +50,8 @@ func TestHandleSuccessfulRequestedCause(t *testing.T) { ranName := "test1" payload := []byte{0x00, 0x07, 0x00, 0x08, 0x00, 0x00, 0x01, 0x00, 0x05, 0x40, 0x01, 0x40} - xaction := []byte(ranName) - msg := rmrCgo.NewMBuf(rmrCgo.RIC_X2_RESET, len(payload), ranName, &payload, &xaction) + var xAction[]byte + msg := rmrCgo.NewMBuf(rmrCgo.RIC_X2_RESET, len(payload), ranName, &payload, &xAction) rmrMessengerMock.On("SendMsg", msg).Return(msg, nil) var nodeb = &entities.NodebInfo{ConnectionStatus: entities.ConnectionStatus_CONNECTED} @@ -125,8 +117,8 @@ func TestHandleFailureRmrError(t *testing.T) { ranName := "test1" // o&m intervention payload := []byte{0x00, 0x07, 0x00, 0x08, 0x00, 0x00, 0x01, 0x00, 0x05, 0x40, 0x01, 0x64} - xaction := []byte(ranName) - msg := rmrCgo.NewMBuf(rmrCgo.RIC_X2_RESET, len(payload), ranName, &payload, &xaction) + var xAction[]byte + msg := rmrCgo.NewMBuf(rmrCgo.RIC_X2_RESET, len(payload), ranName, &payload, &xAction) rmrMessengerMock.On("SendMsg", msg).Return(&rmrCgo.MBuf{}, fmt.Errorf("rmr error")) var nodeb = &entities.NodebInfo{ConnectionStatus: entities.ConnectionStatus_CONNECTED} diff --git a/E2Manager/handlers/rmrmsghandlers/e2_term_init_notification_handler_test.go b/E2Manager/handlers/rmrmsghandlers/e2_term_init_notification_handler_test.go index ae88cb2..fe9b172 100644 --- a/E2Manager/handlers/rmrmsghandlers/e2_term_init_notification_handler_test.go +++ b/E2Manager/handlers/rmrmsghandlers/e2_term_init_notification_handler_test.go @@ -1,3 +1,19 @@ +// +// Copyright 2019 AT&T Intellectual Property +// Copyright 2019 Nokia +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// package rmrmsghandlers import ( @@ -7,7 +23,6 @@ import ( "e2mgr/managers" "e2mgr/mocks" "e2mgr/models" - "e2mgr/rNibWriter" "e2mgr/rmrCgo" "e2mgr/services" "e2mgr/services/rmrsender" @@ -15,7 +30,6 @@ import ( "fmt" "gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/common" "gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/entities" - "gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/reader" "github.com/stretchr/testify/mock" "testing" ) @@ -29,14 +43,10 @@ func initRanLostConnectionTest(t *testing.T) (*logger.Logger, E2TermInitNotifica rmrSender := initRmrSender(rmrMessengerMock, logger) readerMock := &mocks.RnibReaderMock{} - rnibReaderProvider := func() reader.RNibReader { - return readerMock - } + writerMock := &mocks.RnibWriterMock{} - rnibWriterProvider := func() rNibWriter.RNibWriter { - return writerMock - } - rnibDataService := services.NewRnibDataService(logger, config, rnibReaderProvider, rnibWriterProvider) + + rnibDataService := services.NewRnibDataService(logger, config, readerMock, writerMock) ranSetupManager := managers.NewRanSetupManager(logger, rmrSender, rnibDataService) ranReconnectionManager := managers.NewRanReconnectionManager(logger, configuration.ParseConfiguration(), rnibDataService, ranSetupManager) handler := NewE2TermInitNotificationHandler(logger, ranReconnectionManager, rnibDataService) @@ -248,7 +258,7 @@ func TestE2TerminInitHandlerFailureGetListNodebIds(t *testing.T) { func initRmrSender(rmrMessengerMock *mocks.RmrMessengerMock, log *logger.Logger) *rmrsender.RmrSender { rmrMessenger := rmrCgo.RmrMessenger(rmrMessengerMock) rmrMessengerMock.On("Init", tests.GetPort(), tests.MaxMsgSize, tests.Flags, log).Return(&rmrMessenger) - return rmrsender.NewRmrSender(log, &rmrMessenger) + return rmrsender.NewRmrSender(log, rmrMessenger) } // TODO: extract to test_utils diff --git a/E2Manager/handlers/rmrmsghandlers/enb_load_information_notification_handler.go b/E2Manager/handlers/rmrmsghandlers/enb_load_information_notification_handler.go index a6a6234..8989af5 100644 --- a/E2Manager/handlers/rmrmsghandlers/enb_load_information_notification_handler.go +++ b/E2Manager/handlers/rmrmsghandlers/enb_load_information_notification_handler.go @@ -1,6 +1,21 @@ +// +// Copyright 2019 AT&T Intellectual Property +// Copyright 2019 Nokia +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// package rmrmsghandlers -import "C" import ( "e2mgr/converters" "e2mgr/e2pdus" @@ -44,7 +59,7 @@ func (h EnbLoadInformationNotificationHandler) Handle(request *models.Notificati err = h.extractor.ExtractAndBuildRanLoadInformation(pdu, ranLoadInformation) - if (err != nil) { + if err != nil { h.logger.Errorf("#EnbLoadInformationNotificationHandler.Handle - RAN name: %s - Failed at ExtractAndBuildRanLoadInformation. Error: %v", request.RanName, err) return } diff --git a/E2Manager/handlers/rmrmsghandlers/enb_load_information_notification_handler_test.go b/E2Manager/handlers/rmrmsghandlers/enb_load_information_notification_handler_test.go index b11ed29..265cb39 100644 --- a/E2Manager/handlers/rmrmsghandlers/enb_load_information_notification_handler_test.go +++ b/E2Manager/handlers/rmrmsghandlers/enb_load_information_notification_handler_test.go @@ -31,7 +31,7 @@ const ( GarbagePdu string = "12312312" ) -func createNotificationRequest(ranName string, transactionId string, packedPdu string) (*models.NotificationRequest, error) { +func createNotificationRequest(ranName string, transactionId []byte, packedPdu string) (*models.NotificationRequest, error) { var packedByteSlice []byte _, err := fmt.Sscanf(packedPdu, "%x", &packedByteSlice) @@ -43,7 +43,7 @@ func createNotificationRequest(ranName string, transactionId string, packedPdu s return models.NewNotificationRequest(ranName, packedByteSlice, time.Now(), transactionId), nil } -func createNotificationRequestAndHandle(ranName string, transactionId string, loadInformationHandler EnbLoadInformationNotificationHandler, pdu string) error { +func createNotificationRequestAndHandle(ranName string, transactionId []byte, loadInformationHandler EnbLoadInformationNotificationHandler, pdu string) error { notificationRequest, err := createNotificationRequest(ranName, transactionId, pdu) if err != nil { diff --git a/E2Manager/handlers/rmrmsghandlers/endc_configuration_update_handler.go b/E2Manager/handlers/rmrmsghandlers/endc_configuration_update_handler.go index bcb2c44..7070aa3 100644 --- a/E2Manager/handlers/rmrmsghandlers/endc_configuration_update_handler.go +++ b/E2Manager/handlers/rmrmsghandlers/endc_configuration_update_handler.go @@ -17,10 +17,6 @@ package rmrmsghandlers -// #cgo CFLAGS: -I../../asn1codec/inc/ -I../../asn1codec/e2ap_engine/ -// #cgo LDFLAGS: -L ../../asn1codec/lib/ -L../../asn1codec/e2ap_engine/ -le2ap_codec -lasncodec -// #include -// #include import "C" import ( "e2mgr/converters" @@ -29,7 +25,7 @@ import ( "e2mgr/models" "e2mgr/rmrCgo" "e2mgr/services/rmrsender" - "unsafe" + "e2mgr/utils" ) type EndcConfigurationUpdateHandler struct { @@ -46,35 +42,22 @@ func NewEndcConfigurationUpdateHandler(logger *logger.Logger, rmrSender *rmrsend func (h EndcConfigurationUpdateHandler) Handle(request *models.NotificationRequest) { - var payloadSize C.ulong - payloadSize = e2pdus.MaxAsn1PackedBufferSize - packedBuffer := [e2pdus.MaxAsn1PackedBufferSize]C.uchar{} - errorBuffer := [e2pdus.MaxAsn1PackedBufferSize]C.char{} refinedMessage, err := converters.UnpackX2apPduAndRefine(h.logger, e2pdus.MaxAsn1CodecAllocationBufferSize /*allocation buffer*/, request.Len, request.Payload, e2pdus.MaxAsn1CodecMessageBufferSize /*message buffer*/) + if err != nil { - status := C.build_pack_endc_configuration_update_failure(&payloadSize, &packedBuffer[0], e2pdus.MaxAsn1PackedBufferSize, &errorBuffer[0]) - if status { - payload := (*[1 << 30]byte)(unsafe.Pointer(&packedBuffer))[:payloadSize:payloadSize] - h.logger.Debugf("#endc_configuration_update_handler.Handle - Endc configuration update negative ack message payload: (%d) %02x", len(payload), payload) - msg := models.NewRmrMessage(rmrCgo.RIC_ENDC_CONF_UPDATE_FAILURE, request.RanName, payload) - _ = h.rmrSender.Send(msg) - } else { - h.logger.Errorf("#endc_configuration_update_handler.Handle - failed to build and pack Endc configuration update unsuccessful outcome message. Error: %v", errorBuffer) - } h.logger.Errorf("#endc_configuration_update_handler.Handle - unpack failed. Error: %v", err) - } else { - h.logger.Infof("#endc_configuration_update_handler.Handle - Endc configuration update initiating message received") - h.logger.Debugf("#endc_configuration_update_handler.Handle - Endc configuration update initiating message payload: %s", refinedMessage.PduPrint) - status := C.build_pack_endc_configuration_update_ack(&payloadSize, &packedBuffer[0], e2pdus.MaxAsn1PackedBufferSize, &errorBuffer[0]) - if status { - payload := (*[1 << 30]byte)(unsafe.Pointer(&packedBuffer))[:payloadSize:payloadSize] - h.logger.Debugf("#endc_configuration_update_handler.Handle - Endc configuration update positive ack message payload: (%d) %02x", len(payload), payload) - msg := models.NewRmrMessage(rmrCgo.RIC_ENDC_CONF_UPDATE_ACK, request.RanName, payload) - _ = h.rmrSender.Send(msg) - } else { - h.logger.Errorf("#endc_configuration_update_handler.Handle - failed to build and pack endc configuration update successful outcome message. Error: %v", errorBuffer) - } + + msg := models.NewRmrMessage(rmrCgo.RIC_ENDC_CONF_UPDATE_FAILURE, request.RanName, e2pdus.PackedEndcConfigurationUpdateFailure, request.TransactionId) + _ = h.rmrSender.Send(msg) + + h.logger.Infof("#EndcConfigurationUpdateHandler.Handle - Summary: elapsed time for receiving and handling endc configuration update initiating message from E2 terminator: %f ms", utils.ElapsedTime(request.StartTime)) + return } - printHandlingSetupResponseElapsedTimeInMs(h.logger, "#endc_configuration_update_handler.Handle - Summary: Elapsed time for receiving and handling endc configuration update initiating message from E2 terminator", request.StartTime) + h.logger.Infof("#endc_configuration_update_handler.Handle - Endc configuration update initiating message received") + h.logger.Debugf("#endc_configuration_update_handler.Handle - Endc configuration update initiating message payload: %s", refinedMessage.PduPrint) + msg := models.NewRmrMessage(rmrCgo.RIC_ENDC_CONF_UPDATE_ACK, request.RanName, e2pdus.PackedEndcConfigurationUpdateAck, request.TransactionId) + _ = h.rmrSender.Send(msg) + + h.logger.Infof("#EndcConfigurationUpdateHandler.Handle - Summary: elapsed time for receiving and handling endc configuration update initiating message from E2 terminator: %f ms", utils.ElapsedTime(request.StartTime)) } diff --git a/E2Manager/handlers/rmrmsghandlers/endc_configuration_update_handler_test.go b/E2Manager/handlers/rmrmsghandlers/endc_configuration_update_handler_test.go index b7518a1..c14b89d 100644 --- a/E2Manager/handlers/rmrmsghandlers/endc_configuration_update_handler_test.go +++ b/E2Manager/handlers/rmrmsghandlers/endc_configuration_update_handler_test.go @@ -40,13 +40,14 @@ func TestHandleEndcConfigUpdateSuccess(t *testing.T) { h, rmrMessengerMock := initEndcConfigurationUpdateHandlerTest(t) ranName := "test" - xaction := []byte(ranName) + xAction := []byte("123456aa") var payload []byte _, _ = fmt.Sscanf(PackedEndcConfigurationUpdateAck, "%x", &payload) - mBuf := rmrCgo.NewMBuf(rmrCgo.RIC_ENDC_CONF_UPDATE_ACK, len(payload), ranName, &payload, &xaction) - notificationRequest := models.NotificationRequest{RanName: mBuf.Meid, Len: mBuf.Len, Payload: *mBuf.Payload, StartTime: time.Now()} + mBuf := rmrCgo.NewMBuf(rmrCgo.RIC_ENDC_CONF_UPDATE_ACK, len(payload), ranName, &payload, &xAction) + notificationRequest := models.NotificationRequest{RanName: mBuf.Meid, Len: mBuf.Len, Payload: *mBuf.Payload, StartTime: time.Now(), + TransactionId: *mBuf.XAction} var err error rmrMessengerMock.On("SendMsg", mBuf).Return(&rmrCgo.MBuf{}, err) h.Handle(¬ificationRequest) @@ -57,13 +58,14 @@ func TestHandleEndcConfigUpdateFailure(t *testing.T) { h, rmrMessengerMock := initEndcConfigurationUpdateHandlerTest(t) ranName := "test" - xaction := []byte(ranName) + xAction := []byte("123456aa") var payload []byte _, _ = fmt.Sscanf(PackedEndcConfigurationUpdateFailure, "%x", &payload) - mBuf := rmrCgo.NewMBuf(rmrCgo.RIC_ENDC_CONF_UPDATE_FAILURE, len(payload), ranName, &payload, &xaction) - notificationRequest := models.NotificationRequest{RanName: mBuf.Meid, Len: 0, Payload: []byte{0}, StartTime: time.Now()} + mBuf := rmrCgo.NewMBuf(rmrCgo.RIC_ENDC_CONF_UPDATE_FAILURE, len(payload), ranName, &payload, &xAction) + notificationRequest := models.NotificationRequest{RanName: mBuf.Meid, Len: 0, Payload: []byte{0}, StartTime: time.Now(), + TransactionId: *mBuf.XAction} rmrMessengerMock.On("SendMsg", mBuf).Return(&rmrCgo.MBuf{}, fmt.Errorf("send failure")) h.Handle(¬ificationRequest) rmrMessengerMock.AssertCalled(t, "SendMsg", mBuf) diff --git a/E2Manager/handlers/rmrmsghandlers/notification_handler.go b/E2Manager/handlers/rmrmsghandlers/notification_handler.go index ec1b887..db4174f 100644 --- a/E2Manager/handlers/rmrmsghandlers/notification_handler.go +++ b/E2Manager/handlers/rmrmsghandlers/notification_handler.go @@ -18,16 +18,9 @@ package rmrmsghandlers import ( - "e2mgr/logger" "e2mgr/models" - "time" ) type NotificationHandler interface { Handle(*models.NotificationRequest) } - -//TODO: remove that -func printHandlingSetupResponseElapsedTimeInMs(logger *logger.Logger, msg string, startTime time.Time) { - logger.Infof("%s: %f ms", msg, float64(time.Since(startTime))/float64(time.Millisecond)) -} diff --git a/E2Manager/handlers/rmrmsghandlers/setup_response_notification_handler_test.go b/E2Manager/handlers/rmrmsghandlers/setup_response_notification_handler_test.go index 55f6012..5e2eca2 100644 --- a/E2Manager/handlers/rmrmsghandlers/setup_response_notification_handler_test.go +++ b/E2Manager/handlers/rmrmsghandlers/setup_response_notification_handler_test.go @@ -26,7 +26,6 @@ import ( "e2mgr/managers" "e2mgr/mocks" "e2mgr/models" - "e2mgr/rNibWriter" "e2mgr/rmrCgo" "e2mgr/services" "e2mgr/services/rmrsender" @@ -34,7 +33,6 @@ import ( "fmt" "gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/common" "gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/entities" - "gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/reader" "github.com/pkg/errors" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" @@ -81,13 +79,8 @@ func NewSetupResponseTestContext(manager managers.ISetupResponseManager) *setupR config := &configuration.Configuration{RnibRetryIntervalMs: 10, MaxRnibConnectionAttempts: 3} readerMock := &mocks.RnibReaderMock{} writerMock := &mocks.RnibWriterMock{} - rnibReaderProvider := func() reader.RNibReader { - return readerMock - } - rnibWriterProvider := func() rNibWriter.RNibWriter { - return writerMock - } - rnibDataService := services.NewRnibDataService(logger, config, rnibReaderProvider, rnibWriterProvider) + + rnibDataService := services.NewRnibDataService(logger, config, readerMock, writerMock) rmrMessengerMock := &mocks.RmrMessengerMock{} rmrSender := initRmrSender(rmrMessengerMock, logger) @@ -161,10 +154,10 @@ func executeHandleSetupSuccessResponse(t *testing.T, tc setupSuccessResponseTest } func getRanConnectedMbuf(nodeType entities.Node_Type) *rmrCgo.MBuf { - xaction := []byte(RanName) + var xAction []byte resourceStatusPayload := models.NewResourceStatusPayload(nodeType, enums.RIC_TO_RAN) resourceStatusJson, _ := json.Marshal(resourceStatusPayload) - return rmrCgo.NewMBuf(rmrCgo.RAN_CONNECTED, len(resourceStatusJson), RanName, &resourceStatusJson, &xaction) + return rmrCgo.NewMBuf(rmrCgo.RAN_CONNECTED, len(resourceStatusJson), RanName, &resourceStatusJson, &xAction) } func executeHandleSetupFailureResponse(t *testing.T, tc setupFailureResponseTestCase) (*setupResponseTestContext, *entities.NodebInfo) { @@ -243,11 +236,12 @@ func TestX2SetupFailureResponse(t *testing.T) { } func TestEndcSetupResponse(t *testing.T) { + logger := initLog(t) var saveNodebMockError error var sendMsgError error tc := setupSuccessResponseTestCase{ EndcSetupResponsePackedPdu, - &managers.EndcSetupResponseManager{}, + managers.NewEndcSetupResponseManager(converters.NewEndcSetupResponseConverter(logger)), rmrCgo.RIC_ENDC_X2_SETUP_RESP, saveNodebMockError, sendMsgError, @@ -268,11 +262,11 @@ func TestEndcSetupResponse(t *testing.T) { } func TestEndcSetupFailureResponse(t *testing.T) { - + logger := initLog(t) var saveNodebMockError error tc := setupFailureResponseTestCase{ EndcSetupFailureResponsePackedPdu, - &managers.EndcSetupFailureResponseManager{}, + managers.NewEndcSetupFailureResponseManager(converters.NewEndcSetupFailureResponseConverter(logger)), rmrCgo.RIC_ENDC_X2_SETUP_FAILURE, saveNodebMockError, } diff --git a/E2Manager/handlers/rmrmsghandlers/x2_reset_request_notification_handler.go b/E2Manager/handlers/rmrmsghandlers/x2_reset_request_notification_handler.go index 0c5848f..1417539 100644 --- a/E2Manager/handlers/rmrmsghandlers/x2_reset_request_notification_handler.go +++ b/E2Manager/handlers/rmrmsghandlers/x2_reset_request_notification_handler.go @@ -17,11 +17,6 @@ package rmrmsghandlers -// #cgo CFLAGS: -I../../asn1codec/inc/ -I../../asn1codec/e2ap_engine/ -// #cgo LDFLAGS: -L ../../asn1codec/lib/ -L../../asn1codec/e2ap_engine/ -le2ap_codec -lasncodec -// #include -// #include -import "C" import ( "e2mgr/e2pdus" "e2mgr/enums" @@ -32,9 +27,7 @@ import ( "e2mgr/services" "e2mgr/services/rmrsender" "e2mgr/utils" - "fmt" "gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/entities" - "unsafe" ) type X2ResetRequestNotificationHandler struct { @@ -78,27 +71,9 @@ func (h X2ResetRequestNotificationHandler) Handle(request *models.NotificationRe return } - msg, err := createX2ResetResponseNotification(request) - if err != nil { - h.logger.Errorf("#X2ResetRequestNotificationHandler.Handle - %s", err) - return - } + msg := models.NewRmrMessage(rmrCgo.RIC_X2_RESET_RESP, request.RanName, e2pdus.PackedX2ResetResponse, request.TransactionId) _ = h.rmrSender.Send(msg) h.logger.Infof("#X2ResetRequestNotificationHandler.Handle - Summary: elapsed time for receiving and handling reset request message from E2 terminator: %f ms", utils.ElapsedTime(request.StartTime)) _ = h.ranStatusChangeManager.Execute(rmrCgo.RAN_RESTARTED, enums.RAN_TO_RIC, nb) } - -func createX2ResetResponseNotification(request *models.NotificationRequest) (*models.RmrMessage, error) { - - packedBuffer := make([]C.uchar, e2pdus.MaxAsn1PackedBufferSize) - errorBuffer := make([]C.char, e2pdus.MaxAsn1CodecMessageBufferSize) - var payloadSize = C.ulong(e2pdus.MaxAsn1PackedBufferSize) - - if status := C.build_pack_x2reset_response(&payloadSize, &packedBuffer[0], C.ulong(e2pdus.MaxAsn1CodecMessageBufferSize), &errorBuffer[0]); !status { - return nil, fmt.Errorf("failed to build and pack the reset response message %s ", C.GoString(&errorBuffer[0])) - } - payload := C.GoBytes(unsafe.Pointer(&packedBuffer[0]), C.int(payloadSize)) - msg := models.NewRmrMessage(rmrCgo.RIC_X2_RESET_RESP, request.RanName, payload) - return msg, nil -} diff --git a/E2Manager/handlers/rmrmsghandlers/x2_reset_request_notification_handler_test.go b/E2Manager/handlers/rmrmsghandlers/x2_reset_request_notification_handler_test.go index 95b0306..41c78f1 100644 --- a/E2Manager/handlers/rmrmsghandlers/x2_reset_request_notification_handler_test.go +++ b/E2Manager/handlers/rmrmsghandlers/x2_reset_request_notification_handler_test.go @@ -30,7 +30,6 @@ import ( "encoding/json" "gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/common" "gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/entities" - "gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/reader" "testing" "time" ) @@ -39,10 +38,8 @@ func initX2ResetRequestNotificationHandlerTest(t *testing.T) (X2ResetRequestNoti log := initLog(t) config := &configuration.Configuration{RnibRetryIntervalMs: 10, MaxRnibConnectionAttempts: 3} readerMock := &mocks.RnibReaderMock{} - readerProvider := func() reader.RNibReader { - return readerMock - } - rnibDataService := services.NewRnibDataService(log, config, readerProvider, nil) + + rnibDataService := services.NewRnibDataService(log, config, readerMock, nil) rmrMessengerMock := &mocks.RmrMessengerMock{} rmrSender := initRmrSender(rmrMessengerMock, log) @@ -52,22 +49,22 @@ func initX2ResetRequestNotificationHandlerTest(t *testing.T) (X2ResetRequestNoti } func getRanRestartedMbuf(nodeType entities.Node_Type, messageDirection enums.MessageDirection) *rmrCgo.MBuf { - xaction := []byte(RanName) + var xAction []byte resourceStatusPayload := models.NewResourceStatusPayload(nodeType, messageDirection) resourceStatusJson, _ := json.Marshal(resourceStatusPayload) - return rmrCgo.NewMBuf(rmrCgo.RAN_RESTARTED, len(resourceStatusJson), RanName, &resourceStatusJson, &xaction) + return rmrCgo.NewMBuf(rmrCgo.RAN_RESTARTED, len(resourceStatusJson), RanName, &resourceStatusJson, &xAction) } func TestHandleX2ResetRequestNotificationSuccess(t *testing.T) { h, readerMock, rmrMessengerMock := initX2ResetRequestNotificationHandlerTest(t) ranName := "test" - xaction := []byte(ranName) - notificationRequest := models.NewNotificationRequest(ranName, []byte{}, time.Now(), ranName) + xAction := []byte("123456aa") + notificationRequest := models.NewNotificationRequest(ranName, []byte{}, time.Now(), xAction) nb := &entities.NodebInfo{RanName: ranName, ConnectionStatus: entities.ConnectionStatus_CONNECTED, NodeType: entities.Node_ENB} var err error readerMock.On("GetNodeb", ranName).Return(nb, err) - resetResponseMbuf := rmrCgo.NewMBuf(rmrCgo.RIC_X2_RESET_RESP, len(e2pdus.PackedX2ResetResponse), ranName, &e2pdus.PackedX2ResetResponse, &xaction) + resetResponseMbuf := rmrCgo.NewMBuf(rmrCgo.RIC_X2_RESET_RESP, len(e2pdus.PackedX2ResetResponse), ranName, &e2pdus.PackedX2ResetResponse, &xAction) rmrMessengerMock.On("SendMsg", resetResponseMbuf).Return(&rmrCgo.MBuf{}, err) ranRestartedMbuf := getRanRestartedMbuf(nb.NodeType, enums.RAN_TO_RIC) rmrMessengerMock.On("SendMsg", ranRestartedMbuf).Return(&rmrCgo.MBuf{}, err) @@ -80,10 +77,10 @@ func TestHandleX2ResetRequestNotificationShuttingDownStatus(t *testing.T) { h, readerMock, rmrMessengerMock := initX2ResetRequestNotificationHandlerTest(t) var payload []byte - xaction := []byte("RanName") - mBuf := rmrCgo.NewMBuf(tests.MessageType, len(payload), "RanName", &payload, &xaction) + xAction := []byte("123456aa") + mBuf := rmrCgo.NewMBuf(tests.MessageType, len(payload), "RanName", &payload, &xAction) notificationRequest := models.NotificationRequest{RanName: mBuf.Meid, Len: mBuf.Len, Payload: *mBuf.Payload, - StartTime: time.Now(), TransactionId: string(xaction)} + StartTime: time.Now(), TransactionId: xAction} nb := &entities.NodebInfo{RanName: mBuf.Meid, ConnectionStatus: entities.ConnectionStatus_SHUTTING_DOWN,} var rnibErr error @@ -97,9 +94,9 @@ func TestHandleX2ResetRequestNotificationShuttingDownStatus(t *testing.T) { func TestHandleX2ResetRequestNotificationDisconnectStatus(t *testing.T) { h, readerMock, rmrMessengerMock := initX2ResetRequestNotificationHandlerTest(t) var payload []byte - xaction := []byte("RanName") - mBuf := rmrCgo.NewMBuf(tests.MessageType, len(payload), "RanName", &payload, &xaction) - notificationRequest := models.NotificationRequest{RanName: mBuf.Meid, Len: mBuf.Len, Payload: *mBuf.Payload, StartTime: time.Now(), TransactionId: string(xaction)} + xAction := []byte("123456aa") + mBuf := rmrCgo.NewMBuf(tests.MessageType, len(payload), "RanName", &payload, &xAction) + notificationRequest := models.NotificationRequest{RanName: mBuf.Meid, Len: mBuf.Len, Payload: *mBuf.Payload, StartTime: time.Now(), TransactionId: xAction} nb := &entities.NodebInfo{RanName: mBuf.Meid, ConnectionStatus: entities.ConnectionStatus_DISCONNECTED,} var rnibErr error readerMock.On("GetNodeb", mBuf.Meid).Return(nb, rnibErr) @@ -112,10 +109,10 @@ func TestHandleX2ResetRequestNotificationGetNodebFailed(t *testing.T) { h, readerMock, rmrMessengerMock := initX2ResetRequestNotificationHandlerTest(t) var payload []byte - xaction := []byte("RanName") - mBuf := rmrCgo.NewMBuf(tests.MessageType, len(payload), "RanName", &payload, &xaction) + var xAction []byte + mBuf := rmrCgo.NewMBuf(tests.MessageType, len(payload), "RanName", &payload, &xAction) notificationRequest := models.NotificationRequest{RanName: mBuf.Meid, Len: mBuf.Len, Payload: *mBuf.Payload, - StartTime: time.Now(), TransactionId: string(xaction)} + StartTime: time.Now(), TransactionId: xAction} var nb *entities.NodebInfo rnibErr := &common.ResourceNotFoundError{} diff --git a/E2Manager/handlers/rmrmsghandlers/x2_reset_response_handler.go b/E2Manager/handlers/rmrmsghandlers/x2_reset_response_handler.go index 3d6bd23..b23a3ba 100644 --- a/E2Manager/handlers/rmrmsghandlers/x2_reset_response_handler.go +++ b/E2Manager/handlers/rmrmsghandlers/x2_reset_response_handler.go @@ -17,10 +17,6 @@ package rmrmsghandlers -// #cgo CFLAGS: -I../../asn1codec/inc/ -I../../asn1codec/e2ap_engine/ -// #cgo LDFLAGS: -L ../../asn1codec/lib/ -L../../asn1codec/e2ap_engine/ -le2ap_codec -lasncodec -// #include -import "C" import ( "e2mgr/converters" "e2mgr/enums" @@ -53,7 +49,7 @@ func (h X2ResetResponseHandler) Handle(request *models.NotificationRequest) { ranName := request.RanName h.logger.Infof("#X2ResetResponseHandler.Handle - RAN name: %s - received reset response. Payload: %x", ranName, request.Payload) - nodebInfo, err := h.rnibDataService.GetNodeb(ranName); + nodebInfo, err := h.rnibDataService.GetNodeb(ranName) if err != nil { h.logger.Errorf("#x2ResetResponseHandler.Handle - RAN name: %s - failed to retrieve nodebInfo entity. Error: %s", ranName, err) return diff --git a/E2Manager/handlers/rmrmsghandlers/x2_reset_response_handler_test.go b/E2Manager/handlers/rmrmsghandlers/x2_reset_response_handler_test.go index c051eeb..7504f1d 100644 --- a/E2Manager/handlers/rmrmsghandlers/x2_reset_response_handler_test.go +++ b/E2Manager/handlers/rmrmsghandlers/x2_reset_response_handler_test.go @@ -30,7 +30,6 @@ import ( "fmt" "gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/common" "gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/entities" - "gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/reader" "testing" "time" ) @@ -48,11 +47,8 @@ func initX2ResetResponseHandlerTest(t *testing.T) (X2ResetResponseHandler, *mock t.Errorf("#initX2ResetResponseHandlerTest - failed to initialize logger, error: %s", err) } readerMock := &mocks.RnibReaderMock{} - rnibReaderProvider := func() reader.RNibReader { - return readerMock - } - rnibDataService := services.NewRnibDataService(log, config, rnibReaderProvider, nil) + rnibDataService := services.NewRnibDataService(log, config, readerMock, nil) rmrMessengerMock := &mocks.RmrMessengerMock{} rmrSender := initRmrSender(rmrMessengerMock, log) @@ -70,8 +66,8 @@ func TestX2ResetResponseSuccess(t *testing.T) { t.Fatalf("Failed converting packed pdu. Error: %v\n", err) } - xaction := []byte(RanName) - notificationRequest := models.NotificationRequest{RanName: RanName, Len: len(payload), Payload: payload, StartTime: time.Now(), TransactionId: string(xaction)} + var xAction []byte + notificationRequest := models.NotificationRequest{RanName: RanName, Len: len(payload), Payload: payload, StartTime: time.Now(), TransactionId: xAction} nb := &entities.NodebInfo{RanName: RanName, ConnectionStatus: entities.ConnectionStatus_CONNECTED, NodeType: entities.Node_ENB} var rnibErr error readerMock.On("GetNodeb", RanName).Return(nb, rnibErr) @@ -89,8 +85,8 @@ func TestX2ResetResponseSuccessEmptyIEs(t *testing.T) { t.Fatalf("Failed converting packed pdu. Error: %v\n", err) } - xaction := []byte(RanName) - notificationRequest := models.NotificationRequest{RanName: RanName, Len: len(payload), Payload: payload, StartTime: time.Now(), TransactionId: string(xaction)} + var xAction []byte + notificationRequest := models.NotificationRequest{RanName: RanName, Len: len(payload), Payload: payload, StartTime: time.Now(), TransactionId: xAction} nb := &entities.NodebInfo{RanName: RanName, ConnectionStatus: entities.ConnectionStatus_CONNECTED, NodeType: entities.Node_ENB} var rnibErr error readerMock.On("GetNodeb", RanName).Return(nb, rnibErr) @@ -108,8 +104,8 @@ func TestX2ResetResponseShuttingDown(t *testing.T) { t.Fatalf("Failed converting packed pdu. Error: %v\n", err) } - xaction := []byte(RanName) - notificationRequest := models.NotificationRequest{RanName: RanName, Len: len(payload), Payload: payload, StartTime: time.Now(), TransactionId: string(xaction)} + var xAction []byte + notificationRequest := models.NotificationRequest{RanName: RanName, Len: len(payload), Payload: payload, StartTime: time.Now(), TransactionId: xAction} nb := &entities.NodebInfo{RanName: RanName, ConnectionStatus: entities.ConnectionStatus_SHUTTING_DOWN, NodeType: entities.Node_ENB} var rnibErr error readerMock.On("GetNodeb", RanName).Return(nb, rnibErr) @@ -125,8 +121,8 @@ func TestX2ResetResponseInvalidConnectionStatus(t *testing.T) { t.Fatalf("Failed converting packed pdu. Error: %v\n", err) } - xaction := []byte(RanName) - notificationRequest := models.NotificationRequest{RanName: RanName, Len: len(payload), Payload: payload, StartTime: time.Now(), TransactionId: string(xaction)} + var xAction []byte + notificationRequest := models.NotificationRequest{RanName: RanName, Len: len(payload), Payload: payload, StartTime: time.Now(), TransactionId: xAction} nb := &entities.NodebInfo{RanName: RanName, ConnectionStatus: entities.ConnectionStatus_DISCONNECTED, NodeType: entities.Node_ENB} var rnibErr error readerMock.On("GetNodeb", RanName).Return(nb, rnibErr) @@ -142,8 +138,8 @@ func TestX2ResetResponseError(t *testing.T) { t.Fatalf("Failed converting packed pdu. Error: %v\n", err) } - xaction := []byte(RanName) - notificationRequest := models.NotificationRequest{RanName: RanName, Len: len(payload), Payload: payload, StartTime: time.Now(), TransactionId: string(xaction)} + var xAction []byte + notificationRequest := models.NotificationRequest{RanName: RanName, Len: len(payload), Payload: payload, StartTime: time.Now(), TransactionId: xAction} nb := &entities.NodebInfo{RanName: RanName, ConnectionStatus: entities.ConnectionStatus_CONNECTED, NodeType: entities.Node_ENB} var rnibErr error readerMock.On("GetNodeb", RanName).Return(nb, rnibErr) @@ -160,8 +156,8 @@ func TestX2ResetResponseGetNodebFailure(t *testing.T) { t.Fatalf("Failed converting packed pdu. Error: %v\n", err) } - xaction := []byte(RanName) - notificationRequest := models.NotificationRequest{RanName: RanName, Len: len(payload), Payload: payload, StartTime: time.Now(), TransactionId: string(xaction)} + var xAction []byte + notificationRequest := models.NotificationRequest{RanName: RanName, Len: len(payload), Payload: payload, StartTime: time.Now(), TransactionId: xAction} var nb *entities.NodebInfo rnibErr := common.NewResourceNotFoundError("nodeb not found") @@ -175,8 +171,8 @@ func TestX2ResetResponseUnpackFailure(t *testing.T) { h, readerMock, rmrMessengerMock := initX2ResetResponseHandlerTest(t) payload := []byte("Invalid payload") - xaction := []byte(RanName) - notificationRequest := models.NotificationRequest{RanName: RanName, Len: len(payload), Payload: payload, StartTime: time.Now(), TransactionId: string(xaction)} + var xAction []byte + notificationRequest := models.NotificationRequest{RanName: RanName, Len: len(payload), Payload: payload, StartTime: time.Now(), TransactionId: xAction} nb := &entities.NodebInfo{RanName: RanName, ConnectionStatus: entities.ConnectionStatus_CONNECTED, NodeType: entities.Node_ENB} var rnibErr error readerMock.On("GetNodeb", RanName).Return(nb, rnibErr) diff --git a/E2Manager/handlers/rmrmsghandlers/x2enb_configuration_update_handler.go b/E2Manager/handlers/rmrmsghandlers/x2enb_configuration_update_handler.go index 77a09b3..3bc7ab2 100644 --- a/E2Manager/handlers/rmrmsghandlers/x2enb_configuration_update_handler.go +++ b/E2Manager/handlers/rmrmsghandlers/x2enb_configuration_update_handler.go @@ -17,10 +17,6 @@ package rmrmsghandlers -// #cgo CFLAGS: -I../../asn1codec/inc/ -I../../asn1codec/e2ap_engine/ -// #cgo LDFLAGS: -L ../../asn1codec/lib/ -L../../asn1codec/e2ap_engine/ -le2ap_codec -lasncodec -// #include -// #include import "C" import ( "e2mgr/converters" @@ -29,7 +25,7 @@ import ( "e2mgr/models" "e2mgr/rmrCgo" "e2mgr/services/rmrsender" - "unsafe" + "e2mgr/utils" ) type X2EnbConfigurationUpdateHandler struct { @@ -46,40 +42,23 @@ func NewX2EnbConfigurationUpdateHandler(logger *logger.Logger, rmrSender *rmrsen func (h X2EnbConfigurationUpdateHandler) Handle(request *models.NotificationRequest) { - var payloadSize C.ulong - payloadSize = e2pdus.MaxAsn1PackedBufferSize - packedBuffer := [e2pdus.MaxAsn1PackedBufferSize]C.uchar{} - errorBuffer := [e2pdus.MaxAsn1PackedBufferSize]C.char{} - refinedMessage, err := converters.UnpackX2apPduAndRefine(h.logger, e2pdus.MaxAsn1CodecAllocationBufferSize, request.Len, request.Payload, e2pdus.MaxAsn1CodecMessageBufferSize) if err != nil { - status := C.build_pack_x2enb_configuration_update_failure(&payloadSize, &packedBuffer[0], e2pdus.MaxAsn1PackedBufferSize, &errorBuffer[0]) - if status { - payload := (*[1 << 30]byte)(unsafe.Pointer(&packedBuffer))[:payloadSize:payloadSize] - h.logger.Debugf("#x2enb_configuration_update_handler.Handle - Enb configuration update negative ack message payload: (%d) %02x", len(payload), payload) - msg := models.NewRmrMessage(rmrCgo.RIC_ENB_CONFIGURATION_UPDATE_FAILURE, request.RanName, payload) - _ = h.rmrSender.Send(msg) - } else { - h.logger.Errorf("#x2enb_configuration_update_handler.Handle - failed to build and pack Enb configuration update unsuccessful outcome message. Error: %v", errorBuffer) - } h.logger.Errorf("#x2enb_configuration_update_handler.Handle - unpack failed. Error: %v", err) - printHandlingSetupResponseElapsedTimeInMs(h.logger, "#x2enb_configuration_update_handler.Handle - Summary: Elapsed time for receiving and handling enb configuration update initiating message from E2 terminator", request.StartTime) + msg := models.NewRmrMessage(rmrCgo.RIC_ENB_CONFIGURATION_UPDATE_FAILURE, request.RanName, e2pdus.PackedX2EnbConfigurationUpdateFailure, request.TransactionId) + _ = h.rmrSender.Send(msg) + + h.logger.Infof("#X2EnbConfigurationUpdateHandler.Handle - Summary: elapsed time for receiving and handling enb configuration update initiating message from E2 terminator: %f ms", utils.ElapsedTime(request.StartTime)) return } h.logger.Infof("#x2enb_configuration_update_handler.Handle - Enb configuration update initiating message received") h.logger.Debugf("#x2enb_configuration_update_handler.Handle - Enb configuration update initiating message payload: %s", refinedMessage.PduPrint) - status := C.build_pack_x2enb_configuration_update_ack(&payloadSize, &packedBuffer[0], e2pdus.MaxAsn1PackedBufferSize, &errorBuffer[0]) - if status { - payload := (*[1 << 30]byte)(unsafe.Pointer(&packedBuffer))[:payloadSize:payloadSize] - h.logger.Debugf("#x2enb_configuration_update_handler.Handle - Enb configuration update positive ack message payload: (%d) %02x", len(payload), payload) - msg := models.NewRmrMessage(rmrCgo.RIC_ENB_CONFIGURATION_UPDATE_ACK, request.RanName, payload) - _ = h.rmrSender.Send(msg) - } else { - h.logger.Errorf("#x2enb_configuration_update_handler.Handle - failed to build and pack enb configuration update successful outcome message. Error: %v", errorBuffer) - } - printHandlingSetupResponseElapsedTimeInMs(h.logger, "#x2enb_configuration_update_handler.Handle - Summary: Elapsed time for receiving and handling enb configuration update initiating message from E2 terminator", request.StartTime) + msg := models.NewRmrMessage(rmrCgo.RIC_ENB_CONFIGURATION_UPDATE_ACK, request.RanName, e2pdus.PackedX2EnbConfigurationUpdateAck,request.TransactionId) + _ = h.rmrSender.Send(msg) + + h.logger.Infof("#X2EnbConfigurationUpdateHandler.Handle - Summary: elapsed time for receiving and handling enb configuration update initiating message from E2 terminator: %f ms", utils.ElapsedTime(request.StartTime)) } diff --git a/E2Manager/handlers/rmrmsghandlers/x2enb_configuration_update_handler_test.go b/E2Manager/handlers/rmrmsghandlers/x2enb_configuration_update_handler_test.go index 30ba645..2d55bd1 100644 --- a/E2Manager/handlers/rmrmsghandlers/x2enb_configuration_update_handler_test.go +++ b/E2Manager/handlers/rmrmsghandlers/x2enb_configuration_update_handler_test.go @@ -40,13 +40,13 @@ func TestHandleX2EnbConfigUpdateSuccess(t *testing.T) { h, rmrMessengerMock := initX2EnbConfigurationUpdateHandlerTest(t) ranName := "test" - xaction := []byte(ranName) - + xAction := []byte("123456aa") var payload []byte _, _ = fmt.Sscanf(PackedX2EnbConfigurationUpdateAck, "%x", &payload) - mBuf := rmrCgo.NewMBuf(rmrCgo.RIC_ENB_CONFIGURATION_UPDATE_ACK, len(payload), ranName, &payload, &xaction) - notificationRequest := models.NotificationRequest{RanName: mBuf.Meid, Len: mBuf.Len, Payload: *mBuf.Payload, StartTime: time.Now()} + mBuf := rmrCgo.NewMBuf(rmrCgo.RIC_ENB_CONFIGURATION_UPDATE_ACK, len(payload), ranName, &payload, &xAction) + notificationRequest := models.NotificationRequest{RanName: mBuf.Meid, Len: mBuf.Len, Payload: *mBuf.Payload, + StartTime: time.Now(), TransactionId:xAction} var err error rmrMessengerMock.On("SendMsg", mBuf).Return(&rmrCgo.MBuf{}, err) h.Handle(¬ificationRequest) @@ -57,13 +57,14 @@ func TestHandleX2EnbConfigUpdateFailure(t *testing.T) { h, rmrMessengerMock := initX2EnbConfigurationUpdateHandlerTest(t) ranName := "test" - xaction := []byte(ranName) + xAction := []byte("123456aa") var payload []byte _, _ = fmt.Sscanf(PackedX2EnbConfigurationUpdateFailure, "%x", &payload) - mBuf := rmrCgo.NewMBuf(rmrCgo.RIC_ENB_CONFIGURATION_UPDATE_FAILURE, len(payload), ranName, &payload, &xaction) - notificationRequest := models.NotificationRequest{RanName: mBuf.Meid, Len: 0, Payload: []byte{0}, StartTime: time.Now()} + mBuf := rmrCgo.NewMBuf(rmrCgo.RIC_ENB_CONFIGURATION_UPDATE_FAILURE, len(payload), ranName, &payload, &xAction) + notificationRequest := models.NotificationRequest{RanName: mBuf.Meid, Len: 0, Payload: []byte{0}, + StartTime: time.Now(), TransactionId:xAction} rmrMessengerMock.On("SendMsg", mBuf).Return(&rmrCgo.MBuf{}, fmt.Errorf("send failure")) h.Handle(¬ificationRequest) rmrMessengerMock.AssertCalled(t, "SendMsg", mBuf) diff --git a/E2Manager/httpserver/http_server.go b/E2Manager/httpserver/http_server.go index d6ade1e..741018f 100644 --- a/E2Manager/httpserver/http_server.go +++ b/E2Manager/httpserver/http_server.go @@ -19,13 +19,13 @@ package httpserver import ( "e2mgr/controllers" + "e2mgr/logger" "fmt" "github.com/gorilla/mux" - "log" "net/http" ) -func Run(port int, controller controllers.IRootController, newController controllers.INodebController) { +func Run(log *logger.Logger, port int, controller controllers.IRootController, newController controllers.INodebController) error { router := mux.NewRouter(); initializeRoutes(router, controller, newController) @@ -34,9 +34,8 @@ func Run(port int, controller controllers.IRootController, newController control err := http.ListenAndServe(addr, router) - if err != nil { - log.Fatalf("#http_server.Run - Fail initiating HTTP server. Error: %v", err) - } + log.Errorf("#http_server.Run - Fail initiating HTTP server. Error: %v", err) + return err } func initializeRoutes(router *mux.Router, rootController controllers.IRootController, nodebController controllers.INodebController) { diff --git a/E2Manager/httpserver/http_server_test.go b/E2Manager/httpserver/http_server_test.go index 3d4d3d5..059e017 100644 --- a/E2Manager/httpserver/http_server_test.go +++ b/E2Manager/httpserver/http_server_test.go @@ -18,12 +18,14 @@ package httpserver import ( + "e2mgr/logger" "e2mgr/mocks" "github.com/gorilla/mux" "github.com/stretchr/testify/assert" "net/http" "net/http/httptest" "testing" + "time" ) func setupRouterAndMocks() (*mux.Router, *mocks.ControllerMock, *mocks.NodebControllerMock) { @@ -153,4 +155,31 @@ func TestRouteNotFound(t *testing.T) { router.ServeHTTP(rr, req) assert.Equal(t, http.StatusNotFound, rr.Code, "handler returned wrong status code") +} + +func TestRunError(t *testing.T) { + log := initLog(t) + err := Run(log, 1234567, &mocks.NodebControllerMock{}, &mocks.ControllerMock{}) + assert.NotNil(t, err) +} + +func TestRun(t *testing.T) { + log := initLog(t) + _, controllerMock, nodebControllerMock := setupRouterAndMocks() + go Run(log,11223, nodebControllerMock, controllerMock) + + time.Sleep(time.Millisecond * 100) + resp, err := http.Get("http://localhost:11223/v1/health") + if err != nil { + t.Fatalf("failed to perform GET to http://localhost:11223/v1/health") + } + assert.Equal(t, 200, resp.StatusCode) +} + +func initLog(t *testing.T) *logger.Logger { + log, err := logger.InitLogger(logger.InfoLevel) + if err != nil { + t.Errorf("#initLog test - failed to initialize logger, error: %s", err) + } + return log } \ No newline at end of file diff --git a/E2Manager/logger/logger_test.go b/E2Manager/logger/logger_test.go index 2c8eaf1..b06ab9d 100644 --- a/E2Manager/logger/logger_test.go +++ b/E2Manager/logger/logger_test.go @@ -41,6 +41,34 @@ func TestInitInfoLoggerSuccess(t *testing.T) { assert.True(t, log.Logger.Core().Enabled(zap.InfoLevel)) } +func TestInitWarnLoggerSuccess(t *testing.T) { + log, err := InitLogger(WarnLevel) + assert.Nil(t, err) + assert.NotNil(t, log) + assert.True(t, log.Logger.Core().Enabled(zap.WarnLevel)) +} + +func TestInitErrorLoggerSuccess(t *testing.T) { + log, err := InitLogger(ErrorLevel) + assert.Nil(t, err) + assert.NotNil(t, log) + assert.True(t, log.Logger.Core().Enabled(zap.ErrorLevel)) +} + +func TestInitDPanicLoggerSuccess(t *testing.T) { + log, err := InitLogger(DPanicLevel) + assert.Nil(t, err) + assert.NotNil(t, log) + assert.True(t, log.Logger.Core().Enabled(zap.DPanicLevel)) +} + +func TestInitPanicLoggerSuccess(t *testing.T) { + log, err := InitLogger(PanicLevel) + assert.Nil(t, err) + assert.NotNil(t, log) + assert.True(t, log.Logger.Core().Enabled(zap.PanicLevel)) +} + func TestInitInfoLoggerFailure(t *testing.T) { log, err := InitLogger(99) assert.NotNil(t, err) @@ -60,7 +88,7 @@ func TestSyncSuccess(t *testing.T){ } err = log.Sync() assert.Nil(t, err) - + os.Stdout = old logFile, err = os.Open("./loggerTest.txt") if err != nil{ @@ -141,6 +169,22 @@ func TestDebugfFatalLevel(t *testing.T) { assert.False(t,validateRecordExists(FatalLevel, zap.DebugLevel, t)) } +func TestWarnfWarnLevel(t *testing.T) { + assert.True(t,validateRecordExists(WarnLevel, zap.WarnLevel, t)) +} + +func TestWarnfDebugLevel(t *testing.T) { + assert.True(t,validateRecordExists(DebugLevel, zap.WarnLevel, t)) +} + +func TestWarnfInfoLevel(t *testing.T) { + assert.True(t,validateRecordExists(InfoLevel, zap.WarnLevel, t)) +} + +func TestWarnfFatalLevel(t *testing.T) { + assert.False(t,validateRecordExists(FatalLevel, zap.WarnLevel, t)) +} + func TestLogLevelTokenToLevel(t *testing.T) { level, ok := LogLevelTokenToLevel("deBug") assert.True(t, ok) @@ -215,14 +259,16 @@ func validateRecordExists(logLevel LogLevel, recordLevel zapcore.Level, t *testi t.Errorf("logger_test.TestSyncFailure - failed to initialize logger, error: %s", err) } switch recordLevel{ - case zap.DebugLevel: - log.Debugf("%v, %v, %v", 1, "abc", 0.1) - case zap.InfoLevel: - log.Infof("%v, %v, %v", 1, "abc", 0.1) - case zap.ErrorLevel: - log.Errorf("%v, %v, %v", 1, "abc", 0.1) - case zap.DPanicLevel: - log.DPanicf("%v, %v, %v", 1, "abc", 0.1) + case zap.DebugLevel: + log.Debugf("%v, %v, %v", 1, "abc", 0.1) + case zap.InfoLevel: + log.Infof("%v, %v, %v", 1, "abc", 0.1) + case zap.WarnLevel: + log.Warnf("%v, %v, %v", 1, "abc", 0.1) + case zap.ErrorLevel: + log.Errorf("%v, %v, %v", 1, "abc", 0.1) + case zap.DPanicLevel: + log.DPanicf("%v, %v, %v", 1, "abc", 0.1) } err = w.Close() if err != nil { @@ -241,4 +287,4 @@ func validateRecordExists(logLevel LogLevel, recordLevel zapcore.Level, t *testi s,_= buf.ReadString('\n') } return entryNum == 1 -} +} \ No newline at end of file diff --git a/E2Manager/managers/endc_setup_failure_response_manager.go b/E2Manager/managers/endc_setup_failure_response_manager.go index 52e21fe..f3aec4d 100644 --- a/E2Manager/managers/endc_setup_failure_response_manager.go +++ b/E2Manager/managers/endc_setup_failure_response_manager.go @@ -19,20 +19,23 @@ package managers import ( "e2mgr/converters" - "e2mgr/e2pdus" "e2mgr/logger" "gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/entities" ) -type EndcSetupFailureResponseManager struct{} +type EndcSetupFailureResponseManager struct { + converter converters.IEndcSetupFailureResponseConverter +} -func NewEndcSetupFailureResponseManager() *EndcSetupFailureResponseManager { - return &EndcSetupFailureResponseManager{} +func NewEndcSetupFailureResponseManager(converter converters.IEndcSetupFailureResponseConverter) *EndcSetupFailureResponseManager { + return &EndcSetupFailureResponseManager{ + converter: converter, + } } func (m *EndcSetupFailureResponseManager) PopulateNodebByPdu(logger *logger.Logger, nbIdentity *entities.NbIdentity, nodebInfo *entities.NodebInfo, payload []byte) error { - failureResponse, err := converters.UnpackEndcX2SetupFailureResponseAndExtract(logger, e2pdus.MaxAsn1CodecAllocationBufferSize, len(payload), payload, e2pdus.MaxAsn1CodecMessageBufferSize) + failureResponse, err := m.converter.UnpackEndcSetupFailureResponseAndExtract(payload) if err != nil { logger.Errorf("#EndcSetupFailureResponseManager.PopulateNodebByPdu - RAN name: %s - Unpack and extract failed. Error: %v", nodebInfo.RanName, err) diff --git a/E2Manager/managers/endc_setup_failure_response_manager_test.go b/E2Manager/managers/endc_setup_failure_response_manager_test.go new file mode 100644 index 0000000..4bdc9fa --- /dev/null +++ b/E2Manager/managers/endc_setup_failure_response_manager_test.go @@ -0,0 +1,66 @@ +// +// Copyright 2019 AT&T Intellectual Property +// Copyright 2019 Nokia +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +package managers + +import ( + "e2mgr/converters" + "e2mgr/tests" + "fmt" + "gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/entities" + "github.com/stretchr/testify/assert" + "math/rand" + "testing" +) + +func TestPopulateNodebByPduFailure(t *testing.T) { + logger := tests.InitLog(t) + nodebInfo := &entities.NodebInfo{} + nodebIdentity := &entities.NbIdentity{} + converter := converters.NewEndcSetupFailureResponseConverter(logger) + handler := NewEndcSetupFailureResponseManager(converter) + err := handler.PopulateNodebByPdu(logger, nodebIdentity, nodebInfo, createRandomPayload()) + assert.NotNil(t, err) +} + +func TestPopulateNodebByPduSuccess(t *testing.T) { + logger := tests.InitLog(t) + nodebInfo := &entities.NodebInfo{} + nodebIdentity := &entities.NbIdentity{} + converter := converters.NewEndcSetupFailureResponseConverter(logger) + handler := NewEndcSetupFailureResponseManager(converter) + err := handler.PopulateNodebByPdu(logger, nodebIdentity, nodebInfo, createSetupFailureResponsePayload(t)) + assert.Nil(t, err) + assert.Equal(t, entities.ConnectionStatus_CONNECTED_SETUP_FAILED, nodebInfo.ConnectionStatus) + assert.Equal(t, entities.Failure_ENDC_X2_SETUP_FAILURE, nodebInfo.FailureType) + +} + +func createSetupFailureResponsePayload(t *testing.T) []byte { + packedPdu := "4024001a0000030005400200000016400100001140087821a00000008040" + var payload []byte + _, err := fmt.Sscanf(packedPdu, "%x", &payload) + if err != nil { + t.Errorf("convert inputPayloadAsStr to payloadAsByte. Error: %v\n", err) + } + return payload +} + +func createRandomPayload() []byte { + payload := make([]byte, 20) + rand.Read(payload) + return payload +} diff --git a/E2Manager/managers/endc_setup_response_manager.go b/E2Manager/managers/endc_setup_response_manager.go index bf0bb59..0a20e51 100644 --- a/E2Manager/managers/endc_setup_response_manager.go +++ b/E2Manager/managers/endc_setup_response_manager.go @@ -19,20 +19,23 @@ package managers import ( "e2mgr/converters" - "e2mgr/e2pdus" "e2mgr/logger" "gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/entities" ) -type EndcSetupResponseManager struct{} +type EndcSetupResponseManager struct{ + converter converters.IEndcSetupResponseConverter +} -func NewEndcSetupResponseManager() *EndcSetupResponseManager { - return &EndcSetupResponseManager{} +func NewEndcSetupResponseManager(converter converters.IEndcSetupResponseConverter) *EndcSetupResponseManager { + return &EndcSetupResponseManager{ + converter: converter, + } } func (m *EndcSetupResponseManager) PopulateNodebByPdu(logger *logger.Logger, nbIdentity *entities.NbIdentity, nodebInfo *entities.NodebInfo, payload []byte) error { - gnbId, gnb, err := converters.UnpackEndcX2SetupResponseAndExtract(logger, e2pdus.MaxAsn1CodecAllocationBufferSize, len(payload), payload, e2pdus.MaxAsn1CodecMessageBufferSize) + gnbId, gnb, err := m.converter.UnpackEndcSetupResponseAndExtract(payload) if err != nil { logger.Errorf("#EndcSetupResponseManager.PopulateNodebByPdu - RAN name: %s - Unpack and extract failed. Error: %v", nodebInfo.RanName, err) diff --git a/E2Manager/managers/endc_setup_response_manager_test.go b/E2Manager/managers/endc_setup_response_manager_test.go new file mode 100644 index 0000000..55726c2 --- /dev/null +++ b/E2Manager/managers/endc_setup_response_manager_test.go @@ -0,0 +1,59 @@ +// +// Copyright 2019 AT&T Intellectual Property +// Copyright 2019 Nokia +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +package managers + +import ( + "e2mgr/converters" + "e2mgr/tests" + "fmt" + "gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/entities" + "github.com/stretchr/testify/assert" + "testing" +) + +func TestSetupResponsePopulateNodebByPduFailure(t *testing.T) { + logger := tests.InitLog(t) + nodebInfo := &entities.NodebInfo{} + nodebIdentity := &entities.NbIdentity{} + converter:= converters.NewEndcSetupResponseConverter(logger) + handler := NewEndcSetupResponseManager(converter) + err := handler.PopulateNodebByPdu(logger, nodebIdentity, nodebInfo, createRandomPayload()) + assert.NotNil(t, err) +} + +func TestSetupResponsePopulateNodebByPduSuccess(t *testing.T) { + logger := tests.InitLog(t) + nodebInfo := &entities.NodebInfo{} + nodebIdentity := &entities.NbIdentity{} + converter:= converters.NewEndcSetupResponseConverter(logger) + handler := NewEndcSetupResponseManager(converter) + err := handler.PopulateNodebByPdu(logger, nodebIdentity, nodebInfo, createSetupResponsePayload(t)) + assert.Nil(t, err) + assert.Equal(t, entities.ConnectionStatus_CONNECTED, nodebInfo.ConnectionStatus) + assert.Equal(t, entities.Node_GNB, nodebInfo.NodeType) + +} + +func createSetupResponsePayload(t *testing.T) []byte { + packedPdu := "202400808e00000100f600808640000200fc00090002f829504a952a0a00fd007200010c0005001e3f271f2e3d4ff03d44d34e4f003e4e5e4400010000150400000a000211e148033e4e5e4c0005001e3f271f2e3d4ff03d44d34e4f003e4e5e4400010000150400000a00021a0044033e4e5e000000002c001e3f271f2e3d4ff0031e3f274400010000150400000a00020000" + var payload []byte + _, err := fmt.Sscanf(packedPdu, "%x", &payload) + if err != nil { + t.Errorf("convert inputPayloadAsStr to payloadAsByte. Error: %v\n", err) + } + return payload +} diff --git a/E2Manager/managers/notificationmanager/notification_manager.go b/E2Manager/managers/notificationmanager/notification_manager.go index 12250d2..29b2cdf 100644 --- a/E2Manager/managers/notificationmanager/notification_manager.go +++ b/E2Manager/managers/notificationmanager/notification_manager.go @@ -46,7 +46,7 @@ func (m NotificationManager) HandleMessage(mbuf *rmrCgo.MBuf) error { return err } - notificationRequest := models.NewNotificationRequest(mbuf.Meid, *mbuf.Payload, time.Now(), string(*mbuf.XAction)) + notificationRequest := models.NewNotificationRequest(mbuf.Meid, *mbuf.Payload, time.Now(), *mbuf.XAction) go notificationHandler.Handle(notificationRequest) return nil } diff --git a/E2Manager/managers/notificationmanager/notification_manager_test.go b/E2Manager/managers/notificationmanager/notification_manager_test.go index 770ed02..051a50c 100644 --- a/E2Manager/managers/notificationmanager/notification_manager_test.go +++ b/E2Manager/managers/notificationmanager/notification_manager_test.go @@ -2,19 +2,16 @@ package notificationmanager import ( "e2mgr/configuration" - "e2mgr/converters" "e2mgr/logger" "e2mgr/managers" "e2mgr/mocks" "e2mgr/providers/rmrmsghandlerprovider" - "e2mgr/rNibWriter" "e2mgr/rmrCgo" "e2mgr/services" "e2mgr/services/rmrsender" "e2mgr/tests" "fmt" "gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/entities" - "gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/reader" "github.com/stretchr/testify/assert" "testing" ) @@ -24,24 +21,15 @@ func initNotificationManagerTest(t *testing.T) (*logger.Logger, *mocks.RnibReade config := &configuration.Configuration{RnibRetryIntervalMs: 10, MaxRnibConnectionAttempts: 3} readerMock := &mocks.RnibReaderMock{} - rnibReaderProvider := func() reader.RNibReader { - return readerMock - } + writerMock := &mocks.RnibWriterMock{} - rnibWriterProvider := func() rNibWriter.RNibWriter { - return writerMock - } + rmrSender := initRmrSender(&mocks.RmrMessengerMock{}, logger) - rnibDataService := services.NewRnibDataService(logger, config, rnibReaderProvider, rnibWriterProvider) + rnibDataService := services.NewRnibDataService(logger, config, readerMock, writerMock) ranSetupManager := managers.NewRanSetupManager(logger, rmrSender, rnibDataService) - ranReconnectionManager := managers.NewRanReconnectionManager(logger, configuration.ParseConfiguration(), rnibDataService, ranSetupManager) - ranStatusChangeManager := managers.NewRanStatusChangeManager(logger, rmrSender) - x2SetupResponseConverter := converters.NewX2SetupResponseConverter(logger) - x2SetupResponseManager := managers.NewX2SetupResponseManager(x2SetupResponseConverter) - x2SetupFailureResponseConverter := converters.NewX2SetupFailureResponseConverter(logger) - x2SetupFailureResponseManager := managers.NewX2SetupFailureResponseManager(x2SetupFailureResponseConverter) - rmrNotificationHandlerProvider := rmrmsghandlerprovider.NewNotificationHandlerProvider(logger, rnibDataService, ranReconnectionManager, ranStatusChangeManager, rmrSender, x2SetupResponseManager, x2SetupFailureResponseManager) + rmrNotificationHandlerProvider := rmrmsghandlerprovider.NewNotificationHandlerProvider() + rmrNotificationHandlerProvider.Init(logger, config, rnibDataService, rmrSender, ranSetupManager) notificationManager := NewNotificationManager(logger, rmrNotificationHandlerProvider ) return logger, readerMock, notificationManager } @@ -69,7 +57,7 @@ func TestHandleMessageExistingMessageType(t *testing.T) { func initRmrSender(rmrMessengerMock *mocks.RmrMessengerMock, log *logger.Logger) *rmrsender.RmrSender { rmrMessenger := rmrCgo.RmrMessenger(rmrMessengerMock) rmrMessengerMock.On("Init", tests.GetPort(), tests.MaxMsgSize, tests.Flags, log).Return(&rmrMessenger) - return rmrsender.NewRmrSender(log, &rmrMessenger) + return rmrsender.NewRmrSender(log, rmrMessenger) } // TODO: extract to test_utils diff --git a/E2Manager/managers/ran_reconnection_manager_test.go b/E2Manager/managers/ran_reconnection_manager_test.go index 3aeeeed..97a9f58 100644 --- a/E2Manager/managers/ran_reconnection_manager_test.go +++ b/E2Manager/managers/ran_reconnection_manager_test.go @@ -21,14 +21,12 @@ import ( "e2mgr/configuration" "e2mgr/logger" "e2mgr/mocks" - "e2mgr/rNibWriter" "e2mgr/rmrCgo" "e2mgr/services" "e2mgr/services/rmrsender" "e2mgr/tests" "gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/common" "gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/entities" - "gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/reader" "github.com/pkg/errors" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" @@ -46,14 +44,10 @@ func initRanLostConnectionTest(t *testing.T) (*logger.Logger, *mocks.RmrMessenge rmrSender := initRmrSender(rmrMessengerMock, logger) readerMock := &mocks.RnibReaderMock{} - rnibReaderProvider := func() reader.RNibReader { - return readerMock - } + writerMock := &mocks.RnibWriterMock{} - rnibWriterProvider := func() rNibWriter.RNibWriter { - return writerMock - } - rnibDataService := services.NewRnibDataService(logger, config, rnibReaderProvider, rnibWriterProvider) + + rnibDataService := services.NewRnibDataService(logger, config, readerMock, writerMock) ranSetupManager := NewRanSetupManager(logger, rmrSender, rnibDataService) ranReconnectionManager := NewRanReconnectionManager(logger, configuration.ParseConfiguration(), rnibDataService, ranSetupManager) return logger, rmrMessengerMock, readerMock, writerMock, ranReconnectionManager @@ -161,8 +155,22 @@ func TestConnectedRanExecuteSetupFailure(t *testing.T) { writerMock.AssertNumberOfCalls(t, "UpdateNodebInfo", 1) } +func TestUnnecessaryUpdateNodebInfoStatus(t *testing.T) { + _, _, _, _, ranReconnectionManager := initRanLostConnectionTest(t) + nodebInfo := &entities.NodebInfo{RanName: "ranName", GlobalNbId: &entities.GlobalNbId{PlmnId: "xxx", NbId: "yyy"}, ConnectionStatus: entities.ConnectionStatus_CONNECTED} + err := ranReconnectionManager.updateNodebInfoStatus(nodebInfo, entities.ConnectionStatus_CONNECTED) + assert.Nil(t, err) +} + +func TestNoSetConnectionStatus(t *testing.T) { + _, _, _, _, ranReconnectionManager := initRanLostConnectionTest(t) + nodebInfo := &entities.NodebInfo{RanName: "ranName", GlobalNbId: &entities.GlobalNbId{PlmnId: "xxx", NbId: "yyy"}, ConnectionStatus: entities.ConnectionStatus_CONNECTED} + err := ranReconnectionManager.setConnectionStatusOfUnconnectableRan(nodebInfo) + assert.Nil(t, err) +} + func initRmrSender(rmrMessengerMock *mocks.RmrMessengerMock, log *logger.Logger) *rmrsender.RmrSender { rmrMessenger := rmrCgo.RmrMessenger(rmrMessengerMock) rmrMessengerMock.On("Init", tests.GetPort(), tests.MaxMsgSize, tests.Flags, log).Return(&rmrMessenger) - return rmrsender.NewRmrSender(log, &rmrMessenger) + return rmrsender.NewRmrSender(log, rmrMessenger) } diff --git a/E2Manager/managers/ran_setup_manager.go b/E2Manager/managers/ran_setup_manager.go index 35908a7..0eb6027 100644 --- a/E2Manager/managers/ran_setup_manager.go +++ b/E2Manager/managers/ran_setup_manager.go @@ -102,7 +102,8 @@ func (m *RanSetupManager) ExecuteSetup(nodebInfo *entities.NodebInfo, status ent } // Send the endc/x2 setup request - msg := models.NewRmrMessage(rmrMsgType, nodebInfo.RanName, request.GetMessageAsBytes(m.logger)) + var xAction []byte + msg := models.NewRmrMessage(rmrMsgType, nodebInfo.RanName, request.GetMessageAsBytes(m.logger), xAction) err = m.rmrSender.Send(msg) diff --git a/E2Manager/managers/ran_setup_manager_test.go b/E2Manager/managers/ran_setup_manager_test.go index 1b31c4c..d8bb0d6 100644 --- a/E2Manager/managers/ran_setup_manager_test.go +++ b/E2Manager/managers/ran_setup_manager_test.go @@ -23,13 +23,11 @@ import ( "e2mgr/e2pdus" "e2mgr/logger" "e2mgr/mocks" - "e2mgr/rNibWriter" "e2mgr/rmrCgo" "e2mgr/services" "fmt" "gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/common" "gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/entities" - "gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/reader" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" "testing" @@ -46,14 +44,10 @@ func initRanSetupManagerTest(t *testing.T) (*mocks.RmrMessengerMock, *mocks.Rnib rmrSender := initRmrSender(rmrMessengerMock, logger) readerMock := &mocks.RnibReaderMock{} - rnibReaderProvider := func() reader.RNibReader { - return readerMock - } + writerMock := &mocks.RnibWriterMock{} - rnibWriterProvider := func() rNibWriter.RNibWriter { - return writerMock - } - rnibDataService := services.NewRnibDataService(logger, config, rnibReaderProvider, rnibWriterProvider) + + rnibDataService := services.NewRnibDataService(logger, config, readerMock, writerMock) ranSetupManager := NewRanSetupManager(logger, rmrSender, rnibDataService) return rmrMessengerMock, writerMock, ranSetupManager } diff --git a/E2Manager/managers/ran_status_change_manager.go b/E2Manager/managers/ran_status_change_manager.go index 153255a..049cc86 100644 --- a/E2Manager/managers/ran_status_change_manager.go +++ b/E2Manager/managers/ran_status_change_manager.go @@ -35,6 +35,7 @@ func (m *RanStatusChangeManager) Execute(msgType int, msgDirection enums.Message return err } - rmrMessage := models.NewRmrMessage(msgType, nodebInfo.RanName, resourceStatusJson) + var xAction []byte + rmrMessage := models.NewRmrMessage(msgType, nodebInfo.RanName, resourceStatusJson, xAction) return m.rmrSender.Send(rmrMessage) } diff --git a/E2Manager/managers/x2_setup_failure_response_manager_test.go b/E2Manager/managers/x2_setup_failure_response_manager_test.go new file mode 100644 index 0000000..b5e1849 --- /dev/null +++ b/E2Manager/managers/x2_setup_failure_response_manager_test.go @@ -0,0 +1,57 @@ +// +// Copyright 2019 AT&T Intellectual Property +// Copyright 2019 Nokia +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +package managers + +import ( + "e2mgr/converters" + "e2mgr/tests" + "fmt" + "gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/entities" + "github.com/stretchr/testify/assert" + "testing" +) + +func TestPopulateX2NodebByPduFailure(t *testing.T) { + logger := tests.InitLog(t) + nodebInfo := &entities.NodebInfo{} + nodebIdentity := &entities.NbIdentity{} + handler := NewX2SetupFailureResponseManager(converters.NewX2SetupFailureResponseConverter(logger)) + err := handler.PopulateNodebByPdu(logger, nodebIdentity, nodebInfo, createRandomPayload()) + assert.NotNil(t, err) +} + +func TestPopulateX2NodebByPduSuccess(t *testing.T) { + logger := tests.InitLog(t) + nodebInfo := &entities.NodebInfo{} + nodebIdentity := &entities.NbIdentity{} + handler := NewX2SetupFailureResponseManager(converters.NewX2SetupFailureResponseConverter(logger)) + err := handler.PopulateNodebByPdu(logger, nodebIdentity, nodebInfo, createX2SetupFailureResponsePayload(t)) + assert.Nil(t, err) + assert.Equal(t, entities.ConnectionStatus_CONNECTED_SETUP_FAILED, nodebInfo.ConnectionStatus) + assert.Equal(t, entities.Failure_X2_SETUP_FAILURE, nodebInfo.FailureType) + +} + +func createX2SetupFailureResponsePayload(t *testing.T) []byte { + packedPdu := "4006001a0000030005400200000016400100001140087821a00000008040" + var payload []byte + _, err := fmt.Sscanf(packedPdu, "%x", &payload) + if err != nil { + t.Errorf("convert inputPayloadAsStr to payloadAsByte. Error: %v\n", err) + } + return payload +} diff --git a/E2Manager/mocks/rmrMessengerMock.go b/E2Manager/mocks/rmrMessengerMock.go index dc4fa15..4a69181 100644 --- a/E2Manager/mocks/rmrMessengerMock.go +++ b/E2Manager/mocks/rmrMessengerMock.go @@ -27,9 +27,9 @@ type RmrMessengerMock struct { mock.Mock } -func (m *RmrMessengerMock) Init(port string, maxMsgSize int, flags int, logger *logger.Logger) *rmrCgo.RmrMessenger{ +func (m *RmrMessengerMock) Init(port string, maxMsgSize int, flags int, logger *logger.Logger) rmrCgo.RmrMessenger{ args := m.Called(port, maxMsgSize, flags, logger) - return args.Get(0).(*rmrCgo.RmrMessenger) + return args.Get(0).(rmrCgo.RmrMessenger) } func (m *RmrMessengerMock) SendMsg(msg *rmrCgo.MBuf) (*rmrCgo.MBuf, error){ diff --git a/E2Manager/models/e2_request_message_test.go b/E2Manager/models/e2_request_message_test.go index 4c5ab09..b314b46 100644 --- a/E2Manager/models/e2_request_message_test.go +++ b/E2Manager/models/e2_request_message_test.go @@ -15,10 +15,11 @@ // limitations under the License. // -package models +package models_test import ( "e2mgr/logger" + "e2mgr/models" "e2mgr/tests" "encoding/hex" "github.com/stretchr/testify/assert" @@ -26,12 +27,12 @@ import ( ) const transactionId = "transactionId" -const expectedMessageAsBytesHex = "31302e302e302e337c353535357c746573747c347c01020304" +const expectedMessageAsBytesHex = "31302e302e302e337c333830317c746573747c347c01020304" func TestNewE2RequestMessage(t *testing.T){ - e2 :=NewE2RequestMessage(transactionId, tests.RanIp, uint16(tests.Port), tests.RanName, tests.DummyPayload) + e2 :=models.NewE2RequestMessage(transactionId, tests.RanIp, uint16(tests.Port), tests.RanName, tests.DummyPayload) assert.NotNil(t, e2) - assert.IsType(t, *e2, E2RequestMessage{}) + assert.IsType(t, *e2, models.E2RequestMessage{}) assert.Equal(t, tests.RanName, e2.RanName()) assert.Equal(t, transactionId, e2.TransactionId()) } @@ -42,7 +43,7 @@ func TestGetMessageAsBytes(t *testing.T){ t.Errorf("#nodeb_controller_test.TestHandleRequestSuccess - failed to initialize logger, error: %s", err) } - e2 :=NewE2RequestMessage(transactionId, tests.RanIp, uint16(tests.Port), tests.RanName, tests.DummyPayload) + e2 := models.NewE2RequestMessage(transactionId, tests.RanIp, uint16(tests.Port), tests.RanName, tests.DummyPayload) bytes := e2.GetMessageAsBytes(log) assert.Equal(t, expectedMessageAsBytesHex, hex.EncodeToString(bytes)) } \ No newline at end of file diff --git a/E2Manager/models/notification_request.go b/E2Manager/models/notification_request.go index ebbeeb6..a5a3a37 100644 --- a/E2Manager/models/notification_request.go +++ b/E2Manager/models/notification_request.go @@ -24,10 +24,10 @@ type NotificationRequest struct { Len int Payload []byte StartTime time.Time - TransactionId string + TransactionId []byte } -func NewNotificationRequest(ranName string, payload []byte, startTime time.Time, transactionId string) *NotificationRequest { +func NewNotificationRequest(ranName string, payload []byte, startTime time.Time, transactionId []byte) *NotificationRequest { return &NotificationRequest{ ranName, len(payload), diff --git a/E2Manager/models/rmr_message.go b/E2Manager/models/rmr_message.go index ef102c4..efd3ef0 100644 --- a/E2Manager/models/rmr_message.go +++ b/E2Manager/models/rmr_message.go @@ -17,24 +17,18 @@ package models -import ( - "e2mgr/logger" -) - type RmrMessage struct { MsgType int RanName string Payload []byte + XAction []byte } -func NewRmrMessage(msgType int, ranName string, payload []byte) *RmrMessage { +func NewRmrMessage(msgType int, ranName string, payload []byte, xAction []byte) *RmrMessage { return &RmrMessage{ MsgType: msgType, RanName: ranName, Payload: payload, + XAction: xAction, } } - -func (response RmrMessage) GetMessageAsBytes(logger *logger.Logger) []byte { - return response.Payload -} diff --git a/E2Manager/providers/httpmsghandlerprovider/incoming_request_handler_provider_test.go b/E2Manager/providers/httpmsghandlerprovider/incoming_request_handler_provider_test.go index 4674493..b7f6386 100644 --- a/E2Manager/providers/httpmsghandlerprovider/incoming_request_handler_provider_test.go +++ b/E2Manager/providers/httpmsghandlerprovider/incoming_request_handler_provider_test.go @@ -24,12 +24,10 @@ import ( "e2mgr/logger" "e2mgr/managers" "e2mgr/mocks" - "e2mgr/rNibWriter" "e2mgr/rmrCgo" "e2mgr/services" "e2mgr/services/rmrsender" "e2mgr/tests" - "gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/reader" "github.com/stretchr/testify/assert" "reflect" "testing" @@ -38,20 +36,16 @@ import ( func getRmrSender(rmrMessengerMock *mocks.RmrMessengerMock, log *logger.Logger) *rmrsender.RmrSender { rmrMessenger := rmrCgo.RmrMessenger(rmrMessengerMock) rmrMessengerMock.On("Init", tests.GetPort(), tests.MaxMsgSize, tests.Flags, log).Return(&rmrMessenger) - return rmrsender.NewRmrSender(log, &rmrMessenger) + return rmrsender.NewRmrSender(log, rmrMessenger) } func setupTest(t *testing.T) *IncomingRequestHandlerProvider { rmrMessengerMock := &mocks.RmrMessengerMock{} log := initLog(t) config := &configuration.Configuration{RnibRetryIntervalMs: 10, MaxRnibConnectionAttempts: 3} - readerProvider := func() reader.RNibReader { - return &mocks.RnibReaderMock{} - } - writerProvider := func() rNibWriter.RNibWriter { - return &mocks.RnibWriterMock{} - } - rnibDataService := services.NewRnibDataService(log, config, readerProvider, writerProvider) + readerMock := &mocks.RnibReaderMock{} + writerMock := &mocks.RnibWriterMock{} + rnibDataService := services.NewRnibDataService(log, config, readerMock, writerMock) rmrSender := getRmrSender(rmrMessengerMock, log) ranSetupManager := managers.NewRanSetupManager(log, rmrSender, rnibDataService) return NewIncomingRequestHandlerProvider(log, rmrSender, configuration.ParseConfiguration(), rnibDataService, ranSetupManager) diff --git a/E2Manager/providers/rmrmsghandlerprovider/notification_handler_provider.go b/E2Manager/providers/rmrmsghandlerprovider/notification_handler_provider.go index 5f92a8b..25c3311 100644 --- a/E2Manager/providers/rmrmsghandlerprovider/notification_handler_provider.go +++ b/E2Manager/providers/rmrmsghandlerprovider/notification_handler_provider.go @@ -18,6 +18,7 @@ package rmrmsghandlerprovider import ( + "e2mgr/configuration" "e2mgr/converters" "e2mgr/handlers/rmrmsghandlers" "e2mgr/logger" @@ -32,28 +33,13 @@ type NotificationHandlerProvider struct { notificationHandlers map[int]rmrmsghandlers.NotificationHandler } -func NewNotificationHandlerProvider(logger *logger.Logger, rnibDataService services.RNibDataService, ranReconnectionManager *managers.RanReconnectionManager, ranStatusChangeManager *managers.RanStatusChangeManager, rmrSender *rmrsender.RmrSender, x2SetupResponseManager *managers.X2SetupResponseManager, x2SetupFailureResponseManager *managers.X2SetupFailureResponseManager) *NotificationHandlerProvider { +func NewNotificationHandlerProvider() *NotificationHandlerProvider { return &NotificationHandlerProvider{ - notificationHandlers: initNotificationHandlersMap(logger, rnibDataService, ranReconnectionManager, ranStatusChangeManager, rmrSender, x2SetupResponseManager, x2SetupFailureResponseManager), - } -} - -func initNotificationHandlersMap(logger *logger.Logger, rnibDataService services.RNibDataService, ranReconnectionManager *managers.RanReconnectionManager, ranStatusChangeManager *managers.RanStatusChangeManager, rmrSender *rmrsender.RmrSender, x2SetupResponseManager *managers.X2SetupResponseManager, x2SetupFailureResponseManager *managers.X2SetupFailureResponseManager) map[int]rmrmsghandlers.NotificationHandler { - return map[int]rmrmsghandlers.NotificationHandler{ - rmrCgo.RIC_X2_SETUP_RESP: rmrmsghandlers.NewSetupResponseNotificationHandler(logger, rnibDataService, x2SetupResponseManager, ranStatusChangeManager, rmrCgo.RIC_X2_SETUP_RESP), - rmrCgo.RIC_X2_SETUP_FAILURE: rmrmsghandlers.NewSetupResponseNotificationHandler(logger, rnibDataService, x2SetupFailureResponseManager, nil, rmrCgo.RIC_X2_SETUP_FAILURE), - rmrCgo.RIC_ENDC_X2_SETUP_RESP: rmrmsghandlers.NewSetupResponseNotificationHandler(logger, rnibDataService, managers.NewEndcSetupResponseManager(), ranStatusChangeManager, rmrCgo.RIC_ENDC_X2_SETUP_RESP), - rmrCgo.RIC_ENDC_X2_SETUP_FAILURE: rmrmsghandlers.NewSetupResponseNotificationHandler(logger, rnibDataService, managers.NewEndcSetupFailureResponseManager(), nil, rmrCgo.RIC_ENDC_X2_SETUP_FAILURE), - rmrCgo.RIC_SCTP_CONNECTION_FAILURE: rmrmsghandlers.NewRanLostConnectionHandler(logger, ranReconnectionManager), - rmrCgo.RIC_ENB_LOAD_INFORMATION: rmrmsghandlers.NewEnbLoadInformationNotificationHandler(logger, rnibDataService, converters.NewEnbLoadInformationExtractor(logger)), - rmrCgo.RIC_ENB_CONF_UPDATE: rmrmsghandlers.NewX2EnbConfigurationUpdateHandler(logger, rmrSender), - rmrCgo.RIC_ENDC_CONF_UPDATE: rmrmsghandlers.NewEndcConfigurationUpdateHandler(logger, rmrSender), - rmrCgo.RIC_X2_RESET_RESP: rmrmsghandlers.NewX2ResetResponseHandler(logger, rnibDataService, ranStatusChangeManager, converters.NewX2ResetResponseExtractor(logger)), - rmrCgo.RIC_X2_RESET: rmrmsghandlers.NewX2ResetRequestNotificationHandler(logger, rnibDataService, ranStatusChangeManager, rmrSender), - rmrCgo.RIC_E2_TERM_INIT: rmrmsghandlers.NewE2TermInitNotificationHandler(logger, ranReconnectionManager, rnibDataService), + notificationHandlers: map[int]rmrmsghandlers.NotificationHandler{}, } } +// TODO: check whether it has been initialized func (provider NotificationHandlerProvider) GetNotificationHandler(messageType int) (rmrmsghandlers.NotificationHandler, error) { handler, ok := provider.notificationHandlers[messageType] @@ -63,3 +49,51 @@ func (provider NotificationHandlerProvider) GetNotificationHandler(messageType i return handler, nil } + +func (provider *NotificationHandlerProvider) Register(msgType int, handler rmrmsghandlers.NotificationHandler) { + provider.notificationHandlers[msgType] = handler +} + +func (provider *NotificationHandlerProvider) Init(logger *logger.Logger, config *configuration.Configuration, rnibDataService services.RNibDataService, rmrSender *rmrsender.RmrSender, ranSetupManager *managers.RanSetupManager) { + + // Init converters + x2SetupResponseConverter := converters.NewX2SetupResponseConverter(logger) + x2SetupFailureResponseConverter := converters.NewX2SetupFailureResponseConverter(logger) + endcSetupResponseConverter := converters.NewEndcSetupResponseConverter(logger) + endcSetupFailureResponseConverter := converters.NewEndcSetupFailureResponseConverter(logger) + enbLoadInformationExtractor := converters.NewEnbLoadInformationExtractor(logger) + x2ResetResponseExtractor := converters.NewX2ResetResponseExtractor(logger) + + // Init managers + ranReconnectionManager := managers.NewRanReconnectionManager(logger, config, rnibDataService, ranSetupManager) + ranStatusChangeManager := managers.NewRanStatusChangeManager(logger, rmrSender) + x2SetupResponseManager := managers.NewX2SetupResponseManager(x2SetupResponseConverter) + x2SetupFailureResponseManager := managers.NewX2SetupFailureResponseManager(x2SetupFailureResponseConverter) + endcSetupResponseManager := managers.NewEndcSetupResponseManager(endcSetupResponseConverter) + endcSetupFailureResponseManager := managers.NewEndcSetupFailureResponseManager(endcSetupFailureResponseConverter) + + // Init handlers + x2SetupResponseHandler := rmrmsghandlers.NewSetupResponseNotificationHandler(logger, rnibDataService, x2SetupResponseManager, ranStatusChangeManager, rmrCgo.RIC_X2_SETUP_RESP) + x2SetupFailureResponseHandler := rmrmsghandlers.NewSetupResponseNotificationHandler(logger, rnibDataService, x2SetupFailureResponseManager, nil, rmrCgo.RIC_X2_SETUP_FAILURE) + endcSetupResponseHandler := rmrmsghandlers.NewSetupResponseNotificationHandler(logger, rnibDataService, endcSetupResponseManager, ranStatusChangeManager, rmrCgo.RIC_ENDC_X2_SETUP_RESP) + endcSetupFailureResponseHandler := rmrmsghandlers.NewSetupResponseNotificationHandler(logger, rnibDataService, endcSetupFailureResponseManager, nil, rmrCgo.RIC_ENDC_X2_SETUP_FAILURE) + ranLostConnectionHandler := rmrmsghandlers.NewRanLostConnectionHandler(logger, ranReconnectionManager) + enbLoadInformationNotificationHandler := rmrmsghandlers.NewEnbLoadInformationNotificationHandler(logger, rnibDataService, enbLoadInformationExtractor) + x2EnbConfigurationUpdateHandler := rmrmsghandlers.NewX2EnbConfigurationUpdateHandler(logger, rmrSender) + endcConfigurationUpdateHandler := rmrmsghandlers.NewEndcConfigurationUpdateHandler(logger, rmrSender) + x2ResetResponseHandler := rmrmsghandlers.NewX2ResetResponseHandler(logger, rnibDataService, ranStatusChangeManager, x2ResetResponseExtractor) + x2ResetRequestNotificationHandler := rmrmsghandlers.NewX2ResetRequestNotificationHandler(logger, rnibDataService, ranStatusChangeManager, rmrSender) + e2TermInitNotificationHandler := rmrmsghandlers.NewE2TermInitNotificationHandler(logger, ranReconnectionManager, rnibDataService) + + provider.Register(rmrCgo.RIC_X2_SETUP_RESP, x2SetupResponseHandler) + provider.Register(rmrCgo.RIC_X2_SETUP_FAILURE, x2SetupFailureResponseHandler) + provider.Register(rmrCgo.RIC_ENDC_X2_SETUP_RESP, endcSetupResponseHandler) + provider.Register(rmrCgo.RIC_ENDC_X2_SETUP_FAILURE, endcSetupFailureResponseHandler) + provider.Register(rmrCgo.RIC_SCTP_CONNECTION_FAILURE, ranLostConnectionHandler) + provider.Register(rmrCgo.RIC_ENB_LOAD_INFORMATION, enbLoadInformationNotificationHandler) + provider.Register(rmrCgo.RIC_ENB_CONF_UPDATE, x2EnbConfigurationUpdateHandler) + provider.Register(rmrCgo.RIC_ENDC_CONF_UPDATE, endcConfigurationUpdateHandler) + provider.Register(rmrCgo.RIC_X2_RESET_RESP, x2ResetResponseHandler) + provider.Register(rmrCgo.RIC_X2_RESET, x2ResetRequestNotificationHandler) + provider.Register(rmrCgo.RIC_E2_TERM_INIT, e2TermInitNotificationHandler) +} diff --git a/E2Manager/providers/rmrmsghandlerprovider/notification_handler_provider_test.go b/E2Manager/providers/rmrmsghandlerprovider/notification_handler_provider_test.go index 1d525ac..757c0d4 100644 --- a/E2Manager/providers/rmrmsghandlerprovider/notification_handler_provider_test.go +++ b/E2Manager/providers/rmrmsghandlerprovider/notification_handler_provider_test.go @@ -24,12 +24,10 @@ import ( "e2mgr/logger" "e2mgr/managers" "e2mgr/mocks" - "e2mgr/rNibWriter" "e2mgr/services" "e2mgr/services/rmrsender" "e2mgr/tests" "fmt" - "gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/reader" "strings" "testing" @@ -40,22 +38,40 @@ import ( * Verify support for known providers. */ -func initTestCase(t *testing.T) (*logger.Logger, services.RNibDataService, *managers.RanReconnectionManager, *managers.RanStatusChangeManager, *rmrsender.RmrSender, *managers.X2SetupResponseManager, *managers.X2SetupFailureResponseManager) { +func initTestCase(t *testing.T) (*logger.Logger, *configuration.Configuration, services.RNibDataService, *rmrsender.RmrSender, *managers.RanSetupManager) { logger := initLog(t) config := &configuration.Configuration{RnibRetryIntervalMs: 10, MaxRnibConnectionAttempts: 3} readerMock := &mocks.RnibReaderMock{} - rnibReaderProvider := func() reader.RNibReader { - return readerMock - } writerMock := &mocks.RnibWriterMock{} - rnibWriterProvider := func() rNibWriter.RNibWriter { - return writerMock - } rmrSender := initRmrSender(&mocks.RmrMessengerMock{}, logger) - rnibDataService := services.NewRnibDataService(logger, config, rnibReaderProvider, rnibWriterProvider) + rnibDataService := services.NewRnibDataService(logger, config, readerMock, writerMock) ranSetupManager := managers.NewRanSetupManager(logger, rmrSender, rnibDataService) + //ranReconnectionManager := managers.NewRanReconnectionManager(logger, configuration.ParseConfiguration(), rnibDataService, ranSetupManager) + //ranStatusChangeManager := managers.NewRanStatusChangeManager(logger, rmrSender) + // + //x2SetupResponseConverter := converters.NewX2SetupResponseConverter(logger) + //x2SetupResponseManager := managers.NewX2SetupResponseManager(x2SetupResponseConverter) + // + //x2SetupFailureResponseConverter := converters.NewX2SetupFailureResponseConverter(logger) + //x2SetupFailureResponseManager := managers.NewX2SetupFailureResponseManager(x2SetupFailureResponseConverter) + // + //endcSetupResponseConverter := converters.NewEndcSetupResponseConverter(logger) + //endcSetupResponseManager := managers.NewEndcSetupResponseManager(endcSetupResponseConverter) + // + // + //endcSetupFailureResponseConverter := converters.NewEndcSetupFailureResponseConverter(logger) + //endcSetupFailureResponseManager := managers.NewEndcSetupFailureResponseManager(endcSetupFailureResponseConverter) + + return logger, config, rnibDataService, rmrSender, ranSetupManager +} + +func TestGetNotificationHandlerSuccess(t *testing.T) { + + logger, config, rnibDataService, rmrSender, ranSetupManager := initTestCase(t) + + ranReconnectionManager := managers.NewRanReconnectionManager(logger, configuration.ParseConfiguration(), rnibDataService, ranSetupManager) ranStatusChangeManager := managers.NewRanStatusChangeManager(logger, rmrSender) @@ -65,34 +81,35 @@ func initTestCase(t *testing.T) (*logger.Logger, services.RNibDataService, *mana x2SetupFailureResponseConverter := converters.NewX2SetupFailureResponseConverter(logger) x2SetupFailureResponseManager := managers.NewX2SetupFailureResponseManager(x2SetupFailureResponseConverter) + endcSetupResponseConverter := converters.NewEndcSetupResponseConverter(logger) + endcSetupResponseManager := managers.NewEndcSetupResponseManager(endcSetupResponseConverter) - return logger, rnibDataService, ranReconnectionManager, ranStatusChangeManager, rmrSender, x2SetupResponseManager, x2SetupFailureResponseManager -} -func TestGetNotificationHandlerSuccess(t *testing.T) { + endcSetupFailureResponseConverter := converters.NewEndcSetupFailureResponseConverter(logger) + endcSetupFailureResponseManager := managers.NewEndcSetupFailureResponseManager(endcSetupFailureResponseConverter) - logger, rnibDataService, ranReconnectionManager, ranStatusChangeManager, rmrSender, x2SetupResponseManager, x2SetupFailureResponseManager := initTestCase(t) var testCases = []struct { msgType int handler rmrmsghandlers.NotificationHandler }{ - {rmrCgo.RIC_X2_SETUP_RESP, rmrmsghandlers.NewSetupResponseNotificationHandler(logger,rnibDataService, x2SetupResponseManager, ranStatusChangeManager, rmrCgo.RIC_X2_SETUP_RESP)}, - {rmrCgo.RIC_X2_SETUP_FAILURE, rmrmsghandlers.NewSetupResponseNotificationHandler(logger,rnibDataService, x2SetupFailureResponseManager, ranStatusChangeManager, rmrCgo.RIC_X2_SETUP_FAILURE)}, - {rmrCgo.RIC_ENDC_X2_SETUP_RESP, rmrmsghandlers.NewSetupResponseNotificationHandler(logger,rnibDataService, managers.NewEndcSetupResponseManager(), ranStatusChangeManager, rmrCgo.RIC_ENDC_X2_SETUP_RESP)}, - {rmrCgo.RIC_ENDC_X2_SETUP_FAILURE, rmrmsghandlers.NewSetupResponseNotificationHandler(logger,rnibDataService, managers.NewEndcSetupFailureResponseManager(), ranStatusChangeManager, rmrCgo.RIC_ENDC_X2_SETUP_FAILURE),}, - {rmrCgo.RIC_SCTP_CONNECTION_FAILURE, rmrmsghandlers.NewRanLostConnectionHandler(logger,ranReconnectionManager)}, - {rmrCgo.RIC_ENB_LOAD_INFORMATION, rmrmsghandlers.NewEnbLoadInformationNotificationHandler(logger,rnibDataService, converters.NewEnbLoadInformationExtractor(logger))}, + {rmrCgo.RIC_X2_SETUP_RESP, rmrmsghandlers.NewSetupResponseNotificationHandler(logger, rnibDataService, x2SetupResponseManager, ranStatusChangeManager, rmrCgo.RIC_X2_SETUP_RESP)}, + {rmrCgo.RIC_X2_SETUP_FAILURE, rmrmsghandlers.NewSetupResponseNotificationHandler(logger, rnibDataService, x2SetupFailureResponseManager, ranStatusChangeManager, rmrCgo.RIC_X2_SETUP_FAILURE)}, + {rmrCgo.RIC_ENDC_X2_SETUP_RESP, rmrmsghandlers.NewSetupResponseNotificationHandler(logger, rnibDataService, endcSetupResponseManager, ranStatusChangeManager, rmrCgo.RIC_ENDC_X2_SETUP_RESP)}, + {rmrCgo.RIC_ENDC_X2_SETUP_FAILURE, rmrmsghandlers.NewSetupResponseNotificationHandler(logger, rnibDataService, endcSetupFailureResponseManager, ranStatusChangeManager, rmrCgo.RIC_ENDC_X2_SETUP_FAILURE),}, + {rmrCgo.RIC_SCTP_CONNECTION_FAILURE, rmrmsghandlers.NewRanLostConnectionHandler(logger, ranReconnectionManager)}, + {rmrCgo.RIC_ENB_LOAD_INFORMATION, rmrmsghandlers.NewEnbLoadInformationNotificationHandler(logger, rnibDataService, converters.NewEnbLoadInformationExtractor(logger))}, {rmrCgo.RIC_ENB_CONF_UPDATE, rmrmsghandlers.NewX2EnbConfigurationUpdateHandler(logger, rmrSender)}, {rmrCgo.RIC_ENDC_CONF_UPDATE, rmrmsghandlers.NewEndcConfigurationUpdateHandler(logger, rmrSender)}, - {rmrCgo.RIC_E2_TERM_INIT, rmrmsghandlers.NewE2TermInitNotificationHandler(logger,ranReconnectionManager, rnibDataService)}, + {rmrCgo.RIC_E2_TERM_INIT, rmrmsghandlers.NewE2TermInitNotificationHandler(logger, ranReconnectionManager, rnibDataService)}, {rmrCgo.RIC_X2_RESET_RESP, rmrmsghandlers.NewX2ResetResponseHandler(logger, rnibDataService, ranStatusChangeManager, converters.NewX2ResetResponseExtractor(logger))}, - {rmrCgo.RIC_X2_RESET, rmrmsghandlers.NewX2ResetRequestNotificationHandler(logger,rnibDataService, ranStatusChangeManager, rmrSender)}, + {rmrCgo.RIC_X2_RESET, rmrmsghandlers.NewX2ResetRequestNotificationHandler(logger, rnibDataService, ranStatusChangeManager, rmrSender)}, } for _, tc := range testCases { - provider := NewNotificationHandlerProvider(logger, rnibDataService, ranReconnectionManager, ranStatusChangeManager, rmrSender, x2SetupResponseManager, x2SetupFailureResponseManager) + provider := NewNotificationHandlerProvider() + provider.Init(logger, config, rnibDataService, rmrSender, ranSetupManager) t.Run(fmt.Sprintf("%d", tc.msgType), func(t *testing.T) { handler, err := provider.GetNotificationHandler(tc.msgType) if err != nil { @@ -121,8 +138,9 @@ func TestGetNotificationHandlerFailure(t *testing.T) { } for _, tc := range testCases { - logger, rnibDataService, ranReconnectionManager, ranStatusChangeManager, rmrSender, x2SetupResponseManager, x2SetupFailureResponseManager := initTestCase(t) - provider := NewNotificationHandlerProvider(logger, rnibDataService, ranReconnectionManager, ranStatusChangeManager, rmrSender, x2SetupResponseManager, x2SetupFailureResponseManager) + logger, config, rnibDataService, rmrSender, ranSetupManager := initTestCase(t) + provider := NewNotificationHandlerProvider() + provider.Init(logger, config, rnibDataService, rmrSender, ranSetupManager) t.Run(fmt.Sprintf("%d", tc.msgType), func(t *testing.T) { _, err := provider.GetNotificationHandler(tc.msgType) if err == nil { @@ -139,7 +157,7 @@ func TestGetNotificationHandlerFailure(t *testing.T) { func initRmrSender(rmrMessengerMock *mocks.RmrMessengerMock, log *logger.Logger) *rmrsender.RmrSender { rmrMessenger := rmrCgo.RmrMessenger(rmrMessengerMock) rmrMessengerMock.On("Init", tests.GetPort(), tests.MaxMsgSize, tests.Flags, log).Return(&rmrMessenger) - return rmrsender.NewRmrSender(log, &rmrMessenger) + return rmrsender.NewRmrSender(log, rmrMessenger) } // TODO: extract to test_utils diff --git a/E2Manager/rNibWriter/rNibWriter.go b/E2Manager/rNibWriter/rNibWriter.go index 702c7a0..202a273 100644 --- a/E2Manager/rNibWriter/rNibWriter.go +++ b/E2Manager/rNibWriter/rNibWriter.go @@ -21,15 +21,11 @@ import ( "fmt" "gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/common" "gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/entities" - "gerrit.o-ran-sc.org/r/ric-plt/sdlgo" "github.com/golang/protobuf/proto" ) -var writerPool *common.Pool - type rNibWriterInstance struct { - sdl *common.ISdlInstance - namespace string + sdl common.ISdlInstance } /* @@ -41,43 +37,23 @@ type RNibWriter interface { SaveRanLoadInformation(inventoryName string, ranLoadInformation *entities.RanLoadInformation) error } -/* -Init initializes the infrastructure required for the RNibWriter instance -*/ -func Init(namespace string, poolSize int) { - initPool(poolSize, - func() interface{} { - var sdlI common.ISdlInstance = sdlgo.NewSdlInstance(namespace, sdlgo.NewDatabase()) - return &rNibWriterInstance{sdl: &sdlI, namespace: namespace} - }, - func(obj interface{}) { - (*obj.(*rNibWriterInstance).sdl).Close() - }) -} - -/* -InitPool initializes the writer's instances pool -*/ -func initPool(poolSize int, newObj func() interface{}, destroyObj func(interface{})) { - writerPool = common.NewPool(poolSize, newObj, destroyObj) -} /* GetRNibWriter returns reference to RNibWriter */ -func GetRNibWriter() RNibWriter { - return &rNibWriterInstance{} + +func GetRNibWriter(sdl common.ISdlInstance) RNibWriter { + return &rNibWriterInstance{sdl: sdl} } + /* SaveNodeb saves nodeB entity data in the redis DB according to the specified data model */ -func (*rNibWriterInstance) SaveNodeb(nbIdentity *entities.NbIdentity, entity *entities.NodebInfo) error { - w := writerPool.Get().(*rNibWriterInstance) +func (w *rNibWriterInstance) SaveNodeb(nbIdentity *entities.NbIdentity, entity *entities.NodebInfo) error { isNotEmptyIdentity := isNotEmpty(nbIdentity) if isNotEmptyIdentity && entity.GetNodeType() == entities.Node_UNKNOWN { return common.NewValidationError(fmt.Sprintf("#rNibWriter.saveNodeB - Unknown responding node type, entity: %v", entity)) } - defer writerPool.Put(w) data, err := proto.Marshal(entity) if err != nil { return common.NewInternalError(err) @@ -109,7 +85,7 @@ func (*rNibWriterInstance) SaveNodeb(nbIdentity *entities.NbIdentity, entity *en return rNibErr } } - err = (*w.sdl).Set(pairs) + err = w.sdl.Set(pairs) if err != nil { return common.NewInternalError(err) } @@ -121,7 +97,7 @@ func (*rNibWriterInstance) SaveNodeb(nbIdentity *entities.NbIdentity, entity *en if err != nil { return common.NewInternalError(err) } - err = (*w.sdl).RemoveMember(entities.Node_UNKNOWN.String(), nbIdData) + err = w.sdl.RemoveMember(entities.Node_UNKNOWN.String(), nbIdData) if err != nil { return common.NewInternalError(err) } @@ -133,7 +109,7 @@ func (*rNibWriterInstance) SaveNodeb(nbIdentity *entities.NbIdentity, entity *en if err != nil { return common.NewInternalError(err) } - err = (*w.sdl).AddMember(entity.GetNodeType().String(), nbIdData) + err = w.sdl.AddMember(entity.GetNodeType().String(), nbIdData) if err != nil { return common.NewInternalError(err) } @@ -143,9 +119,7 @@ func (*rNibWriterInstance) SaveNodeb(nbIdentity *entities.NbIdentity, entity *en /* UpdateNodebInfo... */ -func (*rNibWriterInstance) UpdateNodebInfo(nodebInfo *entities.NodebInfo) error { - w := writerPool.Get().(*rNibWriterInstance) - defer writerPool.Put(w) +func (w *rNibWriterInstance) UpdateNodebInfo(nodebInfo *entities.NodebInfo) error { nodebNameKey, rNibErr := common.ValidateAndBuildNodeBNameKey(nodebInfo.GetRanName()) @@ -168,7 +142,7 @@ func (*rNibWriterInstance) UpdateNodebInfo(nodebInfo *entities.NodebInfo) error pairs = append(pairs, nodebIdKey, data) } - err = (*w.sdl).Set(pairs) + err = w.sdl.Set(pairs) if err != nil { return common.NewInternalError(err) @@ -180,9 +154,7 @@ func (*rNibWriterInstance) UpdateNodebInfo(nodebInfo *entities.NodebInfo) error /* SaveRanLoadInformation stores ran load information for the provided ran */ -func (*rNibWriterInstance) SaveRanLoadInformation(inventoryName string, ranLoadInformation *entities.RanLoadInformation) error { - w := writerPool.Get().(*rNibWriterInstance) - defer writerPool.Put(w) +func (w *rNibWriterInstance) SaveRanLoadInformation(inventoryName string, ranLoadInformation *entities.RanLoadInformation) error { key, rnibErr := common.ValidateAndBuildRanLoadInformationKey(inventoryName) @@ -199,7 +171,7 @@ func (*rNibWriterInstance) SaveRanLoadInformation(inventoryName string, ranLoadI var pairs []interface{} pairs = append(pairs, key, data) - err = (*w.sdl).Set(pairs) + err = w.sdl.Set(pairs) if err != nil { return common.NewInternalError(err) @@ -209,10 +181,10 @@ func (*rNibWriterInstance) SaveRanLoadInformation(inventoryName string, ranLoadI } /* -Close closes writer's pool +Close the writer */ func Close() { - writerPool.Close() + //Nothing to do } func appendEnbCells(nbIdentity *entities.NbIdentity, cells []*entities.ServedCellInfo, pairs []interface{}) ([]interface{}, error) { diff --git a/E2Manager/rNibWriter/rNibWriter_test.go b/E2Manager/rNibWriter/rNibWriter_test.go index c887da6..7f0b550 100644 --- a/E2Manager/rNibWriter/rNibWriter_test.go +++ b/E2Manager/rNibWriter/rNibWriter_test.go @@ -29,55 +29,19 @@ import ( "time" ) -func TestInitRNibWriter(t *testing.T) { - writerPool = nil - initSdlInstanceMock(namespace, 1) - available, created := writerPool.Stats() - assert.Equal(t, available, 0, "number of available objects in the writerPool should be 0") - assert.Equal(t, created, 0, "number of created objects in the writerPool should be 0") - w := GetRNibWriter() - assert.NotNil(t, w) -} - -func TestInitPool(t *testing.T) { - writerPool = nil - sdlInstanceMock := new(mocks.MockSdlInstance) - initPool(1, func() interface{} { - sdlI := common.ISdlInstance(sdlInstanceMock) - return &rNibWriterInstance{sdl: &sdlI, namespace: namespace} - }, - func(obj interface{}) { - }, - ) - assert.NotNil(t, writerPool) - assert.NotNil(t, writerPool.New) - assert.NotNil(t, writerPool.Destroy) - available, created := writerPool.Stats() - assert.Equal(t, 0, available, "number of available objects in the writerPool should be 0") - assert.Equal(t, 0, created, "number of created objects in the writerPool should be 0") +func initSdlInstanceMock(namespace string) (w RNibWriter, sdlInstanceMock *mocks.MockSdlInstance) { + sdlInstanceMock = new(mocks.MockSdlInstance) + w = GetRNibWriter(sdlInstanceMock) + return } var namespace = "namespace" -func initSdlInstanceMock(namespace string, poolSize int) *mocks.MockSdlInstance { - sdlInstanceMock := new(mocks.MockSdlInstance) - initPool(poolSize, func() interface{} { - sdlI := common.ISdlInstance(sdlInstanceMock) - return &rNibWriterInstance{sdl: &sdlI, namespace: namespace} - }, - func(obj interface{}) { - }, - ) - return sdlInstanceMock -} - func TestUpdateNodebInfoSuccess(t *testing.T) { inventoryName := "name" plmnId := "02f829" nbId := "4a952a0a" - writerPool = nil - sdlInstanceMock := initSdlInstanceMock(namespace, 1) - w := GetRNibWriter() + w, sdlInstanceMock := initSdlInstanceMock(namespace) nodebInfo := &entities.NodebInfo{} nodebInfo.RanName = inventoryName nodebInfo.GlobalNbId = &entities.GlobalNbId{PlmnId: plmnId, NbId: nbId} @@ -107,9 +71,7 @@ func TestUpdateNodebInfoMissingInventoryNameFailure(t *testing.T) { inventoryName := "name" plmnId := "02f829" nbId := "4a952a0a" - writerPool = nil - sdlInstanceMock := initSdlInstanceMock(namespace, 1) - w := GetRNibWriter() + w, sdlInstanceMock := initSdlInstanceMock(namespace) nodebInfo := &entities.NodebInfo{} data, err := proto.Marshal(nodebInfo) if err != nil { @@ -133,9 +95,7 @@ func TestUpdateNodebInfoMissingInventoryNameFailure(t *testing.T) { func TestUpdateNodebInfoMissingGlobalNbId(t *testing.T) { inventoryName := "name" - writerPool = nil - sdlInstanceMock := initSdlInstanceMock(namespace, 1) - w := GetRNibWriter() + w, sdlInstanceMock := initSdlInstanceMock(namespace) nodebInfo := &entities.NodebInfo{} nodebInfo.RanName = inventoryName data, err := proto.Marshal(nodebInfo) @@ -157,9 +117,7 @@ func TestUpdateNodebInfoMissingGlobalNbId(t *testing.T) { func TestSaveEnb(t *testing.T) { name := "name" ranName := "RAN:" + name - writerPool = nil - sdlInstanceMock := initSdlInstanceMock(namespace, 1) - w := GetRNibWriter() + w, sdlInstanceMock := initSdlInstanceMock(namespace) nb := entities.NodebInfo{} nb.NodeType = entities.Node_ENB nb.ConnectionStatus = 1 @@ -207,9 +165,7 @@ func TestSaveEnb(t *testing.T) { func TestSaveEnbCellIdValidationFailure(t *testing.T) { name := "name" - writerPool = nil - initSdlInstanceMock(namespace, 1) - w := GetRNibWriter() + w, _ := initSdlInstanceMock(namespace) nb := entities.NodebInfo{} nb.NodeType = entities.Node_ENB nb.ConnectionStatus = 1 @@ -228,9 +184,7 @@ func TestSaveEnbCellIdValidationFailure(t *testing.T) { } func TestSaveEnbInventoryNameValidationFailure(t *testing.T) { - writerPool = nil - initSdlInstanceMock(namespace, 1) - w := GetRNibWriter() + w, _ := initSdlInstanceMock(namespace) nb := entities.NodebInfo{} nb.NodeType = entities.Node_ENB nb.ConnectionStatus = 1 @@ -248,35 +202,9 @@ func TestSaveEnbInventoryNameValidationFailure(t *testing.T) { assert.Equal(t, "#utils.ValidateAndBuildNodeBNameKey - an empty inventory name received", rNibErr.Error()) } -func TestSaveEnbOnClosedPool(t *testing.T) { - name := "name" - writerPool = nil - sdlInstanceMock := initSdlInstanceMock(namespace, 1) - w := GetRNibWriter() - nb := entities.NodebInfo{} - nb.NodeType = entities.Node_ENB - nb.ConnectionStatus = 1 - nb.Ip = "localhost" - nb.Port = 5656 - enb := entities.Enb{} - nb.Configuration = &entities.NodebInfo_Enb{Enb: &enb} - data, err := proto.Marshal(&nb) - if err != nil { - t.Errorf("#rNibWriter_test.TestSaveEnbOnClosedPool - Failed to marshal NodeB entity. Error: %v", err) - } - setExpected := []interface{}{name, data} - var e error - sdlInstanceMock.On("Set", setExpected).Return(e) - writerPool.Close() - nbIdentity := &entities.NbIdentity{} - assert.Panics(t, func() { w.SaveNodeb(nbIdentity, &nb) }) -} - func TestSaveGnbCellIdValidationFailure(t *testing.T) { name := "name" - writerPool = nil - initSdlInstanceMock(namespace, 1) - w := GetRNibWriter() + w, _ := initSdlInstanceMock(namespace) nb := entities.NodebInfo{} nb.NodeType = entities.Node_GNB nb.ConnectionStatus = 1 @@ -298,9 +226,7 @@ func TestSaveGnbCellIdValidationFailure(t *testing.T) { func TestSaveGnb(t *testing.T) { name := "name" ranName := "RAN:" + name - writerPool = nil - sdlInstanceMock := initSdlInstanceMock(namespace, 1) - w := GetRNibWriter() + w, sdlInstanceMock := initSdlInstanceMock(namespace) nb := entities.NodebInfo{} nb.NodeType = entities.Node_GNB nb.ConnectionStatus = 1 @@ -354,9 +280,7 @@ func TestSaveRanLoadInformationSuccess(t *testing.T) { t.Errorf("#rNibWriter_test.TestSaveRanLoadInformationSuccess - Failed to build ran load infromation key. Error: %v", validationErr) } - writerPool = nil - sdlInstanceMock := initSdlInstanceMock(namespace, 1) - w := GetRNibWriter() + w, sdlInstanceMock := initSdlInstanceMock(namespace) ranLoadInformation := generateRanLoadInformation() data, err := proto.Marshal(ranLoadInformation) @@ -376,9 +300,7 @@ func TestSaveRanLoadInformationSuccess(t *testing.T) { func TestSaveRanLoadInformationMarshalNilFailure(t *testing.T) { inventoryName := "name2" - writerPool = nil - initSdlInstanceMock(namespace, 1) - w := GetRNibWriter() + w, _ := initSdlInstanceMock(namespace) expectedErr := common.NewInternalError(errors.New("proto: Marshal called with nil")) err := w.SaveRanLoadInformation(inventoryName, nil) @@ -387,9 +309,7 @@ func TestSaveRanLoadInformationMarshalNilFailure(t *testing.T) { func TestSaveRanLoadInformationEmptyInventoryNameFailure(t *testing.T) { inventoryName := "" - writerPool = nil - initSdlInstanceMock(namespace, 1) - w := GetRNibWriter() + w, _ := initSdlInstanceMock(namespace) err := w.SaveRanLoadInformation(inventoryName, nil) assert.NotNil(t, err) @@ -405,9 +325,7 @@ func TestSaveRanLoadInformationSdlFailure(t *testing.T) { t.Errorf("#rNibWriter_test.TestSaveRanLoadInformationSuccess - Failed to build ran load infromation key. Error: %v", validationErr) } - writerPool = nil - sdlInstanceMock := initSdlInstanceMock(namespace, 1) - w := GetRNibWriter() + w, sdlInstanceMock := initSdlInstanceMock(namespace) ranLoadInformation := generateRanLoadInformation() data, err := proto.Marshal(ranLoadInformation) @@ -500,9 +418,7 @@ func generateRanLoadInformation() *entities.RanLoadInformation { } func TestSaveNilEntityFailure(t *testing.T) { - writerPool = nil - initSdlInstanceMock(namespace, 1) - w := GetRNibWriter() + w, _ := initSdlInstanceMock(namespace) expectedErr := common.NewInternalError(errors.New("proto: Marshal called with nil")) nbIdentity := &entities.NbIdentity{} actualErr := w.SaveNodeb(nbIdentity, nil) @@ -510,9 +426,7 @@ func TestSaveNilEntityFailure(t *testing.T) { } func TestSaveUnknownTypeEntityFailure(t *testing.T) { - writerPool = nil - initSdlInstanceMock(namespace, 1) - w := GetRNibWriter() + w, _ := initSdlInstanceMock(namespace) expectedErr := common.NewValidationError("#rNibWriter.saveNodeB - Unknown responding node type, entity: ip:\"localhost\" port:5656 ") nbIdentity := &entities.NbIdentity{InventoryName: "name", GlobalNbId: &entities.GlobalNbId{PlmnId: "02f829", NbId: "4a952a0a"}} nb := &entities.NodebInfo{} @@ -527,9 +441,7 @@ func TestSaveEntityFailure(t *testing.T) { plmnId := "02f829" nbId := "4a952a0a" - writerPool = nil - sdlInstanceMock := initSdlInstanceMock(namespace, 1) - w := GetRNibWriter() + w, sdlInstanceMock := initSdlInstanceMock(namespace) gnb := entities.NodebInfo{} gnb.NodeType = entities.Node_GNB data, err := proto.Marshal(&gnb) @@ -545,77 +457,9 @@ func TestSaveEntityFailure(t *testing.T) { assert.NotEmpty(t, rNibErr) } -func TestGetRNibWriterPoolNotInitializedFailure(t *testing.T) { - writerPool = nil - assert.Panics(t, func() { GetRNibWriter().SaveNodeb(nil,nil) }) -} - func TestGetRNibWriter(t *testing.T) { - writerPool = nil - initSdlInstanceMock(namespace, 1) - received := GetRNibWriter() - assert.Empty(t, received) - available, created := writerPool.Stats() - assert.Equal(t, 0, available, "number of available objects in the writerPool should be 0") - assert.Equal(t, 0, created, "number of created objects in the writerPool should be 0") - writerPool.Close() -} - -func TestClose(t *testing.T) { - writerPool = nil - instanceMock := initSdlInstanceMock(namespace, 2) - w1 := GetRNibWriter() - w2 := GetRNibWriter() - writerPool.Put(w1) - writerPool.Put(w2) - available, created := writerPool.Stats() - assert.Equal(t, 2, available, "number of available objects in the writerPool should be 2") - assert.Equal(t, 0, created, "number of created objects in the writerPool should be 0") - var e error - instanceMock.On("Close").Return(e) - Close() - available, created = writerPool.Stats() - assert.Equal(t, 0, available, "number of available objects in the writerPool should be 0") -} - -func TestCloseOnClosedPoolFailure(t *testing.T) { - writerPool = nil - instanceMock := initSdlInstanceMock(namespace, 1) - w1 := GetRNibWriter() - writerPool.Put(w1) - available, created := writerPool.Stats() - assert.Equal(t, 1, available, "number of available objects in the writerPool should be 1") - assert.Equal(t, 0, created, "number of created objects in the writerPool should be 0") - var e error - instanceMock.On("Close").Return(e) - Close() - assert.Panics(t, func() { Close() }) -} - -func TestCloseFailure(t *testing.T) { - writerPool = nil - instanceMock := initSdlInstanceMock(namespace, 2) - w1 := GetRNibWriter() - writerPool.Put(w1) - available, created := writerPool.Stats() - assert.Equal(t, 1, available, "number of available objects in the writerPool should be 1") - assert.Equal(t, 0, created, "number of created objects in the writerPool should be 0") - e := errors.New("expected error") - instanceMock.On("Close").Return(e) - Close() - available, created = writerPool.Stats() - assert.Equal(t, 0, available, "number of available objects in the writerPool should be 0") -} - -func TestInit(t *testing.T) { - writerPool = nil - Init("", 1) - assert.NotNil(t, writerPool) - assert.NotNil(t, writerPool.New) - assert.NotNil(t, writerPool.Destroy) - available, created := writerPool.Stats() - assert.Equal(t, 0, available, "number of available objects in the writerPool should be 0") - assert.Equal(t, 0, created, "number of created objects in the writerPool should be 0") + received, _ := initSdlInstanceMock(namespace) + assert.NotEmpty(t, received) } //Integration tests diff --git a/E2Manager/rmrCgo/rmrCgoApi.go b/E2Manager/rmrCgo/rmrCgoApi.go index f2ee545..4a9f8c4 100644 --- a/E2Manager/rmrCgo/rmrCgoApi.go +++ b/E2Manager/rmrCgo/rmrCgoApi.go @@ -31,7 +31,7 @@ import ( "e2mgr/logger" ) -func (*Context) Init(port string, maxMsgSize int, flags int, logger *logger.Logger) *RmrMessenger {//TODO remove pointer from interface +func (*Context) Init(port string, maxMsgSize int, flags int, logger *logger.Logger) RmrMessenger { pp := C.CString(port) defer C.free(unsafe.Pointer(pp)) logger.Debugf("#rmrCgoApi.Init - Going to initiate RMR router") @@ -51,7 +51,7 @@ func (*Context) Init(port string, maxMsgSize int, flags int, logger *logger.Logg // Each round is about 1000 attempts with a short sleep between each round. C.rmr_set_stimeout(ctx.RmrCtx, C.int(1000)) r := RmrMessenger(ctx) - return &r + return r } func (ctx *Context) SendMsg(msg *MBuf) (*MBuf, error) { @@ -105,14 +105,6 @@ func (ctx *Context) RecvMsg() (*MBuf, error) { return mbuf, nil } -func (ctx *Context) RtsMsg(msg *MBuf) { - ctx.checkContextInitialized() - ctx.Logger.Debugf("#rmrCgoApi.RtsMsg - Going to return message to the sender") - allocatedCMBuf := C.rmr_alloc_msg(ctx.RmrCtx, C.int(ctx.MaxMsgSize)) - defer C.rmr_free_msg(allocatedCMBuf) - C.rmr_rts_msg(ctx.RmrCtx, allocatedCMBuf) -} - func (ctx *Context) IsReady() bool { ctx.Logger.Debugf("#rmrCgoApi.IsReady - Going to check if routing table is initialized") return int(C.rmr_ready(ctx.RmrCtx)) != 0 diff --git a/E2Manager/rmrCgo/rmrCgoApi_test.go b/E2Manager/rmrCgo/rmrCgoApi_test.go index b71b8f1..fd1e7b2 100644 --- a/E2Manager/rmrCgo/rmrCgoApi_test.go +++ b/E2Manager/rmrCgo/rmrCgoApi_test.go @@ -15,46 +15,37 @@ // limitations under the License. // -package rmrCgo +package rmrCgo_test import ( + "bytes" "e2mgr/logger" + "e2mgr/rmrCgo" "e2mgr/tests" - "bytes" "encoding/json" "github.com/stretchr/testify/assert" "io/ioutil" + "strconv" "testing" - "time" ) var ( - log *logger.Logger - msgr *RmrMessenger + log *logger.Logger + msgr rmrCgo.RmrMessenger ) -func TestLogger(t *testing.T){ - var err error - log, err = logger.InitLogger(logger.DebugLevel) - if err != nil { - t.Errorf("#rmrCgoApi_test.TestLogger - failed to initialize logger, error: %s", err) - } - data := map[string]interface{}{"messageType": 1001, "ranIp":"10.0.0.3", "ranPort": 879, "ranName":"test1"} +func TestLogger(t *testing.T) { + log := initLog(t) + data := map[string]interface{}{"messageType": 1001, "ranIp": "10.0.0.3", "ranPort": 879, "ranName": "test1"} b := new(bytes.Buffer) _ = json.NewEncoder(b).Encode(data) req := tests.GetHttpRequest() boo, _ := ioutil.ReadAll(req.Body) - log.Debugf("#rmrCgoApi_test.TestLogger - request header: %v\n; request body: %s\n", req.Header, string(boo)) + log.Debugf("#rmr_c_go_api_test.TestLogger - request header: %v\n; request body: %s\n", req.Header, string(boo)) } - func TestNewMBufSuccess(t *testing.T) { - var err error - log, err = logger.InitLogger(logger.DebugLevel) - if err != nil { - t.Errorf("#rmrCgoApi_test.TestNewMBufSuccess - failed to initialize logger, error: %s", err) - } - msg := NewMBuf(tests.MessageType, len(tests.DummyPayload),"RanName", &tests.DummyPayload, &tests.DummyXAction) + msg := rmrCgo.NewMBuf(tests.MessageType, len(tests.DummyPayload), "RanName", &tests.DummyPayload, &tests.DummyXAction) assert.NotNil(t, msg) assert.NotEmpty(t, msg.Payload) assert.NotEmpty(t, msg.XAction) @@ -63,80 +54,81 @@ func TestNewMBufSuccess(t *testing.T) { assert.Equal(t, msg.Len, len(tests.DummyPayload)) } -func TestInitFailure(t *testing.T) { - var err error - log, err = logger.InitLogger(logger.DebugLevel) - if err != nil { - t.Errorf("#rmrCgoApi_test.TestInitFailure - failed to initialize logger, error: %s", err) +func TestIsReadySuccess(t *testing.T) { + log := initLog(t) + + initRmr(tests.GetPort(), tests.MaxMsgSize, tests.Flags, log) + if msgr == nil || !msgr.IsReady() { + t.Errorf("#rmr_c_go_api_test.TestIsReadySuccess - The rmr router is not ready") } - go initRmr(tests.GetPort(), tests.MaxMsgSize, tests.Flags, log) - time.Sleep(time.Second) - if msgr != nil { - t.Errorf("The rmr router is ready, should be not ready") + msgr.Close() +} +func TestSendRecvMsgSuccess(t *testing.T) { + log := initLog(t) + + initRmr(tests.GetPort(), tests.MaxMsgSize, tests.Flags, log) + if msgr == nil || !msgr.IsReady() { + t.Errorf("#rmr_c_go_api_test.TestSendRecvMsgSuccess - The rmr router is not ready") } + msg := rmrCgo.NewMBuf(1, tests.MaxMsgSize, "test 1", &tests.DummyPayload, &tests.DummyXAction) + log.Debugf("#rmr_c_go_api_test.TestSendRecvMsgSuccess - Going to send the message: %#v\n", msg) + result, err := msgr.SendMsg(msg) + + assert.Nil(t, err) + assert.NotNil(t, result) + + msgR, err := msgr.RecvMsg() + + assert.Nil(t, err) + assert.NotNil(t, msgR) + msgr.Close() } -//func TestInitSuccess(t *testing.T) { -// var err error -// log, err = logger.InitLogger(true) -// if err != nil { -// t.Errorf("#rmrCgoApi_test.TestInitSuccess - failed to initialize logger, error: %s", err) -// } -// go initRmr(tests.GetPort(), tests.MaxMsgSize, tests.Flags, log) -// time.Sleep(time.Second) -// if msgr == nil { -// t.Errorf("The rmr router is not ready, should be ready") -// } -//} - -func TestIsReadyFailure(t *testing.T) { - var err error - log, err = logger.InitLogger(logger.InfoLevel) - if err != nil { - t.Errorf("#rmrCgoApi_test.TestIsReadyFailure - failed to initialize logger, error: %s", err) +func TestSendMsgRmrInvalidMsgNumError(t *testing.T) { + log := initLog(t) + + initRmr(tests.GetPort(), tests.MaxMsgSize, tests.Flags, log) + if msgr == nil || !msgr.IsReady() { + t.Errorf("#rmr_c_go_api_test.TestSendMsgRmrInvalidMsgNumError - The rmr router is not ready") + } + + msg := rmrCgo.NewMBuf(10, tests.MaxMsgSize, "test 1", &tests.DummyPayload, &tests.DummyXAction) + log.Debugf("#rmr_c_go_api_test.TestSendMsgRmrInvalidMsgNumError - Going to send the message: %#v\n", msg) + result, err := msgr.SendMsg(msg) + + assert.NotNil(t, err) + assert.Nil(t, result) + + msgr.Close() +} + +func TestSendMsgRmrInvalidPortError(t *testing.T) { + log := initLog(t) + + initRmr("tcp:"+strconv.Itoa(5555), tests.MaxMsgSize, tests.Flags, log) + if msgr == nil || !msgr.IsReady() { + t.Errorf("#rmr_c_go_api_test.TestSendMsgRmrInvalidPortError - The rmr router is not ready") } - go initRmr(tests.GetPort(), tests.MaxMsgSize, tests.Flags, log) - time.Sleep(time.Second) - assert.True(t, msgr == nil || !(*msgr).IsReady()) + msg := rmrCgo.NewMBuf(1, tests.MaxMsgSize, "test 1", &tests.DummyPayload, &tests.DummyXAction) + log.Debugf("#rmr_c_go_api_test.TestSendMsgRmrInvalidPortError - Going to send the message: %#v\n", msg) + result, err := msgr.SendMsg(msg) + + assert.NotNil(t, err) + assert.Nil(t, result) + + msgr.Close() } -//func TestSendRecvMsgSuccess(t *testing.T) { -// var err error -// log, err = logger.InitLogger(true) -// if err != nil { -// t.Errorf("#rmrCgoApi_test.TestSendRecvMsgSuccess - failed to initialize logger, error: %s", err) -// } -// go initRmr(tests.GetPort(), tests.MaxMsgSize, tests.Flags, log) -// time.Sleep(time.Second) -// if msgr == nil || !(*msgr).IsReady() { -// t.Errorf("#rmrCgoApi_test.TestSendRecvMsgSuccess - The rmr router is not ready") -// } -// msg := NewMBuf(1, tests.MaxMsgSize, &tests.DummyPayload, &tests.DummyXAction) -// log.Debugf("#rmrCgoApi_test.TestSendRecvMsgSuccess - Going to send the message: %#v\n", msg) -// msgR, _ := (*msgr).SendMsg(msg) -// log.Debugf("#rmrCgoApi_test.TestSendRecvMsgSuccess - The message has been sent %#v\n", msgR) -// log.Debugf("#rmrCgoApi_test.TestSendRecvMsgSuccess - The payload: %#v\n", msgR.Payload) -// msgR = (*msgr).RecvMsg() -// log.Debugf("#rmrCgoApi_test.TestSendRecvMsgSuccess - The message has been received: %#v\n", msgR) -// log.Debugf("#rmrCgoApi_test.TestSendRecvMsgSuccess - The payload: %#v\n", msgR.Payload) -// (*msgr).Close() -//} - -//func TestIsReadySuccess(t *testing.T) { -// var err error -// log, err = logger.InitLogger(true) -// if err != nil { -// t.Errorf("#rmrCgoApi_test.TestIsReadySuccess - The rmr router is not ready") -// } -// go initRmr(tests.GetPort(), tests.MaxMsgSize, tests.Flags, log) -// time.Sleep(time.Second) -// if msgr == nil || !(*msgr).IsReady() { -// t.Errorf("#rmrCgoApi_test.TestIsReadySuccess - The rmr router is not ready") -// } -//} - -func initRmr(port string, maxMsgSize int, flags int, log *logger.Logger){ - var ctx *Context +func initRmr(port string, maxMsgSize int, flags int, log *logger.Logger) { + var ctx *rmrCgo.Context msgr = ctx.Init(port, maxMsgSize, flags, log) } + +func initLog(t *testing.T) *logger.Logger { + log, err := logger.InitLogger(logger.DebugLevel) + if err != nil { + t.Errorf("#rmr_c_go_api_test.initLog - failed to initialize logger, error: %s", err) + } + return log +} diff --git a/E2Manager/rmrCgo/rmrCgoTypes.go b/E2Manager/rmrCgo/rmrCgoTypes.go index 0e351d7..1fe6032 100644 --- a/E2Manager/rmrCgo/rmrCgoTypes.go +++ b/E2Manager/rmrCgo/rmrCgoTypes.go @@ -135,10 +135,9 @@ type Context struct { } type RmrMessenger interface { - Init(port string, maxMsgSize int, flags int, logger *logger.Logger) *RmrMessenger + Init(port string, maxMsgSize int, flags int, logger *logger.Logger) RmrMessenger SendMsg(msg *MBuf) (*MBuf, error) RecvMsg() (*MBuf, error) - RtsMsg(msg *MBuf) IsReady() bool Close() } diff --git a/E2Manager/router_test.txt b/E2Manager/router_test.txt new file mode 100644 index 0000000..2315519 --- /dev/null +++ b/E2Manager/router_test.txt @@ -0,0 +1,3 @@ +newrt|start +rte|1|127.0.0.1:3801 +newrt|end diff --git a/E2Manager/services/rmrreceiver/rmr_receiver.go b/E2Manager/services/rmrreceiver/rmr_receiver.go index 8cc807f..2f57db2 100644 --- a/E2Manager/services/rmrreceiver/rmr_receiver.go +++ b/E2Manager/services/rmrreceiver/rmr_receiver.go @@ -26,10 +26,10 @@ import ( type RmrReceiver struct { logger *logger.Logger nManager *notificationmanager.NotificationManager - messenger *rmrCgo.RmrMessenger + messenger rmrCgo.RmrMessenger } -func NewRmrReceiver(logger *logger.Logger, messenger *rmrCgo.RmrMessenger, nManager *notificationmanager.NotificationManager) *RmrReceiver { +func NewRmrReceiver(logger *logger.Logger, messenger rmrCgo.RmrMessenger, nManager *notificationmanager.NotificationManager) *RmrReceiver { return &RmrReceiver{ logger: logger, nManager: nManager, @@ -40,14 +40,15 @@ func NewRmrReceiver(logger *logger.Logger, messenger *rmrCgo.RmrMessenger, nMana func (r *RmrReceiver) ListenAndHandle() { for { - mbuf, err := (*r.messenger).RecvMsg() - r.logger.Debugf("#RmrReceiver.ListenAndHandle - Going to handle received message: %#v\n", mbuf) + mbuf, err := r.messenger.RecvMsg() if err != nil { - // TODO: error handling? + r.logger.Errorf("#RmrReceiver.ListenAndHandle - error: %s", err) continue } + r.logger.Debugf("#RmrReceiver.ListenAndHandle - Going to handle received message: %#v\n", mbuf) + // TODO: go routine? _ = r.nManager.HandleMessage(mbuf) } diff --git a/E2Manager/services/rmrreceiver/rmr_receiver_test.go b/E2Manager/services/rmrreceiver/rmr_receiver_test.go index 7c947db..f156427 100644 --- a/E2Manager/services/rmrreceiver/rmr_receiver_test.go +++ b/E2Manager/services/rmrreceiver/rmr_receiver_test.go @@ -19,19 +19,16 @@ package rmrreceiver import ( "e2mgr/configuration" - "e2mgr/converters" "e2mgr/logger" "e2mgr/managers" "e2mgr/managers/notificationmanager" "e2mgr/mocks" "e2mgr/providers/rmrmsghandlerprovider" - "e2mgr/rNibWriter" "e2mgr/rmrCgo" "e2mgr/services" "e2mgr/services/rmrsender" "e2mgr/tests" "fmt" - "gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/reader" "testing" "time" ) @@ -46,7 +43,7 @@ func TestListenAndHandle(t *testing.T) { time.Sleep(time.Microsecond * 10) } -func initRmrMessenger(log *logger.Logger) *rmrCgo.RmrMessenger { +func initRmrMessenger(log *logger.Logger) rmrCgo.RmrMessenger { rmrMessengerMock := &mocks.RmrMessengerMock{} rmrMessenger := rmrCgo.RmrMessenger(rmrMessengerMock) rmrMessengerMock.On("Init", tests.GetPort(), tests.MaxMsgSize, tests.Flags, log).Return(&rmrMessenger) @@ -55,32 +52,23 @@ func initRmrMessenger(log *logger.Logger) *rmrCgo.RmrMessenger { var buf *rmrCgo.MBuf e := fmt.Errorf("test error") rmrMessengerMock.On("RecvMsg").Return(buf, e) - return &rmrMessenger + return rmrMessenger } func initRmrReceiver(logger *logger.Logger) *RmrReceiver { config := &configuration.Configuration{RnibRetryIntervalMs: 10, MaxRnibConnectionAttempts: 3} readerMock := &mocks.RnibReaderMock{} - rnibReaderProvider := func() reader.RNibReader { - return readerMock - } + writerMock := &mocks.RnibWriterMock{} - rnibWriterProvider := func() rNibWriter.RNibWriter { - return writerMock - } - rnibDataService := services.NewRnibDataService(logger, config, rnibReaderProvider, rnibWriterProvider) + + rnibDataService := services.NewRnibDataService(logger, config, readerMock, writerMock) rmrMessenger := initRmrMessenger(logger) rmrSender := rmrsender.NewRmrSender(logger, rmrMessenger) ranSetupManager := managers.NewRanSetupManager(logger, rmrSender, rnibDataService) - ranReconnectionManager := managers.NewRanReconnectionManager(logger, configuration.ParseConfiguration(), rnibDataService, ranSetupManager) - ranStatusChangeManager := managers.NewRanStatusChangeManager(logger, rmrSender) - x2SetupResponseConverter := converters.NewX2SetupResponseConverter(logger) - x2SetupResponseManager := managers.NewX2SetupResponseManager(x2SetupResponseConverter) - x2SetupFailureResponseConverter := converters.NewX2SetupFailureResponseConverter(logger) - x2SetupFailureResponseManager := managers.NewX2SetupFailureResponseManager(x2SetupFailureResponseConverter) - rmrNotificationHandlerProvider := rmrmsghandlerprovider.NewNotificationHandlerProvider(logger, rnibDataService, ranReconnectionManager, ranStatusChangeManager, rmrSender, x2SetupResponseManager, x2SetupFailureResponseManager ) + rmrNotificationHandlerProvider := rmrmsghandlerprovider.NewNotificationHandlerProvider() + rmrNotificationHandlerProvider.Init(logger, config, rnibDataService, rmrSender, ranSetupManager) notificationManager := notificationmanager.NewNotificationManager(logger, rmrNotificationHandlerProvider) return NewRmrReceiver(logger, rmrMessenger, notificationManager) } diff --git a/E2Manager/services/rmrsender/rmr_sender.go b/E2Manager/services/rmrsender/rmr_sender.go index daf7679..ca8ce36 100644 --- a/E2Manager/services/rmrsender/rmr_sender.go +++ b/E2Manager/services/rmrsender/rmr_sender.go @@ -25,10 +25,10 @@ import ( type RmrSender struct { logger *logger.Logger - messenger *rmrCgo.RmrMessenger + messenger rmrCgo.RmrMessenger } -func NewRmrSender(logger *logger.Logger, messenger *rmrCgo.RmrMessenger) *RmrSender { +func NewRmrSender(logger *logger.Logger, messenger rmrCgo.RmrMessenger) *RmrSender { return &RmrSender{ logger: logger, messenger: messenger, @@ -36,10 +36,9 @@ func NewRmrSender(logger *logger.Logger, messenger *rmrCgo.RmrMessenger) *RmrSen } func (r *RmrSender) Send(rmrMessage *models.RmrMessage) error { - transactionIdByteArr := []byte(rmrMessage.RanName) - msg := rmrCgo.NewMBuf(rmrMessage.MsgType, len(rmrMessage.Payload), rmrMessage.RanName, &rmrMessage.Payload, &transactionIdByteArr) + msg := rmrCgo.NewMBuf(rmrMessage.MsgType, len(rmrMessage.Payload), rmrMessage.RanName, &rmrMessage.Payload, &rmrMessage.XAction) - _, err := (*r.messenger).SendMsg(msg) + _, err := r.messenger.SendMsg(msg) if err != nil { r.logger.Errorf("#RmrSender.Send - RAN name: %s , Message type: %d - Failed sending message. Error: %v", rmrMessage.RanName, rmrMessage.MsgType, err) diff --git a/E2Manager/services/rmrsender/rmr_sender_test.go b/E2Manager/services/rmrsender/rmr_sender_test.go index 26ab0b4..c4d0c38 100644 --- a/E2Manager/services/rmrsender/rmr_sender_test.go +++ b/E2Manager/services/rmrsender/rmr_sender_test.go @@ -50,12 +50,12 @@ func TestRmrSenderSendSuccess(t *testing.T) { ranName := "test" payload := []byte("some payload") - xaction := []byte(ranName) - mbuf := rmrCgo.NewMBuf(123, len(payload), ranName, &payload, &xaction) + var xAction []byte + mbuf := rmrCgo.NewMBuf(123, len(payload), ranName, &payload, &xAction) rmrMessengerMock.On("SendMsg", mbuf).Return(&rmrCgo.MBuf{}, nil) - rmrMsg := models.NewRmrMessage(123, ranName, payload) + rmrMsg := models.NewRmrMessage(123, ranName, payload, xAction) rmrMessenger := rmrCgo.RmrMessenger(rmrMessengerMock) - rmrSender := NewRmrSender(logger, &rmrMessenger) + rmrSender := NewRmrSender(logger, rmrMessenger) err := rmrSender.Send(rmrMsg) assert.Nil(t, err) rmrMessengerMock.AssertCalled(t, "SendMsg",mbuf) @@ -67,12 +67,12 @@ func TestRmrSenderSendFailure(t *testing.T) { ranName := "test" payload := []byte("some payload") - xaction := []byte(ranName) - mbuf := rmrCgo.NewMBuf(123, len(payload), ranName, &payload, &xaction) + var xAction []byte + mbuf := rmrCgo.NewMBuf(123, len(payload), ranName, &payload, &xAction) rmrMessengerMock.On("SendMsg", mbuf).Return(mbuf, fmt.Errorf("rmr send failure")) - rmrMsg := models.NewRmrMessage(123, ranName, payload) + rmrMsg := models.NewRmrMessage(123, ranName, payload, xAction) rmrMessenger := rmrCgo.RmrMessenger(rmrMessengerMock) - rmrSender := NewRmrSender(logger, &rmrMessenger) + rmrSender := NewRmrSender(logger, rmrMessenger) err := rmrSender.Send(rmrMsg) rmrMessengerMock.AssertCalled(t, "SendMsg",mbuf) assert.NotNil(t, err) diff --git a/E2Manager/services/rnib_data_service.go b/E2Manager/services/rnib_data_service.go index 02f8e1d..1e824e8 100644 --- a/E2Manager/services/rnib_data_service.go +++ b/E2Manager/services/rnib_data_service.go @@ -21,9 +21,9 @@ import ( "e2mgr/configuration" "e2mgr/logger" "e2mgr/rNibWriter" + "gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/common" "gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/entities" "gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/reader" - "gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/common" "net" "time" ) @@ -38,20 +38,20 @@ type RNibDataService interface { } type rNibDataService struct { - logger *logger.Logger - rnibReaderProvider func() reader.RNibReader - rnibWriterProvider func() rNibWriter.RNibWriter - maxAttempts int - retryInterval time.Duration + logger *logger.Logger + rnibReader reader.RNibReader + rnibWriter rNibWriter.RNibWriter + maxAttempts int + retryInterval time.Duration } -func NewRnibDataService(logger *logger.Logger, config *configuration.Configuration, rnibReaderProvider func() reader.RNibReader, rnibWriterProvider func() rNibWriter.RNibWriter) *rNibDataService { +func NewRnibDataService(logger *logger.Logger, config *configuration.Configuration, rnibReader reader.RNibReader, rnibWriter rNibWriter.RNibWriter) *rNibDataService { return &rNibDataService{ - logger: logger, - rnibReaderProvider: rnibReaderProvider, - rnibWriterProvider: rnibWriterProvider, - maxAttempts: config.MaxRnibConnectionAttempts, - retryInterval: time.Duration(config.RnibRetryIntervalMs) * time.Millisecond, + logger: logger, + rnibReader: rnibReader, + rnibWriter: rnibWriter, + maxAttempts: config.MaxRnibConnectionAttempts, + retryInterval: time.Duration(config.RnibRetryIntervalMs) * time.Millisecond, } } @@ -59,7 +59,7 @@ func (w *rNibDataService) UpdateNodebInfo(nodebInfo *entities.NodebInfo) error { w.logger.Infof("#RnibDataService.UpdateNodebInfo - nodebInfo: %s", nodebInfo) err := w.retry("UpdateNodebInfo", func() (err error) { - err = w.rnibWriterProvider().UpdateNodebInfo(nodebInfo) + err = w.rnibWriter.UpdateNodebInfo(nodebInfo) return }) @@ -70,7 +70,7 @@ func (w *rNibDataService) SaveNodeb(nbIdentity *entities.NbIdentity, nb *entitie w.logger.Infof("#RnibDataService.SaveNodeb - nbIdentity: %s, nodebInfo: %s", nbIdentity, nb) err := w.retry("SaveNodeb", func() (err error) { - err = w.rnibWriterProvider().SaveNodeb(nbIdentity, nb) + err = w.rnibWriter.SaveNodeb(nbIdentity, nb) return }) @@ -81,7 +81,7 @@ func (w *rNibDataService) SaveRanLoadInformation(inventoryName string, ranLoadIn w.logger.Infof("#RnibDataService.SaveRanLoadInformation - inventoryName: %s, ranLoadInformation: %s", inventoryName, ranLoadInformation) err := w.retry("SaveRanLoadInformation", func() (err error) { - err = w.rnibWriterProvider().SaveRanLoadInformation(inventoryName, ranLoadInformation) + err = w.rnibWriter.SaveRanLoadInformation(inventoryName, ranLoadInformation) return }) @@ -94,7 +94,7 @@ func (w *rNibDataService) GetNodeb(ranName string) (*entities.NodebInfo, error) var nodeb *entities.NodebInfo = nil err := w.retry("GetNodeb", func() (err error) { - nodeb, err = w.rnibReaderProvider().GetNodeb(ranName) + nodeb, err = w.rnibReader.GetNodeb(ranName) return }) @@ -107,7 +107,7 @@ func (w *rNibDataService) GetListNodebIds() ([]*entities.NbIdentity, error) { var nodeIds []*entities.NbIdentity = nil err := w.retry("GetListNodebIds", func() (err error) { - nodeIds, err = w.rnibReaderProvider().GetListNodebIds() + nodeIds, err = w.rnibReader.GetListNodebIds() return }) @@ -116,7 +116,7 @@ func (w *rNibDataService) GetListNodebIds() ([]*entities.NbIdentity, error) { func (w *rNibDataService) PingRnib() bool { err := w.retry("GetListNodebIds", func() (err error) { - _, err = w.rnibReaderProvider().GetListNodebIds() + _, err = w.rnibReader.GetListNodebIds() return }) @@ -144,7 +144,6 @@ func (w *rNibDataService) retry(rnibFunc string, f func() error) (err error) { } } - func isRnibConnectionError(err error) bool { internalErr, ok := err.(*common.InternalError) if !ok { diff --git a/E2Manager/services/rnib_data_service_test.go b/E2Manager/services/rnib_data_service_test.go index 8d57b4e..0202292 100644 --- a/E2Manager/services/rnib_data_service_test.go +++ b/E2Manager/services/rnib_data_service_test.go @@ -21,11 +21,9 @@ import ( "e2mgr/configuration" "e2mgr/logger" "e2mgr/mocks" - "e2mgr/rNibWriter" "fmt" "gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/common" "gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/entities" - "gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/reader" "github.com/stretchr/testify/assert" "net" "strings" @@ -45,16 +43,12 @@ func setupRnibDataServiceTestWithMaxAttempts(t *testing.T, maxAttempts int) (*rN config := &configuration.Configuration{RnibRetryIntervalMs: 10, MaxRnibConnectionAttempts: maxAttempts} readerMock := &mocks.RnibReaderMock{} - rnibReaderProvider := func() reader.RNibReader { - return readerMock - } + writerMock := &mocks.RnibWriterMock{} - rnibWriterProvider := func() rNibWriter.RNibWriter { - return writerMock - } - rnibDataService := NewRnibDataService(logger, config, rnibReaderProvider, rnibWriterProvider) + + rnibDataService := NewRnibDataService(logger, config, readerMock, writerMock) assert.NotNil(t, rnibDataService) return rnibDataService, readerMock, writerMock diff --git a/E2Manager/tests/dataProvider.go b/E2Manager/tests/dataProvider.go index 64d390e..7e8a501 100644 --- a/E2Manager/tests/dataProvider.go +++ b/E2Manager/tests/dataProvider.go @@ -28,7 +28,7 @@ import ( const ( MaxMsgSize int = 4096 - Port int = 5555 + Port int = 3801 Flags int = 0 MessageType int = 1001 RanPort uint16 = 879 diff --git a/E2Manager/tests/utils.go b/E2Manager/tests/utils.go new file mode 100644 index 0000000..894f554 --- /dev/null +++ b/E2Manager/tests/utils.go @@ -0,0 +1,59 @@ +// +// Copyright 2019 AT&T Intellectual Property +// Copyright 2019 Nokia +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package tests + +import ( + "e2mgr/configuration" + "e2mgr/logger" + "e2mgr/mocks" + "e2mgr/rmrCgo" + "e2mgr/services" + "e2mgr/services/rmrsender" + "testing" +) + +func InitLog(t *testing.T) *logger.Logger { + log, err := logger.InitLogger(logger.InfoLevel) + if err != nil { + t.Errorf("#test.utils.InitLog - failed to initialize logger, error: %s", err) + } + return log +} + +func InitRmrSender(rmrMessengerMock *mocks.RmrMessengerMock, log *logger.Logger) *rmrsender.RmrSender { + rmrMessenger := rmrCgo.RmrMessenger(rmrMessengerMock) + rmrMessengerMock.On("Init", GetPort(), MaxMsgSize, Flags, log).Return(&rmrMessenger) + return rmrsender.NewRmrSender(log, rmrMessenger) +} + +func InitRnibDataService(t *testing.T) services.RNibDataService{ + + logger := InitLog(t) + config := InitConfiguration() + + readerMock := &mocks.RnibReaderMock{} + writerMock := &mocks.RnibWriterMock{} + + return services.NewRnibDataService(logger, config, readerMock, writerMock) +} + +func InitConfiguration() *configuration.Configuration{ + return &configuration.Configuration{RnibRetryIntervalMs: 10, MaxRnibConnectionAttempts: 3} +} + + diff --git a/tools/xapp_mock/configuration.json b/tools/xapp_mock/configuration.json deleted file mode 100644 index 9df43a1..0000000 --- a/tools/xapp_mock/configuration.json +++ /dev/null @@ -1,4 +0,0 @@ -[ - {“id”: “RIC_X2_SETUP_REQ” , “rmrMessageType”: 10060, “transactionId”: “e2e$”, “payloadHeader”: “$ranIp|$ranPort|$ranName|#packedPayload|”, “packedPayload”: "3137322e31372e302e357c353537377c74657374327c34367c0006002a000002001500080013302300fffff000140017000001f700133023fffff0000000133023000000000001" }, - {“id”: “RIC_ENB_CONF_UPDATE_ACK_positive” , “rmrMessageType”: 10081, “transactionId”: “e2e$”, “payloadHeader”: “$ranIp|$ranPort|$ranName|#packedPayload|”, “packedPayload”: "2025000a00000100f70003000000" } -] diff --git a/tools/xapp_mock/main/xapp_mock.go b/tools/xapp_mock/main/xapp_mock.go deleted file mode 100644 index ae2c601..0000000 --- a/tools/xapp_mock/main/xapp_mock.go +++ /dev/null @@ -1,109 +0,0 @@ -// -// Copyright 2019 AT&T Intellectual Property -// Copyright 2019 Nokia -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -package main - -import ( - "../frontend" - "../rmr" - "../sender" - "flag" - "fmt" - "github.com/pkg/errors" - "log" - "os" - "strconv" -) - -const ( - ENV_RMR_PORT = "RMR_PORT" - RMR_PORT_DEFAULT = 5001 -) - -var rmrService *rmr.Service - -func main() { - var rmrContext *rmr.Context - - var rmrConfig rmr.Config = rmr.Config{Port: RMR_PORT_DEFAULT, MaxMsgSize: rmr.RMR_MAX_MSG_SIZE, MaxRetries: 3, Flags: 0} - if port, err := strconv.ParseUint(os.Getenv(ENV_RMR_PORT), 10, 16); err == nil { - rmrConfig.Port = int(port) - } else { - log.Printf("%s: %s, using default (%d).", ENV_RMR_PORT, err,RMR_PORT_DEFAULT) - } - rmrService = rmr.NewService(rmrConfig, rmrContext) - - /* Load configuration file*/ - err := frontend.ProcessConfigurationFile("resources","conf", ".json", - func(data []byte) error { - return frontend.JsonCommandsDecoder(data,jsonCommandsDecoderCB) - }) - if err != nil { - log.Fatalf("processing Error: %s", err) - } - - log.Print("xapp_mock is up and running.") - - cmd:= flag.Arg(0) /*first remaining argument after flags have been processed*/ - if err := frontend.JsonCommandDecoder([]byte(cmd),jsonCommandDecoderCB); err != nil { - log.Printf("command processing Error: %s", err) - } - - rmrService.CloseContext() - - log.Print("xapp_mock is down.") -} - - -// TODO: move callbacks to Dispatcher. -func jsonCommandsDecoderCB(command *frontend.JsonCommand) error { - if len(command.Id) == 0{ - return errors.New(fmt.Sprintf("invalid command, no Id")) - } - frontend.Configuration[command.Id] = command - if rmrMsgId, err := rmr.MessageIdToUint(command.WaitForRmrMessageType); err != nil { - return errors.New(fmt.Sprintf("invalid rmr message id: %s",command.WaitForRmrMessageType)) - } else { - frontend.WaitedForRmrMessageType[int(rmrMsgId)] = command - } - return nil -} - -// TODO: merge command with configuration -func jsonCommandDecoderCB(command *frontend.JsonCommand) error { - if len(command.Id) == 0{ - return errors.New(fmt.Sprintf("invalid command, no Id")) - } - switch command.Action { - case frontend.SendRmrMessage: - if err := sender.SendJsonRmrMessage(*command, nil, rmrService); err != nil { - return err - } - if len(command.WaitForRmrMessageType) > 0 { - rmrService.ListenAndHandle() //TODO: handle error - } - case frontend.ReceiveRmrMessage: - if rmrMsgId, err := rmr.MessageIdToUint(command.RmrMessageType); err != nil { - return errors.New(fmt.Sprintf("invalid rmr message id: %s",command.WaitForRmrMessageType)) - } else { - frontend.WaitedForRmrMessageType[int(rmrMsgId)] = command - } - rmrService.ListenAndHandle() //TODO: handle error - default: - return errors.New(fmt.Sprintf("invalid command action %s", command.Action)) - } - return nil -} \ No newline at end of file diff --git a/tools/xapp_mock/resources/router.txt b/tools/xapp_mock/resources/router.txt deleted file mode 100644 index 1d3fea3..0000000 --- a/tools/xapp_mock/resources/router.txt +++ /dev/null @@ -1,4 +0,0 @@ -newrt|start -rte|1001|10.0.2.15:38000 -rte|2002|10.0.2.15:3801 -newrt|end diff --git a/tools/xapp_mock/Dockerfile b/tools/xappmock/Dockerfile similarity index 66% rename from tools/xapp_mock/Dockerfile rename to tools/xappmock/Dockerfile index 48c07ae..b9cbf64 100644 --- a/tools/xapp_mock/Dockerfile +++ b/tools/xappmock/Dockerfile @@ -16,30 +16,29 @@ # ############################################################################## -FROM nexus3.o-ran-sc.org:10004/bldr-ubuntu16-c-go:1-u16.04-nng1.1.1 as ubuntu +FROM nexus3.o-ran-sc.org:10004/bldr-ubuntu16-c-go:2-u16.04-nng as ubuntu -WORKDIR /opt/xapp_mock +WORKDIR /opt/xappmock COPY . . ENV PATH=$PATH:/usr/local/go/bin:/usr/lib/go-1.12/bin # Install RMr library and dev files -RUN wget --content-disposition https://packagecloud.io/o-ran-sc/master/packages/debian/stretch/rmr_1.3.0_amd64.deb/download.deb -RUN dpkg -i rmr_1.3.0_amd64.deb -RUN wget --content-disposition https://packagecloud.io/o-ran-sc/master/packages/debian/stretch/rmr-dev_1.3.0_amd64.deb/download.deb -RUN dpkg -i rmr-dev_1.3.0_amd64.deb +RUN wget --content-disposition https://packagecloud.io/o-ran-sc/staging/packages/debian/stretch/rmr_1.10.0_amd64.deb/download.deb +RUN dpkg -i rmr_1.10.0_amd64.deb +RUN wget --content-disposition https://packagecloud.io/o-ran-sc/staging/packages/debian/stretch/rmr-dev_1.10.0_amd64.deb/download.deb +RUN dpkg -i rmr-dev_1.10.0_amd64.deb -RUN go get github.com/pkg/errors -RUN go build main/xapp_mock.go +RUN go build main/xappmock.go FROM ubuntu:16.04 -COPY --from=ubuntu /opt/xapp_mock/xapp_mock /opt/xapp_mock/xapp_mock -COPY --from=ubuntu /opt/xapp_mock/resources /opt/xapp_mock/resources +COPY --from=ubuntu /opt/xappmock/xappmock /opt/xappmock/xappmock +COPY --from=ubuntu /opt/xappmock/resources /opt/xappmock/resources COPY --from=ubuntu /usr/local/lib/librmr_nng.so.1 /usr/local/lib/librmr_nng.so.1 COPY --from=ubuntu /usr/local/lib/libnng.so.1 /usr/local/lib/libnng.so.1 -WORKDIR /opt/xapp_mock +WORKDIR /opt/xappmock ENV LD_LIBRARY_PATH=/usr/local/lib ENV RMR_SEED_RT=resources/router.txt ENV RMR_PORT=5001 -#CMD mkdir -p resources/conf exec ./xapp_mock +#CMD mkdir -p resources/conf exec ./xappmock CMD mkdir -p resources/conf && exec /bin/bash diff --git a/tools/xappmock/dispatcher/dispatcher.go b/tools/xappmock/dispatcher/dispatcher.go new file mode 100644 index 0000000..1bf65f1 --- /dev/null +++ b/tools/xappmock/dispatcher/dispatcher.go @@ -0,0 +1,290 @@ +package dispatcher + +import ( + "context" + "fmt" + "github.com/pkg/errors" + "log" + "reflect" + "sync" + "time" + "xappmock/enums" + "xappmock/models" + "xappmock/rmr" + "xappmock/sender" +) + +// Id -> Command +var configuration = make(map[string]*models.JsonCommand) +// Rmr Message Id -> Command +var waitForRmrMessageType = make(map[int]*models.JsonCommand) + +func addRmrMessageToWaitFor(rmrMessageToWaitFor string, command models.JsonCommand) error { + rmrMsgId, err := rmr.MessageIdToUint(rmrMessageToWaitFor) + + if err != nil { + return errors.New(fmt.Sprintf("invalid rmr message id: %s", rmrMessageToWaitFor)) + } + + waitForRmrMessageType[int(rmrMsgId)] = &command + return nil +} + +type Dispatcher struct { + rmrService *rmr.Service + processResult models.ProcessResult +} + +func (d *Dispatcher) GetProcessResult() models.ProcessResult { + return d.processResult +} + +func New(rmrService *rmr.Service) *Dispatcher { + return &Dispatcher{ + rmrService: rmrService, + } +} + +func (d *Dispatcher) JsonCommandsDecoderCB(cmd models.JsonCommand) error { + if len(cmd.Id) == 0 { + return errors.New(fmt.Sprintf("invalid cmd, no id")) + } + configuration[cmd.Id] = &cmd + + if len(cmd.ReceiveRmrMessageType) == 0 { + return nil + } + + return addRmrMessageToWaitFor(cmd.ReceiveRmrMessageType, cmd) +} + +func (d *Dispatcher) sendNoRepeat(command models.JsonCommand) { + err := sender.SendJsonRmrMessage(command, nil, d.rmrService) + + if err != nil { + log.Printf("Dispatcher.sendHandler - error sending rmr message: %s", err) + d.processResult.Err = err + d.processResult.Stats.SentErrorCount++ + return + } + + d.processResult.Stats.SentCount++ + +} + +func (d *Dispatcher) sendWithRepeat(ctx context.Context, command models.JsonCommand) { + for repeatCount := command.RepeatCount; repeatCount > 0; repeatCount-- { + + select { + case <-ctx.Done(): + return + default: + } + + err := sender.SendJsonRmrMessage(command, nil, d.rmrService) + + if err != nil { + log.Printf("Dispatcher.sendHandler - error sending rmr message: %s", err) + d.processResult.Stats.SentErrorCount++ + continue + } + + d.processResult.Stats.SentCount++ + time.Sleep(time.Duration(command.RepeatDelayInMs) * time.Millisecond) + } +} + +func (d *Dispatcher) sendHandler(ctx context.Context, sendAndReceiveWg *sync.WaitGroup, command models.JsonCommand) { + + defer sendAndReceiveWg.Done() + var listenAndHandleWg sync.WaitGroup + + if len(command.ReceiveRmrMessageType) > 0 { + err := addRmrMessageToWaitFor(command.ReceiveRmrMessageType, command) + + if err != nil { + d.processResult.Err = err + return + } + + listenAndHandleWg.Add(1) + go d.listenAndHandle(ctx, &listenAndHandleWg, command.RepeatCount) + } + + if command.RepeatCount == 0 { + d.sendNoRepeat(command) + } else { + d.sendWithRepeat(ctx, command) + } + + if len(command.ReceiveRmrMessageType) > 0 { + listenAndHandleWg.Wait() + } +} + +func (d *Dispatcher) receiveHandler(ctx context.Context, sendAndReceiveWg *sync.WaitGroup, command models.JsonCommand) { + + defer sendAndReceiveWg.Done() + + err := addRmrMessageToWaitFor(command.ReceiveRmrMessageType, command) + + if err != nil { + d.processResult.Err = err + return + } + + var listenAndHandleWg sync.WaitGroup + listenAndHandleWg.Add(1) // this is due to the usage of listenAndHandle as a goroutine in the sender case + d.listenAndHandle(ctx, &listenAndHandleWg, command.RepeatCount) +} + +func getMergedCommand(cmd *models.JsonCommand) (models.JsonCommand, error) { + var command models.JsonCommand + if len(cmd.Id) == 0 { + return command, errors.New(fmt.Sprintf("invalid command, no id")) + } + + command = *cmd + + conf, ok := configuration[cmd.Id] + + if ok { + command = *conf + mergeConfigurationAndCommand(&command, cmd) + } + + return command, nil +} + +func (d *Dispatcher) ProcessJsonCommand(ctx context.Context, cmd *models.JsonCommand) { + + command, err := getMergedCommand(cmd) + + if err != nil { + d.processResult.Err = err + return + } + + var sendAndReceiveWg sync.WaitGroup + + commandAction := enums.CommandAction(command.Action) + + switch commandAction { + + case enums.SendRmrMessage: + sendAndReceiveWg.Add(1) + go d.sendHandler(ctx, &sendAndReceiveWg, command) + case enums.ReceiveRmrMessage: + sendAndReceiveWg.Add(1) + go d.receiveHandler(ctx, &sendAndReceiveWg, command) + default: + d.processResult = models.ProcessResult{Err: errors.New(fmt.Sprintf("invalid command action %s", command.Action))} + return + } + + sendAndReceiveWg.Wait() +} + +func (d *Dispatcher) listenAndHandleNoRepeat(ctx context.Context) { + for { + select { + case <-ctx.Done(): + return + default: + } + + mbuf, err := d.rmrService.RecvMessage() + + if err != nil { + d.processResult.Err = err + d.processResult.Stats.ReceivedErrorCount++ + return + } + + _, ok := waitForRmrMessageType[mbuf.MType] + + if !ok { + log.Printf("#Dispatcher.listenAndHandle - Unexpected msg: %s", mbuf) + d.processResult.Stats.ReceivedUnexpectedCount++ + continue + } + + log.Printf("#Dispatcher.listenAndHandle - expected msg: %s", mbuf) + d.processResult.Stats.ReceivedExpectedCount++ + return + } +} + +func (d *Dispatcher) receive(ctx context.Context) { + +} + +func (d *Dispatcher) listenAndHandleWithRepeat(ctx context.Context, repeatCount int) { + for d.processResult.Stats.ReceivedExpectedCount < repeatCount { + select { + case <-ctx.Done(): + return + default: + } + + mbuf, err := d.rmrService.RecvMessage() + + if err != nil { + log.Printf("#Dispatcher.listenAndHandle - error receiving message: %s", err) + d.processResult.Stats.ReceivedErrorCount++ + continue + } + + _, ok := waitForRmrMessageType[mbuf.MType] + + if !ok { + log.Printf("#Dispatcher.listenAndHandle - Unexpected msg: %s", mbuf) + d.processResult.Stats.ReceivedUnexpectedCount++ + continue + } + + log.Printf("#Dispatcher.listenAndHandle - expected msg: %s", mbuf) + d.processResult.Stats.ReceivedExpectedCount++ + } +} + +func (d *Dispatcher) listenAndHandle(ctx context.Context, listenAndHandleWg *sync.WaitGroup, repeatCount int) { + + defer listenAndHandleWg.Done() + + if repeatCount == 0 { + d.listenAndHandleNoRepeat(ctx) + return + } + + d.listenAndHandleWithRepeat(ctx, repeatCount) +} + +func mergeConfigurationAndCommand(conf *models.JsonCommand, cmd *models.JsonCommand) { + nFields := reflect.Indirect(reflect.ValueOf(cmd)).NumField() + + for i := 0; i < nFields; i++ { + if fieldValue := reflect.Indirect(reflect.ValueOf(cmd)).Field(i); fieldValue.IsValid() { + switch fieldValue.Kind() { + case reflect.String: + if fieldValue.Len() > 0 { + reflect.Indirect(reflect.ValueOf(conf)).Field(i).Set(fieldValue) + } + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + if fieldValue.Int() != 0 { + reflect.Indirect(reflect.ValueOf(conf)).Field(i).Set(fieldValue) + } + case reflect.Bool: + if fieldValue.Bool() { + reflect.Indirect(reflect.ValueOf(conf)).Field(i).Set(fieldValue) + } + case reflect.Float64, reflect.Float32: + if fieldValue.Float() != 0 { + reflect.Indirect(reflect.ValueOf(conf)).Field(i).Set(fieldValue) + } + default: + reflect.Indirect(reflect.ValueOf(conf)).Field(i).Set(fieldValue) + } + } + } +} diff --git a/tools/xappmock/enums/command_action.go b/tools/xappmock/enums/command_action.go new file mode 100644 index 0000000..7e31239 --- /dev/null +++ b/tools/xappmock/enums/command_action.go @@ -0,0 +1,25 @@ +// +// Copyright 2019 AT&T Intellectual Property +// Copyright 2019 Nokia +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package enums + +type CommandAction string + +const ( + SendRmrMessage CommandAction = "send" + ReceiveRmrMessage CommandAction = "receive" +) diff --git a/tools/xapp_mock/frontend/configfile.go b/tools/xappmock/frontend/configfile.go similarity index 91% rename from tools/xapp_mock/frontend/configfile.go rename to tools/xappmock/frontend/configfile.go index f332a0c..509c1c7 100644 --- a/tools/xapp_mock/frontend/configfile.go +++ b/tools/xappmock/frontend/configfile.go @@ -24,7 +24,7 @@ import ( "strings" ) -func ProcessConfigurationFile(resourcesFolder, inputFolder, suffix string, processor func(data []byte) error) error { +func ProcessConfigurationFile(resourcesFolder, inputFolder, suffix string, processor func(data []byte) error) error { cwd, err := os.Getwd() if err != nil { return errors.New(err.Error()) diff --git a/tools/xapp_mock/frontend/jsonDecoder.go b/tools/xappmock/frontend/jsonDecoder.go similarity index 57% rename from tools/xapp_mock/frontend/jsonDecoder.go rename to tools/xappmock/frontend/jsonDecoder.go index 0609db2..3e60341 100644 --- a/tools/xapp_mock/frontend/jsonDecoder.go +++ b/tools/xappmock/frontend/jsonDecoder.go @@ -22,57 +22,31 @@ import ( "fmt" "github.com/pkg/errors" "io" + "xappmock/models" ) -const ( - SendRmrMessage = "send" - ReceiveRmrMessage = "receive" -) - - -type JsonCommand struct { - Id string - RmrMessageType string - TransactionId string - RanName string - RanIp string - RanPort int - PayloadHeader string - PackedPayload string - Payload string - Action string - WaitForRmrMessageType string -} - -// Id -> Command -var Configuration = make(map[string]*JsonCommand) -// Rmr Message Id -> Command -var WaitedForRmrMessageType = make(map[int]*JsonCommand) - -func JsonCommandDecoder(data []byte, processor func (*JsonCommand) error ) error { +func DecodeJsonCommand(data []byte) (*models.JsonCommand, error) { dec := json.NewDecoder(bytes.NewReader(data)) - var cmd JsonCommand + var cmd models.JsonCommand if err := dec.Decode(&cmd); err != nil && err != io.EOF { - return errors.New(err.Error()) - } - if err := processor (&cmd); err != nil { - return err + return nil, errors.New(err.Error()) } - return nil + + return &cmd, nil } -func JsonCommandsDecoder(data []byte, processor func (*JsonCommand) error ) error { +func JsonCommandsDecoder(data []byte, processor func(models.JsonCommand) error) error { dec := json.NewDecoder(bytes.NewReader(data)) for { - var commands []JsonCommand + var commands []models.JsonCommand if err := dec.Decode(&commands); err == io.EOF { break } else if err != nil { return errors.New(err.Error()) } for i, cmd := range commands { - if err := processor(&cmd); err != nil { - return errors.New(fmt.Sprintf("processing error at #%d, %s",i,err)) + if err := processor(cmd); err != nil { + return errors.New(fmt.Sprintf("processing error at #%d, %s", i, err)) } } } diff --git a/tools/xappmock/go.mod b/tools/xappmock/go.mod new file mode 100644 index 0000000..f870a4c --- /dev/null +++ b/tools/xappmock/go.mod @@ -0,0 +1,5 @@ +module xappmock + +go 1.12 + +require github.com/pkg/errors v0.8.1 diff --git a/tools/xappmock/go.sum b/tools/xappmock/go.sum new file mode 100644 index 0000000..f29ab35 --- /dev/null +++ b/tools/xappmock/go.sum @@ -0,0 +1,2 @@ +github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I= +github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= diff --git a/tools/xappmock/main/xappmock.go b/tools/xappmock/main/xappmock.go new file mode 100644 index 0000000..196d1e2 --- /dev/null +++ b/tools/xappmock/main/xappmock.go @@ -0,0 +1,102 @@ +// +// Copyright 2019 AT&T Intellectual Property +// Copyright 2019 Nokia +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +package main + +import ( + "context" + "flag" + "log" + "os" + "os/signal" + "strconv" + "time" + "xappmock/dispatcher" + "xappmock/frontend" + "xappmock/rmr" +) + +const ( + ENV_RMR_PORT = "RMR_PORT" + RMR_PORT_DEFAULT = 5001 +) + +var rmrService *rmr.Service + +func main() { + var rmrContext *rmr.Context + var rmrConfig = rmr.Config{Port: RMR_PORT_DEFAULT, MaxMsgSize: rmr.RMR_MAX_MSG_SIZE, MaxRetries: 10, Flags: 0} + + if port, err := strconv.ParseUint(os.Getenv(ENV_RMR_PORT), 10, 16); err == nil { + rmrConfig.Port = int(port) + } else { + log.Printf("#main - %s: %s, using default (%d).", ENV_RMR_PORT, err, RMR_PORT_DEFAULT) + } + + rmrService = rmr.NewService(rmrConfig, rmrContext) + dispatcherDesc := dispatcher.New(rmrService) + + /* Load configuration file*/ + err := frontend.ProcessConfigurationFile("resources", "conf", ".json", + func(data []byte) error { + return frontend.JsonCommandsDecoder(data, dispatcherDesc.JsonCommandsDecoderCB) + }) + + if err != nil { + log.Fatalf("#main - processing error: %s", err) + } + + log.Print("#main - xApp Mock is up and running...") + + flag.Parse() + cmd := flag.Arg(0) /*first remaining argument after flags have been processed*/ + + command, err := frontend.DecodeJsonCommand([]byte(cmd)) + + if err != nil { + log.Printf("#main - command decoding error: %s", err) + rmrService.CloseContext() + log.Print("#main - xApp Mock is down") + return + } + + c := make(chan os.Signal, 1) + signal.Notify(c, os.Interrupt) + ctx, cancel := context.WithCancel(context.Background()) + + go func() { + oscall := <-c + log.Printf("system call:%+v", oscall) + cancel() + rmrService.CloseContext() + }() + + processStartTime := time.Now() + dispatcherDesc.ProcessJsonCommand(ctx, command) + pr := dispatcherDesc.GetProcessResult() + + if pr.Err != nil { + log.Printf("#main - command processing Error: %s", err) + } + + processElapsedTimeInMs := float64(time.Since(processStartTime)) / float64(time.Millisecond) + + log.Printf("#main - processing (sending/receiving) messages took %.2f ms", processElapsedTimeInMs) + log.Printf("#main - process result: %s", pr) + + rmrService.CloseContext() // TODO: called twice + log.Print("#main - xApp Mock is down") +} diff --git a/tools/xappmock/models/json_command.go b/tools/xappmock/models/json_command.go new file mode 100644 index 0000000..beccbb2 --- /dev/null +++ b/tools/xappmock/models/json_command.go @@ -0,0 +1,35 @@ +// +// Copyright 2019 AT&T Intellectual Property +// Copyright 2019 Nokia +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package models + +type JsonCommand struct { + Id string + SendRmrMessageType string + TransactionId string + RanName string + Meid string + RanIp string + RanPort int + PayloadHeader string + PackedPayload string + Payload string + Action string + ReceiveRmrMessageType string + RepeatCount int + RepeatDelayInMs int +} diff --git a/tools/xappmock/models/process_result.go b/tools/xappmock/models/process_result.go new file mode 100644 index 0000000..eb9543f --- /dev/null +++ b/tools/xappmock/models/process_result.go @@ -0,0 +1,39 @@ +// +// Copyright 2019 AT&T Intellectual Property +// Copyright 2019 Nokia +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package models + +import "fmt" + +type ProcessStats struct { + SentCount int + SentErrorCount int + ReceivedExpectedCount int + ReceivedUnexpectedCount int + ReceivedErrorCount int +} + +type ProcessResult struct { + Stats ProcessStats + Err error +} + +func (pr ProcessResult) String() string { + return fmt.Sprintf("\nNumber of sent messages: %d\nNumber of send errors: %d\n" + + "Number of expected received messages: %d\nNumber of unexpected received messages: %d\n" + + "Number of receive errors: %d\n", pr.Stats.SentCount, pr.Stats.SentErrorCount, pr.Stats.ReceivedExpectedCount, pr.Stats.ReceivedUnexpectedCount, pr.Stats.ReceivedErrorCount) +} diff --git a/tools/xappmock/resources/conf/configuration.json b/tools/xappmock/resources/conf/configuration.json new file mode 100644 index 0000000..5b8eaf7 --- /dev/null +++ b/tools/xappmock/resources/conf/configuration.json @@ -0,0 +1,24 @@ +[ + { + "id": "RIC_X2_SETUP_REQ", + "sendRmrMessageType": "10060", + "transactionId": "e2e$", + "payloadHeader": "$ranIp|$ranPort|$ranName|#packedPayload|", + "packedPayload": "0006002a000002001500080013302300fffff000140017000001f700133023fffff0000000133023000000000001" + }, + { + "id": "RIC_ENB_CONF_UPDATE_ACK_positive", + "sendRmrMessageType": "10081", + "transactionId": "e2e$", + "packedPayload": "2025000a00000100f70003000000" + }, + { + "id": "RIC_SUBSCRIPTION_RESPONSE", + "receiveRmrMessageType": "12011", + "transactionId": "e2e$", + "packedPayload": "20c9001d000003ea7e000500abba0001ea6300020001ea6c000700ea6d40020000" + }, + { + "id": "RIC_X2_SETUP_RESPONSE" + } +] diff --git a/tools/xappmock/resources/router.txt b/tools/xappmock/resources/router.txt new file mode 100644 index 0000000..baf8eec --- /dev/null +++ b/tools/xappmock/resources/router.txt @@ -0,0 +1,24 @@ +newrt|start +rte|10060|10.0.2.15:38000 +rte|10360|10.0.2.15:38000 +rte|10070|10.0.2.15:38000 +rte|10071|10.0.2.15:3801 +rte|10061|10.0.2.15:3801 +rte|10361|10.0.2.15:3801 +rte|10062|10.0.2.15:3801 +rte|10362|10.0.2.15:3801 +rte|1080|10.0.2.15:3801 +rte|10020|10.0.2.15:5557 +rte|10370|10.0.2.15:3801 +rte|10371|10.0.2.15:38000 +rte|10372|10.0.2.15:38000 +rte|10080|10.0.2.15:3801 +rte|10081|10.0.2.15:38000 +rte|10082|10.0.2.15:38000 +rte|1100|10.0.2.15:3801 +rte|1090|10.0.2.15:38000 +rte|1200|10.0.2.15:4801 +rte|1210|10.0.2.15:4801 +rte|1220|10.0.2.15:4801 +rte|10090|10.0.2.15:38000 +newrt|end diff --git a/tools/xapp_mock/resp b/tools/xappmock/resp similarity index 100% rename from tools/xapp_mock/resp rename to tools/xappmock/resp diff --git a/tools/xapp_mock/rmr/rmrCgoApi.go b/tools/xappmock/rmr/rmrCgoApi.go similarity index 92% rename from tools/xapp_mock/rmr/rmrCgoApi.go rename to tools/xappmock/rmr/rmrCgoApi.go index 7686ea8..6580144 100644 --- a/tools/xapp_mock/rmr/rmrCgoApi.go +++ b/tools/xappmock/rmr/rmrCgoApi.go @@ -49,7 +49,7 @@ func (*Context) Init(port string, maxMsgSize int, maxRetries int, flags int) *Me func (ctx *Context) SendMsg(msg *MBuf) (*MBuf, error) { allocatedCMBuf, err := ctx.getAllocatedCRmrMBuf(msg, ctx.MaxMsgSize) - if err != nil{ + if err != nil { return nil, err } if state := allocatedCMBuf.state; state != RMR_OK { @@ -58,14 +58,14 @@ func (ctx *Context) SendMsg(msg *MBuf) (*MBuf, error) { } defer C.rmr_free_msg(allocatedCMBuf) - for i:=0; i < ctx.MaxRetries; i++ { + for i := 0; i < ctx.MaxRetries; i++ { currCMBuf := C.rmr_send_msg(ctx.RmrCtx, allocatedCMBuf) if state := currCMBuf.state; state != RMR_OK { if state != RMR_ERR_RETRY { errorMessage := fmt.Sprintf("#rmrCgoApi.SendMsg - Failed to send message. state: %v - %s", state, states[int(state)]) return nil, errors.New(errorMessage) } - time.Sleep(100*time.Millisecond) + time.Sleep(100 * time.Millisecond) continue } return convertToMBuf(currCMBuf) @@ -75,11 +75,11 @@ func (ctx *Context) SendMsg(msg *MBuf) (*MBuf, error) { } func (ctx *Context) RecvMsg() (*MBuf, error) { - allocatedCMBuf, err :=C.rmr_alloc_msg(ctx.RmrCtx, C.int(ctx.MaxMsgSize)) - if err != nil{ + allocatedCMBuf, err := C.rmr_alloc_msg(ctx.RmrCtx, C.int(ctx.MaxMsgSize)) + if err != nil { return nil, err } - if state := allocatedCMBuf.state;state != RMR_OK { + if state := allocatedCMBuf.state; state != RMR_OK { errorMessage := fmt.Sprintf("#rmrCgoApi.SendMsg - Failed to get allocated message. state: %v - %s", state, states[int(state)]) return nil, errors.New(errorMessage) } @@ -94,7 +94,6 @@ func (ctx *Context) RecvMsg() (*MBuf, error) { return convertToMBuf(currCMBuf) } - func (ctx *Context) IsReady() bool { return int(C.rmr_ready(ctx.RmrCtx)) != 0 } diff --git a/tools/xapp_mock/rmr/rmrCgoTypes.go b/tools/xappmock/rmr/rmrCgoTypes.go similarity index 97% rename from tools/xapp_mock/rmr/rmrCgoTypes.go rename to tools/xappmock/rmr/rmrCgoTypes.go index 54d4f8f..9f5ab7a 100644 --- a/tools/xapp_mock/rmr/rmrCgoTypes.go +++ b/tools/xappmock/rmr/rmrCgoTypes.go @@ -95,17 +95,15 @@ type MBuf struct { XAction []byte } - func (m MBuf) String() string { return fmt.Sprintf("{ MType: %d, Len: %d, Meid: %q, Xaction: %q, Payload: [%x] }", m.MType, m.Len, m.Meid, m.XAction, m.Payload) } - type Context struct { - MaxMsgSize int - MaxRetries int - Flags int - RmrCtx unsafe.Pointer + MaxMsgSize int + MaxRetries int + Flags int + RmrCtx unsafe.Pointer } type Messenger interface { diff --git a/tools/xapp_mock/rmr/rmrCgoUtils.go b/tools/xappmock/rmr/rmrCgoUtils.go similarity index 82% rename from tools/xapp_mock/rmr/rmrCgoUtils.go rename to tools/xappmock/rmr/rmrCgoUtils.go index 9b56785..cea9198 100644 --- a/tools/xapp_mock/rmr/rmrCgoUtils.go +++ b/tools/xappmock/rmr/rmrCgoUtils.go @@ -35,9 +35,9 @@ import ( Allocates an mBuf and initialize it with the content of C.rmr_mbuf_t. The xAction field is assigned a a value without trailing spaces. */ -func convertToMBuf( m *C.rmr_mbuf_t) (*MBuf, error) { - payloadArr := C.GoBytes(unsafe.Pointer(m.payload),C.int(m.len)) - xActionArr := C.GoBytes(unsafe.Pointer(m.xaction),C.int(RMR_MAX_XACTION_LEN)) +func convertToMBuf(m *C.rmr_mbuf_t) (*MBuf, error) { + payloadArr := C.GoBytes(unsafe.Pointer(m.payload), C.int(m.len)) + xActionArr := C.GoBytes(unsafe.Pointer(m.xaction), C.int(RMR_MAX_XACTION_LEN)) // Trim padding (space and 0) xActionStr := strings.TrimRight(string(xActionArr), "\040\000") @@ -54,7 +54,7 @@ func convertToMBuf( m *C.rmr_mbuf_t) (*MBuf, error) { meidBuf := make([]byte, RMR_MAX_MEID_LEN) if meidCstr := C.rmr_get_meid(m, (*C.uchar)(unsafe.Pointer(&meidBuf[0]))); meidCstr != nil { - mbuf.Meid = strings.TrimRight(string(meidBuf), "\000") + mbuf.Meid = strings.TrimRight(string(meidBuf), "\000") } return mbuf, nil @@ -64,9 +64,9 @@ func convertToMBuf( m *C.rmr_mbuf_t) (*MBuf, error) { Allocates an C.rmr_mbuf_t and initialize it with the content of mBuf. The xAction field is padded with trailing spaces upto capacity */ -func (ctx *Context) getAllocatedCRmrMBuf( mBuf *MBuf, maxMsgSize int) (cMBuf *C.rmr_mbuf_t, rc error) { +func (ctx *Context) getAllocatedCRmrMBuf(mBuf *MBuf, maxMsgSize int) (cMBuf *C.rmr_mbuf_t, rc error) { var xActionBuf [RMR_MAX_XACTION_LEN]byte - var meidBuf[RMR_MAX_MEID_LEN]byte + var meidBuf [RMR_MAX_MEID_LEN]byte cMBuf = C.rmr_alloc_msg(ctx.RmrCtx, C.int(maxMsgSize)) cMBuf.mtype = C.int(mBuf.MType) @@ -76,13 +76,13 @@ func (ctx *Context) getAllocatedCRmrMBuf( mBuf *MBuf, maxMsgSize int) (cMBuf *C. xActionLen := len(mBuf.XAction) copy(xActionBuf[:], mBuf.XAction) - for i:= xActionLen; i < RMR_MAX_XACTION_LEN; i++{ + for i := xActionLen; i < RMR_MAX_XACTION_LEN; i++ { xActionBuf[i] = '\040' //space } // Add padding copy(meidBuf[:], mBuf.Meid) - for i:= len(mBuf.Meid); i < RMR_MAX_MEID_LEN; i++{ + for i := len(mBuf.Meid); i < RMR_MAX_MEID_LEN; i++ { meidBuf[i] = 0 } @@ -98,19 +98,19 @@ func (ctx *Context) getAllocatedCRmrMBuf( mBuf *MBuf, maxMsgSize int) (cMBuf *C. return nil, errors.New(fmt.Sprintf("#rmrCgoUtils.getAllocatedCRmrMBuf - Failed to read xAction data to allocated RMR message buffer, %s", err)) } - len := C.rmr_bytes2meid(cMBuf, (*C.uchar)(unsafe.Pointer(&meidBuf[0])), C.int(RMR_MAX_XACTION_LEN)) + len := C.rmr_bytes2meid(cMBuf, (*C.uchar)(unsafe.Pointer(&meidBuf[0])), C.int(RMR_MAX_XACTION_LEN)) if int(len) != RMR_MAX_MEID_LEN { return nil, errors.New( "#rmrCgoUtils.getAllocatedCRmrMBuf - Failed to copy meid data to allocated RMR message buffer") } - return cMBuf,nil + return cMBuf, nil } func MessageIdToUint(id string) (msgId uint64, err error) { if len(id) == 0 { msgId, err = 0, nil - } else{ + } else { msgId, err = strconv.ParseUint(id, 10, 16) } return -} \ No newline at end of file +} diff --git a/tools/xapp_mock/rmr/rmrEndPoint.go b/tools/xappmock/rmr/rmrEndPoint.go similarity index 64% rename from tools/xapp_mock/rmr/rmrEndPoint.go rename to tools/xappmock/rmr/rmrEndPoint.go index fc599a5..fa9cceb 100644 --- a/tools/xapp_mock/rmr/rmrEndPoint.go +++ b/tools/xappmock/rmr/rmrEndPoint.go @@ -17,13 +17,13 @@ package rmr import ( - "../frontend" "log" "strconv" ) + // RmrService holds an instance of RMR messenger as well as its configuration type Service struct { - messenger *Messenger + messenger *Messenger } // NewRmrService instantiates a new Rmr service instance @@ -33,36 +33,18 @@ func NewService(rmrConfig Config, messenger Messenger) *Service { } } -func (r *Service) SendMessage(messageType int, msg []byte, transactionId []byte) (*MBuf, error){ - log.Printf( "SendMessage (type: %d, tid: %s, msg: %v", messageType, transactionId, msg) +func (r *Service) SendMessage(messageType int, meid string, msg []byte, transactionId []byte) (*MBuf, error) { + log.Printf("#rmr.Service.SendMessage - type: %d, tid: %s, msg: %v", messageType, transactionId, msg) mbuf := NewMBuf(messageType, len(msg), msg, transactionId) + mbuf.Meid = meid return (*r.messenger).SendMsg(mbuf) } -// ListenAndHandle waits for messages coming from rmr_rcv_msg and sends it to a designated message handler -func (r *Service) ListenAndHandle() error { - for { - mbuf, err := (*r.messenger).RecvMsg() - - if err != nil { - return err - } - - if _, ok := frontend.WaitedForRmrMessageType[mbuf.MType]; ok { - log.Printf( "ListenAndHandle Expected msg: %s", mbuf) - break - } else { - log.Printf( "ListenAndHandle Unexpected msg: %s", mbuf) - } - } - return nil +func (r *Service) RecvMessage() (*MBuf, error) { + return (*r.messenger).RecvMsg() } - func (r *Service) CloseContext() { (*r.messenger).Close() } - - - diff --git a/tools/xapp_mock/sender/jsonSender.go b/tools/xappmock/sender/jsonSender.go similarity index 75% rename from tools/xapp_mock/sender/jsonSender.go rename to tools/xappmock/sender/jsonSender.go index b68ee9d..e71f3bb 100644 --- a/tools/xapp_mock/sender/jsonSender.go +++ b/tools/xappmock/sender/jsonSender.go @@ -17,8 +17,6 @@ package sender import ( - "../frontend" - "../rmr" "fmt" "github.com/pkg/errors" "log" @@ -28,11 +26,13 @@ import ( "sync/atomic" "time" "unicode" + "xappmock/models" + "xappmock/rmr" ) var counter uint64 -func SendJsonRmrMessage(command frontend.JsonCommand /*the copy is modified locally*/, xAction *[]byte, r *rmr.Service) error { +func SendJsonRmrMessage(command models.JsonCommand /*the copy is modified locally*/, xAction *[]byte, r *rmr.Service) error { var payload []byte _, err := fmt.Sscanf(command.PackedPayload, "%x", &payload) if err != nil { @@ -44,11 +44,12 @@ func SendJsonRmrMessage(command frontend.JsonCommand /*the copy is modified loca command.TransactionId = string(*xAction) } command.PayloadHeader = expandPayloadHeader(command.PayloadHeader, &command) - rmrMsgId, err := rmr.MessageIdToUint(command.RmrMessageType) + log.Printf("#jsonSender.SendJsonRmrMessage - command payload header: %s", command.PayloadHeader) + rmrMsgId, err := rmr.MessageIdToUint(command.SendRmrMessageType) if err != nil { - return errors.New(fmt.Sprintf("invalid rmr message id: %s",command.WaitForRmrMessageType)) + return errors.New(fmt.Sprintf("invalid rmr message id: %s", command.SendRmrMessageType)) } - _, err = r.SendMessage(int(rmrMsgId), append([]byte(command.PayloadHeader), payload...), []byte(command.TransactionId)) + _, err = r.SendMessage(int(rmrMsgId), command.Meid, append([]byte(command.PayloadHeader), payload...), []byte(command.TransactionId)) return err } @@ -75,7 +76,7 @@ func expandTransactionId(id string) string { * Example: “payloadHeader”: “$ranIp|$ranPort|$ranName|#packedPayload|” */ -func expandPayloadHeader(header string, command *frontend.JsonCommand) string { +func expandPayloadHeader(header string, command *models.JsonCommand) string { var name strings.Builder var expandedHeader strings.Builder @@ -85,12 +86,17 @@ func expandPayloadHeader(header string, command *frontend.JsonCommand) string { if err != nil { break } + switch ch { case '$': for { - ch, err = r.ReadByte() //on error ch == 0 + ch, err = r.ReadByte() //on error ch == 0 if unicode.IsDigit(rune(ch)) || unicode.IsLetter(rune(ch)) { - name.WriteByte(ch) + if name.Len() == 0 { + name.WriteByte(byte(unicode.ToUpper(rune(ch)))) + } else { + name.WriteByte(ch) + } } else { if fieldValue := reflect.Indirect(reflect.ValueOf(command)).FieldByName(name.String()); fieldValue.IsValid() { switch fieldValue.Kind() { @@ -103,7 +109,7 @@ func expandPayloadHeader(header string, command *frontend.JsonCommand) string { case reflect.Float64, reflect.Float32: expandedHeader.WriteString(fmt.Sprintf("%g", fieldValue.Float())) default: - log.Fatalf("invalid type for $%s, value must be a string, an int, a bool or a float", name.String()) + log.Fatalf("#jsonSender.expandPayloadHeader - invalid type for $%s, value must be a string, an int, a bool or a float", name.String()) } } name.Reset() @@ -112,15 +118,19 @@ func expandPayloadHeader(header string, command *frontend.JsonCommand) string { } case '#': for { - ch, err = r.ReadByte() //on error ch == 0 + ch, err = r.ReadByte() //on error ch == 0 if unicode.IsDigit(rune(ch)) || unicode.IsLetter(rune(ch)) { - name.WriteByte(ch) + if name.Len() == 0 { + name.WriteByte(byte(unicode.ToUpper(rune(ch)))) + } else { + name.WriteByte(ch) + } } else { if fieldValue := reflect.Indirect(reflect.ValueOf(command)).FieldByName(name.String()); fieldValue.IsValid() { if fieldValue.Kind() == reflect.String { expandedHeader.WriteString(strconv.FormatInt(int64(len(fieldValue.String())), 10)) } else { - log.Fatalf("invalid type for #%s, value must be a string", name.String()) + log.Fatalf("#jsonSender.expandPayloadHeader - invalid type for #%s, value must be a string", name.String()) } } name.Reset() @@ -142,5 +152,5 @@ func incAndGetCounter() uint64 { } func init() { - counter = uint64(time.Now().Second()) + counter = uint64(time.Now().Unix() - 1572000000) } -- 2.16.6