kafka.cpp 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086
  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. // STRING message;
  146. // END;
  147. *(__int32*)(row) = messageObjPtr->partition();
  148. *(__int64*)(row + sizeof(__int32)) = messageObjPtr->offset();
  149. *(size32_t*)(row + sizeof(__int32) + sizeof(__int64)) = messageObjPtr->len();
  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. if (producerPtr)
  317. {
  318. RdKafka::Conf* topicConfPtr = RdKafka::Conf::create(RdKafka::Conf::CONF_TOPIC);
  319. // Set any topic configurations from file
  320. std::string confName = "kafka_publisher_topic_" + topic + ".conf";
  321. applyConfig(confName.c_str(), topicConfPtr, traceLevel);
  322. // Create the topic
  323. topicPtr.store(RdKafka::Topic::create(producerPtr, topic, topicConfPtr, errStr), std::memory_order_release);
  324. if (topicPtr)
  325. {
  326. // Start the attached background poller
  327. pollerPtr->start();
  328. }
  329. else
  330. {
  331. throw MakeStringException(-1, "Kafka: Unable to create producer topic object for topic '%s'; error: '%s'", topic.c_str(), errStr.c_str());
  332. }
  333. }
  334. else
  335. {
  336. throw MakeStringException(-1, "Kafka: Unable to create producer object for brokers '%s'; error: '%s'", brokers.c_str(), errStr.c_str());
  337. }
  338. }
  339. else
  340. {
  341. throw MakeStringException(-1, "Kafka: Unable to create producer global configuration object for brokers '%s'; error: '%s'", brokers.c_str(), errStr.c_str());
  342. }
  343. }
  344. }
  345. }
  346. void Publisher::sendMessage(const std::string& message, const std::string& key)
  347. {
  348. __int32 maxAttempts = 10; //!< Maximum number of tries if local queue is full
  349. __int32 attemptNum = 0;
  350. // Make sure we have a valid connection to the Kafka cluster
  351. ensureSetup();
  352. // Actually send the message
  353. while (true)
  354. {
  355. 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);
  356. if (resp == RdKafka::ERR_NO_ERROR)
  357. {
  358. break;
  359. }
  360. else if (resp == RdKafka::ERR__QUEUE_FULL)
  361. {
  362. if (attemptNum < maxAttempts)
  363. {
  364. usleep(pollTimeout);
  365. ++attemptNum;
  366. }
  367. else
  368. {
  369. throw MakeStringException(-1, "Kafka: Unable to send message to topic '%s'; error: '%s'", topic.c_str(), RdKafka::err2str(resp).c_str());
  370. }
  371. }
  372. else
  373. {
  374. throw MakeStringException(-1, "Kafka: Unable to send message to topic '%s'; error: '%s'", topic.c_str(), RdKafka::err2str(resp).c_str());
  375. }
  376. }
  377. }
  378. void Publisher::event_cb(RdKafka::Event& event)
  379. {
  380. if (traceLevel > 4)
  381. {
  382. switch (event.type())
  383. {
  384. case RdKafka::Event::EVENT_ERROR:
  385. DBGLOG("Kafka: Error: %s", event.str().c_str());
  386. break;
  387. case RdKafka::Event::EVENT_STATS:
  388. DBGLOG("Kafka: Stats: %s", event.str().c_str());
  389. break;
  390. case RdKafka::Event::EVENT_LOG:
  391. DBGLOG("Kafka: Log: %s", event.str().c_str());
  392. break;
  393. }
  394. }
  395. }
  396. void Publisher::dr_cb (RdKafka::Message& message)
  397. {
  398. if (message.err() != RdKafka::ERR_NO_ERROR)
  399. {
  400. StringBuffer payloadStr;
  401. if (message.len() == 0)
  402. payloadStr.append("<no message>");
  403. else
  404. payloadStr.append(message.len(), static_cast<const char*>(message.payload()));
  405. DBGLOG("Kafka: Error publishing message: %d (%s); message: '%s'", message.err(), message.errstr().c_str(), payloadStr.str());
  406. }
  407. }
  408. //--------------------------------------------------------------------------
  409. Consumer::Consumer(const std::string& _brokers, const std::string& _topic, const std::string& _consumerGroup, __int32 _partitionNum, int _traceLevel)
  410. : brokers(_brokers),
  411. topic(_topic),
  412. consumerGroup(_consumerGroup),
  413. partitionNum(_partitionNum),
  414. traceLevel(_traceLevel)
  415. {
  416. consumerPtr = NULL;
  417. topicPtr = NULL;
  418. char cpath[_MAX_DIR];
  419. GetCurrentDirectory(_MAX_DIR, cpath);
  420. offsetPath.append(cpath);
  421. addPathSepChar(offsetPath);
  422. offsetPath.append(topic.c_str());
  423. offsetPath.append("-");
  424. offsetPath.append(partitionNum);
  425. if (!consumerGroup.empty())
  426. {
  427. offsetPath.append("-");
  428. offsetPath.append(consumerGroup.c_str());
  429. }
  430. offsetPath.append(".offset");
  431. }
  432. Consumer::~Consumer()
  433. {
  434. if (consumerPtr && topicPtr)
  435. {
  436. consumerPtr->stop(topicPtr, partitionNum);
  437. }
  438. delete(topicPtr.load());
  439. delete(consumerPtr);
  440. }
  441. RdKafka::Handle* Consumer::handle()
  442. {
  443. return static_cast<RdKafka::Handle*>(consumerPtr);
  444. }
  445. void Consumer::ensureSetup()
  446. {
  447. if (!topicPtr.load(std::memory_order_acquire))
  448. {
  449. CriticalBlock block(lock);
  450. if (!topicPtr.load(std::memory_order_relaxed))
  451. {
  452. initFileOffsetIfNotExist();
  453. std::string errStr;
  454. RdKafka::Conf* globalConfig = RdKafka::Conf::create(RdKafka::Conf::CONF_GLOBAL);
  455. if (globalConfig)
  456. {
  457. // Set global configuration parameters, used mainly at the consumer level
  458. globalConfig->set("metadata.broker.list", brokers, errStr);
  459. globalConfig->set("compression.codec", "snappy", errStr);
  460. globalConfig->set("queued.max.messages.kbytes", "10000000", errStr);
  461. globalConfig->set("fetch.message.max.bytes", "10000000", errStr);
  462. // Set any global configurations from file, allowing
  463. // overrides of above settings
  464. applyConfig("kafka_global.conf", globalConfig, traceLevel);
  465. // Set consumer callbacks
  466. globalConfig->set("event_cb", static_cast<RdKafka::EventCb*>(this), errStr);
  467. // Create the consumer
  468. consumerPtr = RdKafka::Consumer::create(globalConfig, errStr);
  469. if (consumerPtr)
  470. {
  471. RdKafka::Conf* topicConfPtr = RdKafka::Conf::create(RdKafka::Conf::CONF_TOPIC);
  472. // Set the per-topic configuration parameters
  473. topicConfPtr->set("group.id", consumerGroup, errStr);
  474. topicConfPtr->set("auto.offset.reset", "smallest", errStr);
  475. // Set any topic configurations from file, allowing
  476. // overrides of above settings
  477. std::string confName = "kafka_consumer_topic_" + topic + ".conf";
  478. applyConfig(confName.c_str(), topicConfPtr, traceLevel);
  479. // Ensure that some items are set a certain way
  480. // by setting them after loading the external conf
  481. topicConfPtr->set("auto.commit.enable", "false", errStr);
  482. // Additional settings for updated librdkafka
  483. topicConfPtr->set("enable.auto.commit", "false", errStr);
  484. topicConfPtr->set("offset.store.method", "file", errStr);
  485. topicConfPtr->set("offset.store.path", offsetPath.str(), errStr);
  486. // Create the topic
  487. topicPtr.store(RdKafka::Topic::create(consumerPtr, topic, topicConfPtr, errStr), std::memory_order_release);
  488. if (!topicPtr)
  489. {
  490. throw MakeStringException(-1, "Kafka: Unable to create consumer topic object for topic '%s'; error: '%s'", topic.c_str(), errStr.c_str());
  491. }
  492. }
  493. else
  494. {
  495. throw MakeStringException(-1, "Kafka: Unable to create consumer object for brokers '%s'; error: '%s'", brokers.c_str(), errStr.c_str());
  496. }
  497. }
  498. else
  499. {
  500. throw MakeStringException(-1, "Kafka: Unable to create consumer global configuration object for brokers '%s'; error: '%s'", brokers.c_str(), errStr.c_str());
  501. }
  502. }
  503. }
  504. }
  505. RdKafka::Message* Consumer::getOneMessage()
  506. {
  507. return consumerPtr->consume(topicPtr, partitionNum, POLL_TIMEOUT);
  508. }
  509. void Consumer::prepForMessageFetch()
  510. {
  511. // Make sure we have a valid connection to the Kafka cluster
  512. ensureSetup();
  513. // Start the local read queue
  514. RdKafka::ErrorCode startErr = consumerPtr->start(topicPtr, partitionNum, RdKafka::Topic::OFFSET_STORED);
  515. if (startErr == RdKafka::ERR_NO_ERROR)
  516. {
  517. if (traceLevel > 4)
  518. {
  519. DBGLOG("Kafka: Started Consumer for %s:%d @ %s", topic.c_str(), partitionNum, brokers.c_str());
  520. }
  521. }
  522. else
  523. {
  524. throw MakeStringException(-1, "Kafka: Failed to start Consumer read for %s:%d @ %s; error: %d", topic.c_str(), partitionNum, brokers.c_str(), startErr);
  525. }
  526. }
  527. void Consumer::commitOffset(__int64 offset) const
  528. {
  529. if (offset >= 0)
  530. {
  531. // Not using librdkafka's offset_store because it seems to be broken
  532. // topicPtr->offset_store(partitionNum, offset);
  533. // Create/overwrite a file using the same naming convention and
  534. // file contents that librdkafka uses so it can pick up where
  535. // we left off; NOTE: librdkafka does not clean the topic name
  536. // or consumer group name when constructing this path
  537. // (which is actually a security concern), so we can't clean, either
  538. std::ofstream outFile(offsetPath.str(), std::ofstream::trunc);
  539. outFile << offset;
  540. if (traceLevel > 4)
  541. {
  542. DBGLOG("Kafka: Saved offset %lld to %s", offset, offsetPath.str());
  543. }
  544. }
  545. }
  546. void Consumer::initFileOffsetIfNotExist() const
  547. {
  548. if (!checkFileExists(offsetPath.str()))
  549. {
  550. commitOffset(0);
  551. if (traceLevel > 4)
  552. {
  553. DBGLOG("Kafka: Creating initial offset file %s", offsetPath.str());
  554. }
  555. }
  556. }
  557. void Consumer::event_cb(RdKafka::Event& event)
  558. {
  559. if (traceLevel > 4)
  560. {
  561. switch (event.type())
  562. {
  563. case RdKafka::Event::EVENT_ERROR:
  564. DBGLOG("Kafka: Error: %s", event.str().c_str());
  565. break;
  566. case RdKafka::Event::EVENT_STATS:
  567. DBGLOG("Kafka: Stats: %s", event.str().c_str());
  568. break;
  569. case RdKafka::Event::EVENT_LOG:
  570. DBGLOG("Kafka: Log: %s", event.str().c_str());
  571. break;
  572. }
  573. }
  574. }
  575. //--------------------------------------------------------------------------
  576. /** @class PublisherCacheObj
  577. *
  578. * Class used to create and cache publisher objects and connections
  579. */
  580. static class PublisherCacheObj
  581. {
  582. private:
  583. typedef std::map<std::string, Publisher*> ObjMap;
  584. public:
  585. /**
  586. * Constructor
  587. *
  588. * @param _traceLevel The current logging level
  589. */
  590. PublisherCacheObj(int _traceLevel)
  591. : traceLevel(_traceLevel)
  592. {
  593. }
  594. void deleteAll()
  595. {
  596. CriticalBlock block(lock);
  597. for (ObjMap::iterator x = cachedPublishers.begin(); x != cachedPublishers.end(); x++)
  598. {
  599. if (x->second)
  600. {
  601. // Shutdown the attached poller before deleting
  602. x->second->shutdownPoller();
  603. // Now delete
  604. delete(x->second);
  605. }
  606. }
  607. cachedPublishers.clear();
  608. }
  609. /**
  610. * Remove previously-created objects that have been inactive
  611. * for awhile
  612. */
  613. void expire()
  614. {
  615. if (!cachedPublishers.empty())
  616. {
  617. CriticalBlock block(lock);
  618. time_t oldestAllowedTime = time(NULL) - OBJECT_EXPIRE_TIMEOUT_SECONDS;
  619. __int32 expireCount = 0;
  620. for (ObjMap::iterator x = cachedPublishers.begin(); x != cachedPublishers.end(); /* increment handled explicitly */)
  621. {
  622. // Expire only if the publisher has been inactive and if
  623. // there are no messages in the outbound queue
  624. if (x->second && x->second->getTimeTouched() < oldestAllowedTime && x->second->messagesWaitingInQueue() == 0)
  625. {
  626. // Shutdown the attached poller before deleting
  627. x->second->shutdownPoller();
  628. // Delete the object
  629. delete(x->second);
  630. // Erase from map
  631. cachedPublishers.erase(x++);
  632. ++expireCount;
  633. }
  634. else
  635. {
  636. x++;
  637. }
  638. }
  639. if (traceLevel > 4 && expireCount > 0)
  640. {
  641. DBGLOG("Kafka: Expired %d cached publisher%s", expireCount, (expireCount == 1 ? "" : "s"));
  642. }
  643. }
  644. }
  645. /**
  646. * Gets an established Publisher, based on unique broker/topic
  647. * pairs, or creates a new one.
  648. *
  649. * @param brokers One or more Kafka brokers, in the
  650. * format 'name[:port]' where 'name'
  651. * is either a host name or IP address;
  652. * multiple brokers can be delimited
  653. * with commas
  654. * @param topic The name of the topic
  655. * @param pollTimeout The number of milliseconds to give
  656. * to librdkafka when executing
  657. * asynchronous activities
  658. *
  659. * @return A pointer to a Publisher* object.
  660. */
  661. Publisher* getPublisher(const std::string& brokers, const std::string& topic, __int32 pollTimeout)
  662. {
  663. Publisher* pubObjPtr = NULL;
  664. StringBuffer suffixStr;
  665. std::string key;
  666. // Create the key used to look up previously-created objects
  667. suffixStr.append(pollTimeout);
  668. key = brokers + "+" + topic + "+" + suffixStr.str();
  669. {
  670. CriticalBlock block(lock);
  671. // Try to find a cached publisher
  672. pubObjPtr = cachedPublishers[key];
  673. if (pubObjPtr)
  674. {
  675. pubObjPtr->updateTimeTouched();
  676. }
  677. else
  678. {
  679. // Publisher for that set of brokers and topic does not exist; create one
  680. pubObjPtr = new Publisher(brokers, topic, pollTimeout, traceLevel);
  681. cachedPublishers[key] = pubObjPtr;
  682. if (traceLevel > 4)
  683. {
  684. DBGLOG("Kafka: Created and cached new publisher object: %s @ %s", topic.c_str(), brokers.c_str());
  685. }
  686. }
  687. }
  688. if (!pubObjPtr)
  689. {
  690. throw MakeStringException(-1, "Kafka: Unable to create publisher for brokers '%s' and topic '%s'", brokers.c_str(), topic.c_str());
  691. }
  692. return pubObjPtr;
  693. }
  694. private:
  695. ObjMap cachedPublishers; //!< std::map of created Publisher object pointers
  696. CriticalSection lock; //!< Mutex guarding modifications to cachedPublishers
  697. int traceLevel; //!< The current logging level
  698. } *publisherCache;
  699. //--------------------------------------------------------------------------
  700. /** @class PublisherCacheExpirerObj
  701. * Class used to expire old publisher objects held within publisherCache
  702. */
  703. static class PublisherCacheExpirerObj : public Thread
  704. {
  705. public:
  706. PublisherCacheExpirerObj()
  707. : Thread("Kafka::PublisherExpirer"),
  708. shouldRun(false)
  709. {
  710. }
  711. virtual void start()
  712. {
  713. if (!isAlive())
  714. {
  715. shouldRun = true;
  716. Thread::start();
  717. }
  718. }
  719. virtual void stop()
  720. {
  721. if (isAlive())
  722. {
  723. shouldRun = false;
  724. join();
  725. }
  726. }
  727. virtual int run()
  728. {
  729. while (shouldRun)
  730. {
  731. if (publisherCache)
  732. {
  733. publisherCache->expire();
  734. }
  735. usleep(1000);
  736. }
  737. return 0;
  738. }
  739. private:
  740. std::atomic_bool shouldRun; //!< If true, we should execute our thread's main event loop
  741. } *publisherCacheExpirer;
  742. //--------------------------------------------------------------------------
  743. // Lazy Initialization
  744. //--------------------------------------------------------------------------
  745. /**
  746. * Make sure the publisher object cache is initialized as well as the
  747. * associated background thread for expiring idle publishers. This is
  748. * called only once.
  749. *
  750. * @param traceLevel Current logging level
  751. */
  752. static void setupPublisherCache(int traceLevel)
  753. {
  754. KafkaPlugin::publisherCache = new KafkaPlugin::PublisherCacheObj(traceLevel);
  755. KafkaPlugin::publisherCacheExpirer = new KafkaPlugin::PublisherCacheExpirerObj;
  756. KafkaPlugin::publisherCacheExpirer->start();
  757. }
  758. //--------------------------------------------------------------------------
  759. // Advertised Entry Point Functions
  760. //--------------------------------------------------------------------------
  761. ECL_KAFKA_API bool ECL_KAFKA_CALL publishMessage(ICodeContext* ctx, const char* brokers, const char* topic, const char* message, const char* key)
  762. {
  763. std::call_once(pubCacheInitFlag, setupPublisherCache, ctx->queryContextLogger().queryTraceLevel());
  764. Publisher* pubObjPtr = publisherCache->getPublisher(brokers, topic, POLL_TIMEOUT);
  765. pubObjPtr->sendMessage(message, key);
  766. return true;
  767. }
  768. ECL_KAFKA_API __int32 ECL_KAFKA_CALL getTopicPartitionCount(ICodeContext* ctx, const char* brokers, const char* topic)
  769. {
  770. // We have to use librdkafka's C API for this right now, as the C++ API
  771. // does not expose a topic's metadata. In addition, there is no easy
  772. // link between the exposed C++ objects and the structs used by the
  773. // C API, so we are basically creating a brand-new connection from
  774. // scratch.
  775. __int32 pCount = 0;
  776. char errstr[512];
  777. rd_kafka_conf_t* conf = rd_kafka_conf_new();
  778. rd_kafka_t* rk = rd_kafka_new(RD_KAFKA_CONSUMER, conf, errstr, sizeof(errstr));
  779. if (rk)
  780. {
  781. if (rd_kafka_brokers_add(rk, brokers) != 0)
  782. {
  783. rd_kafka_topic_conf_t* topic_conf = rd_kafka_topic_conf_new();
  784. rd_kafka_topic_t* rkt = rd_kafka_topic_new(rk, topic, topic_conf);
  785. if (rkt)
  786. {
  787. const struct rd_kafka_metadata* metadata = NULL;
  788. rd_kafka_resp_err_t err = rd_kafka_metadata(rk, 0, rkt, &metadata, 5000);
  789. if (err == RD_KAFKA_RESP_ERR_NO_ERROR)
  790. {
  791. pCount = metadata->topics[0].partition_cnt;
  792. rd_kafka_metadata_destroy(metadata);
  793. }
  794. else
  795. {
  796. if (ctx->queryContextLogger().queryTraceLevel() > 4)
  797. {
  798. DBGLOG("Kafka: Error retrieving metadata from topic: %s @ %s: '%s'", topic, brokers, rd_kafka_err2str(err));
  799. }
  800. }
  801. rd_kafka_topic_destroy(rkt);
  802. }
  803. else
  804. {
  805. if (ctx->queryContextLogger().queryTraceLevel() > 4)
  806. {
  807. DBGLOG("Kafka: Could not create topic object: %s @ %s", topic, brokers);
  808. }
  809. }
  810. }
  811. else
  812. {
  813. if (ctx->queryContextLogger().queryTraceLevel() > 4)
  814. {
  815. DBGLOG("Kafka: Could not add brokers: %s @ %s", topic, brokers);
  816. }
  817. }
  818. rd_kafka_destroy(rk);
  819. }
  820. if (pCount == 0)
  821. {
  822. DBGLOG("Kafka: Unable to retrieve partition count from topic: %s @ %s", topic, brokers);
  823. }
  824. return pCount;
  825. }
  826. 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)
  827. {
  828. Consumer* consumerObjPtr = new Consumer(brokers, topic, consumerGroup, partitionNum, ctx->queryContextLogger().queryTraceLevel());
  829. try
  830. {
  831. consumerObjPtr->prepForMessageFetch();
  832. }
  833. catch(...)
  834. {
  835. delete(consumerObjPtr);
  836. throw;
  837. }
  838. return new KafkaStreamedDataset(consumerObjPtr, allocator, ctx->queryContextLogger().queryTraceLevel(), maxRecords);
  839. }
  840. ECL_KAFKA_API __int64 ECL_KAFKA_CALL setMessageOffset(ICodeContext* ctx, const char* brokers, const char* topic, const char* consumerGroup, __int32 partitionNum, __int64 newOffset)
  841. {
  842. Consumer consumerObj(brokers, topic, consumerGroup, partitionNum, ctx->queryContextLogger().queryTraceLevel());
  843. consumerObj.commitOffset(newOffset);
  844. return newOffset;
  845. }
  846. }
  847. //==============================================================================
  848. // Plugin Initialization and Teardown
  849. //==============================================================================
  850. #define CURRENT_KAFKA_VERSION "kafka plugin 1.0.0"
  851. static const char* kafkaCompatibleVersions[] = {
  852. CURRENT_KAFKA_VERSION,
  853. NULL };
  854. ECL_KAFKA_API bool getECLPluginDefinition(ECLPluginDefinitionBlock* pb)
  855. {
  856. if (pb->size == sizeof(ECLPluginDefinitionBlockEx))
  857. {
  858. ECLPluginDefinitionBlockEx* pbx = static_cast<ECLPluginDefinitionBlockEx*>(pb);
  859. pbx->compatibleVersions = kafkaCompatibleVersions;
  860. }
  861. else if (pb->size != sizeof(ECLPluginDefinitionBlock))
  862. {
  863. return false;
  864. }
  865. pb->magicVersion = PLUGIN_VERSION;
  866. pb->version = CURRENT_KAFKA_VERSION;
  867. pb->moduleName = "kafka";
  868. pb->ECL = NULL;
  869. pb->flags = PLUGIN_IMPLICIT_MODULE;
  870. pb->description = "ECL plugin library for the C++ API in librdkafka++\n";
  871. return true;
  872. }
  873. MODULE_INIT(INIT_PRIORITY_STANDARD)
  874. {
  875. KafkaPlugin::publisherCache = NULL;
  876. KafkaPlugin::publisherCacheExpirer = NULL;
  877. return true;
  878. }
  879. MODULE_EXIT()
  880. {
  881. // Delete the background thread expiring items from the publisher cache
  882. // before deleting the publisher cache
  883. if (KafkaPlugin::publisherCacheExpirer)
  884. {
  885. KafkaPlugin::publisherCacheExpirer->stop();
  886. delete(KafkaPlugin::publisherCacheExpirer);
  887. KafkaPlugin::publisherCacheExpirer = NULL;
  888. }
  889. if (KafkaPlugin::publisherCache)
  890. {
  891. KafkaPlugin::publisherCache->deleteAll();
  892. delete(KafkaPlugin::publisherCache);
  893. KafkaPlugin::publisherCache = NULL;
  894. }
  895. RdKafka::wait_destroyed(3000);
  896. }