feat: owner review 2 phase 2: scheduled jobs and log settings (#10)
CI / Build and test (push) Successful in 7m0s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 6s
Release / Build, test and publish (push) Successful in 13m28s
CI / PostgreSQL 16 integration (push) Successful in 5m52s
CI / PostgreSQL 17 integration (push) Successful in 4m50s
CI / Docker image (push) Successful in 1m4s
Release / Server image (push) Successful in 1m35s
CI / Build and test (push) Successful in 7m0s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 6s
Release / Build, test and publish (push) Successful in 13m28s
CI / PostgreSQL 16 integration (push) Successful in 5m52s
CI / PostgreSQL 17 integration (push) Successful in 4m50s
CI / Docker image (push) Successful in 1m4s
Release / Server image (push) Successful in 1m35s
- Jobs > Scheduled on the desktop and the admin panel. Every timer that queued work is now a visible system schedule: archive scan, upload clean-up, index backup, job-history and audit clean-ups, desktop housekeeping. New actions: verify, thumbnails, proxies, analysis, maintenance, backup, clean-ups, reports. - The scheduler: migration 0007, in-house recurrence, compare-and-set claim, catch-up, scan at start. - Log settings: levels, retention, size parts, total limit, daily or hourly rotation, audit retention, diagnostics share; the server writes Debug/Trace to its files again; logging never fails a job. Upgrade: CHRONOS_LOG_LEVEL set in an existing container locks both levels; migration 0007 is one-way. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
This commit was merged in pull request #10.
This commit is contained in:
1 parent
1f089888e8
commit
af9eeaab9b
349 files changed
+28341
-1304
No files matched your search
@@ -4,31 +4,27 @@ using MsLogLevel = Microsoft.Extensions.Logging.LogLevel;
|
||||
|
||||
namespace Chronos.Server.Hosting;
|
||||
|
||||
/// <summary>In-house structured file logging for ASP.NET Core (rotating daily files under /data/logs).</summary>
|
||||
public sealed class FileLoggerProvider(FileLogSink sink) : ILoggerProvider
|
||||
/// <summary>
|
||||
/// In-house structured file logging for ASP.NET Core: the rotating files of <see cref="ServerLogging.Sink"/> under
|
||||
/// /data/logs, at <see cref="ServerLogging.FileLevel"/> of the moment (owner review 2, R11: it was fixed at Information,
|
||||
/// so Debug and Trace never reached the files).
|
||||
/// </summary>
|
||||
public sealed class FileLoggerProvider(ServerLogging logging) : ILoggerProvider
|
||||
{
|
||||
public ILogger CreateLogger(string categoryName) => new FileLogger(sink, categoryName);
|
||||
public ILogger CreateLogger(string categoryName) => new FileLogger(logging, categoryName);
|
||||
|
||||
public void Dispose() => sink.Dispose();
|
||||
public void Dispose() => logging.Sink.Dispose();
|
||||
|
||||
private sealed class FileLogger(FileLogSink sink, string category) : ILogger
|
||||
private sealed class FileLogger(ServerLogging logging, string category) : ILogger
|
||||
{
|
||||
public IDisposable? BeginScope<TState>(TState state) where TState : notnull => null;
|
||||
|
||||
public bool IsEnabled(MsLogLevel logLevel) => logLevel >= MsLogLevel.Information;
|
||||
public bool IsEnabled(MsLogLevel logLevel) => logLevel != MsLogLevel.None && logLevel >= logging.FileLevel;
|
||||
|
||||
public void Log<TState>(MsLogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
|
||||
{
|
||||
if (!IsEnabled(logLevel)) return;
|
||||
var level = logLevel switch
|
||||
{
|
||||
MsLogLevel.Trace => CoreLogLevel.Trace,
|
||||
MsLogLevel.Debug => CoreLogLevel.Debug,
|
||||
MsLogLevel.Information => CoreLogLevel.Info,
|
||||
MsLogLevel.Warning => CoreLogLevel.Warning,
|
||||
_ => CoreLogLevel.Error,
|
||||
};
|
||||
sink.Write(level, category, formatter(state, exception), exception);
|
||||
logging.Sink.Write(ServerLogging.Core(logLevel), category, formatter(state, exception), exception);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -56,8 +52,16 @@ public sealed class LoggerSink(ILoggerFactory factory) : ILogSink
|
||||
CoreLogLevel.Warning => MsLogLevel.Warning,
|
||||
_ => MsLogLevel.Error,
|
||||
};
|
||||
try
|
||||
{
|
||||
#pragma warning disable CA2254 // Engine messages are preformatted.
|
||||
logger.Log(ms, exception, message);
|
||||
logger.Log(ms, exception, message);
|
||||
#pragma warning restore CA2254
|
||||
}
|
||||
catch (AggregateException)
|
||||
{
|
||||
// A provider could not write it (Microsoft.Extensions.Logging gathers what they throw): the line is dropped, as
|
||||
// Log.Write would drop it, so the engine code that logs goes on.
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -42,7 +42,15 @@ public sealed record ServerCommandLine(ServerCommand Command, IReadOnlyList<stri
|
||||
CHRONOS_PARALLELISM photos the running job processes at once (jobs run one at a time; default: half the
|
||||
cores); CHRONOS_WORKERS, its former name, still sets it
|
||||
CHRONOS_PRIORITY_QUEUE a job of a higher level pauses the running one, which resumes afterwards (true | false)
|
||||
CHRONOS_LOG_LEVEL (Trace | Debug | Information | Warning | Error)
|
||||
CHRONOS_LOG_LEVEL least severe level of the log files and the console (Trace | Debug | Information |
|
||||
Warning | Error | Critical | None; default Information)
|
||||
CHRONOS_LOG_CONSOLE_LEVEL the console's own level (default: CHRONOS_LOG_LEVEL's)
|
||||
CHRONOS_LOG_RETENTION_DAYS days log files are kept (default 14)
|
||||
CHRONOS_LOG_MAX_FILE_MB size at which a log file continues in a numbered one (default 50; 0: no limit)
|
||||
CHRONOS_LOG_MAX_TOTAL_MB size of all log files; beyond it the oldest are deleted (default 1024; 0: no limit)
|
||||
CHRONOS_LOG_ROTATION a new log file every day or every hour, UTC (daily | hourly; default daily)
|
||||
CHRONOS_AUDIT_RETENTION_DAYS days of audit log the audit-cleanup schedule keeps (default 0: forever)
|
||||
CHRONOS_DIAGNOSTICS_LOG_MB MB from the end of each log file in the diagnostics zip (default 4)
|
||||
CHRONOS_DISCOVERY LAN beacon (true | false); in a container it needs host networking
|
||||
CHRONOS_PUBLIC_HTTP_PORT, CHRONOS_PUBLIC_HTTPS_PORT
|
||||
ports clients reach when the container's ports are published as other host ports
|
||||
@@ -50,7 +58,7 @@ public sealed record ServerCommandLine(ServerCommand Command, IReadOnlyList<stri
|
||||
CHRONOS_TRUSTED_PROXIES proxy mode: addresses or networks (CIDR) whose X-Forwarded-* headers count
|
||||
(default: loopback only; list a proxy in another container or on another machine)
|
||||
|
||||
Container image only: PUID, PGID (user and group the server runs as, owners of /data), TZ (local time zone)
|
||||
Container image only: PUID, PGID (user and group the server runs as, owners of /data), TZ (time zone of the schedules)
|
||||
""";
|
||||
|
||||
public static ServerCommandLine Parse(IReadOnlyList<string> args)
|
||||
|
||||
@@ -4,6 +4,7 @@ using Microsoft.AspNetCore.Server.Kestrel.Core;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Housekeeping;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Server.Api;
|
||||
using Chronos.Server.Configuration;
|
||||
@@ -36,18 +37,16 @@ public static class ServerHost
|
||||
var archiveOpenToOthers = DataFolderAccess.PrepareArchive(options.ArchivePath);
|
||||
|
||||
var builder = WebApplication.CreateSlimBuilder(new WebApplicationOptions { Args = args, ContentRootPath = AppContext.BaseDirectory });
|
||||
builder.Logging.ClearProviders();
|
||||
builder.Logging.SetMinimumLevel(options.LogLevel);
|
||||
builder.Logging.AddSimpleConsole(c => c.SingleLine = true);
|
||||
builder.Logging.AddProvider(new FileLoggerProvider(new FileLogSink(options.LogPath, "server")));
|
||||
builder.Logging.AddFilter("Microsoft.AspNetCore", Microsoft.Extensions.Logging.LogLevel.Warning);
|
||||
builder.Logging.AddFilter("Microsoft.Hosting.Lifetime", options.LogLevel > Microsoft.Extensions.Logging.LogLevel.Information ? options.LogLevel : Microsoft.Extensions.Logging.LogLevel.Information);
|
||||
// The console and the files each follow their own level, which the admin panel changes while the server runs.
|
||||
var logging = new ServerLogging(options);
|
||||
logging.AddTo(builder.Logging);
|
||||
builder.Services.AddSingleton(logging);
|
||||
|
||||
// The archive module registers first, so a missing piece stops the server before it touches the database.
|
||||
configureServices?.Invoke(builder.Services);
|
||||
RequireArchiveModule(builder.Services);
|
||||
|
||||
using var bootLoggerFactory = LoggerFactory.Create(l => l.AddSimpleConsole(c => c.SingleLine = true).SetMinimumLevel(options.LogLevel));
|
||||
using var bootLoggerFactory = LoggerFactory.Create(l => l.AddSimpleConsole(c => c.SingleLine = true).SetMinimumLevel(options.ConsoleLogLevel));
|
||||
var bootLogger = bootLoggerFactory.CreateLogger("Chronos.Server");
|
||||
var certificate = CertificateStore.Load(options, bootLogger);
|
||||
var database = ServerDatabase.OpenAsync(options, bootLogger, CancellationToken.None).GetAwaiter().GetResult();
|
||||
@@ -146,10 +145,16 @@ public static class ServerHost
|
||||
services.AddSingleton<RenderNodeService>();
|
||||
services.AddSingleton<JobEngineHost>();
|
||||
services.AddHostedService(sp => sp.GetRequiredService<JobEngineHost>());
|
||||
// After the engine's host: the scheduler queues on its engine, starts after it and stops before it (owner review 2, R10).
|
||||
services.AddSingleton<ServerScheduleHost>();
|
||||
services.AddSingleton<SchedulerHost>();
|
||||
services.AddHostedService(sp => sp.GetRequiredService<SchedulerHost>());
|
||||
services.AddSingleton<RenderNodeMonitor>();
|
||||
services.AddHostedService(sp => sp.GetRequiredService<RenderNodeMonitor>());
|
||||
// Recovers interrupted commits at start; its sweep is the clean-up step of the upload-cleanup schedule.
|
||||
services.AddSingleton<UploadMaintenance>();
|
||||
services.AddHostedService(sp => sp.GetRequiredService<UploadMaintenance>());
|
||||
services.AddSingleton<ICleanupStep, UploadCleanupStep>();
|
||||
services.AddSingleton<DiscoveryBeaconService>();
|
||||
services.AddHostedService(sp => sp.GetRequiredService<DiscoveryBeaconService>());
|
||||
}
|
||||
@@ -171,6 +176,7 @@ public static class ServerHost
|
||||
FileEndpoints.Map(api);
|
||||
UploadEndpoints.Map(api);
|
||||
JobEndpoints.Map(api);
|
||||
ScheduleEndpoints.Map(api);
|
||||
NodeEndpoints.Map(api);
|
||||
ArchiveEndpoints.Map(api);
|
||||
AdminEndpoints.Map(api);
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
using Microsoft.Extensions.Logging.Console;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Server.Configuration;
|
||||
using CoreLogLevel = Chronos.Core.Diagnostics.LogLevel;
|
||||
using MsLogLevel = Microsoft.Extensions.Logging.LogLevel;
|
||||
|
||||
namespace Chronos.Server.Hosting;
|
||||
|
||||
/// <summary>
|
||||
/// The server's logging (BRIEF §14.1; owner review 2, R11): the console and the files of <c>/data/logs</c>, each with its
|
||||
/// own level, which the logging filters read at every line so a change in the admin panel applies at once; the file
|
||||
/// sink's retention, size limits and rotation; and the engine's <see cref="Log.MinimumLevel"/>, the lower of the two
|
||||
/// levels, so engine lines reach whichever output wants them. ASP.NET Core's own categories never write below Warning and
|
||||
/// the host's lifetime never below Information, whatever the levels.
|
||||
/// </summary>
|
||||
public sealed class ServerLogging
|
||||
{
|
||||
public const int MaxRetentionDays = 3650;
|
||||
public const int MaxFileMb = 10 * 1024;
|
||||
public const int MaxTotalMb = 1024 * 1024;
|
||||
public const int MaxAuditRetentionDays = ServerOptions.MaxAuditRetentionDays;
|
||||
public const int MaxDiagnosticsLogMb = 1024;
|
||||
|
||||
/// <summary>The ranges <see cref="Problem"/> checks, for the start-up error.</summary>
|
||||
public const string Ranges = "log retention 1 to 3650 days, log file 0 to 10240 MB, logs total 0 to 1048576 MB and not below the log file, "
|
||||
+ "audit retention 0 to 3650 days, diagnostics logs 1 to 1024 MB";
|
||||
|
||||
/// <summary>The levels the settings accept, least severe first; their wire names are lower case (<c>information</c>).</summary>
|
||||
public static IReadOnlyList<MsLogLevel> Levels { get; } =
|
||||
[MsLogLevel.Trace, MsLogLevel.Debug, MsLogLevel.Information, MsLogLevel.Warning, MsLogLevel.Error, MsLogLevel.Critical, MsLogLevel.None];
|
||||
|
||||
private volatile MsLogLevel _file;
|
||||
private volatile MsLogLevel _console;
|
||||
|
||||
/// <summary>Opens the log files of <paramref name="options"/> and applies its levels (call once the data folder is prepared).</summary>
|
||||
public ServerLogging(ServerOptions options)
|
||||
{
|
||||
Sink = new FileLogSink(options.LogPath, "server", FileOptions(options));
|
||||
Apply(options);
|
||||
}
|
||||
|
||||
public FileLogSink Sink { get; }
|
||||
|
||||
public MsLogLevel FileLevel => _file;
|
||||
|
||||
public MsLogLevel ConsoleLevel => _console;
|
||||
|
||||
/// <summary>The console and the file provider, each behind a filter that reads its level now.</summary>
|
||||
public void AddTo(ILoggingBuilder logging)
|
||||
{
|
||||
logging.ClearProviders();
|
||||
// Every level reaches the filters; they decide with the levels of the moment.
|
||||
logging.SetMinimumLevel(MsLogLevel.Trace);
|
||||
logging.AddSimpleConsole(c => c.SingleLine = true);
|
||||
logging.AddProvider(new FileLoggerProvider(this));
|
||||
logging.AddFilter<ConsoleLoggerProvider>((category, level) => Allows(category, level, ConsoleLevel));
|
||||
logging.AddFilter<FileLoggerProvider>((category, level) => Allows(category, level, FileLevel));
|
||||
}
|
||||
|
||||
/// <summary>The levels, retention, limits and rotation of <paramref name="options"/>, from the next line on.</summary>
|
||||
public void Apply(ServerOptions options)
|
||||
{
|
||||
_file = options.LogLevel;
|
||||
_console = options.ConsoleLogLevel;
|
||||
Sink.Configure(FileOptions(options));
|
||||
Log.MinimumLevel = Core(options.LogLevel < options.ConsoleLogLevel ? options.LogLevel : options.ConsoleLogLevel);
|
||||
}
|
||||
|
||||
public static LogFileOptions FileOptions(ServerOptions options) => new()
|
||||
{
|
||||
Level = Core(options.LogLevel),
|
||||
RetentionDays = options.LogRetentionDays,
|
||||
MaxFileMb = options.LogMaxFileMb,
|
||||
MaxTotalMb = options.LogMaxTotalMb,
|
||||
Rotation = options.LogRotation,
|
||||
};
|
||||
|
||||
/// <summary>Whether a line of <paramref name="category"/> at <paramref name="level"/> is written by an output at <paramref name="threshold"/>.</summary>
|
||||
public static bool Allows(string? category, MsLogLevel level, MsLogLevel threshold)
|
||||
{
|
||||
if (level == MsLogLevel.None || level < threshold) return false;
|
||||
if (category is null) return true;
|
||||
// A line per request below Warning would bury everything else.
|
||||
if (category.StartsWith("Microsoft.AspNetCore", StringComparison.OrdinalIgnoreCase)) return level >= MsLogLevel.Warning;
|
||||
if (category.StartsWith("Microsoft.Hosting.Lifetime", StringComparison.OrdinalIgnoreCase)) return level >= MsLogLevel.Information;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>The engine's level of an ASP.NET Core level (Critical and None become Error, the engine's most severe).</summary>
|
||||
public static CoreLogLevel Core(MsLogLevel level) => level switch
|
||||
{
|
||||
MsLogLevel.Trace => CoreLogLevel.Trace,
|
||||
MsLogLevel.Debug => CoreLogLevel.Debug,
|
||||
MsLogLevel.Information => CoreLogLevel.Info,
|
||||
MsLogLevel.Warning => CoreLogLevel.Warning,
|
||||
_ => CoreLogLevel.Error,
|
||||
};
|
||||
|
||||
public static bool IsLevel(MsLogLevel level) => Levels.Contains(level);
|
||||
|
||||
/// <summary><c>information</c>.</summary>
|
||||
public static string Wire(MsLogLevel level) => level.ToString().ToLowerInvariant();
|
||||
|
||||
/// <summary><c>daily</c> or <c>hourly</c>.</summary>
|
||||
public static string Wire(LogRotation rotation) => rotation.ToString().ToLowerInvariant();
|
||||
|
||||
/// <summary>A level by name, any case; <c>info</c>, <c>warn</c> and <c>off</c> are accepted too. Numbers are not levels.</summary>
|
||||
public static bool TryParseLevel(string? text, out MsLogLevel level)
|
||||
{
|
||||
level = MsLogLevel.Information;
|
||||
var name = text?.Trim();
|
||||
if (string.IsNullOrEmpty(name)) return false;
|
||||
if (name.Equals("info", StringComparison.OrdinalIgnoreCase)) name = nameof(MsLogLevel.Information);
|
||||
else if (name.Equals("warn", StringComparison.OrdinalIgnoreCase)) name = nameof(MsLogLevel.Warning);
|
||||
else if (name.Equals("off", StringComparison.OrdinalIgnoreCase)) name = nameof(MsLogLevel.None);
|
||||
foreach (var candidate in Levels)
|
||||
{
|
||||
if (!candidate.ToString().Equals(name, StringComparison.OrdinalIgnoreCase)) continue;
|
||||
level = candidate;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static bool TryParseRotation(string? text, out LogRotation rotation)
|
||||
{
|
||||
rotation = LogRotation.Daily;
|
||||
foreach (var candidate in Enum.GetValues<LogRotation>())
|
||||
{
|
||||
if (!candidate.ToString().Equals(text?.Trim(), StringComparison.OrdinalIgnoreCase)) continue;
|
||||
rotation = candidate;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <exception cref="FormatException">Not a level.</exception>
|
||||
public static MsLogLevel ParseLevel(string variable, string value) => TryParseLevel(value, out var level)
|
||||
? level
|
||||
: throw new FormatException($"{variable} must be Trace, Debug, Information, Warning, Error, Critical or None.");
|
||||
|
||||
/// <exception cref="FormatException">Neither daily nor hourly.</exception>
|
||||
public static LogRotation ParseRotation(string variable, string value) => TryParseRotation(value, out var rotation)
|
||||
? rotation
|
||||
: throw new FormatException($"{variable} must be daily or hourly.");
|
||||
|
||||
/// <summary>The setting (a <see cref="ServerOptions"/> property name) whose value is out of range, or null.</summary>
|
||||
public static string? Problem(int retentionDays, int maxFileMb, int maxTotalMb, int auditRetentionDays, int diagnosticsLogMb)
|
||||
{
|
||||
if (retentionDays is < 1 or > MaxRetentionDays) return nameof(ServerOptions.LogRetentionDays);
|
||||
if (maxFileMb is < 0 or > MaxFileMb) return nameof(ServerOptions.LogMaxFileMb);
|
||||
if (maxTotalMb is < 0 or > MaxTotalMb || LogFileOptions.TotalBelowFile(maxFileMb, maxTotalMb)) return nameof(ServerOptions.LogMaxTotalMb);
|
||||
if (auditRetentionDays is < 0 or > MaxAuditRetentionDays) return nameof(ServerOptions.AuditRetentionDays);
|
||||
if (diagnosticsLogMb is < 1 or > MaxDiagnosticsLogMb) return nameof(ServerOptions.DiagnosticsLogMb);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user