Initial OpenECOMP MSO commit
[so.git] / status-control / src / main / java / org / openecomp / mso / HealthCheckUtils.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * OPENECOMP - MSO
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.mso;
22
23
24 import org.openecomp.mso.db.catalog.CatalogDatabase;
25 import org.openecomp.mso.logger.MessageEnum;
26 import org.openecomp.mso.logger.MsoLogger;
27 import org.openecomp.mso.properties.MsoJavaProperties;
28 import org.openecomp.mso.properties.MsoJsonProperties;
29 import org.openecomp.mso.properties.MsoPropertiesFactory;
30 import org.openecomp.mso.requestsdb.RequestsDatabase;
31 import org.openecomp.mso.utils.UUIDChecker;
32 import org.apache.http.HttpEntity;
33 import org.apache.http.HttpResponse;
34 import org.apache.http.HttpStatus;
35 import org.apache.http.client.config.RequestConfig;
36 import org.apache.http.client.methods.HttpGet;
37 import org.apache.http.client.methods.HttpPost;
38 import org.apache.http.entity.StringEntity;
39 import org.apache.http.impl.client.CloseableHttpClient;
40 import org.apache.http.impl.client.HttpClientBuilder;
41
42 import javax.ws.rs.core.Response;
43
44 public class HealthCheckUtils {
45
46     private static MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.GENERAL);
47     private final static String MSO_PROP_TOPOLOGY = "MSO_PROP_TOPOLOGY";
48     private static MsoPropertiesFactory msoPropertiesFactory = new MsoPropertiesFactory();
49     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>";
50     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>";
51     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>";
52     public static final Response HEALTH_CHECK_RESPONSE = Response.status (HttpStatus.SC_OK)
53             .entity (CHECK_HTML)
54             .build ();
55     public static final Response HEALTH_CHECK_NOK_RESPONSE = Response.status (HttpStatus.SC_SERVICE_UNAVAILABLE)
56             .entity (NOT_HEALTHY)
57             .  build ();
58     public static final Response NOT_STARTED_RESPONSE = Response.status (HttpStatus.SC_SERVICE_UNAVAILABLE)
59             .entity (NOT_FOUND)
60             .build ();
61
62     public enum NodeType {APIH, RA};
63
64     public boolean catalogDBCheck (MsoLogger subMsoLogger, long startTime) {
65         try (CatalogDatabase catalogDB = new CatalogDatabase ()) {
66             catalogDB.healthCheck ();
67         } catch (Exception e) {
68             subMsoLogger.error(MessageEnum.GENERAL_EXCEPTION, "", "HealthCheck", MsoLogger.ErrorCode.DataError, "Failed to check catalog database", e);
69             subMsoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.DBAccessError, "Exception during healthcheck");
70             return false;
71         }
72         return true;
73     }
74
75     public boolean requestDBCheck (MsoLogger subMsoLogger, long startTime) {
76         try {
77             RequestsDatabase.healthCheck ();
78         } catch (Exception e) {
79             subMsoLogger.error(MessageEnum.GENERAL_EXCEPTION, "", "HealthCheck", MsoLogger.ErrorCode.DataError, "Failed to check request database", e);
80             subMsoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.ServiceNotAvailable, "Exception during local healthcheck");
81             return false;
82         }
83         return true;
84     }
85
86     public boolean siteStatusCheck (MsoLogger subMsoLogger, long startTime) {
87         // Check the Site Status value in DB first, if set to false, return NOK
88         String site = getProperty("site-name");
89
90         MsoStatusUtil statusUtil = new MsoStatusUtil ();
91         if (!statusUtil.getSiteStatus (site)) {
92             subMsoLogger.debug("This site is currently disabled for maintenance.");
93             return false;
94         }
95         return true;
96     }
97
98     public boolean configFileCheck (MsoLogger subMsoLogger, long startTime, String propertiesFile) {
99         if (null != propertiesFile) {
100             MsoJavaProperties props = loadMsoProperties (propertiesFile);
101             if (props == null) {
102                 subMsoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.ServiceNotAvailable, "Configuration file can not be loaded");
103                 return false;
104             }
105         }
106         return true;
107     }
108
109
110     private MsoJavaProperties loadMsoProperties (String fileName) {
111         MsoJavaProperties msoProperties;
112         try {
113             msoProperties = msoPropertiesFactory.getMsoJavaProperties(fileName);
114         } catch (Exception e) {
115             msoLogger.error (MessageEnum.LOAD_PROPERTIES_FAIL, fileName, "", "HealthCheck", MsoLogger.ErrorCode.DataError, "Failed to load topology properties", e);
116             return null;
117         }
118         if (msoProperties !=null && msoProperties.size() > 0) {
119             return msoProperties;
120         } else {
121             msoLogger.error (MessageEnum.NO_PROPERTIES, fileName, "", "HealthCheck", MsoLogger.ErrorCode.DataError, "No topology properties");
122             return  null;
123         }
124     }
125
126     protected boolean verifyLocalHealth(String ip, String apiPort, String url, String sslEnabled, String requestId) {
127         String finalUrl = getFinalUrl(ip, apiPort, url, sslEnabled);
128         long startTime = System.currentTimeMillis ();
129         if (null != requestId) {
130             finalUrl = finalUrl + "?requestId=" + requestId;
131         }
132         try (CloseableHttpClient client = getHttpClient()) {
133             HttpResponse response;
134             HttpGet get = new HttpGet(finalUrl);
135             msoLogger.debug("Get url is: " + finalUrl);
136             response = client.execute(get);
137             msoLogger.debug("Get response is: " + response);
138             if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
139                 msoLogger.debug("verifyLocalHealth - Successfully communicate with APIH/BPMN/RA");
140                 return true;
141             }
142             msoLogger.debug("verifyLocalHealth - Service not available");
143         } catch (Exception e) {
144             msoLogger.error(MessageEnum.GENERAL_EXCEPTION, "", "HealthCheck", MsoLogger.ErrorCode.UnknownError, "Error in local HealthCheck", e);
145             msoLogger.recordMetricEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.CommunicationError, "Exception while communicate with APIH/BPMN/RA", url, "HealthCheck", null);
146             msoLogger.debug("Exception while triggering local health check api:" + finalUrl);
147         }
148         return false;
149     }
150
151     protected CloseableHttpClient getHttpClient () {
152         // set the connection timeout value to 30 seconds (30000 milliseconds)
153         RequestConfig.Builder requestBuilder = RequestConfig.custom();
154         requestBuilder = requestBuilder.setConnectTimeout(30000);
155         requestBuilder = requestBuilder.setConnectionRequestTimeout(30000);
156         HttpClientBuilder builder = HttpClientBuilder.create ();
157         builder.setDefaultRequestConfig (requestBuilder.build ());
158
159         return builder.build ();
160     }
161
162     public MsoJavaProperties loadTopologyProperties() {
163         MsoJavaProperties msoProperties;
164         try {
165             msoProperties = msoPropertiesFactory.getMsoJavaProperties(MSO_PROP_TOPOLOGY);
166         } catch (Exception e) {
167             msoLogger.error(MessageEnum.LOAD_PROPERTIES_FAIL, MSO_PROP_TOPOLOGY, "", "HealthCheck", MsoLogger.ErrorCode.DataError, "Not able to load topology properties", e);
168             return null;
169         }
170
171         if (msoProperties != null && msoProperties.size() > 0) {
172             return msoProperties;
173         } else {
174             msoLogger.error(MessageEnum.LOAD_PROPERTIES_FAIL, MSO_PROP_TOPOLOGY, "", "HealthCheck", MsoLogger.ErrorCode.DataError, "Not able to load topology properties");
175             return null;
176         }
177     }
178
179     public boolean verifyNodeHealthCheck (HealthCheckUtils.NodeType type, String requestId) {
180         // Get info from topology properties file
181         MsoJavaProperties topologyProp = this.loadTopologyProperties();
182         if (null == topologyProp) {
183             return false;
184         }
185         String port = topologyProp.getProperty("server-port", null);
186         String ip = System.getProperty("jboss.qualified.host.name");
187         String sslEnabled = topologyProp.getProperty("ssl-enable", null);
188
189         if (null == port || null == ip || ip.isEmpty() || port.isEmpty()) {
190             msoLogger.error (MessageEnum.GENERAL_EXCEPTION_ARG, "Not able to get the IP or the Port value. IP:" + ip + "; Port:" + port, "", "HealthCheck", MsoLogger.ErrorCode.DataError, "Not able to get the IP or the Port value. IP:" + ip + "; Port:" + port);
191             return false;
192         }
193
194         String[] apis;
195         if (NodeType.APIH.equals (type)) {
196             String apiList = topologyProp.getProperty("apih-healthcheck-urn", null);
197             if (null == apiList) {
198                 msoLogger.error (MessageEnum.GENERAL_EXCEPTION_ARG, "Not able to get apih-healthcheck-urn parameter", "", "HealthCheck", MsoLogger.ErrorCode.DataError, "Not able to get apih-healthcheck-urn parameter");
199                 return false;
200             }
201             apis = apiList.split(",");
202         } else if (NodeType.RA.equals (type)){
203             String apiList = topologyProp.getProperty("jra-healthcheck-urn", null);
204             if (null == apiList) {
205                 msoLogger.error (MessageEnum.GENERAL_EXCEPTION_ARG, "Not able to get jra-healthcheck-urn parameter", "", "HealthCheck", MsoLogger.ErrorCode.DataError, "Not able to get jra-healthcheck-urn parameter");
206                 return false;
207             }
208             apis = apiList.split(",");
209         } else {
210             msoLogger.error (MessageEnum.GENERAL_EXCEPTION_ARG, "Unknown NodeType:" + type, "", "HealthCheck", MsoLogger.ErrorCode.DataError, "Unknown NodeType:" + type);
211             return false;
212         }
213
214         // Verify health check on APIH servers
215         for (String url : apis) {
216             // if any of the parameters is null or empty, no need to establish the health check request, just go to the next iteration
217             if ((url == null)  || url.isEmpty()) {
218                 continue;
219             }
220             // Exit the loop if local health check returns false from any of the sub component
221             if (!this.verifyLocalHealth(ip, port, url, sslEnabled, requestId)) {
222                 return false;
223             }
224         }
225         return true;
226     }
227
228     public boolean verifyGlobalHealthCheck(boolean verifyBpmn, String requestId) {
229         // Get info from topology properties file
230         MsoJavaProperties topologyProp = this.loadTopologyProperties();
231         if (null == topologyProp) {
232             msoLogger.error (MessageEnum.GENERAL_EXCEPTION_ARG, "Not able to find the topology file", "", "HealthCheck", MsoLogger.ErrorCode.PermissionError, "Not able to find the topology file");
233             return false;
234         }
235
236         String apihLB = topologyProp.getProperty("apih-load-balancer", null);
237         String apihApi = topologyProp.getProperty("apih-nodehealthcheck-urn", null);
238         String bpmnLB= topologyProp.getProperty("camunda-load-balancer", null);
239         String bpmnApi = topologyProp.getProperty("camunda-healthcheck-urn", null);
240         String jraLB = topologyProp.getProperty("jra-load-balancer", null);
241         String jraApi = topologyProp.getProperty("jra-nodehealthcheck-urn", null);
242
243         if (null == apihLB || null == apihApi || null == bpmnLB || null == bpmnApi || null == jraLB || null == jraApi
244                 || apihLB.isEmpty () || apihApi.isEmpty () || bpmnLB.isEmpty () || bpmnApi.isEmpty () || jraLB.isEmpty () || jraApi.isEmpty () ) {
245             msoLogger.error (MessageEnum.GENERAL_EXCEPTION_ARG, "Key parameters are missing from the topology file", "", "HealthCheck", MsoLogger.ErrorCode.DataError, "Key parameters are missing from the topology file");
246             return false;
247         }
248
249         // Verify health check on APIH servers
250         if (!this.verifyLocalHealth (apihLB, null, apihApi, null, requestId)) {
251             return false;
252         }
253
254         // Verify health check on Camunda servers
255         if (verifyBpmn) {
256             if (!this.verifyLocalHealth (bpmnLB, null, bpmnApi, null, requestId)) {
257                 return false;
258             }
259         }
260
261         // Verify health check on RA servers
262         if (!verifyLocalHealth (jraLB, null, jraApi, null, requestId)) {
263             return false;
264         }
265
266         return true;
267     }
268
269     public String getProperty (String name) {
270         MsoJavaProperties prop = this.loadTopologyProperties();
271
272         return prop.getProperty(name, null);
273     }
274
275     protected String getFinalUrl (String ip, String port, String url, String sslEnabled) {
276         if (null == port && null == sslEnabled) {
277             int length = ip.length();
278             if (ip.substring(length - 1).equals ("/")) {
279                 ip = ip.substring (0, length - 1);
280             }
281             return ip + url;
282         } else if (null != sslEnabled && "true".equals (sslEnabled.toLowerCase ())) {
283             return "https://" + ip + ":" + port + url;
284         } else {
285             return "http://" + ip + ":" + port + url;
286         }
287     }
288 }