RIC-193 - Setup from RAN fixes: Marshal XML Response, trim whitespaces, convert ricId...
[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/logger"
26         "e2mgr/managers"
27         "e2mgr/models"
28         "e2mgr/rmrCgo"
29         "e2mgr/services"
30         "e2mgr/services/rmrsender"
31         "e2mgr/utils"
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         if err != nil{
83                 if _, ok := err.(*common.ResourceNotFoundError); ok{
84                         nbIdentity := h.buildNbIdentity(ranName, setupRequest)
85                         nodebInfo, err = h.buildNodebInfo(ranName, e2tIpAddress, setupRequest)
86                         if err != nil{
87                                 h.logger.Errorf("#E2SetupRequestNotificationHandler.Handle - RAN name: %s - failed to build nodebInfo entity. Error: %s", ranName, err)
88                                 return
89                         }
90                         err = h.rNibDataService.SaveNodeb(nbIdentity, nodebInfo)
91                         if err != nil{
92                                 h.logger.Errorf("#E2SetupRequestNotificationHandler.Handle - RAN name: %s - failed to save nodebInfo entity. Error: %s", ranName, err)
93                                 return
94                         }
95                 } else{
96                         h.logger.Errorf("#E2SetupRequestNotificationHandler.Handle - RAN name: %s - failed to retrieve nodebInfo entity. Error: %s", ranName, err)
97                         return
98                 }
99
100         } else {
101                 if nodebInfo.ConnectionStatus == entities.ConnectionStatus_SHUTTING_DOWN {
102                         h.logger.Errorf("#E2SetupRequestNotificationHandler.Handle - RAN name: %s, connection status: %s - nodeB entity in incorrect state", nodebInfo.RanName, nodebInfo.ConnectionStatus)
103                         h.logger.Infof("#E2SetupRequestNotificationHandler.Handle - Summary: elapsed time for receiving and handling setup request message from E2 terminator: %f ms", utils.ElapsedTime(request.StartTime))
104                         return
105                 }
106                 nodebInfo.GetGnb().RanFunctions, err = setupRequest.GetExtractRanFunctionsList()
107                 if err != nil{
108                         h.logger.Errorf("#E2SetupRequestNotificationHandler.Handle - RAN name: %s - failed to update nodebInfo entity. Error: %s", ranName, err)
109                         return
110                 }
111         }
112         nodebInfo.ConnectionStatus = entities.ConnectionStatus_CONNECTED
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                 return
117         }
118
119         ricNearRtId, err := convertTo20BitString(h.config.GlobalRicId.RicNearRtId)
120         if err != nil{
121                 h.logger.Errorf("#E2SetupRequestNotificationHandler.Handle - RAN name: %s - failed to convert RicNearRtId value %s to 20 bit string . Error: %s", ranName, h.config.GlobalRicId.RicNearRtId, err)
122                 return
123         }
124         successResponse := models.NewE2SetupSuccessResponseMessage(h.config.GlobalRicId.PlmnId, ricNearRtId,setupRequest)
125         h.logger.Debugf("#E2SetupRequestNotificationHandler.Handle - E2_SETUP_RESPONSE has been built successfully %+v", successResponse)
126
127         responsePayload, err := xml.Marshal(&successResponse.E2APPDU)
128         if err != nil{
129                 h.logger.Warnf("#E2SetupRequestNotificationHandler.Handle - RAN name: %s - Error marshalling RIC_E2_SETUP_RESP. Payload: %s", ranName, responsePayload)
130         }
131
132         responsePayload = replaceCriticalityTagsWithSelfClosing(responsePayload)
133
134         msg := models.NewRmrMessage(rmrCgo.RIC_E2_SETUP_RESP, ranName, responsePayload, request.TransactionId)
135         h.logger.Infof("#E2SetupRequestNotificationHandler.Handle - RAN name: %s - RIC_E2_SETUP_RESP message has been built successfully. Message: %x", ranName, msg)
136         _ = h.rmrSender.Send(msg)
137 }
138
139 func replaceCriticalityTagsWithSelfClosing(responsePayload []byte) []byte {
140         responseString := strings.Replace(string(responsePayload), "<reject></reject>", "<reject/>", -1)
141         responseString = strings.Replace(responseString, "<ignore></ignore>", "<ignore/>", -1)
142         return []byte(responseString)
143 }
144
145 func convertTo20BitString(ricNearRtId string) (string, error){
146         r, err := strconv.ParseUint(ricNearRtId, 16, 32)
147         if err != nil{
148                 return "", err
149         }
150         return fmt.Sprintf("%020b", r)[:20], nil
151 }
152
153 func (h E2SetupRequestNotificationHandler) parseSetupRequest(payload []byte)(*models.E2SetupRequestMessage, string, error){
154
155         pipInd := bytes.IndexByte(payload, '|')
156         if pipInd < 0 {
157                 return nil, "", errors.New( "#E2SetupRequestNotificationHandler.parseSetupRequest - Error parsing E2 Setup Request failed extract Payload: no | separator found")
158         }
159
160         e2tIpAddress := string(payload[:pipInd])
161         if len(e2tIpAddress) == 0 {
162                 return nil, "", errors.New("#E2SetupRequestNotificationHandler.parseSetupRequest - Empty E2T Address received")
163         }
164         setupRequest := &models.E2SetupRequestMessage{}
165         err := xml.Unmarshal(payload[pipInd + 1:], &setupRequest.E2APPDU)
166         if err != nil {
167                 return nil, "", errors.New(fmt.Sprintf("#E2SetupRequestNotificationHandler.parseSetupRequest - Error unmarshalling E2 Setup Request payload: %x", payload))
168         }
169
170         return setupRequest, e2tIpAddress, nil
171 }
172
173 func (h E2SetupRequestNotificationHandler) buildNodebInfo(ranName string, e2tAddress string, request *models.E2SetupRequestMessage) (*entities.NodebInfo, error){
174         var err error
175         nodebInfo := &entities.NodebInfo{
176                 AssociatedE2TInstanceAddress: e2tAddress,
177                 ConnectionStatus: entities.ConnectionStatus_CONNECTED,
178                 RanName: ranName,
179                 NodeType: entities.Node_GNB,
180                 Configuration: &entities.NodebInfo_Gnb{Gnb: &entities.Gnb{}},
181         }
182         nodebInfo.GetGnb().RanFunctions, err = request.GetExtractRanFunctionsList()
183         return nodebInfo, err
184 }
185
186 func (h E2SetupRequestNotificationHandler) buildNbIdentity(ranName string, setupRequest *models.E2SetupRequestMessage)*entities.NbIdentity{
187         return &entities.NbIdentity{
188                 InventoryName:ranName,
189                 GlobalNbId: &entities.GlobalNbId{
190                         PlmnId: setupRequest.GetPlmnId(),
191                         NbId:   setupRequest.GetNbId(),
192                 },
193         }
194 }