ResourceMonitor.cs 15 KB

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