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