catalog-be servlets refactoring
[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 javax.inject.Inject;
32 import org.apache.commons.lang3.tuple.Pair;
33 import org.openecomp.sdc.be.components.health.HealthCheckBusinessLogic;
34 import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
35 import org.openecomp.sdc.be.components.impl.GroupBusinessLogic;
36 import org.openecomp.sdc.be.components.impl.MonitoringBusinessLogic;
37 import org.openecomp.sdc.be.config.BeEcompErrorManager;
38 import org.openecomp.sdc.be.dao.api.ActionStatus;
39 import org.openecomp.sdc.be.impl.ComponentsUtils;
40 import org.openecomp.sdc.be.user.UserBusinessLogic;
41 import org.openecomp.sdc.common.api.Constants;
42 import org.openecomp.sdc.common.api.HealthCheckInfo;
43 import org.openecomp.sdc.common.api.HealthCheckWrapper;
44 import org.openecomp.sdc.common.log.wrappers.Logger;
45 import org.openecomp.sdc.common.monitoring.MonitoringEvent;
46 import org.openecomp.sdc.exception.ResponseFormat;
47 import org.springframework.beans.factory.annotation.Autowired;
48
49 import javax.inject.Singleton;
50 import javax.servlet.ServletContext;
51 import javax.servlet.http.HttpServletRequest;
52 import javax.ws.rs.*;
53 import javax.ws.rs.core.Context;
54 import javax.ws.rs.core.MediaType;
55 import javax.ws.rs.core.Response;
56 import java.util.List;
57
58 @Loggable(prepend = true, value = Loggable.TRACE, trim = false)
59 @Path("/")
60 @Api(value = "BE Monitoring", description = "BE Monitoring")
61 @Singleton
62 public class BeMonitoringServlet extends BeGenericServlet {
63
64     Gson prettyGson = new GsonBuilder().setPrettyPrinting().create();
65
66     private static final Logger log = Logger.getLogger(ConfigServlet.class);
67     private final HealthCheckBusinessLogic healthCheckBusinessLogic;
68     private final MonitoringBusinessLogic monitoringBusinessLogic;
69
70     @Inject
71     public BeMonitoringServlet(UserBusinessLogic userBusinessLogic,
72         ComponentsUtils componentsUtils,
73         HealthCheckBusinessLogic healthCheckBusinessLogic,
74         MonitoringBusinessLogic monitoringBusinessLogic) {
75         super(userBusinessLogic, componentsUtils);
76         this.healthCheckBusinessLogic = healthCheckBusinessLogic;
77         this.monitoringBusinessLogic = monitoringBusinessLogic;
78     }
79
80     @GET
81     @Path("/healthCheck")
82     @Consumes(MediaType.APPLICATION_JSON)
83     @Produces(MediaType.APPLICATION_JSON)
84     @ApiOperation(value = "Return aggregate BE health check of SDC BE components", notes = "return BE health check", response = String.class)
85     @ApiResponses(value = { @ApiResponse(code = 200, message = "SDC BE components are all up"), @ApiResponse(code = 500, message = "One or more SDC BE components are down") })
86     public Response getHealthCheck(@Context final HttpServletRequest request) {
87         try {
88             Pair<Boolean, List<HealthCheckInfo>> beHealthCheckInfosStatus = healthCheckBusinessLogic.getBeHealthCheckInfosStatus();
89             Boolean aggregateStatus = beHealthCheckInfosStatus.getLeft();
90             ActionStatus status = aggregateStatus ? ActionStatus.OK : ActionStatus.GENERAL_ERROR;
91             String sdcVersion = getVersionFromContext(request);
92             if (sdcVersion == null || sdcVersion.isEmpty()) {
93                 sdcVersion = "UNKNOWN";
94             }
95             String siteMode = healthCheckBusinessLogic.getSiteMode();
96             HealthCheckWrapper healthCheck = new HealthCheckWrapper(beHealthCheckInfosStatus.getRight(), sdcVersion, siteMode);
97             // The response can be either with 200 or 500 aggregate status - the
98             // body of individual statuses is returned either way
99
100             String healthCheckStr = prettyGson.toJson(healthCheck);
101             return buildOkResponse(getComponentsUtils().getResponseFormat(status), healthCheckStr);
102
103         } catch (Exception e) {
104             BeEcompErrorManager.getInstance().logBeHealthCheckError("BeHealthCheck");
105             log.debug("BE health check unexpected exception", e);
106             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
107         }
108     }
109
110     @POST
111     @Path("/monitoring")
112     @Consumes(MediaType.APPLICATION_JSON)
113     @Produces(MediaType.APPLICATION_JSON)
114     public Response processMonitoringMetrics(@Context final HttpServletRequest request, String json) {
115         try {
116             MonitoringEvent monitoringEvent = convertContentToJson(json, MonitoringEvent.class);
117             if (monitoringEvent == null) {
118                 return buildErrorResponse(getComponentsUtils().getResponseFormatAdditionalProperty(ActionStatus.GENERAL_ERROR));
119             }
120             log.trace("Received monitoring metrics: {}", monitoringEvent);
121             Either<Boolean, ResponseFormat> result = monitoringBusinessLogic.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().logBeRestApiGeneralError("getSDCVersion");
159             log.debug("BE get ASDC version unexpected exception", e);
160             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
161         }
162     }
163
164     private String getVersionFromContext(HttpServletRequest request) {
165         ServletContext servletContext = request.getSession().getServletContext();
166         return (String) servletContext.getAttribute(Constants.ASDC_RELEASE_VERSION_ATTR);
167     }
168
169     protected MonitoringEvent convertContentToJson(String content, Class<MonitoringEvent> clazz) {
170
171         MonitoringEvent object = null;
172         try {
173             object = gson.fromJson(content, clazz);
174             object.setFields(null);
175         } catch (Exception e) {
176             log.debug("Failed to convert the content {} to object.", content.substring(0, Math.min(50, content.length())), e);
177         }
178
179         return object;
180     }
181
182 }