mirror of
https://github.com/OPCFoundation/UA-.NETStandard.git
synced 2026-10-18 14:43:08 +08:00
28f1401324
Profiling the reference server under load showed most request-path CPU spent spinning on contended locks, plus several avoidable allocations per request or per node. This PR removes them, switches the reference server to Server GC, and adds the load harness used to measure it. ## Results Paired A/B against `master` (3 alternating rounds, medians, 20 sessions, workstation GC on both sides, 24-core machine): | Scenario | Throughput | p50 | p90 | Server CPU / op | Server alloc / op | Lock contention | |---|---|---|---|---|---|---| | Read, 1 value | **+45%** (94k → 137k req/s) | −20% | −46% | −37% | −39% | −94% | | Read, 100 values | **+40%** | −26% | −17% | −24% | −25% | +130% ¹ | | Read, 100 values, SignAndEncrypt | **+48%** | −36% | −20% | −30% | −26% | +106% ¹ | | Browse (Server object) | **+33%** | −31% | −12% | −13% | −14% | −40% | | Write, 100 values | +13% | −12% | −4% | −10% | −19% | −23% | | Data-change subscriptions | ±0 ² | ≈ | ≈ | −14% | −17% | −29% | ¹ The faster server spends more time in the remaining per-node locks. ² Throughput is bounded by the writer rate in this scenario. Separately, Server GC instead of workstation GC doubles Read-100 throughput (21k → 44k req/s) and cuts p90 from 2.1 ms to 0.6 ms, because workstation GC paused the server for about half the wall time under load. The working set grows from ~210 MB to ~430 MB. ## Changes - **`ObjectPool<T>`**: lock-free slot array. `ConcurrentBag.Count` took every per-thread lock on each `Return` of the pooled response value-task source, once per request. - **`FairRequestQueue`**: - drops redundant gate entries: the fail-fast pre-checks and the stopped check read volatile fields and are re-checked under the gate; the owner count is folded into selection; - coalesces wake pulses with a pending flag, so the bounded signal channel's lock is only taken when no token is outstanding. Wake-count semantics in the tests are unchanged. - **`DefaultServerResourceIsolationProvider`**: - compares peer addresses without `GetAddressBytes()` allocations; - builds the unsecured verification context only when a classifier is configured. - **TCP listener / channel**: caches the certificate DER copies per channel, keyed on the certificate instance. `X509Certificate2.RawData` returns a fresh copy on every access, and the listener read it for every request. - **`EndpointBase`**: resolves the request `ActivitySource` once instead of `Assembly.GetCallingAssembly()` per request. - **Node managers**: - one `ServerSystemContext` copy per request (cached on the `OperationContext`) for per-node callbacks: permission metadata, node metadata, view membership, method lookup; - removes a discarded copy in `GetReferenceDescriptionAsync`; - per-request operation caches are plain `Dictionary` instead of a `ConcurrentDictionary` with 24 lock objects; - the validation cache is built in one pass; - fixes zero-capacity error lists. - **`ResourceManager`**: translation lookups read an immutable snapshot that is rebuilt after writes. Browse serialised on the global lock for every display name. - **`MonitoredItem`**: shares the default `DataChangeFilter` instead of allocating one per sampled value. - **Reference server**: `ServerGarbageCollection=true`; new "Garbage collector mode" section in `docs/ServerScalability.md`. - **`perf/`**: `ServerLoadHarness` (out-of-process server plus load driver, server-side CPU/GC/alloc/contention deltas, optional `dotnet-trace` capture), `TraceAnalyzer` (TraceEvent-based CPU/allocation/contention aggregation), and paired A/B scripts. Not part of `UA.slnx`. ### Behaviour notes for custom node managers - The `IDictionary<NodeId, NodeState>` operation cache handed to overrides is now a `Dictionary`. It was a `ConcurrentDictionary`, but only one request flow uses it. - Within one request, per-node callbacks of a node manager share one `ServerSystemContext` copy. ### Later commits on this PR - **Permission checks without `NodeMetadata`** (`9068684c3`): the role-permission and access-restriction validators run on an internal `PermissionMetadata` struct; `AsyncCustomNodeManager` fills it on the stack from the same attributes and namespace defaults. Browse's reference filter reads 3 attributes per target instead of 13. Read 100 values: 120.6 → 95.7 KB/request, ~21k → 26k req/s; Browse 67.6 → 51.8 KB, 26.7k → 29.8k req/s. - **Read-only channel evidence** (`936b28d76`, `dc638ab9f`): `SecureChannelContext.ClientChannelCertificate`, `ServerChannelCertificate` and `ChannelThumbprint` are `ByteString`, so the cached per-channel certificate buffer is shared without a copy and cannot be altered by handlers or classifiers. **Public API change**, see the new section in `docs/MigrationGuide.md`. The isolation provider's revalidation snapshot still copies. - **Session lookup** (`936b28d76`): `SessionManager.TryGetSessionContext` takes the candidate snapshot without the bindings lock; the validating check under the lock is unchanged (2 instead of 4 global lock acquisitions per request). - Unit tests for `ObjectPool`, the per-request system context cache, the translation snapshot, `SecureChannelContext` null semantics and a stopped `FairRequestQueue`; `perf/` follows the repository conventions. ## Testing - `Opc.Ua.Server.Tests` (net10.0): 8386 passed before the `ByteString` change. After it, 13 secure-session and isolation tests failed; both causes are fixed in `dc638ab9f` and those tests (25 with their variants) pass. A full rerun of the Server, Sessions, Core, Redundancy, LDS and GDS suites on the final commit is in progress. - Full solution builds for net10.0 and net48; `dotnet format whitespace` clean. ### o6-automation opcua-benchmarks (sampling, deep pipelines) Replicated both tests of the [o6-automation benchmark](https://github.com/o6-automation/opcua-benchmarks) in the harness (`--scenario counters`, and `read` with 10 clients × N outstanding), paired against `origin/master`: | Test | master | this PR | |---|---|---| | Subscription sampling, 100 Hz, every item ≥ 99 % of samples, 1 item | FAIL (75–94 %) | PASS (100 %) | | same, 1024 items | FAIL (64–73 %) | PASS (99.9 %) | | same, capacity | — | between 4096 and 6144 items (~410–520k samples/s) | | Read, 10 clients × 100 outstanding, None | stalls (0–1.7k req/s) | 121–131k req/s | | Read, 10 clients × 100 outstanding, SignAndEncrypt | stalls (0 req/s) | 89–91k req/s | | Read, 10 clients × 1000 outstanding | channels faulted (`BadTcpNotEnoughResources`) | 0 errors, ~45–54k req/s | - **Fixed-rate sampling** (`30b769d13`): the sampling loop waited one interval after each sample, adding timer overshoot and sampling time to every cycle; samples now have absolute deadlines. - **Async response send** (`cdac5c5ca`): `SendResponse` blocked thread-pool workers on the channel gate; with many requests in flight the receive loop that was handed the gate waited for a pool thread and the channel stalled. The TCP, Kestrel TCP and WebSocket listeners now use `SendResponseAsync`. - **Backpressure instead of channel fault** (`191cd2ba7`): server channels stop reading while more than 100 responses are queued and resume at 50, instead of faulting the channel. Client channels keep reading. At 10,000 outstanding requests throughput is ~50k req/s with or without the limit engaged, so the remaining gap to the 100-per-client case is not the backpressure. ## Not changed - `SentMessageQueue` deep-clones every `NotificationMessage`. Retained messages return their pooled payloads on acknowledgement while the response copy may still be queued for send, and a client can acknowledge a sequence number before receiving it; the clone keeps a recycled payload from reaching another session's response. Removing it needs a send-completion hook from the transport. - Generated responses allocate a default `ResponseHeader` that is replaced (~2-3 % of per-request allocation). Fixing it means making structure fields of every generated type lazily initialized, a generator-wide change to default values, equality and encoding. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
524 lines
23 KiB
C#
524 lines
23 KiB
C#
/* ========================================================================
|
|
* Copyright (c) 2005-2025 The OPC Foundation, Inc. All rights reserved.
|
|
*
|
|
* OPC Foundation MIT License 1.00
|
|
*
|
|
* Permission is hereby granted, free of charge, to any person
|
|
* obtaining a copy of this software and associated documentation
|
|
* files (the "Software"), to deal in the Software without
|
|
* restriction, including without limitation the rights to use,
|
|
* copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
* copies of the Software, and to permit persons to whom the
|
|
* Software is furnished to do so, subject to the following
|
|
* conditions:
|
|
*
|
|
* The above copyright notice and this permission notice shall be
|
|
* included in all copies or substantial portions of the Software.
|
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
|
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
|
|
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
|
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
|
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
|
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
|
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
|
* OTHER DEALINGS IN THE SOFTWARE.
|
|
*
|
|
* The complete license agreement can be found here:
|
|
* http://opcfoundation.org/License/MIT/1.00/
|
|
* ======================================================================*/
|
|
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Collections.ObjectModel;
|
|
using System.Net;
|
|
using System.Net.Sockets;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
using Microsoft.Extensions.Logging;
|
|
using Opc.Ua.Security.Certificates;
|
|
|
|
namespace Opc.Ua.Server.TestFramework
|
|
{
|
|
/// <summary>
|
|
/// Extensions for server fixture.
|
|
/// </summary>
|
|
public static class ServerFixtureUtils
|
|
{
|
|
public const double DefaultSessionTimeout = 120000;
|
|
public const uint DefaultMaxResponseMessageSize = 128 * 1024;
|
|
public const int MinTestPort = 50000;
|
|
public const int MaxTestPort = 65000;
|
|
private const string kDefaultClientApplicationUri =
|
|
"urn:localhost:opcfoundation.org:ServerFixtureClient";
|
|
|
|
/// <summary>
|
|
/// Create and Activate a session without security.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// The request header is used to call services directly,
|
|
/// without establishing a session with a client.
|
|
/// </remarks>
|
|
/// <param name="server">The server to connect to.</param>
|
|
/// <param name="sessionName">A session name.</param>
|
|
/// <returns>The request header for the session.</returns>
|
|
/// <exception cref="NotSupportedException"></exception>
|
|
public static async Task<(RequestHeader, SecureChannelContext)> CreateAndActivateSessionAsync(
|
|
this SessionServerBase server,
|
|
string sessionName,
|
|
bool useSecurity = false,
|
|
UserIdentityToken? identityToken = null,
|
|
double sessionTimeout = DefaultSessionTimeout,
|
|
uint maxResponseMessageSize = DefaultMaxResponseMessageSize,
|
|
string? clientApplicationUri = null,
|
|
ArrayOf<string> localeIds = default)
|
|
{
|
|
if (clientApplicationUri != null && clientApplicationUri.Length == 0)
|
|
{
|
|
throw new ArgumentException(
|
|
"The client ApplicationUri must not be empty.",
|
|
nameof(clientApplicationUri));
|
|
}
|
|
|
|
// Find TCP endpoint
|
|
ArrayOf<EndpointDescription> endpoints = server.GetEndpoints();
|
|
EndpointDescription endpoint = useSecurity
|
|
? endpoints.Find(e =>
|
|
e.TransportProfileUri!
|
|
.Equals(Profiles.UaTcpTransport, StringComparison.Ordinal) &&
|
|
e.SecurityMode == MessageSecurityMode.Sign &&
|
|
e.SecurityPolicyUri == SecurityPolicies.Basic256Sha256) ??
|
|
endpoints.Find(e =>
|
|
e.TransportProfileUri!
|
|
.Equals(Profiles.HttpsBinaryTransport, StringComparison.Ordinal) &&
|
|
e.SecurityMode == MessageSecurityMode.Sign &&
|
|
e.SecurityPolicyUri == SecurityPolicies.Basic256Sha256)
|
|
: endpoints.Find(e =>
|
|
e.TransportProfileUri!
|
|
.Equals(Profiles.UaTcpTransport, StringComparison.Ordinal) ||
|
|
e.TransportProfileUri
|
|
.Equals(Profiles.HttpsBinaryTransport, StringComparison.Ordinal));
|
|
endpoint ??= endpoints.Find(e =>
|
|
e.TransportProfileUri!
|
|
.Equals(Profiles.UaTcpTransport, StringComparison.Ordinal) ||
|
|
e.TransportProfileUri
|
|
.Equals(Profiles.HttpsBinaryTransport, StringComparison.Ordinal)) ??
|
|
throw new NotSupportedException("Unsupported transport profile or security policy.");
|
|
|
|
if (useSecurity)
|
|
{
|
|
endpoint.SecurityMode = MessageSecurityMode.Sign;
|
|
endpoint.SecurityPolicyUri = SecurityPolicies.Basic256Sha256;
|
|
}
|
|
else
|
|
{
|
|
endpoint.SecurityMode = MessageSecurityMode.None;
|
|
endpoint.SecurityPolicyUri = SecurityPolicies.None;
|
|
}
|
|
|
|
Certificate? clientCertificate = null;
|
|
try
|
|
{
|
|
ByteString clientNonce = default;
|
|
ByteString clientCertificateData = default;
|
|
byte[]? clientChannelCertificate = null;
|
|
byte[]? serverChannelCertificate = null;
|
|
byte[]? channelThumbprint = null;
|
|
if (useSecurity)
|
|
{
|
|
clientCertificate = CertificateBuilder
|
|
.Create("CN=ServerFixtureClient")
|
|
.AddExtension(
|
|
new X509SubjectAltNameExtension(
|
|
clientApplicationUri ?? kDefaultClientApplicationUri,
|
|
[Utils.GetHostName()]))
|
|
.SetRSAKeySize(CertificateFactory.DefaultKeySize)
|
|
.CreateForRSA();
|
|
clientNonce = Nonce.CreateRandomNonceData(32).ToByteString();
|
|
clientCertificateData = clientCertificate.RawData.ToByteString();
|
|
clientChannelCertificate = clientCertificate.RawData;
|
|
channelThumbprint = Nonce.CreateRandomNonceData(32);
|
|
if (!endpoint.ServerCertificate.IsEmpty)
|
|
{
|
|
using CertificateCollection serverCertificateChain =
|
|
Utils.ParseCertificateChainBlob(
|
|
endpoint.ServerCertificate,
|
|
server.MessageContext.Telemetry);
|
|
serverChannelCertificate = serverCertificateChain[0].RawData;
|
|
}
|
|
}
|
|
|
|
var secureChannelContext = new SecureChannelContext(
|
|
sessionName,
|
|
endpoint,
|
|
RequestEncoding.Binary,
|
|
clientChannelCertificate,
|
|
serverChannelCertificate,
|
|
channelThumbprint);
|
|
var requestHeader = new RequestHeader();
|
|
ApplicationDescription clientDescription = (clientApplicationUri == null
|
|
? null
|
|
: new ApplicationDescription
|
|
{
|
|
ApplicationUri = clientApplicationUri,
|
|
ApplicationName = new LocalizedText("ServerFixtureClient"),
|
|
ApplicationType = ApplicationType.Client
|
|
})!;
|
|
|
|
CreateSessionResponse createSessionResponse = await server.CreateSessionAsync(
|
|
secureChannelContext,
|
|
requestHeader,
|
|
clientDescription,
|
|
null,
|
|
null,
|
|
sessionName,
|
|
clientNonce,
|
|
clientCertificateData,
|
|
sessionTimeout,
|
|
maxResponseMessageSize,
|
|
RequestLifetime.None).ConfigureAwait(false);
|
|
ValidateResponse(createSessionResponse.ResponseHeader);
|
|
|
|
SignatureData? clientSignature = null;
|
|
if (useSecurity)
|
|
{
|
|
SecurityPolicyInfo securityPolicy =
|
|
SecurityPolicies.Default.GetInfo(endpoint.SecurityPolicyUri!)!;
|
|
using CertificateCollection serverCertificateChain =
|
|
Utils.ParseCertificateChainBlob(
|
|
createSessionResponse.ServerCertificate,
|
|
server.MessageContext.Telemetry);
|
|
byte[] dataToSign = securityPolicy.GetClientSignatureData(
|
|
secureChannelContext.ChannelThumbprint.ToArrayOrNull(),
|
|
createSessionResponse.ServerNonce.ToArray(),
|
|
serverCertificateChain[0].RawData,
|
|
secureChannelContext.ServerChannelCertificate.ToArrayOrNull(),
|
|
secureChannelContext.ClientChannelCertificate.ToArrayOrNull(),
|
|
clientNonce.ToArray());
|
|
clientSignature = SecurityPolicies.Default.CreateSignatureData(
|
|
securityPolicy,
|
|
clientCertificate!,
|
|
dataToSign);
|
|
}
|
|
|
|
requestHeader.AuthenticationToken = createSessionResponse.AuthenticationToken;
|
|
ActivateSessionResponse activateSessionResponse = await server.ActivateSessionAsync(
|
|
secureChannelContext,
|
|
requestHeader,
|
|
clientSignature,
|
|
[],
|
|
localeIds.IsNull ? [] : localeIds,
|
|
identityToken != null ? new ExtensionObject(identityToken) : default,
|
|
null,
|
|
RequestLifetime.None).ConfigureAwait(false);
|
|
ValidateResponse(activateSessionResponse.ResponseHeader);
|
|
|
|
return (requestHeader, secureChannelContext);
|
|
}
|
|
finally
|
|
{
|
|
clientCertificate?.Dispose();
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Close a session.
|
|
/// </summary>
|
|
/// <param name="server">The server where the session is active.</param>
|
|
/// <param name="requestHeader">The request header of the session.</param>
|
|
public static async Task CloseSessionAsync(
|
|
this SessionServerBase server,
|
|
SecureChannelContext secureChannelContext,
|
|
RequestHeader requestHeader,
|
|
CancellationToken ct)
|
|
{
|
|
// close session
|
|
using var requestLifetime = new RequestLifetime(ct);
|
|
CloseSessionResponse response = await server.CloseSessionAsync(
|
|
secureChannelContext,
|
|
requestHeader,
|
|
true,
|
|
requestLifetime).ConfigureAwait(false);
|
|
ValidateResponse(response.ResponseHeader);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Validate the response of a service call.
|
|
/// </summary>
|
|
/// <param name="header">The response header of the service call.</param>
|
|
/// <exception cref="ServiceResultException"></exception>
|
|
public static void ValidateResponse(ResponseHeader header)
|
|
{
|
|
if (header == null)
|
|
{
|
|
throw new ServiceResultException(
|
|
StatusCodes.BadUnknownResponse,
|
|
"Null header in response.");
|
|
}
|
|
|
|
if (StatusCode.IsBad(header.ServiceResult))
|
|
{
|
|
throw new ServiceResultException(
|
|
new ServiceResult(
|
|
header.ServiceResult,
|
|
header.ServiceDiagnostics,
|
|
header.StringTable));
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Validate the response of a service call and validate the number of items returned.
|
|
/// </summary>
|
|
/// <typeparam name="TRequest"></typeparam>
|
|
/// <typeparam name="TResponse"></typeparam>
|
|
/// <remarks>
|
|
/// On the client the generated code already validates the response but the
|
|
/// check is duplicated here to catch also issues when running tests within
|
|
/// the shared client/server context.
|
|
/// </remarks>
|
|
/// <param name="header">The response header of the service call.</param>
|
|
/// <param name="response">The list of returned values by the service call.</param>
|
|
/// <param name="request">The list of requests passed to the service call.</param>
|
|
/// <exception cref="ArgumentException"></exception>
|
|
/// <exception cref="ServiceResultException"></exception>
|
|
public static void ValidateResponse<TRequest, TResponse>(
|
|
ResponseHeader header,
|
|
ArrayOf<TResponse> response,
|
|
ArrayOf<TRequest> request)
|
|
{
|
|
ValidateResponse(header);
|
|
|
|
if (response is ArrayOf<DiagnosticInfo>)
|
|
{
|
|
throw new ArgumentException(
|
|
"Must call ValidateDiagnosticInfos() for ArrayOf<DiagnosticInfo>.",
|
|
nameof(response));
|
|
}
|
|
|
|
if (response.Count != request.Count)
|
|
{
|
|
throw ServiceResultException.Unexpected(
|
|
"The server returned {0} responses but {1} requests were made.",
|
|
response.Count,
|
|
request.Count);
|
|
}
|
|
|
|
for (int ii = 0; ii < response.Count; ii++)
|
|
{
|
|
if (response[ii] is null)
|
|
{
|
|
throw ServiceResultException.Unexpected(
|
|
"The server returned responses contain a null response at index {0}.", ii);
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Validate the diagnostic response of a service call.
|
|
/// </summary>
|
|
/// <typeparam name="TRequest"></typeparam>
|
|
/// <exception cref="ServiceResultException"></exception>
|
|
public static void ValidateDiagnosticInfos<TRequest>(
|
|
ArrayOf<DiagnosticInfo> response,
|
|
ArrayOf<TRequest> request,
|
|
ArrayOf<string> stringTable,
|
|
ILogger logger)
|
|
{
|
|
// returning an empty list for diagnostic info arrays is allowed.
|
|
if (response.Count != 0)
|
|
{
|
|
if (response.Count != request.Count)
|
|
{
|
|
throw ServiceResultException.Unexpected(
|
|
"The server forgot to fill in the DiagnosticInfos array correctly when returning an operation level error.");
|
|
}
|
|
|
|
// now validate the string table
|
|
if (!stringTable.IsEmpty)
|
|
{
|
|
for (int ii = 0; ii < response.Count; ii++)
|
|
{
|
|
if (response[ii] is DiagnosticInfo diagnosticInfo &&
|
|
!diagnosticInfo.IsNullDiagnosticInfo)
|
|
{
|
|
if (diagnosticInfo.NamespaceUri >= stringTable.Count ||
|
|
diagnosticInfo.SymbolicId >= stringTable.Count ||
|
|
diagnosticInfo.Locale >= stringTable.Count ||
|
|
diagnosticInfo.LocalizedText >= stringTable.Count)
|
|
{
|
|
throw ServiceResultException.Unexpected(
|
|
"The server forgot to fill in string table for the DiagnosticInfos " +
|
|
"array correctly when returning an operation level error.");
|
|
}
|
|
var serviceResult = new ServiceResult(
|
|
StatusCodes.Good,
|
|
ii,
|
|
response,
|
|
stringTable);
|
|
if (logger.IsEnabled(LogLevel.Information))
|
|
{
|
|
logger.LogInformation("DiagnosticInfo: {ServiceResult}", serviceResult);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Create a browse description from a node id collection.
|
|
/// </summary>
|
|
/// <param name="nodeIdCollection">The node id collection.</param>
|
|
/// <param name="template">The template for the browse description for each node id.</param>
|
|
public static ArrayOf<BrowseDescription> CreateBrowseDescriptionCollectionFromNodeId(
|
|
ArrayOf<NodeId> nodeIdCollection,
|
|
BrowseDescription template)
|
|
{
|
|
var browseDescriptionCollection = new List<BrowseDescription>();
|
|
foreach (NodeId nodeId in nodeIdCollection)
|
|
{
|
|
var browseDescription = (BrowseDescription)template.MemberwiseClone();
|
|
browseDescription.NodeId = nodeId;
|
|
browseDescriptionCollection.Add(browseDescription);
|
|
}
|
|
return browseDescriptionCollection;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Create the continuation point collection from the browse result
|
|
/// collection for the BrowseNext service.
|
|
/// </summary>
|
|
/// <param name="browseResultCollection">The browse result collection to use.</param>
|
|
/// <returns>The collection of continuation points for the BrowseNext service.</returns>
|
|
public static ArrayOf<ByteString> PrepareBrowseNext(
|
|
ArrayOf<BrowseResult> browseResultCollection)
|
|
{
|
|
var continuationPoints = new List<ByteString>();
|
|
foreach (BrowseResult browseResult in browseResultCollection)
|
|
{
|
|
if (!browseResult.ContinuationPoint.IsEmpty)
|
|
{
|
|
continuationPoints.Add(browseResult.ContinuationPoint);
|
|
}
|
|
}
|
|
return continuationPoints;
|
|
}
|
|
|
|
/// <summary>
|
|
/// A dictionary of all node attributes.
|
|
/// </summary>
|
|
public static readonly ReadOnlyDictionary<uint, DataValue> AttributesIds = new(
|
|
new SortedDictionary<uint, DataValue>
|
|
{
|
|
{ Attributes.NodeId, default },
|
|
{ Attributes.NodeClass, default },
|
|
{ Attributes.BrowseName, default },
|
|
{ Attributes.DisplayName, default },
|
|
{ Attributes.Description, default },
|
|
{ Attributes.WriteMask, default },
|
|
{ Attributes.UserWriteMask, default },
|
|
{ Attributes.DataType, default },
|
|
{ Attributes.ValueRank, default },
|
|
{ Attributes.ArrayDimensions, default },
|
|
{ Attributes.AccessLevel, default },
|
|
{ Attributes.UserAccessLevel, default },
|
|
{ Attributes.Historizing, default },
|
|
{ Attributes.MinimumSamplingInterval, default },
|
|
{ Attributes.EventNotifier, default },
|
|
{ Attributes.Executable, default },
|
|
{ Attributes.UserExecutable, default },
|
|
{ Attributes.IsAbstract, default },
|
|
{ Attributes.InverseName, default },
|
|
{ Attributes.Symmetric, default },
|
|
{ Attributes.ContainsNoLoops, default },
|
|
{ Attributes.DataTypeDefinition, default },
|
|
{ Attributes.RolePermissions, default },
|
|
{ Attributes.UserRolePermissions, default },
|
|
{ Attributes.AccessRestrictions, default },
|
|
{ Attributes.AccessLevelEx, default }
|
|
});
|
|
|
|
/// <summary>
|
|
/// Get free IP Port.
|
|
/// </summary>
|
|
public static int GetNextFreeIPPort()
|
|
{
|
|
var endpoint = new IPEndPoint(IPAddress.Any, 0);
|
|
using var socket = new Socket(
|
|
endpoint.AddressFamily,
|
|
SocketType.Stream,
|
|
ProtocolType.Tcp);
|
|
socket.Bind(endpoint);
|
|
if (socket.LocalEndPoint is IPEndPoint ep)
|
|
{
|
|
return ep.Port;
|
|
}
|
|
|
|
return 0;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Whether starting a server failed because the port it was asked to
|
|
/// bind is already taken, in which case picking another one and
|
|
/// retrying is worthwhile.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// The port handed out by <see cref="GetNextFreeIPPort"/> is only free
|
|
/// at the instant it is queried - the socket is closed again before the
|
|
/// server binds - so a parallel fixture or an unrelated process on the
|
|
/// agent can take it in between. How that surfaces depends on the
|
|
/// transport: the UA-TCP listener reports
|
|
/// <see cref="StatusCodes.BadNoCommunication"/>, while the HTTPS
|
|
/// listeners bind through Kestrel, which throws an
|
|
/// <see cref="System.IO.IOException"/> wrapping an
|
|
/// <c>AddressInUseException</c> and a
|
|
/// <see cref="SocketError.AddressAlreadyInUse"/>
|
|
/// <see cref="SocketException"/>. Only the former used to be retried,
|
|
/// so the https and opc.https fixtures failed their entire
|
|
/// OneTimeSetUp on a port collision.
|
|
/// </remarks>
|
|
/// <param name="exception">The exception the server start threw.</param>
|
|
public static bool IsPortUnavailable(Exception exception)
|
|
{
|
|
for (Exception current = exception; current != null; current = current.InnerException!)
|
|
{
|
|
if (current is ServiceResultException sre &&
|
|
sre.StatusCode == StatusCodes.BadNoCommunication)
|
|
{
|
|
return true;
|
|
}
|
|
|
|
if (current is SocketException socket &&
|
|
(socket.SocketErrorCode == SocketError.AddressAlreadyInUse ||
|
|
socket.SocketErrorCode == SocketError.AccessDenied))
|
|
{
|
|
return true;
|
|
}
|
|
|
|
// Kestrel reports the collision as
|
|
// Microsoft.AspNetCore.Connections.AddressInUseException. It
|
|
// normally carries the SocketException matched above as its
|
|
// inner exception, but match the type by name too so the
|
|
// detection does not depend on that - and so this file needs no
|
|
// reference to the ASP.NET Core connection abstractions.
|
|
if (current.GetType().Name == "AddressInUseException")
|
|
{
|
|
return true;
|
|
}
|
|
|
|
if (current is AggregateException aggregate)
|
|
{
|
|
foreach (Exception inner in aggregate.InnerExceptions)
|
|
{
|
|
if (IsPortUnavailable(inner))
|
|
{
|
|
return true;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
return false;
|
|
}
|
|
}
|
|
}
|