aboutsummaryrefslogtreecommitdiffstats
path: root/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEnginePollingTask.java
blob: fc7c473d6b141b47b2dca81f513e9180c6b636db (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
/*-
 * ============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 java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.config.DistributionEngineConfiguration;
import org.openecomp.sdc.be.config.DistributionEngineConfiguration.DistributionStatusTopicConfig;
import org.openecomp.sdc.be.impl.ComponentsUtils;
import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
import org.openecomp.sdc.common.config.EcompErrorName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.att.nsa.cambria.client.CambriaConsumer;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import fj.data.Either;

public class DistributionEnginePollingTask implements Runnable {

	public static final String DISTRIBUTION_STATUS_POLLING = "distributionEngineStatusPolling";

	private String topicName;
	private ComponentsUtils componentUtils;
	private int fetchTimeoutInSec = 15;
	private int pollingIntervalInSec;
	private String consumerId;
	private String consumerGroup;
	private DistributionEngineConfiguration distributionEngineConfiguration;

	private CambriaHandler cambriaHandler = new CambriaHandler();
	private Gson gson = new GsonBuilder().setPrettyPrinting().create();

	private ScheduledExecutorService scheduledPollingService = Executors.newScheduledThreadPool(1, new BasicThreadFactory.Builder().namingPattern("TopicPollingThread-%d").build());

	private static Logger logger = LoggerFactory.getLogger(DistributionEnginePollingTask.class.getName());

	ScheduledFuture<?> scheduledFuture = null;
	private CambriaConsumer cambriaConsumer = null;

	private DistributionEngineClusterHealth distributionEngineClusterHealth = null;

	public DistributionEnginePollingTask(DistributionEngineConfiguration distributionEngineConfiguration, String envName, ComponentsUtils componentUtils, DistributionEngineClusterHealth distributionEngineClusterHealth) {

		this.componentUtils = componentUtils;
		this.distributionEngineConfiguration = distributionEngineConfiguration;
		DistributionStatusTopicConfig statusConfig = distributionEngineConfiguration.getDistributionStatusTopic();
		this.pollingIntervalInSec = statusConfig.getPollingIntervalSec();
		this.fetchTimeoutInSec = statusConfig.getFetchTimeSec();
		this.consumerGroup = statusConfig.getConsumerGroup();
		this.consumerId = statusConfig.getConsumerId();
		this.distributionEngineClusterHealth = distributionEngineClusterHealth;
	}

	public void startTask(String topicName) {

		this.topicName = topicName;
		logger.debug("start task for polling topic {}", topicName);
		if (fetchTimeoutInSec < 15) {
			logger.warn("fetchTimeout value should be greater or equal to 15 sec. use default");
			fetchTimeoutInSec = 15;
		}
		try {
			cambriaConsumer = cambriaHandler.createConsumer(distributionEngineConfiguration.getUebServers(), topicName, distributionEngineConfiguration.getUebPublicKey(), distributionEngineConfiguration.getUebSecretKey(), consumerId, consumerGroup,
					fetchTimeoutInSec * 1000);

			if (scheduledPollingService != null) {
				logger.debug("Start Distribution Engine polling task. polling interval {} seconds", pollingIntervalInSec);
				scheduledFuture = scheduledPollingService.scheduleAtFixedRate(this, 0, pollingIntervalInSec, TimeUnit.SECONDS);

			}
		} catch (Exception e) {
			logger.debug("unexpected error occured", e);
			String methodName = new Object() {
			}.getClass().getEnclosingMethod().getName();

			BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDistributionEngineSystemError, methodName, e.getMessage());
			BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(methodName, e.getMessage());
		}
	}

	public void stopTask() {
		if (scheduledFuture != null) {
			boolean result = scheduledFuture.cancel(true);
			logger.debug("Stop polling task. result = {}", result);
			if (false == result) {
				BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeUebSystemError, DISTRIBUTION_STATUS_POLLING, "try to stop the polling task");
				BeEcompErrorManager.getInstance().logBeUebSystemError(DISTRIBUTION_STATUS_POLLING, "try to stop the polling task");
			}
			scheduledFuture = null;
		}
		if (cambriaConsumer != null) {
			logger.debug("close consumer");
			cambriaHandler.closeConsumer(cambriaConsumer);
		}

	}

	public void destroy() {
		this.stopTask();
		shutdownExecutor();
	}

	@Override
	public void run() {
		logger.trace("run() method. polling queue {}", topicName);

		try {
			// init error
			if (cambriaConsumer == null) {
				BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeUebSystemError, DISTRIBUTION_STATUS_POLLING, "polling task was not initialized properly");
				BeEcompErrorManager.getInstance().logBeUebSystemError(DISTRIBUTION_STATUS_POLLING, "polling task was not initialized properly");
				stopTask();
				return;
			}

			Either<Iterable<String>, CambriaErrorResponse> fetchResult = cambriaHandler.fetchFromTopic(cambriaConsumer);
			// fetch error
			if (fetchResult.isRight()) {
				CambriaErrorResponse errorResponse = fetchResult.right().value();
				BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeUebSystemError, DISTRIBUTION_STATUS_POLLING, "failed to fetch messages from topic " + topicName + " error: " + fetchResult.right().value());
				BeEcompErrorManager.getInstance().logBeUebSystemError(DISTRIBUTION_STATUS_POLLING, "failed to fetch messages from topic " + topicName + " error: " + fetchResult.right().value());

				// TODO: if status== internal error (connection problem) change
				// state to inactive
				// in next try, if succeed - change to active
				return;
			}

			// success
			Iterable<String> messages = fetchResult.left().value();
			for (String message : messages) {
				logger.trace("received message {}", message);
				try {
					DistributionStatusNotification notification = gson.fromJson(message, DistributionStatusNotification.class);
					componentUtils.auditDistributionStatusNotification(AuditingActionEnum.DISTRIBUTION_STATUS, notification.getDistributionID(), notification.getConsumerID(), topicName, notification.getArtifactURL(),
							String.valueOf(notification.getTimestamp()), notification.getStatus().name(), notification.getErrorReason());

					distributionEngineClusterHealth.setHealthCheckOkAndReportInCaseLastStateIsDown();

				} catch (Exception e) {
					logger.debug("failed to convert message to object", e);
					BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeUebSystemError, DISTRIBUTION_STATUS_POLLING, "failed to parse message " + message + " from topic " + topicName + " error: " + fetchResult.right().value());
					BeEcompErrorManager.getInstance().logBeUebSystemError(DISTRIBUTION_STATUS_POLLING, "failed to parse message " + message + " from topic " + topicName + " error: " + fetchResult.right().value());
				}

			}
		} catch (Exception e) {
			logger.debug("unexpected error occured", e);
			String methodName = new Object() {
			}.getClass().getEnclosingMethod().getName();

			BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDistributionEngineSystemError, methodName, e.getMessage());
			BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(methodName, e.getMessage());
		}

	}

	private void shutdownExecutor() {
		if (scheduledPollingService == null)
			return;

		scheduledPollingService.shutdown(); // Disable new tasks from being
											// submitted
		try {
			// Wait a while for existing tasks to terminate
			if (!scheduledPollingService.awaitTermination(60, TimeUnit.SECONDS)) {
				scheduledPollingService.shutdownNow(); // Cancel currently
														// executing tasks
				// Wait a while for tasks to respond to being cancelled
				if (!scheduledPollingService.awaitTermination(60, TimeUnit.SECONDS))
					logger.debug("Pool did not terminate");
			}
		} catch (InterruptedException ie) {
			// (Re-)Cancel if current thread also interrupted
			scheduledPollingService.shutdownNow();
			// Preserve interrupt status
			Thread.currentThread().interrupt();
		}
	}

}