[RIC-306] Split configuration of globalRicId to mmc, mnc and ric id
[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 type E2SetupRequestNotificationHandler struct {
42         logger                *logger.Logger
43         config                *configuration.Configuration
44         e2tInstancesManager   managers.IE2TInstancesManager
45         rmrSender             *rmrsender.RmrSender
46         rNibDataService       services.RNibDataService
47         e2tAssociationManager *managers.E2TAssociationManager
48 }
49
50 func NewE2SetupRequestNotificationHandler(logger *logger.Logger, config *configuration.Configuration, e2tInstancesManager managers.IE2TInstancesManager, rmrSender *rmrsender.RmrSender, rNibDataService services.RNibDataService, e2tAssociationManager *managers.E2TAssociationManager) E2SetupRequestNotificationHandler {
51         return E2SetupRequestNotificationHandler{
52                 logger:                logger,
53                 config:                config,
54                 e2tInstancesManager:   e2tInstancesManager,
55                 rmrSender:             rmrSender,
56                 rNibDataService:       rNibDataService,
57                 e2tAssociationManager: e2tAssociationManager,
58         }
59 }
60
61 func (h E2SetupRequestNotificationHandler) Handle(request *models.NotificationRequest) {
62         ranName := request.RanName
63         h.logger.Infof("#E2SetupRequestNotificationHandler.Handle - RAN name: %s - received E2_SETUP_REQUEST. Payload: %x", ranName, request.Payload)
64
65         setupRequest, e2tIpAddress, err := h.parseSetupRequest(request.Payload)
66         if err != nil {
67                 h.logger.Errorf(err.Error())
68                 return
69         }
70
71         h.logger.Infof("#E2SetupRequestNotificationHandler.Handle - E2T Address: %s - handling E2_SETUP_REQUEST", e2tIpAddress)
72         h.logger.Debugf("#E2SetupRequestNotificationHandler.Handle - E2_SETUP_REQUEST has been parsed successfully %+v", setupRequest)
73
74         _, err = h.e2tInstancesManager.GetE2TInstance(e2tIpAddress)
75
76         if err != nil {
77                 h.logger.Errorf("#E2TermInitNotificationHandler.Handle - Failed retrieving E2TInstance. error: %s", err)
78                 return
79         }
80
81         nodebInfo, err := h.rNibDataService.GetNodeb(ranName)
82
83         if err != nil {
84
85                 if _, ok := err.(*common.ResourceNotFoundError); !ok {
86                         h.logger.Errorf("#E2SetupRequestNotificationHandler.Handle - RAN name: %s - failed to retrieve nodebInfo entity. Error: %s", ranName, err)
87                         return
88
89                 }
90
91                 if nodebInfo, err = h.handleNewRan(ranName, e2tIpAddress, setupRequest); err != nil {
92                         return
93                 }
94
95         } else {
96                 if err = h.handleExistingRan(ranName, nodebInfo, setupRequest); err != nil {
97                         return
98                 }
99         }
100
101         err = h.e2tAssociationManager.AssociateRan(e2tIpAddress, nodebInfo)
102
103         if err != nil {
104
105                 h.logger.Errorf("#E2SetupRequestNotificationHandler.Handle - RAN name: %s - failed to associate E2T to nodeB entity. Error: %s", ranName, err)
106                 if _, ok := err.(*e2managererrors.RoutingManagerError); ok {
107                         h.handleUnsuccessfulResponse(nodebInfo, request)
108                 }
109                 return
110         }
111
112         h.handleSuccessfulResponse(ranName, request, setupRequest)
113 }
114
115 func (h E2SetupRequestNotificationHandler) handleNewRan(ranName string, e2tIpAddress string, setupRequest *models.E2SetupRequestMessage) (*entities.NodebInfo, error) {
116
117         nodebInfo, err := h.buildNodebInfo(ranName, e2tIpAddress, setupRequest)
118
119         if err != nil {
120                 h.logger.Errorf("#E2SetupRequestNotificationHandler.handleNewRan - RAN name: %s - failed to build nodebInfo entity. Error: %s", ranName, err)
121                 return nil, err
122         }
123
124         nbIdentity := h.buildNbIdentity(ranName, setupRequest)
125         err = h.rNibDataService.SaveNodeb(nbIdentity, nodebInfo)
126
127         if err != nil {
128                 h.logger.Errorf("#E2SetupRequestNotificationHandler.handleNewRan - RAN name: %s - failed to save nodebInfo entity. Error: %s", ranName, err)
129                 return nil, err
130         }
131
132         return nodebInfo, nil
133 }
134
135 func (h E2SetupRequestNotificationHandler) setGnbFunctions(nodebInfo *entities.NodebInfo, setupRequest *models.E2SetupRequestMessage) error {
136         ranFunctions := setupRequest.ExtractRanFunctionsList()
137
138         if ranFunctions != nil {
139                 nodebInfo.GetGnb().RanFunctions = ranFunctions
140         }
141
142         return nil
143 }
144
145 func (h E2SetupRequestNotificationHandler) handleExistingRan(ranName string, nodebInfo *entities.NodebInfo, setupRequest *models.E2SetupRequestMessage) error {
146         if nodebInfo.GetConnectionStatus() == entities.ConnectionStatus_SHUTTING_DOWN {
147                 h.logger.Errorf("#E2SetupRequestNotificationHandler.Handle - RAN name: %s, connection status: %s - nodeB entity in incorrect state", ranName, nodebInfo.ConnectionStatus)
148                 return errors.New("nodeB entity in incorrect state")
149         }
150
151         err := h.setGnbFunctions(nodebInfo, setupRequest)
152         return err
153 }
154
155 func (h E2SetupRequestNotificationHandler) handleUnsuccessfulResponse(nodebInfo *entities.NodebInfo, req *models.NotificationRequest) {
156         failureResponse := models.NewE2SetupFailureResponseMessage(models.TimeToWaitEnum.V60s)
157         h.logger.Debugf("#E2SetupRequestNotificationHandler.handleUnsuccessfulResponse - E2_SETUP_RESPONSE has been built successfully %+v", failureResponse)
158
159         responsePayload, err := xml.Marshal(&failureResponse.E2APPDU)
160         if err != nil {
161                 h.logger.Warnf("#E2SetupRequestNotificationHandler.handleUnsuccessfulResponse - RAN name: %s - Error marshalling RIC_E2_SETUP_RESP. Payload: %s", nodebInfo.RanName, responsePayload)
162         }
163
164         responsePayload = replaceEmptyTagsWithSelfClosing(responsePayload)
165
166         msg := models.NewRmrMessage(rmrCgo.RIC_E2_SETUP_FAILURE, nodebInfo.RanName, responsePayload, req.TransactionId, req.GetMsgSrc())
167         h.logger.Infof("#E2SetupRequestNotificationHandler.handleUnsuccessfulResponse - RAN name: %s - RIC_E2_SETUP_RESP message has been built successfully. Message: %x", nodebInfo.RanName, msg)
168         _ = h.rmrSender.WhSend(msg)
169
170 }
171
172 func (h E2SetupRequestNotificationHandler) handleSuccessfulResponse(ranName string, req *models.NotificationRequest, setupRequest *models.E2SetupRequestMessage) {
173
174         plmnId := buildPlmnId(strconv.Itoa(h.config.GlobalRicId.Mcc), strconv.Itoa(h.config.GlobalRicId.Mnc))
175
176         ricNearRtId, err := convertTo20BitString(h.config.GlobalRicId.RicId)
177         if err != nil {
178                 return
179         }
180         successResponse := models.NewE2SetupSuccessResponseMessage(plmnId, ricNearRtId, setupRequest)
181         h.logger.Debugf("#E2SetupRequestNotificationHandler.handleSuccessfulResponse - E2_SETUP_RESPONSE has been built successfully %+v", successResponse)
182
183         responsePayload, err := xml.Marshal(&successResponse.E2APPDU)
184         if err != nil {
185                 h.logger.Warnf("#E2SetupRequestNotificationHandler.handleSuccessfulResponse - RAN name: %s - Error marshalling RIC_E2_SETUP_RESP. Payload: %s", ranName, responsePayload)
186         }
187
188         responsePayload = replaceEmptyTagsWithSelfClosing(responsePayload)
189
190         msg := models.NewRmrMessage(rmrCgo.RIC_E2_SETUP_RESP, ranName, responsePayload, req.TransactionId, req.GetMsgSrc())
191         h.logger.Infof("#E2SetupRequestNotificationHandler.handleSuccessfulResponse - RAN name: %s - RIC_E2_SETUP_RESP message has been built successfully. Message: %x", ranName, msg)
192         _ = h.rmrSender.Send(msg)
193 }
194
195 func buildPlmnId(mmc string, mnc string) string{
196         var b strings.Builder
197
198         b.WriteString(string (mmc[1]))
199         b.WriteString(string (mmc[0]))
200         if len(mnc) == 2 {
201                 b.WriteString("F")
202         } else {
203                 b.WriteString(string (mnc[2]))
204         }
205         b.WriteString(string (mmc[2]))
206         b.WriteString(string (mnc[1]))
207         b.WriteString(string (mnc[0]))
208
209         return b.String()
210 }
211
212 func replaceEmptyTagsWithSelfClosing(responsePayload []byte) []byte {
213         responseString := strings.NewReplacer(
214                 "<reject></reject>", "<reject/>",
215                 "<ignore></ignore>", "<ignore/>",
216                 "<transport-resource-unavailable></transport-resource-unavailable>", "<transport-resource-unavailable/>",
217                 "<v60s></v60s>", "<v60s/>",
218                 "<v20s></v20s>", "<v20s/>",
219                 "<v10s></v10s>", "<v10s/>",
220                 "<v5s></v5s>", "<v5s/>",
221                 "<v2s></v2s>", "<v2s/>",
222                 "<v1s></v1s>", "<v1s/>",
223         ).Replace(string(responsePayload))
224         return []byte(responseString)
225 }
226
227 func convertTo20BitString(ricNearRtId string) (string, error) {
228         r, err := strconv.ParseUint(ricNearRtId, 16, 32)
229         if err != nil {
230                 return "", err
231         }
232         return fmt.Sprintf("%020b", r)[:20], nil
233 }
234
235 func (h E2SetupRequestNotificationHandler) parseSetupRequest(payload []byte) (*models.E2SetupRequestMessage, string, error) {
236
237         pipInd := bytes.IndexByte(payload, '|')
238         if pipInd < 0 {
239                 return nil, "", errors.New("#E2SetupRequestNotificationHandler.parseSetupRequest - Error parsing E2 Setup Request failed extract Payload: no | separator found")
240         }
241
242         e2tIpAddress := string(payload[:pipInd])
243         if len(e2tIpAddress) == 0 {
244                 return nil, "", errors.New("#E2SetupRequestNotificationHandler.parseSetupRequest - Empty E2T Address received")
245         }
246
247         h.logger.Infof("#E2SetupRequestNotificationHandler.parseSetupRequest - payload: %s", payload[pipInd+1:])
248
249         setupRequest := &models.E2SetupRequestMessage{}
250         err := xml.Unmarshal(normalizeXml(payload[pipInd+1:]), &setupRequest.E2APPDU)
251         if err != nil {
252                 return nil, "", errors.New(fmt.Sprintf("#E2SetupRequestNotificationHandler.parseSetupRequest - Error unmarshalling E2 Setup Request payload: %x", payload))
253         }
254
255         return setupRequest, e2tIpAddress, nil
256 }
257
258 func normalizeXml(payload []byte) []byte {
259         xmlStr := string(payload)
260         normalized := strings.NewReplacer("&lt;", "<", "&gt;", ">").Replace(xmlStr)
261         return []byte(normalized)
262 }
263
264 func (h E2SetupRequestNotificationHandler) buildNodebInfo(ranName string, e2tAddress string, request *models.E2SetupRequestMessage) (*entities.NodebInfo, error) {
265
266         var err error
267         nodebInfo := &entities.NodebInfo{
268                 AssociatedE2TInstanceAddress: e2tAddress,
269                 ConnectionStatus:             entities.ConnectionStatus_CONNECTED,
270                 RanName:                      ranName,
271                 NodeType:                     entities.Node_GNB,
272                 Configuration:                &entities.NodebInfo_Gnb{Gnb: &entities.Gnb{}},
273                 GlobalNbId:                   h.buildGlobalNbId(request),
274         }
275
276         err = h.setGnbFunctions(nodebInfo, request)
277         return nodebInfo, err
278 }
279
280 func (h E2SetupRequestNotificationHandler) buildGlobalNbId(setupRequest *models.E2SetupRequestMessage) *entities.GlobalNbId {
281         return &entities.GlobalNbId{
282                 PlmnId: setupRequest.GetPlmnId(),
283                 NbId:   setupRequest.GetNbId(),
284         }
285 }
286
287 func (h E2SetupRequestNotificationHandler) buildNbIdentity(ranName string, setupRequest *models.E2SetupRequestMessage) *entities.NbIdentity {
288         return &entities.NbIdentity{
289                 InventoryName: ranName,
290                 GlobalNbId:    h.buildGlobalNbId(setupRequest),
291         }
292 }