2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Copyright (C) 2017 Amdocs
8 * ================================================================================
9 * Modifications Copyright (C) 2018 IBM
10 * ================================================================================
11 * Licensed under the Apache License, Version 2.0 (the "License");
12 * you may not use this file except in compliance with the License.
13 * You may obtain a copy of the License at
15 * http://www.apache.org/licenses/LICENSE-2.0
17 * Unless required by applicable law or agreed to in writing, software
18 * distributed under the License is distributed on an "AS IS" BASIS,
19 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20 * See the License for the specific language governing permissions and
21 * limitations under the License.
23 * ============LICENSE_END=========================================================
26 package org.onap.appc.adapter.messaging.dmaap.impl;
28 import com.att.eelf.configuration.EELFLogger;
29 import com.att.eelf.configuration.EELFManager;
30 import com.att.nsa.mr.client.MRClientFactory;
31 import com.att.nsa.mr.client.MRConsumer;
32 import java.io.IOException;
33 import java.util.ArrayList;
34 import java.util.Collection;
35 import java.util.List;
36 import java.util.Properties;
37 import org.apache.commons.lang3.StringUtils;
38 import org.onap.appc.adapter.message.Consumer;
39 import org.onap.appc.configuration.Configuration;
40 import org.onap.appc.configuration.ConfigurationFactory;
41 import org.onap.appc.metricservice.MetricRegistry;
42 import org.onap.appc.metricservice.MetricService;
43 import org.onap.appc.metricservice.metric.DmaapRequestCounterMetric;
44 import org.onap.appc.metricservice.metric.Metric;
45 import org.onap.appc.metricservice.metric.MetricType;
46 import org.onap.appc.metricservice.policy.PublishingPolicy;
47 import org.onap.appc.metricservice.publisher.LogPublisher;
48 import org.osgi.framework.BundleContext;
49 import org.osgi.framework.FrameworkUtil;
50 import org.osgi.framework.ServiceReference;
52 public class DmaapConsumerImpl implements Consumer {
54 private static final EELFLogger LOG = EELFManager.getInstance().getLogger(DmaapConsumerImpl.class);
55 private final Configuration configuration = ConfigurationFactory.getConfiguration();
57 private static final int DEFAULT_TIMEOUT_MS = 60000;
58 private static final int DEFAULT_LIMIT = 1000;
60 private boolean isMetricEnabled = false;
61 private boolean useHttps = false;
62 private MetricRegistry metricRegistry;
63 private MRConsumer client = null;
64 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 if (user != null && password != null) {
82 props.setProperty("username", user);
83 props.setProperty("password", password);
85 props.setProperty("TransportType", "HTTPNOAUTH");
89 props.setProperty("filter", filter);
93 private void initMetric() {
94 LOG.debug("Metric getting initialized");
95 MetricService metricService = getMetricservice();
96 if (metricService != null) {
97 metricRegistry = metricService.createRegistry("APPC");
99 DmaapRequestCounterMetric dmaapKpiMetric = metricRegistry.metricBuilderFactory()
100 .dmaapRequestCounterBuilder().withName("DMAAP_KPI").withType(MetricType.COUNTER)
101 .withRecievedMessage(0).withPublishedMessage(0).build();
103 if (metricRegistry.register(dmaapKpiMetric)) {
104 Metric[] metrics = new Metric[] { dmaapKpiMetric };
105 LogPublisher logPublisher = new LogPublisher(metricRegistry, metrics);
106 LogPublisher[] logPublishers = new LogPublisher[1];
107 logPublishers[0] = logPublisher;
109 PublishingPolicy manuallyScheduledPublishingPolicy = metricRegistry.policyBuilderFactory()
110 .scheduledPolicyBuilder().withPublishers(logPublishers).withMetrics(metrics).build();
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 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("username", 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");
230 public Properties getProperties() {
234 public boolean isHttps() {