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 com.att.eelf.configuration.EELFLogger;
28 import com.att.eelf.configuration.EELFManager;
29 import com.att.nsa.mr.client.MRClientFactory;
30 import com.att.nsa.mr.client.MRConsumer;
31 import java.io.IOException;
32 import java.util.ArrayList;
33 import java.util.Collection;
34 import java.util.List;
35 import java.util.Properties;
36 import org.apache.commons.lang3.StringUtils;
37 import org.onap.appc.adapter.message.Consumer;
38 import org.onap.appc.configuration.Configuration;
39 import org.onap.appc.configuration.ConfigurationFactory;
40 import org.onap.appc.metricservice.MetricRegistry;
41 import org.onap.appc.metricservice.MetricService;
42 import org.onap.appc.metricservice.metric.DmaapRequestCounterMetric;
43 import org.onap.appc.metricservice.metric.Metric;
44 import org.onap.appc.metricservice.metric.MetricType;
45 import org.onap.appc.metricservice.policy.PublishingPolicy;
46 import org.onap.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 final Configuration configuration = ConfigurationFactory.getConfiguration();
56 private static final int DEFAULT_TIMEOUT_MS = 60000;
57 private static final int DEFAULT_LIMIT = 1000;
59 private boolean isMetricEnabled = false;
60 private boolean useHttps = false;
61 private MetricRegistry metricRegistry;
62 private MRConsumer client = null;
63 private Properties props = null;
66 public DmaapConsumerImpl(Collection<String> urls, String topicName, String consumerGroupName, String consumerId,
67 String user, String password) {
69 this(urls, topicName, consumerGroupName, consumerId,user, password,null);
72 public DmaapConsumerImpl(Collection<String> urls, String topicName, String consumerGroupName, String consumerId,
73 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);
88 private void initMetric() {
89 LOG.debug("Metric getting initialized");
90 MetricService metricService = getMetricservice();
91 if (metricService != null) {
92 metricRegistry = metricService.createRegistry("APPC");
94 DmaapRequestCounterMetric dmaapKpiMetric = metricRegistry.metricBuilderFactory()
95 .dmaapRequestCounterBuilder()
96 .withName("DMAAP_KPI").withType(MetricType.COUNTER)
97 .withRecievedMessage(0)
98 .withPublishedMessage(0)
101 if (metricRegistry.register(dmaapKpiMetric)) {
102 Metric[] metrics = new Metric[]{dmaapKpiMetric};
103 LogPublisher logPublisher = new LogPublisher(metricRegistry, metrics);
104 LogPublisher[] logPublishers = new LogPublisher[1];
105 logPublishers[0] = logPublisher;
107 PublishingPolicy manuallyScheduledPublishingPolicy = metricRegistry.policyBuilderFactory()
108 .scheduledPolicyBuilder().withPublishers(logPublishers)
109 .withMetrics(metrics)
112 LOG.debug("Policy getting initialized");
113 manuallyScheduledPublishingPolicy.init();
114 LOG.debug("Metric initialized");
120 * @return An instance of MRConsumer created from our class variables.
122 private synchronized MRConsumer getClient(int waitMs, int limit) {
124 props.setProperty("timeout",String.valueOf(waitMs));
125 props.setProperty("limit",String.valueOf(limit));
126 String topicProducerPropFileName = DmaapUtil.createConsumerPropFile(topic,props);
127 return MRClientFactory.createConsumer(topicProducerPropFileName);
128 } catch (IOException e1) {
129 LOG.error("failed to createConsumer",e1);
135 public synchronized void updateCredentials(String key, String secret) {
136 LOG.info(String.format("Setting auth to %s for %s", key, this.toString()));
137 props.setProperty("user",String.valueOf(key));
138 props.setProperty("password",String.valueOf(secret));
143 public List<String> fetch() {
144 return fetch(DEFAULT_TIMEOUT_MS, DEFAULT_LIMIT);
148 public List<String> fetch(int waitMs, int limit) {
149 Properties properties = configuration.getProperties();
150 if (properties != null && properties.getProperty("metric.enabled") != null) {
151 isMetricEnabled = Boolean.valueOf(properties.getProperty("metric.enabled"));
153 if (isMetricEnabled) {
156 LOG.debug(String.format("Fetching up to %d records with %dms wait on %s", limit, waitMs, this.toString()));
157 List<String> out = new ArrayList<>();
159 // Create client once and reuse it on subsequent fetches. This is
160 // to support failover to other servers in the DMaaP cluster.
161 if (client == null) {
162 LOG.info("Getting DMaaP Client ...");
163 client = getClient(waitMs, limit);
165 if (client != null) {
167 for (String s : client.fetch(waitMs, limit)) {
169 incrementReceivedMessage();
171 LOG.debug(String.format("Got %d records from %s", out.size(), this.toString()));
172 } catch (Exception e) {
173 // Connection exception
174 LOG.error(String.format("Dmaap Connection Issue Detected. %s", e.getMessage()), e);
176 LOG.warn(String.format("Sleeping for %dms to compensate for connection failure", waitMs));
177 Thread.sleep(waitMs);
178 } catch (InterruptedException e2) {
179 LOG.warn(String.format("Failed to wait for %dms after bad fetch", waitMs));
180 Thread.currentThread().interrupt();
187 private void incrementReceivedMessage() {
188 if (isMetricEnabled && metricRegistry != null) {
189 ((DmaapRequestCounterMetric) metricRegistry.metric("DMAAP_KPI")).incrementRecievedMessage();
194 * Close consumer Dmaap client.
197 public void close() {
198 LOG.debug("Closing Dmaap consumer client....");
199 if (client != null) {
205 public String toString() {
206 String hostStr = (props == null || props.getProperty("host") == null ? "N/A" : props.getProperty("host"));
207 String group = (props == null || props.getProperty("group") == null ? "N/A" : props.getProperty("group"));
208 String id = (props == null || props.getProperty("id") == null ? "N/A" : props.getProperty("id"));
209 return String.format("Consumer %s/%s listening to %s on [%s]", group, id, topic, hostStr);
213 public void useHttps(boolean yes) {
217 private MetricService getMetricservice() {
218 BundleContext bctx = FrameworkUtil.getBundle(MetricService.class).getBundleContext();
219 ServiceReference sref = bctx.getServiceReference(MetricService.class.getName());
221 LOG.info("Metric Service from bundlecontext");
222 return (MetricService) bctx.getService(sref);
224 LOG.info("Metric Service error from bundlecontext");
225 LOG.warn("Cannot find service reference for org.onap.appc.metricservice.MetricService");