Files
lmxopcua/tests/Server/ZB.MOM.WW.OtOpcUa.Host.IntegrationTests/ActorSystemTerminationWatchdogTests.cs
T
Joseph Doherty 645a8b9209 fix(host): #980 review — termination watchdog exits on a cluster leave/down under Akka.Hosting
The first #980 fix stayed quiet whenever ApplicationStopping was already cancelled. Akka.Hosting
1.5.62's AkkaHostedService hooks WhenTerminated earlier and, for ClusterLeavingReason /
ClusterDowningReason, sets Environment.ExitCode = -1 and calls StopApplication() BEFORE the
watchdog's continuation — so manual failover, endpoint step-down and auto-down all still ended in a
graceful stop (SERVICE_STOPPED, win32 exit 0 — SCM reads ServiceBase.ExitCode, not the -1) that
Windows SCM never restarts.

"Expected" is now decided from signals Akka.Hosting never produces: a host stop requested while
the ActorSystem still runs (SCM stop / Ctrl-C / GracefulClusterLeaveService), the watchdog's own
StopAsync before termination, or CoordinatedShutdown reason ClrExitReason. Everything else exits 1.
After an unexpected termination the watchdog's StopAsync holds host shutdown until the exit is
issued, so the service host cannot report SERVICE_STOPPED first. Registration moved to
AddOtOpcUaTerminationWatchdog (shared with tests).

Tests: TerminationWatchdogAkkaHostingTests — real AddAkka host + production cluster bootstrap +
GracefulClusterLeave: Leave(self)/Down(self) => exit 1 (both fail on the old logic); host StopAsync
and StopApplication-while-running => no exit. Live gate on windev SCM passed (7031 + restart; old
logic => Stopped, exit -1, no recovery; sc stop => clean stop).
2026-12-03 11:53:42 -05:00

210 lines
9.8 KiB
C#

using Akka.Actor;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging.Abstractions;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Host;
namespace ZB.MOM.WW.OtOpcUa.Host.IntegrationTests;
/// <summary>
/// Unit coverage for the #459 down-if-alone recovery watchdog: an unexpected
/// <see cref="ActorSystem"/> termination (SBR self-down) must stop the host so the supervisor
/// restarts it, while a graceful host shutdown must stay silent and not re-trigger stop.
/// </summary>
[Trait("Category", "Unit")]
public sealed class ActorSystemTerminationWatchdogTests
{
/// <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_exits_the_process_non_zero_after_flushing_logs()
{
var system = ActorSystem.Create("watchdog-unexpected");
var lifetime = new FakeHostApplicationLifetime();
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(() => 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>
[Fact]
public async Task Graceful_stop_does_not_stop_the_application()
{
var system = ActorSystem.Create("watchdog-graceful");
var lifetime = new FakeHostApplicationLifetime();
var exits = new ExitRecorder();
var watchdog = Create(system, lifetime, exits);
await watchdog.StartAsync(CancellationToken.None);
// Host is shutting down normally: StopAsync runs, THEN the system terminates.
await watchdog.StopAsync(CancellationToken.None);
await system.Terminate();
// 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>
[Fact]
public async Task Termination_while_already_stopping_stays_silent()
{
var system = ActorSystem.Create("watchdog-already-stopping");
var lifetime = new FakeHostApplicationLifetime();
var exits = new ExitRecorder();
var watchdog = Create(system, lifetime, exits);
await watchdog.StartAsync(CancellationToken.None);
lifetime.TriggerStopping(); // the host is already tearing down (ApplicationStopping cancelled)
await system.Terminate();
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");
}
/// <summary>
/// #980 review: Akka.Hosting's termination hook (registered earlier) calls <c>StopApplication</c> AFTER
/// the system terminated and BEFORE the watchdog's continuation. That stop must not read as "expected".
/// </summary>
[Fact]
public async Task Stop_requested_by_a_termination_hook_after_termination_still_exits()
{
var system = ActorSystem.Create("watchdog-hosting-hook-order");
var lifetime = new FakeHostApplicationLifetime();
var exits = new ExitRecorder();
// Mimic AkkaHostedService.TerminationHook: registered first, runs first.
_ = system.WhenTerminated.ContinueWith(_ => lifetime.TriggerStopping(), TaskContinuationOptions.ExecuteSynchronously);
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 host stop that arrives AFTER an unexpected termination (the host reacting to Akka.Hosting's
/// StopApplication) neither cancels the exit nor completes before it is issued — otherwise the Windows
/// service host could report SERVICE_STOPPED first.
/// </summary>
[Fact]
public async Task Stop_after_unexpected_termination_waits_for_the_exit()
{
var system = ActorSystem.Create("watchdog-stop-after-termination");
var lifetime = new FakeHostApplicationLifetime();
var exits = new ExitRecorder();
var exitGate = new ManualResetEventSlim(false);
var watchdog = new ActorSystemTerminationWatchdog(
() => system, lifetime, NullLogger<ActorSystemTerminationWatchdog>.Instance,
code => { exitGate.Wait(TimeSpan.FromSeconds(10)); exits.Exit(code); }, exits.Flush);
await watchdog.StartAsync(CancellationToken.None);
await system.Terminate();
var stop = watchdog.StopAsync(CancellationToken.None);
await Task.Delay(300, TestContext.Current.CancellationToken);
stop.IsCompleted.ShouldBeFalse("host shutdown must be held until the failure exit is issued");
exitGate.Set();
await stop.WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken);
exits.ExitCodes.ShouldBe([ActorSystemTerminationWatchdog.FailureExitCode]);
}
/// <summary>The expected/unexpected verdict by CoordinatedShutdown reason.</summary>
[Fact]
public void Only_a_host_stop_or_ClrExitReason_is_expected()
{
ActorSystemTerminationWatchdog.IsExpectedTermination(CoordinatedShutdown.ClrExitReason.Instance, false).ShouldBeTrue();
ActorSystemTerminationWatchdog.IsExpectedTermination(CoordinatedShutdown.ClusterLeavingReason.Instance, true).ShouldBeTrue();
ActorSystemTerminationWatchdog.IsExpectedTermination(CoordinatedShutdown.ClusterLeavingReason.Instance, false).ShouldBeFalse();
ActorSystemTerminationWatchdog.IsExpectedTermination(CoordinatedShutdown.ClusterDowningReason.Instance, false).ShouldBeFalse();
ActorSystemTerminationWatchdog.IsExpectedTermination(CoordinatedShutdown.ActorSystemTerminateReason.Instance, false).ShouldBeFalse();
ActorSystemTerminationWatchdog.IsExpectedTermination(null, false).ShouldBeFalse();
}
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)
{
var deadline = DateTime.UtcNow + timeout;
while (!condition() && DateTime.UtcNow < deadline)
await Task.Delay(20);
}
/// <summary>Minimal <see cref="IHostApplicationLifetime"/> that records <see cref="StopApplication"/> calls.</summary>
private sealed class FakeHostApplicationLifetime : IHostApplicationLifetime
{
private readonly CancellationTokenSource _stopping = new();
public int StopApplicationCalls { get; private set; }
public CancellationToken ApplicationStarted => CancellationToken.None;
public CancellationToken ApplicationStopping => _stopping.Token;
public CancellationToken ApplicationStopped => CancellationToken.None;
public void StopApplication() => StopApplicationCalls++;
public void TriggerStopping() => _stopping.Cancel();
}
}