Sync Integ to Master
[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 com.google.gson.Gson;
24 import com.google.gson.GsonBuilder;
25 import com.jcabi.aspects.Loggable;
26 import fj.data.Either;
27 import io.swagger.annotations.Api;
28 import io.swagger.annotations.ApiOperation;
29 import io.swagger.annotations.ApiResponse;
30 import io.swagger.annotations.ApiResponses;
31 import org.apache.commons.lang3.tuple.Pair;
32 import org.openecomp.sdc.be.components.health.HealthCheckBusinessLogic;
33 import org.openecomp.sdc.be.components.impl.MonitoringBusinessLogic;
34 import org.openecomp.sdc.be.config.BeEcompErrorManager;
35 import org.openecomp.sdc.be.dao.api.ActionStatus;
36 import org.openecomp.sdc.be.impl.WebAppContextWrapper;
37 import org.openecomp.sdc.common.api.Constants;
38 import org.openecomp.sdc.common.api.HealthCheckInfo;
39 import org.openecomp.sdc.common.api.HealthCheckWrapper;
40 import org.openecomp.sdc.common.config.EcompErrorName;
41 import org.openecomp.sdc.common.monitoring.MonitoringEvent;
42 import org.openecomp.sdc.exception.ResponseFormat;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
45 import org.springframework.web.context.WebApplicationContext;
46
47 import javax.inject.Singleton;
48 import javax.servlet.ServletContext;
49 import javax.servlet.http.HttpServletRequest;
50 import javax.ws.rs.*;
51 import javax.ws.rs.core.Context;
52 import javax.ws.rs.core.MediaType;
53 import javax.ws.rs.core.Response;
54 import java.util.List;
55 @Loggable(prepend = true, value = Loggable.TRACE, trim = false)
56 @Path("/")
57 @Api(value = "BE Monitoring", description = "BE Monitoring")
58 @Singleton
59 public class BeMonitoringServlet extends BeGenericServlet {
60
61     Gson prettyGson = new GsonBuilder().setPrettyPrinting().create();
62
63     private static final Logger log = LoggerFactory.getLogger(ConfigServlet.class);
64
65     @GET
66     @Path("/healthCheck")
67     @Consumes(MediaType.APPLICATION_JSON)
68     @Produces(MediaType.APPLICATION_JSON)
69     @ApiOperation(value = "Return aggregate BE health check of SDC BE components", notes = "return BE health check", response = String.class)
70     @ApiResponses(value = { @ApiResponse(code = 200, message = "SDC BE components are all up"), @ApiResponse(code = 500, message = "One or more SDC BE components are down") })
71     public Response getHealthCheck(@Context final HttpServletRequest request) {
72         try {
73             HealthCheckBusinessLogic healthCheckBusinessLogic = getHealthCheckBL(request.getSession().getServletContext());
74             Pair<Boolean, List<HealthCheckInfo>> beHealthCheckInfosStatus = healthCheckBusinessLogic.getBeHealthCheckInfosStatus();
75             Boolean aggregateStatus = beHealthCheckInfosStatus.getLeft();
76             ActionStatus status = aggregateStatus ? ActionStatus.OK : ActionStatus.GENERAL_ERROR;
77             String sdcVersion = getVersionFromContext(request);
78             if (sdcVersion == null || sdcVersion.isEmpty()) {
79                 sdcVersion = "UNKNOWN";
80             }
81             String siteMode = healthCheckBusinessLogic.getSiteMode();
82             HealthCheckWrapper healthCheck = new HealthCheckWrapper(beHealthCheckInfosStatus.getRight(), sdcVersion, siteMode);
83             // The response can be either with 200 or 500 aggregate status - the
84             // body of individual statuses is returned either way
85
86             String healthCheckStr = prettyGson.toJson(healthCheck);
87             return buildOkResponse(getComponentsUtils().getResponseFormat(status), healthCheckStr);
88
89         } catch (Exception e) {
90             BeEcompErrorManager.getInstance().logBeHealthCheckError("BeHealthCheck");
91             log.debug("BE health check unexpected exception", e);
92             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
93         }
94     }
95
96     @POST
97     @Path("/monitoring")
98     @Consumes(MediaType.APPLICATION_JSON)
99     @Produces(MediaType.APPLICATION_JSON)
100     public Response processMonitoringMetrics(@Context final HttpServletRequest request, String json) {
101         try {
102             MonitoringEvent monitoringEvent = convertContentToJson(json, MonitoringEvent.class);
103             if (monitoringEvent == null) {
104                 return buildErrorResponse(getComponentsUtils().getResponseFormatAdditionalProperty(ActionStatus.GENERAL_ERROR));
105             }
106             log.trace("Received monitoring metrics: {}", monitoringEvent);
107             ServletContext context = request.getSession().getServletContext();
108             MonitoringBusinessLogic bl = getMonitoringBL(context);
109             Either<Boolean, ResponseFormat> result = bl.logMonitoringEvent(monitoringEvent);
110             if (result.isRight()) {
111                 return buildErrorResponse(result.right().value());
112             }
113             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), null);
114
115         } catch (Exception e) {
116             log.debug("BE system metrics unexpected exception", e);
117             return buildErrorResponse(getComponentsUtils().getResponseFormatAdditionalProperty(ActionStatus.GENERAL_ERROR));
118         }
119     }
120
121     @GET
122     @Path("/version")
123     @Consumes(MediaType.APPLICATION_JSON)
124     @Produces(MediaType.APPLICATION_JSON)
125     @ApiOperation(value = "return the ASDC application version", notes = "return the ASDC application version", response = String.class)
126     @ApiResponses(value = { @ApiResponse(code = 200, message = "return ASDC version"), @ApiResponse(code = 500, message = "Internal Error") })
127     public Response getSdcVersion(@Context final HttpServletRequest request) {
128         try {
129             String url = request.getMethod() + " " + request.getRequestURI();
130             log.debug("Start handle request of {}", url);
131
132             String version = getVersionFromContext(request);
133             log.debug("asdc version from manifest is: {}", version);
134             if (version == null || version.isEmpty()) {
135                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.ASDC_VERSION_NOT_FOUND));
136             }
137
138             HealthCheckInfo versionInfo = new HealthCheckInfo();
139             versionInfo.setVersion(version);
140
141             // The response can be either with 200 or 500 aggregate status - the
142             // body of individual statuses is returned either way
143             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), versionInfo);
144
145         } catch (Exception e) {
146             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("getSDCVersion");
147             log.debug("BE get ASDC version unexpected exception", e);
148             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
149         }
150     }
151
152     private String getVersionFromContext(HttpServletRequest request) {
153         ServletContext servletContext = request.getSession().getServletContext();
154         String version = (String) servletContext.getAttribute(Constants.ASDC_RELEASE_VERSION_ATTR);
155         return version;
156     }
157
158     protected MonitoringEvent convertContentToJson(String content, Class<MonitoringEvent> clazz) {
159
160         MonitoringEvent object = null;
161         try {
162             object = gson.fromJson(content, clazz);
163             object.setFields(null);
164         } catch (Exception e) {
165             log.debug("Failed to convert the content {} to object.", content.substring(0, Math.min(50, content.length())), e);
166         }
167
168         return object;
169     }
170
171     private HealthCheckBusinessLogic getHealthCheckBL(ServletContext context) {
172         WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
173         WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
174         HealthCheckBusinessLogic healthCheckBl = webApplicationContext.getBean(HealthCheckBusinessLogic.class);
175         return healthCheckBl;
176     }
177
178 }