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.sdc.be.components.health;
23 import com.fasterxml.jackson.core.type.TypeReference;
24 import com.fasterxml.jackson.databind.ObjectMapper;
25 import org.apache.commons.lang3.tuple.ImmutablePair;
26 import org.apache.commons.lang3.tuple.Pair;
27 import org.openecomp.sdc.be.components.distribution.engine.DistributionEngineClusterHealth;
28 import org.openecomp.sdc.be.components.distribution.engine.DmaapHealth;
29 import org.openecomp.sdc.be.components.impl.CassandraHealthCheck;
30 import org.openecomp.sdc.be.config.BeEcompErrorManager;
31 import org.openecomp.sdc.be.config.Configuration;
32 import org.openecomp.sdc.be.config.ConfigurationManager;
33 import org.openecomp.sdc.be.dao.impl.EsHealthCheckDao;
34 import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
35 import org.openecomp.sdc.be.switchover.detector.SwitchoverDetector;
36 import org.openecomp.sdc.common.api.HealthCheckInfo;
37 import org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus;
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.log.wrappers.Logger;
43 import org.openecomp.sdc.common.util.HealthCheckUtil;
44 import org.springframework.beans.factory.annotation.Autowired;
45 import org.springframework.stereotype.Component;
47 import javax.annotation.PostConstruct;
48 import javax.annotation.PreDestroy;
49 import javax.annotation.Resource;
50 import java.util.ArrayList;
51 import java.util.HashMap;
52 import java.util.List;
54 import java.util.Map.Entry;
55 import java.util.concurrent.ScheduledExecutorService;
56 import java.util.concurrent.ScheduledFuture;
57 import java.util.concurrent.TimeUnit;
58 import java.util.stream.Collectors;
60 import static java.lang.String.format;
61 import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
62 import static org.apache.http.HttpStatus.SC_INTERNAL_SERVER_ERROR;
63 import static org.apache.http.HttpStatus.SC_OK;
64 import static org.openecomp.sdc.common.api.Constants.*;
65 import static org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus.DOWN;
66 import static org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus.UP;
67 import static org.openecomp.sdc.common.impl.ExternalConfiguration.getAppVersion;
70 @Component("healthCheckBusinessLogic")
71 public class HealthCheckBusinessLogic {
73 protected static final String BE_HEALTH_LOG_CONTEXT = "be.healthcheck";
74 private static final String BE_HEALTH_CHECK_STR = "beHealthCheck";
75 private static final String COMPONENT_CHANGED_MESSAGE = "BE Component %s state changed from %s to %s";
76 private static final Logger log = Logger.getLogger(HealthCheckBusinessLogic.class.getName());
77 private static final HealthCheckUtil healthCheckUtil = new HealthCheckUtil();
78 private final ScheduledExecutorService healthCheckScheduler = newSingleThreadScheduledExecutor((Runnable r) -> new Thread(r, "BE-Health-Check-Task"));
79 private HealthCheckScheduledTask healthCheckScheduledTask = null;
81 private TitanGenericDao titanGenericDao;
83 private EsHealthCheckDao esHealthCheckDao;
85 private DistributionEngineClusterHealth distributionEngineClusterHealth;
87 private DmaapHealth dmaapHealth;
89 private CassandraHealthCheck cassandraHealthCheck;
91 private SwitchoverDetector switchoverDetector;
92 private volatile List<HealthCheckInfo> prevBeHealthCheckInfos = null;
93 private ScheduledFuture<?> scheduledFuture = null;
98 prevBeHealthCheckInfos = getBeHealthCheckInfos();
100 log.debug("After initializing prevBeHealthCheckInfos: {}", prevBeHealthCheckInfos);
102 healthCheckScheduledTask = new HealthCheckScheduledTask();
104 if (this.scheduledFuture == null) {
105 this.scheduledFuture = this.healthCheckScheduler.scheduleAtFixedRate(healthCheckScheduledTask, 0, 3, TimeUnit.SECONDS);
110 public boolean isDistributionEngineUp() {
112 HealthCheckInfo healthCheckInfo = distributionEngineClusterHealth.getHealthCheckInfo();
113 return !healthCheckInfo.getHealthCheckStatus().equals(DOWN);
116 public Pair<Boolean, List<HealthCheckInfo>> getBeHealthCheckInfosStatus() {
117 Configuration config = ConfigurationManager.getConfigurationManager().getConfiguration();
118 return new ImmutablePair<>(healthCheckUtil.getAggregateStatus(prevBeHealthCheckInfos, config.getHealthStatusExclude()), prevBeHealthCheckInfos);
121 private List<HealthCheckInfo> getBeHealthCheckInfos() {
123 log.trace("In getBeHealthCheckInfos");
125 List<HealthCheckInfo> healthCheckInfos = new ArrayList<>();
128 getDmaapHealthCheck(healthCheckInfos);
130 getBeHealthCheck(healthCheckInfos);
133 getTitanHealthCheck(healthCheckInfos);
135 getEsHealthCheck(healthCheckInfos);
137 // Distribution Engine
138 getDistributionEngineCheck(healthCheckInfos);
141 getCassandraHealthCheck(healthCheckInfos);
144 getAmdocsHealthCheck(healthCheckInfos);
147 getDcaeHealthCheck(healthCheckInfos);
149 return healthCheckInfos;
152 private List<HealthCheckInfo> getEsHealthCheck(List<HealthCheckInfo> healthCheckInfos) {
154 // ES health check and version
155 String appVersion = getAppVersion();
156 HealthCheckStatus healthCheckStatus;
160 healthCheckStatus = esHealthCheckDao.getClusterHealthStatus();
161 } catch (Exception e) {
162 healthCheckStatus = DOWN;
163 description = "ES cluster error: " + e.getMessage();
164 healthCheckInfos.add(new HealthCheckInfo(HC_COMPONENT_ES, healthCheckStatus, appVersion, description));
165 log.error(description, e);
166 return healthCheckInfos;
168 if (healthCheckStatus.equals(DOWN)) {
169 description = "ES cluster is down";
173 healthCheckInfos.add(new HealthCheckInfo(HC_COMPONENT_ES, healthCheckStatus, appVersion, description));
174 return healthCheckInfos;
177 private List<HealthCheckInfo> getBeHealthCheck(List<HealthCheckInfo> healthCheckInfos) {
178 String appVersion = getAppVersion();
179 String description = "OK";
180 healthCheckInfos.add(new HealthCheckInfo(HC_COMPONENT_BE, UP, appVersion, description));
181 return healthCheckInfos;
184 private List<HealthCheckInfo> getDmaapHealthCheck(List<HealthCheckInfo> healthCheckInfos) {
185 String appVersion = getAppVersion();
186 dmaapHealth.getHealthCheckInfo().setVersion(appVersion);
187 healthCheckInfos.add(dmaapHealth.getHealthCheckInfo());
188 return healthCheckInfos;
192 public List<HealthCheckInfo> getTitanHealthCheck(List<HealthCheckInfo> healthCheckInfos) {
193 // Titan health check and version
198 isTitanUp = titanGenericDao.isGraphOpen();
199 } catch (Exception e) {
200 description = "Titan error: ";
201 healthCheckInfos.add(new HealthCheckInfo(HC_COMPONENT_TITAN, DOWN, null, description));
202 log.error(description, e);
203 return healthCheckInfos;
207 healthCheckInfos.add(new HealthCheckInfo(HC_COMPONENT_TITAN, UP, null, description));
209 description = "Titan graph is down";
210 healthCheckInfos.add(new HealthCheckInfo(HC_COMPONENT_TITAN, DOWN, null, description));
212 return healthCheckInfos;
215 private List<HealthCheckInfo> getCassandraHealthCheck(List<HealthCheckInfo> healthCheckInfos) {
218 boolean isCassandraUp = false;
221 isCassandraUp = cassandraHealthCheck.getCassandraStatus();
222 } catch (Exception e) {
223 description = "Cassandra error: " + e.getMessage();
224 log.error(description, e);
228 healthCheckInfos.add(new HealthCheckInfo(HC_COMPONENT_CASSANDRA, UP, null, description));
230 description = "Cassandra is down";
231 healthCheckInfos.add(new HealthCheckInfo(HC_COMPONENT_CASSANDRA, DOWN, null, description));
233 return healthCheckInfos;
237 private void getDistributionEngineCheck(List<HealthCheckInfo> healthCheckInfos) {
239 HealthCheckInfo healthCheckInfo = distributionEngineClusterHealth.getHealthCheckInfo();
241 healthCheckInfos.add(healthCheckInfo);
245 private List<HealthCheckInfo> getAmdocsHealthCheck(List<HealthCheckInfo> healthCheckInfos) {
246 HealthCheckInfo beHealthCheckInfo = getHostedComponentsBeHealthCheck(HC_COMPONENT_ON_BOARDING, buildOnBoardingHealthCheckUrl());
247 healthCheckInfos.add(beHealthCheckInfo);
248 return healthCheckInfos;
251 private List<HealthCheckInfo> getDcaeHealthCheck(List<HealthCheckInfo> healthCheckInfos) {
252 HealthCheckInfo beHealthCheckInfo = getHostedComponentsBeHealthCheck(HC_COMPONENT_DCAE, buildDcaeHealthCheckUrl());
253 healthCheckInfos.add(beHealthCheckInfo);
254 return healthCheckInfos;
257 private HealthCheckInfo getHostedComponentsBeHealthCheck(String componentName, String healthCheckUrl) {
258 HealthCheckStatus healthCheckStatus;
260 String version = null;
261 List<HealthCheckInfo> componentsInfo = new ArrayList<>();
262 final int timeout = 3000;
264 if (healthCheckUrl != null) {
266 HttpResponse<String> httpResponse = HttpRequest.get(healthCheckUrl, new HttpClientConfig(new Timeouts(timeout, timeout)));
267 int statusCode = httpResponse.getStatusCode();
268 String aggDescription = "";
270 if (statusCode == SC_OK || statusCode == SC_INTERNAL_SERVER_ERROR) {
271 String response = httpResponse.getResponse();
272 log.trace("{} Health Check response: {}", componentName, response);
273 ObjectMapper mapper = new ObjectMapper();
274 Map<String, Object> healthCheckMap = mapper.readValue(response, new TypeReference<Map<String, Object>>() {
276 version = healthCheckMap.get("sdcVersion") != null ? healthCheckMap.get("sdcVersion").toString() : null;
277 if (healthCheckMap.containsKey("componentsInfo")) {
278 componentsInfo = mapper.convertValue(healthCheckMap.get("componentsInfo"), new TypeReference<List<HealthCheckInfo>>() {
282 if (!componentsInfo.isEmpty()) {
283 aggDescription = healthCheckUtil.getAggregateDescription(componentsInfo, null);
285 componentsInfo.add(new HealthCheckInfo(HC_COMPONENT_BE, DOWN, null, null));
288 log.trace("{} Health Check Response code: {}", componentName, statusCode);
291 if (statusCode != SC_OK) {
292 healthCheckStatus = DOWN;
293 description = aggDescription.length() > 0
295 : componentName + " is Down, specific reason unknown";//No inner component returned DOWN, but the status of HC is still DOWN.
296 if (componentsInfo.isEmpty()) {
297 componentsInfo.add(new HealthCheckInfo(HC_COMPONENT_BE, DOWN, null, description));
300 healthCheckStatus = UP;
304 } catch (Exception e) {
305 log.error("{} unexpected response: ", componentName, e);
306 healthCheckStatus = DOWN;
307 description = componentName + " unexpected response: " + e.getMessage();
308 if (componentsInfo != null && componentsInfo.isEmpty()) {
309 componentsInfo.add(new HealthCheckInfo(HC_COMPONENT_BE, DOWN, null, description));
313 healthCheckStatus = DOWN;
314 description = componentName + " health check Configuration is missing";
315 componentsInfo.add(new HealthCheckInfo(HC_COMPONENT_BE, DOWN, null, description));
318 return new HealthCheckInfo(componentName, healthCheckStatus, version, description, componentsInfo);
322 protected void destroy() {
324 if (scheduledFuture != null) {
325 scheduledFuture.cancel(true);
326 scheduledFuture = null;
329 if (healthCheckScheduler != null) {
330 healthCheckScheduler.shutdown();
335 private void logAlarm(String componentChangedMsg) {
336 BeEcompErrorManager.getInstance().logBeHealthCheckRecovery(componentChangedMsg);
339 public String getSiteMode() {
340 return switchoverDetector.getSiteMode();
343 public boolean anyStatusChanged(List<HealthCheckInfo> beHealthCheckInfos, List<HealthCheckInfo> prevBeHealthCheckInfos) {
345 boolean result = false;
347 if (beHealthCheckInfos != null && prevBeHealthCheckInfos != null) {
349 Map<String, HealthCheckStatus> currentValues = beHealthCheckInfos.stream().collect(Collectors.toMap(HealthCheckInfo::getHealthCheckComponent, HealthCheckInfo::getHealthCheckStatus));
350 Map<String, HealthCheckStatus> prevValues = prevBeHealthCheckInfos.stream().collect(Collectors.toMap(HealthCheckInfo::getHealthCheckComponent, HealthCheckInfo::getHealthCheckStatus));
352 if (currentValues != null && prevValues != null) {
353 int currentSize = currentValues.size();
354 int prevSize = prevValues.size();
356 if (currentSize != prevSize) {
358 result = true; //extra/missing component
360 Map<String, HealthCheckStatus> notPresent = null;
361 if (currentValues.keySet().containsAll(prevValues.keySet())) {
362 notPresent = new HashMap<>(currentValues);
363 notPresent.keySet().removeAll(prevValues.keySet());
365 notPresent = new HashMap<>(prevValues);
366 notPresent.keySet().removeAll(currentValues.keySet());
369 for (String component : notPresent.keySet()) {
370 logAlarm(format(COMPONENT_CHANGED_MESSAGE, component, prevValues.get(component), currentValues.get(component)));
375 for (Entry<String, HealthCheckStatus> entry : currentValues.entrySet()) {
376 String key = entry.getKey();
377 HealthCheckStatus value = entry.getValue();
379 if (!prevValues.containsKey(key)) {
380 result = true; //component missing
381 logAlarm(format(COMPONENT_CHANGED_MESSAGE, key, prevValues.get(key), currentValues.get(key)));
385 HealthCheckStatus prevHealthCheckStatus = prevValues.get(key);
387 if (value != prevHealthCheckStatus) {
388 result = true; //component status changed
389 logAlarm(format(COMPONENT_CHANGED_MESSAGE, key, prevValues.get(key), currentValues.get(key)));
396 } else if (beHealthCheckInfos == null && prevBeHealthCheckInfos == null) {
399 logAlarm(format(COMPONENT_CHANGED_MESSAGE, "", prevBeHealthCheckInfos == null ? "null" : "true", prevBeHealthCheckInfos == null ? "true" : "null"));
406 private String buildOnBoardingHealthCheckUrl() {
408 Configuration.OnboardingConfig onboardingConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getOnboarding();
410 if (onboardingConfig != null) {
411 String protocol = onboardingConfig.getProtocol();
412 String host = onboardingConfig.getHost();
413 Integer port = onboardingConfig.getPort();
414 String uri = onboardingConfig.getHealthCheckUri();
416 return protocol + "://" + host + ":" + port + uri;
419 log.error("onboarding health check configuration is missing.");
423 private String buildDcaeHealthCheckUrl() {
425 Configuration.DcaeConfig dcaeConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getDcae();
427 if (dcaeConfig != null) {
428 String protocol = dcaeConfig.getProtocol();
429 String host = dcaeConfig.getHost();
430 Integer port = dcaeConfig.getPort();
431 String uri = dcaeConfig.getHealthCheckUri();
433 return protocol + "://" + host + ":" + port + uri;
436 log.error("dcae health check configuration is missing.");
440 public class HealthCheckScheduledTask implements Runnable {
443 Configuration config = ConfigurationManager.getConfigurationManager().getConfiguration();
444 log.trace("Executing BE Health Check Task");
446 List<HealthCheckInfo> currentBeHealthCheckInfos = getBeHealthCheckInfos();
447 boolean healthStatus = healthCheckUtil.getAggregateStatus(currentBeHealthCheckInfos, config.getHealthStatusExclude());
449 boolean prevHealthStatus = healthCheckUtil.getAggregateStatus(prevBeHealthCheckInfos, config.getHealthStatusExclude());
451 boolean anyStatusChanged = anyStatusChanged(currentBeHealthCheckInfos, prevBeHealthCheckInfos);
453 if (prevHealthStatus != healthStatus || anyStatusChanged) {
454 log.trace("BE Health State Changed to {}. Issuing alarm / recovery alarm...", healthStatus);
456 prevBeHealthCheckInfos = currentBeHealthCheckInfos;
457 logAlarm(healthStatus);
461 private void logAlarm(boolean prevHealthState) {
462 if (prevHealthState) {
463 BeEcompErrorManager.getInstance().logBeHealthCheckRecovery(BE_HEALTH_CHECK_STR);
465 BeEcompErrorManager.getInstance().logBeHealthCheckError(BE_HEALTH_CHECK_STR);