-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCommandLineSwitchServer.cs
More file actions
587 lines (493 loc) · 23.8 KB
/
CommandLineSwitchServer.cs
File metadata and controls
587 lines (493 loc) · 23.8 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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
using Microsoft.Extensions.Logging;
using System;
using System.IO;
using System.IO.Pipes;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace CommandLineSwitchPipe
{
/// <summary>
/// Manages a named-pipe connection to send command-line switches to a running instance, or
/// if this is the only instance, to receive command-line switches after processing starts.
/// </summary>
public static class CommandLineSwitchServer
{
/// <summary>
/// The defaults are appropriate for most needs, but can also be created or modified through code,
/// or populated from any of the standard .NET configuration extension packages.
/// </summary>
public static CommandLinePipeOptions Options { get; set; } = new CommandLinePipeOptions();
/// <summary>
/// Populated when TrySendArgs is invoked with the waitForReply flag set to true.
/// </summary>
public static string QueryResponse = string.Empty;
/// <summary>
/// Populated when TrySendArgs or TryConnect results in an exception.
/// </summary>
public static Exception TryException = null;
/// <summary>
/// DO NOT USE THIS DIRECTLY.
/// It is created and used by the Log methods if Options.LoggerFactory is provided.
/// </summary>
private static ILogger Logger;
/// <summary>
/// Returns true if another instance is already running.
/// </summary>
public static async Task<bool> TryConnect(string server = null, int port = 0)
{
LogTrace($"{nameof(TryConnect)} starting for PID {Environment.ProcessId}");
TryException = null;
try
{
ValidateNetworkArgs(server, port);
return (string.IsNullOrWhiteSpace(server))
? await TryConnectLocalNamedPipe().ConfigureAwait(false)
: await TryConnectNetworkPort(server, port).ConfigureAwait(false);
}
catch (Exception ex)
{
LogException(ex);
TryException = ex;
return false;
}
}
/// <summary>
/// Attempt to send any command-line switches to an already-running instance. If another
/// instance is found but this instance was started without switches, the application will
/// terminate. Leave the argument list null unless Program.Main needs to pre-process that
/// data. When null, the command line will be retrieved from the system environment.
/// </summary>
public static async Task<bool> TrySendArgs(string[] args = null, string server = null, int port = 0)
{
LogTrace($"{nameof(TrySendArgs)} starting for PID {Environment.ProcessId}");
TryException = null;
try
{
if (Options == null || Options.Advanced == null)
throw new ArgumentNullException($"{nameof(CommandLineSwitchServer)}.{nameof(Options)} property must be configured before invoking {nameof(TrySendArgs)}");
ValidateNetworkArgs(server, port);
QueryResponse = string.Empty;
// Use the provided arguments, or environment array 1+ (array 0 is the program name and/or pathname)
var arguments = args ?? Environment.GetCommandLineArgs();
if (args == null)
arguments = arguments.Length == 1 ? new string[0] : arguments[1..];
LogTrace($"Switch list has {arguments.Length} elements");
// Send argument list with control-code separators
var message = string.Empty;
foreach (var arg in arguments) message += arg + Options.Advanced.SeparatorControlCode;
return (string.IsNullOrWhiteSpace(server))
? await TrySendLocalNamedPipe(message).ConfigureAwait(false)
: await TrySendNetworkPort(message, server, port).ConfigureAwait(false);
}
catch(Exception ex)
{
LogException(ex);
TryException = ex;
return false;
}
}
/// <summary>
/// Creates a named-pipe server that waits to receive command-line switches from another
/// running instance. These are sent to the switchHandler delegate as they're received.
/// </summary>
public static async Task StartServer(Func<string[], string> switchHandler, CancellationToken cancellationToken, int port = 0)
{
CancellationTokenSource ctsTCPServer = new();
try
{
if (Options == null || Options.Advanced == null)
throw new ArgumentNullException($"{nameof(CommandLineSwitchServer)}.{nameof(Options)} property must be configured before invoking {nameof(StartServer)}");
if (switchHandler == null)
throw new ArgumentNullException(paramName: nameof(switchHandler));
if (port != 0)
{
ValidatePortArgs(port);
_ = Task.Run(() => StartTCPServer(switchHandler, ctsTCPServer.Token, port), ctsTCPServer.Token);
}
while (!cancellationToken.IsCancellationRequested)
{
using var server = new NamedPipeServerStream(PipeName(), PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);
LogTrace($"Switch server waiting for connection on namedpipe \"{PipeName()}\"");
await server.WaitForConnectionAsync(cancellationToken).ConfigureAwait(false);
Log(LogLevel.Trace, $"Switch server exited namedpipe {nameof(server.WaitForConnectionAsync)}");
cancellationToken.ThrowIfCancellationRequested();
LogTrace("Switch client has connected to namedpipe server");
var message = await ReadStringFromPipe(server);
if (!string.IsNullOrWhiteSpace(message))
{
// Split into original arg array
var args = message.Split(Options.Advanced.SeparatorControlCode, StringSplitOptions.RemoveEmptyEntries);
// Process the switches, but prevent any handler exceptions from bringing down the server
LogTrace($"Invoking switch handler for {args.Length} switches");
try
{
var response = switchHandler.Invoke(args) ?? string.Empty;
await WriteStringToPipe(server, response);
}
catch (Exception ex)
{
Log(LogLevel.Warning, $"{ex.GetType().Name} trapped from switch handler");
}
try
{
// Goodbye, client
if(server.IsConnected)
{
server.Disconnect();
LogTrace("Switch server terminated client namedpipe connection");
}
else
{
LogTrace("Switch server connection was terminated by namedpipe client");
}
}
catch (Exception ex)
{
Log(LogLevel.Warning, $"{ex.GetType().Name} while trying to disconnect from namedpipe client");
}
}
}
ctsTCPServer.Cancel();
}
catch (OperationCanceledException)
{
Log(LogLevel.Trace, "Switch server namedpipe listener caught OperationCanceledException");
ctsTCPServer.Cancel();
}
catch (Exception ex)
{
LogException(ex);
if(!cancellationToken.IsCancellationRequested && Options.Advanced.AutoRestartServer)
{
ctsTCPServer.Cancel();
Log(LogLevel.Warning, "Restarting switch server task");
_ = Task.Run(() => StartServer(switchHandler, cancellationToken), cancellationToken);
}
else
{
ctsTCPServer.Cancel();
Log(LogLevel.Critical, $"Switch server forcibly terminating process in {nameof(StartServer)}");
Environment.Exit(-1);
}
}
finally
{
LogTrace("Switch server has stopped listening on namedpipe");
}
}
private static async Task StartTCPServer(Func<string[], string> switchHandler, CancellationToken cancellationToken, int port)
{
TcpListener server = null;
try
{
server = new TcpListener(IPAddress.Any, port);
server.Start(); // This merely queues connection requests
while (!cancellationToken.IsCancellationRequested)
{
LogTrace($"Switch server waiting for connection on TCP port {port}");
using var client = await server.AcceptTcpClientAsync(cancellationToken).ConfigureAwait(false);
Log(LogLevel.Trace, $"Switch server exited TCP {nameof(server.AcceptTcpClientAsync)}");
cancellationToken.ThrowIfCancellationRequested();
LogTrace("Switch client has connected to TCP port");
string activity = string.Empty;
try
{
activity = "reading data from TCP client";
var message = await ReadStringFromNetworkPort(client);
if (!string.IsNullOrWhiteSpace(message))
{
// Split into original arg array
var args = message.Split(Options.Advanced.SeparatorControlCode, StringSplitOptions.RemoveEmptyEntries);
// Process the switches
LogTrace($"Invoking switch handler for {args.Length} switches");
activity = "invoking switch handler";
var response = switchHandler.Invoke(args) ?? string.Empty;
// Can't rely on client.Connected since TCP is stateless
activity = "sending response to TCP client";
await WriteStringToNetworkPort(client, response).ConfigureAwait(false);
}
}
catch (Exception ex)
{
Log(LogLevel.Warning, $"{ex.GetType().Name} trapped {activity}");
}
finally
{
// Close is handled by Dispose
client.Dispose();
}
}
}
catch (OperationCanceledException)
{
Log(LogLevel.Trace, "Switch server TCP listener caught OperationCanceledException");
}
catch (Exception ex)
{
LogException(ex);
if (!cancellationToken.IsCancellationRequested && Options.Advanced.AutoRestartServer)
{
Log(LogLevel.Warning, "Restarting switch server TCP task");
_ = Task.Run(() => StartTCPServer(switchHandler, cancellationToken, port), cancellationToken);
}
else
{
Log(LogLevel.Critical, $"Switch server forcibly terminating process in {nameof(StartTCPServer)}");
Environment.Exit(-1);
}
}
finally
{
server?.Stop();
LogTrace("Switch server has stopped listening on TCP");
}
}
private static async Task<bool> TryConnectLocalNamedPipe()
{
Log(LogLevel.Trace, $"{nameof(TryConnectLocalNamedPipe)} invoked");
using var client = new NamedPipeClientStream(".", PipeName(), PipeDirection.InOut);
try
{
await client.ConnectAsync(Options.Advanced.PipeConnectionTimeout).ConfigureAwait(false);
}
catch (TimeoutException)
{
LogTrace($"{nameof(TryConnectLocalNamedPipe)}: No running instance found");
return false;
}
LogTrace($"{nameof(TryConnectLocalNamedPipe)}: Running instance found");
return true;
}
private static async Task<bool> TryConnectNetworkPort(string server, int port)
{
Log(LogLevel.Trace, $"{nameof(TryConnectNetworkPort)}(server:{server}, port:{port}) invoked");
var addresses = await Dns.GetHostAddressesAsync(server, (AddressFamily)Options.Advanced.DnsAddressFamily, CancellationToken.None);
if (addresses.Length == 0) throw new ArgumentException("Could not resolve address for host name");
using TcpClient client = new();
try
{
await client.ConnectAsync(addresses, port).ConfigureAwait(false);
}
catch (SocketException ex)
{
if(ex.SocketErrorCode == SocketError.ConnectionRefused)
{
LogTrace($"{nameof(TryConnectNetworkPort)}: No running instance found");
return false;
}
throw;
}
LogTrace($"{nameof(TryConnectNetworkPort)}: Running instance found");
return client.Connected;
}
private static async Task<bool> TrySendLocalNamedPipe(string message)
{
Log(LogLevel.Trace, $"{nameof(TrySendLocalNamedPipe)} invoked");
LogTrace($"Checking for a running instance on pipe \"{PipeName()}\"");
using var client = new NamedPipeClientStream(".", PipeName(), PipeDirection.InOut);
try
{
await client.ConnectAsync(Options.Advanced.PipeConnectionTimeout).ConfigureAwait(false);
}
catch (TimeoutException)
{
LogTrace($"No running instance found");
return false;
}
LogTrace($"Connected to switch pipe server");
// Connected, abort if we don't have arguments to pass
if (string.IsNullOrEmpty(message))
{
LogTrace("No arguments to pass to the running instance.");
if(Options.Advanced.ThrowIfRunning)
throw new ArgumentException("No arguments were provided to pass to the already-running instance");
LogTrace("Not configured to throw an exception; forcing an exit");
Environment.Exit(-1);
}
LogTrace("Sending switches to running instance");
await WriteStringToPipe(client, message).ConfigureAwait(false);
LogTrace("Waiting for reply");
QueryResponse = await ReadStringFromPipe(client).ConfigureAwait(false);
Log(LogLevel.Debug, $"Received:\n{QueryResponse}");
LogTrace($"Switches sent, PID {Environment.ProcessId} can terminate normally");
return true;
}
private static async Task<bool> TrySendNetworkPort(string message, string server, int port)
{
Log(LogLevel.Trace, $"{nameof(TrySendNetworkPort)} invoked");
LogTrace($"Checking for a running instance on server {server}:{port}");
var addresses = await Dns.GetHostAddressesAsync(server, (AddressFamily)Options.Advanced.DnsAddressFamily, CancellationToken.None);
if (addresses.Length == 0) throw new ArgumentException("Could not resolve address for host name");
LogTrace($"Resolved {addresses.Length} addresses for server {server}");
using TcpClient client = new();
try
{
await client.ConnectAsync(addresses, port).ConfigureAwait(false);
}
catch (SocketException ex)
{
if (ex.SocketErrorCode == SocketError.ConnectionRefused)
{
LogTrace($"{nameof(TryConnectNetworkPort)}: No running instance found");
return false;
}
throw;
}
if (!client.Connected) throw new Exception("Failed to connect, but no framework exception was thrown");
LogTrace($"Connected to switch pipe server");
// Connected, abort if we don't have arguments to pass
if (string.IsNullOrEmpty(message))
{
LogTrace("No arguments to pass to the running instance.");
if (Options.Advanced.ThrowIfRunning)
throw new ArgumentException("No arguments were provided to pass to the already-running instance");
LogTrace("Not configured to throw an exception; forcing an exit");
Environment.Exit(-1);
}
LogTrace("Sending switches to running instance");
await WriteStringToNetworkPort(client, message).ConfigureAwait(false);
LogTrace("Waiting for reply");
QueryResponse = await ReadStringFromNetworkPort(client).ConfigureAwait(false);
Log(LogLevel.Debug, $"Received:\n{QueryResponse}");
LogTrace($"Switches sent, PID {Environment.ProcessId} can terminate normally");
return true;
}
private static async Task WriteStringToPipe(PipeStream stream, string message)
{
Log(LogLevel.Trace, $"{nameof(WriteStringToPipe)} invoked");
if (message.Length == 0) return;
try
{
var messageBuffer = Encoding.ASCII.GetBytes(message);
LogTrace($"Sending {messageBuffer.Length} bytes");
var sizeBuffer = BitConverter.GetBytes(messageBuffer.Length);
await stream.WriteAsync(sizeBuffer, 0, sizeBuffer.Length).ConfigureAwait(false);
await stream.WriteAsync(messageBuffer, 0, messageBuffer.Length).ConfigureAwait(false);
await stream.FlushAsync().ConfigureAwait(false);
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
stream.WaitForPipeDrain();
}
else
{
await Task.Delay(Options.Advanced.LinuxWaitAfterWriteMS).ConfigureAwait(false);
}
}
catch (Exception ex)
{
Log(LogLevel.Warning, $"{ex.GetType().Name} while writing to PipeStream");
}
}
private static async Task<string> ReadStringFromPipe(PipeStream stream)
{
Log(LogLevel.Trace, $"{nameof(ReadStringFromPipe)} invoked");
string response = string.Empty;
try
{
using var reader = new BinaryReader(stream, Encoding.ASCII, leaveOpen: true);
// Read the length of the message, then the message itself
var size = reader.ReadInt32();
LogTrace($"Receiving {size} bytes");
if (size > 0)
{
var buffer = reader.ReadBytes(size);
response = Encoding.ASCII.GetString(buffer);
}
await stream.FlushAsync().ConfigureAwait(false);
}
catch(EndOfStreamException)
{ } // normal, disregard
catch (Exception ex)
{
Log(LogLevel.Warning, $"{ex.GetType().Name} while reading from PipeStream");
}
return response;
}
private static async Task WriteStringToNetworkPort(TcpClient client, string message)
{
Log(LogLevel.Trace, $"{nameof(WriteStringToNetworkPort)} invoked");
if (string.IsNullOrEmpty(message)) return;
try
{
var stream = client.GetStream();
var messageBuffer = Encoding.ASCII.GetBytes(message);
var minBuff = Math.Min(client.SendBufferSize, client.ReceiveBufferSize);
if (messageBuffer.Length > minBuff) throw new ArgumentException($"Message with delimiters exceeds {minBuff} byte buffer size");
LogTrace($"Sending {messageBuffer.Length} bytes");
await stream.WriteAsync(messageBuffer, 0, messageBuffer.Length).ConfigureAwait(false);
await stream.FlushAsync().ConfigureAwait(false);
}
catch (Exception ex)
{
Log(LogLevel.Warning, $"{ex.GetType().Name} while writing to NetworkStream");
}
}
private static async Task<string> ReadStringFromNetworkPort(TcpClient client)
{
Log(LogLevel.Trace, $"{nameof(ReadStringFromNetworkPort)} invoked");
string response = string.Empty;
try
{
var stream = client.GetStream();
var maxBuff = Math.Max(client.SendBufferSize, client.ReceiveBufferSize);
var messageBuffer = new byte[maxBuff];
var bytes = await stream.ReadAsync(messageBuffer, 0, maxBuff).ConfigureAwait(false);
await stream.FlushAsync().ConfigureAwait(false);
LogTrace($"Received {bytes} bytes");
response = Encoding.ASCII.GetString(messageBuffer, 0, bytes);
}
catch (EndOfStreamException)
{ } // normal, disregard
catch (Exception ex)
{
Log(LogLevel.Warning, $"{ex.GetType().Name} while reading from NetworkStream");
}
return response;
}
private static string PipeName()
=> string.IsNullOrWhiteSpace(Options.PipeName) ? Environment.GetCommandLineArgs()[0] : Options.PipeName;
private static void ValidateNetworkArgs(string server, int port)
{
// local named pipe
if (string.IsNullOrWhiteSpace(server))
{
if (port != 0) throw new ArgumentException("Local servers do not use a TCP port assignment");
}
// remote server
else
{
ValidatePortArgs(port);
}
}
private static void ValidatePortArgs(int port)
{
if (port < 1 || port > 65536) throw new ArgumentException("Invalid TCP port number");
if (port < 49151) Log(LogLevel.Warning, "TCP port numbers below 49152 may be reserved");
}
private static void Log(LogLevel logLevel, string message)
{
if (Options.LoggerFactory is null) return;
if (Logger is null) Logger = Options.LoggerFactory.CreateLogger(nameof(CommandLineSwitchPipe));
Logger.Log(logLevel, message);
}
private static void LogTrace(string message)
{
Log(LogLevel.Trace, message);
}
private static void LogException(Exception ex)
{
Log(LogLevel.Error, $"Exception {ex.GetType().Name}: {ex.Message}");
Log(LogLevel.Error, ex.StackTrace);
var inner = ex.InnerException;
while(inner is not null)
{
Log(LogLevel.Error, $"Inner exception {ex.InnerException.GetType().Name}: {ex.InnerException.Message}");
inner = ex.InnerException;
}
}
}
}