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:
+56
-9
@@ -24,10 +24,17 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Historian.Gateway;
|
||||
/// was not committed, so the re-send cannot duplicate it. A whole-call failure:
|
||||
/// </para>
|
||||
/// <list type="bullet">
|
||||
/// <item>transient / systemic (<c>Unavailable</c>, auth, back-pressure, deadline, cancellation) ⇒ that call's and
|
||||
/// every later call's events are <see cref="HistorianWriteOutcome.RetryPlease"/>, nothing more is sent (every
|
||||
/// later call would hit it too). Events before the fault may already be committed, so the retry can duplicate
|
||||
/// them — <c>SendEvent</c> is at-least-once too;</item>
|
||||
/// <item>a KNOWN outage (<see cref="IsSystemicFailure"/>: <c>Unavailable</c>, auth, back-pressure, deadline,
|
||||
/// <c>Cancelled</c>, <c>Aborted</c>, or a status-less transport fault) ⇒ that call's and every later call's
|
||||
/// events are <see cref="HistorianWriteOutcome.RetryPlease"/>, nothing more is sent (every later call would hit it
|
||||
/// too). Events before the fault may already be committed, so the retry can duplicate them — <c>SendEvent</c> is
|
||||
/// at-least-once too;</item>
|
||||
/// <item>any other retryable failure (<c>Unknown</c> — the gateway's handler threw — <c>Internal</c>,
|
||||
/// <c>DataLoss</c>, unlisted codes, a non-transport exception) ⇒ the chunk is re-sent event by event at once
|
||||
/// (#976 review), because it may be one event's fault: its siblings Ack and the culprit keeps its RetryPlease,
|
||||
/// which the sink counts toward <c>MaxAttempts</c> on that Ack'd drain and dead-letters alone. If NO single send
|
||||
/// Acks, it was not the event: later chunks are RetryPlease as for an outage (so such an outage costs at most one
|
||||
/// chunk of single sends per drain);</item>
|
||||
/// <item><c>Unimplemented</c> (a gateway older than the RPC) ⇒ the writer stops trying batches for its lifetime and
|
||||
/// sends every event individually;</item>
|
||||
/// <item>any other refusal (<c>InvalidArgument</c> — a poison event or an over-limit batch, nothing sent — and the
|
||||
@@ -50,8 +57,10 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Historian.Gateway;
|
||||
/// (a dropped channel's <see cref="IOException"/> / <see cref="HttpRequestException"/>, a disposed channel, a
|
||||
/// client exception with no inner status, an internal timeout's <see cref="OperationCanceledException"/>). The
|
||||
/// default used to be PermanentFail, which dead-lettered a whole drained batch on a gateway restart. A poison event
|
||||
/// the classifier cannot recognise is still bounded: the store-and-forward sink counts a RetryPlease against
|
||||
/// <c>MaxAttempts</c> whenever the same drain proves the historian reachable (another event Ack'd).
|
||||
/// the classifier cannot recognise is still bounded: the batch path isolates it (above), and the store-and-forward
|
||||
/// sink counts a RetryPlease against <c>MaxAttempts</c> whenever the same drain proves the historian reachable
|
||||
/// (another event Ack'd). Residual: a first chunk in which EVERY event fails that way Acks nothing and stops the
|
||||
/// batch, so that drain is indistinguishable from an outage and is not counted.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public sealed class GatewayAlarmHistorianWriter : IAlarmHistorianWriter, IDisposable
|
||||
@@ -172,9 +181,24 @@ public sealed class GatewayAlarmHistorianWriter : IAlarmHistorianWriter, IDispos
|
||||
}
|
||||
if (Classify(exception) == HistorianWriteOutcome.RetryPlease)
|
||||
{
|
||||
_logger.LogDebug("Alarm SendEvents transiently failed ({Exception}); the batch will retry.", exception.GetType().Name);
|
||||
foreach (var i in indexes) outcomes[i] = HistorianWriteOutcome.RetryPlease;
|
||||
return false;
|
||||
if (IsSystemicFailure(exception))
|
||||
{
|
||||
_logger.LogDebug("Alarm SendEvents transiently failed ({Exception}); the batch will retry.", exception.GetType().Name);
|
||||
foreach (var i in indexes) outcomes[i] = HistorianWriteOutcome.RetryPlease;
|
||||
return false;
|
||||
}
|
||||
|
||||
// #976 review: a RetryPlease the writer cannot vouch for as an outage (Unknown — the gateway handler threw —
|
||||
// Internal, DataLoss, an unlisted code, a non-transport client exception) may be ONE event's fault. Retrying
|
||||
// the whole chunk tied every sibling to it, and the sink counts a RetryPlease only on a drain with an Ack, so
|
||||
// one such event at the queue head stalled all Gateway alarm history until capacity eviction. Re-send the
|
||||
// chunk's events singly NOW: the siblings Ack, the culprit keeps its RetryPlease and the sink dead-letters it
|
||||
// alone via MaxAttempts. If not one single Acks it was not the event — treat it as systemic after all.
|
||||
_logger.LogDebug(
|
||||
"Alarm SendEvents failed with an unrecognised error ({Exception}); isolating the chunk's {Count} event(s).",
|
||||
exception.GetType().Name, indexes.Count);
|
||||
await SendSinglesAsync(batch, indexes, outcomes, cancellationToken).ConfigureAwait(false);
|
||||
return indexes.Any(i => outcomes[i] == HistorianWriteOutcome.Ack);
|
||||
}
|
||||
// Refused up front (a poison event, an over-limit batch, …): nothing was sent — send them one by one so a poison
|
||||
// event dead-letters alone and its siblings still land.
|
||||
@@ -241,6 +265,29 @@ public sealed class GatewayAlarmHistorianWriter : IAlarmHistorianWriter, IDispos
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Whether a RetryPlease-class failure is a KNOWN outage of the whole gateway path (so re-sending event by event would
|
||||
/// only multiply the round trips): the transient / back-pressure / auth / deadline / server-cancellation codes, and a
|
||||
/// status-less failure whose chain holds a transport fault (socket, I/O, HTTP, a disposed channel, a timeout or an
|
||||
/// internal cancellation). Everything else — <c>Unknown</c>, <c>Internal</c>, <c>DataLoss</c>, unlisted codes, a
|
||||
/// client exception with no status and no transport cause, any other exception — is unrecognised and gets the chunk
|
||||
/// isolated per event.
|
||||
/// </summary>
|
||||
internal static bool IsSystemicFailure(Exception exception)
|
||||
{
|
||||
if (StatusOf(exception) is { } code)
|
||||
return code is StatusCode.Unavailable or StatusCode.DeadlineExceeded or StatusCode.Cancelled
|
||||
or StatusCode.ResourceExhausted or StatusCode.Aborted or StatusCode.Unauthenticated
|
||||
or StatusCode.PermissionDenied;
|
||||
for (Exception? e = exception; e is not null; e = e.InnerException)
|
||||
if (e is HistorianGatewayUnavailableException or HistorianGatewayAuthenticationException
|
||||
or HistorianGatewayAuthorizationException
|
||||
or IOException or System.Net.Sockets.SocketException or HttpRequestException or ObjectDisposedException
|
||||
or OperationCanceledException or TimeoutException)
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>Maps an event to the wire; a mapping failure is poison (logged, never thrown).</summary>
|
||||
private bool TryMap(AlarmHistorianEvent evt, out HistorianEvent mapped)
|
||||
{
|
||||
|
||||
@@ -18,7 +18,10 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Historian.Sql.Common;
|
||||
/// unrecognised error, lmxopcua#976 G-16) is ALSO re-sent one event at a time: retrying the whole chunk tied
|
||||
/// every sibling to one poison event, and since the store-and-forward sink counts a RetryPlease only when the
|
||||
/// same drain proves the historian reachable, a chunk that never lands would otherwise pin the queue head. The
|
||||
/// poison event keeps its RetryPlease and the sink dead-letters it alone once its siblings keep landing;</item>
|
||||
/// poison event keeps its RetryPlease and the sink dead-letters it alone once its siblings keep landing. Isolation
|
||||
/// stops at the first single that fails with a KNOWN transient error (the outage began, or the chunk failure
|
||||
/// was one the caller's <c>isTransient</c> missed): the chunk's remaining events are RetryPlease, so an outage
|
||||
/// costs at most one extra round trip per chunk rather than one per event (#976 review);</item>
|
||||
/// <item>a cancellation of the caller's token makes every event not yet decided RetryPlease (never a dead letter).</item>
|
||||
/// </list>
|
||||
/// </summary>
|
||||
@@ -60,12 +63,19 @@ public static class AlarmBatchWrite
|
||||
for (var start = 0; start < pending.Count; start += chunkSize)
|
||||
{
|
||||
var chunk = pending.GetRange(start, Math.Min(chunkSize, pending.Count - start));
|
||||
var (outcome, isolate) = await TryAsync(chunk).ConfigureAwait(false);
|
||||
var (outcome, isolate, _) = await TryAsync(chunk).ConfigureAwait(false);
|
||||
if (isolate && chunk.Count > 1)
|
||||
{
|
||||
// Isolate the poison event: one statement per event, so the siblings still land.
|
||||
// Isolate the poison event: one statement per event, so the siblings still land. A single that fails with a
|
||||
// KNOWN outage error ends the isolation: the rest of the chunk is RetryPlease rather than a round trip each
|
||||
// into the same outage (#976 review).
|
||||
foreach (var index in chunk)
|
||||
outcomes[index] = (await TryAsync([index]).ConfigureAwait(false)).Outcome;
|
||||
{
|
||||
var single = await TryAsync([index]).ConfigureAwait(false);
|
||||
outcomes[index] = single.Outcome;
|
||||
if (single.Outage) break;
|
||||
}
|
||||
foreach (var index in chunk) outcomes[index] ??= HistorianWriteOutcome.RetryPlease;
|
||||
continue;
|
||||
}
|
||||
foreach (var index in chunk) outcomes[index] ??= outcome;
|
||||
@@ -76,23 +86,25 @@ public static class AlarmBatchWrite
|
||||
return result;
|
||||
|
||||
// Isolate = the failure is not a known outage: a PermanentFail, or a RetryPlease the caller cannot vouch for.
|
||||
async Task<(HistorianWriteOutcome Outcome, bool Isolate)> TryAsync(IReadOnlyList<int> indexes)
|
||||
// Outage = a known outage-class error (or a shutdown): stop sending into it.
|
||||
async Task<(HistorianWriteOutcome Outcome, bool Isolate, bool Outage)> TryAsync(IReadOnlyList<int> indexes)
|
||||
{
|
||||
if (ct.IsCancellationRequested) return (HistorianWriteOutcome.RetryPlease, false);
|
||||
if (ct.IsCancellationRequested) return (HistorianWriteOutcome.RetryPlease, false, true);
|
||||
try
|
||||
{
|
||||
await writeChunk(indexes, ct).ConfigureAwait(false);
|
||||
return (HistorianWriteOutcome.Ack, false);
|
||||
return (HistorianWriteOutcome.Ack, false, false);
|
||||
}
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||||
{
|
||||
return (HistorianWriteOutcome.RetryPlease, false); // shutdown: never a dead letter
|
||||
return (HistorianWriteOutcome.RetryPlease, false, true); // shutdown: never a dead letter
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var o = classify(ex);
|
||||
onFailure?.Invoke(ex, o);
|
||||
return (o, o == HistorianWriteOutcome.PermanentFail || (o == HistorianWriteOutcome.RetryPlease && !isTransient(ex)));
|
||||
var outage = o == HistorianWriteOutcome.RetryPlease && isTransient(ex);
|
||||
return (o, o == HistorianWriteOutcome.PermanentFail || (o == HistorianWriteOutcome.RetryPlease && !outage), outage);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -122,6 +122,34 @@ internal sealed class SqlHistorianConnection
|
||||
return Array.IndexOf(TransientNumbers, sql.Number) >= 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Connection-level failures that affect every statement alike — login failed (18456/18452), the server not found /
|
||||
/// unreachable / refusing connections (2, 40, 53, 64, 121, 10061, 10065, -1), a fatal error that closes the connection
|
||||
/// (severity ≥ 20), and an exhausted connection pool — none of which can be one event's fault. Not "transient" for a
|
||||
/// retry loop (a bad password never heals by retrying), so <see cref="IsTransient"/> leaves them out.
|
||||
/// </summary>
|
||||
private static readonly int[] OutageNumbers = [18456, 18452, 2, 40, 53, 64, 121, 10061, 10065, -1];
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="IsTransient"/> plus the connection-level failures in <see cref="OutageNumbers"/>: what the alarm batch
|
||||
/// write treats as an outage, so a chunk failing with one is retried whole rather than re-sent one statement per
|
||||
/// event (#976 review — a login failure used to cost 150 round trips per chunk).
|
||||
/// </summary>
|
||||
/// <param name="ex">Exception from a SQL call.</param>
|
||||
/// <returns>Whether the failure is an outage of the whole connection path.</returns>
|
||||
public static bool IsOutage(Exception ex)
|
||||
{
|
||||
if (IsTransient(ex)) return true;
|
||||
// SqlClient's pool timeout: "Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool."
|
||||
if (ex is InvalidOperationException ioe && ioe.Message.Contains("connection from the pool", StringComparison.OrdinalIgnoreCase))
|
||||
return true;
|
||||
if (ex is not SqlException sql) return false;
|
||||
if (sql.Class >= 20) return true;
|
||||
foreach (SqlError e in sql.Errors)
|
||||
if (e.Class >= 20 || Array.IndexOf(OutageNumbers, e.Number) >= 0) return true;
|
||||
return Array.IndexOf(OutageNumbers, sql.Number) >= 0;
|
||||
}
|
||||
|
||||
/// <summary>True when <paramref name="ex"/> is a unique-key violation (2627/2601): "already present".</summary>
|
||||
/// <param name="ex">Exception from a SQL call.</param>
|
||||
/// <returns>Whether it is a duplicate-key error.</returns>
|
||||
|
||||
+1
-1
@@ -71,7 +71,7 @@ internal sealed class SqlServerAlarmHistorianWriter : IAlarmHistorianWriter
|
||||
var written = await AlarmBatchWrite.RunAsync(slots, ChunkRows,
|
||||
(indexes, ct) => WriteChunkAsync(batch, ids, indexes, ct),
|
||||
ClassifyChunk,
|
||||
SqlHistorianConnection.IsTransient,
|
||||
SqlHistorianConnection.IsOutage,
|
||||
(ex, outcome) => _log.LogWarning("SQL alarm event write failed ({Exception}); outcome {Outcome}.", ex.GetType().Name, outcome),
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
for (var i = 0; i < batch.Count; i++) outcomes[i] = written[representative[ids[i]]];
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
{
|
||||
|
||||
Reference in New Issue
Block a user