318 lines
20 KiB
C#
318 lines
20 KiB
C#
using System.Text.Json;
|
|
using System.Text.RegularExpressions;
|
|
using Grpc.Core;
|
|
using Grpc.Net.Client;
|
|
using GrpcDataProbe;
|
|
using Microsoft.AspNetCore.Builder;
|
|
using Microsoft.AspNetCore.Hosting;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using Microsoft.Extensions.Hosting;
|
|
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
|
|
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
|
using T = ZB.MOM.WW.OtOpcUa.Commons.Protos.Telemetry.V1;
|
|
|
|
[assembly: HostingStartup(typeof(GrpcDataNodeProbe.NodeProbeStartup))]
|
|
|
|
namespace GrpcDataNodeProbe;
|
|
|
|
/// <summary>Loaded only by the isolated Docker fixture's explicit hosting-startup assembly.</summary>
|
|
public sealed class NodeProbeStartup : IHostingStartup
|
|
{
|
|
public void Configure(IWebHostBuilder builder) => builder.ConfigureServices(services =>
|
|
{
|
|
services.AddSingleton<InboundDataRequestCounter>();
|
|
services.AddSingleton<IStartupFilter, FixtureDataRequestStartupFilter>();
|
|
services.AddHostedService<NodeProbeWorker>();
|
|
});
|
|
}
|
|
|
|
/// <summary>Fixture-only process counter; retains no request identity or payload.</summary>
|
|
public sealed class InboundDataRequestCounter
|
|
{
|
|
private long _requests;
|
|
public string InstanceId { get; } = Guid.NewGuid().ToString("N");
|
|
public long Requests => Interlocked.Read(ref _requests);
|
|
public void Record() => Interlocked.Increment(ref _requests);
|
|
}
|
|
|
|
/// <summary>Observes HTTP arrivals before the fixture Host's authentication and gRPC pipeline.</summary>
|
|
public sealed class FixtureDataRequestStartupFilter(InboundDataRequestCounter counter) : IStartupFilter
|
|
{
|
|
public Action<IApplicationBuilder> Configure(Action<IApplicationBuilder> next) => app =>
|
|
{
|
|
app.Use(nextMiddleware => async context =>
|
|
{
|
|
if (context.Connection.LocalPort == 4057) counter.Record();
|
|
await nextMiddleware(context);
|
|
});
|
|
next(app);
|
|
};
|
|
}
|
|
|
|
/// <summary>Bounded, one-shot file requests through the caller's deployed DI registry; no listener.</summary>
|
|
public sealed partial class NodeProbeWorker(IServiceProvider services) : BackgroundService
|
|
{
|
|
[GeneratedRegex("^[a-zA-Z0-9][a-zA-Z0-9-]{0,95}$")]
|
|
private static partial Regex SafeId();
|
|
private object CaptureOriginAccounting()
|
|
{
|
|
var hub = services.GetService<PartitionedSampleHub>();
|
|
var acquisition = services.GetService<ZB.MOM.WW.OtOpcUa.Runtime.Drivers.SubscriptionAcquisitionCapacity>();
|
|
var composition = services.GetService<LocalDataRuntimeComposition>();
|
|
return new
|
|
{
|
|
retainedBytes = hub?.Resources.RetainedBytes, maximumRetainedBytes = hub?.Resources.MaximumBytes,
|
|
reservedDrivers = acquisition?.ReservedDriverCount, maximumReservedDrivers = acquisition?.MaxReservations,
|
|
acquisitionOwnerSerial = acquisition?.CurrentOwnerSerial, acquisitionControlGeneration = acquisition?.ControlGeneration,
|
|
workload = composition?.CaptureWorkloadAccounting(),
|
|
sourceIngressCounters = SourceIngressDiagnostics.Capture(),
|
|
historyOpenContinuations = composition?.Services.HistoryOpenContinuations,
|
|
definition = "actual origin hub resource charges and physical driver reservation owners; driver count is not source count"
|
|
};
|
|
}
|
|
|
|
private static async Task<ProbeResult> LegacyTelemetryAsync(ProbeCommand command, CancellationToken cancellationToken)
|
|
{
|
|
var observations = new Dictionary<string, object?>();
|
|
var assertions = 0;
|
|
void Check(bool condition)
|
|
{
|
|
if (!condition) throw new InvalidOperationException();
|
|
assertions++;
|
|
}
|
|
try
|
|
{
|
|
// These are the two run-owned SOURCE nodes, never a caller-supplied URL.
|
|
var address = command.ExpectedNodeId switch
|
|
{
|
|
"source-1:4053" => "http://source-1:4056",
|
|
"source-2:4053" => "http://source-2:4056",
|
|
_ => throw new InvalidOperationException()
|
|
};
|
|
Check(command.TimeoutSeconds is >= 1 and <= 20);
|
|
var key = Environment.GetEnvironmentVariable("Telemetry__ApiKey");
|
|
Check(!string.IsNullOrWhiteSpace(key));
|
|
observations["protocol"] = "authenticated gRPC over HTTP/2";
|
|
observations["service"] = "telemetry.v1.TelemetryStreamService/Subscribe";
|
|
observations["eventClass"] = "DriverHealth";
|
|
observations["target"] = new { mode = "Node", expectedClusterId = "SOURCE", expectedNodeId = command.ExpectedNodeId };
|
|
using var handler = new SocketsHttpHandler
|
|
{
|
|
AllowAutoRedirect = false,
|
|
UseProxy = false,
|
|
ConnectTimeout = TimeSpan.FromSeconds(Math.Min(command.TimeoutSeconds, 5))
|
|
};
|
|
using var channel = GrpcChannel.ForAddress(address, new GrpcChannelOptions
|
|
{
|
|
HttpHandler = handler,
|
|
MaxReceiveMessageSize = 64 * 1024
|
|
});
|
|
var client = new T.TelemetryStreamService.TelemetryStreamServiceClient(channel);
|
|
var headers = new Metadata { { "authorization", "Bearer " + key } };
|
|
using var call = client.Subscribe(new T.TelemetryStreamRequest { CorrelationId = command.Id }, headers,
|
|
deadline: DateTime.UtcNow.AddSeconds(command.TimeoutSeconds), cancellationToken: cancellationToken);
|
|
while (await call.ResponseStream.MoveNext(cancellationToken))
|
|
{
|
|
var envelope = call.ResponseStream.Current;
|
|
// The production local telemetry hub primes new subscribers with its
|
|
// actual driver-health snapshot. Other telemetry is not a substitute.
|
|
if (envelope.DriverHealth is not { DriverInstanceId: "source-modbus" } health) continue;
|
|
Check(envelope.CorrelationId == command.Id);
|
|
Check(health.DriverInstanceId == "source-modbus");
|
|
Check(health.HasReportingNodeId);
|
|
Check(health.ReportingNodeId == command.ExpectedNodeId);
|
|
Check(health.ClusterId == "SOURCE");
|
|
observations["driverInstanceId"] = health.DriverInstanceId;
|
|
observations["servingNodeId"] = health.ReportingNodeId;
|
|
observations["reportingNodeId"] = health.ReportingNodeId;
|
|
observations["clusterId"] = health.ClusterId;
|
|
observations["authenticatedSnapshotReceived"] = true;
|
|
return new(command.Id, command.Operation, true, assertions, observations);
|
|
}
|
|
return new(command.Id, command.Operation, false, assertions, observations, "SnapshotUnavailable");
|
|
}
|
|
catch (Exception error) when (error is not OutOfMemoryException)
|
|
{
|
|
// Headers, credentials and remote exception detail stay out of evidence.
|
|
return new(command.Id, command.Operation, false, assertions, observations, error.GetType().Name);
|
|
}
|
|
}
|
|
/// <summary>
|
|
/// A4 (A08/§5.7): listen to THIS node's own authenticated telemetry stream for the command's window and return every
|
|
/// <c>alerts</c> transition it carries — the exact feed central's <c>/alerts</c> page and the alarm-history adapter
|
|
/// consume. A consumer node must publish none for imported conditions; the SOURCE Primary's list is the positive control.
|
|
/// </summary>
|
|
private static async Task<ProbeResult> AlertTransitionsAsync(ProbeCommand command, CancellationToken cancellationToken)
|
|
{
|
|
var observations = new Dictionary<string, object?>();
|
|
var transitions = new List<object>();
|
|
var envelopes = 0;
|
|
var host = Environment.GetEnvironmentVariable("HOSTNAME");
|
|
var key = Environment.GetEnvironmentVariable("Telemetry__ApiKey");
|
|
if (string.IsNullOrWhiteSpace(host) || string.IsNullOrWhiteSpace(key) || command.TimeoutSeconds is < 3 or > 120)
|
|
return new(command.Id, command.Operation, false, 0, observations, "InvalidCommand");
|
|
using var handler = new SocketsHttpHandler { AllowAutoRedirect = false, UseProxy = false, ConnectTimeout = TimeSpan.FromSeconds(5) };
|
|
using var channel = GrpcChannel.ForAddress($"http://{host}:4056", new GrpcChannelOptions { HttpHandler = handler, MaxReceiveMessageSize = 1024 * 1024 });
|
|
var client = new T.TelemetryStreamService.TelemetryStreamServiceClient(channel);
|
|
var headers = new Metadata { { "authorization", "Bearer " + key } };
|
|
string? failure = null;
|
|
try
|
|
{
|
|
using var call = client.Subscribe(new T.TelemetryStreamRequest { CorrelationId = command.Id }, headers,
|
|
deadline: DateTime.UtcNow.AddSeconds(command.TimeoutSeconds - 2), cancellationToken: cancellationToken);
|
|
while (await call.ResponseStream.MoveNext(cancellationToken))
|
|
{
|
|
envelopes++;
|
|
if (call.ResponseStream.Current.AlarmTransition is { } alarm)
|
|
transitions.Add(new { alarmId = alarm.AlarmId, alarmName = alarm.AlarmName, kind = alarm.TransitionKind,
|
|
equipmentPath = alarm.EquipmentPath, user = alarm.User, comment = alarm.HasComment ? alarm.Comment : null,
|
|
at = alarm.TimestampUtc?.ToDateTime().ToString("O") });
|
|
}
|
|
}
|
|
catch (RpcException error) when (error.StatusCode is StatusCode.DeadlineExceeded or StatusCode.Cancelled) { }
|
|
catch (Exception error) when (error is not OutOfMemoryException) { failure = error.GetType().Name; }
|
|
observations["node"] = host;
|
|
observations["envelopes"] = envelopes;
|
|
observations["alarmTransitions"] = transitions;
|
|
return new(command.Id, command.Operation, failure is null, 1, observations, failure);
|
|
}
|
|
|
|
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
|
{
|
|
var configured = Environment.GetEnvironmentVariable("GRPC_DATA_NODE_PROBE_DIR");
|
|
if (string.IsNullOrWhiteSpace(configured) || !Path.IsPathFullyQualified(configured))
|
|
throw new InvalidOperationException("Fixture command directory required.");
|
|
var folder = new DirectoryInfo(configured);
|
|
folder.Create();
|
|
if (folder.LinkTarget is not null) throw new InvalidOperationException("Fixture command directory cannot be linked.");
|
|
while (!stoppingToken.IsCancellationRequested)
|
|
{
|
|
foreach (var input in folder.EnumerateFiles("*.request.json").OrderBy(file => file.Name).Take(16))
|
|
{
|
|
if (input.LinkTarget is not null || input.Length is <= 0 or > 16384) continue;
|
|
var id = input.Name[..^".request.json".Length];
|
|
if (!SafeId().IsMatch(id)) continue;
|
|
var resultPath = Path.Combine(folder.FullName, id + ".result.json");
|
|
if (File.Exists(resultPath)) { input.Delete(); continue; }
|
|
var claimed = input.FullName + ".running";
|
|
try { File.Move(input.FullName, claimed, overwrite: false); }
|
|
catch (IOException) { continue; }
|
|
ProbeResult result;
|
|
try
|
|
{
|
|
var command = JsonSerializer.Deserialize<ProbeCommand>(await File.ReadAllTextAsync(claimed, stoppingToken), ProbeEngine.Json)
|
|
?? throw new InvalidOperationException();
|
|
if (command.Id != id || command.TimeoutSeconds is < 1 or > 120) throw new InvalidOperationException();
|
|
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(stoppingToken);
|
|
timeout.CancelAfter(TimeSpan.FromSeconds(command.TimeoutSeconds));
|
|
if (command.Operation == "topology")
|
|
{
|
|
var cluster = Akka.Cluster.Cluster.Get(services.GetRequiredService<Akka.Actor.ActorSystem>());
|
|
var members = cluster.State.Members.Select(member => new
|
|
{
|
|
host = member.Address.Host, port = member.Address.Port,
|
|
status = member.Status.ToString(), roles = member.Roles.ToArray()
|
|
}).ToArray();
|
|
result = new(id, "topology", members.Length == 2 && members.All(member => member.status == "Up"), 2,
|
|
new() { ["members"] = members, ["self"] = cluster.SelfAddress.ToString(), ["processId"] = Environment.ProcessId });
|
|
var cache = services.GetService<ZB.MOM.WW.OtOpcUa.Runtime.DeploymentCache.IDeploymentArtifactCache>();
|
|
var artifact = cache is null ? null : await cache.GetCurrentUnkeyedAsync(timeout.Token);
|
|
result.Observations["artifactRevision"] = artifact?.RevisionHash;
|
|
result.Observations["deploymentId"] = artifact?.DeploymentId;
|
|
result.Observations["connections"] = services.GetService<DataConnectionDeploymentRuntime>()?.CaptureDiagnostics();
|
|
result.Observations["originAccounting"] = CaptureOriginAccounting();
|
|
result.Observations["process"] = WorkloadEngine.CaptureProcess();
|
|
result.Observations["inboundDataRequests"] = services.GetRequiredService<InboundDataRequestCounter>().Requests;
|
|
result.Observations["inboundDataRequestObserverId"] = services.GetRequiredService<InboundDataRequestCounter>().InstanceId;
|
|
}
|
|
else if (command.Operation == "warm-state")
|
|
{
|
|
var settings = services.GetService<WarmRedundancySettings>() ?? WarmRedundancySettings.Unset;
|
|
var warm = services.GetRequiredService<DataConnectionWarmRoleView>().Snapshot;
|
|
var serving = services.GetRequiredService<LocalCatalogCoordinator>().Serving;
|
|
using var process = System.Diagnostics.Process.GetCurrentProcess();
|
|
result = new(id, command.Operation, true, 1, new()
|
|
{
|
|
["nodeId"] = serving.NodeId, ["mode"] = settings.Mode.ToString(), ["isWarm"] = settings.IsWarm,
|
|
["warmRole"] = new { role = warm.Role?.ToString(), generation = warm.Generation },
|
|
["serving"] = serving,
|
|
["process"] = new { id = Environment.ProcessId, startedUtc = process.StartTime.ToUniversalTime().ToString("O") }
|
|
});
|
|
}
|
|
else if (command.Operation == "bundle-commit")
|
|
{
|
|
var observer = services.GetRequiredService<IDataConnectionBundleCommitObserver>();
|
|
var state = await observer.ObserveAsync(command.ConnectionId, timeout.Token);
|
|
result = new(id, command.Operation, true, 1, new()
|
|
{
|
|
["credentialScopeVersion"] = state.CredentialScopeVersion,
|
|
["credentialVersion"] = state.CredentialVersion,
|
|
["credentialDeleted"] = state.CredentialDeleted,
|
|
["trustScopeVersion"] = state.TrustScopeVersion,
|
|
["trustVersion"] = state.TrustVersion,
|
|
["trustRetired"] = state.TrustRetired
|
|
});
|
|
}
|
|
else if (command.Operation == "projection-diagnostics")
|
|
{
|
|
result = CaptureProjectionDiagnostics(command);
|
|
}
|
|
else if (command.Operation == "alert-transitions")
|
|
{
|
|
result = await AlertTransitionsAsync(command, timeout.Token);
|
|
}
|
|
else if (command.Operation == "legacy-telemetry")
|
|
{
|
|
// Feature-disable validation must bypass DataConnection acquisition.
|
|
result = await LegacyTelemetryAsync(command, timeout.Token);
|
|
var callerCluster = Akka.Cluster.Cluster.Get(services.GetRequiredService<Akka.Actor.ActorSystem>());
|
|
result.Observations["caller"] = Environment.GetEnvironmentVariable("HOSTNAME");
|
|
result.Observations["callerNodeId"] = $"{callerCluster.SelfAddress.Host}:{callerCluster.SelfAddress.Port}";
|
|
result.Observations["callerClusterId"] = callerCluster.SelfRoles.Single(role => role.StartsWith("cluster-", StringComparison.Ordinal))["cluster-".Length..];
|
|
}
|
|
else
|
|
{
|
|
var runtime = services.GetRequiredService<DataConnectionDeploymentRuntime>();
|
|
var callerCluster = Akka.Cluster.Cluster.Get(services.GetRequiredService<Akka.Actor.ActorSystem>());
|
|
if (!runtime.TryAcquire(command.ConnectionId, out var lease) || lease is null)
|
|
result = new(id, command.Operation, command.ExpectedState == "Unavailable", 1,
|
|
new() { ["readiness"] = "Unavailable", ["caller"] = Environment.GetEnvironmentVariable("HOSTNAME") });
|
|
else
|
|
{
|
|
await using (lease)
|
|
{
|
|
using var linked = CancellationTokenSource.CreateLinkedTokenSource(timeout.Token, lease.CancellationToken);
|
|
result = command.Operation == "workload"
|
|
? await WorkloadEngine.RunAsync(lease.Connection, command, linked.Token,
|
|
() => new { connections = runtime.CaptureDiagnostics(), originAccounting = CaptureOriginAccounting() })
|
|
: await ProbeEngine.RunAsync(lease.Connection, command, linked.Token);
|
|
result.Observations["caller"] = Environment.GetEnvironmentVariable("HOSTNAME");
|
|
var target = lease.Connection.Target;
|
|
result.Observations["target"] = new { mode = target.Mode.ToString(), target.ExpectedClusterId,
|
|
target.ExpectedNodeId, consistency = target.Consistency.ToString() };
|
|
result.Observations["realm"] = command.Realm;
|
|
result.Observations["namespaceUri"] = command.NamespaceUri;
|
|
result.Observations["path"] = command.Path;
|
|
}
|
|
}
|
|
result.Observations["callerNodeId"] = $"{callerCluster.SelfAddress.Host}:{callerCluster.SelfAddress.Port}";
|
|
result.Observations["callerClusterId"] = callerCluster.SelfRoles.Single(role => role.StartsWith("cluster-", StringComparison.Ordinal))["cluster-".Length..];
|
|
}
|
|
}
|
|
catch (Exception error) when (error is not OutOfMemoryException)
|
|
{
|
|
var failure = ProbeFailureClassifier.Capture(error, ProbeFailurePhase.NodeProbe);
|
|
result = new(id, "invalid", false, 0,
|
|
new() { ["failurePhase"] = failure.Phase, ["failureEvidence"] = failure }, failure.Category);
|
|
}
|
|
var temporary = resultPath + ".tmp";
|
|
await File.WriteAllTextAsync(temporary, JsonSerializer.Serialize(result, ProbeEngine.Json), stoppingToken);
|
|
if (!OperatingSystem.IsWindows()) File.SetUnixFileMode(temporary, UnixFileMode.UserRead | UnixFileMode.UserWrite);
|
|
File.Move(temporary, resultPath, overwrite: false);
|
|
File.Delete(claimed);
|
|
}
|
|
await Task.Delay(100, stoppingToken);
|
|
}
|
|
}
|
|
}
|