aboutsummaryrefslogtreecommitdiffstats
path: root/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineClusterHealth.java
blob: e803730566379a229c2d103b142078fb9ff32085 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
/*-
 * ============LICENSE_START=======================================================
 * SDC
 * ================================================================================
 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */

package org.openecomp.sdc.be.components.distribution.engine;

import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.config.DistributionEngineConfiguration;
import org.openecomp.sdc.common.api.Constants;
import org.openecomp.sdc.common.api.HealthCheckInfo;
import org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus;
import org.openecomp.sdc.common.log.wrappers.Logger;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
@Component("distribution-engine-cluster-health")
public class DistributionEngineClusterHealth {

    protected static String UEB_HEALTH_LOG_CONTEXT = "ueb.healthcheck";

    //TODO use LoggerMetric instead
    private static final Logger healthLogger = Logger.getLogger(UEB_HEALTH_LOG_CONTEXT);

    private static final String UEB_HEALTH_CHECK_STR = "uebHealthCheck";

    boolean lastHealthState = false;

    Object lockOject = new Object();

    private long reconnectInterval = 5;

    private long healthCheckReadTimeout = 20;

    private static final Logger logger = Logger.getLogger(DistributionEngineClusterHealth.class.getName());

    private List<String> uebServers = null;

    private String publicApiKey = null;

    public enum HealthCheckInfoResult {

        OK(new HealthCheckInfo(Constants.HC_COMPONENT_DISTRIBUTION_ENGINE, HealthCheckStatus.UP, null, ClusterStatusDescription.OK.getDescription())),
        UNAVAILABLE(new HealthCheckInfo(Constants.HC_COMPONENT_DISTRIBUTION_ENGINE, HealthCheckStatus.DOWN, null, ClusterStatusDescription.UNAVAILABLE.getDescription())),
        NOT_CONFIGURED(new HealthCheckInfo(Constants.HC_COMPONENT_DISTRIBUTION_ENGINE, HealthCheckStatus.DOWN, null, ClusterStatusDescription.NOT_CONFIGURED.getDescription())),
        DISABLED(new HealthCheckInfo(Constants.HC_COMPONENT_DISTRIBUTION_ENGINE, HealthCheckStatus.DOWN, null, ClusterStatusDescription.DISABLED.getDescription()));

        private HealthCheckInfo healthCheckInfo;

        HealthCheckInfoResult(HealthCheckInfo healthCheckInfo) {
            this.healthCheckInfo = healthCheckInfo;
        }

        public HealthCheckInfo getHealthCheckInfo() {
            return healthCheckInfo;
        }

    }

    private HealthCheckInfo healthCheckInfo = HealthCheckInfoResult.UNAVAILABLE.getHealthCheckInfo();

    private Map<String, AtomicBoolean> envNamePerStatus = null;

    private ScheduledFuture<?> scheduledFuture = null;

