ccce4a842e08ca8d0c320808aee4ce8eac292c22
[ric-plt/e2mgr.git] / E2Manager / handlers / rmrmsghandlers / ric_service_update_handler.go
1 //
2 // Copyright (c) 2020 Samsung Electronics Co., Ltd. All Rights Reserved.
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 //      http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15
16 //  This source code is part of the near-RT RIC (RAN Intelligent Controller)
17 //  platform project (RICP).
18
19 package rmrmsghandlers
20
21 import (
22         "bytes"
23         "e2mgr/utils"
24         "e2mgr/logger"
25         "e2mgr/managers"
26         "e2mgr/models"
27         "e2mgr/rmrCgo"
28         "e2mgr/services"
29         "e2mgr/services/rmrsender"
30         "encoding/xml"
31         "fmt"
32         "gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/common"
33         "gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/entities"
34 )
35
36 //type FunctionChange int
37
38 const (
39         RAN_FUNCTIONS_ADDED int = 10 + iota
40         RAN_FUNCTIONS_DELETED
41         RAN_FUNCTIONS_MODIFIED
42 )
43
44 type functionDetails struct {
45         functionChange       int
46         functionId           uint32
47         functionDefinition   string
48         functionRevision     uint32
49 }
50
51 type RicServiceUpdateHandler struct {
52         logger                *logger.Logger
53     rmrSender             *rmrsender.RmrSender
54         rNibDataService       services.RNibDataService
55         ranListManager        managers.RanListManager
56 }
57
58 func NewRicServiceUpdateHandler(logger *logger.Logger, rmrSender *rmrsender.RmrSender, rNibDataService services.RNibDataService, ranListManager managers.RanListManager) *RicServiceUpdateHandler {
59         return &RicServiceUpdateHandler {
60                 logger:                logger,
61                 rmrSender:             rmrSender,
62                 rNibDataService:       rNibDataService,
63                                 ranListManager:            ranListManager,
64         }
65 }
66
67 func (h *RicServiceUpdateHandler) Handle(request *models.NotificationRequest) {
68         ranName := request.RanName
69         h.logger.Infof("#RicServiceUpdateHandler.Handle - RAN name: %s - received RIC_SERVICE_UPDATE. Payload: %s", ranName, request.Payload)
70
71         nodebInfo, err := h.rNibDataService.GetNodeb(ranName)
72          if err != nil {
73                  _, ok := err.(*common.ResourceNotFoundError)
74                 if !ok {
75                         h.logger.Errorf("#RicServiceUpdateHandler.Handle - failed to get nodeB entity for ran name: %v due to RNIB Error: %s", ranName, err)
76                 } else{
77                          h.logger.Errorf("#RicServiceUpdateHandler.Handle - nobeB entity of RanName:%s absent in RNIB. Error: %s", ranName, err)
78                  }
79                  return
80         }
81
82         ricServiceUpdate, err := h.parseSetupRequest(request.Payload)
83         if err != nil {
84                 h.logger.Errorf(err.Error())
85                 return
86         }
87         h.logger.Infof("#RicServiceUpdateHandler.Handle - RIC_SERVICE_UPDATE has been parsed successfully %+v", ricServiceUpdate)
88
89         ackFunctionIds := h.updateFunctions(ricServiceUpdate.E2APPDU.InitiatingMessage.Value.RICServiceUpdate.ProtocolIEs.RICServiceUpdateIEs, nodebInfo)
90         if len(ricServiceUpdate.E2APPDU.InitiatingMessage.Value.RICServiceUpdate.ProtocolIEs.RICServiceUpdateIEs) != 0 {
91                 err = h.rNibDataService.UpdateNodebInfoAndPublish(nodebInfo)
92                 if err != nil {
93                         h.logger.Errorf("#RicServiceUpdateHandler.Handle - RAN name: %s - Failed at UpdateNodebInfoAndPublish. error: %s", nodebInfo.RanName, err)
94                         return
95                 }
96         }
97
98         oldNbIdentity, newNbIdentity := h.ranListManager.UpdateHealthcheckTimeStampReceived(nodebInfo.RanName)
99         err = h.ranListManager.UpdateNbIdentities(nodebInfo.NodeType, []*entities.NbIdentity{oldNbIdentity}, []*entities.NbIdentity{newNbIdentity})
100         if err != nil {
101                 h.logger.Errorf("#RicServiceUpdate.Handle - failed to Update NbIdentities: %s", err)
102                 return
103         }
104
105         updateAck := models.NewServiceUpdateAck(ackFunctionIds)
106         err = h.sendUpdateAck(updateAck, nodebInfo, request)
107         if err != nil {
108                 h.logger.Errorf("#RicServiceUpdate.Handle - failed to send RIC_SERVICE_UPDATE_ACK message to RMR: %s", err)
109                 return
110         }
111
112         h.logger.Infof("#RicServiceUpdate.Handle - Completed successfully")
113 }
114
115 func (h *RicServiceUpdateHandler) sendUpdateAck(updateAck models.RicServiceUpdateAckE2APPDU, nodebInfo *entities.NodebInfo, request *models.NotificationRequest) error {
116         payLoad, err := xml.Marshal(updateAck)
117         if err != nil {
118                 h.logger.Errorf("#RicServiceUpdate.sendUpdateAck - RAN name: %s - Error marshalling RIC_SERVICE_UPDATE_ACK. Payload: %s", nodebInfo.RanName, payLoad)
119         }
120
121         toReplaceTags := []string{"reject", "ignore", "procedureCode", "id", "RANfunctionID-Item", "RANfunctionsID-List"}
122         payLoad = utils.ReplaceEmptyTagsWithSelfClosing(payLoad,toReplaceTags)
123
124         h.logger.Infof("#RicServiceUpdate.sendUpdateAck - Sending RIC_SERVICE_UPDATE_ACK to RAN name: %s with payload %s",nodebInfo.RanName, payLoad)
125         msg := models.NewRmrMessage(rmrCgo.RIC_SERVICE_UPDATE_ACK, nodebInfo.RanName, payLoad, request.TransactionId, request.GetMsgSrc())
126         err = h.rmrSender.Send(msg)
127         return err
128 }
129
130 func (h *RicServiceUpdateHandler) updateFunctions(RICServiceUpdateIEs []models.RICServiceUpdateIEs,nodebInfo *entities.NodebInfo) []models.RicServiceAckRANFunctionIDItem {
131         ranFunctions := nodebInfo.GetGnb().RanFunctions
132         RanFIdtoIdxMap := make(map[uint32]int)
133         var acceptedFunctionIds []models.RicServiceAckRANFunctionIDItem
134         functionsToBeDeleted := make(map[int]bool)
135
136         for index, ranFunction := range ranFunctions {
137                 RanFIdtoIdxMap[ranFunction.RanFunctionId] = index
138         }
139
140         for _, ricServiceUpdateIE := range RICServiceUpdateIEs {
141                 functionDetails, err := h.getFunctionDetails(ricServiceUpdateIE)
142                 if err != nil {
143                         h.logger.Errorf("#RicServiceUpdate.updateFunctions- GetFunctionDetails returned err: %s", err)
144                 }
145
146                 for _, functionDetail := range functionDetails {
147                         functionChange, functionId, functionDefinition, functionRevision := functionDetail.functionChange,
148                         functionDetail.functionId, functionDetail.functionDefinition, functionDetail.functionRevision
149                         ranFIndex, ok := RanFIdtoIdxMap[functionId]
150                         if !ok {
151                                 switch functionChange {
152                                 case RAN_FUNCTIONS_ADDED,RAN_FUNCTIONS_MODIFIED :
153                                         ranFunctions = append(ranFunctions, &entities.RanFunction{RanFunctionId:functionId,
154                                                 RanFunctionDefinition:functionDefinition, RanFunctionRevision:functionRevision})
155                                 case RAN_FUNCTIONS_DELETED:
156                                         //Do nothing
157                                 }
158                         } else {
159                                 switch functionChange {
160                                 case RAN_FUNCTIONS_ADDED, RAN_FUNCTIONS_MODIFIED:
161                                         ranFunctions[ranFIndex].RanFunctionDefinition = functionDefinition
162                                         ranFunctions[ranFIndex].RanFunctionRevision = functionRevision
163                                 case RAN_FUNCTIONS_DELETED:
164                                         functionsToBeDeleted[ranFIndex] = true
165                                 }
166                         }
167                         serviceupdateAckFunctionId := models.RicServiceAckRANFunctionIDItem{RanFunctionID:functionId, RanFunctionRevision:functionRevision}
168                         acceptedFunctionIds = append(acceptedFunctionIds, serviceupdateAckFunctionId)
169                 }
170         }
171         finalranFunctions := h.remove(ranFunctions, functionsToBeDeleted)
172         nodebInfo.GetGnb().RanFunctions = finalranFunctions
173         return acceptedFunctionIds
174 }
175
176 func (h *RicServiceUpdateHandler) remove(ranFunctions []*entities.RanFunction, functionsToBeDeleted map[int]bool) []*entities.RanFunction {
177         if len(functionsToBeDeleted) == 0 {
178                 return ranFunctions
179         }
180         var finalranFunctions []*entities.RanFunction
181         for i := 0; i < len(ranFunctions); i++ {
182                 _, ok := functionsToBeDeleted[i]
183                 if !ok {
184                         finalranFunctions = append(finalranFunctions, ranFunctions[i])
185                 }
186         }
187         return finalranFunctions
188 }
189
190 func (h *RicServiceUpdateHandler) getFunctionDetails(ricServiceUpdateIE models.RICServiceUpdateIEs) ([]functionDetails , error) {
191         functionChange := ricServiceUpdateIE.ID
192         switch functionChange{
193                 case RAN_FUNCTIONS_ADDED, RAN_FUNCTIONS_MODIFIED:
194                         return h.getFunctionsAddedModifiedHandler(ricServiceUpdateIE)
195                 case RAN_FUNCTIONS_DELETED:
196                         return h.getFunctionsDeleteHandler(ricServiceUpdateIE)
197                 default:
198                         return nil, common.NewInternalError(fmt.Errorf("#RicServiceUpdate.getFunctionDetails - Unknown change type %v", functionChange))
199         }
200         return nil, common.NewInternalError(fmt.Errorf("#RicServiceUpdate.getFunctionDetails - Internal Error"))
201 }
202
203 func (h *RicServiceUpdateHandler) getFunctionsAddedModifiedHandler(ricServiceUpdateIE models.RICServiceUpdateIEs) ([]functionDetails , error){
204         functionChange := ricServiceUpdateIE.ID
205         ranFunctionsIEList := ricServiceUpdateIE.Value.RANfunctionsList.RANfunctionsItemProtocolIESingleContainer
206         if len(ranFunctionsIEList) ==0 {
207                 return nil, common.NewInternalError(fmt.Errorf("#RicServiceUpdate.getFunctionDetails - function change type is %v but Functions list is empty", functionChange))
208         }
209
210         functionDetailsList := make([]functionDetails, len(ranFunctionsIEList))
211         for index, ranFunctionIE := range ranFunctionsIEList {
212                 ranFunction := ranFunctionIE.Value.RANfunctionItem
213                 functionDetailsList[index] = functionDetails{functionChange:functionChange, functionId:ranFunction.RanFunctionID,
214                         functionDefinition:ranFunction.RanFunctionDefinition, functionRevision:ranFunction.RanFunctionRevision}
215         }
216         return functionDetailsList, nil
217 }
218
219 func (h *RicServiceUpdateHandler) getFunctionsDeleteHandler(ricServiceUpdateIE models.RICServiceUpdateIEs) ([]functionDetails , error){
220         functionChange := ricServiceUpdateIE.ID
221         ranFunctionIdIEsList := ricServiceUpdateIE.Value.RANfunctionsIDList.RANfunctionsItemIDProtocolIESingleContainer
222         if len(ranFunctionIdIEsList) == 0 {
223                 return nil, common.NewInternalError(fmt.Errorf("#RicServiceUpdate.getFunctionDetails - function change type is %v but FunctionIds list is empty", functionChange))
224         }
225
226         functionDetailsList := make([]functionDetails, len(ranFunctionIdIEsList))
227         for index, ranFunctionIdIE := range ranFunctionIdIEsList {
228                 ranFunctionId := ranFunctionIdIE.Value.RANfunctionIDItem
229                 functionDetailsList[index] = functionDetails{functionChange:functionChange, functionId:ranFunctionId.RanFunctionID,
230                         functionDefinition:"", functionRevision:ranFunctionId.RanFunctionRevision}
231         }
232         return functionDetailsList, nil
233 }
234
235 func (h *RicServiceUpdateHandler) parseSetupRequest(payload []byte) (*models.RICServiceUpdateMessage, error) {
236         pipInd := bytes.IndexByte(payload, '|')
237         if pipInd < 0 {
238                 return nil, common.NewInternalError(fmt.Errorf("#RicServiceUpdateHandler.parseSetupRequest - Error parsing RIC SERVICE UPDATE failed extract Payload: no | separator found"))
239         }
240
241         ricServiceUpdate := &models.RICServiceUpdateMessage{}
242         err := xml.Unmarshal(utils.NormalizeXml(payload[pipInd+1:]), &ricServiceUpdate.E2APPDU)
243         if err != nil {
244                 return nil, common.NewInternalError(fmt.Errorf("#RicServiceUpdateHandler.parseSetupRequest - Error unmarshalling RIC SERVICE UPDATE payload: %x", payload))
245         }
246         return ricServiceUpdate, nil
247 }