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