MainForm.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Configuration;
  4. using System.Diagnostics;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Management;
  8. using System.Reflection;
  9. using System.Threading.Tasks;
  10. using System.Windows.Forms;
  11. using XdCxRhDW.Dto;
  12. using XdCxRhDW.WebApi;
  13. using XdCxRhDW.UI.Lib;
  14. namespace CpuCgServer
  15. {
  16. public partial class MainForm : Form
  17. {
  18. EnumSvrType svrType = EnumSvrType.CpuCgSvr;
  19. public MainForm()
  20. {
  21. InitializeComponent();
  22. LogHelper.Logger = info =>
  23. {
  24. try
  25. {
  26. this.Invoke(new Action(() =>
  27. {
  28. this.listBox1.Items.Insert(0, $"{info.LogTime:yyyyMMddHHmmss.fff}--{info.Msg}");
  29. if (this.listBox1.Items.Count > 1000)
  30. this.listBox1.Items.RemoveAt(this.listBox1.Items.Count - 1);
  31. }));
  32. }
  33. catch
  34. { }
  35. };
  36. }
  37. //清理10分钟之前的文件
  38. private async Task ClearLocalFile()
  39. {
  40. while (true)
  41. {
  42. try
  43. {
  44. var uploadFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "wwwroot");
  45. var files = Directory.EnumerateFiles(uploadFolder);
  46. foreach (var file in files)
  47. {
  48. FileInfo info = new FileInfo(file);
  49. if (info.CreationTime < DateTime.Now.AddMinutes(-10))
  50. {
  51. try
  52. {
  53. info.Delete();
  54. }
  55. catch (Exception ex)
  56. {
  57. await XdCxRhDW.UI.Lib.LogHelper.Error("清理wwwroot历史文件异常", ex);
  58. }
  59. }
  60. }
  61. }
  62. catch (Exception ex)
  63. {
  64. await XdCxRhDW.UI.Lib.LogHelper.Error("清理wwwroot历史文件异常", ex);
  65. }
  66. await Task.Delay(60 * 1000);
  67. }
  68. }
  69. private async void MainForm_LoadAsync(object sender, EventArgs e)
  70. {
  71. if (Debugger.IsAttached)//结束已启动的进程,方便调试
  72. {
  73. var pros = Process.GetProcessesByName(Assembly.GetExecutingAssembly().GetName().Name).OrderBy(p => p.StartTime).ToList();
  74. pros.RemoveAt(pros.Count - 1);
  75. foreach (var item in pros)
  76. {
  77. try
  78. {
  79. item.Kill();
  80. }
  81. catch
  82. { }
  83. }
  84. }
  85. try
  86. {
  87. if (Directory.Exists("tmp"))
  88. Directory.Delete("tmp");
  89. }
  90. catch
  91. { }
  92. var port = Convert.ToInt32(ConfigurationManager.AppSettings["LocalHttpPort"].Trim());
  93. var svrID = ConfigurationManager.AppSettings["SvrID"].Trim();
  94. var posPlatformAddr = ConfigurationManager.AppSettings["PosPlatformAddr"].Trim();
  95. LogHelper.BaseUrl = posPlatformAddr + "/api/";
  96. this.Text = svrType.GetEnumDisplayName() + "-" + svrID;
  97. string localIp;
  98. string getIpUrl = $"{posPlatformAddr}/api/task/getclientip";
  99. while (true)
  100. {
  101. try
  102. {
  103. var rsp = await HttpHelper.GetRequestAsync<string>(getIpUrl);
  104. if (rsp.code == 0)
  105. {
  106. await XdCxRhDW.UI.Lib.LogHelper.Error(rsp.msg);
  107. return;
  108. }
  109. else
  110. {
  111. localIp = rsp.data;
  112. }
  113. break;
  114. }
  115. catch (Exception ex)
  116. {
  117. await XdCxRhDW.UI.Lib.LogHelper.Error($"无法连接到平台{getIpUrl},请检测地址是否正确并确保平台防火墙允许端口通过", ex);
  118. await Task.Delay(5000);
  119. }
  120. }
  121. await XdCxRhDW.UI.Lib.LogHelper.Info($"本机IP={localIp}");
  122. IpHelper.SetLocalIp(localIp);
  123. string url;
  124. if (posPlatformAddr.EndsWith("/"))
  125. url = posPlatformAddr + "api/SvrReport/Report";
  126. else
  127. url = posPlatformAddr + "/api/SvrReport/Report";
  128. try
  129. {
  130. Startup.Start(port, $"{System.Reflection.Assembly.GetExecutingAssembly().GetName().Name}.xml", "XdCxRhDW.Dto.xml");
  131. await XdCxRhDW.UI.Lib.LogHelper.Info($"服务启动成功.接口地址http://{localIp}:{port}/swagger");
  132. }
  133. catch
  134. {
  135. try
  136. {
  137. await HttpHelper.PostRequestAsync(url, new SvrStateReportDto()
  138. {
  139. SvrID = svrID,
  140. SvrType = svrType,
  141. ReportType = 1,
  142. BaseHttpAddr = $"http://{IpHelper.GetLocalIp()}:{port}",
  143. DevId = ConfigurationManager.AppSettings["DevID"].Trim(),
  144. ModuleType = EnumModuleType.Port,
  145. ModuleState = EnumModuleState.Error,
  146. });
  147. }
  148. catch (Exception ex)
  149. {
  150. XdCxRhDW.Framework.LogHelper.Error("端口状态上报异常", ex);
  151. }
  152. }
  153. await HttpHelper.PostRequestAsync(url, new SvrStateReportDto()
  154. {
  155. SvrType = svrType,
  156. SvrID = svrID,
  157. ReportType = 0,
  158. BaseHttpAddr = $"http://{localIp}:{port}",
  159. SwaggerAddr = $"http://{localIp}:{port}/Swagger",
  160. DevId = ConfigurationManager.AppSettings["DevID"].Trim(),
  161. ModuleType = EnumModuleType.Soft,
  162. ModuleState = EnumModuleState.正常,
  163. });
  164. bool preSucceed = false;
  165. long id = 0;
  166. _=ClearLocalFile();
  167. while (!this.Disposing)
  168. {
  169. try
  170. {
  171. if (!preSucceed)
  172. await XdCxRhDW.UI.Lib.LogHelper.Info($"服务状态上报成功![url={url}]");
  173. preSucceed = true;
  174. await HttpHelper.PostRequestAsync(url, new SvrStateReportDto()
  175. {
  176. SvrType = svrType,
  177. SvrID = svrID,
  178. ID = id++,
  179. DevId = ConfigurationManager.AppSettings["DevID"].Trim(),
  180. ReportType = 0,
  181. BaseHttpAddr = $"http://{localIp}:{port}",
  182. SwaggerAddr = $"http://{localIp}:{port}/Swagger",
  183. ModuleType = EnumModuleType.Soft,
  184. ModuleState = EnumModuleState.空闲,
  185. });
  186. }
  187. catch (Exception ex)
  188. {
  189. await XdCxRhDW.UI.Lib.LogHelper.Error($"服务状态上报异常[url={url}]", ex);
  190. preSucceed = false;
  191. }
  192. var pro = Process.GetCurrentProcess();
  193. if ((pro.PrivateMemorySize64 >> 20) > 4096)//程序内存大于4096MB
  194. {
  195. try
  196. {
  197. await HttpHelper.PostRequestAsync(url, new SvrStateReportDto()
  198. {
  199. SvrType = svrType,
  200. SvrID = svrID,
  201. ReportType = 0,
  202. BaseHttpAddr = $"http://{localIp}:{port}",
  203. SwaggerAddr = $"http://{localIp}:{port}/Swagger",
  204. DevId = ConfigurationManager.AppSettings["DevID"].Trim(),
  205. ModuleType = EnumModuleType.Memory,
  206. ModuleState = EnumModuleState.Error,
  207. });
  208. }
  209. catch (Exception ex)
  210. {
  211. XdCxRhDW.Framework.LogHelper.Error("内存状态上报异常", ex);
  212. }
  213. }
  214. try
  215. {
  216. ManagementClass diskClass = new ManagementClass("Win32_LogicalDisk");
  217. ManagementObjectCollection disks = diskClass.GetInstances();
  218. foreach (ManagementObject disk in disks)
  219. {
  220. try
  221. {
  222. double totalSpace = Convert.ToDouble(disk["Size"]);
  223. if (totalSpace <= 0) continue;
  224. long freqSpace = Convert.ToInt64(disk["FreeSpace"]);
  225. if (freqSpace / totalSpace < 0.1 && id % 10 == 0)//磁盘可用空间不足10%
  226. {
  227. await XdCxRhDW.UI.Lib.LogHelper.Error($"{disk["Name"].ToString().Replace(":", "")}盘可用空间不足10%");
  228. await HttpHelper.PostRequestAsync(url, new SvrStateReportDto()
  229. {
  230. SvrType = svrType,
  231. SvrID = svrID,
  232. ReportType = 0,
  233. BaseHttpAddr = $"http://{localIp}:{port}",
  234. SwaggerAddr = $"http://{localIp}:{port}/Swagger",
  235. DevId = ConfigurationManager.AppSettings["DevID"].Trim(),
  236. ModuleType = EnumModuleType.Disk,
  237. ModuleState = EnumModuleState.Error,
  238. });
  239. }
  240. }
  241. catch (Exception ex)
  242. {
  243. XdCxRhDW.Framework.LogHelper.Error("磁盘状态上报异常", ex);
  244. }
  245. }
  246. }
  247. catch
  248. { }
  249. await Task.Delay(6000);
  250. }
  251. }
  252. private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
  253. {
  254. try
  255. {
  256. var port = Convert.ToInt32(ConfigurationManager.AppSettings["LocalHttpPort"].Trim());
  257. var svrID = ConfigurationManager.AppSettings["SvrID"].Trim();
  258. var posPlatformAddr = ConfigurationManager.AppSettings["PosPlatformAddr"].Trim();
  259. string url;
  260. if (posPlatformAddr.EndsWith("/"))
  261. url = posPlatformAddr + "api/SvrReport/Report";
  262. else
  263. url = posPlatformAddr + "/api/SvrReport/Report";
  264. _ = HttpHelper.PostRequestAsync(url, new SvrStateReportDto()
  265. {
  266. SvrID = svrID,
  267. SvrType = svrType,
  268. ReportType = 1,
  269. BaseHttpAddr = $"http://{IpHelper.GetLocalIp()}:{port}",
  270. DevId = ConfigurationManager.AppSettings["DevID"].Trim(),
  271. ModuleType = EnumModuleType.Soft,
  272. ModuleState = EnumModuleState.Error,
  273. });
  274. }
  275. catch (Exception ex)
  276. {
  277. _=XdCxRhDW.UI.Lib.LogHelper.Error("服务状态上报异常", ex);
  278. }
  279. }
  280. }
  281. }