2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Copyright (C) 2017 Amdocs
8 * =============================================================================
9 * Licensed under the Apache License, Version 2.0 (the "License");
10 * you may not use this file except in compliance with the License.
11 * You may obtain a copy of the License at
13 * http://www.apache.org/licenses/LICENSE-2.0
15 * Unless required by applicable law or agreed to in writing, software
16 * distributed under the License is distributed on an "AS IS" BASIS,
17 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 * See the License for the specific language governing permissions and
19 * limitations under the License.
21 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22 * ============LICENSE_END=========================================================
25 package org.onap.appc.adapter.messaging.dmaap.impl;
27 import java.io.IOException;
30 import com.att.eelf.configuration.EELFLogger;
31 import com.att.eelf.configuration.EELFManager;
32 //import com.att.nsa.cambria.client.CambriaClientBuilders;
33 //import com.att.nsa.cambria.client.CambriaClientBuilders.ConsumerBuilder;
34 //import com.att.nsa.cambria.client.CambriaConsumer;
36 import com.att.nsa.mr.client.MRClientFactory;
37 import com.att.nsa.mr.client.MRConsumer;
38 import org.apache.commons.lang3.StringUtils;
39 import org.onap.appc.adapter.message.Consumer;
40 import org.onap.appc.configuration.Configuration;
41 import org.onap.appc.configuration.ConfigurationFactory;
42 import org.onap.appc.metricservice.MetricRegistry;
43 import org.onap.appc.metricservice.MetricService;
44 import org.onap.appc.metricservice.impl.MetricServiceImpl;
45 import org.onap.appc.metricservice.metric.Metric;
46 import org.onap.appc.metricservice.metric.MetricType;
47 import org.onap.appc.metricservice.metric.DmaapRequestCounterMetric;
48 import org.onap.appc.metricservice.policy.PublishingPolicy;
49 import org.onap.appc.metricservice.publisher.LogPublisher;
50 import org.osgi.framework.BundleContext;
51 import org.osgi.framework.FrameworkUtil;
52 import org.osgi.framework.ServiceReference;
54 public class DmaapConsumerImpl implements Consumer {
56 private final EELFLogger LOG = EELFManager.getInstance().getLogger(DmaapConsumerImpl.class);
57 private final Configuration configuration = ConfigurationFactory.getConfiguration();
59 private static final int DEFAULT_TIMEOUT_MS = 60000;
60 private static final int DEFAULT_LIMIT = 1000;
61 private static MetricRegistry metricRegistry;
63 private boolean isMetricEnabled=false;
64 private boolean useHttps = false;
65 private MRConsumer client = null;
66 private Properties props = null;
69 public DmaapConsumerImpl(Collection<String> urls, String topicName, String consumerGroupName, String consumerId,String user, String password) {
70 this(urls, topicName, consumerGroupName, consumerId,user, password,null);
74 public DmaapConsumerImpl(Collection<String> urls, String topicName, String consumerGroupName, String consumerId,String user, String password,String filter) {
75 this.topic = topicName;
76 this.props = new Properties();
77 String urlsStr = StringUtils.join(urls, ',');
78 props.setProperty("host",urlsStr);
79 props.setProperty("group",consumerGroupName);
80 props.setProperty("id",consumerId);
81 props.setProperty("username",user);
82 props.setProperty("password",password);
84 props.setProperty("filter", filter);
89 private void initMetric() {
90 LOG.debug("Metric getting initialized");
91 MetricService metricService = getMetricservice();
92 metricRegistry = metricService.createRegistry("APPC");
93 DmaapRequestCounterMetric dmaapKpiMetric = metricRegistry.metricBuilderFactory().
94 dmaapRequestCounterBuilder().
95 withName("DMAAP_KPI").withType(MetricType.COUNTER).
96 withRecievedMessage(0)
97 .withPublishedMessage(0)
99 if (metricRegistry.register(dmaapKpiMetric)) {
100 Metric[] metrics = new Metric[]{dmaapKpiMetric};
101 LogPublisher logPublisher = new LogPublisher(metricRegistry, metrics);
102 LogPublisher[] logPublishers = new LogPublisher[1];
103 logPublishers[0] = logPublisher;
104 PublishingPolicy manuallyScheduledPublishingPolicy = metricRegistry.policyBuilderFactory().
105 scheduledPolicyBuilder().withPublishers(logPublishers).
106 withMetrics(metrics).
108 LOG.debug("Policy getting initialized");
109 manuallyScheduledPublishingPolicy.init();
110 LOG.debug("Metric initialized");
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()));
133 props.setProperty("user",String.valueOf(key));
134 props.setProperty("password",String.valueOf(secret));
139 public List<String> fetch(int waitMs, int limit) {
140 Properties properties=configuration.getProperties();
141 if(properties!=null && properties.getProperty("metric.enabled")!=null ){
142 isMetricEnabled=Boolean.valueOf(properties.getProperty("metric.enabled"));
147 LOG.debug(String.format("Fetching up to %d records with %dms wait on %s", limit, waitMs, this.toString()));
148 List<String> out = new ArrayList<>();
150 // Create client once and reuse it on subsequent fetches. This is
151 // to support failover to other servers in the DMaaP cluster.
152 if (client == null) {
153 LOG.info("Getting DMaaP Client ...");
154 client = getClient(waitMs, limit);
157 for (String s : client.fetch(waitMs, limit)) {
160 ((DmaapRequestCounterMetric)metricRegistry.metric("DMAAP_KPI")).incrementRecievedMessage();
163 LOG.debug(String.format("Got %d records from %s", out.size(), this.toString()));
164 } catch (Exception e) {
165 // Connection exception
166 LOG.error(String.format("Dmaap Connection Issue Detected. %s", e.getMessage()));
169 LOG.warn(String.format("Sleeping for %dms to compensate for connection failure", waitMs));
170 Thread.sleep(waitMs);
171 } catch (InterruptedException e2) {
172 LOG.warn(String.format("Failed to wait for %dms after bad fetch", waitMs));
181 * Close consumer Dmaap client
184 public void close() {
185 LOG.debug("Closing Dmaap consumer client....");
186 if (client != null) {
192 public List<String> fetch() {
193 return fetch(DEFAULT_TIMEOUT_MS, DEFAULT_LIMIT);
197 public String toString() {
198 String hostStr = (props == null || props.getProperty("host") == null? "N/A" : props.getProperty("host"));
199 String group = (props == null || props.getProperty("group") == null? "N/A" : props.getProperty("group"));
200 String id = (props == null || props.getProperty("id") == null? "N/A" : props.getProperty("id"));
201 return String.format("Consumer %s/%s listening to %s on [%s]", group, id, topic, hostStr);
205 public void useHttps(boolean yes) {
210 private MetricService getMetricservice() {
211 BundleContext bctx = FrameworkUtil.getBundle(MetricService.class).getBundleContext();
212 // Get AAIadapter reference
213 ServiceReference sref = bctx.getServiceReference(MetricService.class.getName());
215 LOG.info("Metric Service from bundlecontext");
216 return (MetricServiceImpl) bctx.getService(sref);
219 LOG.info("Metric Service error from bundlecontext");
220 LOG.warn("Cannot find service reference for org.onap.appc.metricservice.MetricService");