ab93fce535bbb40e66ea7e3080a3a7b466c8f08e.svn-base 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Collections;
  5. using System.Diagnostics;
  6. using System.Runtime.InteropServices;
  7. using Core.Mes.Common;
  8. using Core.Mes.ServerFrameWork;
  9. using System.Threading;
  10. using System.IO;
  11. using System.Management;
  12. using System.Data;
  13. using System.Security.Cryptography;
  14. using System.Windows.Forms.DataVisualization.Charting;
  15. namespace Core.Mes.ServerFrameWork
  16. {
  17. public class ResDaemon : IDisposable
  18. {
  19. private bool disposed = false;
  20. private string filePath = System.Environment.CurrentDirectory + @"\log\Daemon\";
  21. private object lockObj = new object();
  22. private FileStream daemon_fs = null;
  23. private FileStream read_fs = null;
  24. private ManualResetEvent _RunningEvent = new ManualResetEvent(false);
  25. public delegate void ShowResDataEvent(List<DataPoint> ps1, List<DataPoint> ps2);
  26. private TimeSpan prevCpuTime = TimeSpan.Zero;
  27. private DateTime prevTime = DateTime.Now;
  28. public void GetMemoryUsed(out double MemUsedMB, out double CpuUsed, out DateTime curTime)
  29. {
  30. const int MB_DIV = 1024 * 1024;
  31. Process cur = Process.GetCurrentProcess();
  32. PerformanceCounter curpc = new PerformanceCounter("Process", "Working Set", cur.ProcessName);
  33. MemUsedMB = curpc.NextValue() / MB_DIV;
  34. curTime = DateTime.Now;
  35. if (prevCpuTime == TimeSpan.Zero)
  36. {
  37. CpuUsed = 0;
  38. prevTime = curTime;
  39. prevCpuTime = cur.TotalProcessorTime;
  40. return;
  41. }
  42. TimeSpan ts1 = new TimeSpan(curTime.Ticks);
  43. TimeSpan ts2 = new TimeSpan(prevTime.Ticks);
  44. double interval = ts1.Subtract(ts2).Duration().TotalMilliseconds;
  45. TimeSpan curCpuTime = cur.TotalProcessorTime;
  46. CpuUsed = (curCpuTime - prevCpuTime).TotalMilliseconds / interval / Environment.ProcessorCount * 100;
  47. prevCpuTime = curCpuTime;
  48. prevTime = curTime;
  49. // Debug.Print(string.Format("MEM: {0} MB CPU: {1}", MemUsedMB, CpuUsed));
  50. }
  51. public void GetSysFreeMem(out double FreeMemMB)
  52. {
  53. SystemInfo sys = new SystemInfo();
  54. FreeMemMB = sys.MemoryAvailable / 1024 / 1024;
  55. }
  56. public void StartDaemon()
  57. {
  58. Thread daemon_thread = new Thread(DaemonResFunc);
  59. daemon_thread.Name = "资源监控实时存档";
  60. daemon_thread.Start();
  61. }
  62. #region 系统资源监控
  63. private void DaemonResFunc()
  64. {
  65. DateTime curTime;
  66. double memUsed = 0;
  67. double cpuUsed = 0;
  68. GetMemoryUsed(out memUsed, out cpuUsed, out curTime);
  69. if (!Directory.Exists(filePath))
  70. {
  71. Directory.CreateDirectory(filePath);
  72. }
  73. string logFile = Path.Combine(filePath, "DM_" + curTime.ToString("yyyyMMdd") + ".dat");
  74. daemon_fs = new FileStream(logFile, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read);
  75. do
  76. {
  77. WriteResData(filePath, daemon_fs);
  78. Thread.Sleep(1000);
  79. } while (true);
  80. }
  81. DateTime prev_WriteFileDate = new DateTime(2000, 1, 1);
  82. private void WriteResData(string _filePath, FileStream fs)
  83. {
  84. string logFile = "";
  85. lock (lockObj)
  86. {
  87. try
  88. {
  89. DateTime curTime;
  90. double memUsed = 0;
  91. double cpuUsed = 0;
  92. GetMemoryUsed(out memUsed, out cpuUsed, out curTime);
  93. if (prev_ReadFileDate.Date != curTime.Date)
  94. {
  95. if (fs != null)
  96. {
  97. fs.Close();
  98. }
  99. if (!Directory.Exists(_filePath))
  100. {
  101. Directory.CreateDirectory(_filePath);
  102. }
  103. logFile = Path.Combine(_filePath, "DM_" + curTime.ToString("yyyyMMdd") + ".dat");
  104. daemon_fs = new FileStream(logFile, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read);
  105. }
  106. try
  107. {
  108. int offset = (sizeof(double) + sizeof(double)) * (curTime.Hour * 60 * 60 + curTime.Minute * 60 + curTime.Second);
  109. byte[] s1 = System.BitConverter.GetBytes(memUsed);
  110. byte[] s2 = System.BitConverter.GetBytes(cpuUsed);
  111. daemon_fs.Seek(offset, SeekOrigin.Begin);
  112. daemon_fs.Write(s1, 0, s1.GetLength(0));
  113. daemon_fs.Write(s2, 0, s2.GetLength(0));
  114. daemon_fs.Flush();
  115. prev_WriteFileDate = curTime;
  116. }
  117. catch (Exception ex) { Debug.Print(ex.Message); }
  118. }
  119. catch
  120. {
  121. // do nothing.
  122. }
  123. }
  124. }
  125. public DataTable DaemonResData(DateTime curDate, int count, int interval)
  126. {
  127. if (count < 1) count = 1;
  128. if (interval < 1) interval = 1;
  129. DateTime idx_date = curDate.AddSeconds(-1 * (count - 1) * interval);
  130. DateTime prev_Date = idx_date.Date;
  131. string logFile = Path.Combine(filePath, "DM_" + curDate.ToString("yyyyMMdd") + ".dat");
  132. DataTable table = new DataTable();
  133. table.Columns.Add("Time", typeof(DateTime));
  134. table.Columns.Add("MemUsed", typeof(double));
  135. table.Columns.Add("CpuUsed", typeof(double));
  136. table.Columns.Add("EMPTY", typeof(int));
  137. do
  138. {
  139. getFile(idx_date);
  140. if (read_fs != null)
  141. {
  142. double d_memUsed = 0;
  143. double d_cpuUsed = 0;
  144. byte[] data1 = new byte[sizeof(double)];
  145. byte[] data2 = new byte[sizeof(double)];
  146. try
  147. {
  148. read_fs.Seek((idx_date.Hour * 60 * 60 + idx_date.Minute * 60 + idx_date.Second) * (sizeof(double) + sizeof(double)), SeekOrigin.Begin);
  149. read_fs.Read(data1, 0, sizeof(double));
  150. read_fs.Read(data2, 0, sizeof(double));
  151. d_memUsed = System.BitConverter.ToDouble(data1, 0);
  152. d_cpuUsed = System.BitConverter.ToDouble(data2, 0);
  153. }
  154. catch { }
  155. DataRow dr = table.NewRow();
  156. dr[0] = idx_date;
  157. dr[1] = d_memUsed;
  158. dr[2] = d_cpuUsed;
  159. if (d_memUsed < 0.00001)
  160. {
  161. dr[3] = 0;
  162. if (table.Rows.Count > 0 && (int)(table.Rows[table.Rows.Count - 1][3]) == 1)
  163. {
  164. dr[1] = table.Rows[table.Rows.Count - 1][1];
  165. dr[2] = table.Rows[table.Rows.Count - 1][2];
  166. }
  167. }
  168. else
  169. {
  170. dr[3] = 1;
  171. }
  172. table.Rows.Add(dr);
  173. }
  174. idx_date = idx_date.AddSeconds(interval);
  175. } while (idx_date <= curDate);
  176. table.AcceptChanges();
  177. return table;
  178. }
  179. DateTime prev_ReadFileDate = new DateTime(2000, 1, 1);
  180. private void getFile(DateTime cur_Date)
  181. {
  182. string logFile = Path.Combine(filePath, "DM_" + cur_Date.ToString("yyyyMMdd") + ".dat");
  183. if (cur_Date.Date == prev_ReadFileDate.Date)
  184. {
  185. if (read_fs == null && File.Exists(logFile))
  186. {
  187. read_fs = new FileStream(logFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
  188. }
  189. }
  190. else
  191. {
  192. if (read_fs != null)
  193. {
  194. read_fs.Close();
  195. }
  196. read_fs = null;
  197. if (File.Exists(logFile))
  198. {
  199. read_fs = new FileStream(logFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
  200. }
  201. }
  202. prev_ReadFileDate = cur_Date;
  203. }
  204. public void SuspendMe()
  205. {
  206. _RunningEvent.Reset();
  207. }
  208. public void ResumeMe()
  209. {
  210. _RunningEvent.Set();
  211. }
  212. public void ShowResData(Chart ctl_chart, ShowResDataEvent srde)
  213. {
  214. do
  215. {
  216. _RunningEvent.WaitOne();
  217. List<DataPoint> s1 = new List<DataPoint>();
  218. List<DataPoint> s2 = new List<DataPoint>();
  219. if (ctl_chart.Series[0].Points.Count > 0)
  220. {
  221. foreach (DataPoint dp in ctl_chart.Series[0].Points)
  222. {
  223. s1.Add(dp);
  224. }
  225. }
  226. if (ctl_chart.Series[1].Points.Count > 0)
  227. {
  228. foreach (DataPoint dp in ctl_chart.Series[1].Points)
  229. {
  230. s2.Add(dp);
  231. }
  232. }
  233. int Interval = 2000;
  234. DataTable datas = DaemonResData(DateTime.Now.AddSeconds(-1), 100, Interval / 1000);
  235. if (s1 != null && s1.Count > 0 && datas.Rows.Count > 0)
  236. {
  237. if (((DateTime)(datas.Rows[0][0])).CompareTo((DateTime)(s1[0].Tag)) < 0)
  238. {
  239. s1.Clear();
  240. s2.Clear();
  241. }
  242. }
  243. if (s1.Count == 0)
  244. {
  245. foreach (DataRow dr in datas.Rows)
  246. {
  247. DataPoint dp1 = new DataPoint();
  248. dp1.SetValueXY((DateTime)dr[0], (double)dr[1]);
  249. dp1.Tag = (DateTime)dr[0];
  250. s1.Add(dp1);
  251. DataPoint dp2 = new DataPoint();
  252. dp2.SetValueXY((DateTime)dr[0], (double)dr[2]);
  253. dp2.Tag = (DateTime)dr[0];
  254. s2.Add(dp2);
  255. //Debug.Print(string.Format("READ MEM:{0} CPU:{1}", dp1.YValues[0], dp2.YValues[0]));
  256. }
  257. }
  258. else
  259. {
  260. string str_date = ((DateTime)(s1[s1.Count - 1].Tag)).ToString("yyyy-MM-dd HH:mm:ss");
  261. DataRow[] drs = datas.Select(string.Format("TIME > CONVERT( '{0}','System.DateTime')", str_date), "TIME");
  262. foreach (DataRow dr in drs)
  263. {
  264. DataPoint dp1 = new DataPoint();
  265. dp1.SetValueXY((DateTime)dr[0], (double)dr[1]);
  266. dp1.Tag = (DateTime)dr[0];
  267. s1.Add(dp1);
  268. DataPoint dp2 = new DataPoint();
  269. dp2.SetValueXY((DateTime)dr[0], (double)dr[2]);
  270. dp2.Tag = (DateTime)dr[0];
  271. s2.Add(dp2);
  272. //Debug.Print(string.Format("READ MEM:{0} CPU:{1}", dp1.YValues[0], dp2.YValues[0]));
  273. s1.RemoveAt(0);
  274. s2.RemoveAt(0);
  275. }
  276. }
  277. if (srde != null)
  278. {
  279. srde.Invoke(s1, s2);
  280. }
  281. Thread.Sleep(2000);
  282. } while (true);
  283. }
  284. #endregion
  285. public void Dispose()
  286. {
  287. if (!disposed)
  288. {
  289. if (daemon_fs != null)
  290. {
  291. daemon_fs.Close();
  292. }
  293. if (read_fs != null)
  294. {
  295. read_fs.Close();
  296. }
  297. disposed = true;
  298. }
  299. }
  300. }
  301. public class SrvDaemon //: IDisposable
  302. {
  303. private ManualResetEvent _RunningEvent = new ManualResetEvent(false);
  304. public delegate void ShowSrvDataEvent(List<DataPoint> ps1, List<DataPoint> ps2);
  305. private object obj_lock = new object();
  306. private FileStream write_fs = null;
  307. private string filePath = System.Environment.CurrentDirectory + @"\log\Daemon\";
  308. private Hashtable HtAssemblyServer = null;
  309. private Hashtable _srvClassManager = new Hashtable();
  310. private Hashtable _srvUsedManager = new Hashtable();
  311. public Hashtable SrvClassManager
  312. {
  313. get { return _srvClassManager; }
  314. }
  315. public SrvDaemon(Hashtable HtServers)
  316. {
  317. HtAssemblyServer = HtServers;
  318. InitSrvDaemon();
  319. }
  320. private void InitSrvDaemon()
  321. {
  322. if (HtAssemblyServer == null) return;
  323. foreach (string serverName in HtAssemblyServer.Keys)
  324. {
  325. IServerPool sPool = (IServerPool)HtAssemblyServer[serverName];
  326. foreach (string className in sPool.HtComponent.Keys)
  327. {
  328. GetSrvClsInfo(serverName, className, "");
  329. sPool.srvDaemon = this;
  330. }
  331. }
  332. }
  333. public SrvClassInfo GetSrvClsInfo(string serverName, string className, string methodName)
  334. {
  335. SrvClassInfo svi = null;
  336. string _sName = serverName.Trim().ToUpper();
  337. string _cName = string.IsNullOrEmpty(className.Trim().ToUpper()) ? "" : ("." + className.Trim().ToUpper());
  338. string _mName = string.IsNullOrEmpty(methodName.Trim().ToUpper()) ? "" : ("." + methodName.Trim().ToUpper());
  339. string _name = _sName + _cName + _mName;
  340. if (!_srvClassManager.ContainsKey(_name))
  341. {
  342. svi = new SrvClassInfo();
  343. svi.ServerName = serverName.ToUpper();
  344. svi.ClassName = className.ToUpper();
  345. svi.AvgMemUsed = 30;
  346. svi.TotalCalled = 0;
  347. svi.MethodName = "";
  348. svi.SrvEvents = new LinkedList<SrvEventItem>();
  349. _srvClassManager.Add(_name, svi);
  350. }
  351. else
  352. {
  353. svi = (SrvClassInfo)(_srvClassManager[_name]);
  354. }
  355. return svi;
  356. }
  357. public void StartDaemon()
  358. {
  359. Thread daemon_thread = new Thread(DaemonResFunc);
  360. daemon_thread.Name = "服务监控实时存档";
  361. daemon_thread.Start();
  362. }
  363. #region 系统资源监控
  364. public void SuspendMe()
  365. {
  366. _RunningEvent.Reset();
  367. }
  368. public void ResumeMe()
  369. {
  370. _RunningEvent.Set();
  371. }
  372. private void DaemonResFunc()
  373. {
  374. do
  375. {
  376. try
  377. {
  378. CreateMemSnap();
  379. }
  380. catch (Exception ex)
  381. {
  382. Debug.Print(ex.Message);
  383. }
  384. Thread.Sleep(2000);
  385. } while (true);
  386. }
  387. DateTime PrevSnapTime = new DateTime(1900, 1, 1);
  388. private void CreateMemSnap()
  389. {
  390. if (HtAssemblyServer == null) return;
  391. lock (obj_lock)
  392. {
  393. PrevSnapTime = DateTime.Now;
  394. Process cur = Process.GetCurrentProcess();
  395. PerformanceCounter curpc = new PerformanceCounter("Process", "Working Set", cur.ProcessName);
  396. double MemUsedMB = curpc.NextValue() / 1024 / 1024;
  397. double CurBsy_HisMem = 0;
  398. Hashtable CurBsySrv = new Hashtable();
  399. foreach (string serverName in HtAssemblyServer.Keys)
  400. {
  401. try
  402. {
  403. SrvUsedInfo sui = null;
  404. //循环服务,获取服务使用情况
  405. if (!_srvUsedManager.ContainsKey(serverName))
  406. {
  407. sui = new SrvUsedInfo();
  408. sui.ServerName = serverName.ToUpper();
  409. _srvUsedManager.Add(serverName, sui);
  410. }
  411. else
  412. {
  413. sui = (SrvUsedInfo)_srvUsedManager[serverName];
  414. sui.CallingMethod.Clear();
  415. }
  416. lock (_srvUsedManager[serverName])
  417. {
  418. sui.CurrentUsed = 0;
  419. sui.MaxLimit = 0;
  420. //循环服务提供类
  421. IServerPool sPool = (IServerPool)HtAssemblyServer[serverName];
  422. foreach (string className in sPool.HtComponent.Keys)
  423. {
  424. Hashtable classPoolHash = (Hashtable)sPool.HtComponent[className];
  425. sui.MaxLimit += classPoolHash.Contains(2) ? ((int)classPoolHash[2]) : 30;
  426. string _clsFullName = serverName.ToUpper() + "." + className.ToUpper();
  427. if (classPoolHash != null)
  428. {
  429. if (classPoolHash.ContainsKey(1) && classPoolHash[1] != null)
  430. {
  431. ArrayList bsyList = (ArrayList)classPoolHash[1];
  432. sui.CurrentUsed += bsyList.Count;
  433. //循环忙列表
  434. foreach (IComponent module in bsyList)
  435. {
  436. sui.CallingMethod.Add(module.CallingMethod.ToUpper());
  437. string method_name = _clsFullName + "." + module.CallingMethod.ToUpper();
  438. SrvClassInfo sci = null;
  439. if (!_srvClassManager.ContainsKey(method_name))
  440. {
  441. sci = new SrvClassInfo();
  442. sci.ServerName = serverName.ToUpper();
  443. sci.ClassName = className.ToUpper();
  444. sci.MethodName = module.CallingMethod.ToUpper();
  445. if (sci.TotalCalled == long.MaxValue) sci.TotalCalled = 0;
  446. sci.TotalCalled += 1;
  447. sci.AvgMemUsed = 30;
  448. _srvClassManager.Add(method_name, sci);
  449. }
  450. else
  451. {
  452. sci = (SrvClassInfo)_srvClassManager[method_name];
  453. }
  454. if (!CurBsySrv.ContainsKey(method_name))
  455. {
  456. CurBsySrv.Add(method_name, 1);
  457. CurBsy_HisMem += sci.AvgMemUsed;
  458. }
  459. else
  460. {
  461. CurBsySrv[method_name] = (int)(CurBsySrv[method_name]) + 1;
  462. CurBsy_HisMem += sci.AvgMemUsed;
  463. }
  464. }
  465. }
  466. }
  467. }
  468. }
  469. }
  470. catch { }
  471. }
  472. //计算主线程
  473. SrvClassInfo main_sci;
  474. if (!_srvClassManager.ContainsKey("MAIN"))
  475. {
  476. main_sci = new SrvClassInfo();
  477. main_sci.ServerName = "MAIN";
  478. main_sci.AvgMemUsed = 30;
  479. _srvClassManager.Add("MAIN", main_sci);
  480. }
  481. else
  482. {
  483. main_sci = (SrvClassInfo)_srvClassManager["MAIN"];
  484. }
  485. if (!CurBsySrv.ContainsKey("MAIN"))
  486. {
  487. CurBsySrv.Add("MAIN", 1);
  488. CurBsy_HisMem += main_sci.AvgMemUsed;
  489. }
  490. foreach (string cbs in CurBsySrv.Keys)
  491. {
  492. lock (_srvClassManager[cbs])
  493. {
  494. for (int idx = 0; idx < (int)(CurBsySrv[cbs]); idx++)
  495. {
  496. double cm = (long)(((SrvClassInfo)_srvClassManager[cbs]).AvgMemUsed * 1.0 / CurBsy_HisMem * MemUsedMB);
  497. LinkedList<SrvEventItem> nodes = ((SrvClassInfo)_srvClassManager[cbs]).SrvEvents;
  498. ((SrvClassInfo)_srvClassManager[cbs]).AvgMemUsed = (((SrvClassInfo)_srvClassManager[cbs]).AvgMemUsed * nodes.Count + cm) / (nodes.Count + 1);
  499. SrvEventItem sei;
  500. sei.dt = PrevSnapTime;
  501. sei._memUsed = cm;
  502. nodes.AddLast(sei);
  503. if (nodes.Count > 100) nodes.RemoveFirst();
  504. }
  505. }
  506. }
  507. }
  508. }
  509. #endregion
  510. public void ShowSrvData(ShowSrvDataEvent ssde)
  511. {
  512. do
  513. {
  514. _RunningEvent.WaitOne();
  515. List<DataPoint> s1 = new List<DataPoint>();
  516. List<DataPoint> s2 = new List<DataPoint>();
  517. ArrayList _keys = new ArrayList();
  518. foreach (string ServerName in _srvUsedManager.Keys)
  519. {
  520. _keys.Add(ServerName);
  521. }
  522. _keys.Sort();
  523. int idx = 0;
  524. foreach (string ServerName in _keys)
  525. {
  526. SrvUsedInfo sui = (SrvUsedInfo)_srvUsedManager[ServerName];
  527. DataPoint dp = new DataPoint();
  528. dp.SetValueXY(idx, sui.CurrentUsed);
  529. //dp.SetValueXY(idx, sui.MaxLimit == 0 ? (sui.CurrentUsed > 0 ? 1 : 0) : sui.CurrentUsed / sui.MaxLimit);
  530. dp.ToolTip = string.Format("{0}\n {1}/{2}", ServerName, sui.CurrentUsed, sui.MaxLimit);
  531. dp.LabelToolTip = ServerName;
  532. s1.Add(dp);
  533. dp = new DataPoint();
  534. //dp.SetValueXY(idx, sui.MaxLimit - sui.CurrentUsed > 0 ? sui.MaxLimit - sui.CurrentUsed : 0);
  535. dp.SetValueXY(idx, sui.MaxLimit);
  536. dp.ToolTip = string.Format("{0}\n {1}/{2}", ServerName, sui.CurrentUsed, sui.MaxLimit);
  537. dp.LabelToolTip = ServerName;
  538. s2.Add(dp);
  539. idx++;
  540. }
  541. if (ssde != null)
  542. {
  543. ssde.Invoke(s1, s2);
  544. }
  545. Thread.Sleep(2500);
  546. } while (true);
  547. }
  548. private void WriteSrvData(Hashtable srv)
  549. {
  550. string logFile = Path.Combine(filePath, "DM_ServerUsed.tmp");
  551. string logFile1 = Path.Combine(filePath, "DM_ServerUsed.dat");
  552. if (write_fs != null)
  553. {
  554. write_fs.Close();
  555. }
  556. lock (srv)
  557. {
  558. try
  559. {
  560. write_fs = new FileStream(logFile, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None);
  561. write_fs.Seek(0, SeekOrigin.Begin);
  562. write_fs.SetLength(0);
  563. foreach (SrvClassInfo svi in srv)
  564. {
  565. byte[] b_svi = Utility.SerializeAndCompressObject(svi);
  566. long l_size = b_svi.GetLongLength(0);
  567. byte[] b_size = System.BitConverter.GetBytes(l_size);
  568. write_fs.Write(b_size, 0, b_size.GetLength(0));
  569. write_fs.Write(b_svi, 0, b_svi.GetLength(0));
  570. }
  571. write_fs.Flush();
  572. write_fs.Close();
  573. if (File.Exists(logFile1))
  574. {
  575. File.Delete(logFile1);
  576. }
  577. File.Move(logFile, logFile1);
  578. }
  579. catch { }
  580. finally
  581. {
  582. write_fs.Close();
  583. }
  584. }
  585. }
  586. }
  587. public class ExtSrvDaemon
  588. {
  589. public delegate void ShowExtSrvEvent();
  590. private ManualResetEvent _RunningEvent = new ManualResetEvent(false);
  591. #region 扩展服务监控
  592. public void ShowExtServer(ShowExtSrvEvent sese)
  593. {
  594. do
  595. {
  596. if (sese != null)
  597. {
  598. sese();
  599. }
  600. Thread.Sleep(5000);
  601. } while (true);
  602. }
  603. public void SuspendMe()
  604. {
  605. _RunningEvent.Reset();
  606. }
  607. public void ResumeMe()
  608. {
  609. _RunningEvent.Set();
  610. }
  611. #endregion
  612. }
  613. public class SystemInfo
  614. {
  615. private int m_ProcessorCount = 0; //CPU个数
  616. private PerformanceCounter pcCpuLoad; //CPU计数器
  617. private long m_PhysicalMemory = 0; //物理内存
  618. private const int GW_HWNDFIRST = 0;
  619. private const int GW_HWNDNEXT = 2;
  620. private const int GWL_STYLE = (-16);
  621. private const int WS_VISIBLE = 268435456;
  622. private const int WS_BORDER = 8388608;
  623. #region AIP声明
  624. [DllImport("IpHlpApi.dll")]
  625. extern static public uint GetIfTable(byte[] pIfTable, ref uint pdwSize, bool bOrder);
  626. [DllImport("User32")]
  627. private extern static int GetWindow(int hWnd, int wCmd);
  628. [DllImport("User32")]
  629. private extern static int GetWindowLongA(int hWnd, int wIndx);
  630. [DllImport("user32.dll")]
  631. private static extern bool GetWindowText(int hWnd, StringBuilder title, int maxBufSize);
  632. [DllImport("user32", CharSet = CharSet.Auto)]
  633. private extern static int GetWindowTextLength(IntPtr hWnd);
  634. #endregion
  635. #region 构造函数
  636. /// <summary>
  637. /// 构造函数,初始化计数器等
  638. /// </summary>
  639. public SystemInfo()
  640. {
  641. //初始化CPU计数器
  642. pcCpuLoad = new PerformanceCounter("Processor", "% Processor Time", "_Total");
  643. pcCpuLoad.MachineName = ".";
  644. pcCpuLoad.NextValue();
  645. //CPU个数
  646. m_ProcessorCount = Environment.ProcessorCount;
  647. //获得物理内存
  648. ManagementClass mc = new ManagementClass("Win32_ComputerSystem");
  649. ManagementObjectCollection moc = mc.GetInstances();
  650. foreach (ManagementObject mo in moc)
  651. {
  652. if (mo["TotalPhysicalMemory"] != null)
  653. {
  654. m_PhysicalMemory = long.Parse(mo["TotalPhysicalMemory"].ToString());
  655. }
  656. }
  657. }
  658. #endregion
  659. #region CPU个数
  660. /// <summary>
  661. /// 获取CPU个数
  662. /// </summary>
  663. public int ProcessorCount
  664. {
  665. get
  666. {
  667. return m_ProcessorCount;
  668. }
  669. }
  670. #endregion
  671. #region CPU占用率
  672. /// <summary>
  673. /// 获取CPU占用率
  674. /// </summary>
  675. public float CpuLoad
  676. {
  677. get
  678. {
  679. return pcCpuLoad.NextValue();
  680. }
  681. }
  682. #endregion
  683. #region 可用内存
  684. /// <summary>
  685. /// 获取可用内存
  686. /// </summary>
  687. public long MemoryAvailable
  688. {
  689. get
  690. {
  691. long availablebytes = 0;
  692. //ManagementObjectSearcher mos = new ManagementObjectSearcher("SELECT * FROM Win32_PerfRawData_PerfOS_Memory");
  693. //foreach (ManagementObject mo in mos.Get())
  694. //{
  695. // availablebytes = long.Parse(mo["Availablebytes"].ToString());
  696. //}
  697. ManagementClass mos = new ManagementClass("Win32_OperatingSystem");
  698. foreach (ManagementObject mo in mos.GetInstances())
  699. {
  700. if (mo["FreePhysicalMemory"] != null)
  701. {
  702. availablebytes = 1024 * long.Parse(mo["FreePhysicalMemory"].ToString());
  703. }
  704. }
  705. return availablebytes;
  706. }
  707. }
  708. #endregion
  709. #region 物理内存
  710. /// <summary>
  711. /// 获取物理内存
  712. /// </summary>
  713. public long PhysicalMemory
  714. {
  715. get
  716. {
  717. return m_PhysicalMemory;
  718. }
  719. }
  720. #endregion
  721. #region 结束指定进程
  722. /// <summary>
  723. /// 结束指定进程
  724. /// </summary>
  725. /// <param name="pid">进程的 Process ID</param>
  726. public static void EndProcess(int pid)
  727. {
  728. try
  729. {
  730. Process process = Process.GetProcessById(pid);
  731. process.Kill();
  732. }
  733. catch { }
  734. }
  735. #endregion
  736. #region 查找所有应用程序标题
  737. /// <summary>
  738. /// 查找所有应用程序标题
  739. /// </summary>
  740. /// <returns>应用程序标题范型</returns>
  741. public static List<string> FindAllApps(int Handle)
  742. {
  743. List<string> Apps = new List<string>();
  744. int hwCurr;
  745. hwCurr = GetWindow(Handle, GW_HWNDFIRST);
  746. while (hwCurr > 0)
  747. {
  748. int IsTask = (WS_VISIBLE | WS_BORDER);
  749. int lngStyle = GetWindowLongA(hwCurr, GWL_STYLE);
  750. bool TaskWindow = ((lngStyle & IsTask) == IsTask);
  751. if (TaskWindow)
  752. {
  753. int length = GetWindowTextLength(new IntPtr(hwCurr));
  754. StringBuilder sb = new StringBuilder(2 * length + 1);
  755. GetWindowText(hwCurr, sb, sb.Capacity);
  756. string strTitle = sb.ToString();
  757. if (!string.IsNullOrEmpty(strTitle))
  758. {
  759. Apps.Add(strTitle);
  760. }
  761. }
  762. hwCurr = GetWindow(hwCurr, GW_HWNDNEXT);
  763. }
  764. return Apps;
  765. }
  766. private byte[] CalcSHA(string Content)
  767. {
  768. SHA256Managed sh = new SHA256Managed();
  769. byte[] bs = System.Text.Encoding.Default.GetBytes(Content);
  770. return sh.ComputeHash(bs);
  771. }
  772. #endregion
  773. }
  774. [Serializable]
  775. public struct SrvEventItem
  776. {
  777. public DateTime dt;
  778. public double _memUsed;
  779. }
  780. [Serializable]
  781. public class SrvClassInfo
  782. {
  783. public string ServerName = "";
  784. public string ClassName = "";
  785. public string MethodName = "";
  786. public long TotalCalled = 0;
  787. public double AvgMemUsed = 10;
  788. public LinkedList<SrvEventItem> SrvEvents = new LinkedList<SrvEventItem>();
  789. }
  790. public class SrvUsedInfo
  791. {
  792. public string ServerName = "";
  793. public string ClassName = "";
  794. public int MaxLimit = 0;
  795. public int CurrentUsed = 0;
  796. public ArrayList CallingMethod = new ArrayList();
  797. }
  798. }