MdpSourceHealthCheckJob.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. using Admin.NET.Plugin.AiDOP.DataPlatform;
  2. using Admin.NET.Plugin.AiDOP.DataPlatform.Inbound;
  3. using Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
  4. using Admin.NET.Plugin.AiDOP.Entity.DataPlatform;
  5. using Furion.Schedule;
  6. using Microsoft.Extensions.DependencyInjection;
  7. using Microsoft.Extensions.Logging;
  8. namespace Admin.NET.Plugin.AiDOP.Job;
  9. /// <summary>
  10. /// 定时探活 mdp_source:DB SELECT 1 / API GET baseUrl(或 /health)。
  11. /// </summary>
  12. [JobDetail("job_mdp_source_health", Description = "MDP 数据源健康检查", GroupName = "default", Concurrent = false)]
  13. [PeriodSeconds(300, TriggerId = "trigger_mdp_source_health", Description = "每 5 分钟探活数据源", RunOnStart = false)]
  14. public class MdpSourceHealthCheckJob : IJob
  15. {
  16. private readonly IServiceScopeFactory _scopeFactory;
  17. private readonly ILogger _logger;
  18. public MdpSourceHealthCheckJob(IServiceScopeFactory scopeFactory, ILoggerFactory loggerFactory)
  19. {
  20. _scopeFactory = scopeFactory;
  21. _logger = loggerFactory.CreateLogger(nameof(MdpSourceHealthCheckJob));
  22. }
  23. public async Task ExecuteAsync(JobExecutingContext context, CancellationToken stoppingToken)
  24. {
  25. if (!AidopJobGate.ShouldRun(nameof(MdpSourceHealthCheckJob), _logger)) return;
  26. using var scope = _scopeFactory.CreateScope();
  27. var db = scope.ServiceProvider.GetRequiredService<ISqlSugarClient>();
  28. var scopeFactory = scope.ServiceProvider.GetRequiredService<MdpSourceScopeFactory>();
  29. var egress = scope.ServiceProvider.GetRequiredService<MdpApiPullEgress>();
  30. var sources = await db.Queryable<MdpSource>().Where(x => x.Status == 1).ToListAsync(stoppingToken);
  31. var ok = 0;
  32. var fail = 0;
  33. foreach (var src in sources)
  34. {
  35. stoppingToken.ThrowIfCancellationRequested();
  36. var now = DateTime.Now;
  37. try
  38. {
  39. if (string.Equals(src.SourceType, "DB", StringComparison.OrdinalIgnoreCase))
  40. {
  41. var illegal = MdpSourceScopeFactory.IllegalExtraKeys(src.DbType, src.DbExtraParams);
  42. var illegalNote = illegal.Count == 0
  43. ? null
  44. : $"db_extra_params 含非法关键字 {string.Join(",", illegal)},已忽略";
  45. var scopeDb = await scopeFactory.GetScopeAsync(src, stoppingToken);
  46. await scopeDb.Ado.GetIntAsync("SELECT 1");
  47. src.HealthStatus = 1;
  48. src.HealthMsg = illegalNote == null ? "OK" : $"OK({illegalNote})";
  49. ok++;
  50. }
  51. else if (string.Equals(src.SourceType, "API", StringComparison.OrdinalIgnoreCase))
  52. {
  53. if (string.IsNullOrWhiteSpace(src.ApiBaseUrl))
  54. throw new InvalidOperationException("api_base_url 为空");
  55. var endpoint = new Uri(src.ApiBaseUrl.TrimEnd('/') + "/");
  56. using var http = egress.Open(src.TenantId, src.Id, endpoint, requireHttps: false);
  57. http.Timeout = TimeSpan.FromSeconds(15);
  58. using var resp = await http.GetAsync(endpoint, HttpCompletionOption.ResponseHeadersRead, stoppingToken);
  59. src.HealthStatus = (int)resp.StatusCode is >= 200 and < 500 ? 1 : 0;
  60. src.HealthMsg = $"HTTP {(int)resp.StatusCode}";
  61. if (src.HealthStatus == 1) ok++; else fail++;
  62. }
  63. else if (string.Equals(src.SourceType, "API_INBOUND", StringComparison.OrdinalIgnoreCase))
  64. {
  65. src.HealthStatus = 1;
  66. src.HealthMsg = "OK";
  67. ok++;
  68. }
  69. else
  70. {
  71. src.HealthStatus = 0;
  72. src.HealthMsg = $"未知 source_type={src.SourceType}";
  73. fail++;
  74. }
  75. }
  76. catch (Exception ex)
  77. {
  78. src.HealthStatus = 0;
  79. var code = ClassifyHealthFailure(ex);
  80. var illegal = string.Equals(src.SourceType, "DB", StringComparison.OrdinalIgnoreCase)
  81. ? MdpSourceScopeFactory.IllegalExtraKeys(src.DbType, src.DbExtraParams)
  82. : Array.Empty<string>();
  83. var prefix = illegal.Count == 0
  84. ? ""
  85. : $"db_extra_params 含非法关键字 {string.Join(",", illegal)},已忽略。";
  86. src.HealthMsg = prefix + code + " " + SafeHealthMessage(ex.Message);
  87. if (src.HealthMsg.Length > 480)
  88. src.HealthMsg = src.HealthMsg[..480];
  89. _logger.LogWarning(
  90. "[MdpSourceHealthCheckJob] source={SourceCode} code={Code}",
  91. src.SourceCode, code);
  92. fail++;
  93. }
  94. src.LastHealthCheck = now;
  95. src.UpdateTime = now;
  96. await db.Updateable(src)
  97. .UpdateColumns(x => new { x.HealthStatus, x.HealthMsg, x.LastHealthCheck, x.UpdateTime })
  98. .ExecuteCommandAsync(stoppingToken);
  99. }
  100. if (sources.Count > 0)
  101. _logger.LogInformation("[MdpSourceHealthCheckJob] total={Total} ok={Ok} fail={Fail}", sources.Count, ok, fail);
  102. await ExpireInboundSnapshotsAsync(scope, stoppingToken);
  103. await CheckInboundSilenceAsync(db, sources, stoppingToken);
  104. }
  105. /// <summary>顺带把 OPEN 且已过期的快照置 EXPIRED;未 commit 不产生删除语义。</summary>
  106. private async Task ExpireInboundSnapshotsAsync(IServiceScope scope, CancellationToken ct)
  107. {
  108. try
  109. {
  110. var snaps = scope.ServiceProvider.GetRequiredService<MdpInboundSnapshotService>();
  111. await snaps.ExpireStaleOpenAsync(ct);
  112. }
  113. catch (Exception ex)
  114. {
  115. _logger.LogWarning(ex, "[MdpSourceHealthCheckJob] inbound snapshot expire failed");
  116. }
  117. }
  118. /// <summary>
  119. /// 入站实体沉默:inbound_enabled=1 且配置了 silence_alert_hours,
  120. /// 最近 COMMITTED 超过阈值且当天命中 silence_calendar(空=每天)则写回源健康告警。
  121. /// 从未推送过的实体以 update_time/create_time 为基线。
  122. /// </summary>
  123. private async Task CheckInboundSilenceAsync(
  124. ISqlSugarClient db, List<MdpSource> sources, CancellationToken ct)
  125. {
  126. List<MdpEntity> entities;
  127. try
  128. {
  129. entities = await db.Queryable<MdpEntity>()
  130. .Where(e => e.InboundEnabled == 1 && e.SilenceAlertHours != null)
  131. .ToListAsync(ct);
  132. }
  133. catch (Exception ex)
  134. {
  135. _logger.LogWarning(ex, "[MdpSourceHealthCheckJob] inbound silence query entities failed");
  136. return;
  137. }
  138. if (entities.Count == 0)
  139. return;
  140. var today = DateTime.Now;
  141. var isoDow = today.DayOfWeek == DayOfWeek.Sunday ? 7 : (int)today.DayOfWeek;
  142. var alertsBySource = new Dictionary<long, List<string>>();
  143. foreach (var entity in entities)
  144. {
  145. ct.ThrowIfCancellationRequested();
  146. if (!HitsSilenceCalendar(entity.SilenceCalendar, isoDow))
  147. continue;
  148. DateTime? lastCommitted = null;
  149. try
  150. {
  151. var last = await db.Queryable<MdpInboundRequest>()
  152. .Where(r => r.Status == "COMMITTED")
  153. .Where("UPPER(entity_code) = @code", new { code = entity.EntityCode.ToUpperInvariant() })
  154. .OrderBy(r => r.CreateTime, OrderByType.Desc)
  155. .FirstAsync(ct);
  156. lastCommitted = last?.CreateTime;
  157. }
  158. catch (Exception ex)
  159. {
  160. _logger.LogWarning(ex, "[MdpSourceHealthCheckJob] inbound silence query requests failed entity={Entity}", entity.EntityCode);
  161. continue;
  162. }
  163. var baseline = lastCommitted
  164. ?? (entity.UpdateTime != default ? entity.UpdateTime : entity.CreateTime);
  165. var hours = entity.SilenceAlertHours.GetValueOrDefault();
  166. if (hours <= 0)
  167. continue;
  168. if ((today - baseline).TotalHours <= hours)
  169. continue;
  170. var lastText = lastCommitted.HasValue
  171. ? lastCommitted.Value.ToString("yyyy-MM-dd HH:mm:ss")
  172. : "never";
  173. var msg = $"INBOUND silence: {entity.EntityCode} last COMMITTED {lastText} (threshold {hours}h)";
  174. _logger.LogWarning("[MdpSourceHealthCheckJob] {Message}", msg);
  175. if (!alertsBySource.TryGetValue(entity.SourceId, out var list))
  176. {
  177. list = [];
  178. alertsBySource[entity.SourceId] = list;
  179. }
  180. list.Add(msg);
  181. }
  182. var sourceById = sources.ToDictionary(s => s.Id);
  183. foreach (var (sourceId, messages) in alertsBySource)
  184. {
  185. if (!sourceById.TryGetValue(sourceId, out var src))
  186. {
  187. src = await db.Queryable<MdpSource>().Where(s => s.Id == sourceId).FirstAsync(ct);
  188. if (src == null)
  189. continue;
  190. }
  191. var now = DateTime.Now;
  192. src.HealthStatus = 0;
  193. src.HealthMsg = Truncate(string.Join("; ", messages), 480);
  194. src.LastHealthCheck = now;
  195. src.UpdateTime = now;
  196. await db.Updateable(src)
  197. .UpdateColumns(x => new { x.HealthStatus, x.HealthMsg, x.LastHealthCheck, x.UpdateTime })
  198. .ExecuteCommandAsync(ct);
  199. }
  200. }
  201. private static bool HitsSilenceCalendar(string calendar, int isoDow)
  202. {
  203. if (string.IsNullOrWhiteSpace(calendar))
  204. return true;
  205. var days = calendar.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
  206. return days.Any(d => int.TryParse(d, out var n) && n == isoDow);
  207. }
  208. private static string Truncate(string s, int max) =>
  209. string.IsNullOrEmpty(s) || s.Length <= max ? s : s[..max];
  210. internal static string ClassifyHealthFailure(Exception ex)
  211. {
  212. if (ex is MdpSourceSecretException secret)
  213. return secret.Code;
  214. for (var current = ex; current != null; current = current.InnerException)
  215. {
  216. var number = current.GetType().GetProperty("Number")?.GetValue(current);
  217. if (number is int n && (n == 1045 || n == 18456))
  218. return "AUTH_FAILED";
  219. var msg = current.Message ?? "";
  220. if (msg.Contains("登录失败", StringComparison.Ordinal)
  221. || msg.Contains("Login failed", StringComparison.OrdinalIgnoreCase)
  222. || msg.Contains("Access denied", StringComparison.OrdinalIgnoreCase))
  223. return "AUTH_FAILED";
  224. if (msg.Contains("timeout", StringComparison.OrdinalIgnoreCase)
  225. || msg.Contains("Unable to connect", StringComparison.OrdinalIgnoreCase)
  226. || msg.Contains("network-related", StringComparison.OrdinalIgnoreCase)
  227. || msg.Contains("连接", StringComparison.Ordinal))
  228. return "NETWORK_FAILED";
  229. }
  230. return "FAILED";
  231. }
  232. internal static string SafeHealthMessage(string? message)
  233. {
  234. var text = message ?? "";
  235. if (text.Contains("Password=", StringComparison.OrdinalIgnoreCase)
  236. || text.Contains("Pwd=", StringComparison.OrdinalIgnoreCase)
  237. || text.Contains("ConnectionString", StringComparison.OrdinalIgnoreCase)
  238. || text.Contains("Server=", StringComparison.OrdinalIgnoreCase))
  239. return "连接失败,详情见运行日志";
  240. return text.Length > 400 ? text[..400] : text;
  241. }
  242. }