kafka.cpp 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104
  1. /*##############################################################################
  2. HPCC SYSTEMS software Copyright (C) 2015 HPCC Systems®.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. ############################################################################## */
  13. #include "kafka.hpp"
  14. #include "rtlds_imp.hpp"
  15. #include "jlog.hpp"
  16. #include "jmutex.hpp"
  17. #include "jprop.hpp"
  18. #include "jfile.hpp"
  19. #include "build-config.h"
  20. #include "librdkafka/rdkafka.h"
  21. #include <map>
  22. #include <fstream>
  23. #include <mutex>
  24. //==============================================================================
  25. // Kafka Interface Code
  26. //==============================================================================
  27. namespace KafkaPlugin
  28. {
  29. //--------------------------------------------------------------------------
  30. // File Constants
  31. //--------------------------------------------------------------------------
  32. // The minimum number of seconds that a cached object can live
  33. // without activity
  34. const time_t OBJECT_EXPIRE_TIMEOUT_SECONDS = 60 * 2;
  35. // The number of milliseconds given to librdkafka to perform explicit
  36. // background activity
  37. const __int32 POLL_TIMEOUT = 1000;
  38. //--------------------------------------------------------------------------
  39. // Static Variables
  40. //--------------------------------------------------------------------------
  41. static std::once_flag pubCacheInitFlag;
  42. //--------------------------------------------------------------------------
  43. // Static Methods (internal)
  44. //--------------------------------------------------------------------------
  45. /**
  46. * Look for an optional configuration file and apply any found configuration
  47. * parameters to a librdkafka configuration object.
  48. *
  49. * @param configFilePath The path to a configuration file; it is not
  50. * necessary for the file to exist
  51. * @param globalConfigPtr A pointer to the configuration object that
  52. * will receive any found parameters
  53. * @param traceLevel The current log trace level
  54. */
  55. static void applyConfig(const char* configFilePath, RdKafka::Conf* globalConfigPtr, int traceLevel)
  56. {
  57. if (configFilePath && *configFilePath && globalConfigPtr)
  58. {
  59. std::string errStr;
  60. StringBuffer fullConfigPath;
  61. fullConfigPath.append(CONFIG_DIR).append(PATHSEPSTR).append(configFilePath);
  62. Owned<IProperties> properties = createProperties(fullConfigPath.str(), true);
  63. Owned<IPropertyIterator> props = properties->getIterator();
  64. ForEach(*props)
  65. {
  66. StringBuffer key(props->getPropKey());
  67. key.trim();
  68. if (key.length() > 0 && key.charAt(0) != '#')
  69. {
  70. if (strcmp(key.str(), "metadata.broker.list") != 0)
  71. {
  72. const char* value = properties->queryProp(key);
  73. if (value && *value)
  74. {
  75. if (globalConfigPtr->set(key.str(), value, errStr) != RdKafka::Conf::CONF_OK)
  76. {
  77. DBGLOG("Kafka: Failed to set config param from file %s: '%s' = '%s'; error: '%s'", configFilePath, key.str(), value, errStr.c_str());
  78. }
  79. else if (traceLevel > 4)
  80. {
  81. DBGLOG("Kafka: Set config param from file %s: '%s' = '%s'", configFilePath, key.str(), value);
  82. }
  83. }
  84. }
  85. else
  86. {
  87. DBGLOG("Kafka: Setting '%s' ignored in config file %s", key.str(), configFilePath);
  88. }
  89. }
  90. }
  91. }
  92. }
  93. //--------------------------------------------------------------------------
  94. // Plugin Classes
  95. //--------------------------------------------------------------------------
  96. KafkaStreamedDataset::KafkaStreamedDataset(Consumer* _consumerPtr, IEngineRowAllocator* _resultAllocator, int _traceLevel, __int64 _maxRecords)
  97. : consumerPtr(_consumerPtr),
  98. resultAllocator(_resultAllocator),
  99. traceLevel(_traceLevel),
  100. maxRecords(_maxRecords)
  101. {
  102. shouldRead = true;
  103. consumedRecCount = 0;
  104. lastMsgOffset = 0;
  105. }
  106. KafkaStreamedDataset::~KafkaStreamedDataset()
  107. {
  108. if (consumerPtr)
  109. {
  110. if (consumedRecCount > 0)
  111. {
  112. consumerPtr->commitOffset(lastMsgOffset);
  113. }
  114. delete(consumerPtr);
  115. }
  116. }
  117. const void* KafkaStreamedDataset::nextRow()
  118. {
  119. const void* result = NULL;
  120. __int32 maxAttempts = 10; //!< Maximum number of tries if local queue is full
  121. __int32 timeoutWait = 100; //!< Amount of time to wait between retries
  122. __int32 attemptNum = 0;
  123. if (consumerPtr && (maxRecords <= 0 || consumedRecCount < maxRecords))
  124. {
  125. RdKafka::Message* messageObjPtr = NULL;
  126. bool messageConsumed = false;
  127. while (!messageConsumed && shouldRead && attemptNum < maxAttempts)
  128. {
  129. messageObjPtr = consumerPtr->getOneMessage(); // messageObjPtr must be deleted when we are through with it
  130. if (messageObjPtr)
  131. {
  132. try
  133. {
  134. switch (messageObjPtr->err())
  135. {
  136. case RdKafka::ERR_NO_ERROR:
  137. {
  138. RtlDynamicRowBuilder rowBuilder(resultAllocator);
  139. unsigned len = sizeof(__int32) + sizeof(__int64) + sizeof(size32_t) + messageObjPtr->len();
  140. byte* row = rowBuilder.ensureCapacity(len, NULL);
  141. // Populating this structure:
  142. // EXPORT KafkaMessage := RECORD
  143. // UNSIGNED4 partitionNum;
  144. // UNSIGNED8 offset;
  145. // UTF8 message;
  146. // END;
  147. *(__int32*)(row) = messageObjPtr->partition();
  148. *(__int64*)(row + sizeof(__int32)) = messageObjPtr->offset();
  149. *(size32_t*)(row + sizeof(__int32) + sizeof(__int64)) = rtlUtf8Length(messageObjPtr->len(), messageObjPtr->payload());
  150. memcpy(row + sizeof(__int32) + sizeof(__int64) + sizeof(size32_t), messageObjPtr->payload(), messageObjPtr->len());
  151. result = rowBuilder.finalizeRowClear(len);
  152. lastMsgOffset = messageObjPtr->offset();
  153. ++consumedRecCount;
  154. // Give opportunity for consumer to pull in any additional messages
  155. consumerPtr->handle()->poll(0);
  156. // Mark as loaded so we don't retry
  157. messageConsumed = true;
  158. }
  159. break;
  160. case RdKafka::ERR__TIMED_OUT:
  161. // No new messages arrived and we timed out waiting
  162. ++attemptNum;
  163. consumerPtr->handle()->poll(timeoutWait);
  164. break;
  165. case RdKafka::ERR__PARTITION_EOF:
  166. // We reached the end of the messages in the partition
  167. if (traceLevel > 4)
  168. {
  169. DBGLOG("Kafka: EOF reading message from partition %d", messageObjPtr->partition());
  170. }
  171. shouldRead = false;
  172. break;
  173. case RdKafka::ERR__UNKNOWN_PARTITION:
  174. // Unknown partition; don't throw an error here because
  175. // in some configurations (e.g. more Thor slaves than
  176. // partitions) not all consumers will have a partition
  177. // to read
  178. if (traceLevel > 4)
  179. {
  180. DBGLOG("Kafka: Unknown partition while trying to read");
  181. }
  182. shouldRead = false;
  183. break;
  184. case RdKafka::ERR__UNKNOWN_TOPIC:
  185. throw MakeStringException(-1, "Kafka: Error while reading message: '%s'", messageObjPtr->errstr().c_str());
  186. break;
  187. }
  188. }
  189. catch (...)
  190. {
  191. delete(messageObjPtr);
  192. throw;
  193. }
  194. delete(messageObjPtr);
  195. messageObjPtr = NULL;
  196. }
  197. }
  198. }
  199. return result;
  200. }
  201. void KafkaStreamedDataset::stop()
  202. {
  203. shouldRead = false;
  204. }
  205. //--------------------------------------------------------------------------
  206. Poller::Poller(KafkaObj* _parentPtr, __int32 _pollTimeout)
  207. : Thread("Kafka::Poller"),
  208. parentPtr(_parentPtr),
  209. pollTimeout(_pollTimeout),
  210. shouldRun(false)
  211. {
  212. }
  213. void Poller::start()
  214. {
  215. if (!isAlive() && parentPtr)
  216. {
  217. shouldRun = true;
  218. Thread::start();
  219. }
  220. }
  221. void Poller::stop()
  222. {
  223. if (isAlive())
  224. {
  225. shouldRun = false;
  226. join();
  227. }
  228. }
  229. int Poller::run()
  230. {
  231. RdKafka::Handle* handle = parentPtr->handle();
  232. while (shouldRun)
  233. {
  234. handle->poll(pollTimeout);
  235. }
  236. return 0;
  237. }
  238. //--------------------------------------------------------------------------
  239. Publisher::Publisher(const std::string& _brokers, const std::string& _topic, __int32 _pollTimeout, int _traceLevel)
  240. : brokers(_brokers),
  241. topic(_topic),
  242. pollTimeout(_pollTimeout),
  243. traceLevel(_traceLevel)
  244. {
  245. producerPtr = NULL;
  246. topicPtr = NULL;
  247. pollerPtr = new Poller(this, _pollTimeout);
  248. updateTimeTouched();
  249. }
  250. Publisher::~Publisher()
  251. {
  252. delete(pollerPtr);
  253. delete(topicPtr.load());
  254. delete(producerPtr);
  255. }
  256. RdKafka::Handle* Publisher::handle()
  257. {
  258. return static_cast<RdKafka::Handle*>(producerPtr);
  259. }
  260. time_t Publisher::updateTimeTouched()
  261. {
  262. timeCreated = time(NULL);
  263. return timeCreated;
  264. }
  265. time_t Publisher::getTimeTouched() const
  266. {
  267. return timeCreated;
  268. }
  269. void Publisher::shutdownPoller()
  270. {
  271. if (pollerPtr)
  272. {
  273. // Wait until we send all messages
  274. while (messagesWaitingInQueue() > 0)
  275. {
  276. usleep(pollTimeout);
  277. }
  278. // Tell poller to stop
  279. pollerPtr->stop();
  280. }
  281. }
  282. __int32 Publisher::messagesWaitingInQueue()
  283. {
  284. __int32 queueLength = 0;
  285. if (producerPtr)
  286. {
  287. queueLength = producerPtr->outq_len();
  288. }
  289. return queueLength;
  290. }
  291. void Publisher::ensureSetup()
  292. {
  293. if (!topicPtr.load(std::memory_order_acquire))
  294. {
  295. CriticalBlock block(lock);
  296. if (!topicPtr.load(std::memory_order_relaxed))
  297. {
  298. std::string errStr;
  299. RdKafka::Conf* globalConfig = RdKafka::Conf::create(RdKafka::Conf::CONF_GLOBAL);
  300. if (globalConfig)
  301. {
  302. // Set global configuration parameters, used mainly at the producer level
  303. globalConfig->set("metadata.broker.list", brokers, errStr);
  304. globalConfig->set("queue.buffering.max.messages", "1000000", errStr);
  305. globalConfig->set("compression.codec", "snappy", errStr);
  306. globalConfig->set("message.send.max.retries", "3", errStr);
  307. globalConfig->set("retry.backoff.ms", "500", errStr);
  308. // Set any global configurations from file, allowing
  309. // overrides of above settings
  310. applyConfig("kafka_global.conf", globalConfig, traceLevel);
  311. // Set producer callbacks
  312. globalConfig->set("event_cb", static_cast<RdKafka::EventCb*>(this), errStr);
  313. globalConfig->set("dr_cb", static_cast<RdKafka::DeliveryReportCb*>(this), errStr);
  314. // Create the producer
  315. producerPtr = RdKafka::Producer::create(globalConfig, errStr);
  316. delete globalConfig;
  317. if (producerPtr)
  318. {
  319. RdKafka::Conf* topicConfPtr = RdKafka::Conf::create(RdKafka::Conf::CONF_TOPIC);
  320. // Set any topic configurations from file
  321. std::string confName = "kafka_publisher_topic_" + topic + ".conf";
  322. applyConfig(confName.c_str(), topicConfPtr, traceLevel);
  323. // Create the topic
  324. topicPtr.store(RdKafka::Topic::create(producerPtr, topic, topicConfPtr, errStr), std::memory_order_release);
  325. delete topicConfPtr;
  326. if (topicPtr)
  327. {
  328. // Start the attached background poller
  329. pollerPtr->start();
  330. }
  331. else
  332. {
  333. throw MakeStringException(-1, "Kafka: Unable to create producer topic object for topic '%s'; error: '%s'", topic.c_str(), errStr.c_str());
  334. }
  335. }
  336. else
  337. {
  338. throw MakeStringException(-1, "Kafka: Unable to create producer object for brokers '%s'; error: '%s'", brokers.c_str(), errStr.c_str());
  339. }
  340. }
  341. else
  342. {
  343. throw MakeStringException(-1, "Kafka: Unable to create producer global configuration object for brokers '%s'; error: '%s'", brokers.c_str(), errStr.c_str());
  344. }
  345. }
  346. }
  347. }
  348. void Publisher::sendMessage(const std::string& message, const std::string& key)
  349. {
  350. __int32 maxAttempts = 10; //!< Maximum number of tries if local queue is full
  351. __int32 attemptNum = 0;
  352. // Make sure we have a valid connection to the Kafka cluster
  353. ensureSetup();
  354. // Actually send the message
  355. while (true)
  356. {
  357. RdKafka::ErrorCode resp = producerPtr->produce(topicPtr, RdKafka::Topic::PARTITION_UA, RdKafka::Producer::RK_MSG_COPY, const_cast<char*>(message.c_str()), message.size(), (key.empty() ? NULL : &key), NULL);
  358. if (resp == RdKafka::ERR_NO_ERROR)
  359. {
  360. break;
  361. }
  362. else if (resp == RdKafka::ERR__QUEUE_FULL)
  363. {
  364. if (attemptNum < maxAttempts)
  365. {
  366. usleep(pollTimeout);
  367. ++attemptNum;
  368. }
  369. else
  370. {
  371. throw MakeStringException(-1, "Kafka: Unable to send message to topic '%s'; error: '%s'", topic.c_str(), RdKafka::err2str(resp).c_str());
  372. }
  373. }
  374. else
  375. {
  376. throw MakeStringException(-1, "Kafka: Unable to send message to topic '%s'; error: '%s'", topic.c_str(), RdKafka::err2str(resp).c_str());
  377. }
  378. }
  379. }
  380. void Publisher::event_cb(RdKafka::Event& event)
  381. {
  382. if (traceLevel > 4)
  383. {
  384. switch (event.type())
  385. {
  386. case RdKafka::Event::EVENT_ERROR:
  387. DBGLOG("Kafka: Error: %s", event.str().c_str());
  388. break;
  389. case RdKafka::Event::EVENT_STATS:
  390. DBGLOG("Kafka: Stats: %s", event.str().c_str());
  391. break;
  392. case RdKafka::Event::EVENT_LOG:
  393. DBGLOG("Kafka: Log: %s", event.str().c_str());
  394. break;
  395. }
  396. }
  397. }
  398. void Publisher::dr_cb (RdKafka::Message& message)
  399. {
  400. if (message.err() != RdKafka::ERR_NO_ERROR)
  401. {
  402. StringBuffer payloadStr;
  403. if (message.len() == 0)
  404. payloadStr.append("<no message>");
  405. else
  406. payloadStr.append(message.len(), static_cast<const char*>(message.payload()));
  407. DBGLOG("Kafka: Error publishing message: %d (%s); message: '%s'", message.err(), message.errstr().c_str(), payloadStr.str());
  408. }
  409. }
  410. //--------------------------------------------------------------------------
  411. Consumer::Consumer(const std::string& _brokers, const std::string& _topic, const std::string& _consumerGroup, __int32 _partitionNum, int _traceLevel)
  412. : brokers(_brokers),
  413. topic(_topic),
  414. consumerGroup(_consumerGroup),
  415. partitionNum(_partitionNum),
  416. traceLevel(_traceLevel)
  417. {
  418. consumerPtr = NULL;
  419. topicPtr = NULL;
  420. char cpath[_MAX_DIR];
  421. GetCurrentDirectory(_MAX_DIR, cpath);
  422. offsetPath.append(cpath);
  423. addPathSepChar(offsetPath);
  424. offsetPath.append(topic.c_str());
  425. offsetPath.append("-");
  426. offsetPath.append(partitionNum);
  427. if (!consumerGroup.empty())
  428. {
  429. offsetPath.append("-");
  430. offsetPath.append(consumerGroup.c_str());
  431. }
  432. offsetPath.append(".offset");
  433. }
  434. Consumer::~Consumer()
  435. {
  436. if (consumerPtr && topicPtr)
  437. {
  438. consumerPtr->stop(topicPtr, partitionNum);
  439. }
  440. delete(topicPtr.load());
  441. delete(consumerPtr);
  442. }
  443. RdKafka::Handle* Consumer::handle()
  444. {
  445. return static_cast<RdKafka::Handle*>(consumerPtr);
  446. }
  447. void Consumer::ensureSetup()
  448. {
  449. if (!topicPtr.load(std::memory_order_acquire))
  450. {
  451. CriticalBlock block(lock);
  452. if (!topicPtr.load(std::memory_order_relaxed))
  453. {
  454. initFileOffsetIfNotExist();
  455. std::string errStr;
  456. RdKafka::Conf* globalConfig = RdKafka::Conf::create(RdKafka::Conf::CONF_GLOBAL);
  457. if (globalConfig)
  458. {
  459. // Set global configuration parameters, used mainly at the consumer level
  460. globalConfig->set("metadata.broker.list", brokers, errStr);
  461. globalConfig->set("compression.codec", "snappy", errStr);
  462. globalConfig->set("queued.max.messages.kbytes", "10000000", errStr);
  463. globalConfig->set("fetch.message.max.bytes", "10000000", errStr);
  464. // Set any global configurations from file, allowing
  465. // overrides of above settings
  466. applyConfig("kafka_global.conf", globalConfig, traceLevel);
  467. // Set consumer callbacks
  468. globalConfig->set("event_cb", static_cast<RdKafka::EventCb*>(this), errStr);
  469. // Create the consumer
  470. consumerPtr = RdKafka::Consumer::create(globalConfig, errStr);
  471. delete globalConfig;
  472. if (consumerPtr)
  473. {
  474. RdKafka::Conf* topicConfPtr = RdKafka::Conf::create(RdKafka::Conf::CONF_TOPIC);
  475. // Set the per-topic configuration parameters
  476. topicConfPtr->set("group.id", consumerGroup, errStr);
  477. topicConfPtr->set("auto.offset.reset", "smallest", errStr);
  478. // Set any topic configurations from file, allowing
  479. // overrides of above settings
  480. std::string confName = "kafka_consumer_topic_" + topic + ".conf";
  481. applyConfig(confName.c_str(), topicConfPtr, traceLevel);
  482. // Ensure that some items are set a certain way
  483. // by setting them after loading the external conf
  484. topicConfPtr->set("auto.commit.enable", "false", errStr);
  485. // Additional settings for updated librdkafka
  486. topicConfPtr->set("enable.auto.commit", "false", errStr);
  487. topicConfPtr->set("offset.store.method", "file", errStr);
  488. topicConfPtr->set("offset.store.path", offsetPath.str(), errStr);
  489. // Create the topic
  490. topicPtr.store(RdKafka::Topic::create(consumerPtr, topic, topicConfPtr, errStr), std::memory_order_release);
  491. delete topicConfPtr;
  492. if (!topicPtr)
  493. {
  494. throw MakeStringException(-1, "Kafka: Unable to create consumer topic object for topic '%s'; error: '%s'", topic.c_str(), errStr.c_str());
  495. }
  496. }
  497. else
  498. {
  499. throw MakeStringException(-1, "Kafka: Unable to create consumer object for brokers '%s'; error: '%s'", brokers.c_str(), errStr.c_str());
  500. }
  501. }
  502. else
  503. {
  504. throw MakeStringException(-1, "Kafka: Unable to create consumer global configuration object for brokers '%s'; error: '%s'", brokers.c_str(), errStr.c_str());
  505. }
  506. }
  507. }
  508. }
  509. RdKafka::Message* Consumer::getOneMessage()
  510. {
  511. return consumerPtr->consume(topicPtr, partitionNum, POLL_TIMEOUT);
  512. }
  513. void Consumer::prepForMessageFetch()
  514. {
  515. // Make sure we have a valid connection to the Kafka cluster
  516. ensureSetup();
  517. // Start the local read queue
  518. RdKafka::ErrorCode startErr = consumerPtr->start(topicPtr, partitionNum, RdKafka::Topic::OFFSET_STORED);
  519. if (startErr == RdKafka::ERR_NO_ERROR)
  520. {
  521. if (traceLevel > 4)
  522. {
  523. DBGLOG("Kafka: Started Consumer for %s:%d @ %s", topic.c_str(), partitionNum, brokers.c_str());
  524. }
  525. }
  526. else
  527. {
  528. throw MakeStringException(-1, "Kafka: Failed to start Consumer read for %s:%d @ %s; error: %d", topic.c_str(), partitionNum, brokers.c_str(), startErr);
  529. }
  530. }
  531. void Consumer::commitOffset(__int64 offset) const
  532. {
  533. if (offset >= 0)
  534. {
  535. // Not using librdkafka's offset_store because it seems to be broken
  536. // topicPtr->offset_store(partitionNum, offset);
  537. // Create/overwrite a file using the same naming convention and
  538. // file contents that librdkafka uses so it can pick up where
  539. // we left off; NOTE: librdkafka does not clean the topic name
  540. // or consumer group name when constructing this path
  541. // (which is actually a security concern), so we can't clean, either
  542. std::ofstream outFile(offsetPath.str(), std::ofstream::trunc);
  543. outFile << offset;
  544. if (traceLevel > 4)
  545. {
  546. DBGLOG("Kafka: Saved offset %lld to %s", offset, offsetPath.str());
  547. }
  548. }
  549. }
  550. void Consumer::initFileOffsetIfNotExist() const
  551. {
  552. if (!checkFileExists(offsetPath.str()))
  553. {
  554. commitOffset(0);
  555. if (traceLevel > 4)
  556. {
  557. DBGLOG("Kafka: Creating initial offset file %s", offsetPath.str());
  558. }
  559. }
  560. }
  561. void Consumer::event_cb(RdKafka::Event& event)
  562. {
  563. if (traceLevel > 4)
  564. {
  565. switch (event.type())
  566. {
  567. case RdKafka::Event::EVENT_ERROR:
  568. DBGLOG("Kafka: Error: %s", event.str().c_str());
  569. break;
  570. case RdKafka::Event::EVENT_STATS:
  571. DBGLOG("Kafka: Stats: %s", event.str().c_str());
  572. break;
  573. case RdKafka::Event::EVENT_LOG:
  574. DBGLOG("Kafka: Log: %s", event.str().c_str());
  575. break;
  576. }
  577. }
  578. }
  579. //--------------------------------------------------------------------------
  580. /** @class PublisherCacheObj
  581. *
  582. * Class used to create and cache publisher objects and connections
  583. */
  584. static class PublisherCacheObj
  585. {
  586. private:
  587. typedef std::map<std::string, Publisher*> ObjMap;
  588. public:
  589. /**
  590. * Constructor
  591. *
  592. * @param _traceLevel The current logging level
  593. */
  594. PublisherCacheObj(int _traceLevel)
  595. : traceLevel(_traceLevel)
  596. {
  597. }
  598. void deleteAll()
  599. {
  600. CriticalBlock block(lock);
  601. for (ObjMap::iterator x = cachedPublishers.begin(); x != cachedPublishers.end(); x++)
  602. {
  603. if (x->second)
  604. {
  605. // Shutdown the attached poller before deleting
  606. x->second->shutdownPoller();
  607. // Now delete
  608. delete(x->second);
  609. }
  610. }
  611. cachedPublishers.clear();
  612. }
  613. /**
  614. * Remove previously-created objects that have been inactive
  615. * for awhile
  616. */
  617. void expire()
  618. {
  619. if (!cachedPublishers.empty())
  620. {
  621. CriticalBlock block(lock);
  622. time_t oldestAllowedTime = time(NULL) - OBJECT_EXPIRE_TIMEOUT_SECONDS;
  623. __int32 expireCount = 0;
  624. for (ObjMap::iterator x = cachedPublishers.begin(); x != cachedPublishers.end(); /* increment handled explicitly */)
  625. {
  626. // Expire only if the publisher has been inactive and if
  627. // there are no messages in the outbound queue
  628. if (x->second && x->second->getTimeTouched() < oldestAllowedTime && x->second->messagesWaitingInQueue() == 0)
  629. {
  630. // Shutdown the attached poller before deleting
  631. x->second->shutdownPoller();
  632. // Delete the object
  633. delete(x->second);
  634. // Erase from map
  635. cachedPublishers.erase(x++);
  636. ++expireCount;
  637. }
  638. else
  639. {
  640. x++;
  641. }
  642. }
  643. if (traceLevel > 4 && expireCount > 0)
  644. {
  645. DBGLOG("Kafka: Expired %d cached publisher%s", expireCount, (expireCount == 1 ? "" : "s"));
  646. }
  647. }
  648. }
  649. /**
  650. * Gets an established Publisher, based on unique broker/topic
  651. * pairs, or creates a new one.
  652. *
  653. * @param brokers One or more Kafka brokers, in the
  654. * format 'name[:port]' where 'name'
  655. * is either a host name or IP address;
  656. * multiple brokers can be delimited
  657. * with commas
  658. * @param topic The name of the topic
  659. * @param pollTimeout The number of milliseconds to give
  660. * to librdkafka when executing
  661. * asynchronous activities
  662. *
  663. * @return A pointer to a Publisher* object.
  664. */
  665. Publisher* getPublisher(const std::string& brokers, const std::string& topic, __int32 pollTimeout)
  666. {
  667. Publisher* pubObjPtr = NULL;
  668. StringBuffer suffixStr;
  669. std::string key;
  670. // Create the key used to look up previously-created objects
  671. suffixStr.append(pollTimeout);
  672. key = brokers + "+" + topic + "+" + suffixStr.str();
  673. {
  674. CriticalBlock block(lock);
  675. // Try to find a cached publisher
  676. pubObjPtr = cachedPublishers[key];
  677. if (pubObjPtr)
  678. {
  679. pubObjPtr->updateTimeTouched();
  680. }
  681. else
  682. {
  683. // Publisher for that set of brokers and topic does not exist; create one
  684. pubObjPtr = new Publisher(brokers, topic, pollTimeout, traceLevel);
  685. cachedPublishers[key] = pubObjPtr;
  686. if (traceLevel > 4)
  687. {
  688. DBGLOG("Kafka: Created and cached new publisher object: %s @ %s", topic.c_str(), brokers.c_str());
  689. }
  690. }
  691. }
  692. if (!pubObjPtr)
  693. {
  694. throw MakeStringException(-1, "Kafka: Unable to create publisher for brokers '%s' and topic '%s'", brokers.c_str(), topic.c_str());
  695. }
  696. return pubObjPtr;
  697. }
  698. private:
  699. ObjMap cachedPublishers; //!< std::map of created Publisher object pointers
  700. CriticalSection lock; //!< Mutex guarding modifications to cachedPublishers
  701. int traceLevel; //!< The current logging level
  702. } *publisherCache;
  703. //--------------------------------------------------------------------------
  704. /** @class PublisherCacheExpirerObj
  705. * Class used to expire old publisher objects held within publisherCache
  706. */
  707. static class PublisherCacheExpirerObj : public Thread
  708. {
  709. public:
  710. PublisherCacheExpirerObj()
  711. : Thread("Kafka::PublisherExpirer"),
  712. shouldRun(false)
  713. {
  714. }
  715. virtual void start()
  716. {
  717. if (!isAlive())
  718. {
  719. shouldRun = true;
  720. Thread::start();
  721. }
  722. }
  723. virtual void stop()
  724. {
  725. if (isAlive())
  726. {
  727. shouldRun = false;
  728. join();
  729. }
  730. }
  731. virtual int run()
  732. {
  733. while (shouldRun)
  734. {
  735. if (publisherCache)
  736. {
  737. publisherCache->expire();
  738. }
  739. usleep(1000);
  740. }
  741. return 0;
  742. }
  743. private:
  744. std::atomic_bool shouldRun; //!< If true, we should execute our thread's main event loop
  745. } *publisherCacheExpirer;
  746. //--------------------------------------------------------------------------
  747. // Lazy Initialization
  748. //--------------------------------------------------------------------------
  749. /**
  750. * Make sure the publisher object cache is initialized as well as the
  751. * associated background thread for expiring idle publishers. This is
  752. * called only once.
  753. *
  754. * @param traceLevel Current logging level
  755. */
  756. static void setupPublisherCache(int traceLevel)
  757. {
  758. KafkaPlugin::publisherCache = new KafkaPlugin::PublisherCacheObj(traceLevel);
  759. KafkaPlugin::publisherCacheExpirer = new KafkaPlugin::PublisherCacheExpirerObj;
  760. KafkaPlugin::publisherCacheExpirer->start();
  761. }
  762. //--------------------------------------------------------------------------
  763. // Advertised Entry Point Functions
  764. //--------------------------------------------------------------------------
  765. ECL_KAFKA_API bool ECL_KAFKA_CALL publishMessage(ICodeContext* ctx, const char* brokers, const char* topic, const char* message, const char* key)
  766. {
  767. std::call_once(pubCacheInitFlag, setupPublisherCache, ctx->queryContextLogger().queryTraceLevel());
  768. Publisher* pubObjPtr = publisherCache->getPublisher(brokers, topic, POLL_TIMEOUT);
  769. pubObjPtr->sendMessage(message, key);
  770. return true;
  771. }
  772. ECL_KAFKA_API bool ECL_KAFKA_CALL publishMessage(ICodeContext* ctx, const char* brokers, const char* topic, size32_t lenMessage, const char* message, size32_t lenKey, const char* key)
  773. {
  774. std::call_once(pubCacheInitFlag, setupPublisherCache, ctx->queryContextLogger().queryTraceLevel());
  775. Publisher* pubObjPtr = publisherCache->getPublisher(brokers, topic, POLL_TIMEOUT);
  776. std::string messageStr(message, rtlUtf8Size(lenMessage, message));
  777. std::string keyStr(key, rtlUtf8Size(lenKey, key));
  778. pubObjPtr->sendMessage(messageStr, keyStr);
  779. return true;
  780. }
  781. ECL_KAFKA_API __int32 ECL_KAFKA_CALL getTopicPartitionCount(ICodeContext* ctx, const char* brokers, const char* topic)
  782. {
  783. // We have to use librdkafka's C API for this right now, as the C++ API
  784. // does not expose a topic's metadata. In addition, there is no easy
  785. // link between the exposed C++ objects and the structs used by the
  786. // C API, so we are basically creating a brand-new connection from
  787. // scratch.
  788. __int32 pCount = 0;
  789. char errstr[512];
  790. rd_kafka_conf_t* conf = rd_kafka_conf_new();
  791. rd_kafka_t* rk = rd_kafka_new(RD_KAFKA_CONSUMER, conf, errstr, sizeof(errstr));
  792. if (rk)
  793. {
  794. if (rd_kafka_brokers_add(rk, brokers) != 0)
  795. {
  796. rd_kafka_topic_conf_t* topic_conf = rd_kafka_topic_conf_new();
  797. rd_kafka_topic_t* rkt = rd_kafka_topic_new(rk, topic, topic_conf);
  798. if (rkt)
  799. {
  800. const struct rd_kafka_metadata* metadata = NULL;
  801. rd_kafka_resp_err_t err = rd_kafka_metadata(rk, 0, rkt, &metadata, 5000);
  802. if (err == RD_KAFKA_RESP_ERR_NO_ERROR)
  803. {
  804. pCount = metadata->topics[0].partition_cnt;
  805. rd_kafka_metadata_destroy(metadata);
  806. }
  807. else
  808. {
  809. if (ctx->queryContextLogger().queryTraceLevel() > 4)
  810. {
  811. DBGLOG("Kafka: Error retrieving metadata from topic: %s @ %s: '%s'", topic, brokers, rd_kafka_err2str(err));
  812. }
  813. }
  814. rd_kafka_topic_destroy(rkt);
  815. }
  816. else
  817. {
  818. if (ctx->queryContextLogger().queryTraceLevel() > 4)
  819. {
  820. DBGLOG("Kafka: Could not create topic object: %s @ %s", topic, brokers);
  821. }
  822. }
  823. }
  824. else
  825. {
  826. if (ctx->queryContextLogger().queryTraceLevel() > 4)
  827. {
  828. DBGLOG("Kafka: Could not add brokers: %s @ %s", topic, brokers);
  829. }
  830. }
  831. rd_kafka_destroy(rk);
  832. }
  833. if (pCount == 0)
  834. {
  835. DBGLOG("Kafka: Unable to retrieve partition count from topic: %s @ %s", topic, brokers);
  836. }
  837. return pCount;
  838. }
  839. ECL_KAFKA_API IRowStream* ECL_KAFKA_CALL getMessageDataset(ICodeContext* ctx, IEngineRowAllocator* allocator, const char* brokers, const char* topic, const char* consumerGroup, __int32 partitionNum, __int64 maxRecords)
  840. {
  841. Consumer* consumerObjPtr = new Consumer(brokers, topic, consumerGroup, partitionNum, ctx->queryContextLogger().queryTraceLevel());
  842. try
  843. {
  844. consumerObjPtr->prepForMessageFetch();
  845. }
  846. catch(...)
  847. {
  848. delete(consumerObjPtr);
  849. throw;
  850. }
  851. return new KafkaStreamedDataset(consumerObjPtr, allocator, ctx->queryContextLogger().queryTraceLevel(), maxRecords);
  852. }
  853. ECL_KAFKA_API __int64 ECL_KAFKA_CALL setMessageOffset(ICodeContext* ctx, const char* brokers, const char* topic, const char* consumerGroup, __int32 partitionNum, __int64 newOffset)
  854. {
  855. Consumer consumerObj(brokers, topic, consumerGroup, partitionNum, ctx->queryContextLogger().queryTraceLevel());
  856. consumerObj.commitOffset(newOffset);
  857. return newOffset;
  858. }
  859. }
  860. //==============================================================================
  861. // Plugin Initialization and Teardown
  862. //==============================================================================
  863. #define CURRENT_KAFKA_VERSION "kafka plugin 1.1.0"
  864. static const char* kafkaCompatibleVersions[] = {
  865. "kafka plugin 1.0.0",
  866. CURRENT_KAFKA_VERSION,
  867. NULL };
  868. ECL_KAFKA_API bool getECLPluginDefinition(ECLPluginDefinitionBlock* pb)
  869. {
  870. if (pb->size == sizeof(ECLPluginDefinitionBlockEx))
  871. {
  872. ECLPluginDefinitionBlockEx* pbx = static_cast<ECLPluginDefinitionBlockEx*>(pb);
  873. pbx->compatibleVersions = kafkaCompatibleVersions;
  874. }
  875. else if (pb->size != sizeof(ECLPluginDefinitionBlock))
  876. {
  877. return false;
  878. }
  879. pb->magicVersion = PLUGIN_VERSION;
  880. pb->version = CURRENT_KAFKA_VERSION;
  881. pb->moduleName = "kafka";
  882. pb->ECL = NULL;
  883. pb->flags = PLUGIN_IMPLICIT_MODULE;
  884. pb->description = "ECL plugin library for the C++ API in librdkafka++\n";
  885. return true;
  886. }
  887. MODULE_INIT(INIT_PRIORITY_STANDARD)
  888. {
  889. KafkaPlugin::publisherCache = NULL;
  890. KafkaPlugin::publisherCacheExpirer = NULL;
  891. return true;
  892. }
  893. MODULE_EXIT()
  894. {
  895. // Delete the background thread expiring items from the publisher cache
  896. // before deleting the publisher cache
  897. if (KafkaPlugin::publisherCacheExpirer)
  898. {
  899. KafkaPlugin::publisherCacheExpirer->stop();
  900. delete(KafkaPlugin::publisherCacheExpirer);
  901. KafkaPlugin::publisherCacheExpirer = NULL;
  902. }
  903. if (KafkaPlugin::publisherCache)
  904. {
  905. KafkaPlugin::publisherCache->deleteAll();
  906. delete(KafkaPlugin::publisherCache);
  907. KafkaPlugin::publisherCache = NULL;
  908. }
  909. RdKafka::wait_destroyed(3000);
  910. }