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