feat(audit,install): #1030 audit overflow drops exported as otopcua.audit.dropped; scripted SCM-restart-after-cluster-exit gate

- AuditWriterActor: every buffer-full drop is added to OtOpcUaTelemetry.AuditDropped
  (otopcua.audit.dropped{reason=buffer_full, actor}) — the count used to be readable only
  through the actor's own property.
- scripts/install/tests/Test-ScmRestartAfterClusterExit.Windows.ps1: the windev manual gate
  of 2026-12-03 as a script (qfailure restart action; failover/command trigger => non-zero exit,
  7031, Running under a new pid; Stop-Service stays stopped; optional kill control). Parse-checked
  with pwsh on macOS; must be run elevated on a Windows box hosting OtOpcUaHost.

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Joseph Doherty
2026-12-03 15:02:09 -05:00
parent 6b19f4add6
commit 2a8bac5bf5
7 changed files with 266 additions and 2 deletions
+1 -1
View File
@@ -435,7 +435,7 @@ 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).
*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; since #1030 every drop is also exported as the meter counter `otopcua.audit.dropped{reason=buffer_full}` on the `ZB.MOM.WW.OtOpcUa` meter — alert on any non-zero rate, it means `ConfigAuditLog` is missing rows). 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
+9
View File
@@ -504,6 +504,15 @@ two-node pair that choice means *any* crash of the oldest node is a full outage.
that Akka's -1 is invisible to SCM recovery). Positive control: `sc stop` on the fixed build → clean
`Stopped`, exit 0, no recovery. Under `auto-down` the *survivor* no longer needs this (it is never the one
downed); the **downed** node still does.
**Scripted form of that gate (#1030):** `scripts/install/tests/Test-ScmRestartAfterClusterExit.Windows.ps1`, run
elevated on the box hosting an installed `OtOpcUaHost` (the pair's current Primary for the default
`-Trigger Failover`, which pauses while the operator presses *Trigger failover* on the cluster redundancy page;
`-Trigger Command -TriggerCommand '…'` for an unattended trigger). It checks `sc.exe qfailure` has a restart action,
that the leave ends the process non-zero, logs **7031** and comes back `Running` under a new pid, and — as the
negative control — that `Stop-Service` stays `Stopped` with no 7031; `-KillControl` adds a hard-kill leg that
proves the SCM recovery config on its own. It never reconfigures the service and always leaves it running. Not
for the wonder boxes while remote access is on hold.
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
cluster. Without the self-first ordering it waits in `InitJoin` forever (auto-down removes the crash
+3
View File
@@ -186,6 +186,9 @@ steps inside the window (a `data\` backup) and the host start-up to `/health/rea
- `scripts/install/Install-Services.ps1 -Roles admin,driver` — installs `OtOpcUaHost`.
- `scripts/install/Install-ScriptWorkerIsolation.ps1` — the ScriptWorker identity, ACLs and firewall rule (above); only for `Scripting:Runner` ≠ `InProcess`.
- `scripts/install/Invoke-OtOpcUaInstallSwap.ps1` — upgrade/rollback folder swap with the isolation `-Reapply` + `-Verify` gate built in (lmxopcua#901), scoped so only the swapped-in folder is handled while the service is stopped (lmxopcua#905, above).
- `scripts/install/tests/Test-ScmRestartAfterClusterExit.Windows.ps1` — elevated, on the node's own box: checks that a node
leaving its cluster (manual failover) is restarted by the `sc.exe failure` recovery `Install-Services.ps1` sets, and that a
clean `Stop-Service` is not (#980/#1030; `docs/Redundancy.md` §"Recovery still depends on supervision").
- `scripts/install/Uninstall-Services.ps1` — stops + removes the host service. (The historian backend is the external HistorianGateway — not installed/removed by these scripts.)
## Logging
@@ -0,0 +1,187 @@
<#
.SYNOPSIS
Windows-executed gate for lmxopcua#980 / #1030: an OtOpcUaHost node whose ActorSystem terminates because it LEFT or was
DOWNED from its cluster (manual failover, endpoint step-down, auto-down) must be RESTARTED by Windows SCM recovery
(sc.exe failure), while an operator `sc stop` must stay stopped.
.DESCRIPTION
Background (docs/Redundancy.md "Recovery still depends on supervision"): ActorSystemTerminationWatchdog exits the process
with code 1 on an unexpected termination, so SCM sees the service process die WITHOUT reporting SERVICE_STOPPED, logs
System event 7031 ("terminated unexpectedly") and runs the configured recovery action. Before #980 the node ended in a
clean stop (SERVICE_STOPPED, win32 exit 0) and SCM never restarted it. This script is the scripted form of the manual
windev gate of 2026-12-03.
It runs ON the Windows box that hosts the service under test, elevated, against an INSTALLED OtOpcUaHost
(scripts\install\Install-Services.ps1). It never installs, uninstalls or reconfigures anything; it stops/starts only the
named service and always leaves it Running (finally block).
Legs (each prints PASS/FAIL lines; exit 0 = all passed, 1 = a check failed, 2 = cannot run here):
1. Recovery config sc.exe qfailure lists at least one RESTART action (what Install-Services.ps1 sets).
2. Cluster exit the trigger makes this node leave / be downed. Expected: the service process exits (exit code 1
when readable), SCM logs 7031 for the service, and the service is Running again under a NEW pid
within the recovery delay + -TimeoutSeconds.
3. Clean stop (unless -SkipStopControl) Stop-Service: the service reports Stopped, NO new 7031 is logged and it
is NOT restarted within the first recovery delay + 15 s; then the script starts it again.
4. Kill control (only with -KillControl) Stop-Process -Force: a crash is restarted (7031/7034). This proves the
SCM recovery config, not the watchdog — use it to tell "recovery not configured" from "the
node did not exit non-zero" when leg 2 fails.
Triggers (-Trigger):
Failover (default) the script pauses and asks the operator to press "Trigger failover" on the AdminUI cluster
redundancy page (/clusters/{id}/redundancy). Manual failover asks the driver PRIMARY to leave, so run this on
the box hosting the current Primary of a two-node pair. Needs an interactive console.
Command runs -TriggerCommand (a PowerShell script block, as text) that makes THIS node leave or be downed, e.g. a
local admin tool; the script does not interpret it.
Do NOT run this on the wonder boxes (vd03 / vq03 / vq04) while remote access is on hold — it is meant for windev or a QA
pair, run locally by an operator. It restarts the node it targets: a two-node pair fails over once (and again for
-KillControl); a single-node cluster has an outage for each leg.
Run once per PowerShell host if in doubt; it uses nothing host-specific:
pwsh -NoProfile -File scripts\install\tests\Test-ScmRestartAfterClusterExit.Windows.ps1
powershell -NoProfile -ExecutionPolicy Bypass -File scripts\install\tests\Test-ScmRestartAfterClusterExit.Windows.ps1 -KillControl
pwsh -NoProfile -File ...\Test-ScmRestartAfterClusterExit.Windows.ps1 -Trigger Command -TriggerCommand '<script>'
.PARAMETER ServiceName
The service under test (default OtOpcUaHost, as Install-Services.ps1 names it).
.PARAMETER TimeoutSeconds
How long, beyond the first recovery delay, to wait for the process to exit after the trigger and for the restart.
#>
[CmdletBinding()]
param(
[string]$ServiceName = 'OtOpcUaHost',
[ValidateSet('Failover', 'Command')][string]$Trigger = 'Failover',
[string]$TriggerCommand,
[int]$TimeoutSeconds = 180,
[switch]$SkipStopControl,
[switch]$KillControl)
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
if ($PSVersionTable.PSEdition -eq 'Core' -and -not $IsWindows) { Write-Host 'SKIP: Windows only'; exit 0 }
$principal = [Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()
if (-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { Write-Host 'run elevated'; exit 2 }
if ($Trigger -eq 'Command' -and [string]::IsNullOrWhiteSpace($TriggerCommand)) { Write-Host '-Trigger Command needs -TriggerCommand'; exit 2 }
if ($Trigger -eq 'Failover' -and -not [Environment]::UserInteractive) { Write-Host '-Trigger Failover needs an interactive console (use -Trigger Command)'; exit 2 }
$svc = Get-CimInstance Win32_Service -Filter "Name='$ServiceName'"
if (-not $svc) { Write-Host "service $ServiceName is not installed"; exit 2 }
if ($svc.State -ne 'Running') { Write-Host "service $ServiceName is $($svc.State); start it first"; exit 2 }
$displayName = $svc.DisplayName
$script:failures = 0; $script:passes = 0
function Assert([bool]$Condition, [string]$Message) {
if ($Condition) { $script:passes++; Write-Host " PASS: $Message" -ForegroundColor Green }
else { $script:failures++; Write-Host " FAIL: $Message" -ForegroundColor Red }
}
function Get-ServicePid { [int](Get-CimInstance Win32_Service -Filter "Name='$ServiceName'").ProcessId }
function Get-ServiceState { (Get-CimInstance Win32_Service -Filter "Name='$ServiceName'").State }
# SCM "terminated unexpectedly" (7031) and "terminated unexpectedly ... times" (7034, no recovery action configured) events for
# THIS service since $Since. Insertion string 0 is the service's display name.
function Get-UnexpectedTerminationEvents([datetime]$Since, [int[]]$Ids = @(7031)) {
$events = Get-WinEvent -FilterHashtable @{ LogName = 'System'; ProviderName = 'Service Control Manager'; Id = $Ids; StartTime = $Since } -ErrorAction SilentlyContinue
@($events | Where-Object { $_.Properties.Count -gt 0 -and $_.Properties[0].Value -eq $displayName })
}
# Opens a handle on the CURRENT service process before anything happens, so its exit code is readable after it exits
# (best effort: reading another session's process needs SeDebugPrivilege, which an elevated admin holds).
function Watch-ServiceProcess([int]$ProcessId) {
try { $p = [Diagnostics.Process]::GetProcessById($ProcessId); $null = $p.Handle; $p } catch { $null }
}
function Wait-Until([scriptblock]$Condition, [int]$Seconds) {
$deadline = [DateTime]::UtcNow.AddSeconds($Seconds)
while ([DateTime]::UtcNow -lt $deadline) {
if (& $Condition) { return $true }
Start-Sleep -Milliseconds 500
}
return [bool](& $Condition)
}
# First RESTART delay from `sc.exe qfailure` (ms), or $null when none is configured.
function Get-FirstRestartDelayMs {
$q = & sc.exe qfailure $ServiceName 5000 | Out-String
$m = [regex]::Match($q, 'RESTART\s*--\s*Delay\s*=\s*(?<ms>\d+)', 'IgnoreCase')
if ($m.Success) { [int]$m.Groups['ms'].Value } else { $null }
}
Write-Host "Service: $ServiceName ('$displayName'), pid $(Get-ServicePid); host $($PSVersionTable.PSEdition) $($PSVersionTable.PSVersion); trigger $Trigger"
try {
# ---- 1. recovery config ----
Write-Host 'Recovery config'
$delayMs = Get-FirstRestartDelayMs
Assert ($null -ne $delayMs) "sc.exe qfailure $ServiceName lists a RESTART action (Install-Services.ps1 sets restart/5000/restart/30000/restart/60000)"
if ($null -eq $delayMs) { throw 'no SCM restart action is configured; nothing below can pass (re-run Install-Services.ps1 or sc.exe failure)' }
$waitSeconds = [int][Math]::Ceiling($delayMs / 1000.0) + $TimeoutSeconds
# ---- 2. cluster exit -> SCM restart ----
Write-Host 'Cluster leave / down'
$before = Get-ServicePid
$proc = Watch-ServiceProcess $before
$since = (Get-Date).AddSeconds(-1)
if ($Trigger -eq 'Failover') {
Write-Host ' Press "Trigger failover" on the AdminUI cluster redundancy page for THIS node''s cluster (this node must be the'
Write-Host ' driver Primary), then press Enter here.'
$null = Read-Host
}
else {
& ([scriptblock]::Create($TriggerCommand))
}
$exited = Wait-Until { (Get-ServicePid) -ne $before } $waitSeconds
Assert $exited "the service process (pid $before) exited after the trigger (if not: this node was not the one leaving - run on the Primary)"
if ($proc) {
if ($proc.WaitForExit(10000)) {
Assert ($proc.ExitCode -ne 0) "the process exit code is non-zero (was $($proc.ExitCode); the watchdog exits 1 - 0 or -1 means a clean stop SCM ignores)"
}
$proc.Dispose()
}
$restarted = Wait-Until { (Get-ServiceState) -eq 'Running' -and (Get-ServicePid) -notin 0, $before } $waitSeconds
Assert $restarted "SCM restarted the service (state $(Get-ServiceState), pid $(Get-ServicePid))"
$evt = Get-UnexpectedTerminationEvents $since
Assert ($evt.Count -ge 1) "System log has event 7031 (terminated unexpectedly) for '$displayName' since the trigger"
# ---- 3. clean stop stays stopped ----
if (-not $SkipStopControl) {
Write-Host 'Clean stop (negative control)'
$since = (Get-Date).AddSeconds(-1)
Stop-Service -Name $ServiceName
Assert ((Get-ServiceState) -eq 'Stopped') 'Stop-Service leaves the service Stopped'
$quiet = [int][Math]::Ceiling($delayMs / 1000.0) + 15
$cameBack = Wait-Until { (Get-ServiceState) -ne 'Stopped' } $quiet
Assert (-not $cameBack) "a clean stop is NOT restarted within $quiet s"
Assert ((Get-UnexpectedTerminationEvents $since).Count -eq 0) 'a clean stop logs no 7031'
Start-Service -Name $ServiceName
Assert (Wait-Until { (Get-ServiceState) -eq 'Running' } 60) 'the service starts again'
}
# ---- 4. kill control ----
if ($KillControl) {
Write-Host 'Kill (SCM recovery control)'
$before = Get-ServicePid
$since = (Get-Date).AddSeconds(-1)
Stop-Process -Id $before -Force
$back = Wait-Until { (Get-ServiceState) -eq 'Running' -and (Get-ServicePid) -notin 0, $before } $waitSeconds
Assert $back 'a killed process is restarted by SCM recovery'
Assert ((Get-UnexpectedTerminationEvents $since @(7031, 7034)).Count -ge 1) 'the kill logged 7031/7034'
}
}
catch { $script:failures++; Write-Host " FAIL: unexpected error: $($_ | Out-String)" -ForegroundColor Red }
finally {
# Always leave the node running, whatever failed.
try {
if ((Get-ServiceState) -ne 'Running') {
Write-Host "Restoring: starting $ServiceName"
Start-Service -Name $ServiceName -ErrorAction Continue
}
}
catch { Write-Host " could not restart $ServiceName - start it by hand: $($_.Exception.Message)" -ForegroundColor Yellow }
}
Write-Host ''
Write-Host "$($script:passes) passed, $($script:failures) failed"
if ($script:failures -gt 0) { exit 1 }
@@ -107,6 +107,20 @@ public static class OtOpcUaTelemetry
Meter.CreateCounter<long>("otopcua.scriptedalarm.transition", unit: "{transition}",
description: "Scripted-alarm state transitions (state=active|acknowledged|inactive).");
// ---------------- Audit ----------------
/// <summary>Instrument name of <see cref="AuditDropped"/>.</summary>
public const string AuditDroppedName = "otopcua.audit.dropped";
/// <summary>
/// lmxopcua#1030 — audit events the central <c>AuditWriterActor</c> dropped (oldest first) because its retry buffer
/// hit its bound while the ConfigDb was not accepting writes (#980). Tagged <c>reason=buffer_full</c> and
/// <c>actor</c> (the writer's path). Any non-zero value means <c>ConfigAuditLog</c> is missing rows.
/// </summary>
public static readonly Counter<long> AuditDropped =
Meter.CreateCounter<long>(AuditDroppedName, unit: "{event}",
description: "Audit events dropped by the AuditWriter because its retry buffer was full (reason=buffer_full).");
// ---------------- OPC UA address-space + redundancy ----------------
public static readonly Counter<long> OpcUaSinkWrite =
@@ -2,6 +2,7 @@ using Akka.Actor;
using Akka.Event;
using Microsoft.EntityFrameworkCore;
using ZB.MOM.WW.Audit;
using ZB.MOM.WW.OtOpcUa.Commons.Observability;
using ZB.MOM.WW.OtOpcUa.Configuration;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
@@ -18,7 +19,8 @@ namespace ZB.MOM.WW.OtOpcUa.ControlPlane.Audit;
/// 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.
/// (<see cref="OverflowDroppedCount"/>, exported as the <c>otopcua.audit.dropped</c> meter counter — #1030) 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.
///
@@ -41,12 +43,16 @@ public sealed class AuditWriterActor : ReceiveActor, IWithTimers, IAuditWriter
/// <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;
/// <summary>The exported counter overflow drops are metered on (#1030): <see cref="OtOpcUaTelemetry.AuditDropped"/>.</summary>
public const string DroppedCounterName = OtOpcUaTelemetry.AuditDroppedName;
private readonly IDbContextFactory<OtOpcUaConfigDbContext> _dbFactory;
private readonly ILoggingAdapter _log = Context.GetLogger();
// 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;
private string? _actorTag;
/// <summary>Total events dropped (oldest first) because the retry buffer hit <see cref="MaxBufferedEvents"/>.</summary>
public long OverflowDroppedCount => Interlocked.Read(ref _overflowDropped);
@@ -116,6 +122,10 @@ public sealed class AuditWriterActor : ReceiveActor, IWithTimers, IAuditWriter
for (var i = 0; i < overflow; i++) _buffer.RemoveAt(0);
var before = Interlocked.Read(ref _overflowDropped);
var total = Interlocked.Add(ref _overflowDropped, overflow);
// #1030: exported, so a scrape sees lost audit rows without reading this actor's property.
OtOpcUaTelemetry.AuditDropped.Add(overflow,
new KeyValuePair<string, object?>("reason", "buffer_full"),
new KeyValuePair<string, object?>("actor", _actorTag ??= Self.Path.ToStringWithoutAddress()));
// 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(
@@ -1,3 +1,5 @@
using System.Collections.Concurrent;
using System.Diagnostics.Metrics;
using Akka.Actor;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
@@ -91,6 +93,45 @@ public sealed class AuditWriterActorRetryTests : ControlPlaneActorTestBase
persisted.ShouldContain(ids[extra]);
}
/// <summary>
/// #1030: the overflow drop count is exported on the shared OtOpcUa meter as
/// <c>otopcua.audit.dropped</c> (it used to be visible only through the actor's own property, which nothing
/// outside a test can read). Measurements are filtered by the writer's <c>actor</c> tag so a parallel test's
/// writer cannot leak into the sum.
/// </summary>
[Fact]
public void Overflow_drops_are_exported_on_the_audit_dropped_meter_counter()
{
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 actorTag = actor.Path.ToStringWithoutAddress();
var measured = new ConcurrentQueue<long>();
using var listener = new MeterListener();
listener.InstrumentPublished = (instrument, l) =>
{
if (instrument.Name == AuditWriterActor.DroppedCounterName) l.EnableMeasurementEvents(instrument);
};
listener.SetMeasurementEventCallback<long>((_, value, tags, _) =>
{
string? owner = null, reason = null;
foreach (var tag in tags)
{
if (tag.Key == "actor") owner = tag.Value as string;
if (tag.Key == "reason") reason = tag.Value as string;
}
if (owner == actorTag && reason == "buffer_full") measured.Enqueue(value);
});
listener.Start();
const int extra = 7;
for (var i = 0; i < AuditWriterActor.MaxBufferedEvents + extra; i++) actor.Tell(NewEvent(Guid.NewGuid()));
actor.UnderlyingActor.OverflowDroppedCount.ShouldBe(extra, "positive control: the drops really happened");
measured.Sum().ShouldBe(extra, "every dropped event must be counted on the exported meter");
}
private static AuditEvent NewEvent(Guid eventId) => new()
{
EventId = eventId, Category = "Config", Action = "Edit", Actor = "joe",