-
Notifications
You must be signed in to change notification settings - Fork 4.6k
/
DiagnosticsServerRouterFactory.cs
1412 lines (1123 loc) · 51.8 KB
/
DiagnosticsServerRouterFactory.cs
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
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.IO;
using System.IO.Pipes;
using System.Security.Principal;
using System.Threading;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.Extensions.Logging;
using System.Net;
using System.Net.Sockets;
namespace Microsoft.Diagnostics.NETCore.Client
{
internal class RuntimeTimeoutException : TimeoutException
{
public RuntimeTimeoutException(int TimeoutMs)
: base(string.Format("No new runtime endpoints connected, waited {0} ms", TimeoutMs))
{ }
}
internal class BackendStreamTimeoutException : TimeoutException
{
public BackendStreamTimeoutException(int TimeoutMs)
: base(string.Format("No new back end streams available, waited {0} ms", TimeoutMs))
{ }
}
/// <summary>
/// Base class representing a Diagnostics Server router factory.
/// </summary>
internal class DiagnosticsServerRouterFactory
{
int IsStreamConnectedTimeoutMs { get; set; } = 500;
public virtual string IpcAddress { get; }
public virtual string TcpAddress { get; }
public virtual ILogger Logger { get; }
public virtual Task Start(CancellationToken token)
{
throw new NotImplementedException();
}
public virtual Task Stop()
{
throw new NotImplementedException();
}
public virtual void Reset()
{
throw new NotImplementedException();
}
public virtual Task<Router> CreateRouterAsync(CancellationToken token)
{
throw new NotImplementedException();
}
protected bool IsStreamConnected(Stream stream, CancellationToken token)
{
bool connected = true;
if (stream is NamedPipeServerStream || stream is NamedPipeClientStream)
{
PipeStream pipeStream = stream as PipeStream;
// PeekNamedPipe will return false if the pipe is disconnected/broken.
connected = NativeMethods.PeekNamedPipe(
pipeStream.SafePipeHandle,
null,
0,
IntPtr.Zero,
IntPtr.Zero,
IntPtr.Zero);
}
else if (stream is ExposedSocketNetworkStream networkStream)
{
bool blockingState = networkStream.Socket.Blocking;
try
{
// Check connection read state by peek one byte. Will return 0 in case connection is closed.
// A closed connection could also raise exception, but then socket connected state should
// be set to false.
networkStream.Socket.Blocking = false;
if (networkStream.Socket.Receive(new byte[1], 0, 1, System.Net.Sockets.SocketFlags.Peek) == 0)
connected = false;
// Check connection write state by sending non-blocking zero-byte data.
// A closed connection should raise exception, but then socket connected state should
// be set to false.
if (connected)
networkStream.Socket.Send(Array.Empty<byte>(), 0, System.Net.Sockets.SocketFlags.None);
}
catch (Exception)
{
connected = networkStream.Socket.Connected;
}
finally
{
networkStream.Socket.Blocking = blockingState;
}
}
else
{
connected = false;
}
return connected;
}
protected async Task IsStreamConnectedAsync(Stream stream, CancellationToken token)
{
while (!token.IsCancellationRequested)
{
// Check if tcp stream connection is still available.
if (!IsStreamConnected(stream, token))
{
throw new EndOfStreamException();
}
try
{
// Wait before rechecking connection.
await Task.Delay(IsStreamConnectedTimeoutMs, token).ConfigureAwait(false);
}
catch { }
}
}
protected bool IsCompletedSuccessfully(Task t)
{
#if NETCOREAPP2_0_OR_GREATER
return t.IsCompletedSuccessfully;
#else
return t.IsCompleted && !t.IsCanceled && !t.IsFaulted;
#endif
}
}
/// <summary>
/// This class represent a TCP/IP server endpoint used when building up router instances.
/// </summary>
internal class TcpServerRouterFactory : IIpcServerTransportCallbackInternal
{
protected readonly ILogger _logger;
string _tcpServerAddress;
ReversedDiagnosticsServer _tcpServer;
IpcEndpointInfo _tcpServerEndpointInfo;
bool _auto_shutdown;
int RuntimeTimeoutMs { get; set; } = 60000;
int TcpServerTimeoutMs { get; set; } = 5000;
public Guid RuntimeInstanceId
{
get { return _tcpServerEndpointInfo.RuntimeInstanceCookie; }
}
public int RuntimeProcessId
{
get { return _tcpServerEndpointInfo.ProcessId; }
}
public string TcpServerAddress
{
get { return _tcpServerAddress; }
}
public delegate TcpServerRouterFactory CreateInstanceDelegate(string tcpServer, int runtimeTimeoutMs, ILogger logger);
public static TcpServerRouterFactory CreateDefaultInstance(string tcpServer, int runtimeTimeoutMs, ILogger logger)
{
return new TcpServerRouterFactory(tcpServer, runtimeTimeoutMs, logger);
}
public TcpServerRouterFactory(string tcpServer, int runtimeTimeoutMs, ILogger logger)
{
_logger = logger;
_tcpServerAddress = IpcTcpSocketEndPoint.NormalizeTcpIpEndPoint(string.IsNullOrEmpty(tcpServer) ? "127.0.0.1:0" : tcpServer);
_auto_shutdown = runtimeTimeoutMs != Timeout.Infinite;
if (runtimeTimeoutMs != Timeout.Infinite)
RuntimeTimeoutMs = runtimeTimeoutMs;
_tcpServer = new ReversedDiagnosticsServer(_tcpServerAddress, enableTcpIpProtocol : true);
_tcpServerEndpointInfo = new IpcEndpointInfo();
_tcpServer.TransportCallback = this;
}
public virtual void Start()
{
_tcpServer.Start();
}
public virtual async Task Stop()
{
await _tcpServer.DisposeAsync().ConfigureAwait(false);
}
public void Reset()
{
if (_tcpServerEndpointInfo.Endpoint != null)
{
_tcpServer.RemoveConnection(_tcpServerEndpointInfo.RuntimeInstanceCookie);
_tcpServerEndpointInfo = new IpcEndpointInfo();
}
}
public async Task<Stream> AcceptTcpStreamAsync(CancellationToken token)
{
Stream tcpServerStream;
_logger?.LogDebug($"Waiting for a new tcp connection at endpoint \"{_tcpServerAddress}\".");
if (_tcpServerEndpointInfo.Endpoint == null)
{
using var acceptTimeoutTokenSource = new CancellationTokenSource();
using var acceptTokenSource = CancellationTokenSource.CreateLinkedTokenSource(token, acceptTimeoutTokenSource.Token);
try
{
// If no new runtime instance connects, timeout.
acceptTimeoutTokenSource.CancelAfter(RuntimeTimeoutMs);
_tcpServerEndpointInfo = await _tcpServer.AcceptAsync(acceptTokenSource.Token).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
if (acceptTimeoutTokenSource.IsCancellationRequested)
{
_logger?.LogDebug("No runtime instance connected before timeout.");
if (_auto_shutdown)
throw new RuntimeTimeoutException(RuntimeTimeoutMs);
}
throw;
}
}
using var connectTimeoutTokenSource = new CancellationTokenSource();
using var connectTokenSource = CancellationTokenSource.CreateLinkedTokenSource(token, connectTimeoutTokenSource.Token);
try
{
// Get next connected tcp stream. Should timeout if no endpoint appears within timeout.
// If that happens we need to remove endpoint since it might indicate a unresponsive runtime.
connectTimeoutTokenSource.CancelAfter(TcpServerTimeoutMs);
tcpServerStream = await _tcpServerEndpointInfo.Endpoint.ConnectAsync(connectTokenSource.Token).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
if (connectTimeoutTokenSource.IsCancellationRequested)
{
_logger?.LogDebug("No tcp stream connected before timeout.");
throw new BackendStreamTimeoutException(TcpServerTimeoutMs);
}
throw;
}
if (tcpServerStream != null)
_logger?.LogDebug($"Successfully connected tcp stream, runtime id={RuntimeInstanceId}, runtime pid={RuntimeProcessId}.");
return tcpServerStream;
}
public void CreatedNewServer(EndPoint localEP)
{
if (localEP is IPEndPoint ipEP)
_tcpServerAddress = _tcpServerAddress.Replace(":0", string.Format(":{0}", ipEP.Port));
}
}
/// <summary>
/// This class represent a TCP/IP client endpoint used when building up router instances.
/// </summary>
internal class TcpClientRouterFactory
{
protected readonly ILogger _logger;
protected readonly string _tcpClientAddress;
protected bool _auto_shutdown;
protected int TcpClientTimeoutMs { get; set; } = Timeout.Infinite;
protected int TcpClientRetryTimeoutMs { get; set; } = 500;
public delegate TcpClientRouterFactory CreateInstanceDelegate(string tcpClient, int runtimeTimeoutMs, ILogger logger);
public static TcpClientRouterFactory CreateDefaultInstance(string tcpClient, int runtimeTimeoutMs, ILogger logger)
{
return new TcpClientRouterFactory(tcpClient, runtimeTimeoutMs, logger);
}
public string TcpClientAddress {
get { return _tcpClientAddress; }
}
public TcpClientRouterFactory(string tcpClient, int runtimeTimeoutMs, ILogger logger)
{
_logger = logger;
_tcpClientAddress = IpcTcpSocketEndPoint.NormalizeTcpIpEndPoint(string.IsNullOrEmpty(tcpClient) ? "127.0.0.1:" + string.Format("{0}", 56000 + (Process.GetCurrentProcess().Id % 1000)) : tcpClient);
_auto_shutdown = runtimeTimeoutMs != Timeout.Infinite;
if (runtimeTimeoutMs != Timeout.Infinite)
TcpClientTimeoutMs = runtimeTimeoutMs;
}
public virtual async Task<Stream> ConnectTcpStreamAsync(CancellationToken token)
{
return await ConnectTcpStreamAsyncInternal(token, _auto_shutdown).ConfigureAwait(false);
}
public virtual async Task<Stream> ConnectTcpStreamAsync(CancellationToken token, bool retry)
{
return await ConnectTcpStreamAsyncInternal(token, retry).ConfigureAwait(false);
}
public virtual void Start()
{
}
public virtual void Stop()
{
}
async Task<Stream> ConnectTcpStreamAsyncInternal(CancellationToken token, bool retry)
{
Stream tcpClientStream = null;
_logger?.LogDebug($"Connecting new tcp endpoint \"{_tcpClientAddress}\".");
IpcTcpSocketEndPoint clientTcpEndPoint = new IpcTcpSocketEndPoint(_tcpClientAddress);
Socket clientSocket = null;
using var connectTimeoutTokenSource = new CancellationTokenSource();
using var connectTokenSource = CancellationTokenSource.CreateLinkedTokenSource(token, connectTimeoutTokenSource.Token);
connectTimeoutTokenSource.CancelAfter(TcpClientTimeoutMs);
do
{
clientSocket = new Socket(SocketType.Stream, ProtocolType.Tcp);
try
{
await ConnectAsyncInternal(clientSocket, clientTcpEndPoint, connectTokenSource.Token).ConfigureAwait(false);
retry = false;
}
catch (Exception)
{
clientSocket?.Dispose();
if (connectTimeoutTokenSource.IsCancellationRequested)
{
_logger?.LogDebug("No tcp stream connected, timing out.");
if (_auto_shutdown)
throw new RuntimeTimeoutException(TcpClientTimeoutMs);
throw new TimeoutException();
}
// If we are not doing retries when runtime is unavailable, fail right away, this will
// break any accepted IPC connections, making sure client is notified and could reconnect.
// If not, retry until succeed or time out.
if (!retry)
{
_logger?.LogTrace($"Failed connecting {_tcpClientAddress}.");
throw;
}
_logger?.LogTrace($"Failed connecting {_tcpClientAddress}, wait {TcpClientRetryTimeoutMs} ms before retrying.");
// If we get an error (without hitting timeout above), most likely due to unavailable listener.
// Delay execution to prevent to rapid retry attempts.
await Task.Delay(TcpClientRetryTimeoutMs, token).ConfigureAwait(false);
}
}
while (retry);
tcpClientStream = new ExposedSocketNetworkStream(clientSocket, ownsSocket: true);
_logger?.LogDebug("Successfully connected tcp stream.");
return tcpClientStream;
}
async Task ConnectAsyncInternal(Socket clientSocket, EndPoint remoteEP, CancellationToken token)
{
using (token.Register(() => clientSocket.Close(0)))
{
try
{
Func<AsyncCallback, object, IAsyncResult> beginConnect = (callback, state) =>
{
return clientSocket.BeginConnect(remoteEP, callback, state);
};
await Task.Factory.FromAsync(beginConnect, clientSocket.EndConnect, this).ConfigureAwait(false);
}
// When the socket is closed, the FromAsync logic will try to call EndAccept on the socket,
// but that will throw an ObjectDisposedException. Only catch the exception if due to cancellation.
catch (ObjectDisposedException) when (token.IsCancellationRequested)
{
// First check if the cancellation token caused the closing of the socket,
// then rethrow the exception if it did not.
token.ThrowIfCancellationRequested();
}
}
}
}
/// <summary>
/// This class represent a IPC server endpoint used when building up router instances.
/// </summary>
internal class IpcServerRouterFactory
{
readonly ILogger _logger;
readonly string _ipcServerPath;
IpcServerTransport _ipcServer;
int IpcServerTimeoutMs { get; set; } = Timeout.Infinite;
public string IpcServerPath {
get { return _ipcServerPath; }
}
public IpcServerRouterFactory(string ipcServer, ILogger logger)
{
if (string.IsNullOrEmpty(ipcServer))
throw new ArgumentException("Missing IPC server path.");
_logger = logger;
_ipcServerPath = ipcServer;
_ipcServer = IpcServerTransport.Create(_ipcServerPath, IpcServerTransport.MaxAllowedConnections, false);
}
public void Start()
{
}
public void Stop()
{
_ipcServer?.Dispose();
}
public async Task<Stream> AcceptIpcStreamAsync(CancellationToken token)
{
Stream ipcServerStream = null;
_logger?.LogDebug($"Waiting for new ipc connection at endpoint \"{_ipcServerPath}\".");
using var connectTimeoutTokenSource = new CancellationTokenSource();
using var connectTokenSource = CancellationTokenSource.CreateLinkedTokenSource(token, connectTimeoutTokenSource.Token);
try
{
connectTimeoutTokenSource.CancelAfter(IpcServerTimeoutMs);
ipcServerStream = await _ipcServer.AcceptAsync(connectTokenSource.Token).ConfigureAwait(false);
}
catch (Exception)
{
ipcServerStream?.Dispose();
if (connectTimeoutTokenSource.IsCancellationRequested)
{
_logger?.LogDebug("No ipc stream connected, timing out.");
throw new TimeoutException();
}
throw;
}
if (ipcServerStream != null)
_logger?.LogDebug("Successfully connected ipc stream.");
return ipcServerStream;
}
}
/// <summary>
/// This class represent a IPC client endpoint used when building up router instances.
/// </summary>
internal class IpcClientRouterFactory
{
readonly ILogger _logger;
readonly string _ipcClientPath;
int IpcClientTimeoutMs { get; set; } = Timeout.Infinite;
int IpcClientRetryTimeoutMs { get; set; } = 500;
public string IpcClientPath {
get { return _ipcClientPath; }
}
public IpcClientRouterFactory(string ipcClient, ILogger logger)
{
_logger = logger;
_ipcClientPath = ipcClient;
}
public async Task<Stream> ConnectIpcStreamAsync(CancellationToken token)
{
Stream ipcClientStream = null;
_logger?.LogDebug($"Connecting new ipc endpoint \"{_ipcClientPath}\".");
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
var namedPipe = new NamedPipeClientStream(
".",
_ipcClientPath,
PipeDirection.InOut,
PipeOptions.Asynchronous,
TokenImpersonationLevel.Impersonation);
try
{
await namedPipe.ConnectAsync(IpcClientTimeoutMs, token).ConfigureAwait(false);
}
catch (Exception ex)
{
namedPipe?.Dispose();
if (ex is TimeoutException)
_logger?.LogDebug("No ipc stream connected, timing out.");
throw;
}
ipcClientStream = namedPipe;
}
else
{
bool retry = false;
IpcUnixDomainSocket unixDomainSocket;
using var connectTimeoutTokenSource = new CancellationTokenSource();
using var connectTokenSource = CancellationTokenSource.CreateLinkedTokenSource(token, connectTimeoutTokenSource.Token);
connectTimeoutTokenSource.CancelAfter(IpcClientTimeoutMs);
do
{
unixDomainSocket = new IpcUnixDomainSocket();
try
{
await unixDomainSocket.ConnectAsync(new IpcUnixDomainSocketEndPoint(_ipcClientPath), token).ConfigureAwait(false);
retry = false;
}
catch (Exception)
{
unixDomainSocket?.Dispose();
if (connectTimeoutTokenSource.IsCancellationRequested)
{
_logger?.LogDebug("No ipc stream connected, timing out.");
throw new TimeoutException();
}
_logger?.LogTrace($"Failed connecting {_ipcClientPath}, wait {IpcClientRetryTimeoutMs} ms before retrying.");
// If we get an error (without hitting timeout above), most likely due to unavailable listener.
// Delay execution to prevent to rapid retry attempts.
await Task.Delay(IpcClientRetryTimeoutMs, token).ConfigureAwait(false);
retry = true;
}
}
while (retry);
ipcClientStream = new ExposedSocketNetworkStream(unixDomainSocket, ownsSocket: true);
}
if (ipcClientStream != null)
_logger?.LogDebug("Successfully connected ipc stream.");
return ipcClientStream;
}
}
/// <summary>
/// This class creates IPC Server - TCP Server router instances.
/// Supports NamedPipes/UnixDomainSocket server and TCP/IP server.
/// </summary>
internal class IpcServerTcpServerRouterFactory : DiagnosticsServerRouterFactory
{
ILogger _logger;
TcpServerRouterFactory _tcpServerRouterFactory;
IpcServerRouterFactory _ipcServerRouterFactory;
public IpcServerTcpServerRouterFactory(string ipcServer, string tcpServer, int runtimeTimeoutMs, TcpServerRouterFactory.CreateInstanceDelegate factory, ILogger logger)
{
_logger = logger;
_tcpServerRouterFactory = factory(tcpServer, runtimeTimeoutMs, logger);
_ipcServerRouterFactory = new IpcServerRouterFactory(ipcServer, logger);
}
public override string IpcAddress
{
get
{
return _ipcServerRouterFactory.IpcServerPath;
}
}
public override string TcpAddress
{
get
{
return _tcpServerRouterFactory.TcpServerAddress;
}
}
public override ILogger Logger
{
get
{
return _logger;
}
}
public override Task Start(CancellationToken token)
{
_tcpServerRouterFactory.Start();
_ipcServerRouterFactory.Start();
_logger?.LogInformation($"Starting IPC server ({_ipcServerRouterFactory.IpcServerPath}) <--> TCP server ({_tcpServerRouterFactory.TcpServerAddress}) router.");
return Task.CompletedTask;
}
public override Task Stop()
{
_logger?.LogInformation($"Stopping IPC server ({_ipcServerRouterFactory.IpcServerPath}) <--> TCP server ({_tcpServerRouterFactory.TcpServerAddress}) router.");
_ipcServerRouterFactory.Stop();
return _tcpServerRouterFactory.Stop();
}
public override void Reset()
{
_tcpServerRouterFactory.Reset();
}
public override async Task<Router> CreateRouterAsync(CancellationToken token)
{
Stream tcpServerStream = null;
Stream ipcServerStream = null;
_logger?.LogDebug($"Trying to create new router instance.");
try
{
using CancellationTokenSource cancelRouter = CancellationTokenSource.CreateLinkedTokenSource(token);
// Get new tcp server endpoint.
using var tcpServerStreamTask = _tcpServerRouterFactory.AcceptTcpStreamAsync(cancelRouter.Token);
// Get new ipc server endpoint.
using var ipcServerStreamTask = _ipcServerRouterFactory.AcceptIpcStreamAsync(cancelRouter.Token);
await Task.WhenAny(ipcServerStreamTask, tcpServerStreamTask).ConfigureAwait(false);
if (IsCompletedSuccessfully(ipcServerStreamTask) && IsCompletedSuccessfully(tcpServerStreamTask))
{
ipcServerStream = ipcServerStreamTask.Result;
tcpServerStream = tcpServerStreamTask.Result;
}
else if (IsCompletedSuccessfully(ipcServerStreamTask))
{
ipcServerStream = ipcServerStreamTask.Result;
// We have a valid ipc stream and a pending tcp accept. Wait for completion
// or disconnect of ipc stream.
using var checkIpcStreamTask = IsStreamConnectedAsync(ipcServerStream, cancelRouter.Token);
// Wait for at least completion of one task.
await Task.WhenAny(tcpServerStreamTask, checkIpcStreamTask).ConfigureAwait(false);
// Cancel out any pending tasks not yet completed.
cancelRouter.Cancel();
try
{
await Task.WhenAll(tcpServerStreamTask, checkIpcStreamTask).ConfigureAwait(false);
}
catch (Exception)
{
// Check if we have an accepted tcp stream.
if (IsCompletedSuccessfully(tcpServerStreamTask))
tcpServerStreamTask.Result?.Dispose();
if (checkIpcStreamTask.IsFaulted)
{
_logger?.LogInformation("Broken ipc connection detected, aborting tcp connection.");
checkIpcStreamTask.GetAwaiter().GetResult();
}
throw;
}
tcpServerStream = tcpServerStreamTask.Result;
}
else if (IsCompletedSuccessfully(tcpServerStreamTask))
{
tcpServerStream = tcpServerStreamTask.Result;
// We have a valid tcp stream and a pending ipc accept. Wait for completion
// or disconnect of tcp stream.
using var checkTcpStreamTask = IsStreamConnectedAsync(tcpServerStream, cancelRouter.Token);
// Wait for at least completion of one task.
await Task.WhenAny(ipcServerStreamTask, checkTcpStreamTask).ConfigureAwait(false);
// Cancel out any pending tasks not yet completed.
cancelRouter.Cancel();
try
{
await Task.WhenAll(ipcServerStreamTask, checkTcpStreamTask).ConfigureAwait(false);
}
catch (Exception)
{
// Check if we have an accepted ipc stream.
if (IsCompletedSuccessfully(ipcServerStreamTask))
ipcServerStreamTask.Result?.Dispose();
if (checkTcpStreamTask.IsFaulted)
{
_logger?.LogInformation("Broken tcp connection detected, aborting ipc connection.");
checkTcpStreamTask.GetAwaiter().GetResult();
}
throw;
}
ipcServerStream = ipcServerStreamTask.Result;
}
else
{
// Error case, cancel out. wait and throw exception.
cancelRouter.Cancel();
try
{
await Task.WhenAll(ipcServerStreamTask, tcpServerStreamTask).ConfigureAwait(false);
}
catch (Exception)
{
// Check if we have an ipc stream.
if (IsCompletedSuccessfully(ipcServerStreamTask))
ipcServerStreamTask.Result?.Dispose();
throw;
}
}
}
catch (Exception)
{
_logger?.LogDebug("Failed creating new router instance.");
// Cleanup and rethrow.
ipcServerStream?.Dispose();
tcpServerStream?.Dispose();
throw;
}
// Create new router.
_logger?.LogDebug("New router instance successfully created.");
return new Router(ipcServerStream, tcpServerStream, _logger);
}
}
/// <summary>
/// This class creates IPC Server - TCP Client router instances.
/// Supports NamedPipes/UnixDomainSocket server and TCP/IP client.
/// </summary>
internal class IpcServerTcpClientRouterFactory : DiagnosticsServerRouterFactory
{
ILogger _logger;
IpcServerRouterFactory _ipcServerRouterFactory;
TcpClientRouterFactory _tcpClientRouterFactory;
public IpcServerTcpClientRouterFactory(string ipcServer, string tcpClient, int runtimeTimeoutMs, TcpClientRouterFactory.CreateInstanceDelegate factory, ILogger logger)
{
_logger = logger;
_ipcServerRouterFactory = new IpcServerRouterFactory(ipcServer, logger);
_tcpClientRouterFactory = factory(tcpClient, runtimeTimeoutMs, logger);
}
public override string IpcAddress
{
get
{
return _ipcServerRouterFactory.IpcServerPath;
}
}
public override string TcpAddress
{
get
{
return _tcpClientRouterFactory.TcpClientAddress;
}
}
public override ILogger Logger
{
get
{
return _logger;
}
}
public override Task Start(CancellationToken token)
{
_ipcServerRouterFactory.Start();
_tcpClientRouterFactory.Start();
_logger?.LogInformation($"Starting IPC server ({_ipcServerRouterFactory.IpcServerPath}) <--> TCP client ({_tcpClientRouterFactory.TcpClientAddress}) router.");
return Task.CompletedTask;
}
public override Task Stop()
{
_logger?.LogInformation($"Stopping IPC server ({_ipcServerRouterFactory.IpcServerPath}) <--> TCP client ({_tcpClientRouterFactory.TcpClientAddress}) router.");
_tcpClientRouterFactory.Stop();
_ipcServerRouterFactory.Stop();
return Task.CompletedTask;
}
public override async Task<Router> CreateRouterAsync(CancellationToken token)
{
Stream tcpClientStream = null;
Stream ipcServerStream = null;
_logger?.LogDebug("Trying to create a new router instance.");
try
{
using CancellationTokenSource cancelRouter = CancellationTokenSource.CreateLinkedTokenSource(token);
// Get new server endpoint.
ipcServerStream = await _ipcServerRouterFactory.AcceptIpcStreamAsync(cancelRouter.Token).ConfigureAwait(false);
// Get new client endpoint.
using var tcpClientStreamTask = _tcpClientRouterFactory.ConnectTcpStreamAsync(cancelRouter.Token);
// We have a valid ipc stream and a pending tcp stream. Wait for completion
// or disconnect of ipc stream.
using var checkIpcStreamTask = IsStreamConnectedAsync(ipcServerStream, cancelRouter.Token);
// Wait for at least completion of one task.
await Task.WhenAny(tcpClientStreamTask, checkIpcStreamTask).ConfigureAwait(false);
// Cancel out any pending tasks not yet completed.
cancelRouter.Cancel();
try
{
await Task.WhenAll(tcpClientStreamTask, checkIpcStreamTask).ConfigureAwait(false);
}
catch (Exception)
{
// Check if we have an accepted tcp stream.
if (IsCompletedSuccessfully(tcpClientStreamTask))
tcpClientStreamTask.Result?.Dispose();
if (checkIpcStreamTask.IsFaulted)
{
_logger?.LogInformation("Broken ipc connection detected, aborting tcp connection.");
checkIpcStreamTask.GetAwaiter().GetResult();
}
throw;
}
tcpClientStream = tcpClientStreamTask.Result;
}
catch (Exception)
{
_logger?.LogDebug("Failed creating new router instance.");
// Cleanup and rethrow.
ipcServerStream?.Dispose();
tcpClientStream?.Dispose();
throw;
}
// Create new router.
_logger?.LogDebug("New router instance successfully created.");
return new Router(ipcServerStream, tcpClientStream, _logger);
}
}
/// <summary>
/// This class creates IPC Client - TCP Server router instances.
/// Supports NamedPipes/UnixDomainSocket client and TCP/IP server.
/// </summary>
internal class IpcClientTcpServerRouterFactory : DiagnosticsServerRouterFactory
{
ILogger _logger;
IpcClientRouterFactory _ipcClientRouterFactory;
TcpServerRouterFactory _tcpServerRouterFactory;
public IpcClientTcpServerRouterFactory(string ipcClient, string tcpServer, int runtimeTimeoutMs, TcpServerRouterFactory.CreateInstanceDelegate factory, ILogger logger)
{
_logger = logger;
_ipcClientRouterFactory = new IpcClientRouterFactory(ipcClient, logger);
_tcpServerRouterFactory = factory(tcpServer, runtimeTimeoutMs, logger);
}
public override string IpcAddress
{
get
{
return _ipcClientRouterFactory.IpcClientPath;
}
}
public override string TcpAddress
{
get
{
return _tcpServerRouterFactory.TcpServerAddress;
}
}
public override ILogger Logger
{
get
{
return _logger;
}
}
public override Task Start(CancellationToken token)
{
if (string.IsNullOrEmpty(_ipcClientRouterFactory.IpcClientPath))
throw new ArgumentException("No IPC client path specified.");
_tcpServerRouterFactory.Start();
_logger?.LogInformation($"Starting IPC client ({_ipcClientRouterFactory.IpcClientPath}) <--> TCP server ({_tcpServerRouterFactory.TcpServerAddress}) router.");
return Task.CompletedTask;
}
public override Task Stop()
{
_logger?.LogInformation($"Stopping IPC client ({_ipcClientRouterFactory.IpcClientPath}) <--> TCP server ({_tcpServerRouterFactory.TcpServerAddress}) router.");
return _tcpServerRouterFactory.Stop();
}
public override void Reset()
{
_tcpServerRouterFactory.Reset();
}
public override async Task<Router> CreateRouterAsync(CancellationToken token)
{
Stream tcpServerStream = null;
Stream ipcClientStream = null;
_logger?.LogDebug("Trying to create a new router instance.");
try
{
using CancellationTokenSource cancelRouter = CancellationTokenSource.CreateLinkedTokenSource(token);
// Get new server endpoint.
tcpServerStream = await _tcpServerRouterFactory.AcceptTcpStreamAsync(cancelRouter.Token).ConfigureAwait(false);
// Get new client endpoint.
using var ipcClientStreamTask = _ipcClientRouterFactory.ConnectIpcStreamAsync(cancelRouter.Token);
// We have a valid tcp stream and a pending ipc stream. Wait for completion
// or disconnect of tcp stream.
using var checkTcpStreamTask = IsStreamConnectedAsync(tcpServerStream, cancelRouter.Token);
// Wait for at least completion of one task.