2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2020 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.sdc.fe.impl;
23 import com.fasterxml.jackson.core.type.TypeReference;
24 import com.fasterxml.jackson.databind.ObjectMapper;
25 import com.google.common.annotations.VisibleForTesting;
26 import com.google.common.collect.Lists;
27 import com.google.gson.Gson;
28 import com.google.gson.GsonBuilder;
29 import com.google.gson.JsonSyntaxException;
30 import com.google.gson.reflect.TypeToken;
31 import org.apache.commons.collections.CollectionUtils;
32 import org.apache.commons.lang3.StringUtils;
33 import org.apache.http.HttpStatus;
34 import org.openecomp.sdc.common.api.Constants;
35 import org.openecomp.sdc.common.api.HealthCheckInfo;
36 import org.openecomp.sdc.common.api.HealthCheckWrapper;
37 import org.openecomp.sdc.common.config.EcompErrorEnum;
38 import org.openecomp.sdc.common.http.client.api.HttpRequest;
39 import org.openecomp.sdc.common.http.client.api.HttpResponse;
40 import org.openecomp.sdc.common.http.config.HttpClientConfig;
41 import org.openecomp.sdc.common.http.config.Timeouts;
42 import org.openecomp.sdc.common.impl.ExternalConfiguration;
43 import org.openecomp.sdc.common.log.elements.ErrorLogOptionalData;
44 import org.openecomp.sdc.common.log.elements.LogFieldsMdcHandler;
45 import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode;
46 import org.openecomp.sdc.common.log.wrappers.Logger;
47 import org.openecomp.sdc.common.util.HealthCheckUtil;
48 import org.openecomp.sdc.fe.config.Configuration;
49 import org.openecomp.sdc.fe.config.FeEcompErrorManager;
51 import java.io.IOException;
52 import java.lang.reflect.Type;
53 import java.util.ArrayList;
54 import java.util.Arrays;
55 import java.util.Collections;
56 import java.util.List;
59 import static org.openecomp.sdc.common.api.Constants.HC_COMPONENT_CATALOG_FACADE_MS;
60 import static org.openecomp.sdc.common.api.Constants.HC_COMPONENT_ON_BOARDING;
62 public class HealthCheckScheduledTask implements Runnable {
63 private static final Logger healthLogger = Logger.getLogger("asdc.fe.healthcheck");
64 private static final Logger log = Logger.getLogger(HealthCheckScheduledTask.class.getName());
65 private static final String LOG_PARTNER_NAME = "SDC.FE";
66 private static final String LOG_TARGET_ENTITY_BE = "SDC.BE";
67 private static final String LOG_TARGET_ENTITY_CONFIG = "SDC.FE.Configuration";
68 private static final String LOG_TARGET_SERVICE_NAME_OB = "getOnboardingConfig";
69 private static final String LOG_TARGET_SERVICE_NAME_FACADE = "getCatalogFacadeConfig";
70 private static final String LOG_SERVICE_NAME = "/rest/healthCheck";
71 private static LogFieldsMdcHandler mdcFieldsHandler = new LogFieldsMdcHandler();
73 private static final String URL = "%s://%s:%s/sdc2/rest/healthCheck";
75 private final List<String> healthCheckFeComponents =
76 Arrays.asList(HC_COMPONENT_ON_BOARDING, HC_COMPONENT_CATALOG_FACADE_MS);
77 private static final HealthCheckUtil healthCheckUtil = new HealthCheckUtil();
78 private static final String DEBUG_CONTEXT = "HEALTH_FE";
79 private static final String EXTERNAL_HC_URL = "%s://%s:%s%s";
80 private static String ONBOARDING_HC_URL;
81 private static String CATALOG_FACADE_MS_HC_URL;
83 private final HealthCheckService service;
85 HealthCheckScheduledTask(HealthCheckService service) {
86 this.service = service;
89 static String getOnboardingHcUrl() {
90 return ONBOARDING_HC_URL;
93 static String getCatalogFacadeMsHcUrl() {
94 return CATALOG_FACADE_MS_HC_URL;
100 mdcFieldsHandler.addInfoForErrorAndDebugLogging(LOG_PARTNER_NAME);
101 healthLogger.trace("Executing FE Health Check Task - Start");
102 HealthCheckService.HealthStatus currentHealth = checkHealth();
103 int currentHealthStatus = currentHealth.getStatusCode();
104 healthLogger.trace("Executing FE Health Check Task - Status = {}", currentHealthStatus);
106 // In case health status was changed, issue alarm/recovery
107 if (currentHealthStatus != service.getLastHealthStatus().getStatusCode()) {
108 log.trace("FE Health State Changed to {}. Issuing alarm / recovery alarm...", currentHealthStatus);
109 logFeAlarm(currentHealthStatus);
111 // Anyway, update latest response
112 service.setLastHealthStatus(currentHealth);
115 private List<HealthCheckInfo> addHostedComponentsFeHealthCheck(String baseComponent, boolean requestedByBE) {
116 String healthCheckUrl = getExternalComponentHcUrl(baseComponent);
117 String serviceName = getExternalComponentHcUri(baseComponent);
118 ErrorLogOptionalData errorLogOptionalData = ErrorLogOptionalData.newBuilder().targetEntity(baseComponent)
119 .targetServiceName(serviceName).build();
121 StringBuilder description = new StringBuilder("");
122 int connectTimeoutMs = 3000;
123 int readTimeoutMs = service.getConfig().getHealthCheckSocketTimeoutInMs(5000);
125 if (healthCheckUrl != null) {
126 ObjectMapper mapper = new ObjectMapper();
128 HttpResponse<String> response = HttpRequest.get(healthCheckUrl, new HttpClientConfig(new Timeouts(connectTimeoutMs, readTimeoutMs)));
129 int beStatus = response.getStatusCode();
130 if (beStatus == HttpStatus.SC_OK || beStatus == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
131 String beJsonResponse = response.getResponse();
132 return convertResponse(beJsonResponse, mapper, baseComponent, description, beStatus);
134 description.append("Response code: " + beStatus);
135 log.trace("{} Health Check Response code: {}", baseComponent, beStatus);
137 } catch (Exception e) {
138 log.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, serviceName, errorLogOptionalData, baseComponent + " unexpected response ", e);
139 description.append(baseComponent + " Unexpected response: " + e.getMessage());
142 description.append(baseComponent + " health check Configuration is missing");
145 String compName = requestedByBE ? Constants.HC_COMPONENT_FE : baseComponent;
146 return Collections.singletonList(new HealthCheckInfo(
148 HealthCheckInfo.HealthCheckStatus.DOWN,
150 description.toString()));
153 private String getExternalComponentHcUri(String baseComponent) {
154 String healthCheckUri = null;
155 switch (baseComponent) {
156 case HC_COMPONENT_ON_BOARDING:
157 healthCheckUri = service.getConfig().getOnboarding().getHealthCheckUriFe();
159 case HC_COMPONENT_CATALOG_FACADE_MS:
160 healthCheckUri = service.getConfig().getCatalogFacadeMs().getHealthCheckUri();
163 log.debug("Unsupported base component {}", baseComponent);
166 return healthCheckUri;
171 String getExternalComponentHcUrl(String baseComponent) {
172 String healthCheckUrl = null;
173 switch (baseComponent) {
174 case HC_COMPONENT_ON_BOARDING:
175 healthCheckUrl = getOnboardingHealthCheckUrl();
177 case HC_COMPONENT_CATALOG_FACADE_MS:
178 healthCheckUrl = getCatalogFacadeHealthCheckUrl();
181 log.debug("Unsupported base component {}", baseComponent);
184 return healthCheckUrl;
187 private void logFeAlarm(int lastFeStatus) {
188 switch (lastFeStatus) {
190 FeEcompErrorManager.getInstance().processEcompError(DEBUG_CONTEXT, EcompErrorEnum.FeHealthCheckRecovery, "FE Health Recovered");
191 FeEcompErrorManager.getInstance().logFeHealthCheckRecovery("FE Health Recovered");
194 FeEcompErrorManager.getInstance().processEcompError(DEBUG_CONTEXT, EcompErrorEnum.FeHealthCheckError, "Connection with ASDC-BE is probably down");
195 FeEcompErrorManager.getInstance().logFeHealthCheckError("Connection with ASDC-BE is probably down");
202 private HealthCheckService.HealthStatus checkHealth() {
203 Gson gson = new GsonBuilder().setPrettyPrinting().create();
204 Configuration config = service.getConfig();
206 HealthCheckWrapper feAggHealthCheck;
207 boolean aggregateFeStatus = false;
208 String redirectedUrl = String.format(URL, config.getBeProtocol(), config.getBeHost(),
209 Constants.HTTPS.equals(config.getBeProtocol()) ? config.getBeSslPort() : config.getBeHttpPort());
210 int connectTimeoutMs = 3000;
211 int readTimeoutMs = config.getHealthCheckSocketTimeoutInMs(5000);
212 ErrorLogOptionalData errorLogOptionalData = ErrorLogOptionalData.newBuilder().targetEntity(LOG_TARGET_ENTITY_BE)
213 .targetServiceName(LOG_SERVICE_NAME).build();
216 HttpResponse<String> response = HttpRequest.get(redirectedUrl, new HttpClientConfig(new Timeouts(connectTimeoutMs, readTimeoutMs)));
217 log.debug("HC call to BE - status code is {}", response.getStatusCode());
218 String beJsonResponse = response.getResponse();
219 feAggHealthCheck = getFeHealthCheckInfos(gson, beJsonResponse);
220 if (response.getStatusCode() != HttpStatus.SC_INTERNAL_SERVER_ERROR) {
221 aggregateFeStatus = healthCheckUtil.getAggregateStatus(feAggHealthCheck.getComponentsInfo(), getExcludedComponentList());
223 //Getting aggregate FE status
224 return new HealthCheckService.HealthStatus(aggregateFeStatus ? HttpStatus.SC_OK : HttpStatus.SC_INTERNAL_SERVER_ERROR, gson.toJson(feAggHealthCheck));
227 catch (Exception e) {
228 log.debug("Health Check error when trying to connect to BE or external FE. Error: {}", e);
229 log.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, LOG_SERVICE_NAME, errorLogOptionalData,
230 "Health Check error when trying to connect to BE or external FE.", e.getMessage());
231 FeEcompErrorManager.getInstance().processEcompError(DEBUG_CONTEXT,EcompErrorEnum.FeHealthCheckGeneralError, "Unexpected FE Health check error");
232 FeEcompErrorManager.getInstance().logFeHealthCheckGeneralError("Unexpected FE Health check error");
233 return new HealthCheckService.HealthStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR, gson.toJson(getBeDownCheckInfos()));
238 List<String> getExcludedComponentList() {
239 List <String> excludedComponentList = Lists.newArrayList(service.getConfig().getHealthStatusExclude());
240 if (isCatalogFacadeMsExcluded()) {
241 if (log.isInfoEnabled()) {
242 log.info(HC_COMPONENT_CATALOG_FACADE_MS + " has been added to the Healthcheck exclude list");
244 excludedComponentList.add(HC_COMPONENT_CATALOG_FACADE_MS);
246 return excludedComponentList;
249 private boolean isCatalogFacadeMsExcluded() {
250 //CATALOG_FACADE_MS is excluded if it is not configured
251 return service.getConfig().getCatalogFacadeMs() == null || StringUtils.isEmpty(service.getConfig().getCatalogFacadeMs().getPath());
254 private HealthCheckWrapper getFeHealthCheckInfos(Gson gson, String responseString) {
255 Type wrapperType = new TypeToken<HealthCheckWrapper>() {
257 HealthCheckWrapper healthCheckWrapper = gson.fromJson(responseString, wrapperType);
258 String description = "OK";
259 healthCheckWrapper.getComponentsInfo()
260 .add(new HealthCheckInfo(Constants.HC_COMPONENT_FE, HealthCheckInfo.HealthCheckStatus.UP, ExternalConfiguration.getAppVersion(), description));
262 //add FE hosted components
263 for (String component : healthCheckFeComponents) {
264 buildHealthCheckListForComponent(component, healthCheckWrapper);
266 return healthCheckWrapper;
269 private void buildHealthCheckListForComponent(String component, HealthCheckWrapper healthCheckWrapper) {
271 HealthCheckInfo componentHCInfoFromBE = getComponentHcFromList(component, healthCheckWrapper.getComponentsInfo());
272 List<HealthCheckInfo> componentHCInfoList = addHostedComponentsFeHealthCheck(component, componentHCInfoFromBE != null);
273 HealthCheckInfo calculateStatusFor;
274 if (componentHCInfoFromBE != null) {
275 if (log.isDebugEnabled()) {
276 log.debug("{} component healthcheck info has been received from the BE and from the component itself", component);
278 //update the subcomponents's HC if exist and recalculate the component status according to the subcomponets HC
279 calculateStatusFor = updateSubComponentsInfoOfBeHc(componentHCInfoFromBE, componentHCInfoList);
283 //this component is not in the BE HC response, need to add it and calculate the aggregated status
284 if (log.isDebugEnabled()) {
285 log.debug("{} component healthcheck info has been received from the component itself, it is not monitored by the BE", component);
287 //we assume that response from components which HC is not requested by BE have only one entry in the responded list
288 calculateStatusFor = componentHCInfoList.get(0);
289 healthCheckWrapper.getComponentsInfo()
290 .add(calculateStatusFor);
293 calculateAggregatedStatus(calculateStatusFor);
298 HealthCheckInfo updateSubComponentsInfoOfBeHc(HealthCheckInfo componentHCInfoFromBE, List<HealthCheckInfo> componentHcReceivedByFE) {
299 if (!CollectionUtils.isEmpty(componentHcReceivedByFE)) {
300 //this component HC is received from BE, just need to calculate the status for that
301 if (componentHCInfoFromBE.getComponentsInfo() == null) {
302 componentHCInfoFromBE.setComponentsInfo(new ArrayList<>());
304 componentHCInfoFromBE.getComponentsInfo().addAll(componentHcReceivedByFE);
306 return componentHCInfoFromBE;
309 private HealthCheckInfo getComponentHcFromList(String component, List<HealthCheckInfo> hcList) {
310 return hcList.stream().filter(c -> c.getHealthCheckComponent().equals(component)).findFirst().orElse(null);
313 private void calculateAggregatedStatus(HealthCheckInfo baseComponentHCInfo) {
314 if (!CollectionUtils.isEmpty(baseComponentHCInfo.getComponentsInfo())) {
315 boolean status = healthCheckUtil.getAggregateStatus(baseComponentHCInfo.getComponentsInfo(), getExcludedComponentList());
316 baseComponentHCInfo.setHealthCheckStatus(status ?
317 HealthCheckInfo.HealthCheckStatus.UP : HealthCheckInfo.HealthCheckStatus.DOWN);
319 String componentsDesc = healthCheckUtil.getAggregateDescription(baseComponentHCInfo.getComponentsInfo());
320 if (!StringUtils.isEmpty(componentsDesc)) { //aggregated description contains all the internal components desc
321 baseComponentHCInfo.setDescription(componentsDesc);
326 private HealthCheckWrapper getBeDownCheckInfos() {
327 List<HealthCheckInfo> healthCheckInfos = new ArrayList<>();
328 healthCheckInfos.add(new HealthCheckInfo(Constants.HC_COMPONENT_FE, HealthCheckInfo.HealthCheckStatus.UP,
329 ExternalConfiguration.getAppVersion(), "OK"));
330 healthCheckInfos.add(new HealthCheckInfo(Constants.HC_COMPONENT_BE, HealthCheckInfo.HealthCheckStatus.DOWN, null, null));
331 healthCheckInfos.add(new HealthCheckInfo(Constants.HC_COMPONENT_JANUSGRAPH, HealthCheckInfo.HealthCheckStatus.UNKNOWN, null, null));
332 healthCheckInfos.add(new HealthCheckInfo(Constants.HC_COMPONENT_CASSANDRA, HealthCheckInfo.HealthCheckStatus.UNKNOWN, null, null));
333 healthCheckInfos.add(new HealthCheckInfo(Constants.HC_COMPONENT_DISTRIBUTION_ENGINE, HealthCheckInfo.HealthCheckStatus.UNKNOWN, null, null));
334 healthCheckInfos.add(new HealthCheckInfo(Constants.HC_COMPONENT_ON_BOARDING, HealthCheckInfo.HealthCheckStatus.UNKNOWN, null, null));
335 healthCheckInfos.add(new HealthCheckInfo(HC_COMPONENT_CATALOG_FACADE_MS, HealthCheckInfo.HealthCheckStatus.UNKNOWN, null, null));
336 return new HealthCheckWrapper(healthCheckInfos, "UNKNOWN", "UNKNOWN");
339 String buildHealthCheckUrl(String protocol, String host, Integer port, String uri) {
340 return String.format(EXTERNAL_HC_URL, protocol, host, port, uri);
343 private String getOnboardingHealthCheckUrl() {
344 Configuration.OnboardingConfig onboardingConfig = service.getConfig().getOnboarding();
345 ErrorLogOptionalData errorLogOptionalData = ErrorLogOptionalData.newBuilder().targetEntity(LOG_TARGET_ENTITY_CONFIG)
346 .targetServiceName(LOG_TARGET_SERVICE_NAME_OB).build();
348 if (StringUtils.isEmpty(ONBOARDING_HC_URL)) {
349 if (onboardingConfig != null) {
350 ONBOARDING_HC_URL = buildHealthCheckUrl(
351 onboardingConfig.getProtocolFe(), onboardingConfig.getHostFe(),
352 onboardingConfig.getPortFe(), onboardingConfig.getHealthCheckUriFe());
355 log.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, LOG_SERVICE_NAME, errorLogOptionalData,
356 "Onboarding health check configuration is missing.");
359 return ONBOARDING_HC_URL;
362 private String getCatalogFacadeHealthCheckUrl() {
363 Configuration.CatalogFacadeMsConfig catalogFacadeMsConfig = service.getConfig().getCatalogFacadeMs();
364 ErrorLogOptionalData errorLogOptionalData = ErrorLogOptionalData.newBuilder().targetEntity(LOG_TARGET_ENTITY_CONFIG)
365 .targetServiceName(LOG_TARGET_SERVICE_NAME_FACADE).build();
367 if (StringUtils.isEmpty(CATALOG_FACADE_MS_HC_URL)) {
368 if (catalogFacadeMsConfig != null) {
369 CATALOG_FACADE_MS_HC_URL = buildHealthCheckUrl(
370 catalogFacadeMsConfig.getProtocol(), catalogFacadeMsConfig.getHost(),
371 catalogFacadeMsConfig.getPort(), catalogFacadeMsConfig.getHealthCheckUri());
374 log.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, LOG_SERVICE_NAME, errorLogOptionalData,
375 "Catalog Facade MS health check configuration is missing.");
378 return CATALOG_FACADE_MS_HC_URL;
382 private List<HealthCheckInfo> convertResponse(String beJsonResponse, ObjectMapper mapper, String baseComponent, StringBuilder description, int beStatus) {
383 ErrorLogOptionalData errorLogOptionalData = ErrorLogOptionalData.newBuilder().targetEntity(baseComponent)
384 .targetServiceName(LOG_SERVICE_NAME).build();
387 Map<String, Object> healthCheckMap = mapper.readValue(beJsonResponse, new TypeReference<Map<String, Object>>() {
389 if (healthCheckMap.containsKey("componentsInfo")) {
390 return mapper.convertValue(healthCheckMap.get("componentsInfo"), new TypeReference<List<HealthCheckInfo>>() {
393 description.append("Internal components are missing");
395 } catch (JsonSyntaxException | IOException e) {
396 log.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, LOG_SERVICE_NAME, errorLogOptionalData,
397 baseComponent + " Unexpected response body ", e);
398 description.append(baseComponent)
399 .append("Unexpected response body. Response code: ")
402 return new ArrayList<>();