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