using System.Diagnostics; using System.Text.Json; using ClassNotify.Server.Data; using ClassNotify.Server.Domain.Diagnostics; using ClassNotify.Server.Services; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; namespace ClassNotify.Server.Controllers; [ApiController] public class HealthDiagnosticsController : ControllerBase { private readonly ClassNotifyDbContext _db; private readonly OperationalHealthState _healthState; private readonly ISecurityService _securityService; private readonly IConfiguration _config; private readonly ILogger _logger; public HealthDiagnosticsController( ClassNotifyDbContext db, OperationalHealthState healthState, ISecurityService securityService, IConfiguration config, ILogger logger) { _db = db; _healthState = healthState; _securityService = securityService; _config = config; _logger = logger; } /// /// 进程存活探针: 仅判断 ASP.NET Core 主进程是否存活,不连数据库 /// [HttpGet("/health/live")] [AllowAnonymous] public IActionResult GetLive() { return Ok(new { status = "Healthy" }); } /// /// 流量就绪探针: 校验核心数据库连通性与响应时间 /// [HttpGet("/health/ready")] [AllowAnonymous] public async Task GetReady(CancellationToken ct) { var sw = Stopwatch.StartNew(); try { var canConnect = await _db.Database.CanConnectAsync(ct); sw.Stop(); if (!canConnect) { return StatusCode(503, new { status = "Unhealthy", error = "Database connection failed" }); } if (sw.ElapsedMilliseconds > 500) { return StatusCode(200, new { status = "Degraded", latencyMs = sw.ElapsedMilliseconds }); } return Ok(new { status = "Healthy", latencyMs = sw.ElapsedMilliseconds }); } catch (Exception ex) { sw.Stop(); _logger.LogError(ex, "Ready health check failed"); return StatusCode(503, new { status = "Unhealthy", error = "Database check exception" }); } } /// /// 超管深度运维诊断端点: 返回数据库、磁盘、备份状态、清理任务及活跃连接全量指标 /// 绝不暴露数据库密码、连接串或任何敏感密钥 /// [HttpGet("api/health/diagnostics")] [Authorize(Roles = "SuperAdmin")] public async Task> GetDiagnostics(CancellationToken ct) { var dto = new DiagnosticsDto { ServerUtc = DateTimeOffset.UtcNow, UptimeSeconds = (long)(DateTimeOffset.UtcNow - _healthState.StartedAtUtc).TotalSeconds, ReleaseId = Environment.GetEnvironmentVariable("CLASSNOTIFY_RELEASE_ID") ?? (System.IO.File.Exists("release.txt") ? System.IO.File.ReadAllText("release.txt").Trim() : null) ?? _config["Release:Id"] ?? "20260925-P25-RC0" }; // 1. Database Check var swDb = Stopwatch.StartNew(); try { var canConnect = await _db.Database.CanConnectAsync(ct); swDb.Stop(); if (canConnect) { dto.Database.LatencyMs = swDb.ElapsedMilliseconds; if (swDb.ElapsedMilliseconds <= 500) { dto.Database.Status = "Healthy"; dto.Database.Summary = $"PostgreSQL connected ({swDb.ElapsedMilliseconds}ms)"; } else { dto.Database.Status = "Degraded"; dto.Database.Summary = $"PostgreSQL latency elevated ({swDb.ElapsedMilliseconds}ms)"; } dto.Database.LastSuccessUtc = DateTimeOffset.UtcNow; } else { dto.Database.Status = "Unhealthy"; dto.Database.Summary = "PostgreSQL cannot connect"; } } catch (Exception ex) { swDb.Stop(); dto.Database.Status = "Unhealthy"; dto.Database.Summary = "PostgreSQL error"; _logger.LogWarning(ex, "Database diagnostic probe failed"); } // 2. Disk Check try { var drive = new DriveInfo(Path.GetPathRoot(AppContext.BaseDirectory) ?? "/"); var freeBytes = drive.AvailableFreeSpace; var totalBytes = drive.TotalSize; var freePercent = (double)freeBytes / totalBytes * 100.0; var freeGb = freeBytes / (1024.0 * 1024 * 1024); if (freePercent >= 10.0) { dto.Disk.Status = "Healthy"; dto.Disk.Summary = $"可用空间 {freeGb:F1} GB ({freePercent:F1}%)"; } else if (freePercent >= 5.0) { dto.Disk.Status = "Degraded"; dto.Disk.Summary = $"磁盘余量偏低: {freeGb:F1} GB ({freePercent:F1}%)"; } else { dto.Disk.Status = "Unhealthy"; dto.Disk.Summary = $"磁盘空间不足严重告警: {freeGb:F1} GB ({freePercent:F1}%)"; } } catch { dto.Disk.Status = "Healthy"; dto.Disk.Summary = "Disk check skipped on current environment"; } // 3. Backup Check (reads status file generated by classnotify-backup.sh) var backupStatusPath = OperatingSystem.IsLinux() ? "/var/lib/classnotify/ops/backup-status.json" : Path.Combine(AppContext.BaseDirectory, "backup-status.json"); if (System.IO.File.Exists(backupStatusPath)) { try { var json = await System.IO.File.ReadAllTextAsync(backupStatusPath, ct); using var doc = JsonDocument.Parse(json); if (doc.RootElement.TryGetProperty("lastSuccessUtc", out var lastUtcProp) && DateTimeOffset.TryParse(lastUtcProp.GetString(), out var lastUtc)) { dto.Backup.LastSuccessUtc = lastUtc; var ageHours = (DateTimeOffset.UtcNow - lastUtc).TotalHours; if (ageHours < 26) { dto.Backup.Status = "Healthy"; dto.Backup.Summary = $"最新自动备份完成于 {ageHours:F1} 小时前"; } else if (ageHours < 48) { dto.Backup.Status = "Degraded"; dto.Backup.Summary = $"自动备份超过 24 小时未更新 ({ageHours:F1} 小时前)"; } else { dto.Backup.Status = "Unhealthy"; dto.Backup.Summary = $"备份超期严重告警: 距上次备份已达 {ageHours:F1} 小时"; } } } catch { dto.Backup.Status = "Degraded"; dto.Backup.Summary = "无法读取备份状态文件"; } } else { dto.Backup.Status = "Healthy"; dto.Backup.Summary = "系统备份任务就绪 (待首期周期触发)"; } // 4. Visual Receipt Cleanup Check if (_healthState.LastVisualReceiptCleanupSuccessUtc.HasValue) { dto.VisualReceiptCleanup.LastSuccessUtc = _healthState.LastVisualReceiptCleanupSuccessUtc; var ageHours = (DateTimeOffset.UtcNow - _healthState.LastVisualReceiptCleanupSuccessUtc.Value).TotalHours; if (ageHours < 2) { dto.VisualReceiptCleanup.Status = "Healthy"; dto.VisualReceiptCleanup.Summary = $"视觉回执定时清理正常运行 ({ageHours * 60:F0} 分钟前)"; } else if (ageHours < 6) { dto.VisualReceiptCleanup.Status = "Degraded"; dto.VisualReceiptCleanup.Summary = $"视觉回执清理已延迟 {ageHours:F1} 小时"; } else { dto.VisualReceiptCleanup.Status = "Unhealthy"; dto.VisualReceiptCleanup.Summary = $"视觉回执清理停滞 ({ageHours:F1} 小时未执行)"; } } else { dto.VisualReceiptCleanup.Status = "Healthy"; dto.VisualReceiptCleanup.Summary = "视觉回执清理任务已启动"; } // 5. Active Connections Count (Information only, does not degrade server health) dto.ActiveDeviceConnections = _healthState.ActiveDeviceConnections; dto.ActiveTeacherConnections = _healthState.ActiveTeacherConnections; // 6. Overall Status Determination if (dto.Database.Status == "Unhealthy" || dto.Disk.Status == "Unhealthy" || dto.Backup.Status == "Unhealthy") { dto.OverallStatus = "Unhealthy"; } else if (dto.Database.Status == "Degraded" || dto.Disk.Status == "Degraded" || dto.Backup.Status == "Degraded" || dto.VisualReceiptCleanup.Status == "Degraded") { dto.OverallStatus = "Degraded"; } else { dto.OverallStatus = "Healthy"; } return Ok(dto); } }