MdpSourceHealthCheckJob.cs 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. using Admin.NET.Plugin.AiDOP.DataPlatform;
  2. using Admin.NET.Plugin.AiDOP.DataPlatform.Inbound;
  3. using Admin.NET.Plugin.AiDOP.Entity.DataPlatform;
  4. using Furion.Schedule;
  5. using Microsoft.Extensions.DependencyInjection;
  6. using Microsoft.Extensions.Logging;
  7. namespace Admin.NET.Plugin.AiDOP.Job;
  8. /// <summary>
  9. /// 定时探活 mdp_source:DB SELECT 1 / API GET baseUrl(或 /health)。
  10. /// </summary>
  11. [JobDetail("job_mdp_source_health", Description = "MDP 数据源健康检查", GroupName = "default", Concurrent = false)]
  12. [PeriodSeconds(300, TriggerId = "trigger_mdp_source_health", Description = "每 5 分钟探活数据源", RunOnStart = false)]
  13. public class MdpSourceHealthCheckJob : IJob
  14. {
  15. private readonly IServiceScopeFactory _scopeFactory;
  16. private readonly ILogger _logger;
  17. public MdpSourceHealthCheckJob(IServiceScopeFactory scopeFactory, ILoggerFactory loggerFactory)
  18. {
  19. _scopeFactory = scopeFactory;
  20. _logger = loggerFactory.CreateLogger(nameof(MdpSourceHealthCheckJob));
  21. }
  22. public async Task ExecuteAsync(JobExecutingContext context, CancellationToken stoppingToken)
  23. {
  24. using var scope = _scopeFactory.CreateScope();
  25. var db = scope.ServiceProvider.GetRequiredService<ISqlSugarClient>();
  26. var scopeFactory = scope.ServiceProvider.GetRequiredService<MdpSourceScopeFactory>();
  27. using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(15) };
  28. var sources = await db.Queryable<MdpSource>().Where(x => x.Status == 1).ToListAsync(stoppingToken);
  29. var ok = 0;
  30. var fail = 0;
  31. foreach (var src in sources)
  32. {
  33. stoppingToken.ThrowIfCancellationRequested();
  34. var now = DateTime.Now;
  35. try
  36. {
  37. if (string.Equals(src.SourceType, "DB", StringComparison.OrdinalIgnoreCase))
  38. {
  39. var scopeDb = await scopeFactory.GetScopeAsync(src.SourceCode, stoppingToken);
  40. await scopeDb.Ado.GetIntAsync("SELECT 1");
  41. src.HealthStatus = 1;
  42. src.HealthMsg = "OK";
  43. ok++;
  44. }
  45. else if (string.Equals(src.SourceType, "API", StringComparison.OrdinalIgnoreCase))
  46. {
  47. if (string.IsNullOrWhiteSpace(src.ApiBaseUrl))
  48. throw new InvalidOperationException("api_base_url 为空");
  49. var url = src.ApiBaseUrl.TrimEnd('/') + "/";
  50. using var resp = await http.GetAsync(url, stoppingToken);
  51. src.HealthStatus = (int)resp.StatusCode is >= 200 and < 500 ? 1 : 0;
  52. src.HealthMsg = $"HTTP {(int)resp.StatusCode}";
  53. if (src.HealthStatus == 1) ok++; else fail++;
  54. }
  55. else if (string.Equals(src.SourceType, "API_INBOUND", StringComparison.OrdinalIgnoreCase))
  56. {
  57. src.HealthStatus = 1;
  58. src.HealthMsg = "OK";
  59. ok++;
  60. }
  61. else
  62. {
  63. src.HealthStatus = 0;
  64. src.HealthMsg = $"未知 source_type={src.SourceType}";
  65. fail++;
  66. }
  67. }
  68. catch (Exception ex)
  69. {
  70. src.HealthStatus = 0;
  71. src.HealthMsg = ex.Message.Length > 480 ? ex.Message[..480] : ex.Message;
  72. fail++;
  73. }
  74. src.LastHealthCheck = now;
  75. src.UpdateTime = now;
  76. await db.Updateable(src)
  77. .UpdateColumns(x => new { x.HealthStatus, x.HealthMsg, x.LastHealthCheck, x.UpdateTime })
  78. .ExecuteCommandAsync(stoppingToken);
  79. }
  80. if (sources.Count > 0)
  81. _logger.LogInformation("[MdpSourceHealthCheckJob] total={Total} ok={Ok} fail={Fail}", sources.Count, ok, fail);
  82. await ExpireInboundSnapshotsAsync(scope, stoppingToken);
  83. await CheckInboundSilenceAsync(db, sources, stoppingToken);
  84. }
  85. /// <summary>顺带把 OPEN 且已过期的快照置 EXPIRED;未 commit 不产生删除语义。</summary>
  86. private async Task ExpireInboundSnapshotsAsync(IServiceScope scope, CancellationToken ct)
  87. {
  88. try
  89. {
  90. var snaps = scope.ServiceProvider.GetRequiredService<MdpInboundSnapshotService>();
  91. await snaps.ExpireStaleOpenAsync(ct);
  92. }
  93. catch (Exception ex)
  94. {
  95. _logger.LogWarning(ex, "[MdpSourceHealthCheckJob] inbound snapshot expire failed");
  96. }
  97. }
  98. /// <summary>
  99. /// 入站实体沉默:inbound_enabled=1 且配置了 silence_alert_hours,
  100. /// 最近 COMMITTED 超过阈值且当天命中 silence_calendar(空=每天)则写回源健康告警。
  101. /// 从未推送过的实体以 update_time/create_time 为基线。
  102. /// </summary>
  103. private async Task CheckInboundSilenceAsync(
  104. ISqlSugarClient db, List<MdpSource> sources, CancellationToken ct)
  105. {
  106. List<MdpEntity> entities;
  107. try
  108. {
  109. entities = await db.Queryable<MdpEntity>()
  110. .Where(e => e.InboundEnabled == 1 && e.SilenceAlertHours != null)
  111. .ToListAsync(ct);
  112. }
  113. catch (Exception ex)
  114. {
  115. _logger.LogWarning(ex, "[MdpSourceHealthCheckJob] inbound silence query entities failed");
  116. return;
  117. }
  118. if (entities.Count == 0)
  119. return;
  120. var today = DateTime.Now;
  121. var isoDow = today.DayOfWeek == DayOfWeek.Sunday ? 7 : (int)today.DayOfWeek;
  122. var alertsBySource = new Dictionary<long, List<string>>();
  123. foreach (var entity in entities)
  124. {
  125. ct.ThrowIfCancellationRequested();
  126. if (!HitsSilenceCalendar(entity.SilenceCalendar, isoDow))
  127. continue;
  128. DateTime? lastCommitted = null;
  129. try
  130. {
  131. var last = await db.Queryable<MdpInboundRequest>()
  132. .Where(r => r.Status == "COMMITTED")
  133. .Where("UPPER(entity_code) = @code", new SugarParameter("@code", entity.EntityCode.ToUpperInvariant()))
  134. .OrderBy(r => r.CreateTime, OrderByType.Desc)
  135. .FirstAsync(ct);
  136. lastCommitted = last?.CreateTime;
  137. }
  138. catch (Exception ex)
  139. {
  140. _logger.LogWarning(ex, "[MdpSourceHealthCheckJob] inbound silence query requests failed entity={Entity}", entity.EntityCode);
  141. continue;
  142. }
  143. var baseline = lastCommitted
  144. ?? (entity.UpdateTime != default ? entity.UpdateTime : entity.CreateTime);
  145. var hours = entity.SilenceAlertHours.GetValueOrDefault();
  146. if (hours <= 0)
  147. continue;
  148. if ((today - baseline).TotalHours <= hours)
  149. continue;
  150. var lastText = lastCommitted.HasValue
  151. ? lastCommitted.Value.ToString("yyyy-MM-dd HH:mm:ss")
  152. : "never";
  153. var msg = $"INBOUND silence: {entity.EntityCode} last COMMITTED {lastText} (threshold {hours}h)";
  154. _logger.LogWarning("[MdpSourceHealthCheckJob] {Message}", msg);
  155. if (!alertsBySource.TryGetValue(entity.SourceId, out var list))
  156. {
  157. list = [];
  158. alertsBySource[entity.SourceId] = list;
  159. }
  160. list.Add(msg);
  161. }
  162. var sourceById = sources.ToDictionary(s => s.Id);
  163. foreach (var (sourceId, messages) in alertsBySource)
  164. {
  165. if (!sourceById.TryGetValue(sourceId, out var src))
  166. {
  167. src = await db.Queryable<MdpSource>().Where(s => s.Id == sourceId).FirstAsync(ct);
  168. if (src == null)
  169. continue;
  170. }
  171. var now = DateTime.Now;
  172. src.HealthStatus = 0;
  173. src.HealthMsg = Truncate(string.Join("; ", messages), 480);
  174. src.LastHealthCheck = now;
  175. src.UpdateTime = now;
  176. await db.Updateable(src)
  177. .UpdateColumns(x => new { x.HealthStatus, x.HealthMsg, x.LastHealthCheck, x.UpdateTime })
  178. .ExecuteCommandAsync(ct);
  179. }
  180. }
  181. private static bool HitsSilenceCalendar(string calendar, int isoDow)
  182. {
  183. if (string.IsNullOrWhiteSpace(calendar))
  184. return true;
  185. var days = calendar.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
  186. return days.Any(d => int.TryParse(d, out var n) && n == isoDow);
  187. }
  188. private static string Truncate(string s, int max) =>
  189. string.IsNullOrEmpty(s) || s.Length <= max ? s : s[..max];
  190. }