ResourceMonitor.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. using Aitex.Core.RT.Device.Unit;
  2. using Aitex.Core.RT.Log;
  3. using Aitex.Core.RT.SCCore;
  4. using Aitex.Core.Util;
  5. using MECF.Framework.Common.Equipment;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.Diagnostics;
  9. using System.IO;
  10. using System.Linq;
  11. using System.Management;
  12. using System.Net.NetworkInformation;
  13. using System.Reflection;
  14. using System.ServiceModel.Channels;
  15. using System.Text;
  16. using System.Threading;
  17. using System.Timers;
  18. using System.Windows;
  19. namespace EfemDualRT.Resources
  20. {
  21. public class ResourceMonitor
  22. {
  23. private string processRTname = Process.GetCurrentProcess().ProcessName;
  24. private string processUIname = "EfemDualUI";
  25. private int threshold = 800;
  26. private Process pro;
  27. private string Response = string.Empty;
  28. private string MainWindowHandle = string.Empty;
  29. private string AssociatedProcessHandle = string.Empty;
  30. private string Numberofhandlesopened = string.Empty;
  31. private string Numberofmodules = string.Empty;
  32. private string Basicpriority = string.Empty;
  33. private string Increasepriority = string.Empty;
  34. private string processor = string.Empty;
  35. private string Minimumworkingset = string.Empty;
  36. private string MaximumWorkingSet = string.Empty;
  37. private string Workset = string.Empty;
  38. private string Peakworkingset = string.Empty;
  39. private string Dedicatedmemorysize = string.Empty;
  40. private string UnpagedMemorySize = string.Empty;
  41. private string PagingMemorySize = string.Empty;
  42. private string Peakpagingmemorysize = string.Empty;
  43. private string VirtualMemorySize = string.Empty;
  44. private string PeakVirtualMemorySize = string.Empty;
  45. private string Occupytime = string.Empty;
  46. private string PrivilegeOccupancytime = string.Empty;
  47. private string Useroccupiedtime = string.Empty;
  48. private PerformanceCounter CpuOccupied;
  49. private Dictionary<string, PerformanceCounter[]> _netAdapterNames = new Dictionary<string, PerformanceCounter[]>();
  50. private PerformanceCounter _readDisk;
  51. private PerformanceCounter _writeDisk;
  52. private PerformanceCounter _transferDisk;
  53. private PeriodicJob _thread;
  54. private bool _isTerminate;
  55. public ResourceMonitor()
  56. {
  57. //ProcessName = "进程名称";
  58. //ProcessID = "进程ID".PadRight(_stringlen - 2, ' ');
  59. //Starttime = "启动时间";
  60. Response = "Response or not";
  61. MainWindowHandle = "Main Window Handle";
  62. //MainWindowTitle = "主窗口标题";
  63. AssociatedProcessHandle = "Associated Process Handle ";
  64. Numberofhandlesopened = "Number of handles opened ";
  65. Numberofmodules = "Number of modules ";
  66. Basicpriority = "Basic priority ";
  67. Increasepriority = "Increase priority ";
  68. processor = "processor ";
  69. Minimumworkingset = "Minimum working set ";
  70. MaximumWorkingSet = "Maximum working Set ";
  71. Workset = "Work set ";
  72. Peakworkingset = "Peak working set ";
  73. Dedicatedmemorysize = "Dedicated memory size ";
  74. UnpagedMemorySize = "Unpaged Memory Size ";
  75. PagingMemorySize = "Paging Memory Size ";
  76. Peakpagingmemorysize = "Peak paging memory size ";
  77. VirtualMemorySize = "Virtual Memory Size ";
  78. PeakVirtualMemorySize = "Peak Virtual Memory Size ";
  79. Occupytime = "Occupy time ";
  80. PrivilegeOccupancytime = "Privilege Occupancy time ";
  81. Useroccupiedtime = "User occupied time ";
  82. _netAdapterNames.Clear();
  83. }
  84. public bool Initialize()
  85. {
  86. var checkInterval = SC.GetValue<int>("System.CheckResourceInterval") * 1000;
  87. if (checkInterval > 0)
  88. {
  89. InitNetAdapter();
  90. _readDisk = new PerformanceCounter("PhysicalDisk", "Avg. Disk sec/Read", "_Total");
  91. _writeDisk = new PerformanceCounter("PhysicalDisk", "Avg. Disk sec/Write", "_Total");
  92. _transferDisk = new PerformanceCounter("PhysicalDisk", "Avg. Disk sec/Transfer", "_Total");
  93. CpuOccupied = new PerformanceCounter("Processor", "% Processor Time", "_Total");
  94. _thread = new PeriodicJob(checkInterval, GetProcessInfo, "ResourceMonitor", true);
  95. }
  96. return true;
  97. }
  98. public void Terminate()
  99. {
  100. if (_thread != null)
  101. {
  102. _isTerminate = true;
  103. _thread.Stop();
  104. _thread = null;
  105. }
  106. }
  107. public void InitNetAdapter()
  108. {
  109. _netAdapterNames.Clear();
  110. NetworkInterface.GetAllNetworkInterfaces().ToList().ForEach(p => {
  111. var name = p.Description.Replace('(', '[').Replace(')', ']');
  112. var list = new PerformanceCounter[2];
  113. list[0] = new PerformanceCounter("Network Interface", "Bytes Sent/sec", name);
  114. list[1] = new PerformanceCounter("Network Interface", "Bytes Received/sec", name);
  115. try
  116. {
  117. list[0].NextValue();
  118. _netAdapterNames[name] = list;
  119. }
  120. catch(Exception)
  121. {}
  122. });
  123. }
  124. StringBuilder sbNetInfo = new StringBuilder();
  125. private bool GetProcessInfo()
  126. {
  127. try
  128. {
  129. if (_isTerminate) return true;
  130. string rtmonoitor = process_use(processRTname);
  131. string uimonoitor = process_use(processUIname);
  132. string systemMonitor = $"PC => {drive_use()}" +
  133. $"{cpu_use()}{cpu_use_byprocess()}" +
  134. $"{memory_use()}";
  135. sbNetInfo.Clear();
  136. foreach (var name in _netAdapterNames.Keys)
  137. {
  138. sbNetInfo.Append($" {name}:");
  139. var perCounter = _netAdapterNames[name];
  140. sbNetInfo.Append($"Bytes Sent/sec:{perCounter[0].NextValue()} b/s ");
  141. sbNetInfo.Append($"Bytes Received/sec:{perCounter[1].NextValue()} b/s ");
  142. }
  143. var diskInfo = $"Avg. Disk sec/Read:{_readDisk.NextValue()} Avg. Disk sec/Write:{_writeDisk.NextValue()} Avg.Disk sec/Transfer:{_transferDisk.NextValue()}";
  144. LOG.Write($"{ModuleName.System} ResourceMonitor RT Process Info: [{rtmonoitor}] ");
  145. LOG.Write($"{ModuleName.System} ResourceMonitor UI Process Info: [{uimonoitor}] ");
  146. LOG.Write($"{ModuleName.System} ResourceMonitor System Info: [{systemMonitor}] ");
  147. LOG.Write($"{ModuleName.System} ResourceMonitor Network Info: [{sbNetInfo.ToString()}] ");
  148. LOG.Write($"{ModuleName.System} ResourceMonitor Disk Read/Write Info: [{diskInfo}] ");
  149. }
  150. catch (Exception ex)
  151. {
  152. LOG.Write($"{ModuleName.System} Monitor Error happened: {ex}");
  153. }
  154. return true;
  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($" {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. private string cpu_use_byprocess()
  219. {
  220. StringBuilder sb = new StringBuilder();
  221. ManagementObjectCollection moc1 = ExecSearch("SELECT * FROM Win32_PerfFormattedData_PerfProc_Process");
  222. if (moc1 != null)
  223. {
  224. foreach (ManagementObject mo1 in moc1)
  225. {
  226. var pid = Convert.ToInt64(mo1.Properties["IDProcess"].Value.ToString());
  227. var name = mo1.Properties["Name"].Value.ToString();
  228. var workingSet = Convert.ToSingle(mo1.Properties["WorkingSet"].Value.ToString()) / (1024 * 1024);
  229. var percentProcessorTime = Convert.ToSingle(mo1.Properties["PercentProcessorTime"].Value.ToString()) / Environment.ProcessorCount;
  230. if (percentProcessorTime > 1 || workingSet > 200)
  231. {
  232. sb.Append($"{name}_{pid} CPU:{percentProcessorTime:F2} % WorkingSet:{workingSet:F2} MB ");
  233. }
  234. }
  235. }
  236. return sb.Length > 0 ? $" detail:[{sb.ToString()}] " : string.Empty;
  237. }
  238. //disk
  239. private string drive_use()
  240. {
  241. string drive_use = "";
  242. foreach (DriveInfo drive in DriveInfo.GetDrives())
  243. {
  244. if (drive.IsReady)
  245. {
  246. drive_use += $"{drive.Name}";
  247. drive_use += $" Total:{drive.TotalSize / 1024 / 1024 }MB";
  248. drive_use += $" Used:{(drive.TotalSize - drive.AvailableFreeSpace) / 1024 / 1024 }MB";
  249. drive_use += $" Free:{drive.AvailableFreeSpace / 1024 / 1024 }MB\t";
  250. }
  251. }
  252. return drive_use;
  253. }
  254. //memory
  255. private string memory_use()
  256. {
  257. string memory_use = "Memory status:" +
  258. $"Memory Available:{GetMemoryAvailable():F2}GB\t" +
  259. $"Memory Used:{GetMemoryUsed():F2}GB\t" +
  260. $"Memory Used Rate:{GetMemoryUsedRate():F2}%\t";
  261. return memory_use;
  262. }
  263. //MemoryAvailable
  264.         private double? GetMemoryAvailable()
  265. {
  266. double availablebytes = 0;
  267. var managementClassOs = new ManagementClass("Win32_OperatingSystem");
  268. foreach (var managementBaseObject in managementClassOs.GetInstances())
  269. if (managementBaseObject["FreePhysicalMemory"] != null)
  270. availablebytes = 1024 * double.Parse(managementBaseObject["FreePhysicalMemory"].ToString());
  271. return availablebytes / GbDiv;
  272. }
  273. //MemoryUsed
  274.         private double? GetMemoryUsed()
  275. {
  276. double? PhysicalMemory = GetPhysicalMemory();
  277. double? MemoryAvailable = GetMemoryAvailable();
  278. double? MemoryUsed = (double?)(PhysicalMemory - MemoryAvailable);
  279. double currentMemoryUsed = (double)MemoryUsed;
  280. return currentMemoryUsed;
  281. }
  282. //PhysicalMemory
  283. private long? GetPhysicalMemory()
  284. {
  285.             //获得物理内存
  286.             var managementClass = new ManagementClass("Win32_ComputerSystem");
  287. var managementObjectCollection = managementClass.GetInstances();
  288. //long PhysicalMemory;
  289. foreach (var managementBaseObject in managementObjectCollection)
  290. if (managementBaseObject["TotalPhysicalMemory"] != null)
  291. {
  292. return long.Parse(managementBaseObject["TotalPhysicalMemory"].ToString()) / GbDiv;
  293. }
  294. return null;
  295. }
  296. //MemoryUsedRate
  297. private double? GetMemoryUsedRate()
  298. {
  299. double? PhysicalMemory = GetPhysicalMemory();
  300. double? MemoryAvailable = GetMemoryAvailable();
  301. double? MemoryUsedRate = (double?)(PhysicalMemory - MemoryAvailable) / PhysicalMemory;
  302. return MemoryUsedRate.HasValue ? Convert.ToDouble(MemoryUsedRate * 100) : 0;
  303. }
  304. private static ManagementObjectCollection ExecSearch(string command)
  305. {
  306. try
  307. {
  308. ObjectQuery objQuery = new ObjectQuery(command);
  309. return new ManagementObjectSearcher(objQuery).Get();
  310. }
  311. catch (Exception ex)
  312. {
  313. LOG.Error($"ExecSearch exception:{ex}");
  314. }
  315. return null;
  316. }
  317. #region 单位转换进制
  318. private const int KbDiv = 1024;
  319. private const int MbDiv = 1024 * 1024;
  320. private const int GbDiv = 1024 * 1024 * 1024;
  321.         #endregion
  322. }
  323. }