mirror of
https://github.com/OPCFoundation/UA-.NETStandard.git
synced 2026-10-18 14:43:08 +08:00
712e770fbe
This change adds a **new Opc.Ua.Types** nuget that contains core types that do not rely on generated code. Why the name? Because almost all code that was in the Types subfolder is part of it, and because we do not want to change the name of the Opc.Ua.Core nuget/assembly because code relies on it. Any other name like base or bootstrap felt out of place due to the current structure already defining the name "types". Key design is to depend on only a small set of libraries with limited transitive dependencies, that includes hashcode, logging.abstraction, and for non standard20 builds System.Text.Json (needed for localizedText mul parsing). Also, key is to support .netstd 2.0 to support source generators and to allow removal of EEC_SUPPORT defines by removing std2.0 from core and all libraries. The changes are mostly restructuring, and thus small but contain some key changes: - **Status code** struct now comes with a Symbol field, which is used to carry symbols in case the code is not generated. Currently (until generated) the status code struct must be manually created with a symbol or the ToSymbolicId extension must be called in the core project. Future will generate Status code constants just like NodeId that contain the symbol which also removes the reflection-based lookup. Several tests needed to be adjusted as they checked the status code symbol strings instead of the code. - **Core identifiers** are copied as they were needed for code to compile, that includes attributes, a subset of status codes and node identifiers. These will never change so no need to generate them. - The types folder now contains **encoders**, except for json which is still in core. Once the json encoder is ported to system.text.json it will also be included and Newtonsoft.Json dropped as dependency (-> #3329). - Since types relies on **IOperationContext** and **ISystemContext**, and these export IUserIdentity which relies on crypto, these were split and extended in core with ISessionOperationContext and ISessionSystemContext, which mean changes to ServerSystemContext and introduction of SessionOperationContext and SessionSystemContext classes that extend OperationContext and SystemContext. Some runtime checks in the server are therefore needed to get at the session and auth info, however, those are anyway optional fields and are not on the critical paths, and thus a type check is in order (and was done in the past already, but against OperationContext class). - **Manifest resources** are now split between Core (nodeset zip, some generated resoures) and Types (built in bsd/xsds). This needs to be revisited later if the bsd/xsd need to be regenerated during type generation. Note that the embedded resource names changed as a result. Since these are only used internally and do not constitute public API this feels reasonable vs duplication of resources in 2 assemblies. - Reflection however now needs to load not just the built in **encodeables** from Opc.Ua.Types assembly, but also the generated encodeables from Opc.Ua.Core assembly. For this a new helper Utils method was added to get the Core assembly when linked against Opc.Ua.Core otherwise null. - Whatever utils methods needed to be split out into the new Opc.Ua.Types assembly, they are now in **CoreUtils** static class in Opc.Ua.Types, and Utils.xxxx forwards to them to ensure minimal changes. Later we would want to obsolete them in favor of CoreUtils, although it might make sense to split them again into domain specific utilities, such as networking, files, etc
197 lines
8.7 KiB
C#
197 lines
8.7 KiB
C#
/* ========================================================================
|
|
* Copyright (c) 2005-2020 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.Globalization;
|
|
using System.IO;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
using Microsoft.Extensions.Logging;
|
|
using Opc.Ua;
|
|
|
|
namespace Quickstarts.ReferenceServer
|
|
{
|
|
/// <summary>
|
|
/// The program.
|
|
/// </summary>
|
|
public static class Program
|
|
{
|
|
public static async Task<int> Main(string[] args)
|
|
{
|
|
Console.WriteLine("{0} OPC UA Reference Server", Utils.IsRunningOnMono() ? "Mono" : ".NET Core");
|
|
|
|
Console.WriteLine(
|
|
"OPC UA library: {0} @ {1} -- {2}",
|
|
Utils.GetAssemblyBuildNumber(),
|
|
Utils.GetAssemblyTimestamp().ToString("G", CultureInfo.InvariantCulture),
|
|
Utils.GetAssemblySoftwareVersion()
|
|
);
|
|
|
|
// The application name and config file names
|
|
string applicationName = Utils.IsRunningOnMono() ? "MonoReferenceServer" : "ConsoleReferenceServer";
|
|
string configSectionName = Utils.IsRunningOnMono()
|
|
? "Quickstarts.MonoReferenceServer"
|
|
: "Quickstarts.ReferenceServer";
|
|
|
|
// command line options
|
|
bool showHelp = false;
|
|
bool autoAccept = false;
|
|
bool logConsole = false;
|
|
bool appLog = false;
|
|
bool fileLog = false;
|
|
bool renewCertificate = false;
|
|
bool shadowConfig = false;
|
|
bool samplingGroups = false;
|
|
bool cttMode = false;
|
|
char[] password = null;
|
|
int timeout = -1;
|
|
|
|
string usage = Utils.IsRunningOnMono()
|
|
? $"Usage: mono {applicationName}.exe [OPTIONS]"
|
|
: $"Usage: dotnet {applicationName}.dll [OPTIONS]";
|
|
var options = new Mono.Options.OptionSet
|
|
{
|
|
usage,
|
|
{ "h|help", "show this message and exit", h => showHelp = h != null },
|
|
{ "a|autoaccept", "auto accept certificates (for testing only)", a => autoAccept = a != null },
|
|
{ "c|console", "log to console", c => logConsole = c != null },
|
|
{ "l|log", "log app output", c => appLog = c != null },
|
|
{ "f|file", "log to file", f => fileLog = f != null },
|
|
{ "p|password=", "optional password for private key", p => password = p.ToCharArray() },
|
|
{ "r|renew", "renew application certificate", r => renewCertificate = r != null },
|
|
{ "t|timeout=", "timeout in seconds to exit application", (int t) => timeout = t * 1000 },
|
|
{ "s|shadowconfig", "create configuration in pki root", s => shadowConfig = s != null },
|
|
{
|
|
"sg|samplinggroups",
|
|
"use the sampling group mechanism in the Reference Node Manager",
|
|
sg => samplingGroups = sg != null
|
|
},
|
|
{ "ctt", "CTT mode, use to preset alarms for CTT testing.", c => cttMode = c != null }
|
|
};
|
|
|
|
using var telemetry = new ConsoleTelemetry();
|
|
ILogger logger = LoggerUtils.Null.Logger;
|
|
try
|
|
{
|
|
// parse command line and set options
|
|
ConsoleUtils.ProcessCommandLine(args, options, ref showHelp, "REFSERVER");
|
|
|
|
// log console output to logger
|
|
if (logConsole && appLog)
|
|
{
|
|
logger = telemetry.CreateLogger("Main");
|
|
}
|
|
|
|
// create the UA server
|
|
var server = new UAServer<ReferenceServer>(telemetry)
|
|
{
|
|
AutoAccept = autoAccept,
|
|
Password = password
|
|
};
|
|
|
|
// load the server configuration, validate certificates
|
|
logger.LogInformation("Loading configuration from config section {Name}.", configSectionName);
|
|
await server.LoadAsync(applicationName, configSectionName).ConfigureAwait(false);
|
|
|
|
// use the shadow config to map the config to an externally accessible location
|
|
if (shadowConfig)
|
|
{
|
|
logger.LogInformation("Using shadow configuration.");
|
|
string shadowPath = Directory
|
|
.GetParent(
|
|
Path.GetDirectoryName(
|
|
Utils.ReplaceSpecialFolderNames(server.Configuration.TraceConfiguration.OutputFilePath)
|
|
)
|
|
)
|
|
.FullName;
|
|
string shadowFilePath = Path.Combine(
|
|
shadowPath,
|
|
Path.GetFileName(server.Configuration.SourceFilePath)
|
|
);
|
|
if (!File.Exists(shadowFilePath))
|
|
{
|
|
logger.LogInformation("Create a copy of the config in the shadow location.");
|
|
File.Copy(server.Configuration.SourceFilePath, shadowFilePath, true);
|
|
}
|
|
logger.LogInformation("Reloading configuration from shadow location {FilePath}.", shadowFilePath);
|
|
await server
|
|
.LoadAsync(applicationName, Path.Combine(shadowPath, configSectionName))
|
|
.ConfigureAwait(false);
|
|
}
|
|
|
|
// setup the logging
|
|
telemetry.ConfigureLogging(server.Configuration, applicationName, logConsole, fileLog, appLog, LogLevel.Information);
|
|
|
|
// check or renew the certificate
|
|
logger.LogInformation("Check the certificate.");
|
|
await server.CheckCertificateAsync(renewCertificate).ConfigureAwait(false);
|
|
|
|
// Create and add the node managers
|
|
server.Create(Servers.Utils.NodeManagerFactories);
|
|
|
|
// enable the sampling groups if requested
|
|
if (samplingGroups)
|
|
{
|
|
Servers.Utils.UseSamplingGroupsInReferenceNodeManager(server.Server);
|
|
}
|
|
|
|
// start the server
|
|
logger.LogInformation("Start the server.");
|
|
await server.StartAsync().ConfigureAwait(false);
|
|
|
|
// Apply custom settings for CTT testing
|
|
if (cttMode)
|
|
{
|
|
logger.LogInformation("Apply settings for CTT.");
|
|
// start Alarms and other settings for CTT test
|
|
Servers.Utils.ApplyCTTMode(Console.Out, server.Server);
|
|
}
|
|
|
|
logger.LogInformation("Server started. Press Ctrl-C to exit...");
|
|
|
|
// wait for timeout or Ctrl-C
|
|
var quitCTS = new CancellationTokenSource();
|
|
ManualResetEvent quitEvent = ConsoleUtils.CtrlCHandler(quitCTS);
|
|
bool ctrlc = quitEvent.WaitOne(timeout);
|
|
|
|
// stop server. May have to wait for clients to disconnect.
|
|
logger.LogInformation("Server stopped. Waiting for exit...");
|
|
await server.StopAsync().ConfigureAwait(false);
|
|
|
|
return (int)ExitCode.Ok;
|
|
}
|
|
catch (ErrorExitException eee)
|
|
{
|
|
logger.LogInformation("The application exits with error: {ExitMessage}", eee.Message);
|
|
return (int)eee.ExitCode;
|
|
}
|
|
}
|
|
}
|
|
}
|