loggingmanager.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  1. /*##############################################################################
  2. HPCC SYSTEMS software Copyright (C) 2014 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 "LoggingErrors.hpp"
  14. #include "loggingcommon.hpp"
  15. #include "loggingmanager.hpp"
  16. #include "compressutil.hpp"
  17. #include "logconfigptree.hpp"
  18. using namespace LogConfigPTree;
  19. CLoggingManager::~CLoggingManager(void)
  20. {
  21. for (unsigned int x = 0; x < loggingAgentThreads.size(); x++)
  22. {
  23. loggingAgentThreads[x]->stop();
  24. loggingAgentThreads[x]->Release();
  25. }
  26. loggingAgentThreads.clear();
  27. }
  28. //Called when Logging manager is created. Create logging agents based on settings
  29. bool CLoggingManager::init(IPropertyTree* cfg, const char* service)
  30. {
  31. if (!cfg)
  32. {
  33. OERRLOG(EspLoggingErrors::ConfigurationFileEntryError, "Logging Manager setting not found for %s", service);
  34. return false;
  35. }
  36. StringAttr failSafeLogsDir;
  37. decoupledLogging = getConfigValue<bool>(cfg, PropDecoupledLogging, false);
  38. oneTankFile = getConfigValue<bool>(cfg, "FailSafe", true);
  39. if (decoupledLogging)
  40. { //Only set the failSafeLogsDir for decoupledLogging.
  41. //The failSafeLogsDir tells a logging agent to work as a decoupledLogging agent,
  42. //as well as where to read the tank file.
  43. const char* logsDir = queryConfigValue(cfg, PropFailSafeLogsDir);
  44. if (!isEmptyString(logsDir))
  45. failSafeLogsDir.set(logsDir);
  46. else
  47. failSafeLogsDir.set(DefaultFailSafeLogsDir);
  48. }
  49. if (oneTankFile || decoupledLogging)
  50. {// the logFailSafe is used to create a tank file.
  51. logFailSafe.setown(createFailSafeLogger(cfg, service, cfg->queryProp("@name")));
  52. logContentFilter.readAllLogFilters(cfg);
  53. }
  54. Owned<IPTreeIterator> loggingAgentSettings = cfg->getElements("LogAgent");
  55. ForEach(*loggingAgentSettings)
  56. {
  57. IPropertyTree& loggingAgentTree = loggingAgentSettings->query();
  58. const char* agentName = loggingAgentTree.queryProp("@name");
  59. const char* agentType = loggingAgentTree.queryProp("@type");
  60. const char* agentPlugin = loggingAgentTree.queryProp("@plugin");
  61. if (!agentName || !*agentName || !agentPlugin || !*agentPlugin)
  62. continue;
  63. IEspLogAgent* loggingAgent = loadLoggingAgent(agentName, agentPlugin, service, cfg);
  64. if (!loggingAgent)
  65. {
  66. OERRLOG(-1, "Failed to create logging agent for %s", agentName);
  67. continue;
  68. }
  69. loggingAgent->init(agentName, agentType, &loggingAgentTree, service);
  70. loggingAgent->initVariants(&loggingAgentTree);
  71. if (loggingAgent->hasService(LGSTGetTransactionID))
  72. setServiceMaskService(LGSTGetTransactionID);
  73. if (loggingAgent->hasService(LGSTGetTransactionSeed))
  74. setServiceMaskService(LGSTGetTransactionSeed);
  75. if (loggingAgent->hasService(LGSTUpdateLOG))
  76. setServiceMaskService(LGSTUpdateLOG);
  77. IUpdateLogThread* logThread = createUpdateLogThread(&loggingAgentTree, service, agentName, failSafeLogsDir.get(), loggingAgent);
  78. if(!logThread)
  79. throw MakeStringException(-1, "Failed to create update log thread for %s", agentName);
  80. loggingAgentThreads.push_back(logThread);
  81. }
  82. initialized = true;
  83. return !loggingAgentThreads.empty();
  84. }
  85. typedef IEspLogAgent* (*newLoggingAgent_t_)();
  86. IEspLogAgent* CLoggingManager::loadLoggingAgent(const char* name, const char* dll, const char* service, IPropertyTree* cfg)
  87. {
  88. StringBuffer plugin;
  89. plugin.append(SharedObjectPrefix).append(dll).append(SharedObjectExtension);
  90. HINSTANCE loggingAgentLib = LoadSharedObject(plugin.str(), true, false);
  91. if(!loggingAgentLib)
  92. throw MakeStringException(EspLoggingErrors::LoadLoggingLibraryError, "can't load library %s", plugin.str());
  93. newLoggingAgent_t_ xproc = (newLoggingAgent_t_)GetSharedProcedure(loggingAgentLib, "newLoggingAgent");
  94. if (!xproc)
  95. throw MakeStringException(EspLoggingErrors::LoadLoggingLibraryError, "procedure newLoggingAgent of %s can't be loaded", plugin.str());
  96. return (IEspLogAgent*) xproc();
  97. }
  98. IEspLogEntry* CLoggingManager::createLogEntry()
  99. {
  100. return new CEspLogEntry();
  101. }
  102. bool CLoggingManager::hasService(LOGServiceType service) const
  103. {
  104. return ((serviceMask & (1 << service)) != 0);
  105. }
  106. bool CLoggingManager::updateLog(IEspLogEntry* entry, StringBuffer& status)
  107. {
  108. if (entry->getLogContent())
  109. return updateLog(entry->getEspContext(), entry->getOption(), entry->getLogContent(), status);
  110. if (entry->getLogInfoTree())
  111. return updateLog(entry->getEspContext(), entry->getOption(), entry->getLogInfoTree(), entry->getExtraLog(), status);
  112. return updateLog(entry->getEspContext(), entry->getOption(), entry->getUserContextTree(), entry->getUserRequestTree(), entry->getScriptValuesTree(),
  113. entry->getBackEndReq(), entry->getBackEndResp(), entry->getUserResp(), entry->getLogDatasets(), status);
  114. }
  115. bool CLoggingManager::updateLog(IEspContext* espContext, const char* option, const char* logContent, StringBuffer& status)
  116. {
  117. if (!initialized)
  118. throw MakeStringException(-1,"LoggingManager not initialized");
  119. bool bRet = false;
  120. try
  121. {
  122. Owned<IEspUpdateLogRequestWrap> req = new CUpdateLogRequestWrap(nullptr, option, logContent);
  123. Owned<IEspUpdateLogResponse> resp = createUpdateLogResponse();
  124. bRet = updateLog(espContext, *req, *resp, status);
  125. }
  126. catch (IException* e)
  127. {
  128. status.set("Failed to update log: ");
  129. e->errorMessage(status);
  130. OERRLOG("%s", status.str());
  131. e->Release();
  132. }
  133. return bRet;
  134. }
  135. bool CLoggingManager::updateLog(IEspContext* espContext, const char* option, IPropertyTree* logInfo, IInterface* extraLog, StringBuffer& status)
  136. {
  137. if (!initialized)
  138. throw MakeStringException(-1,"LoggingManager not initialized");
  139. bool bRet = false;
  140. try
  141. {
  142. Owned<IEspUpdateLogRequestWrap> req = new CUpdateLogRequestWrap(nullptr, option, LINK(logInfo), LINK(extraLog));
  143. Owned<IEspUpdateLogResponse> resp = createUpdateLogResponse();
  144. bRet = updateLog(espContext, *req, *resp, status);
  145. }
  146. catch (IException* e)
  147. {
  148. status.set("Failed to update log: ");
  149. e->errorMessage(status);
  150. OERRLOG("%s", status.str());
  151. e->Release();
  152. }
  153. return bRet;
  154. }
  155. bool CLoggingManager::updateLog(IEspContext* espContext, const char* option, IPropertyTree* userContext, IPropertyTree* userRequest, IPropertyTree *scriptValues,
  156. const char* backEndReq, const char* backEndResp, const char* userResp, const char* logDatasets, StringBuffer& status)
  157. {
  158. if (!initialized)
  159. throw MakeStringException(-1,"LoggingManager not initialized");
  160. bool bRet = false;
  161. try
  162. {
  163. Owned<IPropertyTree> espContextTree;
  164. if (espContext)
  165. {
  166. double responseTime = (msTick() - espContext->queryCreationTime()) / 1000.0;
  167. CDateTime when;
  168. when.setNow();
  169. espContextTree.setown(createPTree("ESPContext"));
  170. short port;
  171. StringBuffer sourceIP, peerStr;
  172. const char* esdlBindingID = espContext->queryESDLBindingID();
  173. espContext->getServAddress(sourceIP, port);
  174. espContextTree->addProp("SourceIP", sourceIP.str());
  175. espContext->getPeer(peerStr);
  176. espContextTree->addProp("Peer", peerStr.str());
  177. if (!isEmptyString(esdlBindingID))
  178. espContextTree->addProp("ESDLBindingID", esdlBindingID);
  179. //More information in espContext may be added to the espContextTree later.
  180. const char* userId = espContext->queryUserId();
  181. if (userId && *userId)
  182. espContextTree->addProp("UserName", userId);
  183. espContextTree->addProp("ResponseTime", VStringBuffer("%.4f", responseTime));
  184. StringBuffer whenStr;
  185. when.getString(whenStr);
  186. espContextTree->addProp("TransactionEnd", whenStr);
  187. if (responseTime > 1.0)
  188. {
  189. when.adjustTimeSecs(-int(responseTime));
  190. when.getString(whenStr.clear());
  191. }
  192. espContextTree->addProp("TransactionStart", whenStr);
  193. }
  194. Owned<IEspUpdateLogRequestWrap> req = new CUpdateLogRequestWrap(nullptr, option, espContextTree.getClear(), LINK(userContext), LINK(userRequest),
  195. backEndReq, backEndResp, userResp, logDatasets);
  196. if (scriptValues)
  197. req->setScriptValuesTree(LINK(scriptValues));
  198. Owned<IEspUpdateLogResponse> resp = createUpdateLogResponse();
  199. bRet = updateLog(espContext, *req, *resp, status);
  200. }
  201. catch (IException* e)
  202. {
  203. status.set("Failed to update log: ");
  204. e->errorMessage(status);
  205. OERRLOG("%s", status.str());
  206. e->Release();
  207. }
  208. return bRet;
  209. }
  210. bool CLoggingManager::updateLog(IEspContext* espContext, IEspUpdateLogRequestWrap& req, IEspUpdateLogResponse& resp, StringBuffer& status)
  211. {
  212. bool bRet = updateLog(espContext, req, resp);
  213. if (bRet)
  214. status.set("Log request has been sent.");
  215. else
  216. {
  217. const char* statusMsg = resp.getStatusMessage();
  218. if (statusMsg && *statusMsg)
  219. status.setf("Failed to update log: %s", statusMsg);
  220. else
  221. status.set("Failed to update log");
  222. }
  223. return bRet;
  224. }
  225. bool CLoggingManager::updateLog(IEspContext* espContext, IEspUpdateLogRequestWrap& req, IEspUpdateLogResponse& resp)
  226. {
  227. if (!initialized)
  228. throw MakeStringException(-1,"LoggingManager not initialized");
  229. try
  230. {
  231. if (espContext)
  232. espContext->addTraceSummaryTimeStamp(LogMin, "LMgr:startQLog");
  233. Linked<IPropertyTree> scriptValues = req.getScriptValuesTree();
  234. if (oneTankFile || decoupledLogging)
  235. {
  236. Owned<CLogRequestInFile> reqInFile = new CLogRequestInFile();
  237. if (!saveToTankFile(req, reqInFile))
  238. throw MakeStringException(-1, "LoggingManager: failed in saveToTankFile().");
  239. //Build new log request for logging agents
  240. StringBuffer logContent, v;
  241. appendXMLOpenTag(logContent, LOGCONTENTINFILE);
  242. appendXMLTag(logContent, LOGCONTENTINFILE_FILENAME, reqInFile->getFileName());
  243. appendXMLTag(logContent, LOGCONTENTINFILE_FILEPOS, v.append(reqInFile->getPos()));
  244. appendXMLTag(logContent, LOGCONTENTINFILE_FILESIZE, v.clear().append(reqInFile->getSize()));
  245. appendXMLTag(logContent, LOGREQUEST_GUID, reqInFile->getGUID());
  246. appendXMLCloseTag(logContent, LOGCONTENTINFILE);
  247. Owned<IEspUpdateLogRequest> logRequest = new CUpdateLogRequest("", "");
  248. logRequest->setOption(reqInFile->getOption());
  249. logRequest->setLogContent(logContent);
  250. if (!decoupledLogging)
  251. {
  252. for (unsigned int x = 0; x < loggingAgentThreads.size(); x++)
  253. {
  254. IUpdateLogThread* loggingThread = loggingAgentThreads[x];
  255. if (loggingThread->hasService(LGSTUpdateLOG))
  256. {
  257. if (checkSkipThreadQueue(scriptValues, *loggingThread))
  258. continue;
  259. loggingThread->queueLog(logRequest);
  260. }
  261. }
  262. }
  263. }
  264. else
  265. {
  266. for (unsigned int x = 0; x < loggingAgentThreads.size(); x++)
  267. {
  268. IUpdateLogThread* loggingThread = loggingAgentThreads[x];
  269. if (loggingThread->hasService(LGSTUpdateLOG))
  270. {
  271. //leave the fact that a script can control the thread queue as an option undocumented, naming scheme could change,
  272. // controlling the queue is a very low level mechanism and should be frowned upon
  273. // once scripts can communicate with the agent that should be the mechanism to skip a particular type of logging
  274. if (checkSkipThreadQueue(scriptValues, *loggingThread))
  275. continue;
  276. loggingThread->queueLog(&req);
  277. }
  278. }
  279. }
  280. if (espContext)
  281. espContext->addTraceSummaryTimeStamp(LogMin, "LMgr:endQLog");
  282. }
  283. catch (IException* e)
  284. {
  285. StringBuffer errorStr;
  286. e->errorMessage(errorStr);
  287. OERRLOG("Failed to update log: %s",errorStr.str());
  288. resp.setStatusCode(-1);
  289. resp.setStatusMessage(errorStr.str());
  290. e->Release();
  291. }
  292. return true;
  293. }
  294. bool CLoggingManager::saveToTankFile(IEspUpdateLogRequestWrap& logRequest, CLogRequestInFile* reqInFile)
  295. {
  296. if (!logFailSafe.get())
  297. {
  298. ERRLOG("CLoggingManager::saveToTankFile: logFailSafe not configured.");
  299. return false;
  300. }
  301. unsigned startTime = (getEspLogLevel()>=LogNormal) ? msTick() : 0;
  302. StringBuffer GUID;
  303. logFailSafe->GenerateGUID(GUID, NULL);
  304. reqInFile->setGUID(GUID);
  305. reqInFile->setOption(logRequest.getOption());
  306. StringBuffer reqBuf;
  307. Owned<IEspUpdateLogRequestWrap> logRequestFiltered = logContentFilter.filterLogContent(&logRequest);
  308. if (!serializeLogRequestContent(logRequestFiltered, GUID, reqBuf))
  309. {
  310. ERRLOG("CLoggingManager::saveToTankFile: failed in serializeLogRequestContent().");
  311. return false;
  312. }
  313. if (decoupledLogging)
  314. {
  315. Linked<IPropertyTree> scriptValues = logRequestFiltered->getScriptValuesTree();
  316. logFailSafe->Add(GUID, scriptValues, reqBuf, reqInFile);
  317. }
  318. else
  319. {
  320. logFailSafe->AddACK(GUID);//Ack this logging request since the task will be done as soon as the next line is called.
  321. logFailSafe->Add(GUID, nullptr, reqBuf, reqInFile);
  322. }
  323. ESPLOG(LogNormal, "LThread:saveToTankFile: %dms\n", msTick() - startTime);
  324. return true;
  325. }
  326. unsigned CLoggingManager::serializeLogRequestContent(IEspUpdateLogRequestWrap* request, const char* GUID, StringBuffer& logData)
  327. {
  328. appendXMLTag(logData, LOGREQUEST_GUID, GUID);
  329. const char* option = request->getOption();
  330. if (!isEmptyString(option))
  331. appendXMLTag(logData, LOGREQUEST_OPTION, option);
  332. appendXMLOpenTag(logData, LOGREQUEST);
  333. const char* logRequest = request->getUpdateLogRequest();
  334. MemoryBuffer memBuf;
  335. LZWCompress(logRequest, strlen(logRequest), memBuf, 0x100);
  336. JBASE64_Encode(memBuf.toByteArray(), memBuf.length(), logData, true);
  337. appendXMLCloseTag(logData, LOGREQUEST);
  338. return logData.length();
  339. }
  340. bool CLoggingManager::getTransactionSeed(StringBuffer& transactionSeed, StringBuffer& status)
  341. {
  342. if (!initialized)
  343. throw MakeStringException(-1,"LoggingManager not initialized");
  344. bool bRet = false;
  345. try
  346. {
  347. Owned<IEspGetTransactionSeedRequest> req = createGetTransactionSeedRequest();
  348. Owned<IEspGetTransactionSeedResponse> resp = createGetTransactionSeedResponse();
  349. transactionSeed.set("Seed");
  350. bRet = getTransactionSeed(*req, *resp);
  351. if (bRet && !resp->getStatusCode())
  352. {
  353. const char* seed = resp->getSeedId();
  354. if (!seed || !*seed)
  355. status.set("Failed to get Transaction Seed");
  356. else
  357. {
  358. transactionSeed.set(seed);
  359. status.set("Transaction Seed returned.");
  360. bRet = true;
  361. }
  362. }
  363. else
  364. {
  365. const char* statusMsg = resp->getStatusMessage();
  366. if (statusMsg && *statusMsg)
  367. status.setf("Failed to get Transaction Seed: %s", statusMsg);
  368. else
  369. status.set("Failed to get Transaction Seed");
  370. }
  371. }
  372. catch (IException* e)
  373. {
  374. e->errorMessage(status);
  375. status.insert(0, "Failed to get Transaction Seed: ");
  376. OERRLOG("%s",status.str());
  377. e->Release();
  378. }
  379. return bRet;
  380. }
  381. bool CLoggingManager::getTransactionSeed(IEspGetTransactionSeedRequest& req, IEspGetTransactionSeedResponse& resp)
  382. {
  383. if (!initialized)
  384. throw MakeStringException(-1,"LoggingManager not initialized");
  385. bool bRet = false;
  386. try
  387. {
  388. for (unsigned int x = 0; x < loggingAgentThreads.size(); x++)
  389. {
  390. IUpdateLogThread* loggingThread = loggingAgentThreads[x];
  391. if (!loggingThread->hasService(LGSTGetTransactionSeed))
  392. continue;
  393. IEspLogAgent* loggingAgent = loggingThread->getLogAgent();
  394. bRet = loggingAgent->getTransactionSeed(req, resp);
  395. if (bRet)
  396. break;
  397. }
  398. }
  399. catch (IException* e)
  400. {
  401. StringBuffer errorStr;
  402. e->errorMessage(errorStr);
  403. OERRLOG("Failed to get Transaction Seed: %s",errorStr.str());
  404. resp.setStatusCode(-1);
  405. resp.setStatusMessage(errorStr.str());
  406. e->Release();
  407. }
  408. return bRet;
  409. }
  410. bool CLoggingManager::getTransactionID(StringAttrMapping* transFields, StringBuffer& transactionID, StringBuffer& status)
  411. {
  412. if (!initialized)
  413. throw MakeStringException(-1,"LoggingManager not initialized");
  414. try
  415. {
  416. for (unsigned int x = 0; x < loggingAgentThreads.size(); x++)
  417. {
  418. IUpdateLogThread* loggingThread = loggingAgentThreads[x];
  419. if (!loggingThread->hasService(LGSTGetTransactionID))
  420. continue;
  421. IEspLogAgent* loggingAgent = loggingThread->getLogAgent();
  422. loggingAgent->getTransactionID(transFields, transactionID);
  423. if (!transactionID.isEmpty())
  424. ESPLOG(LogMax, "Got TransactionID '%s'", transactionID.str());
  425. return true;
  426. }
  427. }
  428. catch (IException* e)
  429. {
  430. e->errorMessage(status);
  431. e->Release();
  432. }
  433. return false;
  434. }
  435. extern "C"
  436. {
  437. LOGGINGMANAGER_API ILoggingManager* newLoggingManager()
  438. {
  439. return new CLoggingManager();
  440. }
  441. }