aboutsummaryrefslogtreecommitdiffstats
path: root/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEnginePollingTask.java
blob: 933d3ef4a1fcc8b219ab006a3279d4ea6e9871d4 (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
/*-
 * ============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 com.att.nsa.cambria.client.CambriaConsumer;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import fj.data.Either;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.openecomp.sdc.be.components.distribution.engine.report.DistributionCompleteReporter;
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.OperationalEnvironmentEntry;
import org.openecomp.sdc.common.log.wrappers.Logger;
import org.openecomp.sdc.common.log.wrappers.LoggerSdcAudit;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

public class DistributionEnginePollingTask implements Runnable {

    public static final String DISTRIBUTION_STATUS_POLLING = "distributionEngineStatusPolling";
    private static final String PARTNER_NAME = "UNKNOWN";

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

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

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

    private static final Logger logger = Logger.getLogger(DistributionEnginePollingTask.class.getName());
    private static LoggerSdcAudit audit = new LoggerSdcAudit(DistributionEnginePollingTask.class);

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

    private DistributionEngineClusterHealth distributionEngineClusterHealth = null;

    private OperationalEnvironmentEntry environmentEntry;

    public DistributionEnginePollingTask(DistributionEngineConfiguration distributionEngineConfiguration, DistributionCompleteReporter distributionCompleteReporter, ComponentsUtils componentUtils, DistributionEngineClusterHealth distributionEngineClusterHealth, OperationalEnvironmentEntry environmentEntry) {

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

    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(environmentEntry.getDmaapUebAddress(), topicName, environmentEntry.getUebApikey(), environmentEntry.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 = Object.class.getEnclosingMethod().getName();
            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 (!result) {
                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().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().logBeUebSystemError(DISTRIBUTION_STATUS_POLLING, "failed to fetch messages from topic " + topicName + " error: " + errorResponse);

                // 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);
                    audit.startAuditFetchLog(PARTNER_NAME, DistributionEnginePollingTask.class.getName());
                    handleDistributionNotificationMsg(notification, audit);
                    distributionEngineClusterHealth.setHealthCheckOkAndReportInCaseLastStateIsDown();
                } catch (Exception e) {
                    logger.debug("failed to convert message to object", e);
                    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 occurred", e);
            String methodName = Object.class.getEnclosingMethod().getName();
            BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(methodName, e.getMessage());
        }

    }

    private void handleDistributionNotificationMsg(DistributionStatusNotification notification, LoggerSdcAudit audit) {
        componentUtils.auditDistributionStatusNotification(notification.getDistributionID(),
                notification.getConsumerID(), topicName, notification.getArtifactURL(),
                String.valueOf(notification.getTimestamp()), notification.getStatus().name(),
                notification.getErrorReason(), audit);
        if (notification.isDistributionCompleteNotification()) {
            distributionCompleteReporter.reportDistributionComplete(notification);
        }
    }

    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();
        }
    }

}