Sync Integ to Master
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / components / distribution / engine / DistributionEnginePollingTask.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.distribution.engine;
22
23 import com.att.nsa.cambria.client.CambriaConsumer;
24 import com.google.gson.Gson;
25 import com.google.gson.GsonBuilder;
26 import fj.data.Either;
27 import org.apache.commons.lang3.concurrent.BasicThreadFactory;
28 import org.openecomp.sdc.be.components.distribution.engine.report.DistributionCompleteReporter;
29 import org.openecomp.sdc.be.config.BeEcompErrorManager;
30 import org.openecomp.sdc.be.config.DistributionEngineConfiguration;
31 import org.openecomp.sdc.be.config.DistributionEngineConfiguration.DistributionStatusTopicConfig;
32 import org.openecomp.sdc.be.impl.ComponentsUtils;
33 import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry;
34 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
37
38 import java.util.concurrent.Executors;
39 import java.util.concurrent.ScheduledExecutorService;
40 import java.util.concurrent.ScheduledFuture;
41 import java.util.concurrent.TimeUnit;
42
43 public class DistributionEnginePollingTask implements Runnable {
44
45     public static final String DISTRIBUTION_STATUS_POLLING = "distributionEngineStatusPolling";
46
47     private String topicName;
48     private ComponentsUtils componentUtils;
49     private int fetchTimeoutInSec = 15;
50     private int pollingIntervalInSec;
51     private String consumerId;
52     private String consumerGroup;
53
54     private CambriaHandler cambriaHandler = new CambriaHandler();
55     private Gson gson = new GsonBuilder().setPrettyPrinting().create();
56     private DistributionCompleteReporter distributionCompleteReporter;
57
58     private ScheduledExecutorService scheduledPollingService = Executors.newScheduledThreadPool(1, new BasicThreadFactory.Builder().namingPattern("TopicPollingThread-%d").build());
59
60     private static final Logger logger = LoggerFactory.getLogger(DistributionEnginePollingTask.class);
61
62     ScheduledFuture<?> scheduledFuture = null;
63     private CambriaConsumer cambriaConsumer = null;
64
65     private DistributionEngineClusterHealth distributionEngineClusterHealth = null;
66
67     private OperationalEnvironmentEntry environmentEntry;
68
69     public DistributionEnginePollingTask(DistributionEngineConfiguration distributionEngineConfiguration, DistributionCompleteReporter distributionCompleteReporter, ComponentsUtils componentUtils, DistributionEngineClusterHealth distributionEngineClusterHealth, OperationalEnvironmentEntry environmentEntry) {
70
71         this.componentUtils = componentUtils;
72         DistributionStatusTopicConfig statusConfig = distributionEngineConfiguration.getDistributionStatusTopic();
73         this.pollingIntervalInSec = statusConfig.getPollingIntervalSec();
74         this.fetchTimeoutInSec = statusConfig.getFetchTimeSec();
75         this.consumerGroup = statusConfig.getConsumerGroup();
76         this.consumerId = statusConfig.getConsumerId();
77         this.distributionEngineClusterHealth = distributionEngineClusterHealth;
78         this.environmentEntry = environmentEntry;
79         this.distributionCompleteReporter = distributionCompleteReporter;
80     }
81
82     public void startTask(String topicName) {
83
84         this.topicName = topicName;
85         logger.debug("start task for polling topic {}", topicName);
86         if (fetchTimeoutInSec < 15) {
87             logger.warn("fetchTimeout value should be greater or equal to 15 sec. use default");
88             fetchTimeoutInSec = 15;
89         }
90         try {
91             cambriaConsumer = cambriaHandler.createConsumer(environmentEntry.getDmaapUebAddress(), topicName, environmentEntry.getUebApikey(), environmentEntry.getUebSecretKey(), consumerId, consumerGroup,
92                     fetchTimeoutInSec * 1000);
93
94             if (scheduledPollingService != null) {
95                 logger.debug("Start Distribution Engine polling task. polling interval {} seconds", pollingIntervalInSec);
96                 scheduledFuture = scheduledPollingService.scheduleAtFixedRate(this, 0, pollingIntervalInSec, TimeUnit.SECONDS);
97
98             }
99         } catch (Exception e) {
100             logger.debug("unexpected error occured", e);
101             String methodName = new Object() {
102             }.getClass().getEnclosingMethod().getName();
103
104             BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(methodName, e.getMessage());
105         }
106     }
107
108     public void stopTask() {
109         if (scheduledFuture != null) {
110             boolean result = scheduledFuture.cancel(true);
111             logger.debug("Stop polling task. result = {}", result);
112             if (false == result) {
113                 BeEcompErrorManager.getInstance().logBeUebSystemError(DISTRIBUTION_STATUS_POLLING, "try to stop the polling task");
114             }
115             scheduledFuture = null;
116         }
117         if (cambriaConsumer != null) {
118             logger.debug("close consumer");
119             cambriaHandler.closeConsumer(cambriaConsumer);
120         }
121
122     }
123
124     public void destroy() {
125         this.stopTask();
126         shutdownExecutor();
127     }
128
129     @Override
130     public void run() {
131         logger.trace("run() method. polling queue {}", topicName);
132
133         try {
134             // init error
135             if (cambriaConsumer == null) {
136                 BeEcompErrorManager.getInstance().logBeUebSystemError(DISTRIBUTION_STATUS_POLLING, "polling task was not initialized properly");
137                 stopTask();
138                 return;
139             }
140
141             Either<Iterable<String>, CambriaErrorResponse> fetchResult = cambriaHandler.fetchFromTopic(cambriaConsumer);
142             // fetch error
143             if (fetchResult.isRight()) {
144                 CambriaErrorResponse errorResponse = fetchResult.right().value();
145                 BeEcompErrorManager.getInstance().logBeUebSystemError(DISTRIBUTION_STATUS_POLLING, "failed to fetch messages from topic " + topicName + " error: " + errorResponse);
146
147                 // TODO: if status== internal error (connection problem) change
148                 // state to inactive
149                 // in next try, if succeed - change to active
150                 return;
151             }
152
153             // success
154             Iterable<String> messages = fetchResult.left().value();
155             for (String message : messages) {
156                 logger.trace("received message {}", message);
157                 try {
158                     DistributionStatusNotification notification = gson.fromJson(message, DistributionStatusNotification.class);
159                     handleDistributionNotificationMsg(notification);
160                     distributionEngineClusterHealth.setHealthCheckOkAndReportInCaseLastStateIsDown();
161                 } catch (Exception e) {
162                     logger.debug("failed to convert message to object", e);
163                     BeEcompErrorManager.getInstance().logBeUebSystemError(DISTRIBUTION_STATUS_POLLING, "failed to parse message " + message + " from topic " + topicName + " error: " + fetchResult.right().value());
164                 }
165
166             }
167         } catch (Exception e) {
168             logger.debug("unexpected error occured", e);
169             String methodName = new Object() {
170             }.getClass().getEnclosingMethod().getName();
171
172             BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(methodName, e.getMessage());
173         }
174
175     }
176
177     private void handleDistributionNotificationMsg(DistributionStatusNotification notification) {
178         componentUtils.auditDistributionStatusNotification(AuditingActionEnum.DISTRIBUTION_STATUS, notification.getDistributionID(), notification.getConsumerID(), topicName, notification.getArtifactURL(),
179                 String.valueOf(notification.getTimestamp()), notification.getStatus().name(), notification.getErrorReason());
180         if (notification.isDistributionCompleteNotification()) {
181             distributionCompleteReporter.reportDistributionComplete(notification);
182         }
183     }
184
185     private void shutdownExecutor() {
186         if (scheduledPollingService == null)
187             return;
188
189         scheduledPollingService.shutdown(); // Disable new tasks from being
190         // submitted
191         try {
192             // Wait a while for existing tasks to terminate
193             if (!scheduledPollingService.awaitTermination(60, TimeUnit.SECONDS)) {
194                 scheduledPollingService.shutdownNow(); // Cancel currently
195                 // executing tasks
196                 // Wait a while for tasks to respond to being cancelled
197                 if (!scheduledPollingService.awaitTermination(60, TimeUnit.SECONDS))
198                     logger.debug("Pool did not terminate");
199             }
200         } catch (InterruptedException ie) {
201             // (Re-)Cancel if current thread also interrupted
202             scheduledPollingService.shutdownNow();
203             // Preserve interrupt status
204             Thread.currentThread().interrupt();
205         }
206     }
207
208 }