ResourceMonitor.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. using Aitex.Core.RT.Log;
  2. using Aitex.Core.RT.SCCore;
  3. using MECF.Framework.Common.Equipment;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Diagnostics;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Management;
  10. using System.Reflection;
  11. using System.ServiceModel.Channels;
  12. using System.Text;
  13. using System.Timers;
  14. using System.Windows;
  15. namespace CyberX8_RT.Modules
  16. {
  17. public class ResourceMonitor
  18. {
  19. private string processRTname = Process.GetCurrentProcess().ProcessName;
  20. private string processUIname = "Venus_UI";
  21. //private int _stringlen = 20;
  22. private int threshold = 800;
  23. private Process pro;
  24. private Timer _timer;
  25. //数据波动监测可用
  26. //List<double> _Numberofhandlesopened = new List<double>() { };
  27. //List<double> _Numberofmodules = new List<double>() { };
  28. //List<double> _Basicpriority = new List<double>() { };
  29. //List<double> _processor = new List<double>() { };
  30. //List<double> _Minimumworkingset = new List<double>() { };
  31. //List<double> _MaximumWorkingSet = new List<double>() { };
  32. //List<double> _Workset = new List<double>() { };
  33. //List<double> _Peakworkingset = new List<double>() { };
  34. //List<double> _Dedicatedmemorysize = new List<double>() { };
  35. //List<double> _UnpagedMemorySize = new List<double>() { };
  36. //List<double> _PagingMemorySize = new List<double>() { };
  37. //List<double> _Peakpagingmemorysize = new List<double>() { };
  38. //List<double> _VirtualMemorySize = new List<double>() { };
  39. //List<double> _PeakVirtualMemorySize = new List<double>() { };
  40. //string ProcessName = string.Empty;
  41. //string ProcessID = string.Empty;
  42. //string Starttime = string.Empty;
  43. private string Response = string.Empty;
  44. private string MainWindowHandle = string.Empty;
  45. //string MainWindowTitle = string.Empty;
  46. private string AssociatedProcessHandle = string.Empty;
  47. private string Numberofhandlesopened = string.Empty;
  48. private string Numberofmodules = string.Empty;
  49. private string Basicpriority = string.Empty;
  50. private string Increasepriority = string.Empty;
  51. private string processor = string.Empty;
  52. private string Minimumworkingset = string.Empty;
  53. private string MaximumWorkingSet = string.Empty;
  54. private string Workset = string.Empty;
  55. private string Peakworkingset = string.Empty;
  56. private string Dedicatedmemorysize = string.Empty;
  57. private string UnpagedMemorySize = string.Empty;
  58. private string PagingMemorySize = string.Empty;
  59. private string Peakpagingmemorysize = string.Empty;
  60. private string VirtualMemorySize = string.Empty;
  61. private string PeakVirtualMemorySize = string.Empty;
  62. private string Occupytime = string.Empty;
  63. private string PrivilegeOccupancytime = string.Empty;
  64. private string Useroccupiedtime = string.Empty;
  65. private PerformanceCounter CpuOccupied;
  66. public ResourceMonitor()
  67. {
  68. //ProcessName = "进程名称";
  69. //ProcessID = "进程ID".PadRight(_stringlen - 2, ' ');
  70. //Starttime = "启动时间";
  71. Response = "Response or not";
  72. MainWindowHandle = "Main Window Handle";
  73. //MainWindowTitle = "主窗口标题";
  74. AssociatedProcessHandle = "Associated Process Handle ";
  75. Numberofhandlesopened = "Number of handles opened ";
  76. Numberofmodules = "Number of modules ";
  77. Basicpriority = "Basic priority ";
  78. Increasepriority = "Increase priority ";
  79. processor = "processor ";
  80. Minimumworkingset = "Minimum working set ";
  81. MaximumWorkingSet = "Maximum working Set ";
  82. Workset = "Work set ";
  83. Peakworkingset = "Peak working set ";
  84. Dedicatedmemorysize = "Dedicated memory size ";
  85. UnpagedMemorySize = "Unpaged Memory Size ";
  86. PagingMemorySize = "Paging Memory Size ";
  87. Peakpagingmemorysize = "Peak paging memory size ";
  88. VirtualMemorySize = "Virtual Memory Size ";
  89. PeakVirtualMemorySize = "Peak Virtual Memory Size ";
  90. Occupytime = "Occupy time ";
  91. PrivilegeOccupancytime = "Privilege Occupancy time ";
  92. Useroccupiedtime = "User occupied time ";
  93. }
  94. ~ResourceMonitor() => _timer.Dispose();//定时器销毁
  95. public bool Initialize()
  96. {
  97. //>0 开启否则不开启
  98. if (SC.GetValue<int>("System.CheckResourceInterval") > 0)
  99. {
  100. _timer = new Timer();
  101. CpuOccupied = new PerformanceCounter("Processor", "% Processor Time", "_Total");
  102. _timer.Enabled = true;
  103. _timer.Interval = SC.GetValue<int>("System.CheckResourceInterval") * 60 * 1000;
  104. _timer.Elapsed += GetProcessInfo;
  105. _timer.Start();
  106. //LOG.Write($"{ProcessName}" +
  107. //$"{ProcessID}" +
  108. ////$"{Starttime}"+
  109. //$"{Response}" +
  110. //$"{MainWindowHandle}" +
  111. ////$"{MainWindowTitle}"+
  112. //$"{AssociatedProcessHandle}" +
  113. //$"{Numberofhandlesopened}" +
  114. //$"{Numberofmodules}" +
  115. //$"{Basicpriority}" +
  116. //$"{Increasepriority}" +
  117. //$"{processor}" +
  118. //$"{Minimumworkingset}" +
  119. //$"{MaximumWorkingSet}" +
  120. //$"{Workset}" +
  121. //$"{Peakworkingset}" +
  122. //$"{Dedicatedmemorysize}" +
  123. //$"{UnpagedMemorySize}" +
  124. //$"{PagingMemorySize}" +
  125. //$"{Peakpagingmemorysize}" +
  126. //$"{VirtualMemorySize}" +
  127. //$"{PeakVirtualMemorySize}" +
  128. //$"{Occupytime}" +
  129. //$"{PrivilegeOccupancytime}" +
  130. //$"{Useroccupiedtime}");
  131. }
  132. return true;
  133. }
  134. private void GetProcessInfo(object sender, ElapsedEventArgs e)
  135. {
  136. try
  137. {
  138. string rtmonoitor = process_use(processRTname);
  139. string uimonoitor = process_use(processUIname);
  140. string systemMonitor = $"PC => {drive_use()}" +
  141. $"{cpu_use()}" +
  142. $"{memory_use()}";
  143. LOG.Write(eEvent.INFO_WINRESOURCE, ModuleName.System,
  144. rtmonoitor +
  145. " ".PadLeft(56, ' ') + uimonoitor +
  146. " ".PadLeft(56, ' ') + systemMonitor
  147. );
  148. //没有就不做任何操作
  149. }
  150. catch (Exception ex)
  151. {
  152. LOG.Write(eEvent.ERR_WINRESOURCE, ModuleName.System,$"Monitor Error happened: {ex}");
  153. }
  154. }
  155. //process
  156. private string process_use(string processname)
  157. {
  158. string monitor = "";
  159. //判断是否存在该进程
  160. //有就开始记录
  161. if (Process.GetProcessesByName(processname).Length > 0)
  162. {
  163. pro = Process.GetProcessesByName(processname)[0];
  164. //_Numberofhandlesopened.Add(pro.HandleCount); //进程打开的句柄数
  165. //_Numberofmodules.Add(pro.Modules.Count); //模块数量
  166. //_Basicpriority.Add(pro.BasePriority); //基本优先级
  167. //_processor.Add(pro.ProcessorAffinity.ToInt32()); //处理器
  168. //_Minimumworkingset.Add(pro.MinWorkingSet.ToInt32()); //最小工作集
  169. //_MaximumWorkingSet.Add(pro.MaxWorkingSet.ToInt32()); //最大工作集
  170. //_Workset.Add(Convert.ToInt32(pro.WorkingSet64)); //工作集
  171. //_Peakworkingset.Add(Convert.ToInt32(pro.PeakWorkingSet64)); //峰值工作集
  172. //_Dedicatedmemorysize.Add(Convert.ToInt32(pro.PrivateMemorySize64 / 1048576)); //专用内存大小
  173. //_UnpagedMemorySize.Add(Convert.ToInt32(pro.NonpagedSystemMemorySize64 / 1048576)); //未分页内存大小
  174. //_PagingMemorySize.Add(Convert.ToInt32(pro.PagedMemorySize64 / 1048576)); //分页内存大小
  175. //_Peakpagingmemorysize.Add(Convert.ToInt32(pro.PeakPagedMemorySize64 / 1048576)); //峰值分页内存大小
  176. //_VirtualMemorySize.Add(Convert.ToInt32(pro.VirtualMemorySize64 / 1024)); //虚拟内存大小
  177. //_PeakVirtualMemorySize.Add(Convert.ToInt32(pro.PeakVirtualMemorySize64 / 1048576)); //峰值虚拟内存大小
  178. monitor = //$"{ProcessName}:{pro.ProcessName}" +
  179. //$"{pro.StartTime.ToLongDateString() + pro.StartTime.ToLongTimeString()}" +
  180. $"{processname} => {Response}:{pro.Responding.ToString()}\t" +
  181. $"{MainWindowHandle}:{pro.MainWindowHandle.ToString()}\t" +
  182. //$"{pro.MainWindowTitle}" +
  183. $"{AssociatedProcessHandle}:{pro.Handle.ToString()}\t" +
  184. $"{Numberofhandlesopened}:{pro.HandleCount.ToString()}\t" +
  185. $"{Numberofmodules}:{pro.Modules.Count.ToString()}\t" +
  186. $"{Basicpriority}:{pro.BasePriority.ToString()} \t" +
  187. $"{Increasepriority}:{pro.PriorityBoostEnabled.ToString()}\t" +
  188. $"{processor}:{pro.ProcessorAffinity.ToInt32().ToString()}\t" +
  189. //$"{Minimumworkingset}:{pro.MinWorkingSet.ToInt32().ToString()}\t" +
  190. $"{MaximumWorkingSet}:{pro.MaxWorkingSet.ToInt32().ToString()}\t" +
  191. $"{Workset}:{pro.WorkingSet64.ToString()}\t" +
  192. $"{Peakworkingset}:{pro.PeakWorkingSet64.ToString()}\t" +
  193. $"{Dedicatedmemorysize}:{(pro.PrivateMemorySize64 / 1048576).ToString()}MB\t" +
  194. $"{UnpagedMemorySize}:{(pro.NonpagedSystemMemorySize64 / 1048576).ToString()}MB\t" +
  195. $"{PagingMemorySize}:{(pro.PagedMemorySize64 / 1048576).ToString()}MB\t" +
  196. $"{Peakpagingmemorysize}:{(pro.PeakPagedMemorySize64 / 1048576).ToString()}MB\t" +
  197. $"{VirtualMemorySize}:{(pro.VirtualMemorySize64 / 1048576).ToString()}MB\t" +
  198. $"{PeakVirtualMemorySize}:{(pro.PeakVirtualMemorySize64 / 1048576).ToString()}MB\t" +
  199. $"{Occupytime}:{pro.TotalProcessorTime.ToString()}\t" +
  200. $"{PrivilegeOccupancytime}:{pro.PrivilegedProcessorTime.ToString()}\t" +
  201. $"{Useroccupiedtime}:{pro.UserProcessorTime.ToString()}\r\n";
  202. //如果虚拟内存大于800MB 即报警
  203. if (pro.PagedMemorySize64 / 1048576 >= threshold)
  204. {
  205. LOG.Write(eEvent.WARN_WINRESOURCE, ModuleName.System, $"警告!进程 {processname} 内存异常增长,超过{threshold}MB阈值!");
  206. }
  207. }
  208. return monitor;
  209. }
  210. //CPU
  211. private string cpu_use()
  212. {
  213. float cpu_use_per = CpuOccupied.NextValue();
  214. string cpu_use = $"CPU usage rate:{cpu_use_per:F2}%\t";
  215. return cpu_use;
  216. }
  217. //disk
  218. private string drive_use()
  219. {
  220. string drive_use = "";
  221. foreach (DriveInfo drive in DriveInfo.GetDrives())
  222. {
  223. if (drive.IsReady)
  224. {
  225. drive_use += $"{drive.Name}";
  226. drive_use += $" Total:{drive.TotalSize / 1024 / 1024 / 1024}GB";
  227. drive_use += $" Used:{(drive.TotalSize - drive.AvailableFreeSpace) / 1024 / 1024 / 1024}GB";
  228. drive_use += $" Free:{drive.AvailableFreeSpace / 1024 / 1024 / 1024}GB\t";
  229. }
  230. }
  231. return drive_use;
  232. }
  233. //memory
  234. private string memory_use()
  235. {
  236. string memory_use = "Memory status:" +
  237. $"Memory Available:{GetMemoryAvailable():F2}GB\t" +
  238. $"Memory Used:{GetMemoryUsed():F2}GB\t" +
  239. $"Memory Used Rate:{GetMemoryUsedRate():F2}%\t";
  240. return memory_use;
  241. }
  242. //MemoryAvailable
  243.         private double? GetMemoryAvailable()
  244. {
  245. double availablebytes = 0;
  246. var managementClassOs = new ManagementClass("Win32_OperatingSystem");
  247. foreach (var managementBaseObject in managementClassOs.GetInstances())
  248. if (managementBaseObject["FreePhysicalMemory"] != null)
  249. availablebytes = 1024 * double.Parse(managementBaseObject["FreePhysicalMemory"].ToString());
  250. return availablebytes / GbDiv;
  251. }
  252. //MemoryUsed
  253.         private double? GetMemoryUsed()
  254. {
  255. double? PhysicalMemory = GetPhysicalMemory();
  256. double? MemoryAvailable = GetMemoryAvailable();
  257. double? MemoryUsed = (double?)(PhysicalMemory - MemoryAvailable);
  258. double currentMemoryUsed = (double)MemoryUsed;
  259. return currentMemoryUsed;
  260. }
  261. //PhysicalMemory
  262. private long? GetPhysicalMemory()
  263. {
  264.             //获得物理内存
  265.             var managementClass = new ManagementClass("Win32_ComputerSystem");
  266. var managementObjectCollection = managementClass.GetInstances();
  267. foreach (var managementBaseObject in managementObjectCollection)
  268. if (managementBaseObject["TotalPhysicalMemory"] != null)
  269. {
  270. return long.Parse(managementBaseObject["TotalPhysicalMemory"].ToString()) / GbDiv;
  271. }
  272. return null;
  273. }
  274. //MemoryUsedRate
  275. private double? GetMemoryUsedRate()
  276. {
  277. double? PhysicalMemory = GetPhysicalMemory();
  278. double? MemoryAvailable = GetMemoryAvailable();
  279. double? MemoryUsedRate = (double?)(PhysicalMemory - MemoryAvailable) / PhysicalMemory;
  280. return MemoryUsedRate.HasValue ? Convert.ToDouble(MemoryUsedRate * 100) : 0;
  281. }
  282. #region 单位转换进制
  283. private const int KbDiv = 1024;
  284. private const int MbDiv = 1024 * 1024;
  285. private const int GbDiv = 1024 * 1024 * 1024;
  286.         #endregion
  287. }
  288. }