Update release version to 5.4.7
[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 const ApplicationJson = "application/json"
44 const ContentType = "Content-Type"
45
46 type INodebController interface {
47         Shutdown(writer http.ResponseWriter, r *http.Request)
48         X2Reset(writer http.ResponseWriter, r *http.Request)
49         GetNodeb(writer http.ResponseWriter, r *http.Request)
50         UpdateGnb(writer http.ResponseWriter, r *http.Request)
51         UpdateEnb(writer http.ResponseWriter, r *http.Request)
52         GetNodebIdList(writer http.ResponseWriter, r *http.Request)
53         SetGeneralConfiguration(writer http.ResponseWriter, r *http.Request)
54         AddEnb(writer http.ResponseWriter, r *http.Request)
55         DeleteEnb(writer http.ResponseWriter, r *http.Request)
56 }
57
58 type NodebController struct {
59         logger          *logger.Logger
60         handlerProvider *httpmsghandlerprovider.IncomingRequestHandlerProvider
61 }
62
63 func NewNodebController(logger *logger.Logger, handlerProvider *httpmsghandlerprovider.IncomingRequestHandlerProvider) *NodebController {
64         return &NodebController{
65                 logger:          logger,
66                 handlerProvider: handlerProvider,
67         }
68 }
69
70 func (c *NodebController) GetNodebIdList(writer http.ResponseWriter, r *http.Request) {
71         c.logger.Infof("[Client -> E2 Manager] #NodebController.GetNodebIdList - request: %v", c.prettifyRequest(r))
72
73         c.handleRequest(writer, &r.Header, httpmsghandlerprovider.GetNodebIdListRequest, nil, false, http.StatusOK)
74 }
75
76 func (c *NodebController) GetNodeb(writer http.ResponseWriter, r *http.Request) {
77         c.logger.Infof("[Client -> E2 Manager] #NodebController.GetNodeb - request: %v", c.prettifyRequest(r))
78         vars := mux.Vars(r)
79         ranName := vars["ranName"]
80         request := models.GetNodebRequest{RanName: ranName}
81         c.handleRequest(writer, &r.Header, httpmsghandlerprovider.GetNodebRequest, request, false, http.StatusOK)
82 }
83
84 func (c *NodebController) UpdateGnb(writer http.ResponseWriter, r *http.Request) {
85         c.logger.Infof("[Client -> E2 Manager] #NodebController.UpdateGnb - request: %v", c.prettifyRequest(r))
86         vars := mux.Vars(r)
87         ranName := vars[ParamRanName]
88
89         request := models.UpdateGnbRequest{}
90
91         gnb := entities.Gnb{}
92
93         if !c.extractRequestBodyToProto(r, &gnb, writer) {
94                 return
95         }
96
97         request.Gnb = &gnb
98         request.RanName = ranName
99         c.handleRequest(writer, &r.Header, httpmsghandlerprovider.UpdateGnbRequest, &request, true, http.StatusOK)
100 }
101
102 func (c *NodebController) UpdateEnb(writer http.ResponseWriter, r *http.Request) {
103         c.logger.Infof("[Client -> E2 Manager] #NodebController.UpdateEnb - request: %v", c.prettifyRequest(r))
104
105         defer r.Body.Close()
106         body, err := ioutil.ReadAll(r.Body)
107
108         if err != nil {
109                 c.logger.Errorf("[Client -> E2 Manager] #NodebController.UpdateEnb - unable to read request body - error: %s", err)
110                 c.handleErrorResponse(e2managererrors.NewInvalidJsonError(), writer)
111                 return
112         }
113
114         updateEnbRequest := models.UpdateEnbRequest{}
115         err = json.Unmarshal(body, &updateEnbRequest)
116
117         if err != nil {
118                 c.logger.Errorf("[Client -> E2 Manager] #NodebController.UpdateEnb - unable to unmarshal json - error: %s", err)
119                 c.handleErrorResponse(e2managererrors.NewInvalidJsonError(), writer)
120                 return
121         }
122
123         vars := mux.Vars(r)
124         ranName := vars[ParamRanName]
125
126         updateEnbRequest.RanName = ranName
127
128         c.handleRequest(writer, &r.Header, httpmsghandlerprovider.UpdateEnbRequest, &updateEnbRequest, true, http.StatusOK)
129 }
130
131 func (c *NodebController) AddEnb(writer http.ResponseWriter, r *http.Request) {
132         c.logger.Infof("[Client -> E2 Manager] #NodebController.AddEnb - request: %v", c.prettifyRequest(r))
133
134         defer r.Body.Close()
135         body, err := ioutil.ReadAll(r.Body)
136
137         if err != nil {
138                 c.logger.Errorf("[Client -> E2 Manager] #NodebController.AddEnb - unable to read request body - error: %s", err)
139                 c.handleErrorResponse(e2managererrors.NewInvalidJsonError(), writer)
140                 return
141         }
142
143         addEnbRequest := models.AddEnbRequest{}
144         err = json.Unmarshal(body, &addEnbRequest)
145
146         if err != nil {
147                 c.logger.Errorf("[Client -> E2 Manager] #NodebController.AddEnb - unable to unmarshal json - error: %s", err)
148                 c.handleErrorResponse(e2managererrors.NewInvalidJsonError(), writer)
149                 return
150         }
151
152         c.handleRequest(writer, &r.Header, httpmsghandlerprovider.AddEnbRequest, &addEnbRequest, true, http.StatusCreated)
153 }
154
155 func (c *NodebController) DeleteEnb(writer http.ResponseWriter, r *http.Request) {
156         c.logger.Infof("[Client -> E2 Manager] #NodebController.DeleteEnb - request: %v", c.prettifyRequest(r))
157         vars := mux.Vars(r)
158         ranName := vars["ranName"]
159         request := &models.DeleteEnbRequest{RanName: ranName}
160         c.handleRequest(writer, &r.Header, httpmsghandlerprovider.DeleteEnbRequest, request, true, http.StatusNoContent)
161 }
162
163 func (c *NodebController) SetGeneralConfiguration(writer http.ResponseWriter, r *http.Request) {
164         c.logger.Infof("[Client -> E2 Manager] #NodebController.SetGeneralConfiguration - request: %v", c.prettifyRequest(r))
165
166         request := models.GeneralConfigurationRequest{}
167
168         if !c.extractJsonBodyDisallowUnknownFields(r, &request, writer) {
169                 return
170         }
171         c.handleRequest(writer, &r.Header, httpmsghandlerprovider.SetGeneralConfigurationRequest, request, false, http.StatusOK)
172 }
173
174 func (c *NodebController) Shutdown(writer http.ResponseWriter, r *http.Request) {
175         c.logger.Infof("[Client -> E2 Manager] #NodebController.Shutdown - request: %v", c.prettifyRequest(r))
176         c.handleRequest(writer, &r.Header, httpmsghandlerprovider.ShutdownRequest, nil, false, http.StatusNoContent)
177 }
178
179 func (c *NodebController) X2Reset(writer http.ResponseWriter, r *http.Request) {
180         c.logger.Infof("[Client -> E2 Manager] #NodebController.X2Reset - request: %v", c.prettifyRequest(r))
181         request := models.ResetRequest{}
182         vars := mux.Vars(r)
183         ranName := vars[ParamRanName]
184
185         if err := c.extractJsonBody(r, &request); err != nil {
186                 c.handleErrorResponse(err, writer)
187                 return
188         }
189         request.RanName = ranName
190         c.handleRequest(writer, &r.Header, httpmsghandlerprovider.ResetRequest, request, false, http.StatusNoContent)
191 }
192
193 func (c *NodebController) extractRequestBodyToProto(r *http.Request, pb proto.Message, writer http.ResponseWriter) bool {
194         defer r.Body.Close()
195
196         err := jsonpb.Unmarshal(r.Body, pb)
197
198         if err != nil {
199                 c.logger.Errorf("[Client -> E2 Manager] #NodebController.extractJsonBody - unable to extract json body - error: %s", err)
200                 c.handleErrorResponse(e2managererrors.NewInvalidJsonError(), writer)
201                 return false
202         }
203
204         return true
205 }
206
207 func (c *NodebController) extractJsonBodyDisallowUnknownFields(r *http.Request, request models.Request, writer http.ResponseWriter) bool {
208         defer r.Body.Close()
209
210         decoder := json.NewDecoder(r.Body)
211         decoder.DisallowUnknownFields()
212
213         if err := decoder.Decode(&request); err != nil {
214                 c.logger.Errorf("[Client -> E2 Manager] #NodebController.extractJsonBody - unable to extract json body - error: %s", err)
215                 c.handleErrorResponse(e2managererrors.NewInvalidJsonError(), writer)
216                 return false
217         }
218
219         return true
220 }
221
222 func (c *NodebController) extractJsonBody(r *http.Request, request models.Request) error {
223         defer r.Body.Close()
224         body, err := ioutil.ReadAll(io.LimitReader(r.Body, LimitRequest))
225
226         if err != nil {
227                 c.logger.Errorf("[Client -> E2 Manager] #NodebController.extractJsonBody - unable to extract json body - error: %s", err)
228                 return e2managererrors.NewInvalidJsonError()
229         }
230
231         err = json.Unmarshal(body, &request)
232         if err != nil {
233                 c.logger.Errorf("[Client -> E2 Manager] #NodebController.extractJsonBody - unable to extract json body - error: %s", err)
234                 return e2managererrors.NewInvalidJsonError()
235         }
236
237         return nil
238 }
239
240 func (c *NodebController) handleRequest(writer http.ResponseWriter, header *http.Header, requestName httpmsghandlerprovider.IncomingRequest, request models.Request, validateRequestHeaders bool, successStatusCode int) {
241
242         if validateRequestHeaders {
243
244                 err := c.validateRequestHeader(header)
245                 if err != nil {
246                         c.handleErrorResponse(err, writer)
247                         return
248                 }
249         }
250
251         handler, err := c.handlerProvider.GetHandler(requestName)
252
253         if err != nil {
254                 c.handleErrorResponse(err, writer)
255                 return
256         }
257
258         response, err := handler.Handle(request)
259
260         if err != nil {
261                 c.handleErrorResponse(err, writer)
262                 return
263         }
264
265         if successStatusCode == http.StatusNoContent {
266                 writer.WriteHeader(successStatusCode)
267                 c.logger.Infof("[E2 Manager -> Client] #NodebController.handleRequest - status response: %v", http.StatusNoContent)
268                 return
269         }
270
271         result, err := response.Marshal()
272
273         if err != nil {
274                 c.handleErrorResponse(err, writer)
275                 return
276         }
277
278         c.logger.Infof("[E2 Manager -> Client] #NodebController.handleRequest - response: %s", result)
279         writer.Header().Set(ContentType, ApplicationJson)
280         writer.WriteHeader(successStatusCode)
281         writer.Write(result)
282 }
283
284 func (c *NodebController) validateRequestHeader(header *http.Header) error {
285
286         if header.Get(ContentType) != ApplicationJson {
287                 c.logger.Errorf("#NodebController.validateRequestHeader - validation failure, incorrect content type")
288
289                 return e2managererrors.NewHeaderValidationError()
290         }
291         return nil
292 }
293
294 func (c *NodebController) handleErrorResponse(err error, writer http.ResponseWriter) {
295
296         var errorResponseDetails models.ErrorResponse
297         var httpError int
298
299         if err != nil {
300                 switch err.(type) {
301                 case *e2managererrors.RnibDbError:
302                         e2Error, _ := err.(*e2managererrors.RnibDbError)
303                         errorResponseDetails = models.ErrorResponse{Code: e2Error.Code, Message: e2Error.Message}
304                         httpError = http.StatusInternalServerError
305                 case *e2managererrors.CommandAlreadyInProgressError:
306                         e2Error, _ := err.(*e2managererrors.CommandAlreadyInProgressError)
307                         errorResponseDetails = models.ErrorResponse{Code: e2Error.Code, Message: e2Error.Message}
308                         httpError = http.StatusMethodNotAllowed
309                 case *e2managererrors.HeaderValidationError:
310                         e2Error, _ := err.(*e2managererrors.HeaderValidationError)
311                         errorResponseDetails = models.ErrorResponse{Code: e2Error.Code, Message: e2Error.Message}
312                         httpError = http.StatusUnsupportedMediaType
313                 case *e2managererrors.WrongStateError:
314                         e2Error, _ := err.(*e2managererrors.WrongStateError)
315                         errorResponseDetails = models.ErrorResponse{Code: e2Error.Code, Message: e2Error.Message}
316                         httpError = http.StatusBadRequest
317                 case *e2managererrors.RequestValidationError:
318                         e2Error, _ := err.(*e2managererrors.RequestValidationError)
319                         errorResponseDetails = models.ErrorResponse{Code: e2Error.Code, Message: e2Error.Message}
320                         httpError = http.StatusBadRequest
321                 case *e2managererrors.InvalidJsonError:
322                         e2Error, _ := err.(*e2managererrors.InvalidJsonError)
323                         errorResponseDetails = models.ErrorResponse{Code: e2Error.Code, Message: e2Error.Message}
324                         httpError = http.StatusBadRequest
325                 case *e2managererrors.RmrError:
326                         e2Error, _ := err.(*e2managererrors.RmrError)
327                         errorResponseDetails = models.ErrorResponse{Code: e2Error.Code, Message: e2Error.Message}
328                         httpError = http.StatusInternalServerError
329                 case *e2managererrors.ResourceNotFoundError:
330                         e2Error, _ := err.(*e2managererrors.ResourceNotFoundError)
331                         errorResponseDetails = models.ErrorResponse{Code: e2Error.Code, Message: e2Error.Message}
332                         httpError = http.StatusNotFound
333                 case *e2managererrors.E2TInstanceAbsenceError:
334                         e2Error, _ := err.(*e2managererrors.E2TInstanceAbsenceError)
335                         errorResponseDetails = models.ErrorResponse{Code: e2Error.Code, Message: e2Error.Message}
336                         httpError = http.StatusServiceUnavailable
337                 case *e2managererrors.RoutingManagerError:
338                         e2Error, _ := err.(*e2managererrors.RoutingManagerError)
339                         errorResponseDetails = models.ErrorResponse{Code: e2Error.Code, Message: e2Error.Message}
340                         httpError = http.StatusServiceUnavailable
341                 case *e2managererrors.NodebExistsError:
342                         e2Error, _ := err.(*e2managererrors.NodebExistsError)
343                         errorResponseDetails = models.ErrorResponse{Code: e2Error.Code, Message: e2Error.Message}
344                         httpError = http.StatusBadRequest
345                 default:
346                         e2Error := e2managererrors.NewInternalError()
347                         errorResponseDetails = models.ErrorResponse{Code: e2Error.Code, Message: e2Error.Message}
348                         httpError = http.StatusInternalServerError
349                 }
350         }
351         errorResponse, _ := json.Marshal(errorResponseDetails)
352
353         c.logger.Errorf("[E2 Manager -> Client] #NodebController.handleErrorResponse - http status: %d, error response: %+v", httpError, errorResponseDetails)
354
355         writer.Header().Set(ContentType, ApplicationJson)
356         writer.WriteHeader(httpError)
357         _, err = writer.Write(errorResponse)
358 }
359
360 func (c *NodebController) prettifyRequest(request *http.Request) string {
361         dump, _ := httputil.DumpRequest(request, true)
362         requestPrettyPrint := strings.Replace(string(dump), "\r\n", " ", -1)
363         return strings.Replace(requestPrettyPrint, "\n", "", -1)
364 }