diff --git a/src/Configuration/OpcUaAppConfigFactory.cs b/src/Configuration/OpcUaAppConfigFactory.cs index 9b6fc885..049e687f 100644 --- a/src/Configuration/OpcUaAppConfigFactory.cs +++ b/src/Configuration/OpcUaAppConfigFactory.cs @@ -106,7 +106,7 @@ public async Task ConfigureAsync() .SetMaxRegistrationInterval(_config.OpcUa.LdsRegistrationInterval) // Enable auditing events and diagnostics. .SetDiagnosticsEnabled(true) - .SetAuditingEnabled(true) + .SetAuditingEnabled(false) // Set the server capabilities. .SetMaxSessionCount(_config.OpcUa.MaxSessionCount) .SetMaxSessionTimeout(_config.OpcUa.MaxSessionTimeout) diff --git a/src/PlcServer.cs b/src/PlcServer.cs index c985477c..6d5f89e7 100644 --- a/src/PlcServer.cs +++ b/src/PlcServer.cs @@ -1,16 +1,16 @@ -namespace OpcPlc; - -using AlarmCondition; -using Microsoft.Extensions.Logging; -using Opc.Ua; +namespace OpcPlc; + +using AlarmCondition; +using Microsoft.Extensions.Logging; +using Opc.Ua; using Opc.Ua.Bindings; -using Opc.Ua.Server; +using Opc.Ua.Server; using OpcPlc.CompanionSpecs.DI; using OpcPlc.Configuration; -using OpcPlc.DeterministicAlarms; +using OpcPlc.DeterministicAlarms; using OpcPlc.PluginNodes.Models; -using OpcPlc.Reference; -using SimpleEvents; +using OpcPlc.Reference; +using SimpleEvents; using System; using System.Collections.Generic; using System.Collections.Immutable; @@ -20,18 +20,18 @@ namespace OpcPlc; using System.Reflection; using System.Threading; -public partial class PlcServer : StandardServer +public partial class PlcServer : StandardServer { private const uint PlcShutdownWaitSeconds = 10; private const int PeriodicLoggingTimerSeconds = 60; - - public PlcNodeManager PlcNodeManager { get; set; } - public AlarmConditionServerNodeManager AlarmNodeManager { get; set; } + public PlcNodeManager PlcNodeManager { get; set; } + + public AlarmConditionServerNodeManager AlarmNodeManager { get; set; } - public SimpleEventsNodeManager SimpleEventsNodeManager { get; set; } + public SimpleEventsNodeManager SimpleEventsNodeManager { get; set; } - public ReferenceNodeManager SimulationNodeManager { get; set; } + public ReferenceNodeManager SimulationNodeManager { get; set; } public DeterministicAlarmsNodeManager DeterministicAlarmsNodeManager { get; set; } @@ -47,11 +47,11 @@ public partial class PlcServer : StandardServer private uint _countCreateSubscription; private uint _countCreateMonitoredItems; private uint _countRead; - private uint _countWrite; + private uint _countWrite; private uint _countPublish; - - public PlcServer(OpcPlcConfiguration config, PlcSimulation plcSimulation, TimeService timeService, ImmutableList pluginNodes, ILogger logger) - { + + public PlcServer(OpcPlcConfiguration config, PlcSimulation plcSimulation, TimeService timeService, ImmutableList pluginNodes, ILogger logger) + { Config = config; PlcSimulation = plcSimulation; TimeService = timeService; @@ -68,18 +68,18 @@ public PlcServer(OpcPlcConfiguration config, PlcSimulation plcSimulation, TimeSe uint sessionCount = ServerInternal.ServerDiagnostics.CurrentSessionCount; IList subscriptions = ServerInternal.SubscriptionManager.GetSubscriptions(); - int monitoredItemsCount = subscriptions.Sum(s => s.MonitoredItemCount); + int monitoredItemsCount = subscriptions.Sum(s => s.MonitoredItemCount); _autoDisablePublishMetrics = sessionCount > 40 || monitoredItemsCount > 500; LogPeriodicInfo( - sessionCount, - ServerInternal.ServerDiagnostics.CurrentSubscriptionCount, + sessionCount, + ServerInternal.ServerDiagnostics.CurrentSubscriptionCount, monitoredItemsCount, ServerInternal.ServerDiagnostics.CumulatedSessionCount, ServerInternal.ServerDiagnostics.CumulatedSubscriptionCount, - curProc.WorkingSet64 / 1024 / 1024, - availWorkerThreads, + curProc.WorkingSet64 / 1024 / 1024, + availWorkerThreads, curProc.Threads.Count, PeriodicLoggingTimerSeconds, _countCreateSession, @@ -121,58 +121,58 @@ public PlcServer(OpcPlcConfiguration config, PlcSimulation plcSimulation, TimeSe (Config.OtlpPublishMetrics == "auto" && !_autoDisablePublishMetrics) ); - public override ResponseHeader CreateSession( - RequestHeader requestHeader, - ApplicationDescription clientDescription, - string serverUri, - string endpointUrl, - string sessionName, - byte[] clientNonce, - byte[] clientCertificate, - double requestedSessionTimeout, - uint maxResponseMessageSize, - out NodeId sessionId, - out NodeId authenticationToken, - out double revisedSessionTimeout, - out byte[] serverNonce, - out byte[] serverCertificate, - out EndpointDescriptionCollection serverEndpoints, - out SignedSoftwareCertificateCollection serverSoftwareCertificates, - out SignatureData serverSignature, - out uint maxRequestMessageSize) + public override ResponseHeader CreateSession( + RequestHeader requestHeader, + ApplicationDescription clientDescription, + string serverUri, + string endpointUrl, + string sessionName, + byte[] clientNonce, + byte[] clientCertificate, + double requestedSessionTimeout, + uint maxResponseMessageSize, + out NodeId sessionId, + out NodeId authenticationToken, + out double revisedSessionTimeout, + out byte[] serverNonce, + out byte[] serverCertificate, + out EndpointDescriptionCollection serverEndpoints, + out SignedSoftwareCertificateCollection serverSoftwareCertificates, + out SignatureData serverSignature, + out uint maxRequestMessageSize) { _countCreateSession++; - - try - { + + try + { var responseHeader = base.CreateSession(requestHeader, clientDescription, serverUri, endpointUrl, sessionName, clientNonce, clientCertificate, requestedSessionTimeout, maxResponseMessageSize, out sessionId, out authenticationToken, out revisedSessionTimeout, out serverNonce, out serverCertificate, out serverEndpoints, out serverSoftwareCertificates, out serverSignature, out maxRequestMessageSize); MetricsHelper.AddSessionCount(sessionId.ToString()); - + LogSuccessWithSessionId(nameof(CreateSession), sessionId); return responseHeader; - } - catch (Exception ex) - { + } + catch (Exception ex) + { MetricsHelper.RecordTotalErrors(nameof(CreateSession)); - LogError(nameof(CreateSession), ex); - throw; - } - } - - public override ResponseHeader CreateSubscription( - RequestHeader requestHeader, - double requestedPublishingInterval, - uint requestedLifetimeCount, - uint requestedMaxKeepAliveCount, - uint maxNotificationsPerPublish, - bool publishingEnabled, - byte priority, - out uint subscriptionId, - out double revisedPublishingInterval, - out uint revisedLifetimeCount, + LogError(nameof(CreateSession), ex); + throw; + } + } + + public override ResponseHeader CreateSubscription( + RequestHeader requestHeader, + double requestedPublishingInterval, + uint requestedLifetimeCount, + uint requestedMaxKeepAliveCount, + uint maxNotificationsPerPublish, + bool publishingEnabled, + byte priority, + out uint subscriptionId, + out double revisedPublishingInterval, + out uint revisedLifetimeCount, out uint revisedMaxKeepAliveCount) { _countCreateSubscription++; @@ -185,8 +185,8 @@ public override ResponseHeader CreateSubscription( MetricsHelper.AddSubscriptionCount(sessionId.ToString(), subscriptionId.ToString()); LogSuccessWithSessionIdAndSubscriptionId( - nameof(CreateSubscription), - sessionId, + nameof(CreateSubscription), + sessionId, subscriptionId); return responseHeader; @@ -195,7 +195,7 @@ public override ResponseHeader CreateSubscription( { MetricsHelper.RecordTotalErrors(nameof(CreateSubscription)); - LogError(nameof(CreateSubscription), ex); + LogError(nameof(CreateSubscription), ex); throw; } } @@ -219,7 +219,7 @@ public override ResponseHeader CreateMonitoredItems( MetricsHelper.AddMonitoredItemCount(itemsToCreate.Count); - if(_logger.IsEnabled(LogLevel.Debug)) + if (_logger.IsEnabled(LogLevel.Debug)) { LogSuccessWithSessionIdAndSubscriptionIdAndCount( nameof(CreateMonitoredItems), @@ -292,9 +292,9 @@ public override ResponseHeader Publish( { MetricsHelper.RecordTotalErrors(nameof(Publish)); - LogErrorWithStatusCode( - nameof(Publish), - nameof(StatusCodes.BadSessionIdInvalid), + LogErrorWithStatusCode( + nameof(Publish), + nameof(StatusCodes.BadSessionIdInvalid), ex); return new ResponseHeader { ServiceResult = StatusCodes.BadSessionIdInvalid }; @@ -303,9 +303,9 @@ public override ResponseHeader Publish( { MetricsHelper.RecordTotalErrors(nameof(Publish)); - LogErrorWithStatusCode( - nameof(Publish), - nameof(StatusCodes.BadSecureChannelIdInvalid), + LogErrorWithStatusCode( + nameof(Publish), + nameof(StatusCodes.BadSecureChannelIdInvalid), ex); return new ResponseHeader { ServiceResult = StatusCodes.BadSecureChannelIdInvalid }; @@ -381,14 +381,14 @@ public override ResponseHeader Write(RequestHeader requestHeader, WriteValueColl } } - /// - /// Creates the node managers for the server. - /// - /// - /// This method allows the sub-class create any additional node managers which it uses. The SDK - /// always creates a CoreNodesManager which handles the built-in nodes defined by the specification. - /// Any additional NodeManagers are expected to handle application specific nodes. - /// + /// + /// Creates the node managers for the server. + /// + /// + /// This method allows the sub-class create any additional node managers which it uses. The SDK + /// always creates a CoreNodesManager which handles the built-in nodes defined by the specification. + /// Any additional NodeManagers are expected to handle application specific nodes. + /// protected override MasterNodeManager CreateMasterNodeManager(IServerInternal server, ApplicationConfiguration configuration) { var nodeManagers = new List(); @@ -462,12 +462,12 @@ protected override MasterNodeManager CreateMasterNodeManager(IServerInternal ser return masterNodeManager; } - /// - /// Loads the non-configurable properties for the application. - /// - /// - /// These properties are exposed by the server but cannot be changed by administrators. - /// + /// + /// Loads the non-configurable properties for the application. + /// + /// + /// These properties are exposed by the server but cannot be changed by administrators. + /// protected override ServerProperties LoadServerProperties() { var fileVersion = FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location); @@ -488,9 +488,9 @@ protected override ServerProperties LoadServerProperties() return properties; } - /// - /// Creates the resource manager for the server. - /// + /// + /// Creates the resource manager for the server. + /// protected override ResourceManager CreateResourceManager(IServerInternal server, ApplicationConfiguration configuration) { var resourceManager = new ResourceManager(server, configuration); @@ -510,9 +510,9 @@ protected override ResourceManager CreateResourceManager(IServerInternal server, return resourceManager; } - /// - /// Initializes the server before it starts up. - /// + /// + /// Initializes the server before it starts up. + /// protected override void OnServerStarting(ApplicationConfiguration configuration) { base.OnServerStarting(configuration); @@ -531,7 +531,7 @@ protected override void OnServerStarted(IServerInternal server) server.SessionManager.ImpersonateUser += new ImpersonateEventHandler(SessionManager_ImpersonateUser); } - /// + /// protected override void ProcessRequest(IEndpointIncomingRequest request, object calldata) { if (request is IAsyncResult asyncResult && @@ -547,12 +547,12 @@ asyncResult.AsyncState is object[] asyncStateArray && } } - /// - /// Cleans up before the server shuts down. - /// - /// - /// This method is called before any shutdown processing occurs. - /// + /// + /// Cleans up before the server shuts down. + /// + /// + /// This method is called before any shutdown processing occurs. + /// protected override void OnServerStopping() { try @@ -614,13 +614,13 @@ private void AddPublishMetrics(NotificationMessage notificationMessage) private NodeId GetSessionId(NodeId authenticationToken) => ServerInternal.SessionManager.GetSession(authenticationToken).Id; - [LoggerMessage( - Level = LogLevel.Information, - Message = "\n\t# Open/total sessions: {Sessions}/{TotalSessions}\n" + - "\t# Open/total subscriptions: {Subscriptions}/{TotalSubscriptions}\n" + + [LoggerMessage( + Level = LogLevel.Information, + Message = "\n\t# Open/total sessions: {Sessions} | {TotalSessions}\n" + + "\t# Open/total subscriptions: {Subscriptions} | {TotalSubscriptions}\n" + "\t# Monitored items: {MonitoredItems:N0}\n" + - "\t# Working set: {WorkingSet:N0} MB\n" + - "\t# Used/available worker threads: {ThreadCount:N0}/{AvailWorkerThreads:N0}\n" + + "\t# Working set: {WorkingSet:N0} MB\n" + + "\t# Used/available worker threads: {ThreadCount:N0} | {AvailWorkerThreads:N0}\n" + "\t# Stats for the last {PeriodicLoggingTimerSeconds} s\n" + "\t# Sessions created: {CountCreateSession}\n" + "\t# Subscriptions created: {CountCreateSubscription}\n" + @@ -633,7 +633,7 @@ partial void LogPeriodicInfo( uint sessions, uint subscriptions, int monitoredItems, - uint totalSessions, + uint totalSessions, uint totalSubscriptions, long workingSet, int availWorkerThreads, @@ -647,43 +647,43 @@ partial void LogPeriodicInfo( uint countPublish, bool publishMetricsEnabled); - [LoggerMessage( - Level = LogLevel.Debug, + [LoggerMessage( + Level = LogLevel.Debug, Message = "{Function} completed successfully")] partial void LogSuccess(string function); - [LoggerMessage( - Level = LogLevel.Debug, + [LoggerMessage( + Level = LogLevel.Debug, Message = "{Function} completed successfully with sessionId: {SessionId}")] partial void LogSuccessWithSessionId(string function, NodeId sessionId); - [LoggerMessage( - Level = LogLevel.Debug, + [LoggerMessage( + Level = LogLevel.Debug, Message = "{Function} completed successfully with sessionId: {SessionId} and subscriptionId: {SubscriptionId}")] partial void LogSuccessWithSessionIdAndSubscriptionId(string function, NodeId sessionId, uint subscriptionId); - [LoggerMessage( - Level = LogLevel.Debug, + [LoggerMessage( + Level = LogLevel.Debug, Message = "{Function} completed successfully with sessionId: {SessionId}, subscriptionId: {SubscriptionId} and count: {Count}")] partial void LogSuccessWithSessionIdAndSubscriptionIdAndCount(string function, NodeId sessionId, uint subscriptionId, int count); - [LoggerMessage( - Level = LogLevel.Error, + [LoggerMessage( + Level = LogLevel.Error, Message = "{Function} error")] partial void LogError(string function, Exception exception); - [LoggerMessage( - Level = LogLevel.Debug, + [LoggerMessage( + Level = LogLevel.Debug, Message = "{Function} error: {StatusCode}")] partial void LogErrorWithStatusCode(string function, string statusCode, Exception exception); - [LoggerMessage( - Level = LogLevel.Error, + [LoggerMessage( + Level = LogLevel.Error, Message = "{message}")] partial void LogErrorMessage(string message); - [LoggerMessage( - Level = LogLevel.Debug, + [LoggerMessage( + Level = LogLevel.Debug, Message = "Unknown notification type: {NotificationType}")] partial void LogUnknownNotification(string notificationType); -} +} diff --git a/src/opc-plc.csproj b/src/opc-plc.csproj index 4a4c922d..e8a8efb8 100644 --- a/src/opc-plc.csproj +++ b/src/opc-plc.csproj @@ -36,7 +36,7 @@ - +