-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathProgram.cs
More file actions
351 lines (323 loc) · 15 KB
/
Copy pathProgram.cs
File metadata and controls
351 lines (323 loc) · 15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
/* ========================================================================
* 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/
* ======================================================================*/
#nullable enable
using System;
using System.Collections.Generic;
using System.CommandLine;
using System.CommandLine.Invocation;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Opc.Ua;
using Opc.Ua.Client;
using Opc.Ua.Client.Redundancy;
using Opc.Ua.Configuration;
using Opc.Ua.Redundancy;
namespace RedundantClient
{
/// <summary>
/// Entry point for the managed client sample.
/// </summary>
public static class Program
{
/// <summary>
/// Starts the sample.
/// </summary>
public static Task<int> Main(string[] args)
{
var serverOption = new Option<string>("--server", "-s")
{
Description = "Discovery URL of any server in the (optionally) redundant set.",
DefaultValueFactory = _ => "opc.tcp://localhost:62543/RedundantServer"
};
var noSecurityOption = new Option<bool>("--nosecurity")
{
Description = "Select endpoints with MessageSecurityMode.None."
};
var autoAcceptOption = new Option<bool>("--autoaccept")
{
Description = "Automatically accept untrusted server certificates for sample runs."
};
var durationOption = new Option<TimeSpan>("--duration", "-d")
{
Description = "How long to monitor before exiting. Use 00:00:00 to run until Ctrl+C.",
DefaultValueFactory = _ => TimeSpan.FromMinutes(2)
};
var replicasOption = new Option<int>("--replicas")
{
Description = "Run an in-process client replica set of this size (leader holds the session).",
DefaultValueFactory = _ => 1
};
var rootCommand = new RootCommand(
"OPC UA managed client sample that transparently handles server redundancy")
{
serverOption,
noSecurityOption,
autoAcceptOption,
durationOption,
replicasOption
};
rootCommand.SetAction(async (parseResult, cancellationToken) =>
{
await RunAsync(
parseResult.GetValue(serverOption)!,
parseResult.GetValue(noSecurityOption),
parseResult.GetValue(autoAcceptOption),
parseResult.GetValue(durationOption),
parseResult.GetValue(replicasOption),
cancellationToken).ConfigureAwait(false);
});
ParseResult parseResult = rootCommand.Parse(args);
return parseResult.InvokeAsync(new InvocationConfiguration(), CancellationToken.None);
}
private static async Task RunAsync(
string serverUrl,
bool noSecurity,
bool autoAccept,
TimeSpan duration,
int replicas,
CancellationToken ct)
{
ITelemetryContext telemetry = DefaultTelemetry.Create(builder =>
{
builder.SetMinimumLevel(LogLevel.Information);
});
using IDisposable? telemetryDisposable = telemetry as IDisposable;
var application = new ApplicationInstance(telemetry)
{
ApplicationName = kApplicationName,
ApplicationType = ApplicationType.Client,
ConfigSectionName = kConfigSectionName,
CertificatePasswordProvider = new CertificatePasswordProvider([])
};
await using (application.ConfigureAwait(false))
{
ApplicationConfiguration configuration = await application
.LoadApplicationConfigurationAsync(silent: false, ct: ct)
.ConfigureAwait(false);
if (autoAccept)
{
configuration.CertificateManager.AcceptError = (_, _) => true;
}
bool haveCertificate = await application
.CheckApplicationInstanceCertificatesAsync(silent: false, ct: ct)
.ConfigureAwait(false);
if (!haveCertificate)
{
throw new InvalidOperationException("Application instance certificate invalid.");
}
EndpointDescription selectedEndpoint = await CoreClientUtils
.SelectEndpointAsync(configuration, serverUrl, useSecurity: !noSecurity, telemetry, ct)
.ConfigureAwait(false)
?? throw new InvalidOperationException(
$"No endpoint could be selected for '{serverUrl}'.");
var endpoint = new ConfiguredEndpoint(
null,
selectedEndpoint,
EndpointConfiguration.Create(configuration));
Console.WriteLine("Connecting managed client to {0}", serverUrl);
if (replicas > 1)
{
await RunReplicaSetAsync(
configuration, endpoint, telemetry, replicas, duration, ct).ConfigureAwait(false);
return;
}
// A single ManagedSession is the managed client. WithServerRedundancy() lets it
// discover the redundant set (if any) from the connected server and fail over
// transparently; against a server that is not configured for redundancy it simply
// behaves as a resilient reconnecting session. The caller does not need to know the
// server topology before connecting.
ManagedSession session = await new ManagedSessionBuilder(configuration, telemetry)
.UseEndpoint(endpoint)
.WithSessionName(kApplicationName)
.WithUserIdentity(new UserIdentity())
.WithServerRedundancy()
.ConnectAsync(ct)
.ConfigureAwait(false);
await using (session.ConfigureAwait(false))
{
session.ConnectionStateChanged += OnConnectionStateChanged;
await LogRedundancyInfoAsync(session, ct).ConfigureAwait(false);
await SubscribeToCurrentTimeAsync(session, ct).ConfigureAwait(false);
Console.WriteLine("Monitoring ServerStatus.CurrentTime. Press Ctrl+C to stop.");
await RunForDurationAsync(duration, ct).ConfigureAwait(false);
session.ConnectionStateChanged -= OnConnectionStateChanged;
}
}
}
private static async Task LogRedundancyInfoAsync(ManagedSession session, CancellationToken ct)
{
var handler = new DefaultServerRedundancyHandler();
ServerRedundancyInfo info = await handler
.FetchRedundancyInfoAsync(session, ct)
.ConfigureAwait(false);
if (info.Mode == RedundancySupport.None)
{
Console.WriteLine(
"Server is not configured for redundancy (RedundancySupport=None); " +
"running as a single resilient session.");
return;
}
Console.WriteLine(
"Server reports RedundancySupport={0}, ServiceLevel={1} ({2}), CurrentServerId={3}.",
info.Mode,
info.ServiceLevel,
info.ServiceLevelSubrange,
info.CurrentServerId);
for (int ii = 0; ii < info.RedundantServers.Count; ii++)
{
RedundantServer server = info.RedundantServers[ii];
Console.WriteLine(
"Peer {0}: uri={1}, state={2}, serviceLevel={3}, endpoint={4}",
ii + 1,
server.ServerUri,
server.ServerState,
server.ServiceLevel,
server.Endpoint?.EndpointUrl?.ToString() ?? "(unresolved)");
}
}
private static async Task SubscribeToCurrentTimeAsync(ManagedSession session, CancellationToken ct)
{
// Ownership of the subscription transfers to the session via AddSubscription;
// the session disposes its subscriptions when it is disposed.
#pragma warning disable CA2000
var subscription = new Subscription(session.DefaultSubscription)
{
DisplayName = "RedundantClient CurrentTime",
PublishingEnabled = true,
PublishingInterval = 1000,
KeepAliveCount = 10,
LifetimeCount = 0,
MinLifetimeInterval = 10_000,
FastDataChangeCallback = OnDataChange
};
session.AddSubscription(subscription);
#pragma warning restore CA2000
await subscription.CreateAsync(ct).ConfigureAwait(false);
var currentTime = new MonitoredItem(subscription.DefaultItem)
{
StartNodeId = VariableIds.Server_ServerStatus_CurrentTime,
AttributeId = Attributes.Value,
DisplayName = "ServerStatus.CurrentTime",
SamplingInterval = 1000,
QueueSize = 10,
DiscardOldest = true
};
subscription.AddItem(currentTime);
await subscription.ApplyChangesAsync(ct).ConfigureAwait(false);
}
private static void OnDataChange(
Subscription subscription,
DataChangeNotification notification,
ArrayOf<string> stringTable)
{
for (int ii = 0; ii < notification.MonitoredItems.Count; ii++)
{
MonitoredItemNotification item = notification.MonitoredItems[ii];
Console.WriteLine(
"CurrentTime={0:o} Status={1}",
item.Value.GetValue(DateTime.MinValue),
item.Value.StatusCode);
}
}
private static void OnConnectionStateChanged(object? sender, ConnectionStateChangedEventArgs e)
{
Console.WriteLine("Connection state: {0} -> {1}", e.PreviousState, e.NewState);
}
private static async Task RunForDurationAsync(TimeSpan duration, CancellationToken ct)
{
try
{
await Task.Delay(
duration <= TimeSpan.Zero ? Timeout.InfiniteTimeSpan : duration,
ct).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
// Ctrl+C or the run duration elapsed; exit cleanly.
}
}
private static async Task RunReplicaSetAsync(
ApplicationConfiguration configuration,
ConfiguredEndpoint endpoint,
ITelemetryContext telemetry,
int replicas,
TimeSpan duration,
CancellationToken ct)
{
// A shared store + lease election make exactly one replica the leader that holds the
// session; followers stand by and take over on leader loss. This runs in-process with an
// in-memory store; a multi-process deployment uses a CAS-capable shared store (Redis) or
// Kubernetes Lease election with the same coordinator.
using var store = new InMemorySharedKeyValueStore();
var coordinators = new List<ClientReplicaCoordinator>();
try
{
for (int i = 0; i < replicas; i++)
{
string nodeId = $"replica-{i + 1}";
// Ownership of the election transfers to the coordinator, which disposes it.
#pragma warning disable CA2000
var election = new SharedStoreLeaseElection(
store, "client-replica/leader", nodeId,
TimeSpan.FromSeconds(15), TimeSpan.FromSeconds(5), TimeProvider.System);
#pragma warning restore CA2000
var options = new ClientReplicaOptions
{
NodeId = nodeId,
Mode = ClientStandbyMode.Cold,
CreateSessionAsync = token => new ValueTask<ManagedSession>(
new ManagedSessionBuilder(configuration, telemetry)
.UseEndpoint(endpoint)
.WithSessionName(nodeId)
.WithUserIdentity(new UserIdentity())
.ConnectAsync(token))
};
var coordinator = new ClientReplicaCoordinator(
options, election, store, NullRecordProtector.Instance, telemetry);
coordinator.RoleChanged += isLeader =>
Console.WriteLine("{0} is now {1}", nodeId, isLeader ? "LEADER" : "follower");
coordinators.Add(coordinator);
await coordinator.StartAsync(ct).ConfigureAwait(false);
}
Console.WriteLine("Client replica set of {0} started; the leader holds the session.", replicas);
await RunForDurationAsync(duration, ct).ConfigureAwait(false);
}
finally
{
foreach (ClientReplicaCoordinator coordinator in coordinators)
{
await coordinator.DisposeAsync().ConfigureAwait(false);
}
}
}
private const string kApplicationName = "RedundantClient";
private const string kConfigSectionName = "RedundantClient";
}
}