[sdc] update to the current code base
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / servlets / BeMonitoringServlet.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.openecomp.sdc.be.servlets;
22
23 import java.util.List;
24
25 import javax.inject.Singleton;
26 import javax.servlet.ServletContext;
27 import javax.servlet.http.HttpServletRequest;
28 import javax.ws.rs.Consumes;
29 import javax.ws.rs.GET;
30 import javax.ws.rs.POST;
31 import javax.ws.rs.Path;
32 import javax.ws.rs.Produces;
33 import javax.ws.rs.core.Context;
34 import javax.ws.rs.core.MediaType;
35 import javax.ws.rs.core.Response;
36
37 import org.openecomp.sdc.be.components.impl.HealthCheckBusinessLogic;
38 import org.openecomp.sdc.be.components.impl.MonitoringBusinessLogic;
39 import org.openecomp.sdc.be.config.BeEcompErrorManager;
40 import org.openecomp.sdc.be.dao.api.ActionStatus;
41 import org.openecomp.sdc.be.impl.WebAppContextWrapper;
42 import org.openecomp.sdc.common.api.Constants;
43 import org.openecomp.sdc.common.api.HealthCheckInfo;
44 import org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckComponent;
45 import org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus;
46 import org.openecomp.sdc.common.api.HealthCheckWrapper;
47 import org.openecomp.sdc.common.config.EcompErrorName;
48 import org.openecomp.sdc.common.monitoring.MonitoringEvent;
49 import org.openecomp.sdc.exception.ResponseFormat;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
52 import org.springframework.web.context.WebApplicationContext;
53
54 import com.google.gson.Gson;
55 import com.google.gson.GsonBuilder;
56 import com.jcabi.aspects.Loggable;
57 import com.wordnik.swagger.annotations.Api;
58 import com.wordnik.swagger.annotations.ApiOperation;
59 import com.wordnik.swagger.annotations.ApiResponse;
60 import com.wordnik.swagger.annotations.ApiResponses;
61
62 import fj.data.Either;
63
64 @Loggable(prepend = true, value = Loggable.TRACE, trim = false)
65 @Path("/")
66 @Api(value = "BE Monitoring", description = "BE Monitoring")
67 @Singleton
68 public class BeMonitoringServlet extends BeGenericServlet {
69
70         Gson prettyGson = new GsonBuilder().setPrettyPrinting().create();
71
72         private static Logger log = LoggerFactory.getLogger(ConfigServlet.class.getName());
73
74         @GET
75         @Path("/healthCheck")
76         @Consumes(MediaType.APPLICATION_JSON)
77         @Produces(MediaType.APPLICATION_JSON)
78         @ApiOperation(value = "return aggregate BE health check of Titan, ES and BE", notes = "return BE health check", response = String.class)
79         @ApiResponses(value = { @ApiResponse(code = 200, message = "Titan, ES and BE are all up"), @ApiResponse(code = 500, message = "One or more BE components (Titan, ES, BE) are down") })
80         public Response getHealthCheck(@Context final HttpServletRequest request) {
81                 try {
82                         HealthCheckBusinessLogic healthCheckBusinessLogic = getHealthCheckBL(request.getSession().getServletContext());
83                         List<HealthCheckInfo> beHealthCheckInfos = healthCheckBusinessLogic.getBeHealthCheckInfosStatus();
84
85                         // List<HealthCheckInfo> beHealthCheckInfos =
86                         // HealthCheckBusinessLogic.getInstance().getBeHealthCheckInfos(request.getSession().getServletContext());
87                         ActionStatus status = getAggregateBeStatus(beHealthCheckInfos);
88                         String sdcVersion = getVersionFromContext(request);
89                         if (sdcVersion == null || sdcVersion.isEmpty()) {
90                                 sdcVersion = "UNKNOWN";
91                         }
92                         String siteMode = healthCheckBusinessLogic.getSiteMode();
93                         HealthCheckWrapper healthCheck = new HealthCheckWrapper(beHealthCheckInfos, sdcVersion, siteMode);
94                         // The response can be either with 200 or 500 aggregate status - the
95                         // body of individual statuses is returned either way
96
97                         String healthCheckStr = prettyGson.toJson(healthCheck);
98                         return buildOkResponse(getComponentsUtils().getResponseFormat(status), healthCheckStr);
99
100                 } catch (Exception e) {
101                         BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeHealthCheckError, "BeHealthCheck");
102                         BeEcompErrorManager.getInstance().logBeHealthCheckError("BeHealthCheck");
103                         log.debug("BE health check unexpected exception", e);
104                         return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
105                 }
106         }
107
108         @POST
109         @Path("/monitoring")
110         @Consumes(MediaType.APPLICATION_JSON)
111         @Produces(MediaType.APPLICATION_JSON)
112         public Response processMonitoringMetrics(@Context final HttpServletRequest request, String json) {
113                 try {
114                         MonitoringEvent monitoringEvent = convertContentToJson(json, MonitoringEvent.class);
115                         if (monitoringEvent == null) {
116                                 return buildErrorResponse(getComponentsUtils().getResponseFormatAdditionalProperty(ActionStatus.GENERAL_ERROR));
117                         }
118                         log.trace("Received monitoring metrics: {}", monitoringEvent.toString());
119                         ServletContext context = request.getSession().getServletContext();
120                         MonitoringBusinessLogic bl = getMonitoringBL(context);
121                         Either<Boolean, ResponseFormat> result = bl.logMonitoringEvent(monitoringEvent);
122                         if (result.isRight()) {
123                                 return buildErrorResponse(result.right().value());
124                         }
125                         return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), null);
126
127                 } catch (Exception e) {
128                         log.debug("BE system metrics unexpected exception", e);
129                         return buildErrorResponse(getComponentsUtils().getResponseFormatAdditionalProperty(ActionStatus.GENERAL_ERROR));
130                 }
131         }
132
133         @GET
134         @Path("/version")
135         @Consumes(MediaType.APPLICATION_JSON)
136         @Produces(MediaType.APPLICATION_JSON)
137         @ApiOperation(value = "return the ASDC application version", notes = "return the ASDC application version", response = String.class)
138         @ApiResponses(value = { @ApiResponse(code = 200, message = "return ASDC version"), @ApiResponse(code = 500, message = "Internal Error") })
139         public Response getSdcVersion(@Context final HttpServletRequest request) {
140                 try {
141                         String url = request.getMethod() + " " + request.getRequestURI();
142                         log.debug("Start handle request of {}", url);
143
144                         String version = getVersionFromContext(request);
145                         log.debug("asdc version from manifest is: {}", version);
146                         if (version == null || version.isEmpty()) {
147                                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.ASDC_VERSION_NOT_FOUND));
148                         }
149
150                         HealthCheckInfo versionInfo = new HealthCheckInfo();
151                         versionInfo.setVersion(version);
152
153                         // The response can be either with 200 or 500 aggregate status - the
154                         // body of individual statuses is returned either way
155                         return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), versionInfo);
156
157                 } catch (Exception e) {
158                         BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "getSDCVersion");
159                         BeEcompErrorManager.getInstance().logBeRestApiGeneralError("getSDCVersion");
160                         log.debug("BE get ASDC version unexpected exception", e);
161                         return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
162                 }
163         }
164
165         private String getVersionFromContext(HttpServletRequest request) {
166                 ServletContext servletContext = request.getSession().getServletContext();
167                 String version = (String) servletContext.getAttribute(Constants.ASDC_RELEASE_VERSION_ATTR);
168                 return version;
169         }
170
171         private ActionStatus getAggregateBeStatus(List<HealthCheckInfo> beHealthCheckInfos) {
172                 ActionStatus status = ActionStatus.OK;
173                 for (HealthCheckInfo healthCheckInfo : beHealthCheckInfos) {
174                         if (healthCheckInfo.getHealthCheckStatus().equals(HealthCheckStatus.DOWN) && healthCheckInfo.getHealthCheckComponent() != HealthCheckComponent.DE) {
175                                 status = ActionStatus.GENERAL_ERROR;
176                                 break;
177                         }
178                 }
179                 return status;
180         }
181
182         protected MonitoringEvent convertContentToJson(String content, Class<MonitoringEvent> clazz) {
183
184                 MonitoringEvent object = null;
185                 try {
186                         object = gson.fromJson(content, clazz);
187                         object.setFields(null);
188                 } catch (Exception e) {
189                         log.debug("Failed to convert the content {} to object.", content.substring(0, Math.min(50, content.length())), e);
190                 }
191
192                 return object;
193         }
194
195         private HealthCheckBusinessLogic getHealthCheckBL(ServletContext context) {
196                 WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
197                 WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
198                 HealthCheckBusinessLogic healthCheckBl = webApplicationContext.getBean(HealthCheckBusinessLogic.class);
199                 return healthCheckBl;
200         }
201
202 }