6f907ae20c012bf94a49f85c1055e1daf4a52397
[appc.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP : APPC
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
12  * 
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  * 
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.
20  * 
21  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22  * ============LICENSE_END=========================================================
23  */
24
25 package org.onap.appc.adapter.messaging.dmaap.impl;
26
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;
50
51 public class DmaapConsumerImpl implements Consumer {
52
53     private static final EELFLogger LOG = EELFManager.getInstance().getLogger(DmaapConsumerImpl.class);
54     private final Configuration configuration = ConfigurationFactory.getConfiguration();
55     // Default values
56     private static final int DEFAULT_TIMEOUT_MS = 60000;
57     private static final int DEFAULT_LIMIT = 1000;
58     private String topic;
59     private boolean isMetricEnabled = false;
60     private boolean useHttps = false;
61     private MetricRegistry metricRegistry;
62     private MRConsumer client = null;
63     private Properties props = null;
64
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         props.setProperty("username", user);
82         props.setProperty("password", password);
83         if (filter != null) {
84             props.setProperty("filter", filter);
85         }
86     }
87
88     private void initMetric() {
89         LOG.debug("Metric getting initialized");
90         MetricService metricService = getMetricservice();
91         if (metricService != null) {
92             metricRegistry = metricService.createRegistry("APPC");
93
94             DmaapRequestCounterMetric dmaapKpiMetric = metricRegistry.metricBuilderFactory()
95                 .dmaapRequestCounterBuilder()
96                 .withName("DMAAP_KPI").withType(MetricType.COUNTER)
97                 .withRecievedMessage(0)
98                 .withPublishedMessage(0)
99                 .build();
100
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;
106
107                 PublishingPolicy manuallyScheduledPublishingPolicy = metricRegistry.policyBuilderFactory()
108                     .scheduledPolicyBuilder().withPublishers(logPublishers)
109                     .withMetrics(metrics)
110                     .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     private 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("user",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 }