Fix for APPC-1271
[appc.git] / appc-adapters / appc-dmaap-adapter / appc-dmaap-adapter-bundle / src / main / java / org / onap / appc / adapter / messaging / dmaap / impl / DmaapConsumerImpl.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP : APPC
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
14  * 
15  *      http://www.apache.org/licenses/LICENSE-2.0
16  * 
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.
22  * 
23  * ============LICENSE_END=========================================================
24  */
25
26 package org.onap.appc.adapter.messaging.dmaap.impl;
27
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;
51
52 public class DmaapConsumerImpl implements Consumer {
53
54     private static final EELFLogger LOG                = EELFManager.getInstance().getLogger(DmaapConsumerImpl.class);
55     private final Configuration     configuration      = ConfigurationFactory.getConfiguration();
56     // Default values
57     private static final int        DEFAULT_TIMEOUT_MS = 60000;
58     private static final int        DEFAULT_LIMIT      = 1000;
59     private String                  topic;
60     private boolean                 isMetricEnabled    = false;
61     private boolean                 useHttps           = false;
62     private MetricRegistry          metricRegistry;
63     private MRConsumer              client             = null;
64     private Properties              props              = null;
65
66     public DmaapConsumerImpl(Collection<String> urls, String topicName, String consumerGroupName, String consumerId,
67             String user, String password) {
68
69         this(urls, topicName, consumerGroupName, consumerId, user, password, null);
70     }
71
72     public DmaapConsumerImpl(Collection<String> urls, String topicName, String consumerGroupName, String consumerId,
73             String user, String password, String filter) {
74
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);
84         } else {
85             props.setProperty("TransportType", "HTTPNOAUTH");
86         }
87
88         if (filter != null) {
89             props.setProperty("filter", filter);
90         }
91     }
92
93     private void initMetric() {
94         LOG.debug("Metric getting initialized");
95         MetricService metricService = getMetricservice();
96         if (metricService != null) {
97             metricRegistry = metricService.createRegistry("APPC");
98
99             DmaapRequestCounterMetric dmaapKpiMetric = metricRegistry.metricBuilderFactory()
100                     .dmaapRequestCounterBuilder().withName("DMAAP_KPI").withType(MetricType.COUNTER)
101                     .withRecievedMessage(0).withPublishedMessage(0).build();
102
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;
108
109                 PublishingPolicy manuallyScheduledPublishingPolicy = metricRegistry.policyBuilderFactory()
110                         .scheduledPolicyBuilder().withPublishers(logPublishers).withMetrics(metrics).build();
111
112                 LOG.debug("Policy getting initialized");
113                 manuallyScheduledPublishingPolicy.init();
114                 LOG.debug("Metric initialized");
115             }
116         }
117     }
118
119     /**
120      * @return An instance of MRConsumer created from our class variables.
121      */
122     synchronized MRConsumer getClient(int waitMs, int limit) {
123         try {
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);
130             return null;
131         }
132     }
133
134     @Override
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));
139         client = null;
140     }
141
142     @Override
143     public List<String> fetch() {
144         return fetch(DEFAULT_TIMEOUT_MS, DEFAULT_LIMIT);
145     }
146
147     @Override
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"));
152         }
153         if (isMetricEnabled) {
154             initMetric();
155         }
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<>();
158
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);
164         }
165         if (client != null) {
166             try {
167                 for (String s : client.fetch(waitMs, limit)) {
168                     out.add(s);
169                     incrementReceivedMessage();
170                 }
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);
175                 try {
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();
181                 }
182             }
183         }
184         return out;
185     }
186
187     private void incrementReceivedMessage() {
188         if (isMetricEnabled && metricRegistry != null) {
189             ((DmaapRequestCounterMetric) metricRegistry.metric("DMAAP_KPI")).incrementRecievedMessage();
190         }
191     }
192
193     /**
194      * Close consumer Dmaap client.
195      */
196     @Override
197     public void close() {
198         LOG.debug("Closing Dmaap consumer client....");
199         if (client != null) {
200             client.close();
201         }
202     }
203
204     @Override
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);
210     }
211
212     @Override
213     public void useHttps(boolean yes) {
214         useHttps = yes;
215     }
216
217     private MetricService getMetricservice() {
218         BundleContext bctx = FrameworkUtil.getBundle(MetricService.class).getBundleContext();
219         ServiceReference sref = bctx.getServiceReference(MetricService.class.getName());
220         if (sref != null) {
221             LOG.info("Metric Service from bundlecontext");
222             return (MetricService) bctx.getService(sref);
223         } else {
224             LOG.info("Metric Service error from bundlecontext");
225             LOG.warn("Cannot find service reference for org.onap.appc.metricservice.MetricService");
226             return null;
227         }
228     }
229
230     public Properties getProperties() {
231         return props;
232     }
233
234     public boolean isHttps() {
235         return useHttps;
236     }
237 }