Merge review fixes: termination watchdog exits 1 on cluster leave/down under Akka.Hosting (#980, windev SCM gate passed); Gateway alarm writer isolates poison events (#976)

This commit is contained in:
Joseph Doherty
2026-12-03 12:01:50 -05:00
16 changed files with 946 additions and 82 deletions
@@ -1,4 +1,5 @@
using Akka.Actor;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
@@ -29,10 +30,22 @@ namespace ZB.MOM.WW.OtOpcUa.Host;
///
/// <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"/>
/// (never at construction) so it can't race Akka startup. A graceful host stop is distinguished from
/// an unexpected SBR self-down via <see cref="_stopRequested"/> plus
/// <see cref="IHostApplicationLifetime.ApplicationStopping"/>, so normal shutdown never logs a false
/// alarm or double-triggers <see cref="IHostApplicationLifetime.StopApplication"/>.</para>
/// (never at construction) so it can't race Akka startup.</para>
///
/// <para><b>Deciding "expected" (#980 review).</b> NOT from <c>ApplicationStopping</c> at termination
/// time: Akka.Hosting 1.5.x's <c>AkkaHostedService</c> registers its own <c>WhenTerminated</c> hook
/// earlier, and for a <c>ClusterLeavingReason</c>/<c>ClusterDowningReason</c> shutdown it sets
/// <c>Environment.ExitCode = -1</c> and calls <c>StopApplication()</c> BEFORE this watchdog's
/// continuation runs — so the host always looked "already stopping" and every leave/down ended in a
/// graceful stop (SERVICE_STOPPED with win32 exit 0 — <c>ServiceBase.ExitCode</c>, not
/// <c>Environment.ExitCode</c>, is what SCM is told, so the -1 never triggers recovery). The signals
/// used instead are ones Akka.Hosting never produces: a host stop requested while the system was still
/// running (SCM stop, Ctrl-C, <see cref="GracefulClusterLeaveService"/>), this service's own
/// <see cref="StopAsync"/>, or a <see cref="CoordinatedShutdown"/> reason of
/// <see cref="CoordinatedShutdown.ClrExitReason"/> (what every host-initiated stop runs). See
/// <see cref="IsExpectedTermination"/>. On an unexpected termination <see cref="StopAsync"/> also holds
/// the host's shutdown until the exit is issued, so the service host cannot report SERVICE_STOPPED
/// first.</para>
/// </summary>
public sealed class ActorSystemTerminationWatchdog : IHostedService
{
@@ -41,7 +54,11 @@ public sealed class ActorSystemTerminationWatchdog : IHostedService
private readonly ILogger<ActorSystemTerminationWatchdog> _logger;
private readonly Action<int> _exitProcess;
private readonly Action _flushLogs;
private readonly TaskCompletionSource _exitIssued = new(TaskCreationOptions.RunContinuationsAsynchronously);
private readonly TaskCompletionSource<bool> _verdict = new(TaskCreationOptions.RunContinuationsAsynchronously); // true = exiting
private volatile ActorSystem? _system;
private volatile bool _stopRequested;
private volatile bool _hostStopRequestedWhileRunning;
/// <summary>Process exit code used when the actor system terminated outside host shutdown.</summary>
public const int FailureExitCode = 1;
@@ -66,47 +83,149 @@ public sealed class ActorSystemTerminationWatchdog : IHostedService
_flushLogs = flushLogs ?? Serilog.Log.CloseAndFlush;
}
/// <summary>Wires the <see cref="ActorSystem.WhenTerminated"/> continuation that exits the host on an unexpected self-down.</summary>
/// <param name="cancellationToken">Unused; the watchdog only registers a continuation.</param>
/// <summary>
/// Wires the expected-stop signal and the <see cref="ActorSystem.WhenTerminated"/> continuation that
/// exits the process on an unexpected termination.
/// </summary>
/// <param name="cancellationToken">Unused; the watchdog only registers callbacks.</param>
/// <returns>A completed task.</returns>
public Task StartAsync(CancellationToken cancellationToken)
{
var system = _actorSystemAccessor();
_system = system;
// A host stop requested while the ActorSystem is still RUNNING is an operator/supervisor stop
// (SCM stop, Ctrl-C/SIGTERM, GracefulClusterLeaveService.StoppingAsync): expected. Akka.Hosting's
// own termination hook calls StopApplication only AFTER the system has terminated, so it can
// never set this — which is exactly why "ApplicationStopping is cancelled" was not a usable signal
// (#980 review: the hook always ran first, so every leave/down looked like an expected stop).
_lifetime.ApplicationStopping.Register(() =>
{
if (!system.WhenTerminated.IsCompleted)
_hostStopRequestedWhileRunning = true;
});
system.WhenTerminated.ContinueWith(
_ =>
{
// Expected shutdown: our StopAsync ran, or the host is already stopping. Stay quiet.
if (_stopRequested || _lifetime.ApplicationStopping.IsCancellationRequested)
return;
_logger.LogCritical(
"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();
},
_ => OnTerminated(system),
TaskContinuationOptions.ExecuteSynchronously);
return Task.CompletedTask;
}
/// <summary>Marks a graceful shutdown so the termination continuation stays silent and does not re-trigger stop.</summary>
/// <param name="cancellationToken">Unused.</param>
/// <returns>A completed task.</returns>
public Task StopAsync(CancellationToken cancellationToken)
/// <summary>
/// Classifies an <see cref="ActorSystem"/> termination. Expected (stay quiet) when the host asked to
/// stop while the system was still running, or when <see cref="CoordinatedShutdown"/> ran for
/// <see cref="CoordinatedShutdown.ClrExitReason"/> — the reason both
/// <see cref="GracefulClusterLeaveService"/> and Akka.Hosting's own <c>StopAsync</c> use for a host
/// stop. Everything else — <c>ClusterLeavingReason</c> (manual failover, endpoint step-down),
/// <c>ClusterDowningReason</c> (auto-down / SBR), <c>ActorSystemTerminateReason</c>, an unknown or
/// absent reason — is unexpected: the node must exit non-zero so the supervisor restarts it.
/// </summary>
/// <param name="shutdownReason">The <see cref="CoordinatedShutdown.ShutdownReason"/>, or null when none ran.</param>
/// <param name="hostStopRequested">Whether the host asked to stop before the system terminated.</param>
/// <returns><see langword="true"/> when the termination is part of a normal host shutdown.</returns>
public static bool IsExpectedTermination(CoordinatedShutdown.Reason? shutdownReason, bool hostStopRequested) =>
hostStopRequested || shutdownReason is CoordinatedShutdown.ClrExitReason;
private void OnTerminated(ActorSystem system)
{
_stopRequested = true;
return Task.CompletedTask;
CoordinatedShutdown.Reason? reason = null;
try
{
reason = CoordinatedShutdown.Get(system).ShutdownReason;
}
catch (Exception ex)
{
// Unreadable reason ⇒ treat as unexpected: a needless restart beats a node that never returns.
_logger.LogDebug(ex, "Could not read the CoordinatedShutdown reason after ActorSystem termination.");
}
if (IsExpectedTermination(reason, _stopRequested || _hostStopRequestedWhileRunning))
{
_logger.LogInformation(
"ActorSystem terminated as part of a host shutdown (reason {Reason}); no restart requested.",
reason?.GetType().Name ?? "none");
_verdict.TrySetResult(false);
return;
}
_verdict.TrySetResult(true);
_logger.LogCritical(
"ActorSystem terminated outside host shutdown (reason {Reason}: 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).",
reason?.GetType().Name ?? "none",
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 */ }
try { _exitProcess(FailureExitCode); }
finally { _exitIssued.TrySetResult(); }
})
{ IsBackground = true, Name = "otopcua-watchdog-exit" };
exit.Start();
}
/// <summary>
/// Before termination: marks a graceful shutdown so the later termination stays silent. After an
/// unexpected termination: holds the host shutdown until the failure exit is issued: Akka.Hosting's
/// hook has called <c>StopApplication</c>, and if the host finished stopping first the Windows service
/// host would report <c>SERVICE_STOPPED</c> (win32 exit code 0) and SCM would never restart the node.
/// </summary>
/// <param name="cancellationToken">The host's shutdown token; bounds the wait.</param>
/// <returns>A task that completes when the stop may proceed.</returns>
public async Task StopAsync(CancellationToken cancellationToken)
{
var system = _system;
if (system is null)
return; // never started
// Only a stop that arrives while the system still runs marks the termination as expected. A stop that
// arrives after it terminated is the host reacting to Akka.Hosting's StopApplication — and may even
// beat this watchdog's own continuation, so it must not flip that continuation's verdict.
if (!system.WhenTerminated.IsCompleted)
{
_stopRequested = true;
return;
}
try
{
if (await _verdict.Task.WaitAsync(cancellationToken).ConfigureAwait(false))
await _exitIssued.Task.WaitAsync(cancellationToken).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
// Shutdown timeout: let the host finish rather than hang it.
}
}
}
/// <summary>Registration for <see cref="ActorSystemTerminationWatchdog"/> — shared by <c>Program.cs</c> and its tests.</summary>
public static class ActorSystemTerminationWatchdogRegistration
{
/// <summary>
/// Registers <see cref="ActorSystemTerminationWatchdog"/>. Call it after <c>AddAkka</c> so it starts after
/// Akka's hosted service has built the <see cref="ActorSystem"/> (resolved lazily, in <c>StartAsync</c>).
/// </summary>
/// <param name="services">The service collection.</param>
/// <param name="exitProcess">Test seam; defaults to <see cref="Environment.Exit"/>.</param>
/// <param name="flushLogs">Test seam; defaults to <c>Serilog.Log.CloseAndFlush</c>.</param>
/// <returns>The same collection.</returns>
public static IServiceCollection AddOtOpcUaTerminationWatchdog(
this IServiceCollection services, Action<int>? exitProcess = null, Action? flushLogs = null)
{
ArgumentNullException.ThrowIfNull(services);
services.AddHostedService(sp => new ActorSystemTerminationWatchdog(
() => sp.GetRequiredService<ActorSystem>(),
sp.GetRequiredService<IHostApplicationLifetime>(),
sp.GetRequiredService<ILogger<ActorSystemTerminationWatchdog>>(),
exitProcess,
flushLogs));
return services;
}
}
+7 -9
View File
@@ -566,8 +566,9 @@ builder.Services.AddAkka("otopcua", (ab, sp) =>
// (WebApplication starts the server last), and Kestrel drains open requests for up to ShutdownTimeout,
// so without this the peer's long-lived LocalDb sync stream held the Primary role for ~30 s on every
// planned stop. Its StoppingAsync runs before ANY hosted service's StopAsync. Registered BEFORE the
// watchdog below only for readability — it raises ApplicationStopping itself, which is what keeps the
// watchdog quiet, so it does not depend on lifecycle-callback order.
// watchdog below only for readability — it raises ApplicationStopping while the ActorSystem is still
// running and runs CoordinatedShutdown with ClrExitReason, either of which keeps the watchdog quiet, so
// it does not depend on lifecycle-callback order.
builder.Services.AddOtOpcUaGracefulClusterLeave();
// Simultaneous-cold-start split-brain guard (dark switch Cluster:BootstrapGuard:Enabled, default off).
@@ -582,13 +583,10 @@ builder.Services.AddHostedService(sp => new ClusterBootstrapCoordinator(
// Down-if-alone recovery watchdog. Registered AFTER AddAkka so it starts after Akka's own
// hosted service has built the ActorSystem; it resolves the system lazily (never at construction) so
// it can't race startup. On an unexpected SBR self-down it stops the host so the service supervisor
// (sc.exe failure / docker restart: unless-stopped) restarts this node — the 2-node keep-oldest
// exit-and-rejoin recovery path.
builder.Services.AddHostedService(sp => new ActorSystemTerminationWatchdog(
() => sp.GetRequiredService<ActorSystem>(),
sp.GetRequiredService<IHostApplicationLifetime>(),
sp.GetRequiredService<ILogger<ActorSystemTerminationWatchdog>>()));
// it can't race startup. When the ActorSystem terminates for anything but a host stop (cluster leave from
// manual failover / endpoint step-down, auto-down) it exits the process with code 1 so the service
// supervisor (sc.exe failure / docker restart: unless-stopped) restarts this node (#980).
builder.Services.AddOtOpcUaTerminationWatchdog();
if (hasAdmin)
{