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
+++ /dev/null
-##############################################################################
-#
-# 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 <ENDCConfigurationUpdate>
- ${ConfigurationAfterStrip}= Strip String ${Configuration}
- Should Be Equal ${ConfigurationAfterStrip} <ENDCConfigurationUpdate>
-
-Verify logs - Confiugration update - End Tag Get
- ${ConfigurationEnd}= Grep File ./gnb.log </ENDCConfigurationUpdate>
- ${ConfigurationEndAfterStrip}= Strip String ${ConfigurationEnd}
- Should Be Equal ${ConfigurationEndAfterStrip} </ENDCConfigurationUpdate>
-
-Verify logs - Confiugration update - Ack Tag Begin
- ${ConfigurationAck}= Grep File ./gnb.log <ENDCConfigurationUpdateAcknowledge>
- ${ConfigurationAckAfter}= Strip String ${ConfigurationAck}
- Should Be Equal ${ConfigurationAckAfter} <ENDCConfigurationUpdateAcknowledge>
-
-Verify logs - Confiugration update - Ack Tag End
- ${ConfigurationAckEnd}= Grep File ./gnb.log </ENDCConfigurationUpdateAcknowledge>
- ${ConfigurationAckEndAfterStrip}= Strip String ${ConfigurationAckEnd}
- Should Be Equal ${ConfigurationAckEndAfterStrip} </ENDCConfigurationUpdateAcknowledge>
-
-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
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 ***
Remove log files
Save logs
-
-
+Verify logs - Confiugration update - Begin Tag Get
+ ${Configuration}= Grep File ./${gnb_log_filename} <ENDCConfigurationUpdate>
+ ${ConfigurationAfterStrip}= Strip String ${Configuration}
+ Should Be Equal ${ConfigurationAfterStrip} <ENDCConfigurationUpdate>
+
+Verify logs - Confiugration update - End Tag Get
+ ${ConfigurationEnd}= Grep File ./${gnb_log_filename} </ENDCConfigurationUpdate>
+ ${ConfigurationEndAfterStrip}= Strip String ${ConfigurationEnd}
+ Should Be Equal ${ConfigurationEndAfterStrip} </ENDCConfigurationUpdate>
+
+Verify logs - Confiugration update - Ack Tag Begin
+ ${ConfigurationAck}= Grep File ./${gnb_log_filename} <ENDCConfigurationUpdateAcknowledge>
+ ${ConfigurationAckAfter}= Strip String ${ConfigurationAck}
+ Should Be Equal ${ConfigurationAckAfter} <ENDCConfigurationUpdateAcknowledge>
+
+Verify logs - Confiugration update - Ack Tag End
+ ${ConfigurationAckEnd}= Grep File ./${gnb_log_filename} </ENDCConfigurationUpdateAcknowledge>
+ ${ConfigurationAckEndAfterStrip}= Strip String ${ConfigurationAckEnd}
+ Should Be Equal ${ConfigurationAckEndAfterStrip} </ENDCConfigurationUpdateAcknowledge>
+
+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
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
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
+++ /dev/null
-##############################################################################
-#
-# 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
Verfiy Disconnected ConnectionStatus
- Sleep 1s
+ Sleep 10s
GET /v1/nodeb/test1
Integer response status 200
String response body ranName test1
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
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}
Sleep 1s
Run ${Save_sim_log}
Run ${Save_e2mgr_log}
+ Run ${Save_e2t_log}
Run ${Save_rsm_log}
Run ${Save_e2adapter_log}
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}
${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
${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
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}
Library OperatingSystem
Library Collections
Library REST ${url}
+Resource ../Resource/scripts_variables.robot
+Library String
+Library Process
+Library ../Scripts/find_rmr_message.py
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
+++ /dev/null
-##############################################################################
-#
-# 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
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 ***
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}
+
+++ /dev/null
-##############################################################################
-#
-# 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
# 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
import (
"e2mgr/configuration"
"e2mgr/controllers"
- "e2mgr/converters"
"e2mgr/httpserver"
"e2mgr/logger"
"e2mgr/managers"
"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)
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)
}
+
+
"e2mgr/mocks"
"e2mgr/models"
"e2mgr/providers/httpmsghandlerprovider"
- "e2mgr/rNibWriter"
"e2mgr/rmrCgo"
"e2mgr/services"
"e2mgr/services/rmrsender"
"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"
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)
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)
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)
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()
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()
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)
}
"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"
}
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
}
// #include <x2setup_response_wrapper.h>
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{}
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
}
package converters
import (
- "e2mgr/e2pdus"
"e2mgr/logger"
"fmt"
"gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/entities"
/**** 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) {
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 {
// #include <x2setup_response_wrapper.h>
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"
)
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)}
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))
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)}
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
}
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))))
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 {
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 {
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
}
package converters
import (
- "e2mgr/e2pdus"
"e2mgr/logger"
"fmt"
"gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/entities"
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) {
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 {
--- /dev/null
+#----- 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
+
--- /dev/null
+/*******************************************************************************
+ *
+ * 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 <configuration_update_wrapper.h>
+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)
+ }
+}
--- /dev/null
+/*******************************************************************************
+ *
+ * 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
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 {
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
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=
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=
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=
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=
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=
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=
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=
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=
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=
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=
"e2mgr/e2managererrors"
"e2mgr/logger"
"e2mgr/mocks"
- "e2mgr/rNibWriter"
"e2mgr/rmrCgo"
"e2mgr/services"
"e2mgr/services/rmrsender"
"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"
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
}
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)
}
"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"
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
}
"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"
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
}
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"
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)
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)
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)
"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"
)
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)
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)
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}
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}
+//
+// 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 (
"e2mgr/managers"
"e2mgr/mocks"
"e2mgr/models"
- "e2mgr/rNibWriter"
"e2mgr/rmrCgo"
"e2mgr/services"
"e2mgr/services/rmrsender"
"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"
)
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)
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
+//
+// 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"
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
}
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)
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 {
package rmrmsghandlers
-// #cgo CFLAGS: -I../../asn1codec/inc/ -I../../asn1codec/e2ap_engine/
-// #cgo LDFLAGS: -L ../../asn1codec/lib/ -L../../asn1codec/e2ap_engine/ -le2ap_codec -lasncodec
-// #include <asn1codec_utils.h>
-// #include <configuration_update_wrapper.h>
import "C"
import (
"e2mgr/converters"
"e2mgr/models"
"e2mgr/rmrCgo"
"e2mgr/services/rmrsender"
- "unsafe"
+ "e2mgr/utils"
)
type EndcConfigurationUpdateHandler struct {
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))
}
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)
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)
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))
-}
"e2mgr/managers"
"e2mgr/mocks"
"e2mgr/models"
- "e2mgr/rNibWriter"
"e2mgr/rmrCgo"
"e2mgr/services"
"e2mgr/services/rmrsender"
"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"
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)
}
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) {
}
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,
}
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,
}
package rmrmsghandlers
-// #cgo CFLAGS: -I../../asn1codec/inc/ -I../../asn1codec/e2ap_engine/
-// #cgo LDFLAGS: -L ../../asn1codec/lib/ -L../../asn1codec/e2ap_engine/ -le2ap_codec -lasncodec
-// #include <asn1codec_utils.h>
-// #include <x2reset_response_wrapper.h>
-import "C"
import (
"e2mgr/e2pdus"
"e2mgr/enums"
"e2mgr/services"
"e2mgr/services/rmrsender"
"e2mgr/utils"
- "fmt"
"gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/entities"
- "unsafe"
)
type X2ResetRequestNotificationHandler struct {
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
-}
"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"
)
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)
}
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)
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
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)
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{}
package rmrmsghandlers
-// #cgo CFLAGS: -I../../asn1codec/inc/ -I../../asn1codec/e2ap_engine/
-// #cgo LDFLAGS: -L ../../asn1codec/lib/ -L../../asn1codec/e2ap_engine/ -le2ap_codec -lasncodec
-// #include <asn1codec_utils.h>
-import "C"
import (
"e2mgr/converters"
"e2mgr/enums"
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
"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"
)
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)
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)
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)
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)
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)
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)
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")
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)
package rmrmsghandlers
-// #cgo CFLAGS: -I../../asn1codec/inc/ -I../../asn1codec/e2ap_engine/
-// #cgo LDFLAGS: -L ../../asn1codec/lib/ -L../../asn1codec/e2ap_engine/ -le2ap_codec -lasncodec
-// #include <asn1codec_utils.h>
-// #include <configuration_update_wrapper.h>
import "C"
import (
"e2mgr/converters"
"e2mgr/models"
"e2mgr/rmrCgo"
"e2mgr/services/rmrsender"
- "unsafe"
+ "e2mgr/utils"
)
type X2EnbConfigurationUpdateHandler struct {
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))
}
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)
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)
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)
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) {
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) {
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
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)
}
err = log.Sync()
assert.Nil(t, err)
-
+
os.Stdout = old
logFile, err = os.Open("./loggerTest.txt")
if err != nil{
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)
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 {
s,_= buf.ReadString('\n')
}
return entryNum == 1
-}
+}
\ No newline at end of file
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)
--- /dev/null
+//
+// 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
+}
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)
--- /dev/null
+//
+// 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
+}
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
}
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"
)
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
}
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
"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"
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
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)
}
}
// 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)
"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"
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
}
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)
}
--- /dev/null
+//
+// 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
+}
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){
// limitations under the License.
//
-package models
+package models_test
import (
"e2mgr/logger"
+ "e2mgr/models"
"e2mgr/tests"
"encoding/hex"
"github.com/stretchr/testify/assert"
)
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())
}
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
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),
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
-}
"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"
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)
package rmrmsghandlerprovider
import (
+ "e2mgr/configuration"
"e2mgr/converters"
"e2mgr/handlers/rmrmsghandlers"
"e2mgr/logger"
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]
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)
+}
"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"
* 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)
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 {
}
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 {
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
"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
}
/*
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)
return rNibErr
}
}
- err = (*w.sdl).Set(pairs)
+ err = w.sdl.Set(pairs)
if err != nil {
return common.NewInternalError(err)
}
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)
}
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)
}
/*
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())
pairs = append(pairs, nodebIdKey, data)
}
- err = (*w.sdl).Set(pairs)
+ err = w.sdl.Set(pairs)
if err != nil {
return common.NewInternalError(err)
/*
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)
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)
}
/*
-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) {
"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}
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 {
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)
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
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
}
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
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
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
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)
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)
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)
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)
}
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)
}
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{}
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)
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
"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")
// 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) {
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
// 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)
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
+}
}
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()
}
--- /dev/null
+newrt|start
+rte|1|127.0.0.1:3801
+newrt|end
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,
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)
}
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"
)
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)
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)
}
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,
}
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)
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)
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)
"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"
)
}
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,
}
}
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
})
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
})
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
})
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
})
var nodeIds []*entities.NbIdentity = nil
err := w.retry("GetListNodebIds", func() (err error) {
- nodeIds, err = w.rnibReaderProvider().GetListNodebIds()
+ nodeIds, err = w.rnibReader.GetListNodebIds()
return
})
func (w *rNibDataService) PingRnib() bool {
err := w.retry("GetListNodebIds", func() (err error) {
- _, err = w.rnibReaderProvider().GetListNodebIds()
+ _, err = w.rnibReader.GetListNodebIds()
return
})
}
}
-
func isRnibConnectionError(err error) bool {
internalErr, ok := err.(*common.InternalError)
if !ok {
"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"
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
const (
MaxMsgSize int = 4096
- Port int = 5555
+ Port int = 3801
Flags int = 0
MessageType int = 1001
RanPort uint16 = 879
--- /dev/null
+//
+// 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}
+}
+
+
+++ /dev/null
-[
- {“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" }
-]
+++ /dev/null
-//
-// 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
+++ /dev/null
-newrt|start
-rte|1001|10.0.2.15:38000
-rte|2002|10.0.2.15:3801
-newrt|end
#
##############################################################################
-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
--- /dev/null
+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)
+ }
+ }
+ }
+}
--- /dev/null
+//
+// 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"
+)
"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())
"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))
}
}
}
--- /dev/null
+module xappmock
+
+go 1.12
+
+require github.com/pkg/errors v0.8.1
--- /dev/null
+github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I=
+github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
--- /dev/null
+//
+// 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")
+}
--- /dev/null
+//
+// 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
+}
--- /dev/null
+//
+// 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)
+}
--- /dev/null
+[
+ {
+ "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"
+ }
+]
--- /dev/null
+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
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 {
}
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)
}
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)
}
return convertToMBuf(currCMBuf)
}
-
func (ctx *Context) IsReady() bool {
return int(C.rmr_ready(ctx.RmrCtx)) != 0
}
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 {
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")
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
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)
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
}
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
+}
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
}
}
-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()
}
-
-
-
package sender
import (
- "../frontend"
- "../rmr"
"fmt"
"github.com/pkg/errors"
"log"
"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 {
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
}
* 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
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() {
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()
}
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()
}
func init() {
- counter = uint64(time.Now().Second())
+ counter = uint64(time.Now().Unix() - 1572000000)
}