4954ce3d09ebf15888cc6808a7341a39916bcc84.svn-base 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903
  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. CreateMemSnap();
  377. Thread.Sleep(1000);
  378. } while (true);
  379. }
  380. DateTime PrevSnapTime = new DateTime(1900, 1, 1);
  381. private void CreateMemSnap()
  382. {
  383. if (HtAssemblyServer == null) return;
  384. lock (obj_lock)
  385. {
  386. PrevSnapTime = DateTime.Now;
  387. Process cur = Process.GetCurrentProcess();
  388. PerformanceCounter curpc = new PerformanceCounter("Process", "Working Set", cur.ProcessName);
  389. double MemUsedMB = curpc.NextValue() / 1024 / 1024;
  390. double CurBsy_HisMem = 0;
  391. Hashtable CurBsySrv = new Hashtable();
  392. foreach (string serverName in HtAssemblyServer.Keys)
  393. {
  394. try
  395. {
  396. SrvUsedInfo sui = null;
  397. //循环服务,获取服务使用情况
  398. if (!_srvUsedManager.ContainsKey(serverName))
  399. {
  400. sui = new SrvUsedInfo();
  401. sui.ServerName = serverName.ToUpper();
  402. _srvUsedManager.Add(serverName, sui);
  403. }
  404. else
  405. {
  406. sui = (SrvUsedInfo)_srvUsedManager[serverName];
  407. sui.CallingMethod.Clear();
  408. }
  409. int CurrentUsed = 0;
  410. int MaxLimit = 0;
  411. //循环服务提供类
  412. IServerPool sPool = (IServerPool)HtAssemblyServer[serverName];
  413. foreach (string className in sPool.HtComponent.Keys)
  414. {
  415. Hashtable classPoolHash = (Hashtable)sPool.HtComponent[className];
  416. MaxLimit += classPoolHash.Contains(2) ? ((int)classPoolHash[2]) : 30;
  417. string _clsFullName = serverName.ToUpper() + "." + className.ToUpper();
  418. if (classPoolHash != null)
  419. {
  420. if (classPoolHash.ContainsKey(1) && classPoolHash[1] != null)
  421. {
  422. ArrayList bsyList = (ArrayList)classPoolHash[1];
  423. CurrentUsed += bsyList.Count;
  424. //循环忙列表
  425. foreach (IComponent module in bsyList)
  426. {
  427. sui.CallingMethod.Add(module.CallingMethod.ToUpper());
  428. string method_name = _clsFullName + "." + module.CallingMethod.ToUpper();
  429. SrvClassInfo sci = null;
  430. if (!_srvClassManager.ContainsKey(method_name))
  431. {
  432. sci = new SrvClassInfo();
  433. sci.ServerName = serverName.ToUpper();
  434. sci.ClassName = className.ToUpper();
  435. sci.MethodName = module.CallingMethod.ToUpper();
  436. if (sci.TotalCalled == long.MaxValue) sci.TotalCalled = 0;
  437. sci.TotalCalled += 1;
  438. sci.AvgMemUsed = 30;
  439. _srvClassManager.Add(method_name, sci);
  440. }
  441. else
  442. {
  443. sci = (SrvClassInfo)_srvClassManager[method_name];
  444. }
  445. if (!CurBsySrv.ContainsKey(method_name))
  446. {
  447. CurBsySrv.Add(method_name, 1);
  448. CurBsy_HisMem += sci.AvgMemUsed;
  449. }
  450. else
  451. {
  452. CurBsySrv[method_name] = (int)(CurBsySrv[method_name]) + 1;
  453. CurBsy_HisMem += sci.AvgMemUsed;
  454. }
  455. }
  456. }
  457. }
  458. }
  459. sui.CurrentUsed = CurrentUsed;
  460. sui.MaxLimit = MaxLimit;
  461. }
  462. catch { }
  463. }
  464. //计算主线程
  465. SrvClassInfo main_sci;
  466. if (!_srvClassManager.ContainsKey("MAIN"))
  467. {
  468. main_sci = new SrvClassInfo();
  469. main_sci.ServerName = "MAIN";
  470. main_sci.AvgMemUsed = 30;
  471. _srvClassManager.Add("MAIN", main_sci);
  472. }
  473. else
  474. {
  475. main_sci = (SrvClassInfo)_srvClassManager["MAIN"];
  476. }
  477. if (!CurBsySrv.ContainsKey("MAIN"))
  478. {
  479. CurBsySrv.Add("MAIN", 1);
  480. CurBsy_HisMem += main_sci.AvgMemUsed;
  481. }
  482. foreach (string cbs in CurBsySrv.Keys)
  483. {
  484. for (int idx = 0; idx < (int)(CurBsySrv[cbs]); idx++)
  485. {
  486. double cm = (long)(((SrvClassInfo)_srvClassManager[cbs]).AvgMemUsed * 1.0 / CurBsy_HisMem * MemUsedMB);
  487. LinkedList<SrvEventItem> nodes = ((SrvClassInfo)_srvClassManager[cbs]).SrvEvents;
  488. ((SrvClassInfo)_srvClassManager[cbs]).AvgMemUsed = (((SrvClassInfo)_srvClassManager[cbs]).AvgMemUsed * nodes.Count + cm) / (nodes.Count + 1);
  489. SrvEventItem sei;
  490. sei.dt = PrevSnapTime;
  491. sei._memUsed = cm;
  492. nodes.AddLast(sei);
  493. if (nodes.Count > 100) nodes.RemoveFirst();
  494. }
  495. }
  496. }
  497. }
  498. #endregion
  499. public void ShowSrvData(ShowSrvDataEvent ssde)
  500. {
  501. do
  502. {
  503. _RunningEvent.WaitOne();
  504. List<DataPoint> s1 = new List<DataPoint>();
  505. List<DataPoint> s2 = new List<DataPoint>();
  506. ArrayList _keys = new ArrayList();
  507. foreach (string ServerName in _srvUsedManager.Keys)
  508. {
  509. _keys.Add(ServerName);
  510. }
  511. _keys.Sort();
  512. int idx = 0;
  513. foreach (string ServerName in _keys)
  514. {
  515. SrvUsedInfo sui = (SrvUsedInfo)_srvUsedManager[ServerName];
  516. DataPoint dp = new DataPoint();
  517. dp.SetValueXY(idx, sui.CurrentUsed);
  518. dp.ToolTip = string.Format("{0}\n {1}/{2}", ServerName, sui.CurrentUsed, sui.MaxLimit);
  519. dp.LabelToolTip = ServerName;
  520. s1.Add(dp);
  521. dp = new DataPoint();
  522. dp.SetValueXY(idx, sui.MaxLimit - sui.CurrentUsed > 0 ? sui.MaxLimit - sui.CurrentUsed : 0);
  523. dp.ToolTip = string.Format("{0}\n {1}/{2}", ServerName, sui.CurrentUsed, sui.MaxLimit);
  524. dp.LabelToolTip = ServerName;
  525. s2.Add(dp);
  526. idx++;
  527. }
  528. if (ssde != null)
  529. {
  530. ssde.Invoke(s1, s2);
  531. }
  532. Thread.Sleep(2500);
  533. } while (true);
  534. }
  535. private void WriteSrvData(Hashtable srv)
  536. {
  537. string logFile = Path.Combine(filePath, "DM_ServerUsed.tmp");
  538. string logFile1 = Path.Combine(filePath, "DM_ServerUsed.dat");
  539. if (write_fs != null)
  540. {
  541. write_fs.Close();
  542. }
  543. lock (srv)
  544. {
  545. try
  546. {
  547. write_fs = new FileStream(logFile, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None);
  548. write_fs.Seek(0, SeekOrigin.Begin);
  549. write_fs.SetLength(0);
  550. foreach (SrvClassInfo svi in srv)
  551. {
  552. byte[] b_svi = Utility.SerializeAndCompressObject(svi);
  553. long l_size = b_svi.GetLongLength(0);
  554. byte[] b_size = System.BitConverter.GetBytes(l_size);
  555. write_fs.Write(b_size, 0, b_size.GetLength(0));
  556. write_fs.Write(b_svi, 0, b_svi.GetLength(0));
  557. }
  558. write_fs.Flush();
  559. write_fs.Close();
  560. if (File.Exists(logFile1))
  561. {
  562. File.Delete(logFile1);
  563. }
  564. File.Move(logFile, logFile1);
  565. }
  566. catch { }
  567. finally
  568. {
  569. write_fs.Close();
  570. }
  571. }
  572. }
  573. }
  574. public class ExtSrvDaemon
  575. {
  576. public delegate void ShowExtSrvEvent();
  577. private ManualResetEvent _RunningEvent = new ManualResetEvent(false);
  578. #region 扩展服务监控
  579. public void ShowExtServer(ShowExtSrvEvent sese)
  580. {
  581. do
  582. {
  583. if (sese != null)
  584. {
  585. sese();
  586. }
  587. Thread.Sleep(5000);
  588. } while (true);
  589. }
  590. public void SuspendMe()
  591. {
  592. _RunningEvent.Reset();
  593. }
  594. public void ResumeMe()
  595. {
  596. _RunningEvent.Set();
  597. }
  598. #endregion
  599. }
  600. public class SystemInfo
  601. {
  602. private int m_ProcessorCount = 0; //CPU个数
  603. private PerformanceCounter pcCpuLoad; //CPU计数器
  604. private long m_PhysicalMemory = 0; //物理内存
  605. private const int GW_HWNDFIRST = 0;
  606. private const int GW_HWNDNEXT = 2;
  607. private const int GWL_STYLE = (-16);
  608. private const int WS_VISIBLE = 268435456;
  609. private const int WS_BORDER = 8388608;
  610. #region AIP声明
  611. [DllImport("IpHlpApi.dll")]
  612. extern static public uint GetIfTable(byte[] pIfTable, ref uint pdwSize, bool bOrder);
  613. [DllImport("User32")]
  614. private extern static int GetWindow(int hWnd, int wCmd);
  615. [DllImport("User32")]
  616. private extern static int GetWindowLongA(int hWnd, int wIndx);
  617. [DllImport("user32.dll")]
  618. private static extern bool GetWindowText(int hWnd, StringBuilder title, int maxBufSize);
  619. [DllImport("user32", CharSet = CharSet.Auto)]
  620. private extern static int GetWindowTextLength(IntPtr hWnd);
  621. #endregion
  622. #region 构造函数
  623. /// <summary>
  624. /// 构造函数,初始化计数器等
  625. /// </summary>
  626. public SystemInfo()
  627. {
  628. //初始化CPU计数器
  629. pcCpuLoad = new PerformanceCounter("Processor", "% Processor Time", "_Total");
  630. pcCpuLoad.MachineName = ".";
  631. pcCpuLoad.NextValue();
  632. //CPU个数
  633. m_ProcessorCount = Environment.ProcessorCount;
  634. //获得物理内存
  635. ManagementClass mc = new ManagementClass("Win32_ComputerSystem");
  636. ManagementObjectCollection moc = mc.GetInstances();
  637. foreach (ManagementObject mo in moc)
  638. {
  639. if (mo["TotalPhysicalMemory"] != null)
  640. {
  641. m_PhysicalMemory = long.Parse(mo["TotalPhysicalMemory"].ToString());
  642. }
  643. }
  644. }
  645. #endregion
  646. #region CPU个数
  647. /// <summary>
  648. /// 获取CPU个数
  649. /// </summary>
  650. public int ProcessorCount
  651. {
  652. get
  653. {
  654. return m_ProcessorCount;
  655. }
  656. }
  657. #endregion
  658. #region CPU占用率
  659. /// <summary>
  660. /// 获取CPU占用率
  661. /// </summary>
  662. public float CpuLoad
  663. {
  664. get
  665. {
  666. return pcCpuLoad.NextValue();
  667. }
  668. }
  669. #endregion
  670. #region 可用内存
  671. /// <summary>
  672. /// 获取可用内存
  673. /// </summary>
  674. public long MemoryAvailable
  675. {
  676. get
  677. {
  678. long availablebytes = 0;
  679. //ManagementObjectSearcher mos = new ManagementObjectSearcher("SELECT * FROM Win32_PerfRawData_PerfOS_Memory");
  680. //foreach (ManagementObject mo in mos.Get())
  681. //{
  682. // availablebytes = long.Parse(mo["Availablebytes"].ToString());
  683. //}
  684. ManagementClass mos = new ManagementClass("Win32_OperatingSystem");
  685. foreach (ManagementObject mo in mos.GetInstances())
  686. {
  687. if (mo["FreePhysicalMemory"] != null)
  688. {
  689. availablebytes = 1024 * long.Parse(mo["FreePhysicalMemory"].ToString());
  690. }
  691. }
  692. return availablebytes;
  693. }
  694. }
  695. #endregion
  696. #region 物理内存
  697. /// <summary>
  698. /// 获取物理内存
  699. /// </summary>
  700. public long PhysicalMemory
  701. {
  702. get
  703. {
  704. return m_PhysicalMemory;
  705. }
  706. }
  707. #endregion
  708. #region 结束指定进程
  709. /// <summary>
  710. /// 结束指定进程
  711. /// </summary>
  712. /// <param name="pid">进程的 Process ID</param>
  713. public static void EndProcess(int pid)
  714. {
  715. try
  716. {
  717. Process process = Process.GetProcessById(pid);
  718. process.Kill();
  719. }
  720. catch { }
  721. }
  722. #endregion
  723. #region 查找所有应用程序标题
  724. /// <summary>
  725. /// 查找所有应用程序标题
  726. /// </summary>
  727. /// <returns>应用程序标题范型</returns>
  728. public static List<string> FindAllApps(int Handle)
  729. {
  730. List<string> Apps = new List<string>();
  731. int hwCurr;
  732. hwCurr = GetWindow(Handle, GW_HWNDFIRST);
  733. while (hwCurr > 0)
  734. {
  735. int IsTask = (WS_VISIBLE | WS_BORDER);
  736. int lngStyle = GetWindowLongA(hwCurr, GWL_STYLE);
  737. bool TaskWindow = ((lngStyle & IsTask) == IsTask);
  738. if (TaskWindow)
  739. {
  740. int length = GetWindowTextLength(new IntPtr(hwCurr));
  741. StringBuilder sb = new StringBuilder(2 * length + 1);
  742. GetWindowText(hwCurr, sb, sb.Capacity);
  743. string strTitle = sb.ToString();
  744. if (!string.IsNullOrEmpty(strTitle))
  745. {
  746. Apps.Add(strTitle);
  747. }
  748. }
  749. hwCurr = GetWindow(hwCurr, GW_HWNDNEXT);
  750. }
  751. return Apps;
  752. }
  753. private byte[] CalcSHA(string Content)
  754. {
  755. SHA256Managed sh = new SHA256Managed();
  756. byte[] bs = System.Text.Encoding.Default.GetBytes(Content);
  757. return sh.ComputeHash(bs);
  758. }
  759. #endregion
  760. }
  761. [Serializable]
  762. public struct SrvEventItem
  763. {
  764. public DateTime dt;
  765. public double _memUsed;
  766. }
  767. [Serializable]
  768. public class SrvClassInfo
  769. {
  770. public string ServerName = "";
  771. public string ClassName = "";
  772. public string MethodName = "";
  773. public long TotalCalled = 0;
  774. public double AvgMemUsed = 10;
  775. public LinkedList<SrvEventItem> SrvEvents = new LinkedList<SrvEventItem>();
  776. }
  777. public class SrvUsedInfo
  778. {
  779. public string ServerName = "";
  780. public string ClassName = "";
  781. public int MaxLimit = 0;
  782. public int CurrentUsed = 0;
  783. public ArrayList CallingMethod = new ArrayList();
  784. }
  785. }