[RIC-571] Add Automation tests + bug fix in Setup of existing eNB flow
[ric-plt/e2mgr.git] / E2Manager / handlers / rmrmsghandlers / e2_setup_request_notification_handler.go
1 //
2 // Copyright 2019 AT&T Intellectual Property
3 // Copyright 2019 Nokia
4 //
5 // Licensed under the Apache License, Version 2.0 (the "License");
6 // you may not use this file except in compliance with the License.
7 // You may obtain a copy of the License at
8 //
9 //      http://www.apache.org/licenses/LICENSE-2.0
10 //
11 // Unless required by applicable law or agreed to in writing, software
12 // distributed under the License is distributed on an "AS IS" BASIS,
13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 // See the License for the specific language governing permissions and
15 // limitations under the License.
16
17 //  This source code is part of the near-RT RIC (RAN Intelligent Controller)
18 //  platform project (RICP).
19
20 package rmrmsghandlers
21
22 import (
23         "bytes"
24         "e2mgr/configuration"
25         "e2mgr/e2managererrors"
26         "e2mgr/logger"
27         "e2mgr/managers"
28         "e2mgr/models"
29         "e2mgr/rmrCgo"
30         "e2mgr/services"
31         "e2mgr/services/rmrsender"
32         "encoding/xml"
33         "errors"
34         "fmt"
35         "gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/common"
36         "gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/entities"
37         "strconv"
38         "strings"
39 )
40
41 var (
42         emptyTagsToReplaceToSelfClosingTags = []string{"reject", "ignore", "transport-resource-unavailable", "om-intervention", "request-id-unknown",
43                 "v60s", "v20s", "v10s", "v5s", "v2s", "v1s"}
44         gnbTypesMap = map[string]entities.GnbType{
45                 "gnb":    entities.GnbType_GNB,
46                 "en_gnb": entities.GnbType_EN_GNB,
47         }
48         enbTypesMap = map[string]entities.EnbType{
49                 "enB_macro":         entities.EnbType_MACRO_ENB,
50                 "enB_home":          entities.EnbType_HOME_ENB,
51                 "enB_shortmacro":    entities.EnbType_SHORT_MACRO_ENB,
52                 "enB_longmacro":     entities.EnbType_LONG_MACRO_ENB,
53                 "ng_enB_macro":      entities.EnbType_MACRO_NG_ENB,
54                 "ng_enB_shortmacro": entities.EnbType_SHORT_MACRO_NG_ENB,
55                 "ng_enB_longmacro":  entities.EnbType_LONG_MACRO_NG_ENB,
56         }
57 )
58
59 type E2SetupRequestNotificationHandler struct {
60         logger                        *logger.Logger
61         config                        *configuration.Configuration
62         e2tInstancesManager           managers.IE2TInstancesManager
63         rmrSender                     *rmrsender.RmrSender
64         rNibDataService               services.RNibDataService
65         e2tAssociationManager         *managers.E2TAssociationManager
66         ranConnectStatusChangeManager managers.IRanConnectStatusChangeManager
67         ranListManager                managers.RanListManager
68 }
69
70 func NewE2SetupRequestNotificationHandler(logger *logger.Logger, config *configuration.Configuration, e2tInstancesManager managers.IE2TInstancesManager, rmrSender *rmrsender.RmrSender, rNibDataService services.RNibDataService, e2tAssociationManager *managers.E2TAssociationManager, ranConnectStatusChangeManager managers.IRanConnectStatusChangeManager, ranListManager managers.RanListManager) *E2SetupRequestNotificationHandler {
71         return &E2SetupRequestNotificationHandler{
72                 logger:                        logger,
73                 config:                        config,
74                 e2tInstancesManager:           e2tInstancesManager,
75                 rmrSender:                     rmrSender,
76                 rNibDataService:               rNibDataService,
77                 e2tAssociationManager:         e2tAssociationManager,
78                 ranConnectStatusChangeManager: ranConnectStatusChangeManager,
79                 ranListManager:                ranListManager,
80         }
81 }
82
83 func (h *E2SetupRequestNotificationHandler) Handle(request *models.NotificationRequest) {
84         ranName := request.RanName
85         h.logger.Infof("#E2SetupRequestNotificationHandler.Handle - RAN name: %s - received E2_SETUP_REQUEST. Payload: %x", ranName, request.Payload)
86
87         generalConfiguration, err := h.rNibDataService.GetGeneralConfiguration()
88
89         if err != nil {
90                 h.logger.Errorf("#E2SetupRequestNotificationHandler.Handle - Failed retrieving e2m general configuration - quitting e2 setup flow. error: %s", err)
91                 return
92         }
93
94         h.logger.Infof("#E2SetupRequestNotificationHandler.Handle - got general configuration from rnib - enableRic: %t", generalConfiguration.EnableRic)
95
96         if !generalConfiguration.EnableRic {
97                 cause := models.Cause{Misc: &models.CauseMisc{OmIntervention: &struct{}{}}}
98                 h.handleUnsuccessfulResponse(ranName, request, cause)
99                 return
100         }
101
102         setupRequest, e2tIpAddress, err := h.parseSetupRequest(request.Payload)
103         if err != nil {
104                 h.logger.Errorf(err.Error())
105                 return
106         }
107
108         h.logger.Infof("#E2SetupRequestNotificationHandler.Handle - E2T Address: %s - handling E2_SETUP_REQUEST", e2tIpAddress)
109         h.logger.Debugf("#E2SetupRequestNotificationHandler.Handle - E2_SETUP_REQUEST has been parsed successfully %+v", setupRequest)
110
111         _, err = h.e2tInstancesManager.GetE2TInstance(e2tIpAddress)
112
113         if err != nil {
114                 h.logger.Errorf("#E2TermInitNotificationHandler.Handle - Failed retrieving E2TInstance. error: %s", err)
115                 return
116         }
117
118         nodebInfo, err := h.rNibDataService.GetNodeb(ranName)
119
120         var functionsModified bool
121
122         if err != nil {
123
124                 if _, ok := err.(*common.ResourceNotFoundError); !ok {
125                         h.logger.Errorf("#E2SetupRequestNotificationHandler.Handle - RAN name: %s - failed to retrieve nodebInfo entity. Error: %s", ranName, err)
126                         return
127                 }
128
129                 if nodebInfo, err = h.handleNewRan(ranName, e2tIpAddress, setupRequest); err != nil {
130                         if _, ok := err.(*e2managererrors.UnknownSetupRequestRanNameError); ok {
131                                 cause := models.Cause{RicRequest: &models.CauseRic{RequestIdUnknown: &struct{}{}}}
132                                 h.handleUnsuccessfulResponse(ranName, request, cause)
133                         }
134                         return
135                 }
136
137         } else {
138
139                 functionsModified, err = h.handleExistingRan(ranName, nodebInfo, setupRequest)
140
141                 if err != nil {
142                         return
143                 }
144         }
145
146         ranStatusChangePublished, err := h.e2tAssociationManager.AssociateRan(e2tIpAddress, nodebInfo)
147
148         if err != nil {
149
150                 h.logger.Errorf("#E2SetupRequestNotificationHandler.Handle - RAN name: %s - failed to associate E2T to nodeB entity. Error: %s", ranName, err)
151                 if _, ok := err.(*e2managererrors.RoutingManagerError); ok {
152
153                         if err = h.handleUpdateAndPublishNodebInfo(functionsModified, ranStatusChangePublished, nodebInfo); err != nil {
154                                 return
155                         }
156
157                         cause := models.Cause{Transport: &models.CauseTransport{TransportResourceUnavailable: &struct{}{}}}
158                         h.handleUnsuccessfulResponse(nodebInfo.RanName, request, cause)
159                 }
160                 return
161         }
162
163         if err = h.handleUpdateAndPublishNodebInfo(functionsModified, ranStatusChangePublished, nodebInfo); err != nil {
164                 return
165         }
166
167         h.handleSuccessfulResponse(ranName, request, setupRequest)
168 }
169
170 func (h *E2SetupRequestNotificationHandler) handleUpdateAndPublishNodebInfo(functionsModified bool, ranStatusChangePublished bool, nodebInfo *entities.NodebInfo) error {
171
172         if ranStatusChangePublished || !functionsModified {
173                 return nil
174         }
175
176         err := h.rNibDataService.UpdateNodebInfoAndPublish(nodebInfo)
177
178         if err != nil {
179                 h.logger.Errorf("#E2SetupRequestNotificationHandler.handleUpdateAndPublishNodebInfo - RAN name: %s - Failed at UpdateNodebInfoAndPublish. error: %s", nodebInfo.RanName, err)
180                 return err
181         }
182
183         h.logger.Infof("#E2SetupRequestNotificationHandler.handleUpdateAndPublishNodebInfo - RAN name: %s - Successfully executed UpdateNodebInfoAndPublish", nodebInfo.RanName)
184         return nil
185
186 }
187
188 func (h *E2SetupRequestNotificationHandler) handleNewRan(ranName string, e2tIpAddress string, setupRequest *models.E2SetupRequestMessage) (*entities.NodebInfo, error) {
189
190         nodebInfo, err := h.buildNodebInfo(ranName, e2tIpAddress, setupRequest)
191         if err != nil {
192                 h.logger.Errorf("#E2SetupRequestNotificationHandler.handleNewRan - RAN name: %s - failed building nodebInfo. Error: %s", ranName, err)
193                 return nil, err
194         }
195
196         err = h.rNibDataService.SaveNodeb(nodebInfo)
197         if err != nil {
198                 h.logger.Errorf("#E2SetupRequestNotificationHandler.handleNewRan - RAN name: %s - failed saving nodebInfo. Error: %s", ranName, err)
199                 return nil, err
200         }
201
202         nbIdentity := h.buildNbIdentity(ranName, setupRequest)
203
204         err = h.ranListManager.AddNbIdentity(nodebInfo.GetNodeType(), nbIdentity)
205
206         if err != nil {
207                 return nil, err
208         }
209
210         return nodebInfo, nil
211 }
212
213 func (h *E2SetupRequestNotificationHandler) handleExistingRan(ranName string, nodebInfo *entities.NodebInfo, setupRequest *models.E2SetupRequestMessage) (bool, error) {
214         if nodebInfo.GetConnectionStatus() == entities.ConnectionStatus_SHUTTING_DOWN {
215                 h.logger.Errorf("#E2SetupRequestNotificationHandler.Handle - RAN name: %s, connection status: %s - nodeB entity in incorrect state", ranName, nodebInfo.ConnectionStatus)
216                 return false, errors.New("nodeB entity in incorrect state")
217         }
218
219         nodebInfo.SetupFromNetwork = true
220
221         if nodebInfo.NodeType == entities.Node_ENB {
222                 return false, nil
223         }
224
225         setupMessageRanFuncs := setupRequest.ExtractRanFunctionsList()
226
227         if setupMessageRanFuncs == nil || (len(setupMessageRanFuncs) == 0 && len(nodebInfo.GetGnb().RanFunctions) == 0) {
228                 return false, nil
229         }
230
231         nodebInfo.GetGnb().RanFunctions = setupMessageRanFuncs
232         return true, nil
233 }
234
235 func (h *E2SetupRequestNotificationHandler) handleUnsuccessfulResponse(ranName string, req *models.NotificationRequest, cause models.Cause) {
236         failureResponse := models.NewE2SetupFailureResponseMessage(models.TimeToWaitEnum.V60s, cause)
237         h.logger.Debugf("#E2SetupRequestNotificationHandler.handleUnsuccessfulResponse - E2_SETUP_RESPONSE has been built successfully %+v", failureResponse)
238
239         responsePayload, err := xml.Marshal(&failureResponse.E2APPDU)
240         if err != nil {
241                 h.logger.Warnf("#E2SetupRequestNotificationHandler.handleUnsuccessfulResponse - RAN name: %s - Error marshalling RIC_E2_SETUP_RESP. Payload: %s", ranName, responsePayload)
242         }
243
244         responsePayload = replaceEmptyTagsWithSelfClosing(responsePayload)
245
246         h.logger.Infof("#E2SetupRequestNotificationHandler.handleUnsuccessfulResponse - payload: %s", responsePayload)
247         msg := models.NewRmrMessage(rmrCgo.RIC_E2_SETUP_FAILURE, ranName, responsePayload, req.TransactionId, req.GetMsgSrc())
248         h.logger.Infof("#E2SetupRequestNotificationHandler.handleUnsuccessfulResponse - RAN name: %s - RIC_E2_SETUP_RESP message has been built successfully. Message: %x", ranName, msg)
249         _ = h.rmrSender.WhSend(msg)
250
251 }
252
253 func (h *E2SetupRequestNotificationHandler) handleSuccessfulResponse(ranName string, req *models.NotificationRequest, setupRequest *models.E2SetupRequestMessage) {
254
255         plmnId := buildPlmnId(h.config.GlobalRicId.Mcc, h.config.GlobalRicId.Mnc)
256
257         ricNearRtId, err := convertTo20BitString(h.config.GlobalRicId.RicId)
258         if err != nil {
259                 return
260         }
261         successResponse := models.NewE2SetupSuccessResponseMessage(plmnId, ricNearRtId, setupRequest)
262         h.logger.Debugf("#E2SetupRequestNotificationHandler.handleSuccessfulResponse - E2_SETUP_RESPONSE has been built successfully %+v", successResponse)
263
264         responsePayload, err := xml.Marshal(&successResponse.E2APPDU)
265         if err != nil {
266                 h.logger.Warnf("#E2SetupRequestNotificationHandler.handleSuccessfulResponse - RAN name: %s - Error marshalling RIC_E2_SETUP_RESP. Payload: %s", ranName, responsePayload)
267         }
268
269         responsePayload = replaceEmptyTagsWithSelfClosing(responsePayload)
270
271         h.logger.Infof("#E2SetupRequestNotificationHandler.handleSuccessfulResponse - payload: %s", responsePayload)
272
273         msg := models.NewRmrMessage(rmrCgo.RIC_E2_SETUP_RESP, ranName, responsePayload, req.TransactionId, req.GetMsgSrc())
274         h.logger.Infof("#E2SetupRequestNotificationHandler.handleSuccessfulResponse - RAN name: %s - RIC_E2_SETUP_RESP message has been built successfully. Message: %x", ranName, msg)
275         _ = h.rmrSender.Send(msg)
276 }
277
278 func buildPlmnId(mmc string, mnc string) string {
279         var b strings.Builder
280
281         b.WriteByte(mmc[1])
282         b.WriteByte(mmc[0])
283         if len(mnc) == 2 {
284                 b.WriteString("F")
285         } else {
286                 b.WriteByte(mnc[2])
287         }
288         b.WriteByte(mmc[2])
289         b.WriteByte(mnc[1])
290         b.WriteByte(mnc[0])
291
292         return b.String()
293 }
294
295 func replaceEmptyTagsWithSelfClosing(responsePayload []byte) []byte {
296
297         emptyTagVsSelfClosingTagPairs := make([]string, len(emptyTagsToReplaceToSelfClosingTags)*2)
298
299         j := 0
300
301         for i := 0; i < len(emptyTagsToReplaceToSelfClosingTags); i++ {
302                 emptyTagVsSelfClosingTagPairs[j] = fmt.Sprintf("<%[1]s></%[1]s>", emptyTagsToReplaceToSelfClosingTags[i])
303                 emptyTagVsSelfClosingTagPairs[j+1] = fmt.Sprintf("<%s/>", emptyTagsToReplaceToSelfClosingTags[i])
304                 j += 2
305         }
306         responseString := strings.NewReplacer(emptyTagVsSelfClosingTagPairs...).Replace(string(responsePayload))
307         return []byte(responseString)
308 }
309
310 func convertTo20BitString(ricNearRtId string) (string, error) {
311         r, err := strconv.ParseUint(ricNearRtId, 16, 32)
312         if err != nil {
313                 return "", err
314         }
315         return fmt.Sprintf("%020b", r)[:20], nil
316 }
317
318 func (h *E2SetupRequestNotificationHandler) parseSetupRequest(payload []byte) (*models.E2SetupRequestMessage, string, error) {
319
320         pipInd := bytes.IndexByte(payload, '|')
321         if pipInd < 0 {
322                 return nil, "", errors.New("#E2SetupRequestNotificationHandler.parseSetupRequest - Error parsing E2 Setup Request failed extract Payload: no | separator found")
323         }
324
325         e2tIpAddress := string(payload[:pipInd])
326         if len(e2tIpAddress) == 0 {
327                 return nil, "", errors.New("#E2SetupRequestNotificationHandler.parseSetupRequest - Empty E2T Address received")
328         }
329
330         h.logger.Infof("#E2SetupRequestNotificationHandler.parseSetupRequest - payload: %s", payload[pipInd+1:])
331
332         setupRequest := &models.E2SetupRequestMessage{}
333         err := xml.Unmarshal(normalizeXml(payload[pipInd+1:]), &setupRequest.E2APPDU)
334         if err != nil {
335                 return nil, "", errors.New(fmt.Sprintf("#E2SetupRequestNotificationHandler.parseSetupRequest - Error unmarshalling E2 Setup Request payload: %x", payload))
336         }
337
338         return setupRequest, e2tIpAddress, nil
339 }
340
341 func normalizeXml(payload []byte) []byte {
342         xmlStr := string(payload)
343         normalized := strings.NewReplacer("&lt;", "<", "&gt;", ">").Replace(xmlStr)
344         return []byte(normalized)
345 }
346
347 func (h *E2SetupRequestNotificationHandler) buildNodebInfo(ranName string, e2tAddress string, request *models.E2SetupRequestMessage) (*entities.NodebInfo, error) {
348         nodebInfo := &entities.NodebInfo{
349                 AssociatedE2TInstanceAddress: e2tAddress,
350                 RanName:                      ranName,
351                 GlobalNbId:                   h.buildGlobalNbId(request),
352                 SetupFromNetwork:             true,
353         }
354         err := h.setNodeTypeAndConfiguration(nodebInfo)
355         if err != nil {
356                 return nil, err
357         }
358
359         if nodebInfo.NodeType == entities.Node_ENB {
360                 return nodebInfo, nil
361         }
362
363         ranFuncs := request.ExtractRanFunctionsList()
364
365         if ranFuncs != nil {
366                 nodebInfo.GetGnb().RanFunctions = ranFuncs
367         }
368
369         return nodebInfo, nil
370 }
371
372 func (h *E2SetupRequestNotificationHandler) setNodeTypeAndConfiguration(nodebInfo *entities.NodebInfo) error {
373         for k, v := range gnbTypesMap {
374                 if strings.HasPrefix(nodebInfo.RanName, k) {
375                         nodebInfo.NodeType = entities.Node_GNB
376                         nodebInfo.Configuration = &entities.NodebInfo_Gnb{Gnb: &entities.Gnb{GnbType: v}}
377                         return nil
378                 }
379         }
380         for k, v := range enbTypesMap {
381                 if strings.HasPrefix(nodebInfo.RanName, k) {
382                         nodebInfo.NodeType = entities.Node_ENB
383                         nodebInfo.Configuration = &entities.NodebInfo_Enb{Enb: &entities.Enb{EnbType: v}}
384                         return nil
385                 }
386         }
387
388         return e2managererrors.NewUnknownSetupRequestRanNameError(nodebInfo.RanName)
389 }
390
391 func (h *E2SetupRequestNotificationHandler) buildGlobalNbId(setupRequest *models.E2SetupRequestMessage) *entities.GlobalNbId {
392         return &entities.GlobalNbId{
393                 PlmnId: setupRequest.GetPlmnId(),
394                 NbId:   setupRequest.GetNbId(),
395         }
396 }
397
398 func (h *E2SetupRequestNotificationHandler) buildNbIdentity(ranName string, setupRequest *models.E2SetupRequestMessage) *entities.NbIdentity {
399         return &entities.NbIdentity{
400                 InventoryName: ranName,
401                 GlobalNbId:    h.buildGlobalNbId(setupRequest),
402         }
403 }