50a4887d83
# Conflicts: # src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/AdminOperations/AdminOperationsActor.cs
955 lines
53 KiB
C#
955 lines
53 KiB
C#
using Akka.Actor;
|
||
using Akka.Cluster.Tools.PublishSubscribe;
|
||
using Akka.Event;
|
||
using Microsoft.EntityFrameworkCore;
|
||
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Admin;
|
||
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Deploy;
|
||
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Mesh;
|
||
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
|
||
using ZB.MOM.WW.OtOpcUa.Commons.Types;
|
||
using ZB.MOM.WW.OtOpcUa.Configuration;
|
||
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
|
||
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
|
||
using ZB.MOM.WW.OtOpcUa.Configuration.Validation;
|
||
using ZB.MOM.WW.OtOpcUa.ControlPlane.Coordinators;
|
||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||
using ZB.MOM.WW.OtOpcUa.Core.Scripting;
|
||
|
||
namespace ZB.MOM.WW.OtOpcUa.ControlPlane.AdminOperations;
|
||
|
||
/// <summary>
|
||
/// Cluster-singleton admin operations actor. Owns the "snapshot the live-edit state and start
|
||
/// a deployment" workflow plus (eventually) all mutating live-edit ops invoked by the admin UI.
|
||
/// Routed to via <see cref="Commons.Interfaces.IAdminOperationsClient"/> from anywhere in the cluster.
|
||
/// </summary>
|
||
public sealed class AdminOperationsActor : ReceiveActor, IWithTimers
|
||
{
|
||
private readonly IDbContextFactory<OtOpcUaConfigDbContext> _dbFactory;
|
||
private readonly IActorRef _coordinator;
|
||
private readonly IReadOnlyDictionary<string, IDriverProbe> _probesByType;
|
||
private readonly TagConfigValidationMode _tagConfigValidationMode;
|
||
|
||
/// <summary>lmxopcua#971 follow-up: the deploy-time script compile gate; null = not wired, or mode Off.</summary>
|
||
private readonly IDeployScriptChecker? _scriptChecker;
|
||
|
||
private readonly ScriptCompileGateMode _scriptCompileGateMode;
|
||
|
||
private readonly bool _warmScriptGateOnStart;
|
||
|
||
/// <summary>
|
||
/// The coordinator's apply deadline. A <c>Dispatching</c> row with no expected-ack rows that is older
|
||
/// than this is a lost dispatch, closed by the in-flight check (fix round 1 / I7).
|
||
/// </summary>
|
||
private readonly TimeSpan _applyDeadline;
|
||
|
||
/// <summary>
|
||
/// Where central→node commands are handed off (per-cluster mesh), or
|
||
/// <see langword="null"/> to publish on the mediator directly.
|
||
/// </summary>
|
||
private readonly IActorRef? _meshRouter;
|
||
|
||
private readonly ILoggingAdapter _log = Context.GetLogger();
|
||
|
||
/// <summary>#950: how long an <c>/alerts</c> ack/shelve waits for the nodes' verdicts.</summary>
|
||
private readonly TimeSpan _alarmVerdictWindow;
|
||
|
||
/// <summary>#1051: first retry delay of a failed driver-operation audit write (doubles, capped at 30 s).</summary>
|
||
private readonly TimeSpan _driverAuditRetryDelay;
|
||
|
||
/// <summary>Gets or sets the timer scheduler (the #1051 audit-write retry backoff).</summary>
|
||
public ITimerScheduler Timers { get; set; } = null!;
|
||
|
||
/// <summary>Default first retry delay of a failed Restart/Reconnect ConfigEdit audit write (#1051).</summary>
|
||
public static readonly TimeSpan DefaultDriverAuditRetryDelay = TimeSpan.FromSeconds(1);
|
||
|
||
/// <summary>
|
||
/// Attempts (first write + retries) at a Restart/Reconnect ConfigEdit audit row before it is logged and dropped
|
||
/// (#1051): 1 + 2 + 4 + 8 + 16 s of backoff, about half a minute of ConfigDb outage covered.
|
||
/// </summary>
|
||
public const int MaxDriverAuditAttempts = 6;
|
||
|
||
/// <summary>The StartDeployment whose compose is running off-actor, or null. See <see cref="HandleStartDeployment"/>.</summary>
|
||
private StartDeployment? _composeInFlight;
|
||
|
||
/// <summary>Creates actor props for the admin operations actor.</summary>
|
||
/// <param name="dbFactory">Factory for creating config database contexts.</param>
|
||
/// <param name="coordinator">Reference to the deployment coordinator actor.</param>
|
||
/// <param name="probes">Driver probes registered in DI; keyed by DriverType (case-insensitive).</param>
|
||
/// <param name="tagConfigValidationMode">Deploy-gate TagConfig strictness mode (Warn default | Error opt-in).</param>
|
||
/// <param name="meshRouter">
|
||
/// Central comm actor commands are handed to, or <see langword="null"/> to publish on the
|
||
/// DistributedPubSub mediator directly (the behaviour before the per-cluster mesh).
|
||
/// </param>
|
||
/// <param name="applyDeadline">The coordinator's apply deadline; defaults to <see cref="DeployTimings.ApplyDeadline"/> (the coordinator's default source).</param>
|
||
/// <param name="alarmVerdictWindow">#950: how long an <c>/alerts</c> ack/shelve waits for the nodes' verdicts; defaults to <see cref="AlarmCommandVerdictCollector.DefaultWindow"/>.</param>
|
||
/// <param name="scriptChecker">lmxopcua#971 follow-up: the deploy-time script compile gate, or <see langword="null"/> to skip it.</param>
|
||
/// <param name="scriptCompileGateMode">How a refused script is treated (Error default | Warn | Off).</param>
|
||
/// <param name="warmScriptGateOnStart">#1024: when true the checker's cache is warmed in the background as the actor starts (production wiring), so the first deploy after a restart is not a cold Roslyn compile.</param>
|
||
/// <param name="driverAuditRetryDelay">#1051: first retry delay of a failed Restart/Reconnect ConfigEdit audit write; defaults to <see cref="DefaultDriverAuditRetryDelay"/>.</param>
|
||
/// <returns>Props configured to create an AdminOperationsActor.</returns>
|
||
public static Props Props(
|
||
IDbContextFactory<OtOpcUaConfigDbContext> dbFactory,
|
||
IActorRef coordinator,
|
||
IEnumerable<IDriverProbe> probes,
|
||
TagConfigValidationMode tagConfigValidationMode = TagConfigValidationMode.Warn,
|
||
IActorRef? meshRouter = null,
|
||
TimeSpan? applyDeadline = null,
|
||
TimeSpan? alarmVerdictWindow = null,
|
||
IDeployScriptChecker? scriptChecker = null,
|
||
ScriptCompileGateMode scriptCompileGateMode = ScriptCompileGateMode.Error,
|
||
bool warmScriptGateOnStart = false,
|
||
TimeSpan? driverAuditRetryDelay = null) =>
|
||
Akka.Actor.Props.Create(() =>
|
||
new AdminOperationsActor(dbFactory, coordinator, probes, tagConfigValidationMode, meshRouter, applyDeadline,
|
||
alarmVerdictWindow, scriptChecker, scriptCompileGateMode, warmScriptGateOnStart, driverAuditRetryDelay));
|
||
|
||
/// <summary>Initializes a new instance of the AdminOperationsActor.</summary>
|
||
/// <param name="dbFactory">Factory for creating config database contexts.</param>
|
||
/// <param name="coordinator">Reference to the deployment coordinator actor.</param>
|
||
/// <param name="probes">Driver probes registered in DI; keyed by DriverType (case-insensitive).</param>
|
||
/// <param name="tagConfigValidationMode">Deploy-gate TagConfig strictness mode (Warn default | Error opt-in).</param>
|
||
/// <param name="meshRouter">Central comm actor, or <see langword="null"/> for the mediator.</param>
|
||
/// <param name="applyDeadline">The coordinator's apply deadline; defaults to <see cref="DeployTimings.ApplyDeadline"/> (the coordinator's default source).</param>
|
||
/// <param name="alarmVerdictWindow">#950: the <c>/alerts</c> verdict collection window.</param>
|
||
/// <param name="scriptChecker">lmxopcua#971 follow-up: the deploy-time script compile gate, or <see langword="null"/> to skip it.</param>
|
||
/// <param name="scriptCompileGateMode">How a refused script is treated (Error default | Warn | Off).</param>
|
||
/// <param name="warmScriptGateOnStart">#1024: warm the checker's cache in the background on start.</param>
|
||
/// <param name="driverAuditRetryDelay">#1051: first retry delay of a failed driver-operation audit write.</param>
|
||
public AdminOperationsActor(
|
||
IDbContextFactory<OtOpcUaConfigDbContext> dbFactory,
|
||
IActorRef coordinator,
|
||
IEnumerable<IDriverProbe> probes,
|
||
TagConfigValidationMode tagConfigValidationMode = TagConfigValidationMode.Warn,
|
||
IActorRef? meshRouter = null,
|
||
TimeSpan? applyDeadline = null,
|
||
TimeSpan? alarmVerdictWindow = null,
|
||
IDeployScriptChecker? scriptChecker = null,
|
||
ScriptCompileGateMode scriptCompileGateMode = ScriptCompileGateMode.Error,
|
||
bool warmScriptGateOnStart = false,
|
||
TimeSpan? driverAuditRetryDelay = null)
|
||
{
|
||
_warmScriptGateOnStart = warmScriptGateOnStart;
|
||
_driverAuditRetryDelay = driverAuditRetryDelay ?? DefaultDriverAuditRetryDelay;
|
||
_scriptChecker = scriptCompileGateMode == ScriptCompileGateMode.Off ? null : scriptChecker;
|
||
_scriptCompileGateMode = scriptCompileGateMode;
|
||
_alarmVerdictWindow = alarmVerdictWindow ?? AlarmCommandVerdictCollector.DefaultWindow;
|
||
// The same source the coordinator's default reads (ConfigPublishCoordinator.DefaultApplyDeadline IS
|
||
// DeployTimings.ApplyDeadline), so the lost-dispatch closure and the coordinator's own deadline agree.
|
||
_applyDeadline = applyDeadline ?? DeployTimings.ApplyDeadline;
|
||
_dbFactory = dbFactory;
|
||
_coordinator = coordinator;
|
||
_probesByType = probes.ToDictionary(p => p.DriverType, StringComparer.OrdinalIgnoreCase);
|
||
_tagConfigValidationMode = tagConfigValidationMode;
|
||
_meshRouter = meshRouter;
|
||
|
||
// Synchronous receives: the compose and the probe run off-actor and come back as messages, so
|
||
// the mailbox is never suspended for the length of a DB snapshot or a PLC connect timeout.
|
||
Receive<StartDeployment>(HandleStartDeployment);
|
||
Receive<DeployComposed>(HandleDeployComposed);
|
||
Receive<DeployComposeFailed>(HandleDeployComposeFailed);
|
||
Receive<TestDriverConnect>(HandleTestDriverConnect);
|
||
Receive<RestartDriver>(HandleRestartDriver);
|
||
Receive<ReconnectDriver>(HandleReconnectDriver);
|
||
Receive<DriverOperationAuditFailed>(HandleDriverOperationAuditFailed);
|
||
Receive<RetryDriverOperationAudit>(m => StartDriverOperationAudit(m.Audit));
|
||
Receive<AcknowledgeAlarmCommand>(HandleAcknowledgeAlarm);
|
||
Receive<ShelveAlarmCommand>(HandleShelveAlarm);
|
||
}
|
||
|
||
/// <summary>
|
||
/// #1024: warms the script compile gate's cache off the actor thread as the singleton starts (and on every
|
||
/// failover re-spawn), so the FIRST deploy after a central restart is not a cold Roslyn compile of the whole
|
||
/// fleet's scripts racing the AdminUI's ask timeout. Fire-and-forget; the warm-up is best-effort and a
|
||
/// concurrent deploy shares the in-flight compiles (the checker's per-key lazy).
|
||
/// </summary>
|
||
protected override void PreStart()
|
||
{
|
||
base.PreStart();
|
||
if (_warmScriptGateOnStart && _scriptChecker is { } checker)
|
||
_ = Task.Run(() => WarmScriptCompileGateAsync(checker));
|
||
}
|
||
|
||
/// <summary>
|
||
/// The reply text for an unexpected server-side failure (R03:4.1): a fixed sentence plus the request's
|
||
/// correlation id, never <c>ex.Message</c> — a SqlException or UriFormatException message carries
|
||
/// connection-string fragments and host names, and the reply reaches any ConfigEditor browser session.
|
||
/// The detail is in the central log under the same correlation id.
|
||
/// </summary>
|
||
/// <param name="operation">The admin operation that failed.</param>
|
||
/// <param name="correlationId">The request's correlation token, as logged alongside the exception.</param>
|
||
/// <returns>The operator-facing message.</returns>
|
||
internal static string ServerFault(string operation, object correlationId) =>
|
||
$"{operation} failed on the server; see the central node log for correlation {correlationId}.";
|
||
|
||
/// <summary>
|
||
/// Hands a central→node command to the mesh transport router, or publishes it directly when
|
||
/// no router is wired.
|
||
/// </summary>
|
||
/// <remarks>
|
||
/// The fallback keeps ~12 existing tests (and any node wired before per-cluster mesh)
|
||
/// on exactly the pre-mesh behaviour. The DistributedPubSub branch behind it is
|
||
/// <b>retained</b>, not scheduled for deletion — an earlier note here promised Phase 6 would
|
||
/// remove it, which was deliberately reversed (<c>docs/Configuration.md</c> § "The compiled
|
||
/// transport-mode defaults were deliberately NOT flipped"): DPS is still the correct and
|
||
/// default transport for a single-mesh topology; gRPC is what crosses a mesh boundary.
|
||
/// </remarks>
|
||
/// <param name="topic">The legacy DistributedPubSub topic.</param>
|
||
/// <param name="message">The command.</param>
|
||
private void Dispatch(string topic, object message)
|
||
{
|
||
if (_meshRouter is not null) _meshRouter.Tell(new MeshCommand(topic, message));
|
||
else DistributedPubSub.Get(Context.System).Mediator.Tell(new Publish(topic, message));
|
||
}
|
||
|
||
/// <summary>
|
||
/// #950: spawns the per-request verdict collector, which sends <paramref name="command"/> (via the mesh router, or
|
||
/// DistributedPubSub when none is wired) and answers <paramref name="replyTo"/> with <paramref name="reply"/>.
|
||
/// </summary>
|
||
private void CollectVerdict(AlarmCommand command, IActorRef replyTo, Func<AlarmCommandFleetOutcome, object> reply) =>
|
||
Context.ActorOf(AlarmCommandVerdictCollector.Props(command, _meshRouter, replyTo, reply, _alarmVerdictWindow));
|
||
|
||
/// <summary>
|
||
/// AdminUI Acknowledge path. Maps the control-plane command to a
|
||
/// <see cref="AlarmCommand"/> (<c>Operation = "Acknowledge"</c>) and hands it to an
|
||
/// <see cref="AlarmCommandVerdictCollector"/>, which sends it to every driver node (the ownership filter on each
|
||
/// node's <c>ScriptedAlarmHostActor</c> decides who acts, so the admin singleton needs no knowledge of placement),
|
||
/// collects each node's verdict within a bounded window and replies Applied / Refused (reason) / Outcome unknown
|
||
/// (#950 — this was a fire-and-forget publish that always answered "sent"). The mailbox is not held: the collector
|
||
/// is a child actor that answers the requester itself.
|
||
/// </summary>
|
||
private void HandleAcknowledgeAlarm(AcknowledgeAlarmCommand msg)
|
||
{
|
||
var replyTo = Sender;
|
||
try
|
||
{
|
||
var alarmCmd = new AlarmCommand(
|
||
AlarmId: msg.AlarmId,
|
||
Operation: "Acknowledge",
|
||
User: msg.User,
|
||
Comment: msg.Comment,
|
||
UnshelveAtUtc: null);
|
||
|
||
var correlationId = msg.CorrelationId;
|
||
CollectVerdict(alarmCmd, replyTo, o => new AcknowledgeAlarmResult(
|
||
o.Verdict == AlarmCommandVerdict.Applied, o.Detail, correlationId, o.Verdict, o.Summary));
|
||
_log.Info("AdminOps: Acknowledge sent for alarm {AlarmId} by {User}; collecting node verdicts", msg.AlarmId, msg.User);
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
_log.Error(ex, "AdminOps: Acknowledge failed for alarm {AlarmId} (correlation {CorrelationId})", msg.AlarmId, msg.CorrelationId);
|
||
replyTo.Tell(new AcknowledgeAlarmResult(false, ServerFault("Acknowledge", msg.CorrelationId), msg.CorrelationId));
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// AdminUI Shelve / Unshelve path. Maps <see cref="ShelveAlarmCommand.Kind"/> to the matching
|
||
/// <see cref="AlarmCommand"/> operation (<c>OneShotShelve</c> / <c>TimedShelve</c> /
|
||
/// <c>Unshelve</c>), threading <see cref="ShelveAlarmCommand.UnshelveAtUtc"/> for the timed kind,
|
||
/// and sends it exactly as <see cref="HandleAcknowledgeAlarm"/> does — ownership filtered on the nodes, verdicts
|
||
/// collected and reported (#950).
|
||
/// </summary>
|
||
private void HandleShelveAlarm(ShelveAlarmCommand msg)
|
||
{
|
||
var replyTo = Sender;
|
||
try
|
||
{
|
||
var (operation, unshelveAt) = msg.Kind switch
|
||
{
|
||
ShelveKind.OneShot => ("OneShotShelve", (DateTime?)null),
|
||
ShelveKind.Timed => ("TimedShelve", msg.UnshelveAtUtc),
|
||
ShelveKind.Unshelve => ("Unshelve", (DateTime?)null),
|
||
_ => throw new ArgumentOutOfRangeException(nameof(msg), msg.Kind, "Unknown shelve kind."),
|
||
};
|
||
|
||
// TimedShelve requires an unshelve instant — the engine rejects it otherwise. Guard here so
|
||
// the AdminUI gets an immediate, attributable failure instead of a silently-dropped command.
|
||
if (msg.Kind == ShelveKind.Timed && unshelveAt is null)
|
||
{
|
||
replyTo.Tell(new ShelveAlarmResult(false, "TimedShelve requires UnshelveAtUtc.", msg.CorrelationId));
|
||
return;
|
||
}
|
||
|
||
var alarmCmd = new AlarmCommand(
|
||
AlarmId: msg.AlarmId,
|
||
Operation: operation,
|
||
User: msg.User,
|
||
Comment: msg.Comment,
|
||
UnshelveAtUtc: unshelveAt);
|
||
|
||
var correlationId = msg.CorrelationId;
|
||
CollectVerdict(alarmCmd, replyTo, o => new ShelveAlarmResult(
|
||
o.Verdict == AlarmCommandVerdict.Applied, o.Detail, correlationId, o.Verdict, o.Summary));
|
||
_log.Info("AdminOps: {Operation} sent for alarm {AlarmId} by {User}; collecting node verdicts", operation, msg.AlarmId, msg.User);
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
_log.Error(ex, "AdminOps: Shelve ({Kind}) failed for alarm {AlarmId} (correlation {CorrelationId})", msg.Kind, msg.AlarmId, msg.CorrelationId);
|
||
replyTo.Tell(new ShelveAlarmResult(false, ServerFault("Shelve", msg.CorrelationId), msg.CorrelationId));
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// <c>StartDeployment</c>. The only serialised part is the actor-local <see cref="_composeInFlight"/>
|
||
/// flag; the DB in-flight check, the snapshot read, validation, gzip and the row write all run on the
|
||
/// thread pool and come back as a <see cref="DeployComposed"/> / <see cref="DeployComposeFailed"/>
|
||
/// message, so a slow or blocked ConfigDb never suspends the mailbox (R03:3.1; fix round 1 moved the
|
||
/// in-flight query off the actor thread too) and alarm acks keep flowing while it runs.
|
||
/// </summary>
|
||
/// <remarks>
|
||
/// <see cref="_composeInFlight"/> is what keeps the check correct once it is off-actor: it is set
|
||
/// BEFORE the off-actor work starts and cleared when the outcome message lands (both branches), so a
|
||
/// second request is refused in memory for the whole check-plus-compose and two artifacts can never
|
||
/// race for one coordinator.
|
||
/// </remarks>
|
||
private void HandleStartDeployment(StartDeployment msg)
|
||
{
|
||
var replyTo = Sender;
|
||
if (_composeInFlight is { } inFlightRequest)
|
||
{
|
||
replyTo.Tell(new StartDeploymentResult(
|
||
StartDeploymentOutcome.AnotherDeploymentInFlight,
|
||
// The in-flight request's pre-allocated id (#949): a caller retrying after an ask timeout
|
||
// learns which deployment is going ahead instead of getting a bare refusal.
|
||
DeploymentId: inFlightRequest.DeploymentId,
|
||
RevisionHash: null,
|
||
Message: $"A deployment requested by {inFlightRequest.CreatedBy} is still being composed.",
|
||
msg.CorrelationId));
|
||
return;
|
||
}
|
||
|
||
_composeInFlight = msg;
|
||
// Captured here: Context/Sender are not available on the thread-pool thread.
|
||
var sourceNode = Akka.Cluster.Cluster.Get(Context.System).SelfAddress.Host ?? "unknown";
|
||
var self = Self;
|
||
// #955: timed from receipt, not from the compose's first line — the thread-pool hand-off and the
|
||
// in-flight check were outside the #949 breakdown, so a stall there would have read as "fast compose".
|
||
var phases = new ComposePhaseTimer();
|
||
Task.Run(async () =>
|
||
{
|
||
phases.Mark("dispatch");
|
||
try
|
||
{
|
||
var refusal = await CheckInFlightAsync(msg).ConfigureAwait(false);
|
||
phases.Mark("in-flight-check");
|
||
if (refusal is not null)
|
||
{
|
||
phases.LogIfSlow(_log, msg, outcome: "refused-in-flight");
|
||
return refusal;
|
||
}
|
||
return await ComposeDeploymentAsync(msg, sourceNode, phases).ConfigureAwait(false);
|
||
}
|
||
catch (Exception)
|
||
{
|
||
phases.LogIfSlow(_log, msg, outcome: "failed");
|
||
throw;
|
||
}
|
||
})
|
||
.PipeTo(self,
|
||
success: composed => new DeployComposed(msg, replyTo, composed.Result, composed.Dispatch),
|
||
failure: ex => new DeployComposeFailed(msg, replyTo, ex));
|
||
}
|
||
|
||
/// <summary>
|
||
/// The DB half of the in-flight check, off the actor thread. Refuses while a deployment is in flight —
|
||
/// keeping the coordinator's state unambiguous — EXCEPT a lost dispatch, which it closes first.
|
||
/// </summary>
|
||
/// <param name="msg">The request.</param>
|
||
/// <returns>The refusal, or null to proceed.</returns>
|
||
/// <remarks>
|
||
/// <para>
|
||
/// <b>Lost dispatch (fix round 1 / I7).</b> A <c>Dispatching</c> row with ZERO
|
||
/// <c>NodeDeploymentState</c> rows was never taken by the coordinator (its <c>HandleDispatch</c>
|
||
/// seeds the expected set and flips the status in one <c>SaveChanges</c>). The coordinator's PreStart
|
||
/// recovers such a row — but only one that already existed when it started. A row committed AFTER
|
||
/// PreStart whose <c>Tell</c> never arrived (this actor died between the compose's commit and
|
||
/// <see cref="HandleDeployComposed"/>) has no owner at all, and refused every later deploy forever.
|
||
/// Once it is past the apply deadline nothing can still be legitimately dispatching it, so it is
|
||
/// closed <c>TimedOut</c> with a reason and the new deploy proceeds. A late <c>DispatchDeployment</c>
|
||
/// for it is ignored by the coordinator's terminal-state guard.
|
||
/// </para>
|
||
/// <para>
|
||
/// One indexed projection (<c>IX_Deployment_Status</c>) plus, only for a Dispatching row past the
|
||
/// deadline, a count and a tracked update.
|
||
/// </para>
|
||
/// </remarks>
|
||
private async Task<ComposeOutcome?> CheckInFlightAsync(StartDeployment msg)
|
||
{
|
||
await using var db = await _dbFactory.CreateDbContextAsync().ConfigureAwait(false);
|
||
var inflight = await db.Deployments
|
||
.AsNoTracking()
|
||
.Where(d => d.Status == DeploymentStatus.Dispatching || d.Status == DeploymentStatus.AwaitingApplyAcks)
|
||
.OrderByDescending(d => d.CreatedAtUtc)
|
||
.Select(d => new { d.DeploymentId, d.Status, d.CreatedAtUtc })
|
||
.ToListAsync()
|
||
.ConfigureAwait(false);
|
||
|
||
foreach (var row in inflight)
|
||
{
|
||
if (row.Status == DeploymentStatus.Dispatching
|
||
&& DateTime.UtcNow - row.CreatedAtUtc > _applyDeadline
|
||
&& !await db.NodeDeploymentStates.AnyAsync(s => s.DeploymentId == row.DeploymentId).ConfigureAwait(false)
|
||
&& await CloseLostDispatchAsync(db, row.DeploymentId).ConfigureAwait(false))
|
||
{
|
||
continue;
|
||
}
|
||
|
||
return new ComposeOutcome(
|
||
new StartDeploymentResult(
|
||
StartDeploymentOutcome.AnotherDeploymentInFlight,
|
||
DeploymentId: new DeploymentId(row.DeploymentId),
|
||
RevisionHash: null,
|
||
Message: $"Deployment {row.DeploymentId:N} is still in flight.",
|
||
msg.CorrelationId),
|
||
Dispatch: null);
|
||
}
|
||
return null;
|
||
}
|
||
|
||
/// <summary>Closes a lost dispatch as TimedOut, unless it moved on meanwhile (optimistic, on its RowVersion).</summary>
|
||
/// <param name="db">The context.</param>
|
||
/// <param name="deploymentId">The row.</param>
|
||
/// <returns><see langword="true"/> when the row is now closed.</returns>
|
||
private async Task<bool> CloseLostDispatchAsync(OtOpcUaConfigDbContext db, Guid deploymentId)
|
||
{
|
||
var stamp = await db.Deployments
|
||
.AsNoTracking()
|
||
.Where(d => d.DeploymentId == deploymentId && d.Status == DeploymentStatus.Dispatching)
|
||
.Select(d => new { d.RowVersion })
|
||
.FirstOrDefaultAsync()
|
||
.ConfigureAwait(false);
|
||
if (stamp is null) return true; // no longer Dispatching — not in flight as far as this check goes
|
||
|
||
// Stub update: the row's ArtifactBlob is never read just to change its status.
|
||
var stub = new Deployment
|
||
{
|
||
DeploymentId = deploymentId, RevisionHash = string.Empty, CreatedBy = string.Empty,
|
||
RowVersion = stamp.RowVersion,
|
||
Status = DeploymentStatus.TimedOut,
|
||
FailureReason =
|
||
"Dispatch was lost before any node was expected to ack (the coordinator was never told, or never " +
|
||
"took it) and the apply deadline has passed; closed by the next StartDeployment. Redeploy.",
|
||
};
|
||
var entry = db.Deployments.Attach(stub);
|
||
entry.Property(d => d.Status).IsModified = true;
|
||
entry.Property(d => d.FailureReason).IsModified = true;
|
||
try
|
||
{
|
||
await db.SaveChangesAsync().ConfigureAwait(false);
|
||
}
|
||
catch (DbUpdateConcurrencyException)
|
||
{
|
||
// The coordinator took it after all (status flipped, RowVersion moved): it is genuinely in flight.
|
||
return false;
|
||
}
|
||
_log.Warning(
|
||
"StartDeployment: closed lost dispatch {DeploymentId} as TimedOut — Dispatching with no expected-ack rows " +
|
||
"past the {Deadline} apply deadline (the coordinator never took it)", deploymentId, _applyDeadline);
|
||
return true;
|
||
}
|
||
|
||
private void HandleDeployComposed(DeployComposed msg)
|
||
{
|
||
_composeInFlight = null;
|
||
// The row is committed (the compose task completed), so the coordinator can be told now; it reads
|
||
// the row back by id when it seeds the expected-ack set.
|
||
if (msg.Dispatch is { } dispatch) _coordinator.Tell(dispatch);
|
||
msg.ReplyTo.Tell(msg.Result);
|
||
}
|
||
|
||
private void HandleDeployComposeFailed(DeployComposeFailed msg)
|
||
{
|
||
_composeInFlight = null;
|
||
_log.Error(msg.Error, "StartDeployment failed for {CreatedBy} (correlation {CorrelationId})", msg.Request.CreatedBy, msg.Request.CorrelationId);
|
||
msg.ReplyTo.Tell(new StartDeploymentResult(
|
||
StartDeploymentOutcome.Rejected,
|
||
DeploymentId: null,
|
||
RevisionHash: null,
|
||
Message: ServerFault("StartDeployment", msg.Request.CorrelationId),
|
||
msg.Request.CorrelationId));
|
||
}
|
||
|
||
/// <summary>
|
||
/// Per-phase wall-clock of one StartDeployment, from the actor's receipt to the commit; logs only when it is
|
||
/// slow (lmxopcua#949, widened by #955 to the thread-pool hand-off and the in-flight check). Used by one
|
||
/// logical flow at a time (sequential awaits), so it needs no locking.
|
||
/// </summary>
|
||
private sealed class ComposePhaseTimer
|
||
{
|
||
/// <summary>A compose slower than this is logged with its phase breakdown (normal ones take 60-630 ms).</summary>
|
||
private static readonly TimeSpan SlowThreshold = TimeSpan.FromSeconds(3);
|
||
|
||
private readonly System.Diagnostics.Stopwatch _total = System.Diagnostics.Stopwatch.StartNew();
|
||
private readonly List<(string Phase, TimeSpan Elapsed)> _phases = new();
|
||
private TimeSpan _last = TimeSpan.Zero;
|
||
|
||
internal void Mark(string phase)
|
||
{
|
||
var now = _total.Elapsed;
|
||
_phases.Add((phase, now - _last));
|
||
_last = now;
|
||
}
|
||
|
||
internal void LogIfSlow(Akka.Event.ILoggingAdapter log, StartDeployment msg, string outcome)
|
||
{
|
||
if (_total.Elapsed < SlowThreshold) return;
|
||
log.Warning(
|
||
"StartDeployment compose was slow ({Total:F1}s, {Outcome}) for {CreatedBy} (correlation {CorrelationId}, deployment {DeploymentId}); phases: {Phases}",
|
||
_total.Elapsed.TotalSeconds, outcome, msg.CreatedBy, msg.CorrelationId, msg.DeploymentId?.ToString() ?? "(unallocated)",
|
||
string.Join(", ", _phases.Select(p => $"{p.Phase}={p.Elapsed.TotalMilliseconds:F0}ms")));
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// Transaction-owned exclusive app lock serialising deploy composes (#955). Waits up to 20 s (inside the
|
||
/// 30 s command timeout), then fails the compose rather than composing concurrently.
|
||
/// </summary>
|
||
public const string ComposeAppLockSql =
|
||
"DECLARE @r int; " +
|
||
"EXEC @r = sp_getapplock @Resource = N'OtOpcUa/DeployCompose', @LockMode = N'Exclusive', @LockOwner = N'Transaction', @LockTimeout = 20000; " +
|
||
"IF @r < 0 THROW 51955, N'Timed out waiting for another deployment compose to release the compose lock.', 1;";
|
||
|
||
/// <summary>Outcome of the off-actor compose: the reply to send, and the dispatch to issue when Accepted.</summary>
|
||
private sealed record ComposeOutcome(StartDeploymentResult Result, DispatchDeployment? Dispatch);
|
||
|
||
private sealed record DeployComposed(
|
||
StartDeployment Request, IActorRef ReplyTo, StartDeploymentResult Result, DispatchDeployment? Dispatch);
|
||
|
||
private sealed record DeployComposeFailed(StartDeployment Request, IActorRef ReplyTo, Exception Error);
|
||
|
||
/// <summary>
|
||
/// The deploy compose, off the actor thread. Touches no actor state: everything it needs is in
|
||
/// <paramref name="msg"/>, <paramref name="sourceNode"/> and the readonly fields captured at
|
||
/// construction (<see cref="_dbFactory"/>, <see cref="_tagConfigValidationMode"/>, <see cref="_log"/> —
|
||
/// Akka's logging adapter is thread-safe).
|
||
/// </summary>
|
||
private async Task<ComposeOutcome> ComposeDeploymentAsync(StartDeployment msg, string sourceNode, ComposePhaseTimer phases)
|
||
{
|
||
// lmxopcua#971 follow-up: warm the script compile gate's cache BEFORE the snapshot transaction + compose app
|
||
// lock, so the Roslyn work does not run while they are held. The authoritative check runs on the snapshot
|
||
// below; with the cache warm it is (almost always) all hits.
|
||
if (_scriptChecker is not null)
|
||
{
|
||
await WarmScriptCompileGateAsync(_scriptChecker).ConfigureAwait(false);
|
||
phases.Mark("script-gate-warm");
|
||
}
|
||
|
||
// lmxopcua#949: phase timings, logged only when the deploy is slow (see ComposePhaseTimer).
|
||
await using var db = await _dbFactory.CreateDbContextAsync();
|
||
// ONE transaction holds the snapshot read, the scope-revision advance and the Deployment row, committed
|
||
// together. It is SNAPSHOT, not SERIALIZABLE (#955): a serializable read range-locked every config table
|
||
// for the whole validate + compose + gzip, so any concurrent writer (an AdminUI save) either waited for
|
||
// the deploy, made the deploy wait for IT, or deadlocked with it — the deploy then stalled ~5 s per
|
||
// deadlock-monitor cycle or failed outright (reproduced: DeployComposeIsolationSqlServerTests). A
|
||
// snapshot read takes no shared locks, so it neither waits on nor blocks an edit; an edit that commits
|
||
// after the snapshot is simply not in this artifact (R03:3.2), and the next deploy carries it.
|
||
await using var transaction = db.Database.IsRelational()
|
||
? await db.Database.BeginTransactionAsync(System.Data.IsolationLevel.Snapshot)
|
||
: null;
|
||
DataConnectionScopeState scopeState;
|
||
if (transaction is not null)
|
||
{
|
||
// Composes are serialised by an app lock taken BEFORE any data is touched: under SNAPSHOT the
|
||
// version clock starts at the first data access, so a compose that queued behind another one
|
||
// reads (and advances) the scope revision that compose committed. Taking the row lock first instead
|
||
// would fail the second compose with an update conflict (3960). The singleton actor already runs
|
||
// one compose at a time; this covers two singletons overlapping across a handover.
|
||
await db.Database.ExecuteSqlRawAsync(ComposeAppLockSql);
|
||
var locked = await db.Database.ExecuteSqlRawAsync("UPDATE DataConnectionScopeState SET ScopeVersion = ScopeVersion WHERE Id = 1");
|
||
if (locked != 1) throw new InvalidOperationException("Authoritative data scope state is unavailable.");
|
||
scopeState = await db.DataConnectionScopeStates.SingleAsync(x => x.Id == 1);
|
||
phases.Mark("snapshot-begin+compose-lock");
|
||
}
|
||
else
|
||
{
|
||
// Nonrelational providers are used by isolated unit fixtures only.
|
||
scopeState = await db.DataConnectionScopeStates.SingleOrDefaultAsync(x => x.Id == 1) ?? new DataConnectionScopeState();
|
||
if (db.Entry(scopeState).State == EntityState.Detached) db.DataConnectionScopeStates.Add(scopeState);
|
||
}
|
||
|
||
// Full pre-seal gate: run the complete DraftValidator (one pass, all rules) and reject
|
||
// on ANY validation error. The config is now canonical — the company overlay loader emits
|
||
// canonical EquipmentIds and the seed is clean — so every rule (UNS segments, EquipmentId
|
||
// derivation, cross-cluster/namespace binding, driver-namespace compat, signal collisions,
|
||
// …) gates the deploy. A green build in this repo does not prove the config is valid; this
|
||
// is the last guard before a bad address space (or a non-derived EquipmentId) ships.
|
||
var draft = await DraftSnapshotFactory.FromConfigDbAsync(db);
|
||
phases.Mark("snapshot-read");
|
||
// The rule pass — DraftValidator, per-cluster topology, TagConfig inspection, the non-blocking Sql / data-
|
||
// connection warnings — is DeployGateRules (shared with the upgrade preflight, lmxopcua#1013/#1015/#1058).
|
||
// R03:3.2: every check runs off this ONE snapshot read.
|
||
var gate = DeployGateRules.Evaluate(draft, _tagConfigValidationMode);
|
||
var errors = gate.Errors.ToList();
|
||
foreach (var w in gate.TagConfigWarnings)
|
||
_log.Warning("StartDeployment: TagConfig warning (Warn mode, non-blocking): {Warning}", w.Message);
|
||
|
||
// lmxopcua#781 item 3: always non-blocking (independent of TagConfigValidationMode) — the Tag
|
||
// entity's Writable flag and the Sql blob's "writable" disagree.
|
||
foreach (var w in gate.SqlWritableWarnings)
|
||
_log.Warning("StartDeployment: Sql writable mismatch (non-blocking): {Warning}", w);
|
||
|
||
// A2b (plan §6): Σ MaxConditions × 49 of a consumer node's alarm mappings over the host cap — non-blocking.
|
||
foreach (var w in gate.DataConnectionWarnings)
|
||
_log.Warning("StartDeployment: data-connection warning (non-blocking): {Warning}", w);
|
||
|
||
phases.Mark("validate");
|
||
|
||
// lmxopcua#971 follow-up — the deploy-time script compile gate: every script the runtime will compile
|
||
// (enabled VirtualTags, enabled scripted-alarm predicates, Calculation tags), {{equip}} resolved exactly as the
|
||
// compose seams resolve it, through the same compile + allow-list analyzer the runtime runs. On the SAME
|
||
// snapshot as everything else (R03:3.2); the warm-up above means this is normally all cache hits.
|
||
var scriptWarnings = new List<string>();
|
||
if (_scriptChecker is not null)
|
||
{
|
||
try
|
||
{
|
||
foreach (var f in DeployScriptGate.Run(_scriptChecker, draft))
|
||
{
|
||
if (_scriptCompileGateMode == ScriptCompileGateMode.Error)
|
||
errors.Add(new ValidationError(DeployScriptGate.ErrorCode, f.Text, f.ScriptId));
|
||
else
|
||
{
|
||
scriptWarnings.Add(f.Text);
|
||
_log.Warning("StartDeployment: script compile warning (Warn mode, non-blocking): {Warning}", f.Text);
|
||
}
|
||
}
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
// An internal checker failure must not block every deploy; the gate is skipped and says so.
|
||
_log.Error(ex, "StartDeployment: script compile gate failed internally; skipped for this deploy (correlation {CorrelationId})", msg.CorrelationId);
|
||
scriptWarnings.Add("script compile gate skipped (internal error; see the central log)");
|
||
}
|
||
phases.Mark("script-gate");
|
||
}
|
||
if (errors.Count > 0)
|
||
{
|
||
phases.LogIfSlow(_log, msg, outcome: "rejected");
|
||
var summary = string.Join("; ", errors.Select(e => $"[{e.Code}] {e.Message}"));
|
||
_log.Warning("StartDeployment rejected ({Count} validation error(s)): {Summary}",
|
||
errors.Count, summary);
|
||
return new ComposeOutcome(
|
||
new StartDeploymentResult(
|
||
StartDeploymentOutcome.Rejected,
|
||
DeploymentId: null,
|
||
RevisionHash: null,
|
||
Message: summary,
|
||
msg.CorrelationId),
|
||
Dispatch: null);
|
||
}
|
||
|
||
// Warn-only compile-cost guardrail (NEVER blocks). Each genuinely-compiled (non-passthrough)
|
||
// script costs ~1.66 MiB RSS per node to materialize via Roslyn (measured post-A0; design doc
|
||
// 2026-06-07). Passthrough "mirror" scripts compile to ~nothing, so they are excluded; distinct
|
||
// sources are counted (the compile cache keys on source, so duplicates collapse to one unit).
|
||
// This only surfaces the estimate to the operator — the DraftValidator gate above is the hard
|
||
// reject; this advisory rides in the Accepted Message so the UI can show it.
|
||
// advisory is declared outside the inner try so the Accepted reply below can still read it even
|
||
// when the guardrail throws. A failed estimate must NEVER block a valid deploy — the caller's
|
||
// failure branch is reserved for genuine seal/save failures.
|
||
string? advisory = null;
|
||
try
|
||
{
|
||
const double PerScriptMiB = 1.66; // measured post-A0 per-script RSS (design doc 2026-06-07)
|
||
// Projected from the snapshot already in hand — Script.SourceCode used to be read three times.
|
||
var compiled = draft.Scripts
|
||
.Select(s => s.SourceCode)
|
||
.Where(src => !PassthroughScript.TryMatch(src, out _))
|
||
.Distinct(StringComparer.Ordinal)
|
||
.Count();
|
||
if (compiled > 0)
|
||
{
|
||
var estMiB = compiled * PerScriptMiB;
|
||
_log.Warning(
|
||
"StartDeployment: {Compiled} script(s) will compile (~{EstMiB:F0} MiB RSS per node); ensure node mem_limit covers it",
|
||
compiled, estMiB);
|
||
advisory = $"{compiled} script(s) will compile (~{estMiB:F0} MiB/node)";
|
||
}
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
// Guardrail is advisory-only — a failed estimate must never block a valid deploy.
|
||
_log.Warning(ex, "StartDeployment: script compile-cost estimate failed; advisory skipped");
|
||
advisory = null;
|
||
}
|
||
|
||
// Composed from the validated snapshot, never from a second read: an edit that lands between
|
||
// validation and here is simply not in this artifact (R03:3.2).
|
||
var scope = DataConnectionScopeRevision.Advance(scopeState.ScopeVersion, scopeState.Fingerprint, draft.DataConnections);
|
||
scopeState.ScopeVersion = scope.Version;
|
||
scopeState.Fingerprint = scope.Fingerprint;
|
||
draft.DataConnectionScopeVersion = scope.Version;
|
||
var artifact = ConfigComposer.Compose(draft);
|
||
phases.Mark("compose");
|
||
var deploymentId = msg.DeploymentId ?? DeploymentId.NewId();
|
||
var revHash = RevisionHash.Parse(artifact.RevisionHash);
|
||
|
||
db.Deployments.Add(new Deployment
|
||
{
|
||
DeploymentId = deploymentId.Value,
|
||
RevisionHash = artifact.RevisionHash,
|
||
Status = DeploymentStatus.Dispatching,
|
||
CreatedBy = msg.CreatedBy,
|
||
ArtifactBlob = artifact.Blob,
|
||
});
|
||
|
||
// Marker ConfigEdit row so the audit timeline shows the deployment snapshot.
|
||
db.ConfigEdits.Add(new ConfigEdit
|
||
{
|
||
EntityType = "Deployment",
|
||
EntityId = deploymentId.Value,
|
||
FieldsJson = $"{{\"revisionHash\":\"{artifact.RevisionHash}\",\"sizeBytes\":{artifact.Blob.Length}}}",
|
||
EditedBy = msg.CreatedBy,
|
||
SourceNode = sourceNode,
|
||
});
|
||
|
||
await db.SaveChangesAsync();
|
||
if (transaction is not null) await transaction.CommitAsync();
|
||
phases.Mark("save+commit");
|
||
phases.LogIfSlow(_log, msg, outcome: "accepted");
|
||
|
||
// Accepted message = the compile-cost advisory (if any) + any Warn-mode TagConfig warnings, so
|
||
// the operator sees the non-blocking strictness findings on a successful deploy.
|
||
var messageParts = new List<string>();
|
||
if (advisory is not null) messageParts.Add(advisory);
|
||
messageParts.AddRange(gate.TagConfigWarnings.Select(x => x.Message));
|
||
messageParts.AddRange(gate.SqlWritableWarnings);
|
||
messageParts.AddRange(scriptWarnings);
|
||
var acceptedMessage = messageParts.Count > 0 ? string.Join("; ", messageParts) : null;
|
||
|
||
return new ComposeOutcome(
|
||
new StartDeploymentResult(
|
||
StartDeploymentOutcome.Accepted,
|
||
deploymentId,
|
||
revHash,
|
||
Message: acceptedMessage,
|
||
msg.CorrelationId),
|
||
new DispatchDeployment(deploymentId, revHash, msg.CorrelationId));
|
||
}
|
||
|
||
/// <summary>
|
||
/// lmxopcua#971 follow-up: warms the script compile gate's cache from the three small script tables (no
|
||
/// Tags read), outside any transaction. Best-effort — a failure here is logged and the authoritative
|
||
/// in-transaction pass does the work instead.
|
||
/// </summary>
|
||
/// <param name="checker">The compile checker.</param>
|
||
private async Task WarmScriptCompileGateAsync(IDeployScriptChecker checker)
|
||
{
|
||
try
|
||
{
|
||
await using var db = await _dbFactory.CreateDbContextAsync().ConfigureAwait(false);
|
||
var scripts = await db.Scripts.AsNoTracking()
|
||
.Select(s => new { s.ScriptId, s.SourceCode })
|
||
.ToListAsync().ConfigureAwait(false);
|
||
if (scripts.Count == 0) return;
|
||
var vtScriptIds = await db.VirtualTags.AsNoTracking().Where(v => v.Enabled)
|
||
.Select(v => v.ScriptId).Distinct().ToListAsync().ConfigureAwait(false);
|
||
var predicateScriptIds = await db.ScriptedAlarms.AsNoTracking().Where(a => a.Enabled)
|
||
.Select(a => a.PredicateScriptId).Distinct().ToListAsync().ConfigureAwait(false);
|
||
checker.Check(DeployScriptGate.WarmRequests(
|
||
scripts.Select(s => (s.ScriptId, s.SourceCode)), vtScriptIds, predicateScriptIds));
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
_log.Warning(ex, "StartDeployment: script compile gate warm-up failed; the in-snapshot check runs cold");
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// Test Connect runs on the thread pool and pipes its reply straight to the requester: a probe
|
||
/// against a black-holed PLC (60 s clamp) must not suspend the singleton's mailbox (R03:3.1). Every
|
||
/// path inside the task yields a <see cref="TestDriverConnectResult"/>, so the requester never
|
||
/// sees a <c>Status.Failure</c>.
|
||
/// </summary>
|
||
private void HandleTestDriverConnect(TestDriverConnect msg)
|
||
{
|
||
var replyTo = Sender;
|
||
if (!_probesByType.TryGetValue(msg.DriverType, out var probe))
|
||
{
|
||
replyTo.Tell(new TestDriverConnectResult(
|
||
false,
|
||
$"No probe registered for driver type '{msg.DriverType}'.",
|
||
null,
|
||
msg.CorrelationId));
|
||
return;
|
||
}
|
||
|
||
// lmxopcua#815: refuse a credential reference outside the driver's namespace BEFORE any probe runs — the
|
||
// probe would otherwise be the seam that resolves it and sends it to the author-chosen endpoint. Nothing
|
||
// is read from the secret store or the environment on this path.
|
||
var credentialProblems = DriverCredentialPolicy.DescribeProblems(msg.DriverType, msg.ConfigJson);
|
||
if (credentialProblems.Count > 0)
|
||
{
|
||
replyTo.Tell(new TestDriverConnectResult(
|
||
false,
|
||
"Test Connect refused: " + string.Join(" ", credentialProblems),
|
||
null,
|
||
msg.CorrelationId));
|
||
return;
|
||
}
|
||
|
||
Task.Run(() => ProbeAsync(probe, msg)).PipeTo(replyTo);
|
||
}
|
||
|
||
private async Task<TestDriverConnectResult> ProbeAsync(IDriverProbe probe, TestDriverConnect msg)
|
||
{
|
||
var clampedSec = Math.Clamp(msg.TimeoutSeconds, 1, 60);
|
||
var timeout = TimeSpan.FromSeconds(clampedSec);
|
||
using var cts = new CancellationTokenSource(timeout);
|
||
|
||
var sw = System.Diagnostics.Stopwatch.StartNew();
|
||
try
|
||
{
|
||
// lmxopcua#835/#849: a reference naming ANOTHER driver instance's secret (secret:galaxy/<other>/…, env:OTOPCUA_GALAXY_<OTHER>_…) is refused
|
||
// before the probe resolves it — off the mailbox, since it reads the ConfigDb (only when the config
|
||
// carries an in-scope secret:/env: reference at all).
|
||
if (DriverCredentialPolicy.HasInstanceSegments(msg.DriverType, msg.ConfigJson))
|
||
{
|
||
await using var db = await _dbFactory.CreateDbContextAsync(cts.Token);
|
||
var instanceProblems = await DriverInstanceIdentities.DescribeProbeProblemsAsync(
|
||
db, msg.DriverType, msg.ConfigJson, msg.DriverInstanceId, cts.Token);
|
||
if (instanceProblems.Count > 0)
|
||
return new TestDriverConnectResult(
|
||
false, "Test Connect refused: " + string.Join(" ", instanceProblems), null, msg.CorrelationId);
|
||
}
|
||
|
||
var result = await probe.ProbeAsync(msg.ConfigJson, timeout, cts.Token);
|
||
sw.Stop();
|
||
return new TestDriverConnectResult(
|
||
result.Ok,
|
||
result.Message,
|
||
result.Ok ? sw.Elapsed.TotalMilliseconds : (double?)null,
|
||
msg.CorrelationId);
|
||
}
|
||
catch (OperationCanceledException)
|
||
{
|
||
return new TestDriverConnectResult(
|
||
false,
|
||
$"Probe timed out after {clampedSec}s.",
|
||
null,
|
||
msg.CorrelationId);
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
_log.Error(ex, "Probe for {DriverType} threw (correlation {CorrelationId})", msg.DriverType, msg.CorrelationId);
|
||
return new TestDriverConnectResult(
|
||
false,
|
||
ServerFault("Test Connect", msg.CorrelationId),
|
||
null,
|
||
msg.CorrelationId);
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// #996 (review H-3): a Restart/Reconnect REPORTS THE DISPATCH, which is what it does. It used to dispatch, then
|
||
/// write the <c>ConfigEdit</c> audit row inside the same <c>try</c> — so a ConfigDb failure answered "failed" for a
|
||
/// command that was already on its way to every node (the operator retried ⇒ a second restart, a second data gap),
|
||
/// and, as a <c>ReceiveAsync</c>, the audit write suspended the whole mailbox (one connect timeout per click
|
||
/// against an unreachable server; alarm acks and deploys queued behind it). Now both are synchronous receives:
|
||
/// dispatch, reply, and write the audit row off-thread; an audit failure is logged (with the full record) and
|
||
/// never changes the operator-visible result.
|
||
/// </summary>
|
||
private void HandleRestartDriver(RestartDriver msg) =>
|
||
DispatchDriverOperation(msg, "restart", msg.DriverInstanceId, msg.ActorByUserName, msg.CorrelationId,
|
||
new RestartDriverResult(true, null, msg.CorrelationId),
|
||
_ => new RestartDriverResult(false, ServerFault("RestartDriver", msg.CorrelationId), msg.CorrelationId));
|
||
|
||
private void HandleReconnectDriver(ReconnectDriver msg) =>
|
||
DispatchDriverOperation(msg, "reconnect", msg.DriverInstanceId, msg.ActorByUserName, msg.CorrelationId,
|
||
new ReconnectDriverResult(true, null, msg.CorrelationId),
|
||
_ => new ReconnectDriverResult(false, ServerFault("ReconnectDriver", msg.CorrelationId), msg.CorrelationId));
|
||
|
||
private void DispatchDriverOperation(
|
||
object command, string op, string driverInstanceId, string actor, object correlationId,
|
||
object success, Func<Exception, object> failure)
|
||
{
|
||
var replyTo = Sender;
|
||
try
|
||
{
|
||
// Broadcast to every DriverHostActor on every node via the driver-control topic. Only the host that owns the
|
||
// instance acts; others ignore it (id not found in _children).
|
||
Dispatch(DriverControlTopic.Name, command);
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
// The ONLY genuine failure: nothing was dispatched.
|
||
_log.Error(ex, "AdminOps: {Op} dispatch failed for {DriverInstanceId} (correlation {CorrelationId})", op, driverInstanceId, correlationId);
|
||
replyTo.Tell(failure(ex));
|
||
return;
|
||
}
|
||
|
||
_log.Info("AdminOps: {Op} dispatched for {DriverInstanceId} by {User}", op, driverInstanceId, actor);
|
||
replyTo.Tell(success);
|
||
|
||
// Audit off the mailbox. Cluster state is read HERE (actor thread); the DB work is a pool-thread task.
|
||
var sourceNode = Akka.Cluster.Cluster.Get(Context.System).SelfAddress.Host ?? "unknown";
|
||
StartDriverOperationAudit(new DriverOperationAudit(op, driverInstanceId, actor, correlationId, sourceNode, Attempt: 1));
|
||
}
|
||
|
||
/// <summary>One attempt at the ConfigEdit row of a dispatched driver operation, on a pool thread (#996 / H-3).</summary>
|
||
private void StartDriverOperationAudit(DriverOperationAudit audit)
|
||
{
|
||
var factory = _dbFactory;
|
||
Task.Run(async () =>
|
||
{
|
||
await using var db = await factory.CreateDbContextAsync().ConfigureAwait(false);
|
||
db.ConfigEdits.Add(new ConfigEdit
|
||
{
|
||
EntityType = "DriverInstance",
|
||
EntityId = Guid.TryParse(audit.DriverInstanceId, out var guid) ? guid : Guid.Empty,
|
||
FieldsJson = $"{{\"op\":\"{audit.Op}\",\"driverInstanceId\":{System.Text.Json.JsonSerializer.Serialize(audit.DriverInstanceId)}}}",
|
||
EditedBy = audit.Actor,
|
||
SourceNode = audit.SourceNode,
|
||
});
|
||
await db.SaveChangesAsync().ConfigureAwait(false);
|
||
}).PipeTo(Self, failure: ex => new DriverOperationAuditFailed(audit, ex is AggregateException { InnerException: { } inner } ? inner : ex));
|
||
}
|
||
|
||
/// <summary>
|
||
/// lmxopcua#1051 (H-3 remainder): a failed audit write is RETRIED on a doubling backoff (capped at 30 s) up to
|
||
/// <see cref="MaxDriverAuditAttempts"/> attempts — a ConfigDb blip used to lose the operator's Restart/Reconnect
|
||
/// from the audit timeline. A write the database REJECTS (constraint, truncation — the coordinator's poison
|
||
/// allowlist) fails identically every time and is not retried. Either way the command's reply is untouched: it was
|
||
/// dispatched. At-least-once: a write that committed but reported failure (a timeout after commit) can repeat a row.
|
||
/// </summary>
|
||
private void HandleDriverOperationAuditFailed(DriverOperationAuditFailed m)
|
||
{
|
||
var a = m.Audit;
|
||
var poison = ConfigPublishCoordinator.IsPoison(m.Error);
|
||
if (!poison && a.Attempt < MaxDriverAuditAttempts)
|
||
{
|
||
var delay = TimeSpan.FromTicks(Math.Min(
|
||
TimeSpan.FromSeconds(30).Ticks, _driverAuditRetryDelay.Ticks * (1L << Math.Min(a.Attempt - 1, 20))));
|
||
if (a.Attempt == 1)
|
||
_log.Warning(m.Error,
|
||
"AdminOps: the audit row for {Op} of {DriverInstanceId} by {User} could not be written (correlation {CorrelationId}); " +
|
||
"retrying in {Delay}. The command WAS dispatched and the operator was told so",
|
||
a.Op, a.DriverInstanceId, a.Actor, a.CorrelationId, delay);
|
||
else
|
||
_log.Warning(
|
||
"AdminOps: still cannot write the audit row for {Op} of {DriverInstanceId} by {User} (attempt {Attempt}: {Error}); retrying in {Delay}",
|
||
a.Op, a.DriverInstanceId, a.Actor, a.Attempt, m.Error.Message, delay);
|
||
Timers.StartSingleTimer(a.RetryKey, new RetryDriverOperationAudit(a with { Attempt = a.Attempt + 1 }), delay);
|
||
return;
|
||
}
|
||
|
||
_log.Error(m.Error,
|
||
"AdminOps: the audit row for {Op} of {DriverInstanceId} by {User} (correlation {CorrelationId}) could NOT be written " +
|
||
"after {Attempts} attempt(s) ({Why}) and is dropped; the command WAS dispatched and the operator was told so",
|
||
a.Op, a.DriverInstanceId, a.Actor, a.CorrelationId, a.Attempt, poison ? "rejected by the ConfigDb" : "ConfigDb unavailable");
|
||
}
|
||
|
||
/// <summary>A dispatched driver operation's audit record, and which attempt at writing it this is (#1051).</summary>
|
||
private sealed record DriverOperationAudit(
|
||
string Op, string DriverInstanceId, string Actor, object CorrelationId, string SourceNode, int Attempt)
|
||
{
|
||
/// <summary>The retry timer's key: one pending retry per audit record.</summary>
|
||
public Guid RetryKey { get; init; } = Guid.NewGuid();
|
||
}
|
||
|
||
/// <summary>The off-thread ConfigEdit audit write for a dispatched driver operation failed (#996 / H-3).</summary>
|
||
private sealed record DriverOperationAuditFailed(DriverOperationAudit Audit, Exception Error);
|
||
|
||
/// <summary>The backoff tick of a failed audit write (#1051).</summary>
|
||
private sealed record RetryDriverOperationAudit(DriverOperationAudit Audit);
|
||
}
|