DataCollectionManager.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  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. public DataCollectionManager()
  36. {
  37. _preSubscribedRecordedData = new Dictionary<string, Func<object>>();
  38. _subscribedRecordedData = new Dictionary<string, Func<object>>();
  39. dataCollectionInterval = SC.GetValue<int>("System.DataCollectionInterval");
  40. }
  41. public void Initialize(IDataCollectionCallback callback)
  42. {
  43. _callback = callback == null ? new DefaultDataCollectionCallback() : callback;
  44. Connect();
  45. System.Threading.Tasks.Task.Factory.StartNew(DataRecorderThread);
  46. }
  47. public void Initialize(string[] modules, string dbName)
  48. {
  49. _callback = new DefaultDataCollectionCallback(dbName);
  50. if (modules != null && modules.Length > 0 && !string.IsNullOrEmpty(modules[0]))
  51. _modules = modules;
  52. Connect();
  53. System.Threading.Tasks.Task.Factory.StartNew(DataRecorderThread);
  54. }
  55. public void Initialize(string dbName)
  56. {
  57. _callback = new DefaultDataCollectionCallback(dbName);
  58. Connect();
  59. MonitorDataCenter();
  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. //Invoke operation
  114. //EV.PostMessage("DataCollection", EventEnum.da, "Connected with database");
  115. }
  116. catch (Exception ex)
  117. {
  118. if (_conn != null)
  119. {
  120. _conn.Close();
  121. _conn = null;
  122. }
  123. result = false;
  124. EV.PostInfoLog("DataCollection", "Can not connect database");
  125. LOG.WriteExeption(ex);
  126. }
  127. IsConnected = result;
  128. return result;
  129. }
  130. public bool Disconnect()
  131. {
  132. try
  133. {
  134. if (_conn != null)
  135. {
  136. _conn.Close();
  137. _conn = null;
  138. EV.PostInfoLog("DataCollection", "Disconnected with database");
  139. }
  140. }
  141. catch (Exception ex)
  142. {
  143. LOG.WriteExeption(ex);
  144. }
  145. IsConnected = false;
  146. return true;
  147. }
  148. /// <summary>
  149. /// 重置数据库连接出错事件
  150. /// </summary>
  151. public void Reset()
  152. {
  153. _connFailTrig.CLK = false;
  154. }
  155. /// <summary>
  156. /// data recorder thread
  157. /// </summary>
  158. void DataRecorderThread()
  159. {
  160. while (_bAlive)
  161. {
  162. try
  163. {
  164. Thread.Sleep(dataCollectionInterval);
  165. _connFailTrig.CLK = IsConnected;// Connect();
  166. if (_connFailTrig.Q)
  167. {
  168. EV.PostWarningLog("DataCollection", "Can not connect with database");
  169. }
  170. if (!_connFailTrig.M)
  171. continue;
  172. //MonitorDataCenter();
  173. var moduleDataItem = new Dictionary<string, Dictionary<string, Func<object>>>();
  174. var moduleInsertSql = new Dictionary<string, string>();
  175. foreach (var module in _modules)
  176. {
  177. moduleDataItem[module] = new Dictionary<string, Func<object>>();
  178. }
  179. string defaultModule = _modules.Contains("System") ? "System" : (_modules.Contains("Data") ? "Data" : (_modules[0]));
  180. if (_subscribedRecordedData.Count > 0)
  181. {
  182. lock (_lock)
  183. {
  184. bool foundModule;
  185. foreach (var dataName in _subscribedRecordedData.Keys)
  186. {
  187. foundModule = false;
  188. foreach (var module in _modules)
  189. {
  190. if (dataName.StartsWith(module + "."))
  191. {
  192. moduleDataItem[module][dataName] = _subscribedRecordedData[dataName];
  193. foundModule = true;
  194. break;
  195. }
  196. }
  197. if (!foundModule)
  198. {
  199. moduleDataItem[defaultModule][dataName] = _subscribedRecordedData[dataName];
  200. }
  201. }
  202. _preSubscribedRecordedData.Clear();
  203. }
  204. }
  205. DateTime dtToday = DateTime.Now.Date;
  206. foreach (var module in _modules)
  207. {
  208. string tableName = $"{dtToday:yyyyMMdd}.{module}";
  209. UpdateTableSchema(tableName, moduleDataItem[module]);
  210. string preCreatedInsertSQL = string.Format("INSERT INTO \"{0}\"(\"time\" ", tableName);
  211. foreach (var dataName in moduleDataItem[module].Keys)
  212. {
  213. preCreatedInsertSQL += string.Format(",\"{0}\"", dataName);
  214. }
  215. preCreatedInsertSQL += ")";
  216. moduleInsertSql[module] = preCreatedInsertSQL;
  217. }
  218. //insert data into database
  219. StringBuilder sb = new StringBuilder(10000);
  220. while (_bAlive)
  221. {
  222. //Thread.Sleep(990);
  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. //try
  270. //{
  271. //}
  272. //catch (Exception ex)
  273. //{
  274. // LOG.WriteExeption("数据记录发生异常" + moduleInsertSql[module], ex);
  275. //}
  276. }
  277. //if alert to another day, create a new table
  278. if (DateTime.Now.Date != dtToday)
  279. break;
  280. //if preSubscribed data not empty, alert current table's structure
  281. //MonitorDataCenter();
  282. if (_preSubscribedRecordedData.Count > 0)
  283. break;
  284. }//end while
  285. }//end while
  286. catch (Exception ex)
  287. {
  288. LOG.WriteExeption("数据库操作记录发生异常", ex);
  289. }
  290. }
  291. }
  292. public void InserData()
  293. {
  294. }
  295. private string UpdateTableSchema(string tblName, Dictionary<string, Func<object>> dataItem)
  296. {
  297. //query if table already exist?
  298. string sqlTblDefine = string.Format("select column_name from information_schema.columns where table_name = '{0}';", tblName);
  299. NpgsqlCommand cmdTblDefine = new NpgsqlCommand(sqlTblDefine, _conn);
  300. var tblDefineData = cmdTblDefine.ExecuteReader();
  301. string tblAlertString = string.Empty;
  302. List<string> colNameList = new List<string>();
  303. while (tblDefineData.Read())
  304. {
  305. for (int i = 0; i < tblDefineData.FieldCount; i++)
  306. colNameList.Add(tblDefineData[i].ToString());
  307. }
  308. tblDefineData.Close();
  309. if (colNameList.Count > 0)
  310. {
  311. //table exist
  312. foreach (var dataName in dataItem.Keys)
  313. {
  314. if (!colNameList.Contains(dataName))
  315. {
  316. var dataType = dataItem[dataName].Invoke().GetType();
  317. if (dataType == typeof(Boolean))
  318. {
  319. tblAlertString += string.Format("ALTER TABLE \"{0}\" ADD COLUMN \"{1}\" {2};", tblName, dataName, "Boolean");
  320. }
  321. else if (dataType == typeof(double) || dataType == typeof(float) || dataType == typeof(int) || dataType == typeof(ushort) || dataType == typeof(short))
  322. {
  323. tblAlertString += string.Format("ALTER TABLE \"{0}\" ADD COLUMN \"{1}\" {2};", tblName, dataName, "Real");
  324. }
  325. else
  326. {
  327. }
  328. }
  329. }
  330. if (!string.IsNullOrEmpty(tblAlertString))
  331. {
  332. try
  333. {
  334. NpgsqlCommand alertTblCmd = new NpgsqlCommand(tblAlertString, _conn);
  335. alertTblCmd.ExecuteNonQuery();
  336. }
  337. catch (Exception ex)
  338. {
  339. LOG.WriteExeption(ex);
  340. }
  341. }
  342. }
  343. else
  344. {
  345. //table not exist, auto generate a table
  346. string createTble = string.Format("CREATE TABLE \"{0}\"(Time bigint NOT NULL,", tblName);
  347. string commentStr = "";
  348. foreach (var dataName in dataItem.Keys)
  349. {
  350. Type dataType = dataItem[dataName].Invoke().GetType();
  351. if (dataType == typeof(Boolean))
  352. {
  353. createTble += string.Format("\"{0}\" Boolean,\n", dataName);
  354. }
  355. else if (dataType == typeof(double) || dataType == typeof(float) ||
  356. dataType == typeof(int) || dataType == typeof(ushort) || dataType == typeof(short))
  357. {
  358. createTble += string.Format("\"{0}\" Real,\n", dataName);
  359. }
  360. //if (!string.IsNullOrEmpty(alias) && ((dataType == typeof(Boolean)) || (dataType == typeof(double) || dataType == typeof(float) ||
  361. // dataType == typeof(int) || dataType == typeof(ushort) || dataType == typeof(short))))
  362. // commentStr += string.Format("COMMENT ON COLUMN \"{0}\".\"{1}\" IS '{2}';\n", tblName, dataName, alias);
  363. }
  364. createTble += string.Format("CONSTRAINT \"{0}_pkey\" PRIMARY KEY (Time));", tblName);
  365. createTble += string.Format("GRANT SELECT ON TABLE \"{0}\" TO postgres;", tblName);
  366. // createTble += string.Format("CREATE INDEX \"{0}_time_idx\" ON \"{0}\" USING btree (\"time\" );", tblName);
  367. createTble += commentStr;
  368. try
  369. {
  370. NpgsqlCommand cmd = new NpgsqlCommand(createTble.ToString(), _conn);
  371. cmd.ExecuteNonQuery();
  372. }
  373. catch (Exception ex1)
  374. {
  375. LOG.WriteExeption("创建数据库表格失败", ex1);
  376. throw;
  377. }
  378. }
  379. return tblName;
  380. }
  381. }
  382. }