datalogger.cpp 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405
  1. #include <string.h>
  2. #include <cmath>
  3. #include <malloc.h>
  4. #include <limits.h>
  5. #include <signal.h>
  6. #include <sys/stat.h>
  7. #include "fileutil.h"
  8. #include "strutil.h"
  9. #include "datalogger.h"
  10. #include "processclock.h"
  11. #include "debug.h"
  12. /////////////////////////////////////////////////////////////////////////////
  13. #define _USE_MODIFIED_INDEX 1
  14. #define _TRACK_TIME 1
  15. #define _FILE_SIZE_DELETE_MARGIN_PERCENT 10
  16. #define _SIZE_GUARD_TIMESTAMP_FILE_NAME "sguard.ts"
  17. #define _INVALID_TIMESTAMP_VALUE ((time_t)-1)
  18. /////////////////////////////////////////////////////////////////////////////
  19. inline static bool _IsLoggable(double d)
  20. {
  21. int c = std::fpclassify(d);
  22. return (c == FP_NORMAL) || (c == FP_ZERO);
  23. }
  24. /////////////////////////////////////////////////////////////////////////////
  25. CDataLogger::CDataLogger(LPCDLPARAMS pdlp, CLogfile &rlf) : m_lf(rlf),
  26. m_tidSGThread(0),
  27. m_bSGHasSizeLimitPrerequisites(false),
  28. m_bSGInProgress(false),
  29. m_bSGConfigured(false),
  30. m_nSGCurPassUTC(0),
  31. m_nSGLastPassUTC(0),
  32. m_condmtx1(PTHREAD_MUTEX_INITIALIZER),
  33. m_cond1(PTHREAD_COND_INITIALIZER),
  34. m_nLastLogTimestamp(0),
  35. m_bBadDateLogsDetected(false)
  36. {
  37. memset(&m_dlp, 0, sizeof(m_dlp));
  38. memset(&m_gv, 0, sizeof(m_gv));
  39. memset(&m_mtx, 0, sizeof(m_mtx));
  40. memset(&m_mutexAttr, 0, sizeof(m_mutexAttr));
  41. if(pdlp)
  42. memcpy(&m_dlp, pdlp, sizeof(m_dlp));
  43. if(!(m_bSGConfigured = !!m_dlp.nMaxSize || !!m_dlp.nMaxAge))
  44. m_lf.Error("Size guard not configured.\n");
  45. if(m_dlp.pszBaseDir)
  46. strncpy(m_szAppDir, m_dlp.pszBaseDir, sizeof(m_szAppDir) - 1);
  47. else
  48. ::GetAppDirectory(m_szAppDir, sizeof(m_szAppDir));
  49. ::pthread_mutexattr_init(&m_mutexAttr);
  50. ::pthread_mutexattr_settype(&m_mutexAttr, PTHREAD_MUTEX_RECURSIVE);
  51. ::pthread_mutex_init(&m_mtx, &m_mutexAttr);
  52. }
  53. /////////////////////////////////////////////////////////////////////////////
  54. CDataLogger::~CDataLogger(void)
  55. {
  56. Release();
  57. ::pthread_mutex_destroy(&m_mtx);
  58. ::pthread_mutexattr_destroy(&m_mutexAttr);
  59. ::pthread_cond_destroy(&m_cond1);
  60. }
  61. /////////////////////////////////////////////////////////////////////////////
  62. void CDataLogger::Release(void)
  63. {
  64. if(m_tidSGThread)
  65. {
  66. ::pthread_mutex_lock(&m_condmtx1);
  67. bool bSgInProg = m_bSGInProgress;
  68. ::pthread_mutex_unlock(&m_condmtx1);
  69. if(bSgInProg)
  70. CLogfile::StdErr("\nDatalogger is terminating. This may take some time ...\nPlease wait, before powering off the device!\n");
  71. Lock();
  72. m_lf.Lock();
  73. ::pthread_cancel(m_tidSGThread);
  74. m_lf.Unlock();
  75. Unlock();
  76. ::pthread_join(m_tidSGThread, NULL);
  77. m_tidSGThread = 0;
  78. }
  79. }
  80. /////////////////////////////////////////////////////////////////////////////
  81. unsigned long CDataLogger::GetTagID(const char *pszVarPath, int nDataType, int nLogType)
  82. {
  83. CMySqlDB db;
  84. const char *pszID = NULL, *pszDataType = NULL, *pszLogType = 0;
  85. char *pszEndptr;
  86. unsigned long nID = ULONG_MAX;
  87. int nDT, nLT;
  88. std::string sSql;
  89. // sSql = formatString("select `tagid` from `%s` where `path` = '%s' and `dataType` = %d and `logType` = %d", m_dlp.szTagsTable, pszVarPath, nDataType, nLogType);
  90. sSql = formatString("select `tagid`, `dataType`+0, `logType`+0 from `%s` where `path` = '%s'", m_dlp.szTagsTable, pszVarPath);
  91. if(!db.Connect("localhost", m_dlp.szDBUser, m_dlp.szDBPass, m_dlp.szDBName))
  92. {
  93. m_lf.Error("CDataLogger::GetTagID: DB Error: %s\n", db.LastError().c_str());
  94. return nID;
  95. }
  96. CMySqlResult res = db.Query(sSql.c_str());
  97. bool bError = res.error();
  98. if(bError)
  99. m_lf.Error("CDataLogger::GetTagID: DB Error: %s\n", db.LastError().c_str());
  100. else
  101. {
  102. my_ulonglong nCount = res.RowCount();
  103. if(nCount > 0)
  104. {
  105. MYSQL_ROW pRow = res.FetchRow();
  106. pszID = pRow[0];
  107. pszDataType = pRow[1];
  108. pszLogType = pRow[2];
  109. nID = strtoul(pszID, &pszEndptr, 10);
  110. nDT = strtol(pszDataType, &pszEndptr, 10);
  111. nLT = strtol(pszLogType, &pszEndptr, 10);
  112. if((nDT != nDataType) || (nLT != nLogType))
  113. {
  114. sSql = formatString("update `%s` set `dataType` = %d, `logType` = %d where `tagid` = %u", m_dlp.szTagsTable, nDataType, nLogType, nID);
  115. // TRACE("%s\n", sSql.c_str());
  116. res = db.Query(sSql.c_str());
  117. bError = res.error();
  118. if(bError)
  119. m_lf.Error("Error updating Tags-Table: %s\n", db.LastError().c_str());
  120. }
  121. }
  122. else
  123. {
  124. sSql = formatString("insert into `%s` (`dataType`, `logType`, `path`) values(%d, %d, '%s')", m_dlp.szTagsTable, nDataType, nLogType, pszVarPath);
  125. res = db.Query(sSql.c_str());
  126. bError = res.error();
  127. if(bError)
  128. m_lf.Error("DB Error: %s\n", db.LastError().c_str());
  129. else
  130. {
  131. sSql = formatString("select `tagid` from `%s` where `path`='%s'", m_dlp.szTagsTable, pszVarPath);
  132. CMySqlResult res = db.Query(sSql.c_str());
  133. bool bError = res.error();
  134. if(bError)
  135. m_lf.Error("DB Error: %s\n", db.LastError().c_str());
  136. else if(res.RowCount() > 0)
  137. {
  138. MYSQL_ROW pRow = res.FetchRow();
  139. pszID = pRow[0];
  140. nID = strtoul(pszID, &pszEndptr, 10);
  141. }
  142. }
  143. }
  144. }
  145. return nID;
  146. }
  147. /////////////////////////////////////////////////////////////////////////////
  148. bool CDataLogger::TableFileExists(const char *pszTableName)
  149. {
  150. char szDataFile[PATH_MAX];
  151. sprintf(szDataFile, "%s%s/%s.ibd", m_gv.szDataDir, m_dlp.szDBName, pszTableName);
  152. return !!FileExist(szDataFile);
  153. }
  154. /////////////////////////////////////////////////////////////////////////////
  155. int64_t CDataLogger::TableFileSize(const char *pszTableName)
  156. {
  157. struct stat statbuf;
  158. char szDataFile[PATH_MAX];
  159. sprintf(szDataFile, "%s%s/%s.ibd", m_gv.szDataDir, m_dlp.szDBName, pszTableName);
  160. if(stat(szDataFile, &statbuf) == -1)
  161. return 0;
  162. return (int64_t)statbuf.st_size;
  163. }
  164. /////////////////////////////////////////////////////////////////////////////
  165. bool CDataLogger::QueryServerVariable(CMySqlDB &rdb, const char *pszVarname, CMySqlVar &val)
  166. {
  167. if(!pszVarname || !*pszVarname)
  168. {
  169. m_lf.Error("CDataLogger::QueryServerVariable: No Variable name!\n");
  170. return false;
  171. }
  172. bool bError;
  173. std::string sSql;
  174. sSql = formatString("select @@%s;", pszVarname);
  175. CMySqlResult res = rdb.Query(sSql.c_str());
  176. bError = res.error();
  177. if(!bError)
  178. {
  179. bError = true;
  180. do
  181. {
  182. my_ulonglong nRowCount = res.RowCount();
  183. unsigned int nFldCount = res.FieldCount();
  184. const MYSQL_FIELD *pFields = res.FetchFields();
  185. if(nRowCount != 1 || nFldCount != 1 || !pFields)
  186. break;
  187. MYSQL_ROW pRow = res.FetchRow();
  188. if(!pRow || !*pRow || !**pRow)
  189. break;
  190. bError = !val.FromField(pFields[0], pRow[0]);
  191. }
  192. while(false);
  193. }
  194. return !bError;
  195. }
  196. /////////////////////////////////////////////////////////////////////////////
  197. #if 0
  198. bool CDataLogger::QueryStatusVariable(CMySqlDB &rdb, const char *pszVarname, CMySqlVar &val)
  199. {
  200. if(!pszVarname || !*pszVarname)
  201. {
  202. m_lf.Error("CDataLogger::QueryStatusVariable: No Variable name!\n");
  203. return false;
  204. }
  205. bool bError;
  206. std::string sSql;
  207. sSql = formatString("show session status like '%s'", pszVarname);
  208. CMySqlResult res = rdb.Query(sSql.c_str());
  209. bError = res.error();
  210. if(!bError)
  211. {
  212. bError = true;
  213. do
  214. {
  215. my_ulonglong nRowCount = res.RowCount();
  216. unsigned int nFldCount = res.FieldCount();
  217. const MYSQL_FIELD *pFields = res.FetchFields();
  218. if(nRowCount != 1 || nFldCount != 2 || !pFields)
  219. break;
  220. MYSQL_ROW pRow = res.FetchRow();
  221. if(!pRow || !pRow[1] || !*pRow[1])
  222. break;
  223. bError = !val.FromField(pFields[1], pRow[1]);
  224. }
  225. while(false);
  226. }
  227. return !bError;
  228. }
  229. #endif
  230. /////////////////////////////////////////////////////////////////////////////
  231. bool CDataLogger::ReadGlobalOptions(CMySqlDB &rdb)
  232. {
  233. CMySqlVar val;
  234. memset(&m_gv, 0, sizeof(m_gv));
  235. if(QueryServerVariable(rdb, "datadir", val))
  236. {
  237. memset(m_gv.szDataDir, 0, sizeof(m_gv.szDataDir));
  238. if(!val.IsNull())
  239. val.CopyStrVal(m_gv.szDataDir, sizeof(m_gv.szDataDir) - 1, 0);
  240. }
  241. if(QueryServerVariable(rdb, "innodb_file_per_table", val))
  242. {
  243. if(!val.IsNull())
  244. m_gv.bInnoDbFilePerTable = val;
  245. }
  246. if(QueryServerVariable(rdb, "innodb_strict_mode", val))
  247. {
  248. if(!val.IsNull())
  249. m_gv.bInnoDbIsStrictMode = val;
  250. }
  251. if(QueryServerVariable(rdb, "innodb_file_format", val))
  252. {
  253. memset(m_gv.szInnoDbFileFormat, 0, sizeof(m_gv.szInnoDbFileFormat));
  254. if(!val.IsNull())
  255. {
  256. val.CopyStrVal(m_gv.szInnoDbFileFormat, sizeof(m_gv.szInnoDbFileFormat) - 1, 0);
  257. m_gv.bInnoDbIsBarracuda = !strcasecmp(m_gv.szInnoDbFileFormat, "barracuda");
  258. }
  259. }
  260. return true;
  261. }
  262. /////////////////////////////////////////////////////////////////////////////
  263. void CDataLogger::SizeGuardTrigger(time_t ts)
  264. {
  265. if(m_bSGConfigured && m_tidSGThread)
  266. {
  267. ::pthread_mutex_lock(&m_condmtx1);
  268. if( !m_bSGInProgress &&
  269. !SizeGuardDayWorkDone(ts))
  270. {
  271. unsigned long long nMnUTC = (unsigned long long)_MIDNIGHT_TIMESTAMP_UTC(ts);
  272. if(SizeGuardLastPassRead() != nMnUTC)
  273. {
  274. m_nSGCurPassUTC = ts;
  275. ::pthread_cond_signal(&m_cond1);
  276. }
  277. else
  278. m_nSGLastPassUTC = nMnUTC;
  279. }
  280. ::pthread_mutex_unlock(&m_condmtx1);
  281. }
  282. }
  283. /////////////////////////////////////////////////////////////////////////////
  284. #if 0
  285. bool CDataLogger::QueryTableSizes(CMySqlDB &rdb, const char *pszTableName)
  286. {
  287. bool bError;
  288. char *pszEndptr;
  289. MYSQL_ROW pRow;
  290. uint64_t nDataLength = 0, nDataFree = 0, nIndexLength = 0, nFreeExtents, nTotalExtents;
  291. std::string sSql;
  292. sSql = formatString("select `DATA_LENGTH`, `INDEX_LENGTH`, `DATA_FREE` from `information_schema`.`TABLES` where (`TABLE_SCHEMA` = '%s') AND (`TABLE_NAME` = '%s');", m_dlp.szDBName, pszTableName);
  293. CMySqlResult res = rdb.Query(sSql.c_str());
  294. bError = res.error();
  295. if(bError)
  296. {
  297. m_lf.Error("CDataLogger::QueryTableSizes: DB Error: %s\n", rdb.LastError().c_str());
  298. return false;
  299. }
  300. pRow = res.FetchRow();
  301. nDataLength = strtoull(pRow[0], &pszEndptr, 10);
  302. nIndexLength = strtoull(pRow[1], &pszEndptr, 10);
  303. nDataFree = strtoull(pRow[2], &pszEndptr, 10);
  304. //////////////////////////////////////////////////////////////////////////////////////////////
  305. sSql = formatString("select `FREE_EXTENTS`, `TOTAL_EXTENTS`, `DATA_FREE` from `information_schema`.`FILES` where `FILE_NAME` like '%%demo/%s.ibd';", pszTableName);
  306. CMySqlResult res2 = rdb.Query(sSql.c_str());
  307. bError = res2.error();
  308. if(bError)
  309. {
  310. m_lf.Error("CDataLogger::QueryTableSizes: DB Error: %s\n", rdb.LastError().c_str());
  311. return false;
  312. }
  313. pRow = res2.FetchRow();
  314. nFreeExtents = strtoull(pRow[0], &pszEndptr, 10);
  315. nTotalExtents = strtoull(pRow[1], &pszEndptr, 10);
  316. int64_t nFileSize = TableFileSize(pszTableName);
  317. m_lf.Info("Data length: %ju, Data free: %ju, Total extents: %ju, Free extents: %ju, File size: %ju.\n", nDataLength + nIndexLength, nDataFree, nTotalExtents, nFreeExtents, nFileSize);
  318. TRACE("Data length: %ju, Data free: %ju, Total extents: %ju, Free extents: %ju, File size: %ju.\n", nDataLength + nIndexLength, nDataFree, nTotalExtents, nFreeExtents, nFileSize);
  319. return true;
  320. }
  321. #endif
  322. /////////////////////////////////////////////////////////////////////////////
  323. bool CDataLogger::CheckTable(CMySqlDB &rdb, const char *pszTableName, bool &bExists, bool &bUseResortTable, bool &bIsInnoDB)
  324. {
  325. bool bError;
  326. std::string sSql;
  327. const char *pszEngine = NULL;
  328. uint64_t nDataLength = 0, nIndexLength = 0;
  329. int64_t nFileSize = -1;
  330. bExists = bUseResortTable = false;
  331. bIsInnoDB = false;
  332. sSql = formatString("select `ENGINE`, `DATA_LENGTH`, `INDEX_LENGTH` from `information_schema`.`TABLES` where (`TABLE_SCHEMA` = '%s') AND (`TABLE_NAME` = '%s')", m_dlp.szDBName, pszTableName);
  333. CMySqlResult res1 = rdb.Query(sSql.c_str());
  334. bError = res1.error();
  335. if(bError)
  336. {
  337. m_lf.Error("CDataLogger::CheckTables: DB Error: %s\n", rdb.LastError().c_str());
  338. return false;
  339. }
  340. else
  341. {
  342. my_ulonglong nCount = res1.RowCount();
  343. if(nCount > 0)
  344. {
  345. MYSQL_ROW pRow = res1.FetchRow();
  346. unsigned int nFc = res1.FieldCount();
  347. const MYSQL_FIELD *pFields = res1.FetchFields();
  348. CMySqlVar vals[3];
  349. bExists = true;
  350. for(unsigned int i = 0; i < nFc; i++)
  351. {
  352. vals[i].FromField(pFields[i], pRow[i]);
  353. if(!vals[i].FieldnameCmp("ENGINE"))
  354. {
  355. pszEngine = vals[i].StrVal();
  356. bIsInnoDB = !strcasecmp(pszEngine, "InnoDB");
  357. }
  358. else if(!vals[i].FieldnameCmp("DATA_LENGTH"))
  359. nDataLength = (uint64_t)vals[i];
  360. else if(!vals[i].FieldnameCmp("INDEX_LENGTH"))
  361. nIndexLength = (uint64_t)vals[i];
  362. }
  363. if(bIsInnoDB && m_gv.bInnoDbFilePerTable)
  364. {
  365. if(!TableFileExists(pszTableName))
  366. m_lf.Warning("'innodb_file_per_table' configured, but table '%s' does not have a data file!\n", pszTableName);
  367. else
  368. nFileSize = TableFileSize(pszTableName);
  369. }
  370. if(nFileSize >= 0)
  371. m_lf.Info("Found info on table '%s': Engine: '%s', Data size: %s, Index size: %s, File size: %s\n", pszTableName, pszEngine ? pszEngine : "unknown", strFormatByteSize(nDataLength, 1).c_str(), strFormatByteSize(nIndexLength, 1).c_str(), strFormatByteSize(nFileSize, 1).c_str());
  372. else
  373. m_lf.Info("Found info on table '%s': Engine: '%s', Data size: %s, Index size: %s\n", pszTableName, pszEngine ? pszEngine : "unknown", strFormatByteSize(nDataLength, 1).c_str(), strFormatByteSize(nIndexLength, 1).c_str());
  374. if(!pszEngine)
  375. m_lf.Warning("Failed to determine the Database engine of Table '%s'!\n", pszTableName);
  376. else if(strcmp(pszEngine, _DL_DATABSE_ENGINE_NAME))
  377. m_lf.Warning("Current Database engine of Table '%s' is '%s'! Please consider to migrate to '%s'!\n", pszTableName, pszEngine, _DL_DATABSE_ENGINE_NAME);
  378. sSql = formatString("select * from `%s` limit 0, 10", pszTableName);
  379. CMySqlResult res2 = rdb.Query(sSql.c_str()); // try to query table
  380. if(res2.error()) // if the query results in an error, the table may be corrupt!
  381. {
  382. char szTblName[256];
  383. m_lf.Error("Failed to query table '%s': %s\n", pszTableName, rdb.LastError().c_str());
  384. // if the table is corrupt, try to rename it and create a new instane of the original table.
  385. sprintf(szTblName, "%s_corrupt_%08zX", pszTableName, (size_t)time(NULL));
  386. sSql = formatString("rename table `%s` to `%s`", pszTableName, szTblName);
  387. CMySqlResult res3 = rdb.Query(sSql.c_str()); // try to rename the corrupt table
  388. if(res3.error())
  389. {
  390. // if the renaming fails, try to create a new working table with a different name
  391. m_lf.Error("Failed to rename table '%s': %s\n", pszTableName, rdb.LastError().c_str());
  392. bExists = false;
  393. bUseResortTable = true;
  394. }
  395. else
  396. {
  397. m_lf.Warning("Renamed table '%s' to '%s'\n", pszTableName, szTblName);
  398. bExists = false;
  399. }
  400. }
  401. }
  402. }
  403. return !bError;
  404. }
  405. /////////////////////////////////////////////////////////////////////////////
  406. bool CDataLogger::InitDatabase(bool bEnforceCreate)
  407. {
  408. CMySqlDB db;
  409. time_t nMaxLogTimestamp = m_nLastLogTimestamp = 0;
  410. bool bExists, bUseResortTable, bDummy;
  411. m_lf.Info("Connecting to Database server @ 'localhost'.\n");
  412. if(!db.Connect("localhost", m_dlp.szDBUser, m_dlp.szDBPass, NULL))
  413. {
  414. m_lf.Error("CDataLogger::InitDatabase: DB Error: %s\n", db.LastError().c_str());
  415. return false;
  416. }
  417. m_lf.Info("Success!\n");
  418. if(!ReadGlobalOptions(db))
  419. return false;
  420. if(!m_gv.bInnoDbIsBarracuda || !m_gv.bInnoDbFilePerTable || !m_gv.bInnoDbIsStrictMode)
  421. m_lf.Warning("InnoDB file format: '%s', InnoDB table space: '%s', InnoDB strict mode: %s.\n", m_gv.szInnoDbFileFormat, m_gv.bInnoDbFilePerTable ? "File per table" : "System", m_gv.bInnoDbIsStrictMode ? "yes" : "no");
  422. else
  423. m_lf.Info("InnoDB file format: '%s', InnoDB table space: '%s', InnoDB strict mode: %s.\n", m_gv.szInnoDbFileFormat, m_gv.bInnoDbFilePerTable ? "File per table" : "System", m_gv.bInnoDbIsStrictMode ? "yes" : "no");
  424. if(!CreateDatabase(db, bEnforceCreate))
  425. return false;
  426. m_lf.Info("Opening Database '%s'.\n", m_dlp.szDBName);
  427. if(db.SelectDB(m_dlp.szDBName))
  428. {
  429. m_lf.Error("CDataLogger::InitDatabase: DB Error: %s\n", db.LastError().c_str());
  430. return false;
  431. }
  432. m_lf.Info("Success!\n");
  433. if(!CheckTable(db, m_dlp.szTagsTable, bExists, bUseResortTable, bDummy))
  434. return false;
  435. if(!bExists)
  436. {
  437. if(bUseResortTable)
  438. {
  439. char szOrigTable[_DL_MAX_TABLE_NAME_LENGTH];
  440. memcpy(szOrigTable, m_dlp.szTagsTable, sizeof(szOrigTable));
  441. sprintf(m_dlp.szTagsTable, "%s_resort_%08zX", szOrigTable, (size_t)time(NULL));
  442. m_lf.Warning("Resorting to work-around table '%s'.\n", m_dlp.szTagsTable);
  443. }
  444. if(!CreateTagsTable(db))
  445. return false;
  446. }
  447. if(!AlterTagsTable(db)) // 23.10.2020, extend logtype enum if not up to date
  448. return false;
  449. if(!CheckTable(db, m_dlp.szLogsTable, bExists, bUseResortTable, m_gv.bLogsTblIsInnoDB))
  450. return false;
  451. if(!bExists)
  452. {
  453. if(bUseResortTable)
  454. {
  455. char szOrigTable[_DL_MAX_TABLE_NAME_LENGTH];
  456. memcpy(szOrigTable, m_dlp.szLogsTable, sizeof(szOrigTable));
  457. sprintf(m_dlp.szLogsTable, "%s_resort_%08zX", szOrigTable, (size_t)time(NULL));
  458. m_lf.Warning("Resorting to work-around table '%s'.\n", m_dlp.szLogsTable);
  459. }
  460. if(!CreateLogsTable(db))
  461. return false;
  462. #if _DL_DATABSE_ENGINE == _DL_DATABASE_ENGINE_INNODB
  463. m_gv.bLogsTblIsInnoDB = true;
  464. #endif // _DL_DATABSE_ENGINE == _DL_DATABASE_ENGINE_INNODB
  465. }
  466. if(m_bSGConfigured)
  467. {
  468. if(!(m_bSGHasSizeLimitPrerequisites = m_gv.bLogsTblIsInnoDB && m_gv.bInnoDbFilePerTable && TableFileExists(m_dlp.szLogsTable)))
  469. {
  470. m_lf.Warning("SG: Database configuration: InnoDB: %s, File-per-table tablespace: %s\n", m_gv.bLogsTblIsInnoDB ? "yes" : "no", m_gv.bInnoDbFilePerTable ? "yes" : "no");
  471. m_lf.Warning("SG: The current database configuration does not support monitoring of size limits. Size guard will operate on age limits only!\n");
  472. }
  473. ::pthread_mutex_lock(&m_condmtx1);
  474. if(::pthread_create(&m_tidSGThread, NULL, &CDataLogger::SizeGuardWorker, reinterpret_cast<void*>(this)))
  475. {
  476. m_tidSGThread = 0;
  477. m_lf.Error("SG: Failed to start size monitoring thread!\n");
  478. ::pthread_mutex_unlock(&m_condmtx1);
  479. return false;
  480. }
  481. ::pthread_cond_wait(&m_cond1, &m_condmtx1);
  482. ::pthread_mutex_unlock(&m_condmtx1);
  483. }
  484. if(!CreateLogsBDTable(db))
  485. return false;
  486. if(((nMaxLogTimestamp = GetLastLogTimestamp(db)) != _INVALID_TIMESTAMP_VALUE))
  487. m_nLastLogTimestamp = nMaxLogTimestamp;
  488. m_lf.Info("Database initialization complete.\n");
  489. return true;
  490. }
  491. /////////////////////////////////////////////////////////////////////////////
  492. bool CDataLogger::CreateDatabase(CMySqlDB &rdb, bool bEnforceCreate)
  493. {
  494. bool bError = false;
  495. std::string sSql;
  496. if(bEnforceCreate)
  497. {
  498. sSql = formatString("drop database if exists `%s`", m_dlp.szDBName);
  499. CMySqlResult res = rdb.Query(sSql.c_str());
  500. bError = res.error();
  501. if(bError)
  502. m_lf.Error("CDataLogger::CreateDatabase: DB Error: %s\n", rdb.LastError().c_str());
  503. }
  504. if(!bError)
  505. {
  506. sSql = formatString("create database if not exists `%s`", m_dlp.szDBName);
  507. CMySqlResult res = rdb.Query(sSql.c_str());
  508. bError = res.error();
  509. if(bError)
  510. m_lf.Error("CDataLogger::CreateDatabase: DB Error: %s\n", rdb.LastError().c_str());
  511. }
  512. return !bError;
  513. }
  514. /////////////////////////////////////////////////////////////////////////////
  515. bool CDataLogger::CreateTagsTable(CMySqlDB &rdb)
  516. {
  517. std::string sSql;
  518. const char *pszFormat =
  519. "CREATE TABLE IF NOT EXISTS `%s` (" \
  520. " `tagid` smallint(6) unsigned NOT NULL AUTO_INCREMENT," \
  521. " `dataType` enum('bool', 'I1', 'UI1', 'I2', 'UI2', 'I4', 'UI4', 'I8', 'UI8', 'float', 'double', 'string') NOT NULL," \
  522. " `logType` enum('IC', 'IU', 'VC', 'VU', 'ICR', 'IUR', 'VCR', 'VUR') NOT NULL," \
  523. " `path` varchar(%u) NOT NULL," \
  524. " PRIMARY KEY (`tagid`, `dataType`, `logType`)," \
  525. " KEY `path` (`path`)" \
  526. ") ENGINE=%s DEFAULT CHARSET=ascii";
  527. m_lf.Info("Creating Table '%s' (if not exists) using engine '%s'.\n", m_dlp.szTagsTable, _DL_DATABSE_ENGINE_NAME);
  528. sSql = formatString(pszFormat, m_dlp.szTagsTable, _DL_MAX_VARPATH_LENGTH, _DL_DATABSE_ENGINE_NAME);
  529. CMySqlResult res = rdb.Query(sSql.c_str());
  530. bool bError = res.error();
  531. if(bError)
  532. m_lf.Error("CDataLogger::CreateTagsTable: DB Error: %s\n", rdb.LastError().c_str());
  533. else
  534. m_lf.Info("Success!\n");
  535. return !bError;
  536. }
  537. bool CDataLogger::AlterTagsTable(CMySqlDB &rdb)
  538. {
  539. std::string sSql = formatString("ALTER TABLE `%s` MODIFY COLUMN `logType` enum('IC','IU','VC','VU','ICR','IUR','VCR','VUR') NOT NULL", m_dlp.szTagsTable);
  540. CMySqlResult res = rdb.Query(sSql.c_str());
  541. bool bError = res.error();
  542. if(bError)
  543. m_lf.Error("CDataLogger::AlterTagsTable: DB Error: %s\n", rdb.LastError().c_str());
  544. return !bError;
  545. }
  546. /////////////////////////////////////////////////////////////////////////////
  547. bool CDataLogger::CreateLogsTable(CMySqlDB &rdb)
  548. {
  549. std::string sSql;
  550. const char *pszFormat =
  551. #if _USE_MODIFIED_INDEX
  552. "CREATE TABLE IF NOT EXISTS `%s` (" \
  553. " `tagid` smallint(6) unsigned NOT NULL," \
  554. " `tslog` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP," \
  555. " `value` double," \
  556. " `valueMin` double DEFAULT NULL," \
  557. " `valueMax` double DEFAULT NULL," \
  558. " PRIMARY KEY (`tslog`, `tagid`)," \
  559. " KEY `taglog` (`tagid`, `tslog`)" \
  560. ") ENGINE=%s DEFAULT CHARSET=ascii ROW_FORMAT=COMPRESSED";
  561. #else // _USE_MODIFIED_INDEX
  562. "CREATE TABLE IF NOT EXISTS `%s` (" \
  563. " `tagid` smallint(6) unsigned NOT NULL," \
  564. " `tslog` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP," \
  565. " `value` double," \
  566. " `valueMin` double DEFAULT NULL," \
  567. " `valueMax` double DEFAULT NULL," \
  568. " PRIMARY KEY (`tagid`, `tslog`)," \
  569. " KEY `tslog` (`tslog`)" \
  570. ") ENGINE=%s DEFAULT CHARSET=ascii ROW_FORMAT=COMPRESSED";
  571. #endif // _USE_MODIFIED_INDEX
  572. m_lf.Info("Creating Table '%s' if not exists using engine '%s'.\n", m_dlp.szLogsTable, _DL_DATABSE_ENGINE_NAME);
  573. sSql = formatString(pszFormat, m_dlp.szLogsTable, _DL_DATABSE_ENGINE_NAME);
  574. CMySqlResult res = rdb.Query(sSql.c_str());
  575. bool bError = res.error();
  576. if(bError)
  577. m_lf.Error("CDataLogger::CreateLogsTable: DB Error: %s\n", rdb.LastError().c_str());
  578. else
  579. m_lf.Info("Success!\n");
  580. return !bError;
  581. }
  582. /////////////////////////////////////////////////////////////////////////////
  583. bool CDataLogger::CreateLogsBDTable(CMySqlDB &rdb)
  584. {
  585. std::string sSql;
  586. const char *pszFormat =
  587. "CREATE TABLE IF NOT EXISTS `%s` (" \
  588. " `id` int unsigned unsigned NOT NULL AUTO_INCREMENT," \
  589. " `tagid` smallint(6) unsigned NOT NULL," \
  590. " `tslog` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP," \
  591. " `value` double," \
  592. " `valueMin` double DEFAULT NULL," \
  593. " `valueMax` double DEFAULT NULL," \
  594. " PRIMARY KEY (`id`)," \
  595. " KEY `tslog` (`tslog`)," \
  596. " KEY `tagid` (`tagid`)" \
  597. ") ENGINE=%s DEFAULT CHARSET=ascii ROW_FORMAT=COMPRESSED";
  598. m_lf.Info("Creating Table '%s' if not exists using engine '%s'.\n", m_dlp.szLogsTableBD, _DL_DATABSE_ENGINE_NAME);
  599. sSql = formatString(pszFormat, m_dlp.szLogsTableBD, _DL_DATABSE_ENGINE_NAME);
  600. CMySqlResult res = rdb.Query(sSql.c_str());
  601. bool bError = res.error();
  602. if(bError)
  603. m_lf.Error("CDataLogger::CreateLogsBDTable: DB Error: %s\n", rdb.LastError().c_str());
  604. else
  605. m_lf.Info("Success!\n");
  606. return !bError;
  607. }
  608. /////////////////////////////////////////////////////////////////////////////
  609. bool CDataLogger::Log(unsigned long nTagID, double fValue, double fMin, double fMax, time_t nTimestamp, int nIndex, LogTypes lt, bool bNull, bool bNoBadDateCheck)
  610. {
  611. bNull = bNull || !_IsLoggable(fValue) || !_IsLoggable(fMin) || !_IsLoggable(fMax);
  612. DL_LOG_ENTRY log;
  613. log.nTagID = nTagID;
  614. log.nTimestamp = nTimestamp;
  615. log.fValue = fValue;
  616. log.fMin = fMin;
  617. log.fMax = fMax;
  618. log.nIndex = nIndex;
  619. log.lt = lt;
  620. log.bNull = bNull;
  621. if(bNoBadDateCheck || (nTimestamp > m_nLastLogTimestamp))
  622. m_logs.push_back(log);
  623. else
  624. m_logsBD.push_back(log);
  625. return true;
  626. }
  627. /////////////////////////////////////////////////////////////////////////////
  628. time_t CDataLogger::GetLastLogTimestamp(CMySqlDB &rdb)
  629. {
  630. time_t nTs = _INVALID_TIMESTAMP_VALUE;
  631. std::string sSql;
  632. do
  633. {
  634. sSql = formatString("select unix_timestamp(max(`tslog`)) from `%s`", m_dlp.szLogsTable);
  635. CMySqlResult res = rdb.Query(sSql.c_str());
  636. if(res.error())
  637. {
  638. m_lf.Error("CDataLogger::GetLastLogTimestamp: DB Error: %s\n", rdb.LastError().c_str());
  639. break;
  640. }
  641. else
  642. {
  643. CMySqlVar val;
  644. my_ulonglong nRowCount = res.RowCount();
  645. unsigned int nFldCount = res.FieldCount();
  646. const MYSQL_FIELD *pFields = res.FetchFields();
  647. if(nRowCount != 1 || nFldCount != 1 || !pFields)
  648. {
  649. // m_lf.Error("CDataLogger::GetLastLogTimestamp: Unexpected error!\n");
  650. break;
  651. }
  652. MYSQL_ROW pRow = res.FetchRow();
  653. if( !pRow ||
  654. !val.FromField(pFields[0], pRow[0]))
  655. {
  656. // m_lf.Error("CDataLogger::GetLastLogTimestamp: Unexpected error!\n");
  657. break;
  658. }
  659. nTs = (time_t)(uint64_t)val;
  660. }
  661. }
  662. while(false);
  663. return nTs;
  664. }
  665. /////////////////////////////////////////////////////////////////////////////
  666. bool CDataLogger::Flush(time_t nTimestamp)
  667. {
  668. std::string strErr;
  669. ::pthread_mutex_lock(&m_condmtx1);
  670. bool bGoodBadTransition = false, bSgInProg = m_bSGInProgress;
  671. ::pthread_mutex_unlock(&m_condmtx1);
  672. time_t nMaxLogTimestamp = 0, nFirstGoodTimestamp = 0;
  673. size_t nCountValidDate = m_logs.size();
  674. size_t nCountBadDate = m_logsBD.size();
  675. if(!nCountValidDate && !nCountBadDate)
  676. return true; // nothing to do
  677. TRACE("Trying to flush %zu logs ...\n", nCountValidDate + nCountBadDate);
  678. if(bSgInProg && nCountValidDate)
  679. {
  680. TRACE("Flush: SG in progress - flushing of %zu logs deferred!\n", nCountValidDate);
  681. m_lf.Info("Flush: SG in progress - flushing of %zu logs deferred!\n", nCountValidDate);
  682. nCountValidDate = 0; // size guard operates on the valid-date-logs-table only, so we can safely flush invalid-date-logs
  683. if(!nCountBadDate)
  684. return true; // no error
  685. }
  686. if(!m_bBadDateLogsDetected && nCountBadDate)
  687. {
  688. m_bBadDateLogsDetected = true;
  689. bGoodBadTransition = true;
  690. }
  691. else if(m_bBadDateLogsDetected && !nCountBadDate)
  692. {
  693. m_bBadDateLogsDetected = false;
  694. bGoodBadTransition = true;
  695. }
  696. CMySqlDB db;
  697. std::string strUnlock, strSaveFgnKey, strDisableFgnKey, strRestoreFgnKey, strSaveTZ, strSetTZ, strRestoreTZ;
  698. bool bError = false;
  699. std::string sSql;
  700. if(!db.Connect("localhost", m_dlp.szDBUser, m_dlp.szDBPass, m_dlp.szDBName))
  701. {
  702. m_lf.Error("CDataLogger::Flush: DB Error: %s\n", db.LastError().c_str());
  703. return false;
  704. }
  705. strUnlock = formatString("unlock tables");
  706. strSaveFgnKey = formatString("set @old_foreign_key_checks = @@foreign_key_checks");
  707. strDisableFgnKey = formatString("set foreign_key_checks = 0");
  708. strRestoreFgnKey = formatString("set foreign_key_checks = @old_foreign_key_checks");
  709. strSaveTZ = formatString("set @old_time_zone = @@time_zone");
  710. strSetTZ = formatString("set time_zone = '+00:00'");
  711. strRestoreTZ = formatString("set time_zone = @old_time_zone");
  712. db.Query(strSaveTZ.c_str());
  713. db.Query(strSetTZ.c_str());
  714. db.Query(strSaveFgnKey.c_str());
  715. db.Query(strDisableFgnKey.c_str());
  716. if(nCountValidDate > 0)
  717. {
  718. std::string strSql, strLock;
  719. strLock = formatString("lock tables `%s` write", m_dlp.szLogsTable);
  720. strSql.reserve(130 + 111 * nCountValidDate);
  721. auto itFirst = m_logs.begin();
  722. const DL_LOG_ENTRY &rle0 = *itFirst;
  723. if(nMaxLogTimestamp < rle0.nTimestamp)
  724. nMaxLogTimestamp = rle0.nTimestamp;
  725. nFirstGoodTimestamp = rle0.nTimestamp;
  726. if(m_dlp.bMinMax && _IS_INTERVAL_LOGTYPE(rle0.lt))
  727. {
  728. if(!rle0.bNull)
  729. sSql = formatString("insert into `%s` (`tagid`, `tslog`, `value`, `valueMin`, `valueMax`) values (%lu, timestamp(from_unixtime(%lu)), %.20g, %.20g, %.20g)", m_dlp.szLogsTable, rle0.nTagID, rle0.nTimestamp, rle0.fValue, rle0.fMin, rle0.fMax);
  730. else
  731. sSql = formatString("insert into `%s` (`tagid`, `tslog`, `value`, `valueMin`, `valueMax`) values (%lu, timestamp(from_unixtime(%lu)), NULL, NULL, NULL)", m_dlp.szLogsTable, rle0.nTagID, rle0.nTimestamp);
  732. }
  733. else
  734. {
  735. if(!rle0.bNull)
  736. sSql = formatString("insert into `%s` (`tagid`, `tslog`, `value`, `valueMin`, `valueMax`) values (%lu, timestamp(from_unixtime(%lu)), %.20g, NULL, NULL)", m_dlp.szLogsTable, rle0.nTagID, rle0.nTimestamp, rle0.fValue);
  737. else
  738. sSql = formatString("insert into `%s` (`tagid`, `tslog`, `value`, `valueMin`, `valueMax`) values (%lu, timestamp(from_unixtime(%lu)), NULL, NULL, NULL)", m_dlp.szLogsTable, rle0.nTagID, rle0.nTimestamp);
  739. }
  740. strSql = sSql;
  741. for(++itFirst; itFirst < m_logs.end(); itFirst++)
  742. {
  743. const DL_LOG_ENTRY &rle = *itFirst;
  744. if(nMaxLogTimestamp < rle.nTimestamp)
  745. nMaxLogTimestamp = rle.nTimestamp;
  746. if(m_dlp.bMinMax && _IS_INTERVAL_LOGTYPE(rle.lt))
  747. {
  748. if(!rle.bNull)
  749. sSql = formatString(",(%lu, timestamp(from_unixtime(%lu)), %.20g, %.20g, %.20g)", rle.nTagID, rle.nTimestamp, rle.fValue, rle.fMin, rle.fMax);
  750. else
  751. sSql = formatString(",(%lu, timestamp(from_unixtime(%lu)), NULL, NULL, NULL)", rle.nTagID, rle.nTimestamp);
  752. }
  753. else
  754. {
  755. if(!rle.bNull)
  756. sSql = formatString(",(%lu, timestamp(from_unixtime(%lu)), %.20g, NULL, NULL)", rle.nTagID, rle.nTimestamp, rle.fValue);
  757. else
  758. sSql = formatString(",(%lu, timestamp(from_unixtime(%lu)), NULL, NULL, NULL)", rle.nTagID, rle.nTimestamp);
  759. }
  760. strSql += sSql;
  761. }
  762. if(TryLock())
  763. {
  764. db.Query(strLock.c_str());
  765. CMySqlResult res = db.Query(strSql.c_str());
  766. if((bError = res.error()))
  767. strErr = db.LastError();
  768. db.Query(strUnlock.c_str());
  769. Unlock();
  770. if(bError)
  771. m_lf.Error("CDataLogger::Flush: DB Error: %s\n", strErr.c_str());
  772. else
  773. m_nLastLogTimestamp = nMaxLogTimestamp;
  774. m_logs.clear();
  775. }
  776. }
  777. if(bGoodBadTransition)
  778. {
  779. if(m_bBadDateLogsDetected)
  780. {
  781. bool bErr;
  782. char szTs[64];
  783. unsigned long long nNextAIVal = 0;
  784. sSql = formatString("select auto_increment from `information_schema`.`TABLES` where `TABLE_SCHEMA` = '%s' and `TABLE_NAME` = '%s';", m_dlp.szDBName, m_dlp.szLogsTableBD);
  785. CMySqlResult res = db.Query(sSql.c_str());
  786. if(!(bErr = res.error()))
  787. {
  788. CMySqlVar val;
  789. my_ulonglong nRowCount = res.RowCount();
  790. unsigned int nFldCount = res.FieldCount();
  791. const MYSQL_FIELD *pFields = res.FetchFields();
  792. do
  793. {
  794. if(nRowCount != 1 || nFldCount != 1 || !pFields)
  795. break;
  796. MYSQL_ROW pRow = res.FetchRow();
  797. if(!pRow || !*pRow || !**pRow)
  798. break;
  799. if(!val.FromField(pFields[0], pRow[0]))
  800. break;
  801. nNextAIVal = val;
  802. }
  803. while(false);
  804. }
  805. Timestamp2String(m_nLastLogTimestamp, szTs, sizeof(szTs));
  806. if(nNextAIVal)
  807. {
  808. TRACE("Flush: Transition valid -> invalid date detected! The last Timestamp in Table `%s` was '%s+00:00'. Subsequent logs will be written to table `%s` starting with `id` %llu.\n", m_dlp.szLogsTable, szTs, m_dlp.szLogsTableBD, nNextAIVal);
  809. m_lf.Warning("Flush: Transition valid -> invalid date detected! The last Timestamp in Table `%s` was '%s+00:00'. Subsequent logs will be written to table `%s` starting with `id` %llu.\n", m_dlp.szLogsTable, szTs, m_dlp.szLogsTableBD, nNextAIVal);
  810. }
  811. else
  812. {
  813. TRACE("Flush: Transition valid -> invalid date detected! The last Timestamp in Table `%s` was '%s+00:00'. Subsequent logs will be written to table `%s`.\n", m_dlp.szLogsTable, szTs, m_dlp.szLogsTableBD);
  814. m_lf.Warning("Flush: Transition valid -> invalid date detected! The last Timestamp in Table `%s` was '%s+00:00'. Subsequent logs will be written to table `%s`.\n", m_dlp.szLogsTable, szTs, m_dlp.szLogsTableBD);
  815. }
  816. }
  817. else
  818. {
  819. bool bErr;
  820. char szTs[64];
  821. unsigned long long nLastID = 0;
  822. sSql = formatString("select max(`id`) from `%s`.`%s`;", m_dlp.szDBName, m_dlp.szLogsTableBD);
  823. CMySqlResult res = db.Query(sSql.c_str());
  824. if(!(bErr = res.error()))
  825. {
  826. CMySqlVar val;
  827. my_ulonglong nRowCount = res.RowCount();
  828. unsigned int nFldCount = res.FieldCount();
  829. const MYSQL_FIELD *pFields = res.FetchFields();
  830. do
  831. {
  832. if(nRowCount != 1 || nFldCount != 1 || !pFields)
  833. break;
  834. MYSQL_ROW pRow = res.FetchRow();
  835. if(!pRow || !*pRow || !**pRow)
  836. break;
  837. if(!val.FromField(pFields[0], pRow[0]))
  838. break;
  839. nLastID = val;
  840. }
  841. while(false);
  842. }
  843. Timestamp2String(nFirstGoodTimestamp, szTs, sizeof(szTs));
  844. if(nLastID)
  845. {
  846. TRACE("Flush: Transition invalid -> valid date detected! The last `id` in table `%s` was %llu. Subsequent logs will be written to table `%s` beginning with timestamp '%s+00:00'.\n", m_dlp.szLogsTableBD, nLastID, m_dlp.szLogsTable, szTs);
  847. m_lf.Warning("Flush: Transition invalid -> valid date detected! The last `id` in table `%s` was %llu. Subsequent logs will be written to table `%s` beginning with timestamp '%s+00:00'.\n", m_dlp.szLogsTableBD, nLastID, m_dlp.szLogsTable, szTs);
  848. }
  849. else
  850. {
  851. TRACE("Flush: Transition invalid -> valid date detected! Subsequent logs will be written to table `%s` beginning with timestamp '%s+00:00'.\n", m_dlp.szLogsTable, szTs);
  852. m_lf.Warning("Flush: Transition invalid -> valid date detected! Subsequent logs will be written to table `%s` beginning with timestamp '%s+00:00'.\n", m_dlp.szLogsTable, szTs);
  853. }
  854. }
  855. }
  856. if(nCountBadDate > 0)
  857. {
  858. std::string strSql, strLock;
  859. strLock = formatString("lock tables `%s` write", m_dlp.szLogsTableBD);
  860. strSql.reserve(130 + 111 * nCountBadDate);
  861. auto itFirst = m_logsBD.begin();
  862. const DL_LOG_ENTRY &rle0 = *itFirst;
  863. if(m_dlp.bMinMax && _IS_INTERVAL_LOGTYPE(rle0.lt))
  864. {
  865. if(!rle0.bNull)
  866. sSql = formatString("insert into `%s` (`tagid`, `tslog`, `value`, `valueMin`, `valueMax`) values (%lu, timestamp(from_unixtime(%lu)), %.20g, %.20g, %.20g)", m_dlp.szLogsTableBD, rle0.nTagID, rle0.nTimestamp, rle0.fValue, rle0.fMin, rle0.fMax);
  867. else
  868. sSql = formatString("insert into `%s` (`tagid`, `tslog`, `value`, `valueMin`, `valueMax`) values (%lu, timestamp(from_unixtime(%lu)), NULL, NULL, NULL)", m_dlp.szLogsTableBD, rle0.nTagID, rle0.nTimestamp);
  869. }
  870. else
  871. {
  872. if(!rle0.bNull)
  873. sSql = formatString("insert into `%s` (`tagid`, `tslog`, `value`, `valueMin`, `valueMax`) values (%lu, timestamp(from_unixtime(%lu)), %.20g, NULL, NULL)", m_dlp.szLogsTableBD, rle0.nTagID, rle0.nTimestamp, rle0.fValue);
  874. else
  875. sSql = formatString("insert into `%s` (`tagid`, `tslog`, `value`, `valueMin`, `valueMax`) values (%lu, timestamp(from_unixtime(%lu)), NULL, NULL, NULL)", m_dlp.szLogsTableBD, rle0.nTagID, rle0.nTimestamp);
  876. }
  877. strSql = sSql;
  878. for(++itFirst; itFirst < m_logsBD.end(); itFirst++)
  879. {
  880. const DL_LOG_ENTRY &rle = *itFirst;
  881. if(m_dlp.bMinMax && _IS_INTERVAL_LOGTYPE(rle.lt))
  882. {
  883. if(!rle.bNull)
  884. sSql = formatString(",(%lu, timestamp(from_unixtime(%lu)), %.20g, %.20g, %.20g)", rle.nTagID, rle.nTimestamp, rle.fValue, rle.fMin, rle.fMax);
  885. else
  886. sSql = formatString(",(%lu, timestamp(from_unixtime(%lu)), NULL, NULL, NULL)", rle.nTagID, rle.nTimestamp);
  887. }
  888. else
  889. {
  890. if(!rle.bNull)
  891. sSql = formatString(",(%lu, timestamp(from_unixtime(%lu)), %.20g, NULL, NULL)", rle.nTagID, rle.nTimestamp, rle.fValue);
  892. else
  893. sSql = formatString(",(%lu, timestamp(from_unixtime(%lu)), NULL, NULL, NULL)", rle.nTagID, rle.nTimestamp);
  894. }
  895. strSql += sSql;
  896. }
  897. db.Query(strLock.c_str());
  898. CMySqlResult res = db.Query(strSql.c_str());
  899. if((bError = res.error()))
  900. strErr = db.LastError();
  901. db.Query(strUnlock.c_str());
  902. if(bError)
  903. m_lf.Error("CDataLogger::Flush: DB Error: %s\n", strErr.c_str());
  904. m_logsBD.clear();
  905. }
  906. db.Query(strRestoreFgnKey.c_str());
  907. db.Query(strRestoreTZ.c_str());
  908. return !bError;
  909. }
  910. /////////////////////////////////////////////////////////////////////////////
  911. unsigned long long CDataLogger::SizeGuardLastPassRead(void)
  912. {
  913. char szPath[PATH_MAX];
  914. sprintf(szPath, "%s/%s", m_szAppDir, _SIZE_GUARD_TIMESTAMP_FILE_NAME);
  915. FILE *pf = fopen(szPath, "rb");
  916. unsigned long long ts = 0;
  917. if(pf)
  918. {
  919. if(fread(&ts, sizeof(ts), 1, pf) != 1)
  920. ts = 0;
  921. fclose(pf);
  922. }
  923. return ts;
  924. }
  925. /////////////////////////////////////////////////////////////////////////////
  926. void CDataLogger::SizeGuardLastPassWrite(unsigned long long ts)
  927. {
  928. char szPath[PATH_MAX];
  929. sprintf(szPath, "%s/%s", m_szAppDir, _SIZE_GUARD_TIMESTAMP_FILE_NAME);
  930. FILE *pf = fopen(szPath, "wb");
  931. if(pf)
  932. {
  933. fwrite(&ts, sizeof(ts), 1, pf);
  934. fclose(pf);
  935. }
  936. }
  937. /////////////////////////////////////////////////////////////////////////////
  938. size_t CDataLogger::Timestamp2String(time_t t, char *pszBuffer, size_t nCbBuffer)
  939. {
  940. const struct tm * ptm = gmtime(&t);
  941. return strftime(pszBuffer, nCbBuffer, "%F %T", ptm);
  942. }
  943. /////////////////////////////////////////////////////////////////////////////
  944. const char* CDataLogger::Ns2String(unsigned long long nNs, char *pszBuffer, size_t nCbBuffer)
  945. {
  946. *pszBuffer = '\0';
  947. if(nNs < 1000)
  948. snprintf(pszBuffer, nCbBuffer, "%llu ns", nNs);
  949. else if(nNs < 1000000)
  950. snprintf(pszBuffer, nCbBuffer, "%.1f us", (double)nNs / 1000.0);
  951. else
  952. return Ms2String((double)nNs / 1000000.0, pszBuffer, nCbBuffer);
  953. return pszBuffer;
  954. }
  955. /////////////////////////////////////////////////////////////////////////////
  956. const char* CDataLogger::Ms2String(double fMs, char *pszBuffer, size_t nCbBuffer)
  957. {
  958. *pszBuffer = '\0';
  959. if(fMs < 1000.0)
  960. snprintf(pszBuffer, nCbBuffer, "%.2f ms", fMs);
  961. else if(fMs < 60000.0)
  962. snprintf(pszBuffer, nCbBuffer, "%.2f sec", fMs / 1000.0);
  963. else if(fMs < 3600000.0)
  964. snprintf(pszBuffer, nCbBuffer, "%.2f min", fMs / 60000.0);
  965. else
  966. snprintf(pszBuffer, nCbBuffer, "%.2f h", fMs / 3600000.0);
  967. return pszBuffer;
  968. }
  969. /////////////////////////////////////////////////////////////////////////////
  970. bool CDataLogger::DoSizeGuard(void)
  971. {
  972. if(!m_bSGConfigured)
  973. return true;
  974. CMySqlDB db;
  975. bool bError;
  976. MYSQL_ROW pRow;
  977. unsigned long long nElapsed;
  978. char szT1[32], szT2[32], szMs[32];
  979. CProcessClock pc;
  980. CMySqlVar vMinTs, vCountDelete;
  981. int64_t nMinTs, nTsCurMidnightUTC, nTsDeleteUpTo;
  982. std::string sSql;
  983. /////////////////////////////////////////////////////////////////////////
  984. nTsCurMidnightUTC = _MIDNIGHT_TIMESTAMP_UTC(m_nSGCurPassUTC);
  985. if(SizeGuardDayWorkDone(nTsCurMidnightUTC))
  986. return true;
  987. m_nSGLastPassUTC = nTsCurMidnightUTC;
  988. if(SizeGuardLastPassRead() == (unsigned long long)(nTsCurMidnightUTC))
  989. return true;
  990. SizeGuardLastPassWrite(nTsCurMidnightUTC);
  991. /////////////////////////////////////////////////////////////////////////
  992. if(!db.Connect("localhost", m_dlp.szDBUser, m_dlp.szDBPass, NULL))
  993. {
  994. m_lf.Error("CDataLogger::DoSizeGuard(%d): - DB Error: %s\n", __LINE__, db.LastError().c_str());
  995. return false;
  996. }
  997. sSql = formatString("select unix_timestamp(min(`tslog`)) from `%s`.`%s`;", m_dlp.szDBName, m_dlp.szLogsTable);
  998. m_lf.Info("SG: \"%s\".\n", sSql.c_str());
  999. pc.ClockTrigger();
  1000. CMySqlResult res = db.Query(sSql.c_str());
  1001. nElapsed = pc.ClockGetElapsed();
  1002. bError = res.error();
  1003. if(bError)
  1004. {
  1005. m_lf.Error("CDataLogger::DoSizeGuard(%d): \"%s\" - DB Error: %s\n", __LINE__, sSql.c_str(), db.LastError().c_str());
  1006. return false;
  1007. }
  1008. if(!(pRow = res.FetchRow()))
  1009. {
  1010. m_lf.Error("CDataLogger::DoSizeGuard(%d): Unexpected Error!\n", __LINE__);
  1011. return false;
  1012. }
  1013. my_ulonglong nRowCount = res.RowCount();
  1014. unsigned int nFldCount = res.FieldCount();
  1015. const MYSQL_FIELD *pFields = res.FetchFields();
  1016. if(nRowCount != 1 || nFldCount != 1)
  1017. {
  1018. m_lf.Error("CDataLogger::DoSizeGuard(%d): Unexpected Error!\n", __LINE__);
  1019. return false;
  1020. }
  1021. if(!vMinTs.FromField(pFields[0], pRow[0]))
  1022. {
  1023. m_lf.Error("CDataLogger::DoSizeGuard(%d): Unexpected Error!\n", __LINE__);
  1024. return false;
  1025. }
  1026. nMinTs = vMinTs;
  1027. m_lf.Info("SG: operation completed in %s. Min. timestamp: %ju\n", Ns2String(nElapsed, szMs, sizeof(szMs)), nMinTs);
  1028. /////////////////////////////////////////////////////////////////////////
  1029. // process max. size
  1030. if(m_bSGHasSizeLimitPrerequisites && m_dlp.nMaxSize)
  1031. {
  1032. unsigned long long nFileSize = TableFileSize(m_dlp.szLogsTable);
  1033. unsigned long long nGuardThreshold = m_dlp.nMaxSize * (100 - _FILE_SIZE_DELETE_MARGIN_PERCENT) / 100;
  1034. m_lf.Info("SG: File size: %s.\n", strFormatByteSize(nFileSize, 1).c_str());
  1035. if(nFileSize > nGuardThreshold)
  1036. {
  1037. Timestamp2String(nTsCurMidnightUTC - _SECONDS_PER_DAY, szT1, sizeof(szT1));
  1038. Timestamp2String(nTsCurMidnightUTC - 1, szT2, sizeof(szT2));
  1039. sSql = formatString("select count(*) from `%s`.`%s` where `tslog` between '%s' and '%s';", m_dlp.szDBName, m_dlp.szLogsTable, szT1, szT2);
  1040. m_lf.Info("SG: \"%s\"\n", sSql.c_str());
  1041. pc.ClockTrigger();
  1042. CMySqlResult res = db.Query(sSql.c_str());
  1043. bError = res.error();
  1044. if(bError)
  1045. {
  1046. m_lf.Error("CDataLogger::DoSizeGuard(%d): \"%s\" - DB Error: %s\n", __LINE__, sSql.c_str(), db.LastError().c_str());
  1047. return false;
  1048. }
  1049. else
  1050. {
  1051. nElapsed = pc.ClockGetElapsed();
  1052. nRowCount = res.RowCount();
  1053. nFldCount = res.FieldCount();
  1054. pFields = res.FetchFields();
  1055. pRow = res.FetchRow();
  1056. if(pRow && pFields && nRowCount == 1 && nFldCount == 1 && vCountDelete.FromField(pFields[0], pRow[0]))
  1057. {
  1058. unsigned long long nCountDelete = (uint64_t)vCountDelete;
  1059. m_lf.Info("SG: operation completed in %s. Estimated number of rows to delete: %llu.\n", Ns2String(nElapsed, szMs, sizeof(szMs)), nCountDelete);
  1060. if(nCountDelete > 0)
  1061. {
  1062. #if _USE_MODIFIED_INDEX
  1063. sSql = formatString("delete from `%s`.`%s` limit %llu;", m_dlp.szDBName, m_dlp.szLogsTable, nCountDelete);
  1064. #else // _USE_MODIFIED_INDEX
  1065. sSql = formatString("delete from `%s`.`%s` where `tslog` <= (select `tslog` from (select `tslog` from `demo`.`logs` order by `tslog` asc limit %llu, 1) x);", m_dlp.szDBName, m_dlp.szLogsTable, nCountDelete - 1);
  1066. #endif // _USE_MODIFIED_INDEX
  1067. m_lf.Info("SG: triggered on size limit: \"%s\".\n", sSql.c_str());
  1068. pc.ClockTrigger();
  1069. if(db.Query(sSql.c_str()).error())
  1070. {
  1071. m_lf.Error("CDataLogger::DoSizeGuard(%d): \"%s\" - DB Error: %s\n", __LINE__, sSql.c_str(), db.LastError().c_str());
  1072. return false;
  1073. }
  1074. else
  1075. {
  1076. nElapsed = pc.ClockGetElapsed();
  1077. m_lf.Info("SG: operation completed in %s.\n", Ns2String(nElapsed, szMs, sizeof(szMs)));
  1078. }
  1079. }
  1080. }
  1081. else
  1082. {
  1083. m_lf.Error("CDataLogger::DoSizeGuard(%d): Unexpected Error!\n", __LINE__);
  1084. return false;
  1085. }
  1086. }
  1087. }
  1088. }
  1089. /////////////////////////////////////////////////////////////////////////
  1090. // process max. age entries
  1091. if(m_dlp.nMaxAge)
  1092. {
  1093. nTsDeleteUpTo = nTsCurMidnightUTC - m_dlp.nMaxAge * _SECONDS_PER_DAY;
  1094. if(nMinTs <= nTsDeleteUpTo)
  1095. {
  1096. Timestamp2String(nTsDeleteUpTo, szT1, sizeof(szT1));
  1097. sSql = formatString("delete from `%s`.`%s` where `tslog` < '%s';", m_dlp.szDBName, m_dlp.szLogsTable, szT1);
  1098. m_lf.Info("SG: triggered on age limit: \"%s\".\n", sSql.c_str());
  1099. pc.ClockTrigger();
  1100. CMySqlResult res = db.Query(sSql.c_str());
  1101. nElapsed = pc.ClockGetElapsed();
  1102. bError = res.error();
  1103. if(bError)
  1104. {
  1105. m_lf.Error("CDataLogger::DoSizeGuard(%d): DB Error: %s\n", __LINE__, db.LastError().c_str());
  1106. return false;
  1107. }
  1108. else
  1109. {
  1110. m_lf.Info("SG: operation completed in %s.\n", Ns2String(nElapsed, szMs, sizeof(szMs)));
  1111. }
  1112. }
  1113. }
  1114. return true;
  1115. }
  1116. /////////////////////////////////////////////////////////////////////////////
  1117. /////////////////////////////////////////////////////////////////////////////
  1118. /////////////////////////////////////////////////////////////////////////////
  1119. // size guard worker thread
  1120. void* CDataLogger::SizeGuardWorker(void* pParam)
  1121. {
  1122. unsigned long long nElapsed;
  1123. char szMs[32];
  1124. CProcessClock pc;
  1125. CDataLogger *pThis = reinterpret_cast<CDataLogger*>(pParam);
  1126. ::pthread_mutex_lock(&pThis->m_condmtx1);
  1127. ::pthread_cond_signal(&pThis->m_cond1);
  1128. while(true)
  1129. {
  1130. pThis->m_bSGInProgress = false;
  1131. ::pthread_cond_wait(&pThis->m_cond1, &pThis->m_condmtx1);
  1132. pThis->m_bSGInProgress = true;
  1133. ::pthread_mutex_unlock(&pThis->m_condmtx1);
  1134. TRACE("Size guard start.\n");
  1135. pThis->Lock();
  1136. pc.ClockTrigger();
  1137. pThis->DoSizeGuard();
  1138. nElapsed = pc.ClockGetElapsed();
  1139. pThis->Unlock();
  1140. pThis->m_lf.Info("SG: finished in %s.\n", Ns2String(nElapsed, szMs, sizeof(szMs)));
  1141. TRACE("Size guard end - [%s].\n", szMs);
  1142. ::pthread_yield();
  1143. ::pthread_mutex_lock(&pThis->m_condmtx1);
  1144. }
  1145. return NULL;
  1146. }