loggingagentbase.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. /*##############################################################################
  2. HPCC SYSTEMS software Copyright (C) 2016 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 "esploggingservice_esp.ipp"
  15. #include "loggingagentbase.hpp"
  16. static const char* const defaultTransactionTable = "transactions";
  17. static const char* const defaultTransactionAppName = "accounting_log";
  18. static const char* const defaultLoggingTransactionAppName = "logging_transaction";
  19. void CDBLogAgentBase::readDBCfg(IPropertyTree* cfg, StringBuffer& server, StringBuffer& dbUser, StringBuffer& dbPassword)
  20. {
  21. ensureInputString(cfg->queryProp("@server"), true, server, -1, "Database server required");
  22. ensureInputString(cfg->queryProp("@dbName"), true, defaultDB, -1, "Database name required");
  23. transactionTable.set(cfg->hasProp("@dbTableName") ? cfg->queryProp("@dbTableName") : defaultTransactionTable);
  24. dbUser.set(cfg->queryProp("@dbUser"));
  25. const char* encodedPassword = cfg->queryProp("@dbPassWord");
  26. if(encodedPassword && *encodedPassword)
  27. decrypt(dbPassword, encodedPassword);
  28. }
  29. void CDBLogAgentBase::readTransactionCfg(IPropertyTree* cfg)
  30. {
  31. //defaultTransactionApp: if no APP name is given, which APP name (TableName) should be used to get a transaction seed?
  32. //loggingTransactionApp: the TableName used to get a transaction seed for this logging agent
  33. defaultTransactionApp.set(cfg->hasProp("defaultTransaction") ? cfg->queryProp("defaultTransaction") : defaultTransactionAppName);
  34. loggingTransactionApp.set(cfg->hasProp("loggingTransaction") ? cfg->queryProp("loggingTransaction") : defaultLoggingTransactionAppName);
  35. loggingTransactionCount = 0;
  36. }
  37. bool CDBLogAgentBase::getTransactionSeed(IEspGetTransactionSeedRequest& req, IEspGetTransactionSeedResponse& resp)
  38. {
  39. bool bRet = false;
  40. StringBuffer appName = req.getApplication();
  41. appName.trim();
  42. if (appName.length() == 0)
  43. appName = defaultTransactionApp.get();
  44. unsigned retry = 1;
  45. while (1)
  46. {
  47. try
  48. {
  49. StringBuffer logSeed;
  50. queryTransactionSeed(appName, logSeed);
  51. if (!logSeed.length())
  52. throw MakeStringException(EspLoggingErrors::GetTransactionSeedFailed, "Failed to get TransactionSeed");
  53. resp.setSeedId(logSeed.str());
  54. resp.setStatusCode(0);
  55. bRet = true;
  56. break;
  57. }
  58. catch (IException* e)
  59. {
  60. StringBuffer errorStr, errorMessage;
  61. errorMessage.append("Failed to get TransactionSeed: error code ").append(e->errorCode()).append(", error message ").append(e->errorMessage(errorStr));
  62. ERRLOG("%s -- try %d", errorMessage.str(), retry);
  63. e->Release();
  64. if (retry < maxTriesGTS)
  65. {
  66. Sleep(retry*3000);
  67. retry++;
  68. }
  69. else
  70. {
  71. resp.setStatusCode(-1);
  72. resp.setStatusMessage(errorMessage.str());
  73. break;
  74. }
  75. }
  76. }
  77. return bRet;
  78. }
  79. bool CDBLogAgentBase::updateLog(IEspUpdateLogRequestWrap& req, IEspUpdateLogResponse& resp)
  80. {
  81. unsigned startTime = (getEspLogLevel()>=LogNormal) ? msTick() : 0;
  82. bool ret = false;
  83. try
  84. {
  85. const char* updateLogReq = req.getUpdateLogRequest();
  86. if (!updateLogReq || !*updateLogReq)
  87. throw MakeStringException(EspLoggingErrors::UpdateLogFailed, "Failed to read log request.");
  88. StringBuffer requestBuf, logDB, logSource;
  89. requestBuf.append("<LogRequest>").append(updateLogReq).append("</LogRequest>");
  90. Owned<IPropertyTree> logRequestTree = createPTreeFromXMLString(requestBuf.length(), requestBuf.str());
  91. if (!logRequestTree)
  92. throw MakeStringException(EspLoggingErrors::UpdateLogFailed, "Failed to read log request.");
  93. CLogGroup* logGroup = checkLogSource(logRequestTree, logSource, logDB);
  94. if (!logGroup)
  95. throw MakeStringException(EspLoggingErrors::UpdateLogFailed, "Log Group %s undefined.", logSource.str());
  96. StringBuffer logID;
  97. getLoggingTransactionID(logID);
  98. CIArrayOf<CLogTable>& logTables = logGroup->getLogTables();
  99. ForEachItemIn(i, logTables)
  100. {
  101. CLogTable& table = logTables.item(i);
  102. StringBuffer updateDBStatement;
  103. if(!buildUpdateLogStatement(logRequestTree, logDB.str(), table, logID, updateDBStatement))
  104. throw MakeStringException(EspLoggingErrors::UpdateLogFailed, "Failed in creating SQL statement.");
  105. ESPLOG(LogNormal, "LAgent UpdateLog BuildStat %d done: %dms\n", i, msTick() - startTime);
  106. ESPLOG(LogMax, "UpdateLog: %s\n", updateDBStatement.str());
  107. executeUpdateLogStatement(updateDBStatement);
  108. ESPLOG(LogNormal, "LAgent UpdateLog ExecStat %d done: %dms\n", i, msTick() - startTime);
  109. }
  110. resp.setStatusCode(0);
  111. ret = true;
  112. }
  113. catch (IException* e)
  114. {
  115. StringBuffer errorStr, errorMessage;
  116. errorMessage.append("Failed to update log: error code ").append(e->errorCode()).append(", error message ").append(e->errorMessage(errorStr));
  117. ERRLOG("%s", errorMessage.str());
  118. e->Release();
  119. resp.setStatusCode(-1);
  120. resp.setStatusMessage(errorMessage.str());
  121. }
  122. ESPLOG(LogNormal, "LAgent UpdateLog total=%dms\n", msTick() - startTime);
  123. return ret;
  124. }
  125. CLogGroup* CDBLogAgentBase::checkLogSource(IPropertyTree* logRequest, StringBuffer& source, StringBuffer& logDB)
  126. {
  127. if (logSourceCount == 0)
  128. {//if no log source is configured, use default Log Group and DB
  129. logDB.set(defaultDB.str());
  130. source.set(defaultLogGroup.get());
  131. return logGroups.getValue(defaultLogGroup.get());
  132. }
  133. source = logRequest->queryProp(logSourcePath.get());
  134. if (source.isEmpty())
  135. throw MakeStringException(EspLoggingErrors::UpdateLogFailed, "Failed to read log Source from request.");
  136. CLogSource* logSource = logSources.getValue(source.str());
  137. if (!logSource)
  138. throw MakeStringException(EspLoggingErrors::UpdateLogFailed, "Log Source %s undefined.", source.str());
  139. logDB.set(logSource->getDBName());
  140. return logGroups.getValue(logSource->getGroupName());
  141. }
  142. void CDBLogAgentBase::getLoggingTransactionID(StringBuffer& id)
  143. {
  144. id.set(loggingTransactionSeed.str()).append("-").append(++loggingTransactionCount);
  145. }
  146. bool CDBLogAgentBase::buildUpdateLogStatement(IPropertyTree* logRequest, const char* logDB,
  147. CLogTable& table, StringBuffer& logID, StringBuffer& updateDBStatement)
  148. {
  149. StringBuffer fields, values;
  150. BoolHash handledFields;
  151. CIArrayOf<CLogField>& logFields = table.getLogFields();
  152. ForEachItemIn(i, logFields) //Go through data items to be logged
  153. {
  154. CLogField& logField = logFields.item(i);
  155. StringBuffer colName = logField.getMapTo();
  156. bool* found = handledFields.getValue(colName.str());
  157. if (found && *found)
  158. continue;
  159. StringBuffer path = logField.getName();
  160. if (path.charAt(path.length() - 1) == ']')
  161. {//Attr filter. Separate the last [] from the path.
  162. const char* pTr = path.str();
  163. const char* ppTr = strrchr(pTr, '[');
  164. if (!ppTr)
  165. continue;
  166. StringBuffer attr;
  167. attr.set(ppTr+1);
  168. attr.setLength(attr.length() - 1);
  169. path.setLength(ppTr - pTr);
  170. StringBuffer colValue;
  171. Owned<IPropertyTreeIterator> itr = logRequest->getElements(path.str());
  172. ForEach(*itr)
  173. {//Log the first valid match just in case more than one matches.
  174. IPropertyTree& ppTree = itr->query();
  175. colValue.set(ppTree.queryProp(attr.str()));
  176. if (colValue.length())
  177. {
  178. addField(logField, colName.str(), colValue, fields, values);
  179. handledFields.setValue(colName.str(), true);
  180. break;
  181. }
  182. }
  183. continue;
  184. }
  185. Owned<IPropertyTreeIterator> itr = logRequest->getElements(path.str());
  186. ForEach(*itr)
  187. {
  188. IPropertyTree& ppTree = itr->query();
  189. StringBuffer colValue;
  190. if (ppTree.hasChildren()) //This is a tree branch.
  191. toXML(&ppTree, colValue);
  192. else
  193. ppTree.getProp(NULL, colValue);
  194. if (colValue.length())
  195. {
  196. addField(logField, colName.str(), colValue, fields, values);
  197. handledFields.setValue(colName.str(), true);
  198. break;
  199. }
  200. }
  201. }
  202. //add any default fields that may be required but not in request.
  203. addMissingFields(logFields, handledFields, fields, values);
  204. appendFieldInfo("log_id", logID, fields, values, true);
  205. setUpdateLogStatement(logDB, table.getTableName(), fields.str(), values.str(), updateDBStatement);
  206. return true;
  207. }
  208. void CDBLogAgentBase::appendFieldInfo(const char* field, StringBuffer& value, StringBuffer& fields, StringBuffer& values, bool quoted)
  209. {
  210. if(values.length() != 0)
  211. values.append(',');
  212. if (quoted)
  213. values.append('\'').append(value.length(), value.str()).append('\'');
  214. else
  215. values.append(value.length(), value.str());
  216. if(fields.length() != 0)
  217. fields.append(',');
  218. fields.append(field);
  219. }
  220. void CDBLogAgentBase::addMissingFields(CIArrayOf<CLogField>& logFields, BoolHash& handledFields, StringBuffer& fields, StringBuffer& values)
  221. {
  222. ForEachItemIn(i, logFields) //Go through data items to be logged
  223. {
  224. CLogField& logField = logFields.item(i);
  225. const char* colName = logField.getMapTo();
  226. bool* found = handledFields.getValue(colName);
  227. if (found && *found)
  228. continue;
  229. StringBuffer value = logField.getDefault();
  230. if (!value.isEmpty())
  231. addField(logField, colName, value, fields, values);
  232. }
  233. }
  234. void CDBLogAgentBase::getTransactionID(StringAttrMapping* transFields, StringBuffer& transactionID)
  235. {
  236. //Not implemented
  237. }
  238. void CDBLogAgentBase::filterLogContent(IEspUpdateLogRequestWrap* req)
  239. {
  240. //No filter in CDBSQLLogAgent
  241. }