mirror of
https://github.com/OPCFoundation/UA-.NETStandard.git
synced 2026-10-22 17:50:03 +08:00
275c3800b5
# Description Adds supported live add, reload, and remove lifecycle operations for NodeManager instances on a running server. The change introduces a DI-backed `INodeManagerLifecycle` service with direct `StandardServer` access, generation-aware registration handles, copy-on-write routing, transactional prepare/commit/rollback, runtime NodeSet convenience APIs, append-only namespace updates, model and semantic change notifications, additive-compatible complex type priming, and complete teardown behavior. Lifecycle publication is coordinated with requests, sessions, subscriptions, monitored items, continuation points, and shutdown so retired managers cannot remain reachable or be disposed while still in use. Compatible monitored items transfer to replacement generations without a transient bad status. Removed or incompatible Nodes publish `BadNodeIdUnknown` as required by OPC UA Part 4 section 5.8.4.1, retain their MonitoredItem identity, and automatically recover when a compatible Node with the same NodeId returns. Registration is documented end to end in the new [docs/NodeManagerRegistration.md](docs/NodeManagerRegistration.md), which covers compile-time, startup, and runtime registration together with the guarantees for MonitoredItems, Browse continuation points, namespace indexes, DataTypes, and change notifications. ## Review feedback addressed Interface surface reduced, as requested: - `INodeManagerMonitoredItemTracker` folded into `ISubscriptionMonitoredItemLifecycle`. - `INodeManagerMutationCoordinator` and the asynchronous MonitoredItem recovery entry point folded into `IDynamicNodeManagerHost`. - `ISessionClosingRegistry` folded into `IServerInternal`, then replaced by `ISession.IsClosing`. - `ISubscriptionDeletionRegistry` folded into `ISubscriptionManager`, then removed entirely. - `INodeManagerContinuationPointTracker` folded into `ISession`. - The synchronous recovery entry point kept on its own `ISyncNodeManagerMonitoredItemRecovery`, because `AddPredefinedNode` cannot await; it still routes through the asynchronous `INodeManagerMonitoredItemLifecycle` that `AsyncNodeManagerAdapter` exposes. - `IMonitoredItemLifecycle` renamed to `IDetachableMonitoredItem`. Reach into the Subscription area reduced to the minimum the feature needs: - The lifecycle feature itself leaves `SubscriptionManager` almost untouched: two guards that reject a request from a Session that is closing, on `CreateSubscription` and on `TransferSubscriptions`, because it would create state that is about to be torn down. The deletion claim registry, the session closing gates, the closed-session bookkeeping and the deletion restore paths introduced by earlier revisions are gone. Transferring a subscription away from a session that is closing stays allowed, since that is the recovery path the service exists for; the race that exposed is fixed by serialising source-queue closure with the transfer rather than by rejecting it. - Queueing is disabled again for a MonitoredItem with `QueueSize <= 1`, as before this PR. Without a queue the Client is served the last sampled value, so the missing-Node notification simply becomes that value; losing values is expected for a MonitoredItem without queuing. - What remains of the notification is one `DataValue` plus one bool in `DataChangeQueueHandler`, mirroring the existing overflow pair, which stops it being the value discarded when a configured queue is full. - `MonitoredItem` keeps its original publish path, its original queue creation and restore paths, its original triggering behaviour, and no per-epoch bookkeeping. - `IStoredMonitoredItem` carries `IsDeleted` and `IsDetached`, so a restored item reports the state it was stored with rather than one inferred from the last value's StatusCode. Other feedback: - Documented `HostedNodeManagerLifecycle`, `IDynamicNodeManagerHost`, `NodeManagerRoutingTable`, and the `RequestManager` validation and request scopes. - Renamed `ValidateMonitoredItemAsync` to `CanAttachMonitoredItemAsync` and `RestoreMonitoredItemAsync` to `RecoverMonitoredItemAsync`, so the lifecycle API no longer collides with the durable Subscription `RestoreMonitoredItem` path used at server startup. - Removed the `CustomNodeManager2` dependency from the synchronous MonitoredItem recovery path. - `DataChangeQueueHandler` is back to the two constructors 1.5.378 shipped, each taking an optional `TimeProvider`. - Session closing is a one-way latch, and the Session is removed even when teardown throws. - Documented what a custom NodeManager has to implement to take part in live lifecycle operations, and which NodeManager implements `INodeManagerReloadParticipant` today. ## Fixes found during review - The guard that stops a NodeManager lifecycle operation being started from inside a service handler never fired. It was backed by an `AsyncLocal` written inside `async ValidateRequestAsync`, which is invisible to the caller that awaited it, so a lifecycle call from a NodeManager callback waited for its own request and held the lifecycle semaphore forever. The mark is now applied by the service dispatcher, and the drain is bounded so no path can wedge the lifecycle permanently. - `ValidateRequestAsync` is no longer virtual. An override that rejected a request after calling `base` left it registered forever; subclasses now use `OnRequestValidatedAsync`, whose failures complete the request. - A MonitoredItem deleted and disposed while a reload was handing it to the replacement NodeManager could be attached anyway. The item now reserves itself for the hand-over and the transition takes it back if it was disposed meanwhile. - The Overflow bit is recorded and applied when the value is published, as the surrounding design does, rather than written into the value at enqueue time. - MonitoredItem cleanup for a Subscription being deleted no longer passes null entries to `DeleteMonitoredItemsAsync`. - Browse continuation points of a retired NodeManager are persisted and disposed outside the Session lock. ## Open review discussions Three threads are open, replied to and awaiting reviewer decisions: separating service-call dispatch from NodeManager handling in `MasterNodeManager` (tracked as #4098), the request-scoping shape in `StandardServer`, and how much of the async MonitoredItem service implementation should stay in `Subscription`. Issue #4102 records a specification ambiguity found while implementing the missing-Node notification: Part 4 §5.8.4.1 makes it mandatory, but the protected over-capacity queue entry §5.13.1.5 defines applies to `EventQueueOverflowEventType` only, so the specification does not say how it survives a full queue. ## Validation - Full `Opc.Ua.Server.Tests` on net10.0: 3,768 passed, 5 skipped. - Lifecycle, MonitoredItem, Subscription and continuation point suites: 185 passed on net10.0 and 75 on net48. - Server builds complete with zero warnings or errors. - Two failures are pre-existing and unrelated: `DurableDataValueQueueVerifyReferenceBatchingAsync` (flaky `BatchPersistor` file contention, passes in isolation on net10.0 and net48) and `ConfigureApplicationBuildsSharedClientAndServerConfigurationAsync` (fails on a clean tree with these changes stashed). ## Related Issues - Fixes #3993 - Follow-up tracked in #4098
198 lines
7.7 KiB
C#
198 lines
7.7 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.IO;
|
|
using System.Threading.Tasks;
|
|
using Microsoft.Extensions.Logging;
|
|
using Opc.Ua;
|
|
using Opc.Ua.Server;
|
|
|
|
namespace Quickstarts.Servers
|
|
{
|
|
/// <summary>
|
|
/// Helpers to find node managers implemented in this library.
|
|
/// </summary>
|
|
public static class Utils
|
|
{
|
|
/// <summary>
|
|
/// Applies custom settings to quickstart servers for CTT run.
|
|
/// </summary>
|
|
public static async Task ApplyCTTModeAsync(TextWriter output, IStandardServer server)
|
|
{
|
|
var methodsToCall = new List<CallMethodRequest>();
|
|
int index = server.CurrentInstance.NamespaceUris.GetIndex(Alarms.Namespaces.Alarms);
|
|
if (index > 0)
|
|
{
|
|
try
|
|
{
|
|
methodsToCall.Add(
|
|
// Start the Alarms with infinite runtime
|
|
new CallMethodRequest
|
|
{
|
|
MethodId = new NodeId("Alarms.Start", (ushort)index),
|
|
ObjectId = new NodeId("Alarms", (ushort)index),
|
|
InputArguments = [new Variant(uint.MaxValue)]
|
|
});
|
|
var requestHeader = new RequestHeader
|
|
{
|
|
Timestamp = DateTime.UtcNow,
|
|
TimeoutHint = 10000
|
|
};
|
|
using var context = new OperationContext(requestHeader, null, RequestType.Call, RequestLifetime.None);
|
|
(ArrayOf<CallMethodResult> results, ArrayOf<DiagnosticInfo> diagnosticInfos) = await server.CurrentInstance.NodeManager.CallAsync(
|
|
context,
|
|
methodsToCall)
|
|
.ConfigureAwait(false);
|
|
foreach (CallMethodResult result in results)
|
|
{
|
|
if (ServiceResult.IsBad(result.StatusCode))
|
|
{
|
|
ILogger<StandardServer> logger =
|
|
server.CurrentInstance.Telemetry.CreateLogger<StandardServer>();
|
|
logger.ErrorCallingMethod(result.StatusCode);
|
|
}
|
|
}
|
|
output.WriteLine("The Alarms for CTT mode are active.");
|
|
return;
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
ILogger<StandardServer> logger = server.CurrentInstance.Telemetry.CreateLogger<StandardServer>();
|
|
logger.FailedToStartAlarmsForCtt(ex);
|
|
}
|
|
}
|
|
output.WriteLine(
|
|
"The alarms could not be enabled for CTT, the namespace does not exist.");
|
|
}
|
|
|
|
/// <summary>
|
|
/// Add all available node manager factories to the server.
|
|
/// </summary>
|
|
public static void AddDefaultNodeManagers(IStandardServer server)
|
|
{
|
|
foreach (INodeManagerFactory nodeManagerFactory in NodeManagerFactories)
|
|
{
|
|
server.AddNodeManager(nodeManagerFactory);
|
|
}
|
|
|
|
foreach (IAsyncNodeManagerFactory asyncFactory in AsyncNodeManagerFactories)
|
|
{
|
|
server.AddNodeManager(asyncFactory);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Add all available node manager factories to the server.
|
|
/// </summary>
|
|
public static void UseSamplingGroupsInReferenceNodeManager(
|
|
ReferenceServer.ReferenceServer server)
|
|
{
|
|
server.UseSamplingGroupsInReferenceNodeManager = true;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Enable provisioning mode in the ReferenceServer.
|
|
/// </summary>
|
|
public static void EnableProvisioningMode(
|
|
ReferenceServer.ReferenceServer server)
|
|
{
|
|
server.ProvisioningMode = true;
|
|
}
|
|
|
|
/// <summary>
|
|
/// The property with available node manager factories.
|
|
/// </summary>
|
|
public static ArrayOf<INodeManagerFactory> NodeManagerFactories
|
|
{
|
|
get
|
|
{
|
|
s_nodeManagerFactories ??= GetNodeManagerFactories();
|
|
return s_nodeManagerFactories.ToArrayOf();
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// The property with available async node manager factories.
|
|
/// </summary>
|
|
public static ArrayOf<IAsyncNodeManagerFactory> AsyncNodeManagerFactories
|
|
{
|
|
get
|
|
{
|
|
s_asyncNodeManagerFactories ??= GetAsyncNodeManagerFactories();
|
|
return s_asyncNodeManagerFactories.ToArrayOf();
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Enumerates all node manager factories.
|
|
/// </summary>
|
|
private static List<INodeManagerFactory> GetNodeManagerFactories()
|
|
{
|
|
List<INodeManagerFactory> nodeManagerFactories = [];
|
|
|
|
nodeManagerFactories.Add(new MemoryBuffer.MemoryBufferNodeManagerFactory());
|
|
nodeManagerFactories.Add(new Boiler.BoilerNodeManagerFactory());
|
|
|
|
return nodeManagerFactories;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Enumerates all async node manager factories.
|
|
/// </summary>
|
|
private static List<IAsyncNodeManagerFactory> GetAsyncNodeManagerFactories()
|
|
{
|
|
List<IAsyncNodeManagerFactory> factories = [];
|
|
|
|
factories.Add(new TestData.TestDataNodeManagerFactory());
|
|
factories.Add(new Alarms.AlarmNodeManagerFactory());
|
|
|
|
return factories;
|
|
}
|
|
|
|
private static IList<INodeManagerFactory>? s_nodeManagerFactories;
|
|
private static IList<IAsyncNodeManagerFactory>? s_asyncNodeManagerFactories;
|
|
}
|
|
|
|
internal static partial class UtilsLog
|
|
{
|
|
[LoggerMessage(
|
|
EventId = QuickstartsServersEventIds.Utils + 0, Level = LogLevel.Error,
|
|
Message = "Error calling method with status code {StatusCode}.")]
|
|
public static partial void ErrorCallingMethod(this ILogger logger, StatusCode statusCode);
|
|
|
|
[LoggerMessage(
|
|
EventId = QuickstartsServersEventIds.Utils + 1, Level = LogLevel.Error,
|
|
Message = "Failed to start alarms for CTT.")]
|
|
public static partial void FailedToStartAlarmsForCtt(this ILogger logger, Exception exception);
|
|
}
|
|
|
|
}
|