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