2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.openecomp.mso.bpmn.core;
23 import org.apache.http.client.config.RequestConfig;
24 import org.apache.http.impl.client.CloseableHttpClient;
25 import org.apache.http.impl.client.HttpClientBuilder;
26 import org.apache.http.HttpResponse;
27 import org.apache.http.HttpStatus;
28 import org.apache.http.HttpEntity;
29 import org.apache.http.client.methods.HttpPost;
30 import org.apache.http.entity.StringEntity;
32 import java.io.BufferedReader;
33 import java.io.InputStream;
34 import java.io.InputStreamReader;
35 import java.util.Base64;
37 import java.util.Properties;
38 import java.util.UUID;
40 import org.openecomp.mso.logger.MsoLogger;
41 import org.openecomp.mso.utils.UUIDChecker;
42 import org.openecomp.mso.HealthCheckUtils;
43 import org.openecomp.mso.logger.MessageEnum;
44 import org.openecomp.mso.utils.CryptoUtils;
45 import javax.ws.rs.GET;
46 import javax.ws.rs.HEAD;
47 import javax.ws.rs.Path;
48 import javax.ws.rs.Produces;
49 import javax.ws.rs.QueryParam;
50 import javax.ws.rs.core.Response;
52 import org.camunda.bpm.engine.ProcessEngines;
55 public class HealthCheckHandler {
57 private static MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL);
58 private static final String SITENAME = "mso.sitename";
59 private static final String ADPTER_ENDPOINT = "mso.adapters.db.endpoint";
60 private static final String CONFIG = "mso.bpmn.urn.properties";
61 private static final String PENGINE_PROPERTY = "processengine.properties";
62 private static final String PENGINE_PARAM = "processEngineName";
63 private static final String CREDENTIAL = "mso.adapters.db.auth";
64 private static final String MSOKEY = "mso.msoKey";
66 private static final String CHECK_HTML = "<!DOCTYPE html><html><head><meta charset=\"ISO-8859-1\"><title>Health Check</title></head><body>Application ready</body></html>";
67 private static final String NOT_FOUND = "<!DOCTYPE html><html><head><meta charset=\"ISO-8859-1\"><title>Application Not Started</title></head><body>Application not started. Properties file missing or invalid or database Connection failed</body></html>";
68 private static final String NOT_HEALTHY = "<!DOCTYPE html><html><head><meta charset=\"ISO-8859-1\"><title>Application Not Started</title></head><body>Application not available or at least one of the sub-modules is not available.</body></html>";
69 public static final Response HEALTH_CHECK_RESPONSE = Response.status (HttpStatus.SC_OK)
72 public static final Response HEALTH_CHECK_NOK_RESPONSE = Response.status (HttpStatus.SC_SERVICE_UNAVAILABLE)
75 public static final Response NOT_STARTED_RESPONSE = Response.status (HttpStatus.SC_SERVICE_UNAVAILABLE)
81 @Path("/nodehealthcheck")
82 @Produces("text/html")
83 public Response nodeHealthcheck () {
84 MsoLogger.setServiceName ("NodeHealthcheck");
85 // Generate a Request Id
86 String requestId = UUIDChecker.generateUUID(msoLogger);
88 PropertyConfiguration propertyConfiguration = PropertyConfiguration.getInstance();
89 Map<String,String> props = propertyConfiguration.getProperties(CONFIG);
93 msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.AvailabilityError, "Unable to load " + CONFIG);
95 return NOT_STARTED_RESPONSE;
98 String siteName = props.get(SITENAME);
99 String endpoint = props.get(ADPTER_ENDPOINT);
101 if (null == siteName || siteName.length () == 0 || null == endpoint || endpoint.length () == 0) {
103 msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.DataError, "Unable to load key attributes (" + SITENAME + " or " + ADPTER_ENDPOINT + ") from the config file:" + CONFIG);
105 return NOT_STARTED_RESPONSE;
109 if (!this.getSiteStatus (endpoint, siteName, props.get(CREDENTIAL), props.get(MSOKEY))) {
110 msoLogger.debug("This site is currently disabled for maintenance.");
111 return HEALTH_CHECK_NOK_RESPONSE;
113 } catch (Exception e) {
115 msoLogger.error(MessageEnum.GENERAL_EXCEPTION_ARG, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception while getting SiteStatus", e);
117 msoLogger.debug("Exception while getting SiteStatus");
118 return NOT_STARTED_RESPONSE;
122 HealthCheckUtils healthCheck = new HealthCheckUtils ();
123 if (healthCheck.verifyNodeHealthCheck(HealthCheckUtils.NodeType.BPMN, requestId)) {
124 msoLogger.debug("nodeHealthcheck - Successful");
125 return HealthCheckUtils.HEALTH_CHECK_RESPONSE;
127 msoLogger.debug("nodeHealthcheck - At leaset one of the sub-modules is not available.");
128 return HealthCheckUtils.HEALTH_CHECK_NOK_RESPONSE;
134 @Path("/healthcheck")
135 @Produces("text/html")
136 public Response healthcheck (@QueryParam("requestId") String requestId) {
137 MsoLogger.setServiceName ("Healthcheck");
138 verifyOldUUID(requestId);
140 PropertyConfiguration propertyConfiguration = PropertyConfiguration.getInstance();
141 Map<String,String> props = propertyConfiguration.getProperties(CONFIG);
145 msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.AvailabilityError, "Unable to load " + CONFIG);
147 return NOT_STARTED_RESPONSE;
150 String siteName = props.get(SITENAME);
151 String endpoint = props.get(ADPTER_ENDPOINT);
153 if (null == siteName || siteName.length () == 0 || null == endpoint || endpoint.length () == 0) {
155 msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.DataError, "Unable to load key attributes (" + SITENAME + " or " + ADPTER_ENDPOINT + ") from the config file:" + CONFIG);
157 return NOT_STARTED_RESPONSE;
161 if (!this.getSiteStatus (endpoint, siteName, props.get(CREDENTIAL), props.get(MSOKEY))) {
162 msoLogger.debug("This site is currently disabled for maintenance.");
163 return HEALTH_CHECK_NOK_RESPONSE;
165 } catch (Exception e) {
167 msoLogger.error(MessageEnum.GENERAL_EXCEPTION_ARG, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception while getting SiteStatus", e);
169 msoLogger.debug("Exception while getting SiteStatus");
170 return NOT_STARTED_RESPONSE;
174 InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(PENGINE_PROPERTY);
175 Properties prop = new Properties();
177 String [] engineNames = prop.getProperty(PENGINE_PARAM).split(",");
178 for (String engine : engineNames) {
179 ProcessEngines.getProcessEngine(engine).getIdentityService().createGroupQuery().list();
181 } catch (final Exception e) {
183 msoLogger.error(MessageEnum.GENERAL_EXCEPTION_ARG, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception while verifying Camunda engine", e);
185 msoLogger.debug("Exception while verifying Camunda engine");
186 return NOT_STARTED_RESPONSE;
189 return HEALTH_CHECK_RESPONSE;
193 private String verifyOldUUID (String oldId) {
194 if (!isValidUUID(oldId)) {
195 String newId = UUID.randomUUID().toString();
196 MsoLogger.setLogContext(newId, null);
199 MsoLogger.setLogContext(oldId, null);
204 private boolean isValidUUID (String id) {
209 UUID uuid = UUID.fromString(id);
210 return uuid.toString().equalsIgnoreCase(id);
211 } catch (IllegalArgumentException iae) {
216 private String decrypt(String encryptedString, String key){
218 if (encryptedString != null || !encryptedString.isEmpty() && key != null && !key.isEmpty()) {
219 return CryptoUtils.decrypt(encryptedString, key);
221 } catch (Exception e) {
222 msoLogger.error(MessageEnum.GENERAL_EXCEPTION_ARG, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Failed to decrypt credentials", e);
227 private boolean getSiteStatus (String url, String site, String credential, String key) throws Exception {
228 // set the connection timeout value to 30 seconds (30000 milliseconds)
229 RequestConfig.Builder requestBuilder = RequestConfig.custom();
230 requestBuilder = requestBuilder.setConnectTimeout(30000);
231 requestBuilder = requestBuilder.setConnectionRequestTimeout(30000);
232 HttpClientBuilder builder = HttpClientBuilder.create ();
233 builder.setDefaultRequestConfig (requestBuilder.build ());
235 HttpPost post = new HttpPost(url);
237 String cred = decrypt(credential, key);
238 if (cred != null && !cred.isEmpty()) {
239 post.setHeader("Authorization", "Basic " + Base64.getEncoder().encodeToString(cred.getBytes()));
241 msoLogger.debug("Post url is: " + url);
243 //now create a soap request message as follows:
244 final StringBuffer payload = new StringBuffer();
245 payload.append("\n");
246 payload.append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:req=\"http://org.openecomp.mso/requestsdb\">\n");
247 payload.append("<soapenv:Header/>\n");
248 payload.append("<soapenv:Body>\n");
249 payload.append("<req:getSiteStatus>\n");
250 payload.append("<siteName>" + site + "</siteName>\n");
251 payload.append("</req:getSiteStatus>\n");
252 payload.append("</soapenv:Body>\n");
253 payload.append("</soapenv:Envelope>\n");
255 msoLogger.debug ("Initialize SOAP request to url:" + url);
256 msoLogger.debug ("The payload of the request is:" + payload);
257 HttpEntity entity = new StringEntity(payload.toString(),"UTF-8");
258 post.setEntity(entity);
260 CloseableHttpClient client = builder.build ();
261 HttpResponse response = client.execute(post);
262 msoLogger.debug("Response received is:" + response);
264 int statusCode = response.getStatusLine().getStatusCode();
265 if (statusCode != 200) {
267 msoLogger.error(MessageEnum.GENERAL_EXCEPTION_ARG, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.DataError,
268 "Communication with DB Adapter failed, The response received from DB Adapter is with failed status code:" + statusCode);
270 Exception e = new Exception("Communication with DB Adapter failed");
273 BufferedReader rd = new BufferedReader(
274 new InputStreamReader(response.getEntity().getContent()));
276 StringBuffer result = new StringBuffer();
278 while ((line = rd.readLine()) != null) {
281 msoLogger.debug("Content of the response is:" + result);
282 String status = result.substring(result.indexOf("<return>") + 8, result.indexOf("</return>"));
284 client.close (); //shut down the connection
285 return Boolean.valueOf(status);