Merge #980: unexpected cluster exit exits non-zero for SCM, audit buffer survives DB outage, HTTPS listener misconfig fails boot

This commit is contained in:
Joseph Doherty
2026-12-03 09:43:27 -05:00
10 changed files with 445 additions and 51 deletions
@@ -14,6 +14,14 @@ namespace ZB.MOM.WW.OtOpcUa.ControlPlane.Audit;
/// - <see cref="FlushInterval"/> elapses with a non-empty buffer.
/// - <c>PreRestart</c> / <c>PostStop</c> (supervisor swap or coordinated shutdown).
///
/// A flush that fails because the database did not answer (connection loss, login timeout, deadlock — as
/// opposed to the database rejecting specific rows) <b>keeps</b> the batch: the events go back into the buffer
/// and the next timer tick retries them (#980 / review 05 H-2). The buffer is bounded by
/// <see cref="MaxBufferedEvents"/>; past that the OLDEST events are dropped, counted
/// (<see cref="OverflowDroppedCount"/>) and logged, so a long outage cannot grow memory without bound.
/// While flushes are failing, the count-threshold trigger is suppressed (each attempt blocks the actor for a
/// connect timeout) and only the timer retries.
///
/// Dedup is two-layer: in-buffer (the <see cref="Dictionary{TKey, TValue}"/> below collapses
/// duplicate EventIds before flush) and at the database via the filtered unique index
/// <c>UX_ConfigAuditLog_EventId</c> (cross-restart safety — a retry of an already-flushed
@@ -30,9 +38,21 @@ public sealed class AuditWriterActor : ReceiveActor, IWithTimers, IAuditWriter
public const int FlushBatchSize = 500;
public static readonly TimeSpan FlushInterval = TimeSpan.FromSeconds(5);
/// <summary>Upper bound on events held in memory awaiting a successful save; past it the oldest are dropped.</summary>
public const int MaxBufferedEvents = 10_000;
private readonly IDbContextFactory<OtOpcUaConfigDbContext> _dbFactory;
private readonly ILoggingAdapter _log = Context.GetLogger();
private readonly Dictionary<Guid, AuditEvent> _buffer = new();
// Insertion-ordered so the overflow policy can drop the OLDEST events first.
private readonly OrderedDictionary<Guid, AuditEvent> _buffer = new();
private bool _lastFlushFailed;
private long _overflowDropped;
/// <summary>Total events dropped (oldest first) because the retry buffer hit <see cref="MaxBufferedEvents"/>.</summary>
public long OverflowDroppedCount => Interlocked.Read(ref _overflowDropped);
/// <summary>Events currently buffered awaiting a successful save (diagnostic / test seam).</summary>
public int BufferedCount => _buffer.Count;
/// <summary>Gets or sets the timer scheduler for the actor.</summary>
public ITimerScheduler Timers { get; set; } = null!;
@@ -62,8 +82,9 @@ public sealed class AuditWriterActor : ReceiveActor, IWithTimers, IAuditWriter
/// <see cref="IAuditWriter"/> seam. Best-effort and never throws: routes the event onto this
/// actor's mailbox via <c>Tell</c> (thread-safe from any caller) so it flows through the same
/// batching + dedup pipeline as in-cluster traffic, then returns immediately. The actual
/// persistence happens asynchronously on the next flush; a write failure there is logged and
/// the batch dropped (per the best-effort audit contract).
/// persistence happens asynchronously on the next flush; a transient database failure there
/// keeps the batch for retry (bounded — see <see cref="MaxBufferedEvents"/>), while rows the database
/// rejects outright are dropped (per the best-effort audit contract).
/// </summary>
/// <param name="evt">The canonical audit event to persist.</param>
/// <param name="ct">Unused — enqueue is synchronous and non-blocking.</param>
@@ -80,10 +101,30 @@ public sealed class AuditWriterActor : ReceiveActor, IWithTimers, IAuditWriter
// In-buffer dedup. Last write wins on duplicate EventId within the batch — events
// with the same EventId are by contract identical, so this is a no-op.
_buffer[evt.EventId] = evt;
if (_buffer.Count >= FlushBatchSize) FlushBuffer();
TrimToCap();
// While the database is failing, only the timer retries: a threshold-triggered attempt per arriving
// event would block the actor for a connect timeout each time.
if (_buffer.Count >= FlushBatchSize && !_lastFlushFailed) FlushBuffer();
}
private void FlushBuffer()
/// <summary>Drops the oldest events beyond <see cref="MaxBufferedEvents"/>, counting and logging them.</summary>
private void TrimToCap()
{
var overflow = _buffer.Count - MaxBufferedEvents;
if (overflow <= 0) return;
for (var i = 0; i < overflow; i++) _buffer.RemoveAt(0);
var before = Interlocked.Read(ref _overflowDropped);
var total = Interlocked.Add(ref _overflowDropped, overflow);
// Once per 1000 drops (and on the first), so a sustained outage does not log per event.
if (before == 0 || before / 1000 != total / 1000)
_log.Warning(
"AuditWriter retry buffer is full ({Max} events) because the ConfigDb is not accepting writes; " +
"dropped the oldest {Overflow} event(s) ({Total} dropped in total)",
MaxBufferedEvents, overflow, total);
}
private void FlushBuffer(bool final = false)
{
if (_buffer.Count == 0) return;
@@ -93,11 +134,28 @@ public sealed class AuditWriterActor : ReceiveActor, IWithTimers, IAuditWriter
try
{
var dropped = SaveBatch(snapshot);
_lastFlushFailed = false;
_log.Debug("AuditWriter flushed {Count} events ({Dropped} rejected rows dropped)", snapshot.Count - dropped, dropped);
}
catch (Exception ex)
{
_log.Error(ex, "AuditWriter flush failed; {Count} events dropped", snapshot.Count);
_lastFlushFailed = true;
if (final)
{
// The actor is going away; there is no next tick. This is the one place events are lost.
_log.Error(ex, "AuditWriter flush failed while stopping; {Count} events dropped", snapshot.Count);
return;
}
// The database did not answer (or failed in a way that names no row): keep the batch. Events
// that arrived since the snapshot (none today — the actor is single-threaded — but cheap to be
// right about) stay after the older ones. The unique EventId index makes a retried batch safe.
var newer = _buffer.Values.ToList();
_buffer.Clear();
foreach (var evt in snapshot) _buffer[evt.EventId] = evt;
foreach (var evt in newer) _buffer[evt.EventId] = evt;
TrimToCap();
_log.Warning(ex, "AuditWriter flush failed; keeping {Count} events buffered for retry", _buffer.Count);
}
}
@@ -200,14 +258,14 @@ public sealed class AuditWriterActor : ReceiveActor, IWithTimers, IAuditWriter
/// <inheritdoc />
protected override void PreRestart(Exception reason, object message)
{
FlushBuffer();
FlushBuffer(final: true);
base.PreRestart(reason, message);
}
/// <inheritdoc />
protected override void PostStop()
{
FlushBuffer();
FlushBuffer(final: true);
base.PostStop();
}
@@ -15,8 +15,17 @@ namespace ZB.MOM.WW.OtOpcUa.Host;
/// <para>This watchdog closes the gap where the <see cref="ActorSystem"/> terminates but the .NET
/// host process keeps running with a dead actor system (idling forever, never restarted). It watches
/// <see cref="ActorSystem.WhenTerminated"/>; if the system terminates <b>outside</b> a normal host
/// shutdown, it stops the application so the supervisor can restart the process. Mirrors the sister
/// ScadaBridge project's proven pattern.</para>
/// shutdown, it ends the process <b>as a failure</b> (flush logs, exit code <see cref="FailureExitCode"/>)
/// so the supervisor can restart it. Mirrors the sister ScadaBridge project's proven pattern.</para>
///
/// <para><b>Why not <c>StopApplication()</c> (#980 / review 05 H-1).</b> That is a graceful host stop;
/// under <c>UseWindowsService</c> the host then reports <c>SERVICE_STOPPED</c> with exit code 0, and
/// Windows SCM runs <c>sc failure</c> recovery only when the service process dies without reporting
/// a clean stop (or, with <c>sc failureflag</c>, stops with a non-zero code). So a node that left the
/// cluster (manual failover, endpoint step-down, auto-down after a pause) stopped for good and the pair
/// ran on one node. Docker (<c>restart: unless-stopped</c>) restarts on any exit, which is why this never
/// showed on the docker-dev rig. The exit is performed on a separate thread so it cannot deadlock the
/// thread that completed the termination, and is injectable so the path is testable.</para>
///
/// <para>Registered <b>after</b> <c>AddAkka</c> so it starts after Akka's own hosted service has
/// built the system; the <see cref="ActorSystem"/> is resolved lazily in <see cref="StartAsync"/>
@@ -30,20 +39,31 @@ public sealed class ActorSystemTerminationWatchdog : IHostedService
private readonly Func<ActorSystem> _actorSystemAccessor;
private readonly IHostApplicationLifetime _lifetime;
private readonly ILogger<ActorSystemTerminationWatchdog> _logger;
private readonly Action<int> _exitProcess;
private readonly Action _flushLogs;
private volatile bool _stopRequested;
/// <summary>Process exit code used when the actor system terminated outside host shutdown.</summary>
public const int FailureExitCode = 1;
/// <summary>Constructs the watchdog over a lazy <see cref="ActorSystem"/> accessor and the host lifetime.</summary>
/// <param name="actorSystemAccessor">Lazy accessor (resolved in <see cref="StartAsync"/>, never at construction, so it can't race Akka startup).</param>
/// <param name="lifetime">Host application lifetime used to stop the process on an unexpected self-down.</param>
/// <param name="logger">Logger for the critical self-down diagnostic.</param>
/// <param name="exitProcess">Ends the process with the given exit code; defaults to <see cref="Environment.Exit"/>. Test seam.</param>
/// <param name="flushLogs">Flushes the log pipeline before exit; defaults to <c>Serilog.Log.CloseAndFlush</c>. Test seam.</param>
public ActorSystemTerminationWatchdog(
Func<ActorSystem> actorSystemAccessor,
IHostApplicationLifetime lifetime,
ILogger<ActorSystemTerminationWatchdog> logger)
ILogger<ActorSystemTerminationWatchdog> logger,
Action<int>? exitProcess = null,
Action? flushLogs = null)
{
_actorSystemAccessor = actorSystemAccessor;
_lifetime = lifetime;
_logger = logger;
_exitProcess = exitProcess ?? Environment.Exit;
_flushLogs = flushLogs ?? Serilog.Log.CloseAndFlush;
}
/// <summary>Wires the <see cref="ActorSystem.WhenTerminated"/> continuation that exits the host on an unexpected self-down.</summary>
@@ -60,10 +80,22 @@ public sealed class ActorSystemTerminationWatchdog : IHostedService
return;
_logger.LogCritical(
"ActorSystem terminated outside host shutdown (SBR self-down / "
+ "run-coordinated-shutdown-when-down). Stopping the host so the service supervisor "
+ "restarts this node as a fresh incarnation (2-node keep-oldest exit-and-rejoin recovery).");
_lifetime.StopApplication();
"ActorSystem terminated outside host shutdown (downed / left the cluster / "
+ "run-coordinated-shutdown-when-down). Exiting the process with code {ExitCode} so the "
+ "service supervisor (SCM recovery / docker restart) restarts this node as a fresh "
+ "incarnation (exit-and-rejoin recovery).",
FailureExitCode);
// A dedicated thread: the exit must not run on (or wait for) the thread that completed the
// ActorSystem termination, and a failing flush must never prevent the exit.
var exit = new Thread(() =>
{
try { _flushLogs(); }
catch { /* the exit below is the point */ }
_exitProcess(FailureExitCode);
})
{ IsBackground = true, Name = "otopcua-watchdog-exit" };
exit.Start();
},
TaskContinuationOptions.ExecuteSynchronously);
return Task.CompletedTask;
@@ -0,0 +1,58 @@
namespace ZB.MOM.WW.OtOpcUa.Host.Configuration;
/// <summary>
/// Start-up guard for the dedicated h2c listeners (LocalDb sync, ConfigServe, telemetry, data
/// connections). Taking over Kestrel for a dedicated listener means re-binding every existing endpoint
/// explicitly, and an HTTPS endpoint's certificate configuration cannot be replayed (TLS is terminated
/// upstream). #980 / review 05 H-5.
/// </summary>
/// <remarks>
/// A dedicated listener is only ever requested by an explicit non-zero port setting, and every consumer
/// of those ports is load-bearing: without the telemetry/command listener a node can receive no deploy
/// command, without ConfigServe no node can fetch config or ack. The option validators check the
/// <i>configured</i> values, so they pass while the effective ports are zeroed — the node would boot,
/// join its mesh and report ready with every mesh endpoint missing. So a contradictory configuration
/// fails host start with a message naming every setting involved, instead of logging one Error and
/// continuing.
/// </remarks>
public static class DedicatedListenerGuard
{
/// <summary>
/// Throws <see cref="InvalidOperationException"/> when any dedicated listener is requested while an
/// existing HTTPS binding makes it impossible to bind.
/// </summary>
/// <param name="syncListenPort"><c>LocalDb:SyncListenPort</c> effective value (0 = off).</param>
/// <param name="configServeGrpcPort"><c>ConfigServe:GrpcListenPort</c> effective value (0 = off).</param>
/// <param name="telemetryListenPort"><c>Telemetry:GrpcListenPort</c> effective value (0 = off).</param>
/// <param name="dataListenPort"><c>DataConnections:ListenPort</c> effective value (0 = off).</param>
/// <param name="existingBindings">The HTTP surface the host was asked to serve.</param>
/// <param name="configuredUrls">The raw configured URL list, for the message; may be null.</param>
public static void ThrowIfHttpsBlocksDedicatedListeners(
int syncListenPort,
int configServeGrpcPort,
int telemetryListenPort,
int dataListenPort,
IReadOnlyList<KestrelHttpBinding> existingBindings,
string? configuredUrls)
{
ArgumentNullException.ThrowIfNull(existingBindings);
if (!existingBindings.Any(b => b.IsSecure))
return;
var requested = new List<string>();
if (syncListenPort > 0) requested.Add($"LocalDb:SyncListenPort={syncListenPort}");
if (configServeGrpcPort > 0) requested.Add($"ConfigServe:GrpcListenPort={configServeGrpcPort}");
if (telemetryListenPort > 0) requested.Add($"Telemetry:GrpcListenPort={telemetryListenPort}");
if (dataListenPort > 0) requested.Add($"DataConnections:ListenPort={dataListenPort}");
if (requested.Count == 0)
return;
throw new InvalidOperationException(
"Dedicated h2c listener(s) are requested (" + string.Join(", ", requested) + ") but this host " +
$"serves HTTPS endpoint(s) ({configuredUrls ?? "ASPNETCORE_HTTPS_PORTS/HTTPS_PORTS"}). " +
"Binding a dedicated listener requires re-binding every existing endpoint explicitly, and the " +
"HTTPS certificate configuration cannot be replayed safely, so the node cannot start with the " +
"mesh endpoints it was configured to serve. Terminate TLS upstream (as the docker-dev rig does) " +
"and serve the UI/health surface over HTTP, or set the listed port(s) to 0 on this node.");
}
}
+5 -21
View File
@@ -745,27 +745,11 @@ if (syncListenPort > 0 || configServeGrpcPort > 0 || telemetryListenPort > 0 ||
// Re-binding an https endpoint would need its certificate configuration replayed too, which
// this host does not model (TLS is terminated at Traefik). Rather than silently serve it
// without TLS — or drop it — refuse to take over Kestrel at all and leave the existing
// surface exactly as it was. The operator gets a loud, actionable error instead of an
// AdminUI that stopped answering. Disables BOTH dedicated ports (either would force the same
// Kestrel takeover).
if (existingBindings.Any(b => b.IsSecure))
{
if (dataListenPort > 0)
throw new InvalidOperationException("The dedicated data listener cannot safely replay existing HTTPS URL bindings. Configure an HTTP UI/health binding and the dedicated data TLS certificate separately.");
Log.Error(
"A dedicated h2c listener is requested (LocalDb:SyncListenPort={SyncPort}, " +
"ConfigServe:GrpcListenPort={ConfigServePort}, Telemetry:GrpcListenPort={TelemetryPort}) but this " +
"host serves HTTPS endpoint(s) ({Urls}). " +
"Binding a dedicated listener requires re-binding every existing endpoint explicitly, and the " +
"HTTPS certificate configuration cannot be replayed safely. ALL dedicated listeners are DISABLED; " +
"terminate TLS upstream (as the docker-dev rig does) or leave these features off on this node.",
syncListenPort, configServeGrpcPort, telemetryListenPort, configuredUrls);
syncListenPort = 0;
configServeGrpcPort = 0;
telemetryListenPort = 0;
}
else
// without TLS, drop it, or (the pre-#980 behaviour) boot with every mesh listener silently
// disabled and report ready — fail host start with an actionable error (review 05 H-5). The
// Program.cs wrapper turns the throw into a Fatal log + stderr FATAL + exit 1.
DedicatedListenerGuard.ThrowIfHttpsBlocksDedicatedListeners(
syncListenPort, configServeGrpcPort, telemetryListenPort, dataListenPort, existingBindings, configuredUrls);
{
// Capture locals so the ConfigureKestrel closure does not observe later reassignment.
var syncPortToBind = syncListenPort;