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