2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Copyright (C) 2017 Amdocs
8 * ================================================================================
9 * Modifications Copyright (C) 2018 IBM
10 * ================================================================================
11 * Modifications Copyright (C) 2019 Ericsson
12 * ================================================================================
13 * Licensed under the Apache License, Version 2.0 (the "License");
14 * you may not use this file except in compliance with the License.
15 * You may obtain a copy of the License at
17 * http://www.apache.org/licenses/LICENSE-2.0
19 * Unless required by applicable law or agreed to in writing, software
20 * distributed under the License is distributed on an "AS IS" BASIS,
21 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
22 * See the License for the specific language governing permissions and
23 * limitations under the License.
25 * ============LICENSE_END=========================================================
28 package org.onap.appc.adapter.messaging.dmaap.impl;
30 import com.att.eelf.configuration.EELFLogger;
31 import com.att.eelf.configuration.EELFManager;
32 import com.att.nsa.mr.client.MRClientFactory;
33 import com.att.nsa.mr.client.MRConsumer;
34 import java.io.IOException;
35 import java.util.ArrayList;
36 import java.util.Collection;
37 import java.util.List;
38 import java.util.Properties;
39 import org.apache.commons.lang3.StringUtils;
40 import org.onap.appc.adapter.message.Consumer;
41 import org.onap.appc.adapter.messaging.dmaap.utils.DmaapUtil;
42 import org.onap.appc.configuration.Configuration;
43 import org.onap.appc.configuration.ConfigurationFactory;
44 import org.onap.appc.metricservice.MetricRegistry;
45 import org.onap.appc.metricservice.MetricService;
46 import org.onap.appc.metricservice.metric.DmaapRequestCounterMetric;
47 import org.onap.appc.metricservice.metric.Metric;
48 import org.onap.appc.metricservice.metric.MetricType;
49 import org.onap.appc.metricservice.policy.PublishingPolicy;
50 import org.onap.appc.metricservice.publisher.LogPublisher;
51 import org.osgi.framework.BundleContext;
52 import org.osgi.framework.FrameworkUtil;
53 import org.osgi.framework.ServiceReference;
55 public class DmaapConsumerImpl implements Consumer {
57 private static final EELFLogger LOG = EELFManager.getInstance().getLogger(DmaapConsumerImpl.class);
58 private Configuration configuration = ConfigurationFactory.getConfiguration();
60 private static final int DEFAULT_TIMEOUT_MS = 60000;
61 private static final int DEFAULT_LIMIT = 1000;
63 private boolean isMetricEnabled = false;
64 private boolean useHttps = false;
65 private MetricRegistry metricRegistry;
66 private MRConsumer client = null;
67 private Properties props = null;
69 public DmaapConsumerImpl(Collection<String> urls, String topicName, String consumerGroupName, String consumerId,
70 String user, String password) {
72 this(urls, topicName, consumerGroupName, consumerId, user, password, null);
75 public DmaapConsumerImpl(Collection<String> urls, String topicName, String consumerGroupName, String consumerId,
76 String user, String password, String filter) {
78 this.topic = topicName;
79 this.props = new Properties();
80 String urlsStr = StringUtils.join(urls, ',');
81 props.setProperty("host", urlsStr);
82 props.setProperty("group", consumerGroupName);
83 props.setProperty("id", consumerId);
84 if (user != null && password != null) {
85 props.setProperty("username", user);
86 props.setProperty("password", password);
88 props.setProperty("TransportType", "HTTPNOAUTH");
92 props.setProperty("filter", filter);
96 private void initMetric() {
97 LOG.debug("Metric getting initialized");
98 MetricService metricService = getMetricService();
99 if (metricService != null) {
100 metricRegistry = metricService.createRegistry("APPC");
102 DmaapRequestCounterMetric dmaapKpiMetric = metricRegistry.metricBuilderFactory()
103 .dmaapRequestCounterBuilder().withName("DMAAP_KPI").withType(MetricType.COUNTER)
104 .withRecievedMessage(0).withPublishedMessage(0).build();
106 if (metricRegistry.register(dmaapKpiMetric)) {
107 Metric[] metrics = new Metric[] { dmaapKpiMetric };
108 LogPublisher logPublisher = new LogPublisher(metricRegistry, metrics);
109 LogPublisher[] logPublishers = new LogPublisher[1];
110 logPublishers[0] = logPublisher;
112 PublishingPolicy manuallyScheduledPublishingPolicy = metricRegistry.policyBuilderFactory()
113 .scheduledPolicyBuilder()
114 .withPublishers(logPublishers)
115 .withMetrics(metrics)
118 LOG.debug("Policy getting initialized");
119 manuallyScheduledPublishingPolicy.init();
120 LOG.debug("Metric initialized");
126 * @return An instance of MRConsumer created from our class variables.
128 synchronized MRConsumer getClient(int waitMs, int limit) {
130 props.setProperty("timeout", String.valueOf(waitMs));
131 props.setProperty("limit", String.valueOf(limit));
132 String topicProducerPropFileName = DmaapUtil.createConsumerPropFile(topic, props);
133 return MRClientFactory.createConsumer(topicProducerPropFileName);
134 } catch (IOException e1) {
135 LOG.error("failed to createConsumer", e1);
141 public synchronized void updateCredentials(String key, String secret) {
142 LOG.info(String.format("Setting auth to %s for %s", key, this.toString()));
143 props.setProperty("username", String.valueOf(key));
144 props.setProperty("password", String.valueOf(secret));
149 public List<String> fetch() {
150 return fetch(DEFAULT_TIMEOUT_MS, DEFAULT_LIMIT);
154 public List<String> fetch(int waitMs, int limit) {
155 Properties properties = configuration.getProperties();
156 if (properties != null && properties.getProperty("metric.enabled") != null) {
157 isMetricEnabled = Boolean.valueOf(properties.getProperty("metric.enabled"));
159 if (isMetricEnabled) {
162 LOG.debug(String.format("Fetching up to %d records with %dms wait on %s", limit, waitMs, this.toString()));
163 List<String> out = new ArrayList<>();
165 // Create client once and reuse it on subsequent fetches. This is
166 // to support failover to other servers in the DMaaP cluster.
167 if (client == null) {
168 LOG.info("Getting DMaaP Client ...");
169 client = getClient(waitMs, limit);
171 if (client != null) {
173 for (String s : client.fetch(waitMs, limit)) {
175 incrementReceivedMessage();
177 LOG.debug(String.format("Got %d records from %s", out.size(), this.toString()));
178 } catch (Exception e) {
179 // Connection exception
180 LOG.error(String.format("Dmaap Connection Issue Detected. %s", e.getMessage()), e);
182 LOG.warn(String.format("Sleeping for %dms to compensate for connection failure", waitMs));
183 Thread.sleep(waitMs);
184 } catch (InterruptedException e2) {
185 LOG.warn(String.format("Failed to wait for %dms after bad fetch", waitMs));
186 Thread.currentThread().interrupt();
193 private void incrementReceivedMessage() {
194 if (isMetricEnabled && metricRegistry != null) {
195 ((DmaapRequestCounterMetric) metricRegistry.metric("DMAAP_KPI")).incrementRecievedMessage();
200 * Close consumer Dmaap client.
203 public void close() {
204 LOG.debug("Closing Dmaap consumer client....");
205 if (client != null) {
211 public String toString() {
212 String hostStr = (props == null || props.getProperty("host") == null ? "N/A" : props.getProperty("host"));
213 String group = (props == null || props.getProperty("group") == null ? "N/A" : props.getProperty("group"));
214 String id = (props == null || props.getProperty("id") == null ? "N/A" : props.getProperty("id"));
215 return String.format("Consumer %s/%s listening to %s on [%s]", group, id, topic, hostStr);
219 public void useHttps(boolean yes) {
223 protected MetricService getMetricService() {
224 BundleContext bctx = FrameworkUtil.getBundle(MetricService.class).getBundleContext();
225 ServiceReference sref = bctx.getServiceReference(MetricService.class.getName());
227 LOG.info("Metric Service from bundlecontext");
228 return (MetricService) bctx.getService(sref);
230 LOG.info("Metric Service error from bundlecontext");
231 LOG.warn("Cannot find service reference for org.onap.appc.metricservice.MetricService");
236 public Properties getProperties() {
240 public boolean isHttps() {