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:
@@ -307,6 +307,8 @@ h2c mesh settings do not opt this listener into cleartext.
|
||||
|
||||
**The listener is dedicated h2c and coexists with the LocalDb-sync listener.** A fused admin+driver node with **both** `ConfigServe:GrpcListenPort` and `LocalDb:SyncListenPort` set re-binds its existing HTTP surface exactly once and adds both dedicated HTTP/2-only ports on top — see the same Kestrel-takeover caveat under [`LocalDb`](#localdb-pair-local-config-cache--driver-role-only).
|
||||
|
||||
**An HTTPS binding refuses host start (#980 / review 05 H-5).** The takeover cannot replay an HTTPS endpoint's certificate configuration (TLS is terminated upstream), so a node with any HTTPS URL/`HTTPS_PORTS` binding **and** any non-zero `LocalDb:SyncListenPort` / `ConfigServe:GrpcListenPort` / `Telemetry:GrpcListenPort` / `DataConnections:ListenPort` now fails to start with a message naming every requested port (`DedicatedListenerGuard`). It previously logged one Error, zeroed the ports and booted ready with no deploy/config/telemetry endpoints. Serve the UI/health surface over HTTP, or set the port(s) to 0.
|
||||
|
||||
**`RevisionHash == SHA-256(artifact bytes)` is load-bearing.** `ConfigComposer` computes the deployment's revision hash as the lowercase-hex SHA-256 of the exact artifact bytes, so the node verifies a fetch against the `RevisionHash` the dispatch already carries — no hash rides in the proto. If a future change makes the revision hash anything else, every fetch fails verification.
|
||||
|
||||
**`DeploymentArtifactService` is `AllowAnonymous` by design** — same reasoning as `NodeCommandService`/`CentralCommandService` above: the AdminUI cookie `FallbackPolicy` on an admin-role node would otherwise block a correctly-keyed fetch before `ConfigServeAuthInterceptor`'s verdict matters. See [`security.md` § Mesh gRPC ingress is `AllowAnonymous` by design](security.md#mesh-grpc-ingress-is-allowanonymous-by-design).
|
||||
@@ -431,6 +433,8 @@ per cluster at `/clusters/{id}/audit`. It has no `appsettings` section — it is
|
||||
has a `ConfigDb` — but one schema property is worth recording here because it constrains how callers may
|
||||
write to it:
|
||||
|
||||
*Flush behaviour (#980 / review 05 H-2):* `AuditWriterActor` batches events and flushes every 5 s (or at 500). A flush that fails because the database did not answer **keeps** the batch and retries on the next tick; the buffer is bounded at 10 000 events (drop-oldest, with `OverflowDroppedCount` and a Warning). Rows the database rejects outright (e.g. a duplicate `EventId`) are still dropped individually. Events are lost only if the actor stops while the database is still down (logged at Error with the count).
|
||||
|
||||
- **`EventId` gives cross-restart deduplication, and the DB enforces it.** Each row carries the
|
||||
stable per-event `AuditEvent.EventId`, under a *filtered* unique index
|
||||
(`UX_ConfigAuditLog_EventId`, `WHERE [EventId] IS NOT NULL` — so the nullable pre-v2 backfill rows
|
||||
|
||||
+10
-4
@@ -472,9 +472,15 @@ two-node pair that choice means *any* crash of the oldest node is a full outage.
|
||||
`sc.exe failure OtOpcUaHost … actions= restart/5000/restart/30000/restart/60000`; the docker-dev rig sets
|
||||
`restart: unless-stopped`.
|
||||
2. **The recovery watchdog** `ActorSystemTerminationWatchdog` (registered in `Program.cs` after `AddAkka`) —
|
||||
it watches `ActorSystem.WhenTerminated` and, on an unexpected self-down, calls
|
||||
`IHostApplicationLifetime.StopApplication()` so the process exits and the supervisor restarts it instead
|
||||
of idling forever with a dead actor system. Under `auto-down` the *survivor* no longer needs this
|
||||
it watches `ActorSystem.WhenTerminated` and, on a termination outside host shutdown (auto-down, manual
|
||||
failover `Leave`, endpoint step-down), flushes Serilog and **exits the process with code 1**
|
||||
(`Environment.Exit`, on a dedicated thread) so the supervisor restarts it instead of idling forever with
|
||||
a dead actor system. It deliberately does **not** call `StopApplication()` (#980 / review 05 H-1): under
|
||||
`UseWindowsService` that is a *clean* service stop (`SERVICE_STOPPED`, exit 0), which `sc.exe failure`
|
||||
recovery does not act on, so a node that left the cluster stayed stopped on Windows (docker's
|
||||
`restart: unless-stopped` masked it). A graceful host stop (SCM stop, Ctrl-C) is still silent. The
|
||||
real-SCM check (leave a node on a Windows pair, assert the service returns to `Running` within the first
|
||||
recovery delay) is a live gate on `windev`. Under `auto-down` the *survivor* no longer needs this
|
||||
(it is never the one downed); the **downed** node still does.
|
||||
3. **Both peers listed in `SeedNodes`** on every node, **each node listing itself first**, so a restarted
|
||||
node can re-join via either peer and a node cold-starting while its peer is dead still forms the
|
||||
@@ -508,7 +514,7 @@ The mechanism is a graceful cluster **`Leave`** of the current Primary, never a
|
||||
query to `RedundancyStateActor.SelectDriverPrimary`, pinned together by
|
||||
`ManualFailoverServiceTests.Parity_with_SelectDriverPrimary` so the node acted on is exactly the node the
|
||||
election names. The leaving node hands its singletons over through the cluster-leave phases,
|
||||
`CoordinatedShutdown` runs, `ActorSystemTerminationWatchdog` exits the process, the supervisor restarts it,
|
||||
`CoordinatedShutdown` runs, `ActorSystemTerminationWatchdog` exits the process (non-zero), the supervisor restarts it,
|
||||
and it rejoins as the **youngest** member — so the survivor is now the oldest, becomes Primary, and
|
||||
advertises `ServiceLevel` 250. OPC UA clients re-select.
|
||||
|
||||
|
||||
@@ -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.");
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
+5
-1
@@ -108,7 +108,11 @@ public sealed class AuditWriterActorRejectedRowTests : ControlPlaneActorTestBase
|
||||
foreach (var id in ids) persisted.ShouldContain(id);
|
||||
}
|
||||
|
||||
/// <summary>A failure that names no entry is a whole-batch failure, exactly as before.</summary>
|
||||
/// <summary>
|
||||
/// A failure that names no entry is a whole-batch failure: the batch is kept for retry (#980 H-2; see
|
||||
/// <see cref="AuditWriterActorRetryTests"/>), so the ONLY loss left is the final flush at stop with the
|
||||
/// database still down. Terminating ⇒ the retry loop does not spin.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void A_connection_level_failure_still_drops_the_batch_without_looping()
|
||||
{
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
using Akka.Actor;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Diagnostics;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Storage;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.Audit;
|
||||
using ZB.MOM.WW.OtOpcUa.Configuration;
|
||||
using ZB.MOM.WW.OtOpcUa.ControlPlane.Audit;
|
||||
using ZB.MOM.WW.OtOpcUa.ControlPlane.Tests.Harness;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.ControlPlane.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// #980 / review 05 H-2 — a flush that fails because the database did not answer used to clear the
|
||||
/// buffer first and drop the batch. The writer now keeps it (bounded, drop-oldest + counter) and the next
|
||||
/// tick retries; the unique EventId index makes a retried batch safe.
|
||||
/// </summary>
|
||||
public sealed class AuditWriterActorRetryTests : ControlPlaneActorTestBase
|
||||
{
|
||||
[Fact]
|
||||
public void A_transient_connection_failure_keeps_the_batch_and_the_next_flush_persists_it()
|
||||
{
|
||||
var failing = new FailingSaves { Down = true };
|
||||
var factory = new FailingDbFactory(Guid.NewGuid().ToString("N"), new InMemoryDatabaseRoot(), failing);
|
||||
var actor = ActorOfAsTestActorRef<AuditWriterActor>(AuditWriterActor.Props(factory));
|
||||
|
||||
var ids = Enumerable.Range(0, 20).Select(_ => Guid.NewGuid()).ToList();
|
||||
foreach (var id in ids) actor.Tell(NewEvent(id));
|
||||
|
||||
actor.Tell(AuditWriterActor.Flush.Instance); // outage: the save throws
|
||||
actor.UnderlyingActor.BufferedCount.ShouldBe(20, "the failed batch must stay buffered, not be dropped");
|
||||
failing.Attempts.ShouldBeGreaterThan(0, "positive control: the failure path really ran");
|
||||
using (var during = factory.CreateDbContext(withFailure: false))
|
||||
during.ConfigAuditLogs.Count().ShouldBe(0);
|
||||
|
||||
failing.Down = false;
|
||||
actor.Tell(AuditWriterActor.Flush.Instance); // recovery
|
||||
actor.UnderlyingActor.BufferedCount.ShouldBe(0);
|
||||
|
||||
using var db = factory.CreateDbContext(withFailure: false);
|
||||
var persisted = db.ConfigAuditLogs.Select(r => r.EventId).ToList();
|
||||
persisted.Count.ShouldBe(20, "no event may be lost across the outage");
|
||||
foreach (var id in ids) persisted.ShouldContain(id);
|
||||
actor.UnderlyingActor.OverflowDroppedCount.ShouldBe(0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Events_arriving_during_an_outage_are_kept_and_persist_after_recovery()
|
||||
{
|
||||
var failing = new FailingSaves { Down = true };
|
||||
var factory = new FailingDbFactory(Guid.NewGuid().ToString("N"), new InMemoryDatabaseRoot(), failing);
|
||||
var actor = ActorOfAsTestActorRef<AuditWriterActor>(AuditWriterActor.Props(factory));
|
||||
|
||||
// Cross the count threshold so a threshold flush fires, fails, and the writer must NOT retry per event.
|
||||
var ids = Enumerable.Range(0, AuditWriterActor.FlushBatchSize + 50).Select(_ => Guid.NewGuid()).ToList();
|
||||
foreach (var id in ids) actor.Tell(NewEvent(id));
|
||||
|
||||
failing.Attempts.ShouldBe(1, "while the database is failing, arriving events must not each trigger a blocking flush attempt");
|
||||
actor.UnderlyingActor.BufferedCount.ShouldBe(ids.Count);
|
||||
|
||||
failing.Down = false;
|
||||
actor.Tell(AuditWriterActor.Flush.Instance);
|
||||
using var db = factory.CreateDbContext(withFailure: false);
|
||||
db.ConfigAuditLogs.Count().ShouldBe(ids.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void The_retry_buffer_is_bounded_dropping_the_oldest_and_counting_them()
|
||||
{
|
||||
var failing = new FailingSaves { Down = true };
|
||||
var factory = new FailingDbFactory(Guid.NewGuid().ToString("N"), new InMemoryDatabaseRoot(), failing);
|
||||
var actor = ActorOfAsTestActorRef<AuditWriterActor>(AuditWriterActor.Props(factory));
|
||||
|
||||
const int extra = 25;
|
||||
var ids = Enumerable.Range(0, AuditWriterActor.MaxBufferedEvents + extra).Select(_ => Guid.NewGuid()).ToList();
|
||||
foreach (var id in ids) actor.Tell(NewEvent(id));
|
||||
|
||||
actor.UnderlyingActor.BufferedCount.ShouldBe(AuditWriterActor.MaxBufferedEvents);
|
||||
actor.UnderlyingActor.OverflowDroppedCount.ShouldBe(extra);
|
||||
|
||||
failing.Down = false;
|
||||
actor.Tell(AuditWriterActor.Flush.Instance);
|
||||
using var db = factory.CreateDbContext(withFailure: false);
|
||||
var persisted = db.ConfigAuditLogs.Select(r => r.EventId).ToHashSet();
|
||||
persisted.Count.ShouldBe(AuditWriterActor.MaxBufferedEvents);
|
||||
// Drop-OLDEST: the first `extra` are gone, the newest survive.
|
||||
foreach (var id in ids.Take(extra)) persisted.ShouldNotContain(id);
|
||||
persisted.ShouldContain(ids[^1]);
|
||||
persisted.ShouldContain(ids[extra]);
|
||||
}
|
||||
|
||||
private static AuditEvent NewEvent(Guid eventId) => new()
|
||||
{
|
||||
EventId = eventId, Category = "Config", Action = "Edit", Actor = "joe",
|
||||
OccurredAtUtc = DateTimeOffset.UtcNow, Outcome = AuditOutcome.Success,
|
||||
DetailsJson = "{}", SourceNode = "node-a", CorrelationId = Guid.NewGuid(),
|
||||
};
|
||||
|
||||
/// <summary>Throws a connection-level (entry-less) <see cref="DbUpdateException"/> on every save while <see cref="Down"/>.</summary>
|
||||
private sealed class FailingSaves : ISaveChangesInterceptor
|
||||
{
|
||||
private int _attempts;
|
||||
public volatile bool Down;
|
||||
public int Attempts => Volatile.Read(ref _attempts);
|
||||
|
||||
public InterceptionResult<int> SavingChanges(DbContextEventData eventData, InterceptionResult<int> result)
|
||||
{
|
||||
if (!Down) return result;
|
||||
Interlocked.Increment(ref _attempts);
|
||||
throw new DbUpdateException("connection lost (simulated)");
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class FailingDbFactory(string dbName, InMemoryDatabaseRoot root, FailingSaves interceptor)
|
||||
: IDbContextFactory<OtOpcUaConfigDbContext>
|
||||
{
|
||||
public OtOpcUaConfigDbContext CreateDbContext() => CreateDbContext(withFailure: true);
|
||||
|
||||
public OtOpcUaConfigDbContext CreateDbContext(bool withFailure)
|
||||
{
|
||||
var builder = new DbContextOptionsBuilder<OtOpcUaConfigDbContext>().UseInMemoryDatabase(dbName, root);
|
||||
if (withFailure) builder.AddInterceptors(interceptor);
|
||||
return new OtOpcUaConfigDbContext(builder.Options);
|
||||
}
|
||||
}
|
||||
}
|
||||
+66
-10
@@ -15,22 +15,47 @@ namespace ZB.MOM.WW.OtOpcUa.Host.IntegrationTests;
|
||||
[Trait("Category", "Unit")]
|
||||
public sealed class ActorSystemTerminationWatchdogTests
|
||||
{
|
||||
/// <summary>An unexpected ActorSystem termination stops the host so the supervisor restarts the node.</summary>
|
||||
/// <summary>
|
||||
/// An unexpected ActorSystem termination ends the process with a NON-ZERO exit code (#980 H-1):
|
||||
/// a graceful <c>StopApplication</c> reports a clean service stop and SCM never restarts it.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task Unexpected_termination_stops_the_application()
|
||||
public async Task Unexpected_termination_exits_the_process_non_zero_after_flushing_logs()
|
||||
{
|
||||
var system = ActorSystem.Create("watchdog-unexpected");
|
||||
var lifetime = new FakeHostApplicationLifetime();
|
||||
var watchdog = new ActorSystemTerminationWatchdog(
|
||||
() => system, lifetime, NullLogger<ActorSystemTerminationWatchdog>.Instance);
|
||||
var exits = new ExitRecorder();
|
||||
var watchdog = Create(system, lifetime, exits);
|
||||
|
||||
await watchdog.StartAsync(CancellationToken.None);
|
||||
|
||||
// Simulate the SBR self-down: the ActorSystem terminates while the host is still running.
|
||||
await system.Terminate();
|
||||
|
||||
await WaitForAsync(() => lifetime.StopApplicationCalls > 0, TimeSpan.FromSeconds(5));
|
||||
lifetime.StopApplicationCalls.ShouldBe(1, "an out-of-band ActorSystem termination must stop the host once");
|
||||
await WaitForAsync(() => exits.ExitCodes.Count > 0, TimeSpan.FromSeconds(5));
|
||||
exits.ExitCodes.ShouldBe([ActorSystemTerminationWatchdog.FailureExitCode],
|
||||
"an out-of-band ActorSystem termination must end the process once, non-zero");
|
||||
ActorSystemTerminationWatchdog.FailureExitCode.ShouldNotBe(0);
|
||||
exits.FlushCalls.ShouldBe(1, "logs are flushed before the process exits");
|
||||
exits.FlushedBeforeExit.ShouldBeTrue();
|
||||
lifetime.StopApplicationCalls.ShouldBe(0,
|
||||
"StopApplication is a CLEAN stop (SERVICE_STOPPED, exit 0) and would defeat SCM recovery");
|
||||
}
|
||||
|
||||
/// <summary>A throwing log flush must never prevent the exit.</summary>
|
||||
[Fact]
|
||||
public async Task A_failing_log_flush_still_exits_the_process()
|
||||
{
|
||||
var system = ActorSystem.Create("watchdog-flush-throws");
|
||||
var lifetime = new FakeHostApplicationLifetime();
|
||||
var exits = new ExitRecorder { FlushThrows = true };
|
||||
var watchdog = Create(system, lifetime, exits);
|
||||
|
||||
await watchdog.StartAsync(CancellationToken.None);
|
||||
await system.Terminate();
|
||||
|
||||
await WaitForAsync(() => exits.ExitCodes.Count > 0, TimeSpan.FromSeconds(5));
|
||||
exits.ExitCodes.ShouldBe([ActorSystemTerminationWatchdog.FailureExitCode]);
|
||||
}
|
||||
|
||||
/// <summary>A graceful host stop (StopAsync ran) leaves the termination continuation silent.</summary>
|
||||
@@ -39,8 +64,8 @@ public sealed class ActorSystemTerminationWatchdogTests
|
||||
{
|
||||
var system = ActorSystem.Create("watchdog-graceful");
|
||||
var lifetime = new FakeHostApplicationLifetime();
|
||||
var watchdog = new ActorSystemTerminationWatchdog(
|
||||
() => system, lifetime, NullLogger<ActorSystemTerminationWatchdog>.Instance);
|
||||
var exits = new ExitRecorder();
|
||||
var watchdog = Create(system, lifetime, exits);
|
||||
|
||||
await watchdog.StartAsync(CancellationToken.None);
|
||||
|
||||
@@ -51,6 +76,7 @@ public sealed class ActorSystemTerminationWatchdogTests
|
||||
// Give any continuation a chance to run, then assert it stayed silent.
|
||||
await Task.Delay(500, TestContext.Current.CancellationToken);
|
||||
lifetime.StopApplicationCalls.ShouldBe(0, "a graceful shutdown must not re-trigger StopApplication");
|
||||
exits.ExitCodes.ShouldBeEmpty("a graceful shutdown must not exit the process as a failure");
|
||||
}
|
||||
|
||||
/// <summary>Termination while the host is already stopping (ApplicationStopping fired) stays silent.</summary>
|
||||
@@ -59,8 +85,8 @@ public sealed class ActorSystemTerminationWatchdogTests
|
||||
{
|
||||
var system = ActorSystem.Create("watchdog-already-stopping");
|
||||
var lifetime = new FakeHostApplicationLifetime();
|
||||
var watchdog = new ActorSystemTerminationWatchdog(
|
||||
() => system, lifetime, NullLogger<ActorSystemTerminationWatchdog>.Instance);
|
||||
var exits = new ExitRecorder();
|
||||
var watchdog = Create(system, lifetime, exits);
|
||||
|
||||
await watchdog.StartAsync(CancellationToken.None);
|
||||
|
||||
@@ -69,6 +95,36 @@ public sealed class ActorSystemTerminationWatchdogTests
|
||||
|
||||
await Task.Delay(500, TestContext.Current.CancellationToken);
|
||||
lifetime.StopApplicationCalls.ShouldBe(0, "termination during an in-progress host shutdown must stay silent");
|
||||
exits.ExitCodes.ShouldBeEmpty("termination during an in-progress host shutdown must not exit as a failure");
|
||||
}
|
||||
|
||||
private static ActorSystemTerminationWatchdog Create(
|
||||
ActorSystem system, IHostApplicationLifetime lifetime, ExitRecorder exits) =>
|
||||
new(() => system, lifetime, NullLogger<ActorSystemTerminationWatchdog>.Instance, exits.Exit, exits.Flush);
|
||||
|
||||
/// <summary>Records the exit + flush the watchdog performs instead of killing the test process.</summary>
|
||||
private sealed class ExitRecorder
|
||||
{
|
||||
private readonly object _gate = new();
|
||||
public List<int> ExitCodes { get; } = [];
|
||||
public int FlushCalls { get; private set; }
|
||||
public bool FlushedBeforeExit { get; private set; }
|
||||
public bool FlushThrows { get; init; }
|
||||
|
||||
public void Flush()
|
||||
{
|
||||
lock (_gate) FlushCalls++;
|
||||
if (FlushThrows) throw new InvalidOperationException("sink down");
|
||||
}
|
||||
|
||||
public void Exit(int code)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
FlushedBeforeExit = FlushCalls > 0;
|
||||
ExitCodes.Add(code);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task WaitForAsync(Func<bool> condition, TimeSpan timeout)
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Host.Configuration;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Host.IntegrationTests;
|
||||
|
||||
/// <summary>
|
||||
/// #980 / review 05 H-5 — an HTTPS binding combined with a requested dedicated h2c listener used to log one
|
||||
/// Error, zero the ports and keep booting (ready, but with no deploy/config/telemetry endpoints). It must
|
||||
/// fail host start instead, naming every setting involved.
|
||||
/// </summary>
|
||||
[Trait("Category", "Unit")]
|
||||
public sealed class DedicatedListenerGuardTests
|
||||
{
|
||||
[Fact]
|
||||
public void Https_with_a_requested_telemetry_listener_fails_start_naming_the_setting_and_the_urls()
|
||||
{
|
||||
var bindings = KestrelHttpBinding.Parse("https://+:443");
|
||||
var ex = Should.Throw<InvalidOperationException>(() =>
|
||||
DedicatedListenerGuard.ThrowIfHttpsBlocksDedicatedListeners(
|
||||
syncListenPort: 0, configServeGrpcPort: 0, telemetryListenPort: 4056, dataListenPort: 0,
|
||||
bindings, "https://+:443"));
|
||||
ex.Message.ShouldContain("Telemetry:GrpcListenPort=4056");
|
||||
ex.Message.ShouldContain("https://+:443");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Every_requested_listener_is_named_in_the_error()
|
||||
{
|
||||
var bindings = KestrelHttpBinding.Parse("http://localhost:5000;https://+:443");
|
||||
var ex = Should.Throw<InvalidOperationException>(() =>
|
||||
DedicatedListenerGuard.ThrowIfHttpsBlocksDedicatedListeners(
|
||||
4057, 4055, 4056, 0, bindings, "http://localhost:5000;https://+:443"));
|
||||
ex.Message.ShouldContain("LocalDb:SyncListenPort=4057");
|
||||
ex.Message.ShouldContain("ConfigServe:GrpcListenPort=4055");
|
||||
ex.Message.ShouldContain("Telemetry:GrpcListenPort=4056");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void An_https_port_list_binding_is_also_refused()
|
||||
{
|
||||
var bindings = KestrelHttpBinding.ParsePorts("443", isSecure: true);
|
||||
Should.Throw<InvalidOperationException>(() =>
|
||||
DedicatedListenerGuard.ThrowIfHttpsBlocksDedicatedListeners(0, 4055, 0, 0, bindings, null));
|
||||
}
|
||||
|
||||
// Positive controls: the guard must not trip on configurations that are valid.
|
||||
|
||||
[Fact]
|
||||
public void Https_with_no_dedicated_listener_requested_is_fine()
|
||||
{
|
||||
var bindings = KestrelHttpBinding.Parse("https://+:443");
|
||||
Should.NotThrow(() =>
|
||||
DedicatedListenerGuard.ThrowIfHttpsBlocksDedicatedListeners(0, 0, 0, 0, bindings, "https://+:443"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Http_with_every_dedicated_listener_requested_is_fine()
|
||||
{
|
||||
var bindings = KestrelHttpBinding.Parse("http://+:8080");
|
||||
Should.NotThrow(() =>
|
||||
DedicatedListenerGuard.ThrowIfHttpsBlocksDedicatedListeners(4057, 4055, 4056, 4058, bindings, "http://+:8080"));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user