Merge of new rebased code
[appc.git] / appc-adapters / appc-dmaap-adapter / appc-dmaap-adapter-bundle / src / main / java / org / openecomp / appc / adapter / messaging / dmaap / impl / DmaapConsumerImpl.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * openECOMP : APP-C
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights
6  *                                              reserved.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  * 
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  * 
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.openecomp.appc.adapter.messaging.dmaap.impl;
23
24 import java.io.IOException;
25 import java.util.*;
26
27 import com.att.eelf.configuration.EELFLogger;
28 import com.att.eelf.configuration.EELFManager;
29 //import com.att.nsa.cambria.client.CambriaClientBuilders;
30 //import com.att.nsa.cambria.client.CambriaClientBuilders.ConsumerBuilder;
31 //import com.att.nsa.cambria.client.CambriaConsumer;
32
33 import com.att.nsa.mr.client.MRClientFactory;
34 import com.att.nsa.mr.client.MRConsumer;
35 import org.apache.commons.lang3.StringUtils;
36 import org.openecomp.appc.adapter.message.Consumer;
37 import org.openecomp.appc.configuration.Configuration;
38 import org.openecomp.appc.configuration.ConfigurationFactory;
39 import org.openecomp.appc.metricservice.MetricRegistry;
40 import org.openecomp.appc.metricservice.MetricService;
41 import org.openecomp.appc.metricservice.impl.MetricServiceImpl;
42 import org.openecomp.appc.metricservice.metric.Metric;
43 import org.openecomp.appc.metricservice.metric.MetricType;
44 import org.openecomp.appc.metricservice.metric.DmaapRequestCounterMetric;
45 import org.openecomp.appc.metricservice.policy.PublishingPolicy;
46 import org.openecomp.appc.metricservice.publisher.LogPublisher;
47 import org.osgi.framework.BundleContext;
48 import org.osgi.framework.FrameworkUtil;
49 import org.osgi.framework.ServiceReference;
50
51 public class DmaapConsumerImpl implements Consumer {
52
53     private static final EELFLogger LOG = EELFManager.getInstance().getLogger(DmaapConsumerImpl.class);
54     private static final Configuration configuration = ConfigurationFactory.getConfiguration();
55     // Default values
56     private static final int DEFAULT_TIMEOUT_MS = 60000;
57     private static final int DEFAULT_LIMIT = 1000;
58     private static MetricRegistry metricRegistry;
59     private String topic;
60     private DmaapRequestCounterMetric dmaapKpiMetric;
61     private boolean isMetricEnabled=false;
62     private boolean useHttps = false;
63     private MRConsumer client = null;
64     private Properties props = null;
65
66
67     public DmaapConsumerImpl(Collection<String> urls, String topicName, String consumerGroupName, String consumerId,String user, String password) {
68         this(urls, topicName, consumerGroupName, consumerId,user, password,null);
69
70     }
71
72     public DmaapConsumerImpl(Collection<String> urls, String topicName, String consumerGroupName, String consumerId,String user, String password,String filter) {
73         this.topic = topicName;
74         this.props = new Properties();
75         String urlsStr = StringUtils.join(urls, ',');
76         props.setProperty("host",urlsStr);
77         props.setProperty("group",consumerGroupName);
78         props.setProperty("id",consumerId);
79         props.setProperty("username",user);
80         props.setProperty("password",password);
81         if(filter != null) {
82             props.setProperty("filter", filter);
83         }
84     }
85
86
87     private void initMetric() {
88         LOG.debug("Metric getting initialized");
89         MetricService metricService = getMetricservice();
90         metricRegistry = metricService.createRegistry("APPC");
91         dmaapKpiMetric = metricRegistry.metricBuilderFactory().
92                 dmaapRequestCounterBuilder().
93                 withName("DMAAP_KPI").withType(MetricType.COUNTER).
94                 withRecievedMessage(0)
95                 .withPublishedMessage(0)
96                 .build();
97         if (metricRegistry.register(dmaapKpiMetric)) {
98             Metric[] metrics = new Metric[]{dmaapKpiMetric};
99             LogPublisher logPublisher = new LogPublisher(metricRegistry, metrics);
100             LogPublisher[] logPublishers = new LogPublisher[1];
101             logPublishers[0] = logPublisher;
102             PublishingPolicy manuallyScheduledPublishingPolicy = metricRegistry.policyBuilderFactory().
103                     scheduledPolicyBuilder().withPublishers(logPublishers).
104                     withMetrics(metrics).
105                     build();
106             LOG.debug("Policy getting initialized");
107             manuallyScheduledPublishingPolicy.init();
108             LOG.debug("Metric initialized");
109         }
110     }
111     private MRConsumer getClient() {
112         return getClient(DEFAULT_TIMEOUT_MS, DEFAULT_LIMIT);
113     }
114
115     /**
116      * @return An instance of MRConsumer created from our class variables
117      */
118     private synchronized MRConsumer getClient(int waitMs, int limit) {
119         try {
120             props.setProperty("timeout",String.valueOf(waitMs));
121             props.setProperty("limit",String.valueOf(limit));
122             String topicProducerPropFileName = DmaapUtil.createConsumerPropFile(topic,props);
123             return MRClientFactory.createConsumer ( topicProducerPropFileName);
124         } catch (IOException e1) {
125             LOG.error("failed to createConsumer",e1);
126             return null;
127         }
128     }
129
130     @Override
131     public synchronized void updateCredentials(String key, String secret) {
132         LOG.info(String.format("Setting auth to %s for %s", key, this.toString()));
133         String user = key;
134         String password = secret;
135         props.setProperty("user",String.valueOf(user));
136         props.setProperty("password",String.valueOf(password));
137         client = null;
138     }
139
140     @Override
141     public List<String> fetch(int waitMs, int limit) {
142         Properties properties=configuration.getProperties();
143         if(properties!=null && properties.getProperty("metric.enabled")!=null ){
144           isMetricEnabled=Boolean.valueOf(properties.getProperty("metric.enabled"));
145         }
146         if(isMetricEnabled){
147             initMetric();
148         }
149         LOG.debug(String.format("Fetching up to %d records with %dms wait on %s", limit, waitMs, this.toString()));
150         List<String> out = new ArrayList<String>();
151
152         // Create client once and reuse it on subsequent fetches. This is
153         // to support failover to other servers in the DMaaP cluster.
154         if (client == null) {
155                 LOG.info("Getting DMaaP Client ...");
156                 client = getClient(waitMs, limit);
157         }
158         try {
159             for (String s : client.fetch(waitMs, limit)) {
160                 out.add(s);
161                 if(isMetricEnabled){
162                     ((DmaapRequestCounterMetric)metricRegistry.metric("DMAAP_KPI")).incrementRecievedMessage();
163                 }
164             }
165             LOG.debug(String.format("Got %d records from %s", out.size(), this.toString()));
166         } catch (Exception e) {
167             // Connection exception
168             LOG.error(String.format("Dmaap Connection Issue Detected. %s", e.getMessage()));
169             e.printStackTrace();
170             try {
171                 LOG.warn(String.format("Sleeping for %dms to compensate for connection failure", waitMs));
172                 Thread.sleep(waitMs);
173             } catch (InterruptedException e2) {
174                 LOG.warn(String.format("Failed to wait for %dms after bad fetch", waitMs));
175             }
176         }
177
178
179         return out;
180     }
181
182     /**
183      * Close consumer Dmaap client
184      */
185     @Override
186     public void close() {
187         LOG.debug("Closing Dmaap consumer client....");
188         if (client != null) {
189                 client.close();
190         }
191     }
192
193     @Override
194     public List<String> fetch() {
195         return fetch(DEFAULT_TIMEOUT_MS, DEFAULT_LIMIT);
196     }
197
198     @Override
199     public String toString() {
200         String hostStr = (props == null || props.getProperty("host") == null? "N/A" : props.getProperty("host"));
201         String group = (props == null || props.getProperty("group") == null? "N/A" : props.getProperty("group"));
202         String id = (props == null || props.getProperty("id") == null? "N/A" : props.getProperty("id"));
203         return String.format("Consumer %s/%s listening to %s on [%s]", group, id, topic, hostStr);
204     }
205
206     @Override
207     public void useHttps(boolean yes) {
208         useHttps = yes;
209     }
210
211
212     private MetricService getMetricservice() {
213         BundleContext bctx = FrameworkUtil.getBundle(MetricService.class).getBundleContext();
214         // Get AAIadapter reference
215         ServiceReference sref = bctx.getServiceReference(MetricService.class.getName());
216         if (sref != null) {
217             LOG.info("Metric Service from bundlecontext");
218             return (MetricServiceImpl) bctx.getService(sref);
219
220         } else {
221             LOG.info("Metric Service error from bundlecontext");
222             LOG.warn("Cannot find service reference for org.openecomp.appc.metricservice.MetricService");
223             return null;
224
225         }
226     }
227
228     public  Metric getMetric(String name){
229         return metricRegistry.metric(name);
230     }
231 }