MainForm.cs 11 KB

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