DataCollectionManager.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using Aitex.Core.Util;
  6. using Npgsql;
  7. using System.Threading;
  8. using Aitex.Core.RT.Log;
  9. using Aitex.Core.RT.Event;
  10. using Aitex.Core.RT.DBCore;
  11. using System.IO;
  12. using Aitex.Common.Util;
  13. using Aitex.Core.RT.DataCenter;
  14. using System.Collections.Concurrent;
  15. using MECF.Framework.Common.Communications;
  16. using Aitex.Core.RT.SCCore;
  17. namespace Aitex.Core.RT.DataCollection
  18. {
  19. public class DataCollectionManager : Singleton<DataCollectionManager>, IConnection
  20. {
  21. public string Address
  22. {
  23. get { return "DB:DataCollection"; }
  24. }
  25. public bool IsConnected { get; set; }
  26. NpgsqlConnection _conn;
  27. bool _bAlive = true;
  28. Dictionary<string, Func<object>> _preSubscribedRecordedData; //for other thread to subscribe data
  29. Dictionary<string, Func<object>> _subscribedRecordedData; //internal use
  30. object _lock = new object();
  31. F_TRIG _connFailTrig = new F_TRIG();
  32. private int dataCollectionInterval;
  33. IDataCollectionCallback _callback;
  34. private string[] _modules = new string[] { "Data" };
  35. private bool _dbFailed;
  36. public DataCollectionManager()
  37. {
  38. _preSubscribedRecordedData = new Dictionary<string, Func<object>>();
  39. _subscribedRecordedData = new Dictionary<string, Func<object>>();
  40. dataCollectionInterval = SC.ContainsItem("System.DataCollectionInterval") ? SC.GetValue<int>("System.DataCollectionInterval") : 1000;
  41. }
  42. public void Initialize(IDataCollectionCallback callback)
  43. {
  44. _callback = callback == null ? new DefaultDataCollectionCallback() : callback;
  45. Connect();
  46. System.Threading.Tasks.Task.Factory.StartNew(DataRecorderThread);
  47. }
  48. public void Initialize(string[] modules, string dbName)
  49. {
  50. _callback = new DefaultDataCollectionCallback(dbName);
  51. if (modules != null && modules.Length > 0 && !string.IsNullOrEmpty(modules[0]))
  52. _modules = modules;
  53. Connect();
  54. System.Threading.Tasks.Task.Factory.StartNew(DataRecorderThread);
  55. }
  56. public void Initialize(string dbName)
  57. {
  58. _callback = new DefaultDataCollectionCallback(dbName);
  59. Connect();
  60. System.Threading.Tasks.Task.Factory.StartNew(DataRecorderThread);
  61. }
  62. public void Terminate()
  63. {
  64. _bAlive = false;
  65. }
  66. /// <summary>
  67. /// initialization
  68. /// </summary>
  69. public void SubscribeData(string dataName, string alias, Func<object> dataValue)
  70. {
  71. lock (_lock)
  72. {
  73. if (!_preSubscribedRecordedData.Keys.Contains(dataName))
  74. {
  75. _preSubscribedRecordedData[dataName] = dataValue;
  76. }
  77. }
  78. }
  79. private void MonitorDataCenter()
  80. {
  81. lock (_lock)
  82. {
  83. SortedDictionary<string, Func<object>> data = DATA.GetDBRecorderList();
  84. foreach (var item in data)
  85. {
  86. if (!_subscribedRecordedData.ContainsKey(item.Key))
  87. {
  88. object o = item.Value.Invoke();
  89. if (o == null)
  90. continue;
  91. Type dataType = o.GetType();
  92. if (dataType == typeof(Boolean) || dataType == typeof(double) || dataType == typeof(float) ||
  93. dataType == typeof(int) || dataType == typeof(ushort) || dataType == typeof(short))
  94. {
  95. _subscribedRecordedData[item.Key] = item.Value;
  96. _preSubscribedRecordedData[item.Key] = item.Value;
  97. }
  98. }
  99. }
  100. }
  101. }
  102. public bool Connect()
  103. {
  104. bool result = true;
  105. try
  106. {
  107. if (_conn != null)
  108. _conn.Close();
  109. _conn = new NpgsqlConnection(PostgresqlHelper.ConnectionString);
  110. _conn.Open();
  111. _conn.ChangeDatabase(_callback.GetDBName());
  112. EV.PostInfoLog("DataCollection", "Connected with database");
  113. }
  114. catch (Exception ex)
  115. {
  116. if (_conn != null)
  117. {
  118. _conn.Close();
  119. _conn = null;
  120. }
  121. result = false;
  122. EV.PostInfoLog("DataCollection", "Can not connect database");
  123. LOG.Write(ex);
  124. }
  125. IsConnected = result;
  126. return result;
  127. }
  128. public bool Disconnect()
  129. {
  130. try
  131. {
  132. if (_conn != null)
  133. {
  134. _conn.Close();
  135. _conn = null;
  136. EV.PostInfoLog("DataCollection", "Disconnected with database");
  137. }
  138. }
  139. catch (Exception ex)
  140. {
  141. LOG.Write(ex);
  142. }
  143. IsConnected = false;
  144. return true;
  145. }
  146. /// <summary>
  147. /// 重置数据库连接出错事件
  148. /// </summary>
  149. public void Reset()
  150. {
  151. _connFailTrig.CLK = false;
  152. }
  153. /// <summary>
  154. /// data recorder thread
  155. /// </summary>
  156. void DataRecorderThread()
  157. {
  158. while (_bAlive)
  159. {
  160. try
  161. {
  162. // Thread.Sleep(dataCollectionInterval);
  163. _connFailTrig.CLK = IsConnected;// Connect();
  164. if (_connFailTrig.Q)
  165. {
  166. EV.PostWarningLog("DataCollection", "Can not connect with database");
  167. }
  168. if (!_connFailTrig.M)
  169. continue;
  170. MonitorDataCenter();
  171. DateTime dtToday = DateTime.Now.Date;
  172. var moduleDataItem = new Dictionary<string, Dictionary<string, Func<object>>>();
  173. var moduleInsertSql = new Dictionary<string, string>();
  174. lock (_lock)
  175. {
  176. foreach (var module in _modules)
  177. {
  178. moduleDataItem[module] = new Dictionary<string, Func<object>>();
  179. }
  180. string defaultModule = _modules.Contains("System") ? "System" : (_modules.Contains("Data") ? "Data" : (_modules[0]));
  181. if (_subscribedRecordedData.Count > 0)
  182. {
  183. bool foundModule;
  184. foreach (var dataName in _subscribedRecordedData.Keys)
  185. {
  186. foundModule = false;
  187. foreach (var module in _modules)
  188. {
  189. if (dataName.StartsWith(module + "."))
  190. {
  191. moduleDataItem[module][dataName] = _subscribedRecordedData[dataName];
  192. foundModule = true;
  193. break;
  194. }
  195. if (dataName.StartsWith(module + "_"))
  196. {
  197. moduleDataItem[module][dataName] = _subscribedRecordedData[dataName];
  198. foundModule = true;
  199. break;
  200. }
  201. }
  202. if (!foundModule)
  203. {
  204. moduleDataItem[defaultModule][dataName] = _subscribedRecordedData[dataName];
  205. }
  206. }
  207. _preSubscribedRecordedData.Clear();
  208. }
  209. foreach (var module in _modules)
  210. {
  211. string tableName = $"{dtToday:yyyyMMdd}.{module}";
  212. UpdateTableSchema(tableName, moduleDataItem[module]);
  213. string preCreatedInsertSQL = string.Format("INSERT INTO \"{0}\"(\"time\" ", tableName);
  214. foreach (var dataName in moduleDataItem[module].Keys)
  215. {
  216. preCreatedInsertSQL += string.Format(",\"{0}\"", dataName);
  217. }
  218. preCreatedInsertSQL += ")";
  219. moduleInsertSql[module] = preCreatedInsertSQL;
  220. }
  221. }
  222. //insert data into database
  223. StringBuilder sb = new StringBuilder(10000);
  224. while (_bAlive)
  225. {
  226. //Thread.Sleep(990);
  227. //Thread.Sleep((int)(dataCollectionInterval * 0.99)); //for time delay in sleep function
  228. //if alert to another day, create a new table
  229. if (DateTime.Now.Date != dtToday)
  230. break;
  231. foreach (var module in _modules)
  232. {
  233. sb.Remove(0, sb.Length);
  234. sb.Append("Values(");
  235. sb.Append(DateTime.Now.Ticks.ToString());
  236. foreach (var dataName in moduleDataItem[module].Keys)
  237. {
  238. sb.Append(",");
  239. var v1 = moduleDataItem[module][dataName].Invoke();
  240. if (v1 == null)
  241. {
  242. sb.Append("0");
  243. }
  244. else
  245. {
  246. if (v1 is double || v1 is float)
  247. {
  248. double v2 = Convert.ToDouble(v1);
  249. if (double.IsNaN(v2))
  250. v2 = 0;
  251. sb.Append(v2.ToString());
  252. }
  253. else
  254. {
  255. sb.Append(v1.ToString());
  256. }
  257. }
  258. }
  259. sb.Append(");");
  260. NpgsqlCommand cmd = new NpgsqlCommand(moduleInsertSql[module] + sb.ToString(), _conn);
  261. try
  262. {
  263. cmd.ExecuteNonQuery();
  264. _dbFailed = false;
  265. }
  266. catch (Exception ex)
  267. {
  268. if (!_dbFailed)
  269. {
  270. LOG.Write(ex, "数据记录发生异常" + moduleInsertSql[module]);
  271. _dbFailed = true;
  272. }
  273. }
  274. }
  275. //if preSubscribed data not empty, alert current table's structure
  276. MonitorDataCenter();
  277. if (_preSubscribedRecordedData.Count > 0)
  278. break;
  279. Thread.Sleep((int)(dataCollectionInterval * 0.99));
  280. }//end while
  281. _dbFailed = false;
  282. }//end while
  283. catch (Exception ex)
  284. {
  285. if (!_dbFailed)
  286. {
  287. LOG.Write(ex, "数据库操作记录发生异常");
  288. _dbFailed = true;
  289. }
  290. }
  291. }
  292. }
  293. private string UpdateTableSchema(string tblName, Dictionary<string, Func<object>> dataItem)
  294. {
  295. //query if table already exist?
  296. string sqlTblDefine = string.Format("select column_name from information_schema.columns where table_name = '{0}';", tblName);
  297. NpgsqlCommand cmdTblDefine = new NpgsqlCommand(sqlTblDefine, _conn);
  298. var tblDefineData = cmdTblDefine.ExecuteReader();
  299. string tblAlertString = string.Empty;
  300. List<string> colNameList = new List<string>();
  301. while (tblDefineData.Read())
  302. {
  303. for (int i = 0; i < tblDefineData.FieldCount; i++)
  304. colNameList.Add(tblDefineData[i].ToString());
  305. }
  306. tblDefineData.Close();
  307. if (colNameList.Count > 0)
  308. {
  309. //table exist
  310. foreach (var dataName in dataItem.Keys)
  311. {
  312. if (!colNameList.Contains(dataName))
  313. {
  314. var dataType = dataItem[dataName].Invoke().GetType();
  315. if (dataType == typeof(Boolean))
  316. {
  317. tblAlertString += string.Format("ALTER TABLE \"{0}\" ADD COLUMN \"{1}\" {2};", tblName, dataName, "Boolean");
  318. }
  319. else if (dataType == typeof(double) || dataType == typeof(float) || dataType == typeof(int) || dataType == typeof(ushort) || dataType == typeof(short))
  320. {
  321. tblAlertString += string.Format("ALTER TABLE \"{0}\" ADD COLUMN \"{1}\" {2};", tblName, dataName, "Real");
  322. }
  323. else
  324. {
  325. }
  326. }
  327. }
  328. if (!string.IsNullOrEmpty(tblAlertString))
  329. {
  330. try
  331. {
  332. NpgsqlCommand alertTblCmd = new NpgsqlCommand(tblAlertString, _conn);
  333. alertTblCmd.ExecuteNonQuery();
  334. _dbFailed = false;
  335. }
  336. catch (Exception ex)
  337. {
  338. if (!_dbFailed)
  339. {
  340. LOG.Write(ex);
  341. _dbFailed = true;
  342. }
  343. }
  344. }
  345. }
  346. else
  347. {
  348. //table not exist, auto generate a table
  349. string createTble = string.Format("CREATE TABLE \"{0}\"(Time bigint NOT NULL,", tblName);
  350. string commentStr = "";
  351. foreach (var dataName in dataItem.Keys)
  352. {
  353. Type dataType = dataItem[dataName].Invoke().GetType();
  354. if (dataType == typeof(Boolean))
  355. {
  356. createTble += string.Format("\"{0}\" Boolean,\n", dataName);
  357. }
  358. else if (dataType == typeof(double) || dataType == typeof(float) ||
  359. dataType == typeof(int) || dataType == typeof(ushort) || dataType == typeof(short))
  360. {
  361. createTble += string.Format("\"{0}\" Real,\n", dataName);
  362. }
  363. //if (!string.IsNullOrEmpty(alias) && ((dataType == typeof(Boolean)) || (dataType == typeof(double) || dataType == typeof(float) ||
  364. // dataType == typeof(int) || dataType == typeof(ushort) || dataType == typeof(short))))
  365. // commentStr += string.Format("COMMENT ON COLUMN \"{0}\".\"{1}\" IS '{2}';\n", tblName, dataName, alias);
  366. }
  367. createTble += string.Format("CONSTRAINT \"{0}_pkey\" PRIMARY KEY (Time));", tblName);
  368. createTble += string.Format("GRANT SELECT ON TABLE \"{0}\" TO postgres;", tblName);
  369. // createTble += string.Format("CREATE INDEX \"{0}_time_idx\" ON \"{0}\" USING btree (\"time\" );", tblName);
  370. createTble += commentStr;
  371. try
  372. {
  373. NpgsqlCommand cmd = new NpgsqlCommand(createTble.ToString(), _conn);
  374. cmd.ExecuteNonQuery();
  375. _dbFailed = false;
  376. }
  377. catch (Exception ex1)
  378. {
  379. if (!_dbFailed)
  380. {
  381. LOG.Write(ex1, "创建数据库表格失败");
  382. _dbFailed = true;
  383. //throw;
  384. }
  385. }
  386. }
  387. return tblName;
  388. }
  389. }
  390. }