2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights
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
12 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
22 package org.openecomp.appc.adapter.messaging.dmaap.impl;
24 import java.io.IOException;
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;
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;
51 public class DmaapConsumerImpl implements Consumer {
53 private static final EELFLogger LOG = EELFManager.getInstance().getLogger(DmaapConsumerImpl.class);
54 private static final Configuration configuration = ConfigurationFactory.getConfiguration();
56 private static final int DEFAULT_TIMEOUT_MS = 60000;
57 private static final int DEFAULT_LIMIT = 1000;
58 private static MetricRegistry metricRegistry;
60 private DmaapRequestCounterMetric dmaapKpiMetric;
61 private boolean isMetricEnabled=false;
62 private boolean useHttps = false;
63 private MRConsumer client = null;
64 private Properties props = null;
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);
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);
82 props.setProperty("filter", filter);
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)
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).
106 LOG.debug("Policy getting initialized");
107 manuallyScheduledPublishingPolicy.init();
108 LOG.debug("Metric initialized");
111 private MRConsumer getClient() {
112 return getClient(DEFAULT_TIMEOUT_MS, DEFAULT_LIMIT);
116 * @return An instance of MRConsumer created from our class variables
118 private synchronized MRConsumer getClient(int waitMs, int limit) {
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);
131 public synchronized void updateCredentials(String key, String secret) {
132 LOG.info(String.format("Setting auth to %s for %s", key, this.toString()));
134 String password = secret;
135 props.setProperty("user",String.valueOf(user));
136 props.setProperty("password",String.valueOf(password));
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"));
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>();
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);
159 for (String s : client.fetch(waitMs, limit)) {
162 ((DmaapRequestCounterMetric)metricRegistry.metric("DMAAP_KPI")).incrementRecievedMessage();
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()));
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));
183 * Close consumer Dmaap client
186 public void close() {
187 LOG.debug("Closing Dmaap consumer client....");
188 if (client != null) {
194 public List<String> fetch() {
195 return fetch(DEFAULT_TIMEOUT_MS, DEFAULT_LIMIT);
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);
207 public void useHttps(boolean yes) {
212 private MetricService getMetricservice() {
213 BundleContext bctx = FrameworkUtil.getBundle(MetricService.class).getBundleContext();
214 // Get AAIadapter reference
215 ServiceReference sref = bctx.getServiceReference(MetricService.class.getName());
217 LOG.info("Metric Service from bundlecontext");
218 return (MetricServiceImpl) bctx.getService(sref);
221 LOG.info("Metric Service error from bundlecontext");
222 LOG.warn("Cannot find service reference for org.openecomp.appc.metricservice.MetricService");
228 public Metric getMetric(String name){
229 return metricRegistry.metric(name);