Files
lmxopcua/scripts/install/tests/Test-ScmRestartAfterClusterExit.Windows.ps1
T
Joseph Doherty 2a8bac5bf5 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>
2026-12-03 15:20:06 -05:00

188 lines
11 KiB
PowerShell

<#
.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 }