fix(alarms): AdminUI /alerts ack/shelve reports the scripted engine's verdict (#950)
The /alerts buttons went central->node fire-and-forget and always showed "Ack sent". AdminOperationsActor now spawns a per-request AlarmCommandVerdictCollector (7 s window, under the client's 10 s ask) that sends the command with AlarmCommand.VerdictRequested and gathers each node's answer, finishing early once every node it sent to has answered. - gRPC plane: CentralCommunicationActor tells the collector the dialled ClusterNode set and one verdict per node. A node handles a verdict_requested AlarmCommandMessage by asking its driver host (ScriptedAlarmHostActor.ExecuteAlarmCommand, the #937 path, no ask deadline, bounded 5 s) and returns it in the ADDITIVE ExecuteAck.alarm_verdict. Transport failure / timeout / empty ack (pre-#950 node) => that node unknown. - DPS: published with the collector as sender; each ScriptedAlarmHostActor answers (non-owners NotOwned); expected set = Up driver members. - Aggregation: any owner applied => Applied (partial noted); else any unknown/silent node => Outcome unknown (never "refused"); else owner refusal => Refused: <reason>; else no owner => Not applied. - UI: green Applied / red Refused (reason) / amber Outcome unknown, per-node detail in the details pane; a verdict-less reply (validation, server fault, pre-#950 singleton) renders as before. Wire is back-compatible both ways (new proto fields only; VerdictRequested and NotOwned default false). Real-wire test through the real router, dialer, interceptor and NodeCommandGrpcService (red without the node change). Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,310 @@
|
||||
using System.Text;
|
||||
using Akka.Actor;
|
||||
using Akka.Cluster.Tools.PublishSubscribe;
|
||||
using Akka.Event;
|
||||
using ZB.MOM.WW.OtOpcUa.Cluster;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Mesh;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.ControlPlane.AdminOperations;
|
||||
|
||||
/// <summary>
|
||||
/// #950: router → collector. Which nodes an AdminUI alarm command went to — the set the
|
||||
/// <see cref="AlarmCommandVerdictCollector"/> waits on.
|
||||
/// </summary>
|
||||
/// <param name="Nodes">
|
||||
/// The nodes expected to answer (gRPC: the dialled <c>ClusterNode</c> ids; DistributedPubSub: the Up <c>driver</c>
|
||||
/// members' <c>host:port</c>). Empty with a null <paramref name="NotDeliveredReason"/> ⇒ the set is unknown and the
|
||||
/// collector waits out its window.
|
||||
/// </param>
|
||||
/// <param name="NotDeliveredReason">Set when the command reached no node at all (no targets, no dialer, unencodable).</param>
|
||||
public sealed record AlarmVerdictFanOut(IReadOnlyList<string> Nodes, string? NotDeliveredReason = null);
|
||||
|
||||
/// <summary>#950: one node's answer to an AdminUI alarm command, as the gRPC router saw it.</summary>
|
||||
/// <param name="Node">The node (its <c>ClusterNode</c> id).</param>
|
||||
/// <param name="Outcome">Its verdict; transport failures and pre-#950 nodes arrive as <see cref="AlarmCommandVerdict.OutcomeUnknown"/>.</param>
|
||||
public sealed record AlarmNodeVerdict(string Node, AlarmCommandOutcome Outcome);
|
||||
|
||||
/// <summary>#950: the fleet-wide verdict on one AdminUI alarm command.</summary>
|
||||
/// <param name="Verdict">Applied when any owning node applied it; OutcomeUnknown when none did but one may have; else NotApplied.</param>
|
||||
/// <param name="Summary">Short operator-facing text (the <c>/alerts</c> result chip).</param>
|
||||
/// <param name="Detail">Per-node breakdown (the result's details pane).</param>
|
||||
public sealed record AlarmCommandFleetOutcome(AlarmCommandVerdict Verdict, string Summary, string Detail);
|
||||
|
||||
/// <summary>
|
||||
/// #950: folds the per-node answers to one AdminUI alarm command into the verdict the operator sees.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// Every driver node receives the command and only the alarm's owners act — two in a redundant pair, each with its
|
||||
/// own engine (the condition state is then replicated last-writer-wins). So: <b>any owner applied ⇒ Applied</b>
|
||||
/// (other owners' refusals/unknowns are listed, and the summary says it was partial); otherwise <b>any unknown — an
|
||||
/// owner that timed out, a node that did not answer, a transport failure, a pre-#950 node — ⇒ OutcomeUnknown</b>,
|
||||
/// never "refused", because that node may still apply it; otherwise an owner's refusal ⇒ NotApplied with its
|
||||
/// reason; otherwise no node owns the alarm ⇒ NotApplied.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public static class AlarmCommandVerdictAggregator
|
||||
{
|
||||
/// <summary>Aggregates the answers.</summary>
|
||||
/// <param name="answers">Node → its verdict (non-owners carry <see cref="AlarmCommandOutcome.NotOwned"/>).</param>
|
||||
/// <param name="unanswered">Expected nodes that did not answer within the window.</param>
|
||||
/// <param name="expectedKnown">Whether the set of nodes the command reached is known (false ⇒ silence may hide an owner).</param>
|
||||
/// <param name="notDeliveredReason">Set when the command reached no node at all.</param>
|
||||
/// <param name="window">The collection window, for the "no answer" text.</param>
|
||||
/// <returns>The fleet verdict.</returns>
|
||||
public static AlarmCommandFleetOutcome Aggregate(
|
||||
IReadOnlyDictionary<string, AlarmCommandOutcome> answers,
|
||||
IReadOnlyCollection<string> unanswered,
|
||||
bool expectedKnown,
|
||||
string? notDeliveredReason,
|
||||
TimeSpan window)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(answers);
|
||||
ArgumentNullException.ThrowIfNull(unanswered);
|
||||
|
||||
if (notDeliveredReason is not null && answers.Count == 0)
|
||||
return new AlarmCommandFleetOutcome(AlarmCommandVerdict.NotApplied, "Not delivered",
|
||||
$"The command was not delivered to any server, so nothing applied it: {notDeliveredReason}");
|
||||
|
||||
var applied = answers.Count(a => a.Value.Verdict == AlarmCommandVerdict.Applied);
|
||||
var refused = answers.Where(a => a.Value is { Verdict: AlarmCommandVerdict.NotApplied, NotOwned: false })
|
||||
.OrderBy(a => a.Key, StringComparer.Ordinal).ToList();
|
||||
var unknown = answers.Count(a => a.Value.Verdict == AlarmCommandVerdict.OutcomeUnknown) + unanswered.Count;
|
||||
|
||||
AlarmCommandVerdict verdict;
|
||||
string summary;
|
||||
if (applied > 0)
|
||||
{
|
||||
verdict = AlarmCommandVerdict.Applied;
|
||||
summary = refused.Count + unknown == 0
|
||||
? "Applied"
|
||||
: $"Applied on {applied} of {applied + refused.Count + unknown} servers";
|
||||
}
|
||||
else if (unknown > 0)
|
||||
{
|
||||
verdict = AlarmCommandVerdict.OutcomeUnknown;
|
||||
summary = "Outcome unknown";
|
||||
}
|
||||
else if (refused.Count > 0)
|
||||
{
|
||||
verdict = AlarmCommandVerdict.NotApplied;
|
||||
summary = "Refused: " + (refused[0].Value.Reason ?? "the alarm engine did not apply the command.");
|
||||
}
|
||||
else if (!expectedKnown)
|
||||
{
|
||||
// Silence from a node we could not enumerate may be an owner that did not answer (a pre-#950 node).
|
||||
verdict = AlarmCommandVerdict.OutcomeUnknown;
|
||||
summary = "Outcome unknown";
|
||||
}
|
||||
else
|
||||
{
|
||||
verdict = AlarmCommandVerdict.NotApplied;
|
||||
summary = "Not applied: no server owns this alarm";
|
||||
}
|
||||
|
||||
var detail = new StringBuilder(verdict switch
|
||||
{
|
||||
AlarmCommandVerdict.Applied => "The alarm engine applied the command.",
|
||||
AlarmCommandVerdict.OutcomeUnknown =>
|
||||
"No server confirmed the command and at least one did not give a definite answer — it may still apply. "
|
||||
+ "Check the alarm's state before retrying.",
|
||||
_ => "The command was not applied anywhere.",
|
||||
});
|
||||
foreach (var (node, outcome) in answers.OrderBy(a => a.Key, StringComparer.Ordinal))
|
||||
detail.AppendLine().Append(node).Append(": ").Append(Describe(outcome));
|
||||
foreach (var node in unanswered.OrderBy(n => n, StringComparer.Ordinal))
|
||||
detail.AppendLine().Append(node).Append($": no answer within {window.TotalSeconds:0.#} s — outcome unknown.");
|
||||
if (answers.Count == 0 && unanswered.Count == 0)
|
||||
detail.AppendLine().Append($"No server answered within {window.TotalSeconds:0.#} s.");
|
||||
if (notDeliveredReason is not null)
|
||||
detail.AppendLine().Append("Delivery: ").Append(notDeliveredReason);
|
||||
|
||||
return new AlarmCommandFleetOutcome(verdict, summary, detail.ToString());
|
||||
}
|
||||
|
||||
private static string Describe(AlarmCommandOutcome outcome) => outcome switch
|
||||
{
|
||||
{ Verdict: AlarmCommandVerdict.Applied } => "applied.",
|
||||
{ Verdict: AlarmCommandVerdict.NotApplied, NotOwned: true } => "does not own this alarm.",
|
||||
{ Verdict: AlarmCommandVerdict.NotApplied } => "refused — " + (outcome.Reason ?? "no reason given."),
|
||||
_ => "outcome unknown — " + (outcome.Reason ?? "no reason given."),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// #950: the DistributedPubSub leg of an AdminUI alarm command that wants verdicts — used by the router under
|
||||
/// <c>MeshTransport:Mode = Dps</c> and by <see cref="AdminOperationsActor"/> when no router is wired.
|
||||
/// </summary>
|
||||
public static class AlarmVerdictDps
|
||||
{
|
||||
/// <summary>
|
||||
/// Publishes <paramref name="command"/> on <paramref name="topic"/> with <paramref name="collector"/> as the sender
|
||||
/// (DistributedPubSub preserves it, so each node's scripted-alarm host answers the collector) and returns the nodes
|
||||
/// expected to answer: the Up members carrying the <c>driver</c> role, keyed as <see cref="NodeKey"/> keys them.
|
||||
/// </summary>
|
||||
/// <param name="system">The actor system.</param>
|
||||
/// <param name="topic">The DPS topic.</param>
|
||||
/// <param name="command">The command (with <see cref="AlarmCommand.VerdictRequested"/> set).</param>
|
||||
/// <param name="collector">Who the nodes answer.</param>
|
||||
/// <returns>The expected node keys; empty when the membership could not be read.</returns>
|
||||
public static IReadOnlyList<string> Publish(ActorSystem system, string topic, AlarmCommand command, IActorRef collector)
|
||||
{
|
||||
IReadOnlyList<string> expected;
|
||||
try
|
||||
{
|
||||
var cluster = Akka.Cluster.Cluster.Get(system);
|
||||
expected = cluster.State.Members
|
||||
.Where(m => m.Status == Akka.Cluster.MemberStatus.Up && RoleParser.GossipedRolesHave(m.Roles, RoleParser.Driver))
|
||||
.Select(m => NodeKey(m.Address, cluster.SelfAddress))
|
||||
.Distinct(StringComparer.Ordinal)
|
||||
.ToList();
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
expected = [];
|
||||
}
|
||||
|
||||
DistributedPubSub.Get(system).Mediator.Tell(new Publish(topic, command), collector);
|
||||
return expected;
|
||||
}
|
||||
|
||||
/// <summary>The key a DPS-answering node is known by: its <c>host:port</c> (a local-scope address is this node).</summary>
|
||||
/// <param name="address">The member or reply-sender address.</param>
|
||||
/// <param name="self">This node's cluster address, or null when there is no cluster.</param>
|
||||
/// <returns>The key.</returns>
|
||||
public static string NodeKey(Address address, Address? self)
|
||||
{
|
||||
var effective = address.HasGlobalScope || self is null ? address : self;
|
||||
return effective.Host is not null && effective.Port is not null ? effective.HostPort() : effective.ToString();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// #950: one AdminUI alarm command's verdict collection. Sends the command (via the mesh router, or straight onto
|
||||
/// DistributedPubSub when none is wired), gathers each node's answer until every expected node has answered or the
|
||||
/// window closes, and replies the aggregated <see cref="AlarmCommandFleetOutcome"/> (mapped by the caller's
|
||||
/// <c>reply</c>) to the original requester. Stops itself after replying.
|
||||
/// </summary>
|
||||
public sealed class AlarmCommandVerdictCollector : ReceiveActor, IWithTimers
|
||||
{
|
||||
/// <summary>The default collection window — under <c>AdminOperationsClient</c>'s 10 s ask.</summary>
|
||||
public static readonly TimeSpan DefaultWindow = TimeSpan.FromSeconds(7);
|
||||
|
||||
private const string WindowTimerKey = "window";
|
||||
|
||||
private readonly AlarmCommand _command;
|
||||
private readonly IActorRef? _meshRouter;
|
||||
private readonly IActorRef _replyTo;
|
||||
private readonly Func<AlarmCommandFleetOutcome, object> _reply;
|
||||
private readonly TimeSpan _window;
|
||||
private readonly ILoggingAdapter _log = Context.GetLogger();
|
||||
private readonly Dictionary<string, AlarmCommandOutcome> _answers = new(StringComparer.Ordinal);
|
||||
private HashSet<string>? _expected;
|
||||
private string? _notDelivered;
|
||||
private Address? _self;
|
||||
|
||||
/// <summary>Gets or sets the timer scheduler.</summary>
|
||||
public ITimerScheduler Timers { get; set; } = null!;
|
||||
|
||||
/// <summary>Creates the props.</summary>
|
||||
/// <param name="command">The command; <see cref="AlarmCommand.VerdictRequested"/> is forced on.</param>
|
||||
/// <param name="meshRouter">The central comm actor, or null to publish on DistributedPubSub directly.</param>
|
||||
/// <param name="replyTo">The requester.</param>
|
||||
/// <param name="reply">Maps the fleet verdict to the requester's reply message.</param>
|
||||
/// <param name="window">The collection window.</param>
|
||||
/// <returns>The props.</returns>
|
||||
public static Props Props(AlarmCommand command, IActorRef? meshRouter, IActorRef replyTo,
|
||||
Func<AlarmCommandFleetOutcome, object> reply, TimeSpan window) =>
|
||||
Akka.Actor.Props.Create(() => new AlarmCommandVerdictCollector(command, meshRouter, replyTo, reply, window));
|
||||
|
||||
/// <summary>Initializes a new instance of the <see cref="AlarmCommandVerdictCollector"/> class.</summary>
|
||||
/// <param name="command">The command.</param>
|
||||
/// <param name="meshRouter">The router, or null.</param>
|
||||
/// <param name="replyTo">The requester.</param>
|
||||
/// <param name="reply">Maps the verdict to the reply.</param>
|
||||
/// <param name="window">The collection window.</param>
|
||||
public AlarmCommandVerdictCollector(AlarmCommand command, IActorRef? meshRouter, IActorRef replyTo,
|
||||
Func<AlarmCommandFleetOutcome, object> reply, TimeSpan window)
|
||||
{
|
||||
_command = command with { VerdictRequested = true };
|
||||
_meshRouter = meshRouter;
|
||||
_replyTo = replyTo;
|
||||
_reply = reply;
|
||||
_window = window;
|
||||
|
||||
Receive<AlarmVerdictFanOut>(msg =>
|
||||
{
|
||||
_expected = new HashSet<string>(msg.Nodes, StringComparer.Ordinal);
|
||||
_notDelivered = msg.NotDeliveredReason;
|
||||
FinishIfComplete();
|
||||
});
|
||||
Receive<AlarmNodeVerdict>(msg =>
|
||||
{
|
||||
_answers[msg.Node] = msg.Outcome;
|
||||
FinishIfComplete();
|
||||
});
|
||||
// A DistributedPubSub answer straight from a node's ScriptedAlarmHostActor: the node is the sender.
|
||||
Receive<AlarmCommandOutcome>(outcome =>
|
||||
{
|
||||
if (!string.Equals(outcome.AlarmId, _command.AlarmId, StringComparison.Ordinal)) return;
|
||||
_answers[AlarmVerdictDps.NodeKey(Sender.Path.Address, _self)] = outcome;
|
||||
FinishIfComplete();
|
||||
});
|
||||
Receive<WindowClosed>(_ => Finish());
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void PreStart()
|
||||
{
|
||||
try
|
||||
{
|
||||
_self = Akka.Cluster.Cluster.Get(Context.System).SelfAddress;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
_self = null;
|
||||
}
|
||||
|
||||
Timers.StartSingleTimer(WindowTimerKey, WindowClosed.Instance, _window);
|
||||
if (_meshRouter is not null)
|
||||
{
|
||||
_meshRouter.Tell(new MeshCommand(AlarmCommandsTopic.Name, _command, Self));
|
||||
}
|
||||
else
|
||||
{
|
||||
var expected = AlarmVerdictDps.Publish(Context.System, AlarmCommandsTopic.Name, _command, Self);
|
||||
Self.Tell(new AlarmVerdictFanOut(expected));
|
||||
}
|
||||
}
|
||||
|
||||
private void FinishIfComplete()
|
||||
{
|
||||
if (_expected is null) return;
|
||||
if (_notDelivered is not null && _expected.Count == 0)
|
||||
{
|
||||
Finish();
|
||||
return;
|
||||
}
|
||||
|
||||
if (_expected.Count > 0 && _expected.All(_answers.ContainsKey)) Finish();
|
||||
}
|
||||
|
||||
private void Finish()
|
||||
{
|
||||
var expectedKnown = _expected is { Count: > 0 } || _notDelivered is not null;
|
||||
var unanswered = _expected?.Where(n => !_answers.ContainsKey(n)).ToList() ?? [];
|
||||
var outcome = AlarmCommandVerdictAggregator.Aggregate(_answers, unanswered, expectedKnown, _notDelivered, _window);
|
||||
_log.Info("AdminOps: {Operation} for alarm {AlarmId} by {User} → {Outcome}",
|
||||
_command.Operation, _command.AlarmId, _command.User,
|
||||
$"{outcome.Verdict} ({outcome.Summary}; {_answers.Count} answered, {unanswered.Count} silent)");
|
||||
_replyTo.Tell(_reply(outcome));
|
||||
Timers.CancelAll();
|
||||
Context.Stop(Self);
|
||||
}
|
||||
|
||||
private sealed class WindowClosed
|
||||
{
|
||||
public static readonly WindowClosed Instance = new();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user