DataCondenser.cpp 10 KB

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