Files
lmxopcua/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/OpcUa/ServiceLevelEndToEndTests.cs
T
Joseph Doherty f02067d295 test: retry OPC UA host start on a port bind race (TOCTOU in AllocateFreePort)
The tests probe a free port (bind 0, release) and start the SDK server later; under a
highly parallel run another test can take the port in between and the SDK fails with
'Failed to establish tcp listener sockets for Ipv4 and IPv6.'. OpcUaHostStart.StartAsync
builds a fresh host + server on a fresh port per attempt (up to 5) when the failure is a
bind failure; all 45 start sites in OpcUaServer.Tests, OpcUaServer.IntegrationTests and
Runtime.Tests use it. Per-attempt GUID ApplicationUris are hoisted out of the host factory
because a changed URI against a reused PKI store fails with 'Cannot access private key'.

Claude-Session: https://claude.ai/code/session_01Ef2ozxS7QPanGT8uoATbTe
2026-10-08 22:30:55 -04:00

145 lines
5.4 KiB
C#

using Akka.Actor;
using Microsoft.Extensions.Logging.Abstractions;
using Opc.Ua.Server;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Redundancy;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Commons.Types;
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
using ZB.MOM.WW.OtOpcUa.Runtime.OpcUa;
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.OpcUa;
/// <summary>
/// Task 60 / #81 — verifies the full path from cluster redundancy state to OPC UA
/// <c>Server.ServiceLevel</c> visible on the wire. Boots a real <see cref="StandardServer"/>,
/// wires <see cref="SdkServiceLevelPublisher"/> into a <see cref="DeferredServiceLevelPublisher"/>
/// (the production binding pattern), spawns <see cref="OpcUaPublishActor"/> against the
/// deferred publisher, and sends a <see cref="RedundancyStateChanged"/> snapshot. Asserts
/// <c>ServerObject.ServiceLevel.Value</c> reflects the role-derived byte.
/// </summary>
public sealed class ServiceLevelEndToEndTests : RuntimeActorTestBase
{
private static CancellationToken Ct => CancellationToken.None;
/// <summary>Verifies that the primary cluster leader sets Server ServiceLevel to 240.</summary>
[Fact]
public async Task Primary_leader_drives_Server_ServiceLevel_to_240()
{
var pkiRoot = AllocatePkiRoot();
try
{
var started = await OpcUaHostStart.StartAsync(
port => new OpcUaApplicationHost(
BuildOptions("PrimaryLeader", pkiRoot, port),
NullLogger<OpcUaApplicationHost>.Instance),
() => new StandardServer(), Ct);
await using var host = started.Host;
var server = started.Server;
var deferred = new DeferredServiceLevelPublisher();
deferred.SetInner(new SdkServiceLevelPublisher(
server.CurrentInstance,
NullLogger<SdkServiceLevelPublisher>.Instance));
var localNode = NodeId.Parse("node-A");
var actor = Sys.ActorOf(OpcUaPublishActor.PropsForTests(
serviceLevel: deferred,
subscribeRedundancyTopic: false,
localNode: localNode));
actor.Tell(new RedundancyStateChanged(
Nodes: new[]
{
new NodeRedundancyState(localNode, RedundancyRole.Primary, IsClusterLeader: true, IsDriverPrimary: true, AsOfUtc: DateTime.UtcNow),
},
CorrelationId: CorrelationId.NewId()));
AwaitAssertion(() =>
server.CurrentInstance.ServerObject.ServiceLevel.Value.ShouldBe((byte)240));
}
finally
{
DeletePkiRoot(pkiRoot);
}
}
/// <summary>Verifies that the secondary node sets Server ServiceLevel to 100.</summary>
[Fact]
public async Task Secondary_drives_Server_ServiceLevel_to_100()
{
var pkiRoot = AllocatePkiRoot();
try
{
var started = await OpcUaHostStart.StartAsync(
port => new OpcUaApplicationHost(
BuildOptions("Secondary", pkiRoot, port),
NullLogger<OpcUaApplicationHost>.Instance),
() => new StandardServer(), Ct);
await using var host = started.Host;
var server = started.Server;
var deferred = new DeferredServiceLevelPublisher();
deferred.SetInner(new SdkServiceLevelPublisher(
server.CurrentInstance,
NullLogger<SdkServiceLevelPublisher>.Instance));
var localNode = NodeId.Parse("node-B");
var actor = Sys.ActorOf(OpcUaPublishActor.PropsForTests(
serviceLevel: deferred,
subscribeRedundancyTopic: false,
localNode: localNode));
actor.Tell(new RedundancyStateChanged(
Nodes: new[]
{
new NodeRedundancyState(localNode, RedundancyRole.Secondary, IsClusterLeader: false, IsDriverPrimary: false, AsOfUtc: DateTime.UtcNow),
},
CorrelationId: CorrelationId.NewId()));
AwaitAssertion(() =>
server.CurrentInstance.ServerObject.ServiceLevel.Value.ShouldBe((byte)100));
}
finally
{
DeletePkiRoot(pkiRoot);
}
}
private static OpcUaApplicationHostOptions BuildOptions(string name, string pkiRoot, int port) =>
new()
{
ApplicationName = $"OtOpcUa.E2E.{name}",
ApplicationUri = $"urn:OtOpcUa.E2E.{name}:{Path.GetFileName(pkiRoot)}", // stable across bind-race retries
OpcUaPort = port,
PublicHostname = "localhost",
PkiStoreRoot = pkiRoot,
};
private static string AllocatePkiRoot() =>
Path.Combine(Path.GetTempPath(), $"otopcua-pki-{Guid.NewGuid():N}");
private static void DeletePkiRoot(string root)
{
if (Directory.Exists(root))
{
try { Directory.Delete(root, recursive: true); }
catch { /* best-effort */ }
}
}
private void AwaitAssertion(Action assertion)
{
var deadline = DateTime.UtcNow.AddSeconds(3);
Exception? last = null;
while (DateTime.UtcNow < deadline)
{
try { assertion(); return; }
catch (Exception ex) { last = ex; Thread.Sleep(30); }
}
if (last is not null) throw last;
}
}