DataCollectionManager.cs 21 KB

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