    ScheduledExecutorService healthCheckScheduler = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r, "UEB-Health-Check-Task");
        }
    });

    HealthCheckScheduledTask healthCheckScheduledTask = null;

    public enum ClusterStatusDescription {

        OK("OK"), UNAVAILABLE("U-EB cluster is not available"), NOT_CONFIGURED("U-EB cluster is not configured"), DISABLED("DE is disabled in configuration");

        private String desc;

        ClusterStatusDescription(String desc) {
            this.desc = desc;
        }

        public String getDescription() {
            return desc;
        }

    }

    /**
     * Health Check Task Scheduler.
     *
     * 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.
     *
     *
     * @author esofer
     *
     */
    public class HealthCheckScheduledTask implements Runnable {

        List<UebHealthCheckCall> healthCheckCalls = new ArrayList<>();

        public HealthCheckScheduledTask(List<String> uebServers) {

            logger.debug("Create health check calls for servers {}", uebServers);
            if (uebServers != null) {
                for (String server : uebServers) {
                    healthCheckCalls.add(new UebHealthCheckCall(server, publicApiKey));
                }
            }
        }

        @Override
        public void run() {

            healthLogger.trace("Executing UEB Health Check Task - Start");

            boolean healthStatus = verifyAtLeastOneEnvIsUp();

            if (healthStatus) {
                boolean queryUebStatus = queryUeb();
                if (queryUebStatus == lastHealthState) {
                    return;
                }

                synchronized (lockOject) {
                    if (queryUebStatus != lastHealthState) {
                        logger.trace("UEB Health State Changed to {}. Issuing alarm / recovery alarm...", healthStatus);
                        lastHealthState = queryUebStatus;
                        logAlarm(lastHealthState);
                        if (queryUebStatus) {
                            healthCheckInfo = HealthCheckInfoResult.OK.getHealthCheckInfo();
                        } else {
                            healthCheckInfo = HealthCheckInfoResult.UNAVAILABLE.getHealthCheckInfo();
                        }
                    }
                }
            } else {
                healthLogger.trace("Not all UEB Environments are up");
            }

        }

        /**
         * verify that at least one environment is up.
         *
         */
        private boolean verifyAtLeastOneEnvIsUp() {

            boolean healthStatus = false;

            if (envNamePerStatus != null) {
                Collection<AtomicBoolean> values = envNamePerStatus.values();
                if (values != null) {
                    for (AtomicBoolean status : values) {
                        if (status.get()) {
                            healthStatus = true;
                            break;
                        }
                    }
                }
            }

            return healthStatus;
        }

        /**
         * executor for the query itself
         */
        ExecutorService healthCheckExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                return new Thread(r, "UEB-Health-Check-Thread");
            }
        });

        /**
         * 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.
         *
         *
         * @return
         */
        private boolean queryUeb() {

            Boolean result = false;
            int retryNumber = 1;
            for (UebHealthCheckCall healthCheckCall : healthCheckCalls) {
                try {

                    healthLogger.debug("Before running Health Check retry query number {} towards UEB server {}", retryNumber, healthCheckCall.getServer());

                    Future<Boolean> future = healthCheckExecutor.submit(healthCheckCall);
                    result = future.get(healthCheckReadTimeout, TimeUnit.SECONDS);

                    healthLogger.debug("After running Health Check retry query number {} towards UEB server {}. Result is {}", retryNumber, healthCheckCall.getServer(), result);

                    if (result != null && result.booleanValue()) {
                        break;
                    }

                } catch (Exception e) {
                    String message = e.getMessage();
                    if (message == null) {
                        message = e.getClass().getName();
                    }
                    healthLogger.debug("Error occured during running Health Check retry query towards UEB server {}. Result is {}", healthCheckCall.getServer(), message);
                    healthLogger.trace("Error occured during running Health Check retry query towards UEB server {}. Result is {}", healthCheckCall.getServer(), message, e);
                }
                retryNumber++;

            }

            return result;

        }

        public List<UebHealthCheckCall> getHealthCheckCalls() {
            return healthCheckCalls;
        }

    }

    @PostConstruct
    protected void init() {

        logger.trace("Enter init method of DistributionEngineClusterHealth");

        Long reconnectIntervalConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getUebHealthCheckReconnectIntervalInSeconds();
        if (reconnectIntervalConfig != null) {
            reconnectInterval = reconnectIntervalConfig.longValue();
        }
        Long healthCheckReadTimeoutConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getUebHealthCheckReadTimeout();
        if (healthCheckReadTimeoutConfig != null) {
            healthCheckReadTimeout = healthCheckReadTimeoutConfig.longValue();
        }

        DistributionEngineConfiguration distributionEngineConfiguration = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration();

        this.uebServers = distributionEngineConfiguration.getUebServers();
        this.publicApiKey = distributionEngineConfiguration.getUebPublicKey();

        this.healthCheckScheduledTask = new HealthCheckScheduledTask(this.uebServers);

        logger.trace("Exit init method of DistributionEngineClusterHealth");

    }

    @PreDestroy
    protected void destroy() {

        if (scheduledFuture != null) {
            scheduledFuture.cancel(true);
            scheduledFuture = null;
        }

        if (healthCheckScheduler != null) {
            healthCheckScheduler.shutdown();
        }

    }

    /**
     * Start health check task.
     *
     * @param envNamePerStatus
     * @param startTask
     */
    public void startHealthCheckTask(Map<String, AtomicBoolean> envNamePerStatus, boolean startTask) {
        this.envNamePerStatus = envNamePerStatus;

        if (startTask && this.scheduledFuture == null) {
            this.scheduledFuture = this.healthCheckScheduler.scheduleAtFixedRate(healthCheckScheduledTask, 0, reconnectInterval, TimeUnit.SECONDS);
        }
    }

    public void startHealthCheckTask(Map<String, AtomicBoolean> envNamePerStatus) {
        startHealthCheckTask(envNamePerStatus, true);
    }

    private void logAlarm(boolean lastHealthState) {
        if (lastHealthState) {
            BeEcompErrorManager.getInstance().logBeHealthCheckUebClusterRecovery(UEB_HEALTH_CHECK_STR);
        } else {
            BeEcompErrorManager.getInstance().logBeHealthCheckUebClusterError(UEB_HEALTH_CHECK_STR);
        }
    }

    public HealthCheckInfo getHealthCheckInfo() {
        return healthCheckInfo;
    }

    /**
     * change the health check to DISABLE
     */
    public void setHealthCheckUebIsDisabled() {
        healthCheckInfo = HealthCheckInfoResult.DISABLED.getHealthCheckInfo();
    }

    /**
     * change the health check to NOT CONFGIURED
     */
    public void setHealthCheckUebConfigurationError() {
        healthCheckInfo = HealthCheckInfoResult.NOT_CONFIGURED.getHealthCheckInfo();
    }

    public void setHealthCheckOkAndReportInCaseLastStateIsDown() {

        if (lastHealthState) {
            return;
        }
        synchronized (lockOject) {
            if (!lastHealthState) {
                logger.debug("Going to update health check state to available");
                lastHealthState = true;
                healthCheckInfo = HealthCheckInfoResult.OK.getHealthCheckInfo();
                logAlarm(lastHealthState);
            }
        }

    }

}