AppHostedService.cs 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. using FastGithub.Configuration;
  2. using Microsoft.Extensions.Hosting;
  3. using Microsoft.Extensions.Logging;
  4. using Microsoft.Extensions.Options;
  5. using System;
  6. using System.Diagnostics;
  7. using System.Linq;
  8. using System.Net;
  9. using System.Net.Http;
  10. using System.Threading;
  11. using System.Threading.Tasks;
  12. namespace FastGithub
  13. {
  14. /// <summary>
  15. /// app后台服务
  16. /// </summary>
  17. sealed class AppHostedService : BackgroundService
  18. {
  19. private readonly IHost host;
  20. private readonly IOptions<AppOptions> appOptions;
  21. private readonly IOptions<FastGithubOptions> fastGithubOptions;
  22. private readonly ILogger<AppHostedService> logger;
  23. public AppHostedService(
  24. IHost host,
  25. IOptions<AppOptions> appOptions,
  26. IOptions<FastGithubOptions> fastGithubOptions,
  27. ILogger<AppHostedService> logger)
  28. {
  29. this.host = host;
  30. this.appOptions = appOptions;
  31. this.fastGithubOptions = fastGithubOptions;
  32. this.logger = logger;
  33. }
  34. /// <summary>
  35. /// 启动完成
  36. /// </summary>
  37. /// <param name="cancellationToken"></param>
  38. /// <returns></returns>
  39. public override Task StartAsync(CancellationToken cancellationToken)
  40. {
  41. var version = ProductionVersion.Current;
  42. this.logger.LogInformation($"{nameof(FastGithub)}启动完成,当前版本为v{version},访问 https://github.com/dotnetcore/fastgithub 关注新版本");
  43. return base.StartAsync(cancellationToken);
  44. }
  45. /// <summary>
  46. /// 后台任务
  47. /// </summary>
  48. /// <param name="stoppingToken"></param>
  49. /// <returns></returns>
  50. protected override async Task ExecuteAsync(CancellationToken stoppingToken)
  51. {
  52. await Task.Delay(TimeSpan.FromSeconds(1d), stoppingToken);
  53. await this.CheckFastGithubProxyAsync(stoppingToken);
  54. await this.WaitForParentProcessExitAsync(stoppingToken);
  55. }
  56. /// <summary>
  57. /// 检测fastgithub代理设置
  58. /// </summary>
  59. /// <param name="cancellationToken"></param>
  60. /// <returns></returns>
  61. private async Task CheckFastGithubProxyAsync(CancellationToken cancellationToken)
  62. {
  63. if (OperatingSystem.IsWindows() == false)
  64. {
  65. try
  66. {
  67. if (await this.UseFastGithubProxyAsync() == false)
  68. {
  69. var httpProxyPort = this.fastGithubOptions.Value.HttpProxyPort;
  70. this.logger.LogWarning($"请设置系统自动代理为http://{IPAddress.Loopback}:{httpProxyPort},或手动代理http/https为{IPAddress.Loopback}:{httpProxyPort}");
  71. }
  72. }
  73. catch (Exception)
  74. {
  75. this.logger.LogWarning("尝试获取代理信息失败");
  76. }
  77. }
  78. }
  79. /// <summary>
  80. /// 应用fastgithub代理
  81. /// </summary>
  82. /// <param name="proxyServer"></param>
  83. /// <param name="httpProxyPort"></param>
  84. /// <returns></returns>
  85. private async Task<bool> UseFastGithubProxyAsync()
  86. {
  87. var systemProxy = HttpClient.DefaultProxy;
  88. if (systemProxy == null)
  89. {
  90. return false;
  91. }
  92. var domain = this.fastGithubOptions.Value.DomainConfigs.Keys.FirstOrDefault();
  93. if (domain == null)
  94. {
  95. return true;
  96. }
  97. var destination = new Uri($"https://{domain.Replace('*', 'a')}");
  98. var proxyServer = systemProxy.GetProxy(destination);
  99. if (proxyServer == null)
  100. {
  101. return false;
  102. }
  103. var httpProxyPort = this.fastGithubOptions.Value.HttpProxyPort;
  104. if (proxyServer.Port != httpProxyPort)
  105. {
  106. return false;
  107. }
  108. if (IPAddress.TryParse(proxyServer.Host, out var address))
  109. {
  110. return IPAddress.IsLoopback(address);
  111. }
  112. try
  113. {
  114. var addresses = await Dns.GetHostAddressesAsync(proxyServer.Host);
  115. return addresses.Any(item => IPAddress.IsLoopback(item));
  116. }
  117. catch (Exception)
  118. {
  119. return false;
  120. }
  121. }
  122. /// <summary>
  123. /// 等待父进程退出
  124. /// </summary>
  125. /// <param name="cancellationToken"></param>
  126. /// <returns></returns>
  127. private async Task WaitForParentProcessExitAsync(CancellationToken cancellationToken)
  128. {
  129. var parentId = this.appOptions.Value.ParentProcessId;
  130. if (parentId <= 0)
  131. {
  132. return;
  133. }
  134. try
  135. {
  136. Process.GetProcessById(parentId).WaitForExit();
  137. }
  138. catch (Exception ex)
  139. {
  140. this.logger.LogError(ex, $"获取进程{parentId}异常");
  141. }
  142. finally
  143. {
  144. this.logger.LogInformation($"正在主动关闭,因为父进程已退出");
  145. await this.host.StopAsync(cancellationToken);
  146. }
  147. }
  148. }
  149. }