mirror of
https://github.com/OPCFoundation/UA-.NETStandard.git
synced 2026-10-18 06:31:35 +08:00
a0d569d756
## Summary Fixes the findings of a bug audit of `Opc.Ua.Server`, `Opc.Ua.Gds.Server` and `Opc.Ua.Gds.Client`. Rebased on master after #4516. What went in: - **Audit:** 93 findings, each checked against the OPC UA specification. - **Code review of those fixes:** 35 further findings. - **Spec grounding of every fix commit:** 18 conformance gaps, now closed. Commits are one per finding, named `Fix <ID>`, `Fix review <ID>` or `Fix spec gap <name>`. The IDs refer to the audit report (S = Server areas, G1 = GDS server, G2 = GDS client). Validation: - Each finding was traced in code and checked against OPC 10000 (parts 3, 4, 5, 9, 11, 12, 13, 18, 20). - Every fix commit was checked against the spec text again afterwards: 0 non-conformant, remaining gaps fixed. - Regression tests were added for most fixes. - Suites run on net10.0 before the rebase: Server, GDS, History, Configuration, Features, Core.Security, DI, Redundancy, LDS, InformationModel, PubSub.Server, Client, Sessions and the three Subscriptions suites, all green. The same suites on the rebased branch are still running; results will be posted as a comment. ## Behaviour and user-facing changes ### Secure defaults - **`Historize()` / `HistorianBuilder`** grant HistoryRead only. History writes need an explicit `historyAccessLevel: HistoryRead | HistoryWrite`. - **File-system mount:** - Anonymous sessions can no longer create, delete, move or open files for writing (`Bad_UserAccessDenied`). - UserWritable and UserExecutable now reflect the user. - `AllowAnonymousWrite` restores the old behaviour; the ReferenceServer sample turns it on. - **Default PKI root** for the hosted server, hosted GDS, hosted LDS and `OpcUaApplicationConfigurationProvider`: - Moved from the shared temp directory to `{LocalApplicationData}/OPC Foundation/{ApplicationName}/pki`, and startup fails if no per-user directory exists. - When certificate stores of an earlier version still exist under temp, a warning names both paths. Existing deployments that relied on the default get a new application certificate (and the hosted GDS a new CA) unless `PkiRoot` is set to the old path. - **GDS:** - `GdsServerOptions.AutoApprove` defaults to `false`. - The default KeyCredential store grants no roles unless `AuthorizeRoles` allows them. - Certificate requests (StartSigningRequest, StartNewKeyPairRequest, FinishRequest) need an encrypted channel. - **Hosted server anonymous logins:** - Anonymous is rejected (`Bad_IdentityTokenRejected`) when the default authenticator options disable it. - A custom `AddIdentityAuthenticator<T>()` on its own no longer disables anonymous. - With anonymous disabled and no configured token policies, the endpoint advertises the authenticators' token types instead of Anonymous. - **Runtime-added roles:** their properties and methods need SecurityAdmin over an encrypted channel, like the well-known roles. - **Disabled users:** users disabled through Part 18 UserManagement can no longer log in through `RegisterDefaultAuthenticators(IUserDatabase)`. ### GDS server (Part 12) - **Certificate requests:** - FinishRequest / ReadRequest with another application's RequestId returns `Bad_InvalidArgument`. - Every Start*Request returns a new RequestId. - A CSR without the ApplicationUri is rejected (`Bad_CertificateUriInvalid`). - An abstract or unsupported certificate type is rejected at Start (`Bad_InvalidArgument`). - **Private-key password:** no longer persisted in the JSON applications database. A password saved by an earlier version is read into memory once and dropped on the next save. - **CheckRevocationStatus:** validates offline against the GDS's own trust lists and CRLs. It returns Good for good GDS-issued certificates and `Bad_CertificateInvalid` for input that is not a certificate. - **Certificate-group trust lists:** - Writes need CertificateAuthorityAdmin; SecurityAdmin and application admins are read-only. - Writes are validated with the Part 4 certificate validation. - **AuthorizationService:** - The legacy RequestAccessToken applies `AccessControl` and issues the token for the session identity. - StartRequestToken passes the session identity to every identity-aware provider. - Unknown ResourceIds return `Bad_NotFound`. - Expired token requests and refresh tokens are pruned, with at most 10 000 pending requests (`Bad_TooManyOperations`). - **KeyCredential:** requests with PublicKey + SecurityPolicyUri are rejected with `Bad_SecurityPolicyRejected` (secret encryption is not implemented); a PublicKey without SecurityPolicyUri is rejected with `Bad_InvalidArgument`. - **Audit events:** access-token audit events no longer contain the password or token data. - **RegisterTickets / UnregisterTickets:** need the RegistrarAdmin role when called from a session. - **Managed application nodes:** moved from namespace 0 to their own namespace (`ManagedApplicationsNamespaceUri`); the NodeId is the ApplicationUri, and the mandatory child properties exist. - **Hosted GDS:** - New `GdsServerOptions.CertificateGroups` (`GdsCertificateGroupOptions`), bindable from configuration. - The mandatory DefaultApplicationGroup is always present. - The default CA subject uses the resolved application name. - **JSON applications database:** - A corrupt file throws instead of being silently replaced by an empty database. - Saves are atomic and write in place on bind mounts; on net8+ builds they also follow symlinks and keep the Unix file mode. - Issued certificates and trust-list links survive a reload. ### GDS client - **Trust-list download:** - Reads until an empty chunk (Part 20 short reads). - A size-limit rejection of the final end-of-file read, as sent by released servers, counts as end of file. - **Default certificate group:** a null group means DefaultApplicationGroup, and vendor groups in other namespaces are no longer mistaken for well-known groups. - **Status codes and errors:** - Missing directory proxies report `Bad_ServerNotConnected`. - Short or wrongly typed method outputs throw `BadUnexpectedError` / `BadTypeMismatch`. - **GdsAccessTokenProvider:** no longer caches a failed client task, and one caller's cancellation no longer fails other callers. ### Trust lists, push and ConfigurationFile (Part 12 / Part 20) - **AddCertificate:** - `IsTrustedCertificate=false` returns `Bad_CertificateInvalid`. - Added certificates are validated (Part 4), and a certificate revoked by a current CRL returns `Bad_CertificateRevoked`. - **CloseAndUpdate:** validates the uploaded list against its own certificates and CRLs, not the stores it replaces. Validation failures are no longer recorded in the server's Rejected store. - **RemoveCertificate:** removing a trusted or issuer CA that other certificates still need returns `Bad_CertificateChainIncomplete`. - **Handles:** - Several read handles may be open at once. - Any open while a write handle exists returns `Bad_NotReadable` / `Bad_NotWritable`. - A write open while any handle is open returns `Bad_NotWritable`. - Handles of closed sessions are released. - Idle handles close after ActivityTimeout (default 60 s). - **Status codes:** - Read clamps to the remaining bytes and no longer enforces the size limit. - Oversized Write / AddCertificate returns `Bad_RequestTooLarge`. - Unsupported open modes return `Bad_NotSupported`. - **ConfigurationFile.CloseAndUpdate:** - Empty Targets return `Bad_InvalidArgument`. - The ConfigurationUpdatedAuditEvent is raised with the configuration owner as source. - With the new `IApplicationConfigurationFileTargetProvider`, providers receive the Targets, a bad target returns Uncertain with per-target results, and session-interrupting updates are applied after RestartDelayTime. - **Default namespace permissions:** namespaces registered after the first permission lookup now get their NamespaceMetadata default RolePermissions and AccessRestrictions (no stale negative cache). ### Sessions, identity and roles (Part 18) - **Session timeouts:** a failure closing one timed-out session no longer stops the session-timeout monitor. - **ChangePassword:** an empty old password returns `Bad_IdentityTokenInvalid`. - **Removing or disabling a user:** closes only that user's UserName-token sessions. - **Role configuration changes:** roles granted by an `ImpersonateUser` mapping are kept. - **X509Subject rules:** a certificate subject value containing a quote never matches an X509Subject rule. - **`ImpersonateUser` callback:** no longer runs under the global session lock. - **Session diagnostics:** LocaleIds are kept as the client sent them, while null LocaleIds are ignored for translation. ### Subscriptions and monitored items (Part 4) - **Acknowledgements:** a failing acknowledgement returns a per-entry Bad status instead of failing the whole Publish. - **`DiscardedMessageCount`:** counts messages dropped from the retransmission queue and unsent overflow messages. - **Durable subscriptions:** transferring a restored anonymous subscription works (no NullReferenceException). - **Transferred subscriptions:** sampling and permission checks use the item's current owner session. - **Access denied:** a monitored item whose user may no longer read the attribute gets a `Bad_UserAccessDenied` notification instead of going silent. Non-Value attributes need Browse permission (RolePermissions needs ReadRolePermissions), and User* attributes are evaluated per subscriber. - **ModifyMonitoredItems:** a SamplingInterval of -1 uses the subscription's publishing interval. - **AggregateFilter priming:** needs HistoryRead / ReadHistory permission and is bounded (100 000 values, bounded page size). - **Resource leak:** event monitored items no longer leak a consumer task per create/delete cycle. ### Node management services (Part 3 / Part 4) - **Reference types:** AddNodes, AddReferences, DeleteReferences and Browse reject ids that are not ReferenceTypes with `Bad_ReferenceTypeIdInvalid`. AddNodes, AddReferences and DeleteReferences also reject abstract ReferenceTypes; Browse still accepts them (e.g. `HierarchicalReferences` with includeSubtypes). - **Concurrent AddNodes:** duplicate BrowseNames under one parent get `Bad_BrowseNameDuplicated`. - **TranslateBrowsePathsToNodeIds:** - Requires Browse permission on intermediate nodes and final targets (RolePermissions and AccessRestrictions). - A long RelativePath no longer rejects the whole request. - **SemanticChangeEvent:** - Raised once per actual change of a semantic property, whether or not it is monitored. - Also raised for properties with the SemanticChange access-level bit. - Reports the owning node's TypeDefinition as AffectedType. - **Localized diagnostics:** operation-level text is translated when OperationLocalizedText is requested. ### History and aggregates (Part 11 / Part 13) - **DeleteRawModified:** an unspecified or reversed range returns `Bad_InvalidTimestampArgument`, and StartTime == EndTime deletes the value at StartTime for every provider. - **ReadAtTime fallback:** reads only the values around each requested time. A time whose bound is not found within the search limit returns `Bad_BoundNotSupported` instead of failing the request. - **ReadProcessed:** a ProcessingInterval shorter than one tick returns `Bad_AggregateInvalidInputs`. - **Delta / DeltaBounds:** widen to the next larger signed type when the result does not fit the source type (e.g. a decreasing unsigned counter, or an Int16 overflow). - **Range / Range2:** return the source data type. ### Alarms and fluent API (Part 9) - **Suppression:** an alarm stays suppressed while any suppression group is active, and re-evaluation without a state change does not move TransitionTime. - **`MonitorVariable(variable)`:** sets SourceNode, SourceName and InputNode to the variable and makes it a ConditionSource (HasCondition to the alarm, HasEventSource from the object). - **Fluent input/output arguments:** InputArguments / OutputArguments added through the fluent API to a registered method are readable. - **Root notifiers:** a failed root-notifier registration no longer leaves an orphaned event worker. - **State-machine handlers:** exceptions are logged at Error. ### File system (Part 20) - **Delete / MoveOrCopy:** - Only act on direct children of the directory. - A NodeId whose kind does not match the entry returns `Bad_NotFound` (a file NodeId can no longer delete a directory). - Copying a directory into its own subtree returns `Bad_InvalidArgument`. - **Locking:** - An open file, or a directory containing one, cannot be deleted or moved (`Bad_InvalidState`). - The check is atomic with opens. - While a Delete or Move runs, read opens get `Bad_NotReadable` and write opens `Bad_InvalidState`. - **Open:** - Reserved mode bits or EraseExisting without Write return `Bad_InvalidArgument`. - Read+Write returns `Bad_NotSupported`. - Read while a writer is open returns `Bad_NotReadable`. - **Client `FileSystemErrors`:** maps `Bad_NotReadable` to `IOException`. - **RuntimeNodeSet:** well-formed NodeSets with a stray `Model` element, or two models in one file where one requires the other, now load. ### Server core, hosting and lifecycle - **`SessionEstablishmentQueueLimit` > 0:** CreateSession/ActivateSession now queue for a permit. The permit is acquired before the request is registered, and a waiting handshake releases its worker through the request-parking policy. - **Node manager lifecycle:** - Add, reload and remove no longer wait for parked Publish requests. - A Migrate reload racing with CreateMonitoredItems no longer blocks later lifecycle operations. - Late items on retired or removed managers get `Bad_NodeIdUnknown`. - **HistoryUpdate:** a batch mixing data and event details is bounded by both limits. - **Server stop/start:** stopping the server disposes the configuration watcher and certificate subscription; starting recreates them. - **Monitored-item queue factory:** a factory supplied by the caller or the DI container is no longer disposed by the server. - **Audit events:** each certificate validation error raises its own AuditCertificate event. A failed OpenSecureChannel without a service result is audited as failed. ## New public API (additive) - `IQueuedSessionEstablishmentLimiter` - `StandardServer.OwnsMonitoredItemQueueFactory` (protected virtual) - `DefaultPkiRoot.Get` (Opc.Ua.Configuration) - `TrustList.SetCertificateValidation` - `NamespaceMetadataRegistry.Invalidate` - `IApplicationConfigurationFileTargetProvider` and `ApplicationConfigurationUpdatePlan` - `GdsServerOptions.CertificateGroups` / `GdsCertificateGroupOptions` - `InMemoryKeyCredentialRequestStore.AuthorizeRoles` - `DefaultManagedApplicationsNodeManager.ManagedApplicationsNamespaceUri` - `AuthorizationServiceManager.RequestAccessTokenAsync(..., IUserIdentity?, ...)` - `AllowAnonymousWrite` on the file-system node manager and its factory - `IFileSystemHost.TryBeginMutation` / `EndMutation`, replacing `HasOpenHandles` ## Not fixed / known limitations - **KeyCredential:** secret encryption with the client's PublicKey (requests needing it are rejected). - **CSR SAN restriction:** restricting subject / SAN values copied from a CSR (CA policy). - **Ticket signatures:** ticket signature verification (needs a trusted-signer configuration). - **FileType Read+Write open:** needs a read/write stream contract in `IFileSystemProvider`. - **Custom `IUserDatabase` implementations:** the disabled-user check still scans all users per login. The built-in stores do a single lookup. - **64-bit Delta precision:** limited by the calculator's double arithmetic. ## Tests with changed expectations Existing tests were updated where they asserted the old behaviour: - File-system status codes - Trust-list handle eviction - `DiscardedMessageCount` - Localized diagnostics bits - Delta on unsigned sources - SourceNode of fluent alarms - ReferenceServer transfer permission test (now expects `Bad_UserAccessDenied` notifications) - `UserDeactivationShutdownReviewTests` (the revoked session is a UserName login) 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
739 lines
31 KiB
C#
739 lines
31 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.Linq;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
using Microsoft.Extensions.Logging;
|
|
using Opc.Ua;
|
|
using Opc.Ua.Redundancy;
|
|
using Opc.Ua.Redundancy.Server;
|
|
using Opc.Ua.Server;
|
|
using Opc.Ua.Server.Fluent;
|
|
using Opc.Ua.Server.Historian;
|
|
using Opc.Ua.Server.Hosting;
|
|
|
|
namespace RedundantServer
|
|
{
|
|
/// <summary>
|
|
/// Factory that produces <see cref="HaSampleNodeManager"/> instances for DI-hosted servers.
|
|
/// </summary>
|
|
public sealed class HaSampleNodeManagerFactory : IAsyncNodeManagerFactory
|
|
{
|
|
/// <summary>
|
|
/// Shared namespace reserved at the same index before every replica's node managers are created.
|
|
/// </summary>
|
|
public const string NamespaceUri = "http://opcfoundation.org/UA/Samples/HighAvailability";
|
|
private readonly ILeaderElection m_leaderElection;
|
|
private readonly HaSampleReplicaInfo m_replicaInfo;
|
|
private readonly IDistributedValueCache? m_valueCache;
|
|
private readonly SharedKeyValueHistorianProvider? m_historian;
|
|
|
|
/// <summary>
|
|
/// Creates a factory using the distributed leader-election service registered by the host.
|
|
/// </summary>
|
|
/// <param name="leaderElection">The leader-election service that identifies the active writer replica.</param>
|
|
/// <param name="replicaInfo">The local replica identity published by sample variables.</param>
|
|
/// <param name="valueCaches">
|
|
/// The distributed value cache registered by <c>UseDistributedAddressSpace</c>, when present. Injected as
|
|
/// a sequence so active/active and single-instance topologies (which register no cache) resolve to empty.
|
|
/// </param>
|
|
public HaSampleNodeManagerFactory(
|
|
ILeaderElection leaderElection,
|
|
HaSampleReplicaInfo replicaInfo,
|
|
IEnumerable<IDistributedValueCache> valueCaches,
|
|
IEnumerable<SharedKeyValueHistorianProvider> historians)
|
|
{
|
|
m_leaderElection = leaderElection ?? throw new ArgumentNullException(nameof(leaderElection));
|
|
m_replicaInfo = replicaInfo ?? throw new ArgumentNullException(nameof(replicaInfo));
|
|
m_valueCache = valueCaches?.FirstOrDefault();
|
|
m_historian = historians?.FirstOrDefault();
|
|
}
|
|
|
|
/// <inheritdoc/>
|
|
public ArrayOf<string> NamespacesUris => [NamespaceUri];
|
|
|
|
/// <inheritdoc/>
|
|
public ValueTask<IAsyncNodeManager> CreateAsync(
|
|
IServerInternal server,
|
|
ApplicationConfiguration configuration,
|
|
CancellationToken cancellationToken = default)
|
|
{
|
|
_ = configuration;
|
|
_ = cancellationToken;
|
|
|
|
#pragma warning disable CA2000 // ownership transfers to the server
|
|
var manager = new HaSampleNodeManager(
|
|
server,
|
|
m_leaderElection,
|
|
m_replicaInfo,
|
|
m_valueCache,
|
|
m_historian,
|
|
[.. NamespacesUris]);
|
|
#pragma warning restore CA2000
|
|
return new ValueTask<IAsyncNodeManager>(manager);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Carries the local replica identity into sample node managers created by dependency injection.
|
|
/// </summary>
|
|
public sealed class HaSampleReplicaInfo
|
|
{
|
|
/// <summary>
|
|
/// Creates a replica identity descriptor.
|
|
/// </summary>
|
|
/// <param name="nodeId">The unique local high-availability node id.</param>
|
|
public HaSampleReplicaInfo(string nodeId)
|
|
{
|
|
NodeId = nodeId;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Gets the unique local high-availability node id.
|
|
/// </summary>
|
|
public string NodeId { get; }
|
|
}
|
|
|
|
/// <summary>
|
|
/// Starts the sample producer after distributed services and redundancy metadata are initialized.
|
|
/// </summary>
|
|
internal sealed class HaSampleSimulationStartupTask : IServerStartupTask
|
|
{
|
|
/// <inheritdoc/>
|
|
public ValueTask OnServerStartedAsync(
|
|
IServerContext server,
|
|
CancellationToken cancellationToken = default)
|
|
{
|
|
if (server == null)
|
|
{
|
|
throw new ArgumentNullException(nameof(server));
|
|
}
|
|
|
|
cancellationToken.ThrowIfCancellationRequested();
|
|
foreach (HaSampleNodeManager manager in server.FindNodeManagers<HaSampleNodeManager>())
|
|
{
|
|
manager.StartSimulation();
|
|
}
|
|
return default;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Minimal <see cref="FluentNodeManagerBase"/> address space that participates in distributed replication.
|
|
/// </summary>
|
|
public sealed class HaSampleNodeManager : FluentNodeManagerBase
|
|
{
|
|
private readonly ILeaderElection m_leaderElection;
|
|
private readonly HaSampleReplicaInfo m_replicaInfo;
|
|
private readonly IDistributedValueCache? m_valueCache;
|
|
private readonly SharedKeyValueHistorianProvider? m_historian;
|
|
private readonly CancellationTokenSource m_simulationCts = new();
|
|
private readonly Lock m_updateLock = new();
|
|
private static readonly TimeSpan s_valueFreshness = TimeSpan.FromSeconds(10);
|
|
private const string kSampleFolderName = "HighAvailability";
|
|
private FolderState? m_folder;
|
|
private BaseVariableState? m_counter;
|
|
private BaseVariableState? m_activeReplica;
|
|
private BaseObjectState? m_historyEvents;
|
|
private Task? m_simulationTask;
|
|
private int m_counterValue;
|
|
|
|
/// <summary>
|
|
/// Creates the high-availability sample node manager.
|
|
/// </summary>
|
|
/// <param name="server">The server that owns the node manager.</param>
|
|
/// <param name="leaderElection">The leader-election service that gates sample writes.</param>
|
|
/// <param name="replicaInfo">The local replica identity published by sample variables.</param>
|
|
/// <param name="valueCache">
|
|
/// The distributed value cache used to share the Counter value across the replica set, or <c>null</c> when
|
|
/// the topology registers none (active/active and single-instance).
|
|
/// </param>
|
|
/// <param name="historian">
|
|
/// The shared historian used by strong active/passive deployments, or <c>null</c> for other topologies.
|
|
/// </param>
|
|
/// <param name="namespaceUris">The namespace URIs exposed by this node manager.</param>
|
|
public HaSampleNodeManager(
|
|
IServerInternal server,
|
|
ILeaderElection leaderElection,
|
|
HaSampleReplicaInfo replicaInfo,
|
|
IDistributedValueCache? valueCache,
|
|
SharedKeyValueHistorianProvider? historian,
|
|
params string[] namespaceUris)
|
|
: base(server, namespaceUris)
|
|
{
|
|
m_leaderElection = leaderElection ?? throw new ArgumentNullException(nameof(leaderElection));
|
|
m_replicaInfo = replicaInfo ?? throw new ArgumentNullException(nameof(replicaInfo));
|
|
m_valueCache = valueCache;
|
|
m_historian = historian;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Mints the browse name as the identifier, for the handful of nodes
|
|
/// this sample publishes by name.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// <para>
|
|
/// Those identifiers are part of the sample's contract - the redundant
|
|
/// client addresses <c>ns=N;s=Counter</c> directly - so they cannot be
|
|
/// left to the derived form the default factory mints.
|
|
/// </para>
|
|
/// <para>
|
|
/// Every other node keeps that derived form, and the narrowness
|
|
/// matters: a browse name is only unique among its siblings, and the
|
|
/// historian hangs an <c>HA Configuration</c> object off each node it
|
|
/// historizes, so a blanket rule would hand the Counter's and the
|
|
/// HistoryEvents' one the same identifier. An identifier a caller
|
|
/// already chose here is kept, on the default factory's own terms.
|
|
/// </para>
|
|
/// </remarks>
|
|
public override NodeId New(ISystemContext context, NodeState node)
|
|
{
|
|
if (node == null)
|
|
{
|
|
return base.New(context, node!);
|
|
}
|
|
|
|
ushort namespaceIndex = NamespaceIndexes[0];
|
|
if (!node.NodeId.IsNull &&
|
|
(node.NodeId.NamespaceIndex == namespaceIndex ||
|
|
node is not BaseInstanceState { Parent: not null }))
|
|
{
|
|
return node.NodeId;
|
|
}
|
|
|
|
return IsPublishedByName(node)
|
|
? new NodeId(node.BrowseName.Name!, namespaceIndex)
|
|
: base.New(context, node);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Whether <paramref name="node"/> is the sample folder or one of the
|
|
/// nodes directly beneath it - the ones a client spells out.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// The folder reaches this before it has been staged, so it has no
|
|
/// parent yet and is recognised by its browse name instead.
|
|
/// </remarks>
|
|
private bool IsPublishedByName(NodeState node)
|
|
{
|
|
if (string.IsNullOrEmpty(node.BrowseName.Name))
|
|
{
|
|
return false;
|
|
}
|
|
|
|
NodeState? parent = (node as BaseInstanceState)?.Parent;
|
|
return parent == null
|
|
? node.BrowseName.Name == kSampleFolderName
|
|
: ReferenceEquals(parent, m_folder);
|
|
}
|
|
|
|
/// <inheritdoc/>
|
|
public override async ValueTask CreateAddressSpaceAsync(
|
|
IDictionary<NodeId, IList<IReference>> externalReferences,
|
|
CancellationToken cancellationToken = default)
|
|
{
|
|
NodeManagerBuilder builder = CreateFluentBuilder(NamespaceIndexes[0]);
|
|
|
|
// Unparented, so the staged folder organises itself under the
|
|
// Objects folder; the manager used to add that reference and its
|
|
// externalReferences counterpart by hand.
|
|
INodeBuilder<FolderState> folder = builder.AddFolder(kSampleFolderName);
|
|
folder.Node.DisplayName = new LocalizedText("en", "High Availability");
|
|
NodeId folderId = folder.Node.NodeId;
|
|
|
|
// New() names the folder's direct children after their browse
|
|
// name, so it has to know which node the folder is.
|
|
m_folder = folder.Node;
|
|
|
|
m_counter = AddSampleVariable<int>(builder, folderId, "Counter", Variant.From(0));
|
|
if (m_valueCache != null)
|
|
{
|
|
// Opt the Counter's read/write callbacks into the distributed
|
|
// value cache (extension beyond OPC 10000-4 §6.6): the active
|
|
// replica caches each new value write-through, and every replica
|
|
// serves the last value shared through the store while it is
|
|
// fresh (falling back to the local value). This is how the
|
|
// Counter is shared across the set and continues after failover;
|
|
// monitored items keep reading through the normal pipeline.
|
|
m_counter.EnableDistributedValueParticipation(
|
|
m_valueCache,
|
|
s_valueFreshness,
|
|
_ => new ValueTask<DataValue>(ReadLocalCounter()));
|
|
}
|
|
|
|
m_activeReplica = AddSampleVariable<string>(
|
|
builder,
|
|
folderId,
|
|
"ActiveReplica",
|
|
Variant.From("unknown"));
|
|
|
|
m_historyEvents = builder.AddObject("HistoryEvents", folderId).Node;
|
|
m_historyEvents.ReferenceTypeId = ReferenceTypeIds.Organizes;
|
|
m_historyEvents.DisplayName = new LocalizedText("en", "History Events");
|
|
m_historyEvents.EventNotifier = EventNotifiers.SubscribeToEvents;
|
|
|
|
// Deliberately not staged: this subtree exists to show what a
|
|
// factory-assigned identity looks like next to the named ones
|
|
// above, so it keeps minting through the NodeIdFactory itself
|
|
// rather than through New. Attaching it once the folder has been
|
|
// staged leaves those identifiers untouched, and the subtree is
|
|
// still registered as part of the folder's.
|
|
AddFactoryAssignedNodes(folder.Node, NamespaceIndexes[0]);
|
|
|
|
if (m_historian != null)
|
|
{
|
|
#pragma warning disable CA2000 // ownership transfers to the server's historian-builder registry
|
|
HistorianBuilder historian = new HistorianBuilder(Server)
|
|
.UseProvider(m_historian);
|
|
#pragma warning restore CA2000
|
|
await historian.HistorizeAsync(
|
|
m_counter,
|
|
SystemContext,
|
|
historyAccessLevel: AccessLevels.HistoryRead | AccessLevels.HistoryWrite,
|
|
capabilities: HistorianNodeCapabilities.DataReadWrite,
|
|
autoCapture: false,
|
|
cancellationToken: cancellationToken).ConfigureAwait(false);
|
|
await historian.HistorizeEventsAsync(
|
|
m_historyEvents,
|
|
SystemContext,
|
|
capabilities: HistorianNodeCapabilities.EventReadWrite with
|
|
{
|
|
EventTypes = [ObjectTypeIds.BaseEventType]
|
|
},
|
|
cancellationToken: cancellationToken).ConfigureAwait(false);
|
|
}
|
|
|
|
// Registering the staged subtree and re-running the reverse
|
|
// reference pass is what publishes the folder's inverse Organizes
|
|
// reference into externalReferences[ObjectsFolder].
|
|
await RegisterAuthoredNodesAsync(builder, cancellationToken).ConfigureAwait(false);
|
|
await CompleteConfigureAsync(externalReferences, cancellationToken)
|
|
.ConfigureAwait(false);
|
|
await SealConfigurationAsync(builder, cancellationToken).ConfigureAwait(false);
|
|
}
|
|
|
|
private void AddFactoryAssignedNodes(FolderState parent, ushort namespaceIndex)
|
|
{
|
|
var generated = new BaseObjectState(parent)
|
|
{
|
|
BrowseName = new QualifiedName("FactoryAssigned", namespaceIndex),
|
|
DisplayName = new LocalizedText("Factory-assigned identities"),
|
|
ReferenceTypeId = ReferenceTypeIds.HasComponent,
|
|
TypeDefinitionId = ObjectTypeIds.BaseObjectType
|
|
};
|
|
generated.NodeId = NodeIdFactory.New(SystemContext, generated);
|
|
parent.AddChild(generated);
|
|
var value = new BaseDataVariableState(generated)
|
|
{
|
|
BrowseName = new QualifiedName("Value", namespaceIndex),
|
|
DisplayName = new LocalizedText("Value"),
|
|
ReferenceTypeId = ReferenceTypeIds.HasComponent,
|
|
TypeDefinitionId = VariableTypeIds.BaseDataVariableType,
|
|
DataType = DataTypeIds.Int32,
|
|
ValueRank = ValueRanks.Scalar,
|
|
AccessLevel = AccessLevels.CurrentRead,
|
|
UserAccessLevel = AccessLevels.CurrentRead,
|
|
Value = Variant.From(12345),
|
|
StatusCode = StatusCodes.Good
|
|
};
|
|
value.NodeId = NodeIdFactory.New(SystemContext, value);
|
|
generated.AddChild(value);
|
|
var target = new BaseDataVariableState(generated)
|
|
{
|
|
BrowseName = new QualifiedName("Target", namespaceIndex),
|
|
DisplayName = new LocalizedText("Target"),
|
|
ReferenceTypeId = ReferenceTypeIds.HasComponent,
|
|
TypeDefinitionId = VariableTypeIds.BaseDataVariableType,
|
|
DataType = DataTypeIds.NodeId,
|
|
ValueRank = ValueRanks.Scalar,
|
|
AccessLevel = AccessLevels.CurrentRead,
|
|
UserAccessLevel = AccessLevels.CurrentRead,
|
|
Value = Variant.From(value.NodeId),
|
|
StatusCode = StatusCodes.Good
|
|
};
|
|
target.NodeId = NodeIdFactory.New(SystemContext, target);
|
|
generated.AddChild(target);
|
|
}
|
|
|
|
/// <inheritdoc/>
|
|
protected override void Dispose(bool disposing)
|
|
{
|
|
if (disposing)
|
|
{
|
|
m_simulationCts.Cancel();
|
|
m_simulationCts.Dispose();
|
|
}
|
|
base.Dispose(disposing);
|
|
}
|
|
|
|
/// <inheritdoc/>
|
|
protected override IHistorianProvider? GetHistorianProvider(NodeState node)
|
|
{
|
|
return m_historian ?? base.GetHistorianProvider(node);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Stages one writable sample variable under the sample folder.
|
|
/// </summary>
|
|
/// <typeparam name="TValue">
|
|
/// CLR type the variable carries; the staged node takes its DataType
|
|
/// and ValueRank from it.
|
|
/// </typeparam>
|
|
/// <param name="builder">The fluent builder staging the subtree.</param>
|
|
/// <param name="parentId">The folder the variable hangs off.</param>
|
|
/// <param name="name">Browse name of the variable.</param>
|
|
/// <param name="initialValue">The value a client reads before the
|
|
/// simulation has produced one.</param>
|
|
private static BaseVariableState AddSampleVariable<TValue>(
|
|
NodeManagerBuilder builder,
|
|
NodeId parentId,
|
|
string name,
|
|
Variant initialValue)
|
|
{
|
|
BaseVariableState variable = builder
|
|
.AddVariable<TValue>(name, parentId)
|
|
.Writable()
|
|
.Node;
|
|
|
|
// The sample organises its variables rather than componentising
|
|
// them, which is the shape the redundant client browses.
|
|
variable.ReferenceTypeId = ReferenceTypeIds.Organizes;
|
|
variable.DisplayName = new LocalizedText("en", name);
|
|
variable.Value = initialValue;
|
|
variable.StatusCode = StatusCodes.Good;
|
|
variable.Timestamp = DateTime.UtcNow;
|
|
return variable;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Starts the replica's simulation loop if it has not already been started.
|
|
/// </summary>
|
|
internal void StartSimulation()
|
|
{
|
|
m_simulationTask ??= Task.Run(() => RunSimulationAsync(m_simulationCts.Token));
|
|
}
|
|
|
|
private async Task RunSimulationAsync(CancellationToken cancellationToken)
|
|
{
|
|
using var timer = new PeriodicTimer(TimeSpan.FromSeconds(1));
|
|
bool wasLeader = false;
|
|
DateTime lastHeartbeat = DateTime.MinValue;
|
|
while (await timer.WaitForNextTickAsync(cancellationToken).ConfigureAwait(false))
|
|
{
|
|
if (!m_leaderElection.IsLeader)
|
|
{
|
|
if (wasLeader)
|
|
{
|
|
// A failover moved the write role away from this replica.
|
|
m_logger.ReplicaBecameStandby(m_replicaInfo.NodeId);
|
|
}
|
|
wasLeader = false;
|
|
UpdateActiveReplica("standby");
|
|
continue;
|
|
}
|
|
|
|
if (!wasLeader)
|
|
{
|
|
// This replica has just become the active writer (initial
|
|
// election or a failover). Continue the Counter from the
|
|
// last value shared through the distributed store instead of
|
|
// restarting from the local count.
|
|
await SeedCounterFromCacheAsync(cancellationToken).ConfigureAwait(false);
|
|
if (m_logger.IsEnabled(LogLevel.Information))
|
|
{
|
|
m_logger.ReplicaBecameActiveWriter(
|
|
m_replicaInfo.NodeId,
|
|
Volatile.Read(ref m_counterValue));
|
|
}
|
|
wasLeader = true;
|
|
}
|
|
|
|
await UpdateCounterAsync(cancellationToken).ConfigureAwait(false);
|
|
UpdateActiveReplica(m_replicaInfo.NodeId);
|
|
|
|
// Periodic heartbeat so the log shows liveness, which replica is
|
|
// producing which Counter values, and (across replicas) the
|
|
// per-replica divergence a client observes on failover.
|
|
DateTime now = DateTime.UtcNow;
|
|
if (now - lastHeartbeat >= TimeSpan.FromSeconds(5))
|
|
{
|
|
lastHeartbeat = now;
|
|
if (m_logger.IsEnabled(LogLevel.Information))
|
|
{
|
|
m_logger.ReplicaActive(
|
|
m_replicaInfo.NodeId,
|
|
Volatile.Read(ref m_counterValue));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
private async Task UpdateCounterAsync(CancellationToken cancellationToken)
|
|
{
|
|
BaseVariableState? counter = m_counter;
|
|
if (counter == null)
|
|
{
|
|
return;
|
|
}
|
|
|
|
int value = Interlocked.Increment(ref m_counterValue);
|
|
DateTimeUtc timestamp = DateTimeUtc.Now;
|
|
var sample = new DataValue(
|
|
Variant.From(value),
|
|
StatusCodes.Good,
|
|
timestamp,
|
|
timestamp);
|
|
lock (m_updateLock)
|
|
{
|
|
counter.Value = value;
|
|
counter.Timestamp = timestamp.ToDateTime();
|
|
counter.ClearChangeMasks(SystemContext, false);
|
|
}
|
|
|
|
// Share the new value through the distributed store so standby
|
|
// replicas can serve it and a promoted replica continues from it.
|
|
if (m_valueCache != null)
|
|
{
|
|
try
|
|
{
|
|
await m_valueCache
|
|
.CacheAsync(
|
|
counter.NodeId,
|
|
sample,
|
|
cancellationToken)
|
|
.ConfigureAwait(false);
|
|
}
|
|
catch (InvalidOperationException)
|
|
{
|
|
// The distributed store is not ready yet (the server is
|
|
// still starting); the value is shared on the next tick.
|
|
}
|
|
}
|
|
|
|
bool historyReady = m_historian == null ||
|
|
await ArchiveCounterAsync(
|
|
counter,
|
|
sample,
|
|
cancellationToken).ConfigureAwait(false);
|
|
|
|
BaseObjectState? historyEvents = m_historyEvents;
|
|
if (historyEvents != null && historyReady)
|
|
{
|
|
var e = new BaseEventState(historyEvents);
|
|
e.Initialize(
|
|
SystemContext,
|
|
historyEvents,
|
|
EventSeverity.Low,
|
|
new LocalizedText(
|
|
$"Replica '{m_replicaInfo.NodeId}' archived counter {value}."));
|
|
try
|
|
{
|
|
await historyEvents.ReportEventAsync(
|
|
SystemContext,
|
|
e,
|
|
cancellationToken).ConfigureAwait(false);
|
|
}
|
|
catch (ServiceResultException exception)
|
|
{
|
|
m_logger.EventHistoryWriteFailed(
|
|
exception,
|
|
m_replicaInfo.NodeId);
|
|
}
|
|
}
|
|
}
|
|
|
|
private async Task<bool> ArchiveCounterAsync(
|
|
BaseVariableState counter,
|
|
DataValue sample,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
SharedKeyValueHistorianProvider? historian = m_historian;
|
|
if (historian == null || !m_leaderElection.IsLeader)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
try
|
|
{
|
|
using var operationContext = new OperationContext(
|
|
new RequestHeader(),
|
|
null,
|
|
RequestType.HistoryUpdate,
|
|
RequestLifetime.None);
|
|
var historianContext = new HistorianOperationContext(
|
|
SystemContext,
|
|
operationContext,
|
|
counter,
|
|
HistoryUpdateType.Insert);
|
|
HistorianUpdateOutcome<DataValue> outcome = await historian.InsertAsync(
|
|
historianContext,
|
|
counter.NodeId,
|
|
[sample],
|
|
cancellationToken).ConfigureAwait(false);
|
|
StatusCode status = outcome.OperationResults.Count == 1
|
|
? outcome.OperationResults[0]
|
|
: StatusCodes.BadUnexpectedError;
|
|
if (StatusCode.IsBad(status))
|
|
{
|
|
m_logger.CounterHistoryWriteRejected(
|
|
m_replicaInfo.NodeId,
|
|
status);
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
catch (Exception exception) when (
|
|
exception is ServiceResultException or
|
|
TimeoutException or
|
|
InvalidOperationException)
|
|
{
|
|
m_logger.CounterHistoryWriteFailed(
|
|
exception,
|
|
m_replicaInfo.NodeId);
|
|
return false;
|
|
}
|
|
}
|
|
|
|
private async Task SeedCounterFromCacheAsync(CancellationToken cancellationToken)
|
|
{
|
|
BaseVariableState? counter = m_counter;
|
|
if (m_valueCache == null || counter == null)
|
|
{
|
|
return;
|
|
}
|
|
|
|
try
|
|
{
|
|
(bool _, DataValue cached) = await m_valueCache
|
|
.TryGetAsync(counter.NodeId, s_valueFreshness, cancellationToken)
|
|
.ConfigureAwait(false);
|
|
if (cached.WrappedValue.TryGetValue(out int last) && last > Volatile.Read(ref m_counterValue))
|
|
{
|
|
Interlocked.Exchange(ref m_counterValue, last);
|
|
lock (m_updateLock)
|
|
{
|
|
counter.Value = last;
|
|
counter.Timestamp = DateTime.UtcNow;
|
|
counter.ClearChangeMasks(SystemContext, false);
|
|
}
|
|
}
|
|
}
|
|
catch (InvalidOperationException)
|
|
{
|
|
// The distributed store is not ready yet; start from the local
|
|
// value and share on the next tick.
|
|
}
|
|
}
|
|
|
|
private DataValue ReadLocalCounter()
|
|
{
|
|
return new DataValue(
|
|
Variant.From(Volatile.Read(ref m_counterValue)),
|
|
StatusCodes.Good,
|
|
DateTimeUtc.Now);
|
|
}
|
|
|
|
private void UpdateActiveReplica(string value)
|
|
{
|
|
BaseVariableState? activeReplica = m_activeReplica;
|
|
if (activeReplica == null)
|
|
{
|
|
return;
|
|
}
|
|
|
|
lock (m_updateLock)
|
|
{
|
|
activeReplica.Value = value;
|
|
activeReplica.Timestamp = DateTime.UtcNow;
|
|
activeReplica.ClearChangeMasks(SystemContext, false);
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Defines log messages for replica write roles, counter activity, and history capture.
|
|
/// </summary>
|
|
internal static partial class HaSampleNodeManagerLog
|
|
{
|
|
/// <summary>
|
|
/// Logs that a replica has relinquished the active writer role.
|
|
/// </summary>
|
|
[LoggerMessage(EventId = RedundantServerEventIds.HaSampleNodeManager + 0, Level = LogLevel.Information,
|
|
Message = "HA: replica {ReplicaId} became STANDBY (no longer the active writer).")]
|
|
public static partial void ReplicaBecameStandby(this ILogger logger, string replicaId);
|
|
|
|
/// <summary>
|
|
/// Logs that a replica has become the active writer and reports its counter value.
|
|
/// </summary>
|
|
[LoggerMessage(EventId = RedundantServerEventIds.HaSampleNodeManager + 1, Level = LogLevel.Information,
|
|
Message = "HA: replica {ReplicaId} became ACTIVE writer (Counter={Counter}).")]
|
|
public static partial void ReplicaBecameActiveWriter(this ILogger logger, string replicaId, int counter);
|
|
|
|
/// <summary>
|
|
/// Logs the active replica's heartbeat and current counter value.
|
|
/// </summary>
|
|
[LoggerMessage(EventId = RedundantServerEventIds.HaSampleNodeManager + 2, Level = LogLevel.Information,
|
|
Message = "HA: replica {ReplicaId} ACTIVE, Counter={Counter}.")]
|
|
public static partial void ReplicaActive(this ILogger logger, string replicaId, int counter);
|
|
|
|
/// <summary>
|
|
/// Logs a rejected counter history write and its status code.
|
|
/// </summary>
|
|
[LoggerMessage(EventId = RedundantServerEventIds.HaSampleNodeManager + 3, Level = LogLevel.Warning,
|
|
Message = "HA: replica {ReplicaId} could not archive the Counter sample ({StatusCode}).")]
|
|
public static partial void CounterHistoryWriteRejected(
|
|
this ILogger logger,
|
|
string replicaId,
|
|
StatusCode statusCode);
|
|
|
|
/// <summary>
|
|
/// Logs an exception while archiving a counter sample.
|
|
/// </summary>
|
|
[LoggerMessage(EventId = RedundantServerEventIds.HaSampleNodeManager + 4, Level = LogLevel.Warning,
|
|
Message = "HA: replica {ReplicaId} failed to archive the Counter sample.")]
|
|
public static partial void CounterHistoryWriteFailed(
|
|
this ILogger logger,
|
|
Exception exception,
|
|
string replicaId);
|
|
|
|
/// <summary>
|
|
/// Logs an exception while archiving a history event.
|
|
/// </summary>
|
|
[LoggerMessage(EventId = RedundantServerEventIds.HaSampleNodeManager + 5, Level = LogLevel.Warning,
|
|
Message = "HA: replica {ReplicaId} failed to archive the history event.")]
|
|
public static partial void EventHistoryWriteFailed(
|
|
this ILogger logger,
|
|
Exception exception,
|
|
string replicaId);
|
|
}
|
|
}
|