DataCondenser.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. #include "DataCondenser.h"
  2. #include "Util/Util.h"
  3. #include <iostream>
  4. #include <limits>
  5. #include <map>
  6. #include <memory>
  7. #include <sstream>
  8. namespace DataStorageInterface {
  9. namespace DataInterface {
  10. DataCondenser::DataCondenser(MySQL::MySQLClient* pMySQLClient) :
  11. m_pMySQLClient(pMySQLClient)
  12. {
  13. }
  14. void DataCondenser::CondenseData()
  15. {
  16. auto deviceIDs = GetDeviceIDs();
  17. for (int dataId = 0; dataId < 3; ++dataId)
  18. {
  19. std::cout << "DataID: " << dataId << std::endl;
  20. //std::cout << "Daily" << std::endl;
  21. //for (auto& deviceId : deviceIDs)
  22. // WriteReducedData(deviceId, dataId, RRA::Daily);
  23. std::cout << "Weekly" << std::endl;
  24. for (auto& deviceId : deviceIDs)
  25. WriteReducedData(deviceId, dataId, RRA::Weekly);
  26. std::cout << "Monthly" << std::endl;
  27. for (auto& deviceId : deviceIDs)
  28. WriteReducedData(deviceId, dataId, RRA::Monthly);
  29. std::cout << "Yearly" << std::endl;
  30. for (auto& deviceId : deviceIDs)
  31. WriteReducedData(deviceId, dataId, RRA::Yearly);
  32. }
  33. CleanData();
  34. }
  35. int DataCondenser::GetPeriodStamp(int timestamp, const RRA::type& rra)
  36. {
  37. int modulo = timestamp % static_cast<int>(rra);
  38. return timestamp - modulo;
  39. }
  40. std::vector<int> DataCondenser::GetDeviceIDs()
  41. {
  42. std::stringstream query;
  43. query << "SELECT DISTINCT `device_id` FROM `datalog` ORDER BY `device_id`;";
  44. auto resultSet = m_pMySQLClient->ExecuteQuery(query.str());
  45. std::vector<int> returnValue;
  46. while (resultSet.Next())
  47. returnValue.push_back(resultSet.Int("device_id"));
  48. return returnValue;
  49. }
  50. int DataCondenser::GetNewestPeriodStamp(const std::string& sourceTable, int deviceId, int dataId)
  51. {
  52. std::stringstream query;
  53. query << "SELECT MAX(UNIX_TIMESTAMP(`timestamp`)) AS timestamp FROM `" << sourceTable << "` WHERE `device_id` = '" << deviceId <<"' AND `data_id` = '" << dataId << "';";
  54. auto resultSet = m_pMySQLClient->ExecuteQuery(query.str());
  55. if (resultSet.Next())
  56. return resultSet.Int("timestamp");
  57. return 0;
  58. }
  59. MySQL::MySQLResultSet DataCondenser::GetRawData(const std::string& sourceTable, int deviceId, int dataId, int newestPeriodStamp)
  60. {
  61. std::stringstream query;
  62. query << "SELECT UNIX_TIMESTAMP(`timestamp`) AS timestamp, `value` AS `min-value`, `value` AS `mean-value`, `value` AS `max-value` FROM `" << sourceTable << "` WHERE `device_id` = '" << deviceId <<"' AND `data_id` = '" << dataId << "' ";
  63. if (newestPeriodStamp == -1)
  64. query << "LIMIT 1;";
  65. else
  66. query << "AND `timestamp` > FROM_UNIXTIME(" << newestPeriodStamp << ") ORDER BY `timestamp` ASC;";
  67. return m_pMySQLClient->ExecuteQuery(query.str());
  68. }
  69. MySQL::MySQLResultSet DataCondenser::GetReducedData(const std::string& sourceTable, int deviceId, int dataId, int newestPeriodStamp)
  70. {
  71. std::stringstream query;
  72. query << "SELECT UNIX_TIMESTAMP(`timestamp`) AS timestamp, `min-value`, `mean-value`, `max-value` FROM `" << sourceTable << "` WHERE `device_id` = '" << deviceId <<"' AND `data_id` = '" << dataId << "' ";
  73. if (newestPeriodStamp == -1)
  74. query << "LIMIT 1;";
  75. else
  76. query << "AND `timestamp` > FROM_UNIXTIME(" << newestPeriodStamp << ") ORDER BY `timestamp` ASC;";
  77. return m_pMySQLClient->ExecuteQuery(query.str());
  78. }
  79. int DataCondenser::GetMaximumMySQLPacketSize()
  80. {
  81. std::stringstream query;
  82. query << "show variables like 'max_allowed_packet';";
  83. MySQL::MySQLResultSet resultSet = m_pMySQLClient->ExecuteQuery(query.str());
  84. if (resultSet.RowsCount() != 1)
  85. throw std::runtime_error("Unexpected reply when retrieving max_allowed_packet.");
  86. resultSet.Next();
  87. return resultSet.Int("Value");
  88. }
  89. DataType::type DataCondenser::GetDataType(int deviceId, int dataId)
  90. {
  91. auto resultSet = GetRawData("datalog", deviceId, dataId, -1);
  92. if (resultSet.Next())
  93. return DataInterface::GetDataType(resultSet.String("mean-value"));
  94. return DataType::None;
  95. }
  96. std::string DataCondenser::GetSourceTable(const RRA::type& rra)
  97. {
  98. switch (rra)
  99. {
  100. case RRA::Daily:
  101. return "datalog";
  102. case RRA::Weekly:
  103. return "datalog";
  104. case RRA::Monthly:
  105. return "datalog-weekly";
  106. case RRA::Yearly:
  107. return "datalog-monthly";
  108. default:
  109. case RRA::Raw:
  110. return std::string();
  111. }
  112. }
  113. std::string DataCondenser::GetDestinationTable(const RRA::type& rra)
  114. {
  115. switch (rra)
  116. {
  117. case RRA::Daily:
  118. return "datalog-daily";
  119. case RRA::Weekly:
  120. return "datalog-weekly";
  121. case RRA::Monthly:
  122. return "datalog-monthly";
  123. case RRA::Yearly:
  124. return "datalog-yearly";
  125. default:
  126. case RRA::Raw:
  127. return std::string();
  128. }
  129. }
  130. int DataCondenser::StringStreamSize(std::stringstream& ss)
  131. {
  132. ss.seekp(0, std::ios_base::end);
  133. return ss.tellp();
  134. }
  135. void DataCondenser::InitializeInsertQuery(std::stringstream& query, const std::string& table)
  136. {
  137. query.str("");
  138. query << "INSERT INTO `" << table << "` (`device_id`, `data_id`, `timestamp`, `min-value`, `mean-value`, `max-value`) VALUES ";
  139. }
  140. void DataCondenser::ExecuteInsertQuery(std::stringstream& query)
  141. {
  142. query.seekp(-1, std::ios_base::end);
  143. query << ";";
  144. m_pMySQLClient->Execute(query.str());
  145. }
  146. void DataCondenser::WriteReducedData(int deviceId, int dataId, const RRA::type& rra)
  147. {
  148. DataType::type dataType = GetDataType(deviceId, dataId);
  149. if (dataType == DataType::None)
  150. std::cout << " DataType: None" << std::endl;
  151. else if (dataType == DataType::Float)
  152. std::cout << " DataType: Float" << std::endl;
  153. else if (dataType == DataType::String)
  154. std::cout << " DataType: String" << std::endl;
  155. switch (dataType)
  156. {
  157. case DataType::Float:
  158. WriteReducedFloatData(deviceId, dataId, rra);
  159. break;
  160. case DataType::String:
  161. WriteReducedStringData(deviceId, dataId, rra);
  162. break;
  163. default:
  164. case DataType::None:
  165. break;
  166. }
  167. }
  168. void DataCondenser::WriteReducedFloatData(int deviceId, int dataId, const RRA::type& rra)
  169. {
  170. int maxMySQLPacketSize = GetMaximumMySQLPacketSize() - 2;
  171. std::string sourceTable = GetSourceTable(rra);
  172. std::string destinationTable = GetDestinationTable(rra);
  173. int newestSourcePeriodStamp = GetNewestPeriodStamp(sourceTable, deviceId, dataId);
  174. int newestDestinationPeriodStamp = GetNewestPeriodStamp(destinationTable, deviceId, dataId);
  175. std::cout << " DeviceID: " << deviceId << std::endl;
  176. std::cout << " DataID: " << dataId << std::endl;
  177. std::cout << " Newest Src : " << newestSourcePeriodStamp << std::endl;
  178. std::cout << " Newest Dest: " << newestDestinationPeriodStamp << std::endl;
  179. std::stringstream query;
  180. MySQL::MySQLResultSet resultSet;
  181. if (sourceTable == "datalog")
  182. resultSet = GetRawData(sourceTable, deviceId, dataId, newestDestinationPeriodStamp);
  183. else
  184. resultSet = GetReducedData(sourceTable, deviceId, dataId, newestDestinationPeriodStamp);
  185. std::cout << " Source Count: " << resultSet.RowsCount() << std::endl;
  186. int samples = 0;
  187. float min = std::numeric_limits<float>::max();
  188. float mean = 0;
  189. float max = std::numeric_limits<float>::min();
  190. int writeCount = 0;
  191. InitializeInsertQuery(query, destinationTable);
  192. std::stringstream queryPart;
  193. int periodStamp = 0;
  194. while (resultSet.Next())
  195. {
  196. int currentPeriodStamp = GetPeriodStamp(resultSet.Int("timestamp"), rra);
  197. if (currentPeriodStamp != periodStamp)
  198. {
  199. if (samples > 0)
  200. {
  201. mean = mean / samples;
  202. queryPart.str("");
  203. queryPart << "('" << deviceId << "', '" << dataId << "', FROM_UNIXTIME(" << currentPeriodStamp << "), '" << min << "', '" << mean << "', '" << max << "'),";
  204. ++writeCount;
  205. int packetSize = StringStreamSize(query) + StringStreamSize(queryPart);
  206. if (packetSize > maxMySQLPacketSize)
  207. {
  208. ExecuteInsertQuery(query);
  209. InitializeInsertQuery(query, destinationTable);
  210. std::cout << " Write Count: " << writeCount << std::endl;
  211. writeCount = 0;
  212. }
  213. query << queryPart.str();
  214. }
  215. if (currentPeriodStamp > newestSourcePeriodStamp)
  216. break;
  217. samples = 0;
  218. min = std::numeric_limits<float>::max();
  219. mean = 0;
  220. max = std::numeric_limits<float>::min();
  221. periodStamp = currentPeriodStamp;
  222. }
  223. float minValue, meanValue, maxValue;
  224. minValue = static_cast<float>(resultSet.Double("min-value"));
  225. meanValue = static_cast<float>(resultSet.Double("mean-value"));
  226. maxValue = static_cast<float>(resultSet.Double("max-value"));
  227. if (minValue < min)
  228. min = minValue;
  229. if (maxValue > max)
  230. max = maxValue;
  231. mean += meanValue;
  232. ++samples;
  233. }
  234. if (writeCount > 0)
  235. ExecuteInsertQuery(query);
  236. std::cout << " Write Count: " << writeCount << std::endl << std::endl;
  237. }
  238. void DataCondenser::WriteReducedStringData(int deviceId, int dataId, const RRA::type& rra)
  239. {
  240. int maxMySQLPacketSize = GetMaximumMySQLPacketSize() - 2;
  241. std::string sourceTable = GetSourceTable(rra);
  242. std::string destinationTable = GetDestinationTable(rra);
  243. int newestSourcePeriodStamp = GetNewestPeriodStamp(sourceTable, deviceId, dataId);
  244. int newestDestinationPeriodStamp = GetNewestPeriodStamp(destinationTable, deviceId, dataId);
  245. std::cout << " DeviceID: " << deviceId << std::endl;
  246. std::cout << " DataID: " << dataId << std::endl;
  247. std::cout << " Newest Src : " << newestSourcePeriodStamp << std::endl;
  248. std::cout << " Newest Dest: " << newestDestinationPeriodStamp << std::endl;
  249. std::stringstream query;
  250. MySQL::MySQLResultSet resultSet;
  251. if (sourceTable == "datalog")
  252. resultSet = GetRawData(sourceTable, deviceId, dataId, newestDestinationPeriodStamp);
  253. else
  254. resultSet = GetReducedData(sourceTable, deviceId, dataId, newestDestinationPeriodStamp);
  255. std::cout << " Source Count: " << resultSet.RowsCount() << std::endl;
  256. int samples = 0;
  257. std::vector<std::string> values;
  258. int writeCount = 0;
  259. InitializeInsertQuery(query, destinationTable);
  260. std::stringstream queryPart;
  261. int periodStamp = 0;
  262. while (resultSet.Next())
  263. {
  264. int currentPeriodStamp = GetPeriodStamp(resultSet.Int("timestamp"), rra);
  265. if (currentPeriodStamp != periodStamp)
  266. {
  267. if (samples > 0)
  268. {
  269. std::map<std::string, int> map;
  270. for (auto& value : values)
  271. {
  272. auto iterator = map.find(value);
  273. if (iterator == map.end())
  274. map.insert(std::pair<std::string, int>(value, 1));
  275. else
  276. map[value] += 1;
  277. }
  278. auto iterator = map.begin();
  279. for (std::map<std::string, int>::iterator it = map.begin(); it != map.end(); ++it)
  280. {
  281. if (it->second > iterator->second)
  282. iterator = it;
  283. }
  284. queryPart.str("");
  285. queryPart << "('" << deviceId << "', '" << dataId << "', FROM_UNIXTIME(" << currentPeriodStamp << "), '', '" << iterator->first << "', ''),";
  286. int packetSize = StringStreamSize(query) + StringStreamSize(queryPart);
  287. if (packetSize > maxMySQLPacketSize)
  288. {
  289. ExecuteInsertQuery(query);
  290. InitializeInsertQuery(query, destinationTable);
  291. std::cout << " Write Count: " << writeCount << std::endl;
  292. writeCount = 0;
  293. }
  294. query << queryPart.str();
  295. ++writeCount;
  296. }
  297. if (currentPeriodStamp > newestSourcePeriodStamp)
  298. break;
  299. samples = 0;
  300. values.clear();
  301. periodStamp = currentPeriodStamp;
  302. }
  303. std::string meanValue = resultSet.String("mean-value");
  304. values.push_back(meanValue);
  305. ++samples;
  306. }
  307. if (writeCount > 0)
  308. ExecuteInsertQuery(query);
  309. std::cout << " Write Count: " << writeCount << std::endl << std::endl;
  310. }
  311. void DataCondenser::CleanData()
  312. {
  313. std::cout << "Cleaning: " << std::endl;
  314. CleanData(RRA::Daily);
  315. CleanData(RRA::Weekly);
  316. CleanData(RRA::Monthly);
  317. CleanData(RRA::Yearly);
  318. }
  319. void DataCondenser::CleanData(const RRA::type& rra)
  320. {
  321. std::string table = GetDestinationTable(rra);
  322. int periodInSeconds = static_cast<int>(rra) * 400;
  323. int timestamp = Util::GetTimestamp() + Util::GetUTCOffset() - periodInSeconds;
  324. std::cout << " Cleaning " << table << " (<" << timestamp << ")" << std::endl;
  325. std::stringstream query;
  326. query << "DELETE FROM `" << table << "` WHERE `timestamp` < FROM_UNIXTIME(" << timestamp << ");";
  327. m_pMySQLClient->Execute(query.str());
  328. }
  329. } // namespace DataInterface
  330. } // namespace DataStorageInterface