re base code
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / components / health / HealthCheckBusinessLogic.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
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.sdc.be.components.health;
22
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;
46
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;
53 import java.util.Map;
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;
59
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;
68
69
70 @Component("healthCheckBusinessLogic")
71 public class HealthCheckBusinessLogic {
72
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;
80     @Resource
81     private TitanGenericDao titanGenericDao;
82     @Resource
83     private EsHealthCheckDao esHealthCheckDao;
84     @Resource
85     private DistributionEngineClusterHealth distributionEngineClusterHealth;
86     @Resource
87     private DmaapHealth dmaapHealth;
88     @Resource
89     private CassandraHealthCheck cassandraHealthCheck;
90     @Autowired
91     private SwitchoverDetector switchoverDetector;
92     private volatile List<HealthCheckInfo> prevBeHealthCheckInfos = null;
93     private ScheduledFuture<?> scheduledFuture = null;
94
95     @PostConstruct
96     public void init() {
97
98         prevBeHealthCheckInfos = getBeHealthCheckInfos();
99
100         log.debug("After initializing prevBeHealthCheckInfos: {}", prevBeHealthCheckInfos);
101
102         healthCheckScheduledTask = new HealthCheckScheduledTask();
103
104         if (this.scheduledFuture == null) {
105             this.scheduledFuture = this.healthCheckScheduler.scheduleAtFixedRate(healthCheckScheduledTask, 0, 3, TimeUnit.SECONDS);
106         }
107
108     }
109
110     public boolean isDistributionEngineUp() {
111
112         HealthCheckInfo healthCheckInfo = distributionEngineClusterHealth.getHealthCheckInfo();
113         return !healthCheckInfo.getHealthCheckStatus().equals(DOWN);
114     }
115
116     public Pair<Boolean, List<HealthCheckInfo>> getBeHealthCheckInfosStatus() {
117         Configuration config = ConfigurationManager.getConfigurationManager().getConfiguration();
118         return new ImmutablePair<>(healthCheckUtil.getAggregateStatus(prevBeHealthCheckInfos, config.getHealthStatusExclude()), prevBeHealthCheckInfos);
119     }
120
121     private List<HealthCheckInfo> getBeHealthCheckInfos() {
122
123         log.trace("In getBeHealthCheckInfos");
124
125         List<HealthCheckInfo> healthCheckInfos = new ArrayList<>();
126
127         //Dmaap
128         getDmaapHealthCheck(healthCheckInfos);
129         // BE
130         getBeHealthCheck(healthCheckInfos);
131
132         // Titan
133         getTitanHealthCheck(healthCheckInfos);
134         // ES
135         getEsHealthCheck(healthCheckInfos);
136
137         // Distribution Engine
138         getDistributionEngineCheck(healthCheckInfos);
139
140         //Cassandra
141         getCassandraHealthCheck(healthCheckInfos);
142
143         // Amdocs
144         getAmdocsHealthCheck(healthCheckInfos);
145
146         //DCAE
147         getDcaeHealthCheck(healthCheckInfos);
148
149         return healthCheckInfos;
150     }
151
152     private List<HealthCheckInfo> getEsHealthCheck(List<HealthCheckInfo> healthCheckInfos) {
153
154         // ES health check and version
155         String appVersion = getAppVersion();
156         HealthCheckStatus healthCheckStatus;
157         String description;
158
159         try {
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;
167         }
168         if (healthCheckStatus.equals(DOWN)) {
169             description = "ES cluster is down";
170         } else {
171             description = "OK";
172         }
173         healthCheckInfos.add(new HealthCheckInfo(HC_COMPONENT_ES, healthCheckStatus, appVersion, description));
174         return healthCheckInfos;
175     }
176
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;
182     }
183
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;
189     }
190
191
192     public List<HealthCheckInfo> getTitanHealthCheck(List<HealthCheckInfo> healthCheckInfos) {
193         // Titan health check and version
194         String description;
195         boolean isTitanUp;
196
197         try {
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;
204         }
205         if (isTitanUp) {
206             description = "OK";
207             healthCheckInfos.add(new HealthCheckInfo(HC_COMPONENT_TITAN, UP, null, description));
208         } else {
209             description = "Titan graph is down";
210             healthCheckInfos.add(new HealthCheckInfo(HC_COMPONENT_TITAN, DOWN, null, description));
211         }
212         return healthCheckInfos;
213     }
214
215     private List<HealthCheckInfo> getCassandraHealthCheck(List<HealthCheckInfo> healthCheckInfos) {
216
217         String description;
218         boolean isCassandraUp = false;
219
220         try {
221             isCassandraUp = cassandraHealthCheck.getCassandraStatus();
222         } catch (Exception e) {
223             description = "Cassandra error: " + e.getMessage();
224             log.error(description, e);
225         }
226         if (isCassandraUp) {
227             description = "OK";
228             healthCheckInfos.add(new HealthCheckInfo(HC_COMPONENT_CASSANDRA, UP, null, description));
229         } else {
230             description = "Cassandra is down";
231             healthCheckInfos.add(new HealthCheckInfo(HC_COMPONENT_CASSANDRA, DOWN, null, description));
232         }
233         return healthCheckInfos;
234
235     }
236
237     private void getDistributionEngineCheck(List<HealthCheckInfo> healthCheckInfos) {
238
239         HealthCheckInfo healthCheckInfo = distributionEngineClusterHealth.getHealthCheckInfo();
240
241         healthCheckInfos.add(healthCheckInfo);
242
243     }
244
245     private List<HealthCheckInfo> getAmdocsHealthCheck(List<HealthCheckInfo> healthCheckInfos) {
246         HealthCheckInfo beHealthCheckInfo = getHostedComponentsBeHealthCheck(HC_COMPONENT_ON_BOARDING, buildOnBoardingHealthCheckUrl());
247         healthCheckInfos.add(beHealthCheckInfo);
248         return healthCheckInfos;
249     }
250
251     private List<HealthCheckInfo> getDcaeHealthCheck(List<HealthCheckInfo> healthCheckInfos) {
252         HealthCheckInfo beHealthCheckInfo = getHostedComponentsBeHealthCheck(HC_COMPONENT_DCAE, buildDcaeHealthCheckUrl());
253         healthCheckInfos.add(beHealthCheckInfo);
254         return healthCheckInfos;
255     }
256
257     private HealthCheckInfo getHostedComponentsBeHealthCheck(String componentName, String healthCheckUrl) {
258         HealthCheckStatus healthCheckStatus;
259         String description;
260         String version = null;
261         List<HealthCheckInfo> componentsInfo = new ArrayList<>();
262         final int timeout = 3000;
263
264         if (healthCheckUrl != null) {
265             try {
266                 HttpResponse<String> httpResponse = HttpRequest.get(healthCheckUrl, new HttpClientConfig(new Timeouts(timeout, timeout)));
267                 int statusCode = httpResponse.getStatusCode();
268                 String aggDescription = "";
269
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>>() {
275                     });
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>>() {
279                         });
280                     }
281
282                     if (!componentsInfo.isEmpty()) {
283                         aggDescription = healthCheckUtil.getAggregateDescription(componentsInfo, null);
284                     } else {
285                         componentsInfo.add(new HealthCheckInfo(HC_COMPONENT_BE, DOWN, null, null));
286                     }
287                 } else {
288                     log.trace("{} Health Check Response code: {}", componentName, statusCode);
289                 }
290
291                 if (statusCode != SC_OK) {
292                     healthCheckStatus = DOWN;
293                     description = aggDescription.length() > 0
294                             ? aggDescription
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));
298                     }
299                 } else {
300                     healthCheckStatus = UP;
301                     description = "OK";
302                 }
303
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));
310                 }
311             }
312         } else {
313             healthCheckStatus = DOWN;
314             description = componentName + " health check Configuration is missing";
315             componentsInfo.add(new HealthCheckInfo(HC_COMPONENT_BE, DOWN, null, description));
316         }
317
318         return new HealthCheckInfo(componentName, healthCheckStatus, version, description, componentsInfo);
319     }
320
321     @PreDestroy
322     protected void destroy() {
323
324         if (scheduledFuture != null) {
325             scheduledFuture.cancel(true);
326             scheduledFuture = null;
327         }
328
329         if (healthCheckScheduler != null) {
330             healthCheckScheduler.shutdown();
331         }
332
333     }
334
335     private void logAlarm(String componentChangedMsg) {
336         BeEcompErrorManager.getInstance().logBeHealthCheckRecovery(componentChangedMsg);
337     }
338
339     public String getSiteMode() {
340         return switchoverDetector.getSiteMode();
341     }
342
343     public boolean anyStatusChanged(List<HealthCheckInfo> beHealthCheckInfos, List<HealthCheckInfo> prevBeHealthCheckInfos) {
344
345         boolean result = false;
346
347         if (beHealthCheckInfos != null && prevBeHealthCheckInfos != null) {
348
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));
351
352             if (currentValues != null && prevValues != null) {
353                 int currentSize = currentValues.size();
354                 int prevSize = prevValues.size();
355
356                 if (currentSize != prevSize) {
357
358                     result = true; //extra/missing component
359
360                     Map<String, HealthCheckStatus> notPresent = null;
361                     if (currentValues.keySet().containsAll(prevValues.keySet())) {
362                         notPresent = new HashMap<>(currentValues);
363                         notPresent.keySet().removeAll(prevValues.keySet());
364                     } else {
365                         notPresent = new HashMap<>(prevValues);
366                         notPresent.keySet().removeAll(currentValues.keySet());
367                     }
368
369                     for (String component : notPresent.keySet()) {
370                         logAlarm(format(COMPONENT_CHANGED_MESSAGE, component, prevValues.get(component), currentValues.get(component)));
371                     }
372
373                 } else {
374
375                     for (Entry<String, HealthCheckStatus> entry : currentValues.entrySet()) {
376                         String key = entry.getKey();
377                         HealthCheckStatus value = entry.getValue();
378
379                         if (!prevValues.containsKey(key)) {
380                             result = true; //component missing
381                             logAlarm(format(COMPONENT_CHANGED_MESSAGE, key, prevValues.get(key), currentValues.get(key)));
382                             break;
383                         }
384
385                         HealthCheckStatus prevHealthCheckStatus = prevValues.get(key);
386
387                         if (value != prevHealthCheckStatus) {
388                             result = true; //component status changed
389                             logAlarm(format(COMPONENT_CHANGED_MESSAGE, key, prevValues.get(key), currentValues.get(key)));
390                             break;
391                         }
392                     }
393                 }
394             }
395
396         } else if (beHealthCheckInfos == null && prevBeHealthCheckInfos == null) {
397             result = false;
398         } else {
399             logAlarm(format(COMPONENT_CHANGED_MESSAGE, "", prevBeHealthCheckInfos == null ? "null" : "true", prevBeHealthCheckInfos == null ? "true" : "null"));
400             result = true;
401         }
402
403         return result;
404     }
405
406     private String buildOnBoardingHealthCheckUrl() {
407
408         Configuration.OnboardingConfig onboardingConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getOnboarding();
409
410         if (onboardingConfig != null) {
411             String protocol = onboardingConfig.getProtocol();
412             String host = onboardingConfig.getHost();
413             Integer port = onboardingConfig.getPort();
414             String uri = onboardingConfig.getHealthCheckUri();
415
416             return protocol + "://" + host + ":" + port + uri;
417         }
418
419         log.error("onboarding health check configuration is missing.");
420         return null;
421     }
422
423     private String buildDcaeHealthCheckUrl() {
424
425         Configuration.DcaeConfig dcaeConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getDcae();
426
427         if (dcaeConfig != null) {
428             String protocol = dcaeConfig.getProtocol();
429             String host = dcaeConfig.getHost();
430             Integer port = dcaeConfig.getPort();
431             String uri = dcaeConfig.getHealthCheckUri();
432
433             return protocol + "://" + host + ":" + port + uri;
434         }
435
436         log.error("dcae health check configuration is missing.");
437         return null;
438     }
439
440     public class HealthCheckScheduledTask implements Runnable {
441         @Override
442         public void run() {
443             Configuration config = ConfigurationManager.getConfigurationManager().getConfiguration();
444             log.trace("Executing BE Health Check Task");
445
446             List<HealthCheckInfo> currentBeHealthCheckInfos = getBeHealthCheckInfos();
447             boolean healthStatus = healthCheckUtil.getAggregateStatus(currentBeHealthCheckInfos, config.getHealthStatusExclude());
448
449             boolean prevHealthStatus = healthCheckUtil.getAggregateStatus(prevBeHealthCheckInfos, config.getHealthStatusExclude());
450
451             boolean anyStatusChanged = anyStatusChanged(currentBeHealthCheckInfos, prevBeHealthCheckInfos);
452
453             if (prevHealthStatus != healthStatus || anyStatusChanged) {
454                 log.trace("BE Health State Changed to {}. Issuing alarm / recovery alarm...", healthStatus);
455
456                 prevBeHealthCheckInfos = currentBeHealthCheckInfos;
457                 logAlarm(healthStatus);
458             }
459         }
460
461         private void logAlarm(boolean prevHealthState) {
462             if (prevHealthState) {
463                 BeEcompErrorManager.getInstance().logBeHealthCheckRecovery(BE_HEALTH_CHECK_STR);
464             } else {
465                 BeEcompErrorManager.getInstance().logBeHealthCheckError(BE_HEALTH_CHECK_STR);
466             }
467         }
468     }
469
470 }