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.distribution.engine;
23 import org.openecomp.sdc.be.config.BeEcompErrorManager;
24 import org.openecomp.sdc.be.config.ConfigurationManager;
25 import org.openecomp.sdc.be.config.DistributionEngineConfiguration;
26 import org.openecomp.sdc.common.api.Constants;
27 import org.openecomp.sdc.common.api.HealthCheckInfo;
28 import org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus;
29 import org.openecomp.sdc.common.config.EcompErrorName;
30 import org.slf4j.Logger;
31 import org.slf4j.LoggerFactory;
32 import org.springframework.stereotype.Component;
34 import javax.annotation.PostConstruct;
35 import javax.annotation.PreDestroy;
36 import java.util.ArrayList;
37 import java.util.Collection;
38 import java.util.List;
40 import java.util.concurrent.*;
41 import java.util.concurrent.atomic.AtomicBoolean;
43 @Component("distribution-engine-cluster-health")
44 public class DistributionEngineClusterHealth {
46 protected static String UEB_HEALTH_LOG_CONTEXT = "ueb.healthcheck";
48 private static final Logger healthLogger = LoggerFactory.getLogger(UEB_HEALTH_LOG_CONTEXT);
50 private static final String UEB_HEALTH_CHECK_STR = "uebHealthCheck";
52 boolean lastHealthState = false;
54 Object lockOject = new Object();
56 private long reconnectInterval = 5;
58 private long healthCheckReadTimeout = 20;
60 private static final Logger logger = LoggerFactory.getLogger(DistributionEngineClusterHealth.class);
62 private List<String> uebServers = null;
64 private String publicApiKey = null;
66 public enum HealthCheckInfoResult {
68 OK(new HealthCheckInfo(Constants.HC_COMPONENT_DISTRIBUTION_ENGINE, HealthCheckStatus.UP, null, ClusterStatusDescription.OK.getDescription())),
69 UNAVAILABLE(new HealthCheckInfo(Constants.HC_COMPONENT_DISTRIBUTION_ENGINE, HealthCheckStatus.DOWN, null, ClusterStatusDescription.UNAVAILABLE.getDescription())),
70 NOT_CONFIGURED(new HealthCheckInfo(Constants.HC_COMPONENT_DISTRIBUTION_ENGINE, HealthCheckStatus.DOWN, null, ClusterStatusDescription.NOT_CONFIGURED.getDescription())),
71 DISABLED(new HealthCheckInfo(Constants.HC_COMPONENT_DISTRIBUTION_ENGINE, HealthCheckStatus.DOWN, null, ClusterStatusDescription.DISABLED.getDescription()));
73 private HealthCheckInfo healthCheckInfo;
75 HealthCheckInfoResult(HealthCheckInfo healthCheckInfo) {
76 this.healthCheckInfo = healthCheckInfo;
79 public HealthCheckInfo getHealthCheckInfo() {
80 return healthCheckInfo;
85 private HealthCheckInfo healthCheckInfo = HealthCheckInfoResult.UNAVAILABLE.getHealthCheckInfo();
87 private Map<String, AtomicBoolean> envNamePerStatus = null;
89 private ScheduledFuture<?> scheduledFuture = null;
91 ScheduledExecutorService healthCheckScheduler = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
93 public Thread newThread(Runnable r) {
94 return new Thread(r, "UEB-Health-Check-Task");
98 HealthCheckScheduledTask healthCheckScheduledTask = null;
100 public enum ClusterStatusDescription {
102 OK("OK"), UNAVAILABLE("U-EB cluster is not available"), NOT_CONFIGURED("U-EB cluster is not configured"), DISABLED("DE is disabled in configuration");
106 ClusterStatusDescription(String desc) {
110 public String getDescription() {
117 * Health Check Task Scheduler.
119 * It schedules a task which send a apiKey get query towards the UEB servers. In case a query to the first UEB server is failed, then a second query is sent to the next UEB server.
125 public class HealthCheckScheduledTask implements Runnable {
127 List<UebHealthCheckCall> healthCheckCalls = new ArrayList<>();
129 public HealthCheckScheduledTask(List<String> uebServers) {
131 logger.debug("Create health check calls for servers {}", uebServers);
132 if (uebServers != null) {
133 for (String server : uebServers) {
134 healthCheckCalls.add(new UebHealthCheckCall(server, publicApiKey));
142 healthLogger.trace("Executing UEB Health Check Task - Start");
144 boolean healthStatus = verifyAtLeastOneEnvIsUp();
146 if (true == healthStatus) {
147 boolean queryUebStatus = queryUeb();
148 if (queryUebStatus == lastHealthState) {
152 synchronized (lockOject) {
153 if (queryUebStatus != lastHealthState) {
154 logger.trace("UEB Health State Changed to {}. Issuing alarm / recovery alarm...", healthStatus);
155 lastHealthState = queryUebStatus;
156 logAlarm(lastHealthState);
157 if (true == queryUebStatus) {
158 healthCheckInfo = HealthCheckInfoResult.OK.getHealthCheckInfo();
160 healthCheckInfo = HealthCheckInfoResult.UNAVAILABLE.getHealthCheckInfo();
165 healthLogger.trace("Not all UEB Environments are up");
171 * verify that at least one environment is up.
174 private boolean verifyAtLeastOneEnvIsUp() {
176 boolean healthStatus = false;
178 if (envNamePerStatus != null) {
179 Collection<AtomicBoolean> values = envNamePerStatus.values();
180 if (values != null) {
181 for (AtomicBoolean status : values) {
182 if (true == status.get()) {
194 * executor for the query itself
196 ExecutorService healthCheckExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() {
198 public Thread newThread(Runnable r) {
199 return new Thread(r, "UEB-Health-Check-Thread");
204 * go all UEB servers and send a get apiKeys query. In case a query is succeed, no query is sent to the rest of UEB servers.
209 private boolean queryUeb() {
211 Boolean result = false;
213 for (UebHealthCheckCall healthCheckCall : healthCheckCalls) {
216 healthLogger.debug("Before running Health Check retry query number {} towards UEB server {}", retryNumber, healthCheckCall.getServer());
218 Future<Boolean> future = healthCheckExecutor.submit(healthCheckCall);
219 result = future.get(healthCheckReadTimeout, TimeUnit.SECONDS);
221 healthLogger.debug("After running Health Check retry query number {} towards UEB server {}. Result is {}", retryNumber, healthCheckCall.getServer(), result);
223 if (result != null && true == result.booleanValue()) {
227 } catch (Exception e) {
228 String message = e.getMessage();
229 if (message == null) {
230 message = e.getClass().getName();
232 healthLogger.debug("Error occured during running Health Check retry query towards UEB server {}. Result is {}", healthCheckCall.getServer(), message);
233 healthLogger.trace("Error occured during running Health Check retry query towards UEB server {}. Result is {}", healthCheckCall.getServer(), message, e);
243 public List<UebHealthCheckCall> getHealthCheckCalls() {
244 return healthCheckCalls;
250 protected void init() {
252 logger.trace("Enter init method of DistributionEngineClusterHealth");
254 Long reconnectIntervalConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getUebHealthCheckReconnectIntervalInSeconds();
255 if (reconnectIntervalConfig != null) {
256 reconnectInterval = reconnectIntervalConfig.longValue();
258 Long healthCheckReadTimeoutConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getUebHealthCheckReadTimeout();
259 if (healthCheckReadTimeoutConfig != null) {
260 healthCheckReadTimeout = healthCheckReadTimeoutConfig.longValue();
263 DistributionEngineConfiguration distributionEngineConfiguration = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration();
265 this.uebServers = distributionEngineConfiguration.getUebServers();
266 this.publicApiKey = distributionEngineConfiguration.getUebPublicKey();
268 this.healthCheckScheduledTask = new HealthCheckScheduledTask(this.uebServers);
270 logger.trace("Exit init method of DistributionEngineClusterHealth");
275 protected void destroy() {
277 if (scheduledFuture != null) {
278 scheduledFuture.cancel(true);
279 scheduledFuture = null;
282 if (healthCheckScheduler != null) {
283 healthCheckScheduler.shutdown();
289 * Start health check task.
291 * @param envNamePerStatus
294 public void startHealthCheckTask(Map<String, AtomicBoolean> envNamePerStatus, boolean startTask) {
295 this.envNamePerStatus = envNamePerStatus;
297 if (startTask == true && this.scheduledFuture == null) {
298 this.scheduledFuture = this.healthCheckScheduler.scheduleAtFixedRate(healthCheckScheduledTask, 0, reconnectInterval, TimeUnit.SECONDS);
302 public void startHealthCheckTask(Map<String, AtomicBoolean> envNamePerStatus) {
303 startHealthCheckTask(envNamePerStatus, true);
306 private void logAlarm(boolean lastHealthState) {
307 if (lastHealthState == true) {
308 BeEcompErrorManager.getInstance().logBeHealthCheckUebClusterRecovery(UEB_HEALTH_CHECK_STR);
310 BeEcompErrorManager.getInstance().logBeHealthCheckUebClusterError(UEB_HEALTH_CHECK_STR);
314 public HealthCheckInfo getHealthCheckInfo() {
315 return healthCheckInfo;
319 * change the health check to DISABLE
321 public void setHealthCheckUebIsDisabled() {
322 healthCheckInfo = HealthCheckInfoResult.DISABLED.getHealthCheckInfo();
326 * change the health check to NOT CONFGIURED
328 public void setHealthCheckUebConfigurationError() {
329 healthCheckInfo = HealthCheckInfoResult.NOT_CONFIGURED.getHealthCheckInfo();
332 public void setHealthCheckOkAndReportInCaseLastStateIsDown() {
334 if (lastHealthState == true) {
337 synchronized (lockOject) {
338 if (lastHealthState == false) {
339 logger.debug("Going to update health check state to available");
340 lastHealthState = true;
341 healthCheckInfo = HealthCheckInfoResult.OK.getHealthCheckInfo();
342 logAlarm(lastHealthState);