Files
Chronos/src/Chronos.Server/Api/DiagnosticsEndpoints.cs
T
Alby96 0e84392f4f feat(logs): log level, retention, size limits and rotation on server and desktop
Owner review 2, R11 asked for more log settings. The file sink now writes daily or
hourly files, continues a full file in numbered parts and prunes by age and by the
total size (never the file being written); its options change while it runs.

Server: the file and console levels are separate and read by the logging filters
at every line, so the admin panel's new Logs group applies without a restart; the
engine's level follows the lower of the two. This also fixes a bug: the file logger
was fixed at Information, so CHRONOS_LOG_LEVEL=Debug or Trace never reached the
files. New variables CHRONOS_LOG_CONSOLE_LEVEL, CHRONOS_LOG_RETENTION_DAYS,
CHRONOS_LOG_MAX_FILE_MB, CHRONOS_LOG_MAX_TOTAL_MB, CHRONOS_LOG_ROTATION,
CHRONOS_AUDIT_RETENTION_DAYS and CHRONOS_DIAGNOSTICS_LOG_MB lock their settings like
the others; the diagnostics zip keeps the configured share of each log.

Desktop: Settings > Advanced gains Log level, Keep logs, File size, Logs total,
Rotation and Diagnostics logs, applied at every save; Advanced's Reset section
restores them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit cc875784e4952ee0e4c807b9d9c18496d3d5a8c3)
2026-10-27 02:08:09 +01:00

117 lines
6.4 KiB
C#

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;
/// <summary>
/// <c>GET /api/v1/server/diagnostics</c> (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
/// <see cref="SecretScrubber"/> (admin and database passwords, tokens and keys are removed); no archive file is included.
/// </summary>
public static class DiagnosticsEndpoints
{
/// <summary>Failed jobs included, newest first.</summary>
public const int FailedJobs = 100;
public static void Map(RouteGroupBuilder api) =>
api.MapGet("/server/diagnostics", DownloadAsync).Requires(Permissions.ManageArchive);
private static async Task<IResult> 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<ProcessingService>());
// 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();
}
/// <summary>"120 GB free of 500 GB, fuse.shfs mounted at /archive from shfs" (the mount on Linux only; "…, NTFS" elsewhere).</summary>
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}";
}
}