RIC-194 Setup from RAN: On Routing Manager Failure, return Setup Failure
[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         "e2mgr/utils"
33         "encoding/xml"
34         "errors"
35         "fmt"
36         "gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/common"
37         "gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/entities"
38         "strconv"
39         "strings"
40 )
41
42 type E2SetupRequestNotificationHandler struct {
43         logger                 *logger.Logger
44         config                 *configuration.Configuration
45         e2tInstancesManager    managers.IE2TInstancesManager
46         rmrSender              *rmrsender.RmrSender
47         rNibDataService       services.RNibDataService
48         e2tAssociationManager *managers.E2TAssociationManager
49 }
50
51 func NewE2SetupRequestNotificationHandler(logger *logger.Logger, config *configuration.Configuration, e2tInstancesManager managers.IE2TInstancesManager, rmrSender *rmrsender.RmrSender, rNibDataService services.RNibDataService, e2tAssociationManager *managers.E2TAssociationManager) E2SetupRequestNotificationHandler {
52         return E2SetupRequestNotificationHandler{
53                 logger:                 logger,
54                 config:                 config,
55                 e2tInstancesManager:    e2tInstancesManager,
56                 rmrSender: rmrSender,
57                 rNibDataService: rNibDataService,
58                 e2tAssociationManager: e2tAssociationManager,
59         }
60 }
61
62 func (h E2SetupRequestNotificationHandler) Handle(request *models.NotificationRequest){
63         ranName := request.RanName
64         h.logger.Infof("#E2SetupRequestNotificationHandler.Handle - RAN name: %s - received E2_SETUP_REQUEST. Payload: %x", ranName, request.Payload)
65
66         setupRequest, e2tIpAddress, err := h.parseSetupRequest(request.Payload)
67         if err != nil {
68                 h.logger.Errorf(err.Error())
69                 return
70         }
71
72         h.logger.Infof("#E2SetupRequestNotificationHandler.Handle - E2T Address: %s - handling E2_SETUP_REQUEST", e2tIpAddress)
73         h.logger.Debugf("#E2SetupRequestNotificationHandler.Handle - E2_SETUP_REQUEST has been parsed successfully %+v", setupRequest)
74
75         _, err = h.e2tInstancesManager.GetE2TInstance(e2tIpAddress)
76
77         if err != nil {
78                 h.logger.Errorf("#E2TermInitNotificationHandler.Handle - Failed retrieving E2TInstance. error: %s", err)
79                 return
80         }
81
82         nodebInfo, err := h.rNibDataService.GetNodeb(ranName)
83         if err != nil{
84                 if _, ok := err.(*common.ResourceNotFoundError); ok{
85                         nbIdentity := h.buildNbIdentity(ranName, setupRequest)
86                         nodebInfo, err = h.buildNodebInfo(ranName, e2tIpAddress, setupRequest)
87                         if err != nil{
88                                 h.logger.Errorf("#E2SetupRequestNotificationHandler.Handle - RAN name: %s - failed to build nodebInfo entity. Error: %s", ranName, err)
89                                 return
90                         }
91                         err = h.rNibDataService.SaveNodeb(nbIdentity, nodebInfo)
92                         if err != nil{
93                                 h.logger.Errorf("#E2SetupRequestNotificationHandler.Handle - RAN name: %s - failed to save nodebInfo entity. Error: %s", ranName, err)
94                                 return
95                         }
96                 } else{
97                         h.logger.Errorf("#E2SetupRequestNotificationHandler.Handle - RAN name: %s - failed to retrieve nodebInfo entity. Error: %s", ranName, err)
98                         return
99                 }
100
101         } else {
102                 if nodebInfo.ConnectionStatus == entities.ConnectionStatus_SHUTTING_DOWN {
103                         h.logger.Errorf("#E2SetupRequestNotificationHandler.Handle - RAN name: %s, connection status: %s - nodeB entity in incorrect state", nodebInfo.RanName, nodebInfo.ConnectionStatus)
104                         h.logger.Infof("#E2SetupRequestNotificationHandler.Handle - Summary: elapsed time for receiving and handling setup request message from E2 terminator: %f ms", utils.ElapsedTime(request.StartTime))
105                         return
106                 }
107                 nodebInfo.GetGnb().RanFunctions, err = setupRequest.GetExtractRanFunctionsList()
108                 if err != nil{
109                         h.logger.Errorf("#E2SetupRequestNotificationHandler.Handle - RAN name: %s - failed to update nodebInfo entity. Error: %s", ranName, err)
110                         return
111                 }
112         }
113         err = h.e2tAssociationManager.AssociateRan(e2tIpAddress, nodebInfo)
114         if err != nil{
115                 h.logger.Errorf("#E2SetupRequestNotificationHandler.Handle - RAN name: %s - failed to associate E2T to nodeB entity. Error: %s", ranName, err)
116                 if _, ok := err.(*e2managererrors.RoutingManagerError); ok{
117                         h.handleUnsuccessfulResponse(nodebInfo, request)
118                 }
119                 return
120         }
121         h.handleSuccessfulResponse(ranName, request, setupRequest)
122 }
123
124 func (h E2SetupRequestNotificationHandler) handleUnsuccessfulResponse(nodebInfo *entities.NodebInfo, req *models.NotificationRequest){
125         failureResponse := models.NewE2SetupFailureResponseMessage(models.TimeToWaitEnum.V60s)
126         h.logger.Debugf("#E2SetupRequestNotificationHandler.handleUnsuccessfulResponse - E2_SETUP_RESPONSE has been built successfully %+v", failureResponse)
127
128         responsePayload, err := xml.Marshal(&failureResponse.E2APPDU)
129         if err != nil{
130                 h.logger.Warnf("#E2SetupRequestNotificationHandler.handleUnsuccessfulResponse - RAN name: %s - Error marshalling RIC_E2_SETUP_RESP. Payload: %s", nodebInfo.RanName, responsePayload)
131         }
132
133         responsePayload = replaceEmptyTagsWithSelfClosing(responsePayload)
134
135         msg := models.NewRmrMessage(rmrCgo.RIC_E2_SETUP_FAILURE, nodebInfo.RanName, responsePayload, req.TransactionId, req.GetMsgSrc())
136         h.logger.Infof("#E2SetupRequestNotificationHandler.handleUnsuccessfulResponse - RAN name: %s - RIC_E2_SETUP_RESP message has been built successfully. Message: %x", nodebInfo.RanName, msg)
137         _ = h.rmrSender.WhSend(msg)
138
139 }
140
141 func (h E2SetupRequestNotificationHandler) handleSuccessfulResponse(ranName string, req *models.NotificationRequest, setupRequest *models.E2SetupRequestMessage){
142
143         ricNearRtId, err := convertTo20BitString(h.config.GlobalRicId.RicNearRtId)
144         if err != nil{
145                 h.logger.Errorf("#E2SetupRequestNotificationHandler.handleSuccessfulResponse - RAN name: %s - failed to convert RicNearRtId value %s to 20 bit string . Error: %s", ranName, h.config.GlobalRicId.RicNearRtId, err)
146                 return
147         }
148         successResponse := models.NewE2SetupSuccessResponseMessage(h.config.GlobalRicId.PlmnId, ricNearRtId,setupRequest)
149         h.logger.Debugf("#E2SetupRequestNotificationHandler.handleSuccessfulResponse - E2_SETUP_RESPONSE has been built successfully %+v", successResponse)
150
151         responsePayload, err := xml.Marshal(&successResponse.E2APPDU)
152         if err != nil{
153                 h.logger.Warnf("#E2SetupRequestNotificationHandler.handleSuccessfulResponse - RAN name: %s - Error marshalling RIC_E2_SETUP_RESP. Payload: %s", ranName, responsePayload)
154         }
155
156         responsePayload = replaceEmptyTagsWithSelfClosing(responsePayload)
157
158         msg := models.NewRmrMessage(rmrCgo.RIC_E2_SETUP_RESP, ranName, responsePayload, req.TransactionId, req.GetMsgSrc())
159         h.logger.Infof("#E2SetupRequestNotificationHandler.handleSuccessfulResponse - RAN name: %s - RIC_E2_SETUP_RESP message has been built successfully. Message: %x", ranName, msg)
160         _ = h.rmrSender.Send(msg)
161 }
162
163
164 func replaceEmptyTagsWithSelfClosing(responsePayload []byte) []byte {
165         responseString := strings.NewReplacer(
166                 "<reject></reject>", "<reject/>",
167                 "<ignore></ignore>", "<ignore/>",
168                 "<transport-resource-unavailable></transport-resource-unavailable>", "<transport-resource-unavailable/>",
169                 "<v60s></v60s>", "<v60s/>",
170                 "<v20s></v20s>", "<v20s/>",
171                 "<v10s></v10s>", "<v10s/>",
172                 "<v5s></v5s>", "<v5s/>",
173                 "<v2s></v2s>", "<v2s/>",
174                 "<v1s></v1s>", "<v1s/>",
175                 ).Replace(string(responsePayload))
176         return []byte(responseString)
177 }
178
179 func convertTo20BitString(ricNearRtId string) (string, error){
180         r, err := strconv.ParseUint(ricNearRtId, 16, 32)
181         if err != nil{
182                 return "", err
183         }
184         return fmt.Sprintf("%020b", r)[:20], nil
185 }
186
187 func (h E2SetupRequestNotificationHandler) parseSetupRequest(payload []byte)(*models.E2SetupRequestMessage, string, error){
188
189         pipInd := bytes.IndexByte(payload, '|')
190         if pipInd < 0 {
191                 return nil, "", errors.New( "#E2SetupRequestNotificationHandler.parseSetupRequest - Error parsing E2 Setup Request failed extract Payload: no | separator found")
192         }
193
194         e2tIpAddress := string(payload[:pipInd])
195         if len(e2tIpAddress) == 0 {
196                 return nil, "", errors.New("#E2SetupRequestNotificationHandler.parseSetupRequest - Empty E2T Address received")
197         }
198         setupRequest := &models.E2SetupRequestMessage{}
199         err := xml.Unmarshal(payload[pipInd + 1:], &setupRequest.E2APPDU)
200         if err != nil {
201                 return nil, "", errors.New(fmt.Sprintf("#E2SetupRequestNotificationHandler.parseSetupRequest - Error unmarshalling E2 Setup Request payload: %x", payload))
202         }
203
204         return setupRequest, e2tIpAddress, nil
205 }
206
207 func (h E2SetupRequestNotificationHandler) buildNodebInfo(ranName string, e2tAddress string, request *models.E2SetupRequestMessage) (*entities.NodebInfo, error){
208         var err error
209         nodebInfo := &entities.NodebInfo{
210                 AssociatedE2TInstanceAddress: e2tAddress,
211                 ConnectionStatus: entities.ConnectionStatus_CONNECTED,
212                 RanName: ranName,
213                 NodeType: entities.Node_GNB,
214                 Configuration: &entities.NodebInfo_Gnb{Gnb: &entities.Gnb{}},
215                 GlobalNbId:  &entities.GlobalNbId{
216                         PlmnId: request.GetPlmnId(),
217                         NbId:   request.GetNbId(),
218                 },
219         }
220         nodebInfo.GetGnb().RanFunctions, err = request.GetExtractRanFunctionsList()
221         return nodebInfo, err
222 }
223
224 func (h E2SetupRequestNotificationHandler) buildNbIdentity(ranName string, setupRequest *models.E2SetupRequestMessage)*entities.NbIdentity{
225         return &entities.NbIdentity{
226                 InventoryName:ranName,
227                 GlobalNbId: &entities.GlobalNbId{
228                         PlmnId: setupRequest.GetPlmnId(),
229                         NbId:   setupRequest.GetNbId(),
230                 },
231         }
232 }