SQLChannel.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648
  1. //
  2. // SQLChannel.cpp
  3. //
  4. // Library: Data
  5. // Package: Logging
  6. // Module: SQLChannel
  7. //
  8. // Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
  9. // and Contributors.
  10. //
  11. // SPDX-License-Identifier: BSL-1.0
  12. //
  13. #include "Poco/Data/SQLChannel.h"
  14. #include "Poco/Data/SessionFactory.h"
  15. #include "Poco/Data/BulkBinding.h"
  16. #include "Poco/DateTime.h"
  17. #include "Poco/DateTimeFormatter.h"
  18. #include "Poco/DateTimeFormat.h"
  19. #include "Poco/LoggingFactory.h"
  20. #include "Poco/Instantiator.h"
  21. #include "Poco/NumberParser.h"
  22. #include "Poco/NumberFormatter.h"
  23. #include "Poco/Stopwatch.h"
  24. #include "Poco/Format.h"
  25. #include "Poco/File.h"
  26. #include <fstream>
  27. namespace Poco {
  28. namespace Data {
  29. using namespace Keywords;
  30. const std::string SQLChannel::PROP_CONNECTOR("connector");
  31. const std::string SQLChannel::PROP_CONNECT("connect");
  32. const std::string SQLChannel::PROP_NAME("name");
  33. const std::string SQLChannel::PROP_TABLE("table");
  34. const std::string SQLChannel::PROP_ARCHIVE_TABLE("archive");
  35. const std::string SQLChannel::PROP_MAX_AGE("keep");
  36. const std::string SQLChannel::PROP_ASYNC("async");
  37. const std::string SQLChannel::PROP_TIMEOUT("timeout");
  38. const std::string SQLChannel::PROP_MIN_BATCH("minBatch");
  39. const std::string SQLChannel::PROP_MAX_BATCH("maxBatch");
  40. const std::string SQLChannel::PROP_BULK("bulk");
  41. const std::string SQLChannel::PROP_THROW("throw");
  42. const std::string SQLChannel::PROP_FILE("file");
  43. const std::string SQLChannel::SQL_INSERT_STMT = "INSERT INTO %s " \
  44. "(Source, Name, ProcessId, Thread, ThreadId, Priority, Text, DateTime)" \
  45. " VALUES %s";
  46. SQLChannel::SQLChannel():
  47. _name("-"),
  48. _table("T_POCO_LOG"),
  49. _tableChanged(true),
  50. _timeout(1000),
  51. _minBatch(DEFAULT_MIN_BATCH_SIZE),
  52. _maxBatch(DEFAULT_MAX_BATCH_SIZE),
  53. _bulk(true),
  54. _throw(false),
  55. _pid(),
  56. _tid(),
  57. _priority(),
  58. _reconnect(false),
  59. _running(false),
  60. _stop(false),
  61. _logged(0)
  62. {
  63. }
  64. SQLChannel::SQLChannel(const std::string& connector,
  65. const std::string& connect,
  66. const std::string& name,
  67. const std::string& table,
  68. int timeout,
  69. int minBatch,
  70. int maxBatch) :
  71. _connector(connector),
  72. _connect(connect),
  73. _name(name),
  74. _table(table),
  75. _tableChanged(true),
  76. _timeout(timeout),
  77. _minBatch(minBatch),
  78. _maxBatch(maxBatch),
  79. _bulk(false),
  80. _throw(false),
  81. _pid(),
  82. _tid(),
  83. _priority(),
  84. _pDBThread(new Thread),
  85. _reconnect(true),
  86. _running(false),
  87. _stop(false),
  88. _logged(0)
  89. {
  90. _pDBThread->start(*this);
  91. }
  92. SQLChannel::~SQLChannel()
  93. {
  94. try
  95. {
  96. stop();
  97. close(_timeout);
  98. wait();
  99. if (_pFileChannel)
  100. _pFileChannel->close();
  101. }
  102. catch (...)
  103. {
  104. poco_unexpected();
  105. }
  106. }
  107. std::string SQLChannel::maskPwd()
  108. {
  109. std::string displayConnect = _connect;
  110. Poco::istring is1(displayConnect.c_str());
  111. Poco::istring is2("pwd=");
  112. std::size_t pos1 = Poco::isubstr(is1, is2);
  113. if (pos1 == istring::npos)
  114. {
  115. is2 = "password=";
  116. pos1 = Poco::isubstr(is1, is2);
  117. }
  118. if (pos1 != istring::npos)
  119. {
  120. pos1 += is2.length();
  121. std::size_t pos2 = displayConnect.find(';', pos1);
  122. if (pos2 != std::string::npos)
  123. {
  124. std::string toReplace = displayConnect.substr(pos1, pos2-pos1);
  125. Poco::replaceInPlace(displayConnect, toReplace, std::string("***"));
  126. }
  127. else displayConnect.clear();
  128. }
  129. return displayConnect;
  130. }
  131. void SQLChannel::open()
  132. {
  133. if (!_connector.empty() && !_connect.empty())
  134. {
  135. try
  136. {
  137. _pSession = new Session(_connector, _connect, _timeout / 1000);
  138. if (_pSession->hasProperty("maxFieldSize")) _pSession->setProperty("maxFieldSize", 8192);
  139. if (_pSession->hasProperty("autoBind")) _pSession->setFeature("autoBind", true);
  140. _logger.information("Connected to %s: %s", _connector, maskPwd());
  141. return;
  142. }
  143. catch (DataException& ex)
  144. {
  145. _logger.error(ex.displayText());
  146. }
  147. }
  148. _pSession = nullptr;
  149. return;
  150. }
  151. void SQLChannel::close(int ms)
  152. {
  153. wait(ms);
  154. _pSession = nullptr;
  155. }
  156. void SQLChannel::log(const Message& msg)
  157. {
  158. _logQueue.enqueueNotification(new LogNotification(msg));
  159. }
  160. size_t SQLChannel::logSync()
  161. {
  162. try
  163. {
  164. return execSQL();
  165. }
  166. catch (Exception&)
  167. {
  168. if (_throw) throw;
  169. }
  170. return 0;
  171. }
  172. bool SQLChannel::processOne(int minBatch)
  173. {
  174. bool ret = false;
  175. if (_logQueue.size())
  176. {
  177. Notification::Ptr pN = _logQueue.dequeueNotification();
  178. LogNotification::Ptr pLN = pN.cast<LogNotification>();
  179. if (pLN)
  180. {
  181. const Message& msg = pLN->message();
  182. _source.push_back(msg.getSource());
  183. if (_source.back().empty()) _source.back() = _name;
  184. Poco::replaceInPlace(_source.back(), "'", "''");
  185. _pid.push_back(msg.getPid());
  186. _thread.push_back(msg.getThread());
  187. Poco::replaceInPlace(_thread.back(), "'", "''");
  188. _tid.push_back(msg.getTid());
  189. _priority.push_back(msg.getPriority());
  190. _text.push_back(msg.getText());
  191. Poco::replaceInPlace(_text.back(), "'", "''");
  192. _dateTime.push_back(msg.getTime());
  193. }
  194. ret = true;
  195. }
  196. if (_source.size() >= _minBatch) logSync();
  197. return ret;
  198. }
  199. void SQLChannel::run()
  200. {
  201. long sleepTime = 100; // milliseconds
  202. while (!_stop)
  203. {
  204. try
  205. {
  206. if (_reconnect)
  207. {
  208. close(_timeout);
  209. open();
  210. _reconnect = _pSession.isNull();
  211. if (_reconnect && sleepTime < 12800)
  212. sleepTime *= 2;
  213. }
  214. processOne(_minBatch);
  215. sleepTime = 100;
  216. }
  217. catch (Poco::Exception& ex)
  218. {
  219. _logger.error(ex.displayText());
  220. }
  221. catch (std::exception& ex)
  222. {
  223. _logger.error(ex.what());
  224. }
  225. catch (...)
  226. {
  227. _logger.error("SQLChannel::run(): unknown exception");
  228. }
  229. _running = true;
  230. Thread::sleep(100);
  231. }
  232. _running = false;
  233. }
  234. void SQLChannel::stop()
  235. {
  236. if (_pDBThread)
  237. {
  238. _reconnect = false;
  239. _stop = true;
  240. _pDBThread->join();
  241. while (_logQueue.size())
  242. processOne();
  243. }
  244. }
  245. void SQLChannel::reconnect()
  246. {
  247. if (!_pDBThread)
  248. {
  249. _pDBThread.reset(new Thread);
  250. _pDBThread->start(*this);
  251. }
  252. _reconnect = true;
  253. }
  254. void SQLChannel::setProperty(const std::string& name, const std::string& value)
  255. {
  256. Poco::FastMutex::ScopedLock l(_mutex);
  257. if (name == PROP_NAME)
  258. {
  259. _name = value;
  260. if (_name.empty()) _name = "-";
  261. }
  262. else if (name == PROP_CONNECTOR)
  263. {
  264. _connector = value;
  265. reconnect();
  266. }
  267. else if (name == PROP_CONNECT)
  268. {
  269. _connect = value;
  270. reconnect();
  271. }
  272. else if (name == PROP_TABLE)
  273. {
  274. _table = value;
  275. if (_pArchiveStrategy)
  276. _pArchiveStrategy->setSource(value);
  277. _tableChanged = true;
  278. }
  279. else if (name == PROP_ARCHIVE_TABLE)
  280. {
  281. if (value.empty())
  282. {
  283. _pArchiveStrategy = 0;
  284. }
  285. else if (_pArchiveStrategy)
  286. {
  287. _pArchiveStrategy->setDestination(value);
  288. }
  289. else
  290. {
  291. std::string threshold;
  292. if (_pArchiveStrategy) threshold = _pArchiveStrategy->getThreshold();
  293. _pArchiveStrategy = new ArchiveByAgeStrategy(_connector, _connect, _table, value, threshold);
  294. }
  295. }
  296. else if (name == PROP_MAX_AGE)
  297. {
  298. if (value.empty() || "forever" == value)
  299. {
  300. _pArchiveStrategy = 0;
  301. }
  302. else if (_pArchiveStrategy)
  303. {
  304. _pArchiveStrategy->setThreshold(value);
  305. }
  306. else
  307. {
  308. std::string destination = ArchiveByAgeStrategy::DEFAULT_ARCHIVE_DESTINATION;
  309. if (_pArchiveStrategy) destination = _pArchiveStrategy->getDestination();
  310. _pArchiveStrategy = new ArchiveByAgeStrategy(_connector, _connect, _table, destination, value);
  311. }
  312. }
  313. else if (name == PROP_ASYNC)
  314. {
  315. // no-op
  316. }
  317. else if (name == PROP_TIMEOUT)
  318. {
  319. if (value.empty() || '0' == value[0])
  320. _timeout = Statement::WAIT_FOREVER;
  321. else
  322. _timeout = NumberParser::parse(value);
  323. }
  324. else if (name == PROP_MIN_BATCH)
  325. {
  326. int minBatch = NumberParser::parse(value);
  327. if (!minBatch)
  328. throw Poco::InvalidArgumentException(Poco::format("SQLChannel::setProperty(%s,%s)", name, value));
  329. _minBatch = minBatch;
  330. }
  331. else if (name == PROP_MAX_BATCH)
  332. {
  333. int maxBatch = NumberParser::parse(value);
  334. if (!maxBatch)
  335. throw Poco::InvalidArgumentException(Poco::format("SQLChannel::setProperty(%s,%s)", name, value));
  336. _maxBatch = maxBatch;
  337. }
  338. else if (name == PROP_BULK)
  339. {
  340. _bulk = isTrue(value);
  341. }
  342. else if (name == PROP_THROW)
  343. {
  344. _throw = isTrue(value);
  345. }
  346. else if (name == PROP_FILE)
  347. {
  348. _file = value;
  349. }
  350. else
  351. {
  352. Channel::setProperty(name, value);
  353. }
  354. }
  355. std::string SQLChannel::getProperty(const std::string& name) const
  356. {
  357. Poco::FastMutex::ScopedLock l(_mutex);
  358. if (name == PROP_NAME)
  359. {
  360. if (_name != "-") return _name;
  361. else return "";
  362. }
  363. else if (name == PROP_CONNECTOR)
  364. {
  365. return _connector;
  366. }
  367. else if (name == PROP_CONNECT)
  368. {
  369. return _connect;
  370. }
  371. else if (name == PROP_TABLE)
  372. {
  373. return _table;
  374. }
  375. else if (name == PROP_ARCHIVE_TABLE)
  376. {
  377. return _pArchiveStrategy ? _pArchiveStrategy->getDestination() : "";
  378. }
  379. else if (name == PROP_MAX_AGE)
  380. {
  381. return _pArchiveStrategy ? _pArchiveStrategy->getThreshold() : "forever";
  382. }
  383. else if (name == PROP_TIMEOUT)
  384. {
  385. return NumberFormatter::format(_timeout);
  386. }
  387. else if (name == PROP_MIN_BATCH)
  388. {
  389. return std::to_string(_minBatch);
  390. }
  391. else if (name == PROP_MAX_BATCH)
  392. {
  393. return std::to_string(_maxBatch);
  394. }
  395. else if (name == PROP_BULK)
  396. {
  397. if (_bulk) return "true";
  398. else return "false";
  399. }
  400. else if (name == PROP_THROW)
  401. {
  402. if (_throw) return "true";
  403. else return "false";
  404. }
  405. else if (name == PROP_FILE)
  406. {
  407. return _file;
  408. }
  409. else
  410. {
  411. return Channel::getProperty(name);
  412. }
  413. }
  414. size_t SQLChannel::logTofile(AutoPtr<FileChannel>& pFileChannel, const std::string& fileName, bool clear)
  415. {
  416. static std::vector<std::string> names;
  417. if (names.size() != _source.size())
  418. names.resize(_source.size(), Poco::replace(_name, "'", "''"));
  419. std::size_t n = 0;
  420. if (!pFileChannel) pFileChannel = new FileChannel(fileName);
  421. if (pFileChannel)
  422. {
  423. std::string sql;
  424. Poco::format(sql, SQL_INSERT_STMT, _table, std::string());
  425. std::stringstream os;
  426. os << sql << '\n';
  427. auto it = _source.begin();
  428. auto end = _source.end();
  429. int idx = 0, batch = 0;
  430. for (; it != end; ++idx)
  431. {
  432. std::string dt = Poco::DateTimeFormatter::format(_dateTime[idx], "%Y-%m-%d %H:%M:%S.%i");
  433. os << "('" << *it << "','" <<
  434. names[idx] << "'," <<
  435. _pid[idx] << ",'" <<
  436. _thread[idx] << "'," <<
  437. _tid[idx] << ',' <<
  438. _priority[idx] << ",'" <<
  439. _text[idx] << "','" <<
  440. dt << "')";
  441. if (++batch == _maxBatch)
  442. {
  443. os << ";\n";
  444. Message msg(_source[0], os.str(), Message::PRIO_ERROR);
  445. pFileChannel->log(msg);
  446. os.str(""); sql.clear();
  447. Poco::format(sql, SQL_INSERT_STMT, _table, std::string());
  448. batch = 0;
  449. }
  450. if (++it == end)
  451. {
  452. os << ";\n";
  453. break;
  454. }
  455. os << ",\n";
  456. }
  457. Message msg(_source[0], os.str(), Message::PRIO_ERROR);
  458. pFileChannel->log(msg);
  459. n = _source.size();
  460. if (clear && n)
  461. {
  462. _source.clear();
  463. _pid.clear();
  464. _thread.clear();
  465. _tid.clear();
  466. _priority.clear();
  467. _text.clear();
  468. _dateTime.clear();
  469. }
  470. }
  471. return n;
  472. }
  473. size_t SQLChannel::execSQL()
  474. {
  475. static std::vector<std::string> names;
  476. if (names.size() != _source.size())
  477. names.resize(_source.size(), Poco::replace(_name, "'", "''"));
  478. static std::string placeholders = "(?,?,?,?,?,?,?,?)";
  479. Poco::FastMutex::ScopedLock l(_mutex);
  480. if (_tableChanged)
  481. {
  482. Poco::format(_sql, SQL_INSERT_STMT, _table, placeholders);
  483. _tableChanged = false;
  484. }
  485. if (!_pSession || !_pSession->isConnected()) open();
  486. if (_pArchiveStrategy) _pArchiveStrategy->archive();
  487. size_t n = 0;
  488. if (_pSession)
  489. {
  490. try
  491. {
  492. if (_bulk)
  493. {
  494. try
  495. {
  496. (*_pSession) << _sql,
  497. use(_source, bulk),
  498. use(names, bulk),
  499. use(_pid, bulk),
  500. use(_thread, bulk),
  501. use(_tid, bulk),
  502. use(_priority, bulk),
  503. use(_text, bulk),
  504. use(_dateTime, bulk), now;
  505. }
  506. // most likely bulk mode not supported,
  507. // log and try again
  508. catch (Poco::InvalidAccessException& ex)
  509. {
  510. _logger.log(ex);
  511. (*_pSession) << _sql,
  512. use(_source),
  513. use(names),
  514. use(_pid),
  515. use(_thread),
  516. use(_tid),
  517. use(_priority),
  518. use(_text),
  519. use(_dateTime), now;
  520. _bulk = false;
  521. }
  522. }
  523. else
  524. {
  525. (*_pSession) << _sql,
  526. use(_source),
  527. use(names),
  528. use(_pid),
  529. use(_thread),
  530. use(_tid),
  531. use(_priority),
  532. use(_text),
  533. use(_dateTime), now;
  534. }
  535. n = _source.size();
  536. }
  537. catch (Poco::Exception& ex)
  538. {
  539. _logger.error(ex.displayText());
  540. if (!_file.empty())
  541. n = logTofile(_pFileChannel, _file);
  542. close(_timeout);
  543. _reconnect = true;
  544. }
  545. catch (std::exception& ex)
  546. {
  547. _logger.error(ex.what());
  548. if (!_file.empty())
  549. n = logTofile(_pFileChannel, _file);
  550. close(_timeout);
  551. _reconnect = true;
  552. }
  553. }
  554. else
  555. {
  556. if (!_file.empty())
  557. n = logTofile(_pFileChannel, _file);
  558. }
  559. if (n)
  560. {
  561. _logged += n;
  562. _source.clear();
  563. _pid.clear();
  564. _thread.clear();
  565. _tid.clear();
  566. _priority.clear();
  567. _text.clear();
  568. _dateTime.clear();
  569. }
  570. return n;
  571. }
  572. std::size_t SQLChannel::wait(int ms)
  573. {
  574. Stopwatch sw;
  575. sw.start();
  576. int processed = _logQueue.size();
  577. while (_logQueue.size())
  578. {
  579. Thread::sleep(10);
  580. if (ms && sw.elapsed() * 1000 > ms)
  581. break;
  582. }
  583. return processed - _logQueue.size();
  584. }
  585. void SQLChannel::registerChannel()
  586. {
  587. Poco::LoggingFactory::defaultFactory().registerChannelClass("SQLChannel",
  588. new Poco::Instantiator<SQLChannel, Poco::Channel>);
  589. }
  590. } } // namespace Poco::Data