[RICPLT-2165] Add rnibDataService to support retries
[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
18 package controllers
19
20 import (
21         "e2mgr/logger"
22         "e2mgr/models"
23         "e2mgr/services"
24         "e2mgr/utils"
25         "encoding/json"
26         "gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/common"
27         "github.com/golang/protobuf/jsonpb"
28         "github.com/gorilla/mux"
29         "net/http"
30         "time"
31 )
32
33 const (
34         validationErrorCode       int = 402
35         notFoundErrorCode         int = 404
36         internalErrorCode         int = 501
37         validationFailedMessage       = "Validation failed"
38         notFoundErrorMessage          = "Resource not found"
39         internalErrorMessage          = "Internal Server Error. Please try again later"
40 )
41
42 var messageChannel chan *models.E2RequestMessage
43 var errorChannel chan error
44
45 type INodebController interface {
46         GetNodebIdList (writer http.ResponseWriter, request *http.Request)
47         GetNodeb(writer http.ResponseWriter, request *http.Request)
48         HandleHealthCheckRequest(writer http.ResponseWriter, request *http.Request)
49 }
50
51 type NodebController struct {
52         rmrService         *services.RmrService
53         Logger             *logger.Logger
54         rnibDataService services.RNibDataService
55 }
56
57 func NewNodebController(logger *logger.Logger, rmrService *services.RmrService, rnibDataService services.RNibDataService) *NodebController {
58         messageChannel = make(chan *models.E2RequestMessage)
59         errorChannel = make(chan error)
60         return &NodebController{
61                 rmrService:         rmrService,
62                 Logger:             logger,
63                 rnibDataService: rnibDataService,
64         }
65 }
66
67 func (rc NodebController) GetNodebIdList (writer http.ResponseWriter, request *http.Request) {
68         startTime := time.Now()
69         nodebIdList, rnibError := rc.rnibDataService.GetListNodebIds()
70
71         if rnibError != nil {
72                 rc.Logger.Errorf("%v", rnibError);
73                 httpStatusCode, errorCode, errorMessage := rnibErrorToHttpError(rnibError)
74                 handleErrorResponse(rc.Logger, httpStatusCode, errorCode, errorMessage, writer, startTime)
75                 return;
76         }
77
78         pmList := utils.ConvertNodebIdListToProtoMessageList(nodebIdList)
79         result, err := utils.MarshalProtoMessageListToJsonArray(pmList)
80
81         if err != nil {
82                 rc.Logger.Errorf("%v", err);
83                 handleErrorResponse(rc.Logger, http.StatusInternalServerError, internalErrorCode, internalErrorMessage, writer, startTime)
84                 return;
85         }
86
87         writer.Header().Set("Content-Type", "application/json")
88         rc.Logger.Infof("[E2 Manager -> Client] #nodeb_controller.GetNodebIdList - response: %s", result)
89         writer.Write([]byte(result))
90 }
91
92 func (rc NodebController) GetNodeb(writer http.ResponseWriter, request *http.Request) {
93         startTime := time.Now()
94         vars := mux.Vars(request)
95         ranName := vars["ranName"]
96         respondingNode, rnibError := rc.rnibDataService.GetNodeb(ranName)
97         if rnibError != nil {
98                 rc.Logger.Errorf("%v", rnibError)
99                 httpStatusCode, errorCode, errorMessage := rnibErrorToHttpError(rnibError)
100                 handleErrorResponse(rc.Logger, httpStatusCode, errorCode, errorMessage, writer, startTime)
101                 return
102         }
103
104         m := jsonpb.Marshaler{}
105         result, err := m.MarshalToString(respondingNode)
106
107         if err != nil {
108                 rc.Logger.Errorf("%v", err)
109                 handleErrorResponse(rc.Logger, http.StatusInternalServerError, internalErrorCode, internalErrorMessage, writer, startTime)
110                 return
111         }
112
113         writer.Header().Set("Content-Type", "application/json")
114         rc.Logger.Infof("[E2 Manager -> Client] #nodeb_controller.GetNodeb - response: %s", result)
115         writer.Write([]byte(result))
116 }
117
118 func (rc NodebController) HandleHealthCheckRequest(writer http.ResponseWriter, request *http.Request) {
119         //fmt.Println("[X-APP -> Client] #HandleHealthCheckRequest - http status: 200")
120         writer.WriteHeader(http.StatusOK)
121 }
122
123 func handleErrorResponse(logger *logger.Logger, httpStatus int, errorCode int, errorMessage string, writer http.ResponseWriter, startTime time.Time) {
124         errorResponseDetails := models.ErrorResponse{errorCode, errorMessage}
125         errorResponse, _ := json.Marshal(errorResponseDetails)
126         printHandlingRequestElapsedTimeInMs(logger, startTime)
127         logger.Infof("[E2 Manager -> Client] #nodeb_controller.handleErrorResponse - http status: %d, error response: %+v", httpStatus, errorResponseDetails)
128         writer.Header().Set("Content-Type", "application/json")
129         writer.WriteHeader(httpStatus)
130         _, err := writer.Write(errorResponse)
131
132         if err != nil {
133                 logger.Errorf("#nodeb_controller.handleErrorResponse - Cannot send response. writer:%v", writer)
134         }
135 }
136
137 func printHandlingRequestElapsedTimeInMs(logger *logger.Logger, startTime time.Time) {
138         logger.Infof("Summary: #nodeb_controller.printElapsedTimeInMs - Elapsed time for handling request from client to E2 termination: %f ms",
139                 float64(time.Since(startTime))/float64(time.Millisecond))
140 }
141
142 func rnibErrorToHttpError(rnibError error) (int, int, string) {
143         switch rnibError.(type) {
144         case *common.ResourceNotFoundError:
145                 return http.StatusNotFound, notFoundErrorCode, notFoundErrorMessage
146         case *common.InternalError:
147                 return http.StatusInternalServerError, internalErrorCode, internalErrorMessage
148         case *common.ValidationError:
149                 return http.StatusBadRequest, validationErrorCode, validationFailedMessage
150         default:
151                 return http.StatusInternalServerError, internalErrorCode, internalErrorMessage
152         }
153 }