ResourceMonitor.cs 15 KB

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