using System.Globalization; using System.Text; using System.Text.Json; using Chronos.Core.Diagnostics; using Chronos.Core.Model; using Chronos.Data; using Chronos.Data.Processing; using Chronos.Server.Configuration; using Chronos.Server.Jobs; using Chronos.Server.Security; using Chronos.Server.Storage; namespace Chronos.Server.Api; /// /// GET /api/v1/server/diagnostics (BRIEF §22 Phase 8; ManageArchive): a zip with the environment report, the /// effective configuration, the encoders, the latest failed jobs and the server logs. Everything passes through /// (admin and database passwords, tokens and keys are removed); no archive file is included. /// public static class DiagnosticsEndpoints { /// Failed jobs included, newest first. public const int FailedJobs = 100; public static void Map(RouteGroupBuilder api) => api.MapGet("/server/diagnostics", DownloadAsync).Requires(Permissions.ManageArchive); private static async Task DownloadAsync(HttpContext context, Caller caller, ChronosDatabase db, ServerOptions options, ServerState state, AuditLog audit, TimeProvider time, VolumeSpace volumes, IServiceProvider services) { var ct = context.RequestAborted; var failures = (await db.Jobs.ListAsync(JobState.Failed, FailedJobs, null, ct)).Items; var report = Report(options, state, time, volumes); var settings = JsonSerializer.Serialize(options, ServerOptionsJson.Default.ServerOptions); var encoders = Encoders(services.GetService()); // The bundle is built in a temporary file (zip writes are synchronous and logs can be large) that no crash leaves // behind: Windows deletes it when the handle closes; elsewhere it is unlinked at once and lives on through the // open handle (DeleteOnClose there would unlink by name at close, possibly a newer file of the same name). var temp = Path.GetTempFileName(); var file = new FileStream(temp, FileMode.Create, FileAccess.ReadWrite, FileShare.None, 1 << 16, OperatingSystem.IsWindows() ? FileOptions.DeleteOnClose : FileOptions.None); if (!OperatingSystem.IsWindows()) File.Delete(temp); try { await Task.Run(() => { using var bundle = new DiagnosticsArchive(file); bundle.AddText("environment.txt", report); bundle.AddJson("settings.json", settings); bundle.AddText("encoders.txt", encoders); bundle.AddJobs("jobs-failed.json", failures); bundle.AddLogs(options.LogPath, tailBytes: options.DiagnosticsLogMb * LogFileOptions.BytesPerMb, cancellationToken: ct); }, ct); file.Position = 0; } catch { await file.DisposeAsync(); throw; } await audit.WriteAsync(caller, context, "server_diagnostics", "server"); context.Response.Headers.CacheControl = "no-store"; var name = string.Create(CultureInfo.InvariantCulture, $"chronos-server-diagnostics-{time.GetUtcNow():yyyyMMdd-HHmm}.zip"); return Results.File(file, "application/zip", name); } private static string Report(ServerOptions options, ServerState state, TimeProvider time, VolumeSpace volumes) { var sb = new StringBuilder(); sb.AppendLine(CultureInfo.InvariantCulture, $"Chronos Server {SystemEndpoints.Version} ({options.ServerName})"); sb.Append(DiagnosticsArchive.SystemReport()); sb.AppendLine(CultureInfo.InvariantCulture, $"Uptime {time.GetUtcNow() - state.StartedAt:d\\.hh\\:mm\\:ss}"); sb.AppendLine(CultureInfo.InvariantCulture, $"Database {state.Database} ({options.Database})"); // The SQLite build's options (BRIEF §6.2) explain behaviour differences between Windows versions. if (options.Database == DatabaseKind.Sqlite) sb.AppendLine("SQLite compile options: " + string.Join(' ', Chronos.Data.Sqlite.SqliteDatabase.CompileOptions)); sb.AppendLine(CultureInfo.InvariantCulture, $"TLS {options.TlsMode} {state.TlsFingerprint}"); sb.AppendLine(CultureInfo.InvariantCulture, $"Jobs one at a time, parallelism {options.Parallelism}, priority queue {(options.PriorityQueue ? "on" : "off")}"); // The archive's volume is where uploads are written; the space path, when set, is what the admin panel shows. sb.AppendLine(CultureInfo.InvariantCulture, $"Archive {options.ArchivePath} ({Space(volumes, options.ArchivePath)})"); if (!string.IsNullOrWhiteSpace(options.SpacePath)) sb.AppendLine(CultureInfo.InvariantCulture, $"Space {options.SpacePath} ({Space(volumes, options.SpacePath)})"); sb.AppendLine(CultureInfo.InvariantCulture, $"Data {options.DataPath} ({Space(volumes, options.DataPath)})"); sb.AppendLine(CultureInfo.InvariantCulture, $"Container {File.Exists("/.dockerenv")}"); sb.AppendLine("Set by environment: " + string.Join(", ", options.Locked)); return sb.ToString(); } private static string Encoders(ProcessingService? processing) { if (processing is null) return "No processing engine registered.\n"; var sb = new StringBuilder(); foreach (var provider in processing.Options.Encoders) { foreach (var c in provider.Capabilities) { sb.AppendLine(CultureInfo.InvariantCulture, $"{provider.Name}: {c.Codec} {c.Name} ({(c.Hardware ? "hardware" : "software")}{(c.SupportsTenBit ? ", 10-bit" : string.Empty)}, max {c.MaxWidth}x{c.MaxHeight})"); } } return sb.ToString(); } /// "120 GB free of 500 GB, fuse.shfs mounted at /archive from shfs" (the mount on Linux only; "…, NTFS" elsewhere). private static string Space(VolumeSpace volumes, string path) { if (!Directory.Exists(path)) return "missing"; var figures = volumes.Measure(path) is { } v ? string.Create(CultureInfo.InvariantCulture, $"{v.FreeBytes / (1L << 30)} GB free of {v.TotalBytes / (1L << 30)} GB") : "free space unknown"; var mount = VolumeSpace.MountOf(path); var fileSystem = mount?.FileSystem ?? VolumeSpace.FileSystemOf(path) ?? "file system unknown"; return mount is null ? $"{figures}, {fileSystem}" : $"{figures}, {fileSystem} mounted at {mount.MountPoint} from {mount.Source}"; } }