ResourceMonitor.cs 14 KB

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