using System.Globalization; using System.Text; using System.Text.Json; using Titano.Core.Diagnostics; using Titano.Core.Model; using Titano.Data; using Titano.Data.Processing; using Titano.Server.Configuration; using Titano.Server.Jobs; using Titano.Server.Security; namespace Titano.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, TitanoDatabase db, ServerOptions options, ServerState state, JobEngineHost jobs, AuditLog audit, TimeProvider time, IServiceProvider services) { var ct = context.RequestAborted; var failures = (await db.Jobs.ListAsync(JobState.Failed, FailedJobs, null, ct)).Items; var report = Report(options, state, jobs, time); 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, 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, $"titano-server-diagnostics-{time.GetUtcNow():yyyyMMdd-HHmm}.zip"); return Results.File(file, "application/zip", name); } private static string Report(ServerOptions options, ServerState state, JobEngineHost jobs, TimeProvider time) { var sb = new StringBuilder(); sb.AppendLine(CultureInfo.InvariantCulture, $"Titano 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})"); sb.AppendLine(CultureInfo.InvariantCulture, $"TLS {options.TlsMode} {state.TlsFingerprint}"); sb.AppendLine(CultureInfo.InvariantCulture, $"Workers {jobs.Workers}"); sb.AppendLine(CultureInfo.InvariantCulture, $"Archive {options.ArchivePath} ({Space(options.ArchivePath)})"); sb.AppendLine(CultureInfo.InvariantCulture, $"Data {options.DataPath} ({Space(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(); } private static string Space(string path) { try { if (!Directory.Exists(path)) return "missing"; var full = Path.GetFullPath(path); // Windows wants a drive root; Unix accepts any directory and reports the volume it is mounted on. var drive = new DriveInfo(OperatingSystem.IsWindows() ? Path.GetPathRoot(full)! : full); return string.Create(CultureInfo.InvariantCulture, $"{drive.AvailableFreeSpace / (1L << 30)} GB free of {drive.TotalSize / (1L << 30)} GB"); } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException) { return "free space unknown"; } } }