Initial TCA commit into DCAEGEN2
[dcaegen2/analytics/tca.git] / dcae-analytics-cdap-plugins / src / main / java / org / openecomp / dcae / apod / analytics / cdap / plugins / streaming / dmaap / DMaaPMRReceiver.java
1 /*
2  * ===============================LICENSE_START======================================
3  *  dcae-analytics
4  * ================================================================================
5  *    Copyright © 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.dcae.apod.analytics.cdap.plugins.streaming.dmaap;
22
23 import co.cask.cdap.api.data.format.StructuredRecord;
24 import co.cask.cdap.api.metrics.Metrics;
25 import com.google.common.base.Optional;
26 import org.apache.spark.storage.StorageLevel;
27 import org.apache.spark.streaming.receiver.Receiver;
28 import org.openecomp.dcae.apod.analytics.cdap.common.utils.DMaaPMRUtils;
29 import org.openecomp.dcae.apod.analytics.cdap.plugins.domain.config.dmaap.DMaaPMRSourcePluginConfig;
30 import org.openecomp.dcae.apod.analytics.cdap.plugins.utils.CDAPPluginUtils;
31 import org.openecomp.dcae.apod.analytics.cdap.plugins.utils.DMaaPSourceConfigMapper;
32 import org.openecomp.dcae.apod.analytics.common.exception.DCAEAnalyticsRuntimeException;
33 import org.openecomp.dcae.apod.analytics.dmaap.DMaaPMRFactory;
34 import org.openecomp.dcae.apod.analytics.dmaap.service.subscriber.DMaaPMRSubscriber;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
37
38 import java.util.List;
39 import java.util.concurrent.TimeUnit;
40
41 /**
42  * DMaaP MR Receiver which calls DMaaP MR Topic and stores structured records
43  * <p>
44  * @author Rajiv Singla . Creation Date: 1/19/2017.
45  */
46 public class DMaaPMRReceiver extends Receiver<StructuredRecord> {
47
48     private static final Logger LOG = LoggerFactory.getLogger(DMaaPMRReceiver.class);
49     private static final long serialVersionUID = 1L;
50
51     private final DMaaPMRSourcePluginConfig pluginConfig;
52     private final Metrics metrics;
53
54     public DMaaPMRReceiver(final StorageLevel storageLevel, final DMaaPMRSourcePluginConfig pluginConfig,
55                            final Metrics metrics) {
56         super(storageLevel);
57         this.pluginConfig = pluginConfig;
58         this.metrics = metrics;
59         LOG.debug("Created DMaaP MR Receiver instance with plugin Config: {}", pluginConfig);
60     }
61
62     @Override
63     public void onStart() {
64
65         // create DMaaP MR Subscriber
66         final DMaaPMRSubscriber subscriber =
67                 DMaaPMRFactory.create().createSubscriber(DMaaPSourceConfigMapper.map(pluginConfig));
68
69         // Start a new thread with indefinite loop until receiver is stopped
70         new Thread() {
71             @Override
72             public void run() {
73                 while (!isStopped()) {
74                     storeStructuredRecords(subscriber);
75                     try {
76                         final Integer pollingInterval = pluginConfig.getPollingInterval();
77                         LOG.debug("DMaaP MR Receiver sleeping for polling interval: {}", pollingInterval);
78                         TimeUnit.MILLISECONDS.sleep(pollingInterval);
79                     } catch (InterruptedException e) {
80                         final String errorMessage = String.format(
81                                 "Interrupted Exception while DMaaP MR Receiver sleeping polling interval: %s", e);
82                         throw new DCAEAnalyticsRuntimeException(errorMessage, LOG, e);
83                     }
84                 }
85             }
86         }.start();
87
88     }
89
90     @Override
91     public void onStop() {
92         LOG.debug("Stopping DMaaP MR Receiver with plugin config: {}", pluginConfig);
93     }
94
95     /**
96      * Fetches records from DMaaP MR Subscriber and store them as structured records
97      *
98      * @param subscriber DMaaP MR Subscriber Instance
99      */
100     public void storeStructuredRecords(final DMaaPMRSubscriber subscriber) {
101
102         LOG.debug("DMaaP MR Receiver start fetching messages from DMaaP MR Topic");
103
104         // Fetch messages from DMaaP MR Topic
105         final Optional<List<String>> subscriberMessagesOptional =
106                 DMaaPMRUtils.getSubscriberMessages(subscriber, metrics);
107
108         // store records
109         if (subscriberMessagesOptional.isPresent()) {
110             final List<String> messages = subscriberMessagesOptional.get();
111             for (final String message : messages) {
112                 store(CDAPPluginUtils.createDMaaPMRResponseStructuredRecord(message));
113             }
114             LOG.debug("Stored DMaaP Subscriber messages as Structured Records. Message count {}", messages.size());
115         }
116     }
117
118 }