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.consumer.KafkaConsumer;
31 import org.onap.dmaap.dmf.mr.CambriaApiException;
32 import org.onap.dmaap.dmf.mr.backends.Consumer;
33 import org.onap.dmaap.dmf.mr.backends.ConsumerFactory;
34 import org.onap.dmaap.dmf.mr.backends.MetricsSet;
35 import org.onap.dmaap.dmf.mr.backends.kafka.*;
36 import org.onap.dmaap.dmf.mr.backends.kafka.KafkaConsumerCache.KafkaConsumerCacheException;
37 import org.onap.dmaap.dmf.mr.constants.CambriaConstants;
38 import org.onap.dmaap.dmf.mr.utils.ConfigurationReader;
39 import org.onap.dmaap.dmf.mr.utils.Utils;
40 import org.springframework.beans.factory.annotation.Qualifier;
42 import java.net.InetAddress;
43 import java.net.UnknownHostException;
44 import java.util.Collection;
45 import java.util.HashMap;
46 import java.util.Properties;
47 import java.util.concurrent.TimeUnit;
50 * @author nilanjana.maity
53 public class DMaaPKafkaConsumerFactory implements ConsumerFactory {
56 private static final EELFLogger log = EELFManager.getInstance().getLogger(DMaaPKafkaConsumerFactory.class);
60 * constructor initialization
65 * @throws missingReqdSetting
66 * @throws KafkaConsumerCacheException
67 * @throws UnknownHostException
70 public DMaaPKafkaConsumerFactory(@Qualifier("dMaaPMetricsSet") MetricsSet metrics,
71 @Qualifier("curator") CuratorFramework curator,
72 @Qualifier("kafkalockavoid") KafkaLiveLockAvoider2 kafkaLiveLockAvoider)
73 throws missingReqdSetting, KafkaConsumerCacheException, UnknownHostException {
75 String apiNodeId = AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop,
76 CambriaConstants.kSetting_ApiNodeIdentifier);
77 if (apiNodeId == null) {
79 apiNodeId = InetAddress.getLocalHost().getCanonicalHostName() + ":" + CambriaConstants.kDefault_Port;
82 log.info("This Cambria API Node identifies itself as [" + apiNodeId + "].");
83 final String mode = CambriaConstants.DMAAP;
85 fkafkaBrokers = AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop,
86 "kafka.metadata.broker.list");
87 if (null == fkafkaBrokers) {
89 fkafkaBrokers = "localhost:9092";
92 boolean kSetting_EnableCache = kDefault_IsCacheEnabled;
93 String strkSetting_EnableCache = AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop,
94 "cambria.consumer.cache.enabled");
95 if (null != strkSetting_EnableCache)
96 kSetting_EnableCache = Boolean.parseBoolean(strkSetting_EnableCache);
98 final boolean isCacheEnabled = kSetting_EnableCache;
102 if (isCacheEnabled) {
103 fCache = KafkaConsumerCache.getInstance();
106 if (fCache != null) {
107 fCache.setfMetrics(metrics);
108 fCache.setfApiId(apiNodeId);
109 fCache.startCache(mode, curator);
110 if(kafkaLiveLockAvoider!=null){
111 kafkaLiveLockAvoider.startNewWatcherForServer(apiNodeId, makeAvoidanceCallback(apiNodeId));
112 fkafkaLiveLockAvoider = kafkaLiveLockAvoider;
121 * com.att.dmf.mr.backends.ConsumerFactory#getConsumerFor(java.lang.String,
122 * java.lang.String, java.lang.String, int, java.lang.String) This method is
123 * used by EventServiceImpl.getEvents() method to get a Kakfa consumer
124 * either from kafkaconsumer cache or create a new connection This also get
125 * the list of other consumer objects for the same consumer group and set to
126 * KafkaConsumer object. This list may be used during poll-rebalancing
130 public Consumer getConsumerFor(String topic, String consumerGroupName, String consumerId, int timeoutMs,
131 String remotehost) throws UnavailableException, CambriaApiException {
134 // To synchronize based on the consumer group.
136 Object syncObject = synchash.get(topic + consumerGroupName);
137 if (null == syncObject) {
138 syncObject = new Object();
139 synchash.put(topic + consumerGroupName, syncObject);
142 synchronized (syncObject) {
144 kc = (fCache != null) ? fCache.getConsumerFor(topic, consumerGroupName, consumerId) : null; // consumerId
146 } catch (KafkaConsumerCacheException e) {
147 log.info("######@@@@### Error occured in Kafka Caching" + e + " " + topic + "::" + consumerGroupName
148 + "::" + consumerId);
149 log.error("####@@@@## Error occured in Kafka Caching" + e + " " + topic + "::" + consumerGroupName
150 + "::" + consumerId);
151 throw new UnavailableException(e);
154 // Ideally if cache exists below flow should be skipped. If cache
156 // exist, then create this first time on this node.
159 log.info("^Kafka consumer cache value " + topic + "::" + consumerGroupName + "::" + consumerId + " =>"
162 final InterProcessMutex ipLock = new InterProcessMutex(ConfigurationReader.getCurator(),
163 "/consumerFactory/" + topic + "/" + consumerGroupName + "/" + consumerId);
164 boolean locked = false;
168 locked = ipLock.acquire(30, TimeUnit.SECONDS);
171 log.info("Could not acquire lock in order to create (topic, group, consumer) = " + "(" + topic
172 + ", " + consumerGroupName + ", " + consumerId + ") from " + remotehost);
173 throw new UnavailableException(
174 "Could not acquire lock in order to create (topic, group, consumer) = " + "(" + topic
175 + ", " + consumerGroupName + ", " + consumerId + ") " + remotehost);
178 // ConfigurationReader.getCurator().checkExists().forPath("S").
180 log.info("Creating Kafka consumer for group [" + consumerGroupName + "], consumer [" + consumerId
181 + "], on topic [" + topic + "].");
183 if (fCache != null) {
184 fCache.signalOwnership(topic, consumerGroupName, consumerId);
187 final Properties props = createConsumerConfig(topic,consumerGroupName, consumerId);
188 long fCreateTimeMs = System.currentTimeMillis();
189 KafkaConsumer<String, String> cc = new KafkaConsumer<>(props);
190 kc = new Kafka011Consumer(topic, consumerGroupName, consumerId, cc, fkafkaLiveLockAvoider);
191 log.info(" kafka stream created in " + (System.currentTimeMillis() - fCreateTimeMs));
193 if (fCache != null) {
194 fCache.putConsumerFor(topic, consumerGroupName, consumerId, kc); //
197 } catch (org.I0Itec.zkclient.exception.ZkTimeoutException x) {
199 "Kafka consumer couldn't connect to ZK. " + x + " " + consumerGroupName + "/" + consumerId);
200 throw new UnavailableException("Couldn't connect to ZK.");
201 } catch (KafkaConsumerCacheException e) {
202 log.info("Failed to cache consumer (this may have performance implications): " + e.getMessage()
203 + " " + consumerGroupName + "/" + consumerId);
204 } catch (UnavailableException u) {
205 log.info("Failed and in UnavailableException block " + u.getMessage() + " " + consumerGroupName
207 throw new UnavailableException("Error while acquiring consumer factory lock " + u.getMessage(), u);
208 } catch (Exception e) {
209 log.info("Failed and go to Exception block " + e.getMessage() + " " + consumerGroupName + "/"
211 log.error("Failed and go to Exception block " + e.getMessage() + " " + consumerGroupName + "/"
218 } catch (Exception e) {
219 log.error("Error while releasing consumer factory lock", e);
229 public synchronized void destroyConsumer(String topic, String consumerGroup, String clientId) {
230 if (fCache != null) {
231 fCache.dropConsumer(topic, consumerGroup, clientId);
236 public synchronized Collection<? extends Consumer> getConsumers() {
237 return fCache.getConsumers();
241 public synchronized void dropCache() {
242 fCache.dropAllConsumers();
246 private KafkaConsumerCache fCache;
247 private KafkaLiveLockAvoider2 fkafkaLiveLockAvoider;
248 private String fkafkaBrokers;
252 private static String makeLongKey(String key, String prefix) {
253 return prefix + "." + key;
256 private void transferSettingIfProvided(Properties target, String key, String prefix) {
257 String keyVal = AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, makeLongKey(key, prefix));
260 if (null != keyVal) {
262 log.info("Setting [" + key + "] to " + keyVal + ".");
263 target.put(key, keyVal);
268 * Name CreateConsumerconfig
274 * This method is to create Properties required to create kafka connection
275 * Group name is replaced with different format groupid--topic to address same
276 * groupids for multiple topics. Same groupid with multiple topics
277 * may start frequent consumer rebalancing on all the topics . Replacing them makes it unique
279 private Properties createConsumerConfig(String topic ,String groupId, String consumerId) {
280 final Properties props = new Properties();
281 //fakeGroupName is added to avoid multiple consumer group for multiple topics.Donot Change this logic
282 //Fix for CPFMF-644 :
283 final String fakeGroupName = groupId + "--" + topic;
284 props.put("group.id", fakeGroupName);
285 props.put("enable.auto.commit", "false"); // 0.11
286 props.put("bootstrap.servers", fkafkaBrokers);
287 if(Utils.isCadiEnabled()){
288 props.put("sasl.jaas.config", "org.apache.kafka.common.security.plain.PlainLoginModule required username='admin' password='"+Utils.getKafkaproperty()+"';");
289 props.put("security.protocol", "SASL_PLAINTEXT");
290 props.put("sasl.mechanism", "PLAIN");
292 props.put("client.id", consumerId);
294 // additional settings: start with our defaults, then pull in configured
296 populateKafkaInternalDefaultsMap();
297 for (String key : KafkaConsumerKeys) {
298 transferSettingIfProvided(props, key, "kafka");
301 props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
302 props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
308 private static final String KafkaConsumerKeys[] = { "bootstrap.servers", "heartbeat.interval.ms",
309 "auto.offset.reset", "exclude.internal.topics", "session.timeout.ms", "fetch.max.bytes",
310 "auto.commit.interval.ms", "connections.max.idle.ms", "fetch.min.bytes", "isolation.level",
311 "fetch.max.bytes", "request.timeout.ms", "fetch.max.wait.bytes", "reconnect.backoff.max.ms",
312 "max.partition.fetch.bytes", "reconnect.backoff.max.ms", "reconnect.backoff.ms", "retry.backoff.ms",
313 "max.poll.interval.ms", "max.poll.records", "receive.buffer.bytes", "metadata.max.age.ms" };
316 * putting values in hashmap like consumer timeout, zookeeper time out, etc
320 private static void populateKafkaInternalDefaultsMap() { }
323 * The starterIncremnt value is just to emulate calling certain consumers,
324 * in this test app all the consumers are local
327 private LiveLockAvoidance makeAvoidanceCallback(final String appId) {
329 return new LiveLockAvoidance() {
332 public String getAppId() {
337 public void handleRebalanceUnlock(String groupName) {
338 log.info("FORCE A POLL NOW FOR appId: [{}] group: [{}]", getAppId(), groupName);
339 Kafka011ConsumerUtil.forcePollOnConsumer(groupName + "::");
346 @SuppressWarnings("rawtypes")
348 public HashMap getConsumerForKafka011(String topic, String consumerGroupName, String consumerId, int timeoutMs,
349 String remotehost) throws UnavailableException, CambriaApiException {
350 // TODO Auto-generated method stub
354 private HashMap<String, Object> synchash = new HashMap<String, Object>();