[RIC-436] Fix E2 Setup Response population
[ric-plt/e2mgr.git] / E2Manager / controllers / nodeb_controller.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 controllers
21
22 import (
23         "e2mgr/e2managererrors"
24         "e2mgr/logger"
25         "e2mgr/models"
26         "e2mgr/providers/httpmsghandlerprovider"
27         "encoding/json"
28         "gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/entities"
29         "github.com/golang/protobuf/jsonpb"
30         "github.com/golang/protobuf/proto"
31         "github.com/gorilla/mux"
32         "io"
33         "io/ioutil"
34         "net/http"
35         "net/http/httputil"
36         "strings"
37 )
38
39 const (
40         ParamRanName = "ranName"
41         LimitRequest = 2000
42 )
43
44 type INodebController interface {
45         Shutdown(writer http.ResponseWriter, r *http.Request)
46         X2Reset(writer http.ResponseWriter, r *http.Request)
47         X2Setup(writer http.ResponseWriter, r *http.Request)
48         EndcSetup(writer http.ResponseWriter, r *http.Request)
49         GetNodeb(writer http.ResponseWriter, r *http.Request)
50         UpdateGnb(writer http.ResponseWriter, r *http.Request)
51         GetNodebIdList(writer http.ResponseWriter, r *http.Request)
52 }
53
54 type NodebController struct {
55         logger          *logger.Logger
56         handlerProvider *httpmsghandlerprovider.IncomingRequestHandlerProvider
57 }
58
59 func NewNodebController(logger *logger.Logger, handlerProvider *httpmsghandlerprovider.IncomingRequestHandlerProvider) *NodebController {
60         return &NodebController{
61                 logger:          logger,
62                 handlerProvider: handlerProvider,
63         }
64 }
65
66 func (c *NodebController) GetNodebIdList(writer http.ResponseWriter, r *http.Request) {
67         c.logger.Infof("[Client -> E2 Manager] #NodebController.GetNodebIdList - request: %v", c.prettifyRequest(r))
68
69         c.handleRequest(writer, &r.Header, httpmsghandlerprovider.GetNodebIdListRequest, nil, false)
70 }
71
72 func (c *NodebController) GetNodeb(writer http.ResponseWriter, r *http.Request) {
73         c.logger.Infof("[Client -> E2 Manager] #NodebController.GetNodeb - request: %v", c.prettifyRequest(r))
74         vars := mux.Vars(r)
75         ranName := vars["ranName"]
76         request := models.GetNodebRequest{RanName: ranName}
77         c.handleRequest(writer, &r.Header, httpmsghandlerprovider.GetNodebRequest, request, false)
78 }
79
80 func (c *NodebController) UpdateGnb(writer http.ResponseWriter, r *http.Request) {
81         c.logger.Infof("[Client -> E2 Manager] #NodebController.UpdateGnb - request: %v", c.prettifyRequest(r))
82         vars := mux.Vars(r)
83         ranName := vars[ParamRanName]
84
85         request := models.UpdateGnbRequest{}
86
87         gnb := entities.Gnb{}
88
89         if !c.extractRequestBodyToProto(r, &gnb, writer) {
90                 return
91         }
92
93         request.Gnb = &gnb;
94         request.RanName = ranName
95         c.handleRequest(writer, &r.Header, httpmsghandlerprovider.UpdateGnbRequest, request, true)
96 }
97
98 func (c *NodebController) Shutdown(writer http.ResponseWriter, r *http.Request) {
99         c.logger.Infof("[Client -> E2 Manager] #NodebController.Shutdown - request: %v", c.prettifyRequest(r))
100         c.handleRequest(writer, &r.Header, httpmsghandlerprovider.ShutdownRequest, nil, false)
101 }
102
103 func (c *NodebController) X2Reset(writer http.ResponseWriter, r *http.Request) {
104         c.logger.Infof("[Client -> E2 Manager] #NodebController.X2Reset - request: %v", c.prettifyRequest(r))
105         request := models.ResetRequest{}
106         vars := mux.Vars(r)
107         ranName := vars[ParamRanName]
108
109         if r.ContentLength > 0 && !c.extractJsonBody(r, &request, writer) {
110                 return
111         }
112         request.RanName = ranName
113         c.handleRequest(writer, &r.Header, httpmsghandlerprovider.ResetRequest, request, false)
114 }
115
116 func (c *NodebController) X2Setup(writer http.ResponseWriter, r *http.Request) {
117         c.logger.Infof("[Client -> E2 Manager] #NodebController.X2Setup - request: %v", c.prettifyRequest(r))
118
119         request := models.SetupRequest{}
120
121         if !c.extractJsonBody(r, &request, writer) {
122                 return
123         }
124
125         c.handleRequest(writer, &r.Header, httpmsghandlerprovider.X2SetupRequest, request, true)
126 }
127
128 func (c *NodebController) EndcSetup(writer http.ResponseWriter, r *http.Request) {
129         c.logger.Infof("[Client -> E2 Manager] #NodebController.EndcSetup - request: %v", c.prettifyRequest(r))
130
131         request := models.SetupRequest{}
132
133         if !c.extractJsonBody(r, &request, writer) {
134                 return
135         }
136
137         c.handleRequest(writer, &r.Header, httpmsghandlerprovider.EndcSetupRequest, request, true)
138 }
139
140 func (c *NodebController) extractRequestBodyToProto(r *http.Request, pb proto.Message , writer http.ResponseWriter) bool {
141         defer r.Body.Close()
142
143         err := jsonpb.Unmarshal(r.Body, pb)
144
145         if err != nil {
146                 c.logger.Errorf("[Client -> E2 Manager] #NodebController.extractJsonBody - unable to extract json body - error: %s", err)
147                 c.handleErrorResponse(e2managererrors.NewInvalidJsonError(), writer)
148                 return false
149         }
150
151         return true
152 }
153
154 func (c *NodebController) extractJsonBody(r *http.Request, request models.Request, writer http.ResponseWriter) bool {
155         defer r.Body.Close()
156         body, err := ioutil.ReadAll(io.LimitReader(r.Body, LimitRequest))
157
158         if err != nil {
159                 c.logger.Errorf("[Client -> E2 Manager] #NodebController.extractJsonBody - unable to extract json body - error: %s", err)
160                 c.handleErrorResponse(e2managererrors.NewInvalidJsonError(), writer)
161                 return false
162         }
163
164         err = json.Unmarshal(body, &request)
165         if err != nil {
166                 c.logger.Errorf("[Client -> E2 Manager] #NodebController.extractJsonBody - unable to extract json body - error: %s", err)
167                 c.handleErrorResponse(e2managererrors.NewInvalidJsonError(), writer)
168                 return false
169         }
170
171         return true
172 }
173
174 func (c *NodebController) handleRequest(writer http.ResponseWriter, header *http.Header, requestName httpmsghandlerprovider.IncomingRequest, request models.Request, validateRequestHeaders bool) {
175
176         if validateRequestHeaders {
177
178                 err := c.validateRequestHeader(header)
179                 if err != nil {
180                         c.handleErrorResponse(err, writer)
181                         return
182                 }
183         }
184
185         handler, err := c.handlerProvider.GetHandler(requestName)
186
187         if err != nil {
188                 c.handleErrorResponse(err, writer)
189                 return
190         }
191
192         response, err := handler.Handle(request)
193
194         if err != nil {
195                 c.handleErrorResponse(err, writer)
196                 return
197         }
198
199         if response == nil {
200                 writer.WriteHeader(http.StatusNoContent)
201                 c.logger.Infof("[E2 Manager -> Client] #NodebController.handleRequest - status response: %v", http.StatusNoContent)
202                 return
203         }
204
205         result, err := response.Marshal()
206
207         if err != nil {
208                 c.handleErrorResponse(err, writer)
209                 return
210         }
211
212         c.logger.Infof("[E2 Manager -> Client] #NodebController.handleRequest - response: %s", result)
213         writer.Header().Set("Content-Type", "application/json")
214         writer.Write(result)
215 }
216
217 func (c *NodebController) validateRequestHeader(header *http.Header) error {
218
219         if header.Get("Content-Type") != "application/json" {
220                 c.logger.Errorf("#NodebController.validateRequestHeader - validation failure, incorrect content type")
221
222                 return e2managererrors.NewHeaderValidationError()
223         }
224         return nil
225 }
226
227 func (c *NodebController) handleErrorResponse(err error, writer http.ResponseWriter) {
228
229         var errorResponseDetails models.ErrorResponse
230         var httpError int
231
232         if err != nil {
233                 switch err.(type) {
234                 case *e2managererrors.RnibDbError:
235                         e2Error, _ := err.(*e2managererrors.RnibDbError)
236                         errorResponseDetails = models.ErrorResponse{Code: e2Error.Code, Message: e2Error.Message}
237                         httpError = http.StatusInternalServerError
238                 case *e2managererrors.CommandAlreadyInProgressError:
239                         e2Error, _ := err.(*e2managererrors.CommandAlreadyInProgressError)
240                         errorResponseDetails = models.ErrorResponse{Code: e2Error.Code, Message: e2Error.Message}
241                         httpError = http.StatusMethodNotAllowed
242                 case *e2managererrors.HeaderValidationError:
243                         e2Error, _ := err.(*e2managererrors.HeaderValidationError)
244                         errorResponseDetails = models.ErrorResponse{Code: e2Error.Code, Message: e2Error.Message}
245                         httpError = http.StatusUnsupportedMediaType
246                 case *e2managererrors.WrongStateError:
247                         e2Error, _ := err.(*e2managererrors.WrongStateError)
248                         errorResponseDetails = models.ErrorResponse{Code: e2Error.Code, Message: e2Error.Message}
249                         httpError = http.StatusBadRequest
250                 case *e2managererrors.RequestValidationError:
251                         e2Error, _ := err.(*e2managererrors.RequestValidationError)
252                         errorResponseDetails = models.ErrorResponse{Code: e2Error.Code, Message: e2Error.Message}
253                         httpError = http.StatusBadRequest
254                 case *e2managererrors.InvalidJsonError:
255                         e2Error, _ := err.(*e2managererrors.InvalidJsonError)
256                         errorResponseDetails = models.ErrorResponse{Code: e2Error.Code, Message: e2Error.Message}
257                         httpError = http.StatusBadRequest
258                 case *e2managererrors.RmrError:
259                         e2Error, _ := err.(*e2managererrors.RmrError)
260                         errorResponseDetails = models.ErrorResponse{Code: e2Error.Code, Message: e2Error.Message}
261                         httpError = http.StatusInternalServerError
262                 case *e2managererrors.ResourceNotFoundError:
263                         e2Error, _ := err.(*e2managererrors.ResourceNotFoundError)
264                         errorResponseDetails = models.ErrorResponse{Code: e2Error.Code, Message: e2Error.Message}
265                         httpError = http.StatusNotFound
266                 case *e2managererrors.E2TInstanceAbsenceError:
267                         e2Error, _ := err.(*e2managererrors.E2TInstanceAbsenceError)
268                         errorResponseDetails = models.ErrorResponse{Code: e2Error.Code, Message: e2Error.Message}
269                         httpError = http.StatusServiceUnavailable
270                 case *e2managererrors.RoutingManagerError:
271                         e2Error, _ := err.(*e2managererrors.RoutingManagerError)
272                         errorResponseDetails = models.ErrorResponse{Code: e2Error.Code, Message: e2Error.Message}
273                         httpError = http.StatusServiceUnavailable
274                 default:
275                         e2Error := e2managererrors.NewInternalError()
276                         errorResponseDetails = models.ErrorResponse{Code: e2Error.Code, Message: e2Error.Message}
277                         httpError = http.StatusInternalServerError
278                 }
279         }
280         errorResponse, _ := json.Marshal(errorResponseDetails)
281
282         c.logger.Errorf("[E2 Manager -> Client] #NodebController.handleErrorResponse - http status: %d, error response: %+v", httpError, errorResponseDetails)
283
284         writer.Header().Set("Content-Type", "application/json")
285         writer.WriteHeader(httpError)
286         _, err = writer.Write(errorResponse)
287 }
288
289 func (c *NodebController) prettifyRequest(request *http.Request) string {
290         dump, _ := httputil.DumpRequest(request, true)
291         requestPrettyPrint := strings.Replace(string(dump), "\r\n", " ", -1)
292         return strings.Replace(requestPrettyPrint, "\n", "", -1)
293 }