DataCollectionManager.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  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. using System.Threading.Tasks;
  18. namespace Aitex.Core.RT.DataCollection
  19. {
  20. public class DataCollectionManager : Singleton<DataCollectionManager>, IConnection
  21. {
  22. public string Address
  23. {
  24. get { return "DB:DataCollection"; }
  25. }
  26. public bool IsConnected { get; set; }
  27. NpgsqlConnection _conn;
  28. bool _bAlive = true;
  29. Dictionary<string, Func<object>> _preSubscribedRecordedData; //for other thread to subscribe data
  30. Dictionary<string, Func<object>> _subscribedRecordedData; //internal use
  31. object _lock = new object();
  32. F_TRIG _connFailTrig = new F_TRIG();
  33. private int dataCollectionInterval;
  34. IDataCollectionCallback _callback;
  35. private string[] _modules = new string[] { "Data" };
  36. public DataCollectionManager()
  37. {
  38. _preSubscribedRecordedData = new Dictionary<string, Func<object>>();
  39. _subscribedRecordedData = new Dictionary<string, Func<object>>();
  40. dataCollectionInterval = SC.GetValue<int>("System.DataCollectionInterval");
  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. MonitorDataCenter();
  61. System.Threading.Tasks.Task.Factory.StartNew(DataRecorderThread);
  62. }
  63. public void Terminate()
  64. {
  65. _bAlive = false;
  66. }
  67. /// <summary>
  68. /// initialization
  69. /// </summary>
  70. public void SubscribeData(string dataName, string alias, Func<object> dataValue)
  71. {
  72. lock (_lock)
  73. {
  74. if (!_preSubscribedRecordedData.Keys.Contains(dataName))
  75. {
  76. _preSubscribedRecordedData[dataName] = dataValue;
  77. }
  78. }
  79. }
  80. private void MonitorDataCenter()
  81. {
  82. lock (_lock)
  83. {
  84. SortedDictionary<string, Func<object>> data = DATA.GetDBRecorderList();
  85. foreach (var item in data)
  86. {
  87. if (!_subscribedRecordedData.ContainsKey(item.Key))
  88. {
  89. object o = item.Value.Invoke();
  90. if (o == null)
  91. continue;
  92. Type dataType = o.GetType();
  93. if (dataType == typeof(Boolean) || dataType == typeof(double) || dataType == typeof(float) ||
  94. dataType == typeof(int) || dataType == typeof(ushort) || dataType == typeof(short))
  95. {
  96. _subscribedRecordedData[item.Key] = item.Value;
  97. _preSubscribedRecordedData[item.Key] = item.Value;
  98. }
  99. }
  100. }
  101. }
  102. }
  103. public bool Connect()
  104. {
  105. bool result = true;
  106. try
  107. {
  108. if (_conn != null)
  109. _conn.Close();
  110. _conn = new NpgsqlConnection(PostgresqlHelper.ConnectionString);
  111. _conn.Open();
  112. _conn.ChangeDatabase(_callback.GetDBName());
  113. EV.PostInfoLog("DataCollection", "Connected with database");
  114. //Invoke operation
  115. //EV.PostMessage("DataCollection", EventEnum.da, "Connected with database");
  116. }
  117. catch (Exception ex)
  118. {
  119. if (_conn != null)
  120. {
  121. _conn.Close();
  122. _conn = null;
  123. }
  124. result = false;
  125. EV.PostInfoLog("DataCollection", "Can not connect database");
  126. LOG.WriteExeption(ex);
  127. }
  128. IsConnected = result;
  129. return result;
  130. }
  131. public bool Disconnect()
  132. {
  133. try
  134. {
  135. if (_conn != null)
  136. {
  137. _conn.Close();
  138. _conn = null;
  139. EV.PostInfoLog("DataCollection", "Disconnected with database");
  140. }
  141. }
  142. catch (Exception ex)
  143. {
  144. LOG.WriteExeption(ex);
  145. }
  146. IsConnected = false;
  147. return true;
  148. }
  149. /// <summary>
  150. /// 重置数据库连接出错事件
  151. /// </summary>
  152. public void Reset()
  153. {
  154. _connFailTrig.CLK = false;
  155. }
  156. /// <summary>
  157. /// data recorder thread
  158. /// </summary>
  159. void DataRecorderThread()
  160. {
  161. while (_bAlive)
  162. {
  163. try
  164. {
  165. Thread.Sleep(dataCollectionInterval);
  166. _connFailTrig.CLK = IsConnected;// Connect();
  167. if (_connFailTrig.Q)
  168. {
  169. EV.PostWarningLog("DataCollection", "Can not connect with database");
  170. }
  171. if (!_connFailTrig.M)
  172. continue;
  173. //MonitorDataCenter();
  174. var moduleDataItem = new Dictionary<string, Dictionary<string, Func<object>>>();
  175. var moduleInsertSql = new Dictionary<string, string>();
  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. lock (_lock)
  184. {
  185. bool foundModule;
  186. foreach (var dataName in _subscribedRecordedData.Keys)
  187. {
  188. foundModule = false;
  189. foreach (var module in _modules)
  190. {
  191. if (dataName.StartsWith(module + "."))
  192. {
  193. moduleDataItem[module][dataName] = _subscribedRecordedData[dataName];
  194. foundModule = true;
  195. break;
  196. }
  197. }
  198. if (!foundModule)
  199. {
  200. moduleDataItem[defaultModule][dataName] = _subscribedRecordedData[dataName];
  201. }
  202. }
  203. _preSubscribedRecordedData.Clear();
  204. }
  205. }
  206. DateTime dtToday = DateTime.Now.Date;
  207. foreach (var module in _modules)
  208. {
  209. string tableName = $"{dtToday:yyyyMMdd}.{module}";
  210. UpdateTableSchema(tableName, moduleDataItem[module]);
  211. string preCreatedInsertSQL = string.Format("INSERT INTO \"{0}\"(\"time\" ", tableName);
  212. foreach (var dataName in moduleDataItem[module].Keys)
  213. {
  214. preCreatedInsertSQL += string.Format(",\"{0}\"", dataName);
  215. }
  216. preCreatedInsertSQL += ")";
  217. moduleInsertSql[module] = preCreatedInsertSQL;
  218. }
  219. //insert data into database
  220. StringBuilder sb = new StringBuilder(10000);
  221. while (_bAlive)
  222. {
  223. Thread.Sleep((int)(dataCollectionInterval * 0.99)); //for time delay in sleep function
  224. foreach (var module in _modules)
  225. {
  226. sb.Remove(0, sb.Length);
  227. sb.Append("Values(");
  228. sb.Append(DateTime.Now.Ticks.ToString());
  229. foreach (var dataName in moduleDataItem[module].Keys)
  230. {
  231. sb.Append(",");
  232. var v1 = moduleDataItem[module][dataName].Invoke();
  233. if (v1 == null)
  234. {
  235. sb.Append("0");
  236. }
  237. else
  238. {
  239. if (v1 is double || v1 is float)
  240. {
  241. double v2 = Convert.ToDouble(v1);
  242. if (double.IsNaN(v2))
  243. v2 = 0;
  244. sb.Append(v2.ToString());
  245. }
  246. else
  247. {
  248. sb.Append(v1.ToString());
  249. }
  250. }
  251. }
  252. sb.Append(");");
  253. try
  254. {
  255. if (_conn.State == System.Data.ConnectionState.Open)
  256. {
  257. NpgsqlCommand cmd = new NpgsqlCommand(moduleInsertSql[module] + sb.ToString(), _conn);
  258. cmd.ExecuteNonQuery();
  259. }
  260. else
  261. {
  262. Connect();
  263. }
  264. }
  265. catch
  266. {
  267. Connect();
  268. }
  269. }
  270. //if alert to another day, create a new table
  271. if (DateTime.Now.Date != dtToday)
  272. break;
  273. //if preSubscribed data not empty, alert current table's structure
  274. //MonitorDataCenter();
  275. if (_preSubscribedRecordedData.Count > 0)
  276. break;
  277. }//end while
  278. }//end while
  279. catch (Exception ex)
  280. {
  281. LOG.WriteExeption("数据库操作记录发生异常", ex);
  282. }
  283. }
  284. }
  285. public void ManualInsertData()
  286. {
  287. Task.Run(() =>
  288. {
  289. try
  290. {
  291. var moduleDataItem = new Dictionary<string, Dictionary<string, Func<object>>>();
  292. var moduleInsertSql = new Dictionary<string, string>();
  293. foreach (var module in _modules)
  294. {
  295. moduleDataItem[module] = new Dictionary<string, Func<object>>();
  296. }
  297. string defaultModule = _modules.Contains("System") ? "System" : (_modules.Contains("Data") ? "Data" : (_modules[0]));
  298. if (_subscribedRecordedData.Count > 0)
  299. {
  300. lock (_lock)
  301. {
  302. bool foundModule;
  303. foreach (var dataName in _subscribedRecordedData.Keys)
  304. {
  305. foundModule = false;
  306. foreach (var module in _modules)
  307. {
  308. if (dataName.StartsWith(module + "."))
  309. {
  310. moduleDataItem[module][dataName] = _subscribedRecordedData[dataName];
  311. foundModule = true;
  312. break;
  313. }
  314. }
  315. if (!foundModule)
  316. {
  317. moduleDataItem[defaultModule][dataName] = _subscribedRecordedData[dataName];
  318. }
  319. }
  320. _preSubscribedRecordedData.Clear();
  321. }
  322. }
  323. DateTime dtToday = DateTime.Now.Date;
  324. foreach (var module in _modules)
  325. {
  326. string tableName = $"{dtToday:yyyyMMdd}.{module}";
  327. UpdateTableSchema(tableName, moduleDataItem[module]);
  328. string preCreatedInsertSQL = string.Format("INSERT INTO \"{0}\"(\"time\" ", tableName);
  329. foreach (var dataName in moduleDataItem[module].Keys)
  330. {
  331. preCreatedInsertSQL += string.Format(",\"{0}\"", dataName);
  332. }
  333. preCreatedInsertSQL += ")";
  334. moduleInsertSql[module] = preCreatedInsertSQL;
  335. }
  336. StringBuilder sb = new StringBuilder(10000);
  337. foreach (var module in _modules)
  338. {
  339. sb.Remove(0, sb.Length);
  340. sb.Append("Values(");
  341. sb.Append(DateTime.Now.Ticks.ToString());
  342. foreach (var dataName in moduleDataItem[module].Keys)
  343. {
  344. sb.Append(",");
  345. var v1 = moduleDataItem[module][dataName].Invoke();
  346. if (v1 == null)
  347. {
  348. sb.Append("0");
  349. }
  350. else
  351. {
  352. if (v1 is double || v1 is float)
  353. {
  354. double v2 = Convert.ToDouble(v1);
  355. if (double.IsNaN(v2))
  356. v2 = 0;
  357. sb.Append(v2.ToString());
  358. }
  359. else
  360. {
  361. sb.Append(v1.ToString());
  362. }
  363. }
  364. }
  365. sb.Append(");");
  366. try
  367. {
  368. if (_conn.State == System.Data.ConnectionState.Open)
  369. {
  370. NpgsqlCommand cmd = new NpgsqlCommand(moduleInsertSql[module] + sb.ToString(), _conn);
  371. cmd.ExecuteNonQuery();
  372. }
  373. else
  374. {
  375. Connect();
  376. }
  377. }
  378. catch
  379. {
  380. Connect();
  381. }
  382. }
  383. }
  384. catch (Exception ex)
  385. {
  386. LOG.WriteExeption("数据库操作记录发生异常", ex);
  387. }
  388. });
  389. }
  390. private string UpdateTableSchema(string tblName, Dictionary<string, Func<object>> dataItem)
  391. {
  392. //query if table already exist?
  393. string sqlTblDefine = string.Format("select column_name from information_schema.columns where table_name = '{0}';", tblName);
  394. NpgsqlCommand cmdTblDefine = new NpgsqlCommand(sqlTblDefine, _conn);
  395. var tblDefineData = cmdTblDefine.ExecuteReader();
  396. string tblAlertString = string.Empty;
  397. List<string> colNameList = new List<string>();
  398. while (tblDefineData.Read())
  399. {
  400. for (int i = 0; i < tblDefineData.FieldCount; i++)
  401. colNameList.Add(tblDefineData[i].ToString());
  402. }
  403. tblDefineData.Close();
  404. if (colNameList.Count > 0)
  405. {
  406. //table exist
  407. foreach (var dataName in dataItem.Keys)
  408. {
  409. if (!colNameList.Contains(dataName))
  410. {
  411. var dataType = dataItem[dataName].Invoke().GetType();
  412. if (dataType == typeof(Boolean))
  413. {
  414. tblAlertString += string.Format("ALTER TABLE \"{0}\" ADD COLUMN \"{1}\" {2};", tblName, dataName, "Boolean");
  415. }
  416. else if (dataType == typeof(double) || dataType == typeof(float) || dataType == typeof(int) || dataType == typeof(ushort) || dataType == typeof(short))
  417. {
  418. tblAlertString += string.Format("ALTER TABLE \"{0}\" ADD COLUMN \"{1}\" {2};", tblName, dataName, "Real");
  419. }
  420. else
  421. {
  422. }
  423. }
  424. }
  425. if (!string.IsNullOrEmpty(tblAlertString))
  426. {
  427. try
  428. {
  429. NpgsqlCommand alertTblCmd = new NpgsqlCommand(tblAlertString, _conn);
  430. alertTblCmd.ExecuteNonQuery();
  431. }
  432. catch (Exception ex)
  433. {
  434. LOG.WriteExeption(ex);
  435. }
  436. }
  437. }
  438. else
  439. {
  440. //table not exist, auto generate a table
  441. string createTble = string.Format("CREATE TABLE \"{0}\"(Time bigint NOT NULL,", tblName);
  442. string commentStr = "";
  443. foreach (var dataName in dataItem.Keys)
  444. {
  445. Type dataType = dataItem[dataName].Invoke().GetType();
  446. if (dataType == typeof(Boolean))
  447. {
  448. createTble += string.Format("\"{0}\" Boolean,\n", dataName);
  449. }
  450. else if (dataType == typeof(double) || dataType == typeof(float) ||
  451. dataType == typeof(int) || dataType == typeof(ushort) || dataType == typeof(short))
  452. {
  453. createTble += string.Format("\"{0}\" Real,\n", dataName);
  454. }
  455. //if (!string.IsNullOrEmpty(alias) && ((dataType == typeof(Boolean)) || (dataType == typeof(double) || dataType == typeof(float) ||
  456. // dataType == typeof(int) || dataType == typeof(ushort) || dataType == typeof(short))))
  457. // commentStr += string.Format("COMMENT ON COLUMN \"{0}\".\"{1}\" IS '{2}';\n", tblName, dataName, alias);
  458. }
  459. createTble += string.Format("CONSTRAINT \"{0}_pkey\" PRIMARY KEY (Time));", tblName);
  460. createTble += string.Format("GRANT SELECT ON TABLE \"{0}\" TO postgres;", tblName);
  461. // createTble += string.Format("CREATE INDEX \"{0}_time_idx\" ON \"{0}\" USING btree (\"time\" );", tblName);
  462. createTble += commentStr;
  463. try
  464. {
  465. NpgsqlCommand cmd = new NpgsqlCommand(createTble.ToString(), _conn);
  466. cmd.ExecuteNonQuery();
  467. }
  468. catch (Exception ex1)
  469. {
  470. LOG.WriteExeption("创建数据库表格失败", ex1);
  471. throw;
  472. }
  473. }
  474. return tblName;
  475. }
  476. }
  477. }