1 /*******************************************************************************
2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 * http://www.apache.org/licenses/LICENSE-2.0
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 * ============LICENSE_END=========================================================
19 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
21 *******************************************************************************/
22 package org.onap.dmaap.dmf.mr.beans;
24 import com.att.ajsc.filemonitor.AJSCPropertiesMap;
25 import com.att.eelf.configuration.EELFLogger;
26 import com.att.eelf.configuration.EELFManager;
27 import com.att.nsa.drumlin.till.nv.rrNvReadable.missingReqdSetting;
28 import org.apache.curator.framework.CuratorFramework;
29 import org.apache.curator.framework.recipes.locks.InterProcessMutex;
30 import org.apache.kafka.clients.admin.AdminClientConfig;
31 import org.apache.kafka.clients.consumer.KafkaConsumer;
32 import org.onap.dmaap.dmf.mr.CambriaApiException;
33 import org.onap.dmaap.dmf.mr.backends.Consumer;
34 import org.onap.dmaap.dmf.mr.backends.ConsumerFactory;
35 import org.onap.dmaap.dmf.mr.backends.MetricsSet;
36 import org.onap.dmaap.dmf.mr.backends.kafka.*;
37 import org.onap.dmaap.dmf.mr.backends.kafka.KafkaConsumerCache.KafkaConsumerCacheException;
38 import org.onap.dmaap.dmf.mr.constants.CambriaConstants;
39 import org.onap.dmaap.dmf.mr.utils.ConfigurationReader;
40 import org.onap.dmaap.dmf.mr.utils.Utils;
41 import org.springframework.beans.factory.annotation.Qualifier;
43 import java.net.InetAddress;
44 import java.net.UnknownHostException;
45 import java.util.Collection;
46 import java.util.HashMap;
47 import java.util.Properties;
48 import java.util.concurrent.TimeUnit;
51 * @author nilanjana.maity
54 public class DMaaPKafkaConsumerFactory implements ConsumerFactory {
57 private static final EELFLogger log = EELFManager.getInstance().getLogger(DMaaPKafkaConsumerFactory.class);
61 * constructor initialization
66 * @throws missingReqdSetting
67 * @throws KafkaConsumerCacheException
68 * @throws UnknownHostException
71 public DMaaPKafkaConsumerFactory(@Qualifier("dMaaPMetricsSet") MetricsSet metrics,
72 @Qualifier("curator") CuratorFramework curator,
73 @Qualifier("kafkalockavoid") KafkaLiveLockAvoider2 kafkaLiveLockAvoider)
74 throws missingReqdSetting, KafkaConsumerCacheException, UnknownHostException {
76 String apiNodeId = AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop,
77 CambriaConstants.kSetting_ApiNodeIdentifier);
78 if (apiNodeId == null) {
80 apiNodeId = InetAddress.getLocalHost().getCanonicalHostName() + ":" + CambriaConstants.kDefault_Port;
83 log.info("This Cambria API Node identifies itself as [" + apiNodeId + "].");
84 final String mode = CambriaConstants.DMAAP;
86 fkafkaBrokers = AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop,
87 "kafka.metadata.broker.list");
88 if (null == fkafkaBrokers) {
90 fkafkaBrokers = "localhost:9092";
93 boolean kSetting_EnableCache = kDefault_IsCacheEnabled;
94 String strkSetting_EnableCache = AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop,
95 "cambria.consumer.cache.enabled");
96 if (null != strkSetting_EnableCache)
97 kSetting_EnableCache = Boolean.parseBoolean(strkSetting_EnableCache);
99 final boolean isCacheEnabled = kSetting_EnableCache;
103 if (isCacheEnabled) {
104 fCache = KafkaConsumerCache.getInstance();
107 if (fCache != null) {
108 fCache.setfMetrics(metrics);
109 fCache.setfApiId(apiNodeId);
110 fCache.startCache(mode, curator);
111 if(kafkaLiveLockAvoider!=null){
112 kafkaLiveLockAvoider.startNewWatcherForServer(apiNodeId, makeAvoidanceCallback(apiNodeId));
113 fkafkaLiveLockAvoider = kafkaLiveLockAvoider;
122 * com.att.dmf.mr.backends.ConsumerFactory#getConsumerFor(java.lang.String,
123 * java.lang.String, java.lang.String, int, java.lang.String) This method is
124 * used by EventServiceImpl.getEvents() method to get a Kakfa consumer
125 * either from kafkaconsumer cache or create a new connection This also get
126 * the list of other consumer objects for the same consumer group and set to
127 * KafkaConsumer object. This list may be used during poll-rebalancing
131 public Consumer getConsumerFor(String topic, String consumerGroupName, String consumerId, int timeoutMs,
132 String remotehost) throws UnavailableException, CambriaApiException {
135 // To synchronize based on the consumer group.
137 Object syncObject = synchash.get(topic + consumerGroupName);
138 if (null == syncObject) {
139 syncObject = new Object();
140 synchash.put(topic + consumerGroupName, syncObject);
143 synchronized (syncObject) {
145 kc = (fCache != null) ? fCache.getConsumerFor(topic, consumerGroupName, consumerId) : null; // consumerId
147 } catch (KafkaConsumerCacheException e) {
148 log.info("######@@@@### Error occured in Kafka Caching" + e + " " + topic + "::" + consumerGroupName
149 + "::" + consumerId);
150 log.error("####@@@@## Error occured in Kafka Caching" + e + " " + topic + "::" + consumerGroupName
151 + "::" + consumerId);
152 throw new UnavailableException(e);
155 // Ideally if cache exists below flow should be skipped. If cache
157 // exist, then create this first time on this node.
160 log.info("^Kafka consumer cache value " + topic + "::" + consumerGroupName + "::" + consumerId + " =>"
163 final InterProcessMutex ipLock = new InterProcessMutex(ConfigurationReader.getCurator(),
164 "/consumerFactory/" + topic + "/" + consumerGroupName + "/" + consumerId);
165 boolean locked = false;
169 locked = ipLock.acquire(30, TimeUnit.SECONDS);
172 log.info("Could not acquire lock in order to create (topic, group, consumer) = " + "(" + topic
173 + ", " + consumerGroupName + ", " + consumerId + ") from " + remotehost);
174 throw new UnavailableException(
175 "Could not acquire lock in order to create (topic, group, consumer) = " + "(" + topic
176 + ", " + consumerGroupName + ", " + consumerId + ") " + remotehost);
179 // ConfigurationReader.getCurator().checkExists().forPath("S").
181 log.info("Creating Kafka consumer for group [" + consumerGroupName + "], consumer [" + consumerId
182 + "], on topic [" + topic + "].");
184 if (fCache != null) {
185 fCache.signalOwnership(topic, consumerGroupName, consumerId);
188 final Properties props = createConsumerConfig(topic,consumerGroupName, consumerId);
189 long fCreateTimeMs = System.currentTimeMillis();
190 KafkaConsumer<String, String> cc = new KafkaConsumer<>(props);
191 kc = new Kafka011Consumer(topic, consumerGroupName, consumerId, cc, fkafkaLiveLockAvoider);
192 log.info(" kafka stream created in " + (System.currentTimeMillis() - fCreateTimeMs));
194 if (fCache != null) {
195 fCache.putConsumerFor(topic, consumerGroupName, consumerId, kc); //
198 } catch (org.I0Itec.zkclient.exception.ZkTimeoutException x) {
200 "Kafka consumer couldn't connect to ZK. " + x + " " + consumerGroupName + "/" + consumerId);
201 throw new UnavailableException("Couldn't connect to ZK.");
202 } catch (KafkaConsumerCacheException e) {
203 log.info("Failed to cache consumer (this may have performance implications): " + e.getMessage()
204 + " " + consumerGroupName + "/" + consumerId);
205 } catch (UnavailableException u) {
206 log.info("Failed and in UnavailableException block " + u.getMessage() + " " + consumerGroupName
208 throw new UnavailableException("Error while acquiring consumer factory lock " + u.getMessage(), u);
209 } catch (Exception e) {
210 log.info("Failed and go to Exception block " + e.getMessage() + " " + consumerGroupName + "/"
212 log.error("Failed and go to Exception block " + e.getMessage() + " " + consumerGroupName + "/"
219 } catch (Exception e) {
220 log.error("Error while releasing consumer factory lock", e);
230 public synchronized void destroyConsumer(String topic, String consumerGroup, String clientId) {
231 if (fCache != null) {
232 fCache.dropConsumer(topic, consumerGroup, clientId);
237 public synchronized Collection<? extends Consumer> getConsumers() {
238 return fCache.getConsumers();
242 public synchronized void dropCache() {
243 fCache.dropAllConsumers();
247 private KafkaConsumerCache fCache;
248 private KafkaLiveLockAvoider2 fkafkaLiveLockAvoider;
249 private String fkafkaBrokers;
253 private static String makeLongKey(String key, String prefix) {
254 return prefix + "." + key;
257 private void transferSettingIfProvided(Properties target, String key, String prefix) {
258 String keyVal = AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, makeLongKey(key, prefix));
261 if (null != keyVal) {
263 log.info("Setting [" + key + "] to " + keyVal + ".");
264 target.put(key, keyVal);
269 * Name CreateConsumerconfig
275 * This method is to create Properties required to create kafka connection
276 * Group name is replaced with different format groupid--topic to address same
277 * groupids for multiple topics. Same groupid with multiple topics
278 * may start frequent consumer rebalancing on all the topics . Replacing them makes it unique
280 private Properties createConsumerConfig(String topic ,String groupId, String consumerId) {
281 final Properties props = new Properties();
282 //fakeGroupName is added to avoid multiple consumer group for multiple topics.Donot Change this logic
283 //Fix for CPFMF-644 :
284 final String fakeGroupName = groupId + "--" + topic;
285 props.put("group.id", fakeGroupName);
286 props.put("enable.auto.commit", "false"); // 0.11
287 props.put("bootstrap.servers", fkafkaBrokers);
288 if(Utils.isCadiEnabled()){
289 props.putAll(Utils.addSaslProps());
291 props.put("client.id", consumerId);
293 // additional settings: start with our defaults, then pull in configured
295 populateKafkaInternalDefaultsMap();
296 for (String key : KafkaConsumerKeys) {
297 transferSettingIfProvided(props, key, "kafka");
300 props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
301 props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
307 private static final String KafkaConsumerKeys[] = { "bootstrap.servers", "heartbeat.interval.ms",
308 "auto.offset.reset", "exclude.internal.topics", "session.timeout.ms", "fetch.max.bytes",
309 "auto.commit.interval.ms", "connections.max.idle.ms", "fetch.min.bytes", "isolation.level",
310 "fetch.max.bytes", "request.timeout.ms", "fetch.max.wait.bytes", "reconnect.backoff.max.ms",
311 "max.partition.fetch.bytes", "reconnect.backoff.max.ms", "reconnect.backoff.ms", "retry.backoff.ms",
312 "max.poll.interval.ms", "max.poll.records", "receive.buffer.bytes", "metadata.max.age.ms" };
315 * putting values in hashmap like consumer timeout, zookeeper time out, etc
319 private static void populateKafkaInternalDefaultsMap() { }
322 * The starterIncremnt value is just to emulate calling certain consumers,
323 * in this test app all the consumers are local
326 private LiveLockAvoidance makeAvoidanceCallback(final String appId) {
328 return new LiveLockAvoidance() {
331 public String getAppId() {
336 public void handleRebalanceUnlock(String groupName) {
337 log.info("FORCE A POLL NOW FOR appId: [{}] group: [{}]", getAppId(), groupName);
338 Kafka011ConsumerUtil.forcePollOnConsumer(groupName + "::");
345 @SuppressWarnings("rawtypes")
347 public HashMap getConsumerForKafka011(String topic, String consumerGroupName, String consumerId, int timeoutMs,
348 String remotehost) throws UnavailableException, CambriaApiException {
349 // TODO Auto-generated method stub
353 private HashMap<String, Object> synchash = new HashMap<String, Object>();