-
Notifications
You must be signed in to change notification settings - Fork 2k
/
OutsideRuntimeClient.cs
922 lines (809 loc) · 36.9 KB
/
OutsideRuntimeClient.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
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Orleans.CodeGeneration;
using Orleans.Messaging;
using Orleans.Providers;
using Orleans.Runtime;
using Orleans.Runtime.Configuration;
using Orleans.Serialization;
using Orleans.Streams;
namespace Orleans
{
internal class OutsideRuntimeClient : IRuntimeClient, IDisposable, IClusterConnectionStatusListener
{
internal static bool TestOnlyThrowExceptionDuringInit { get; set; }
private Logger logger;
private ClientConfiguration config;
private readonly ConcurrentDictionary<CorrelationId, CallbackData> callbacks;
private readonly ConcurrentDictionary<GuidId, LocalObjectData> localObjects;
private ProxiedMessageCenter transport;
private bool listenForMessages;
private CancellationTokenSource listeningCts;
private bool firstMessageReceived;
private ClientProviderRuntime clientProviderRuntime;
private StatisticsProviderManager statisticsProviderManager;
internal ClientStatisticsManager ClientStatistics;
private GrainId clientId;
private readonly GrainId handshakeClientId;
private IGrainTypeResolver grainInterfaceMap;
private ThreadTrackingStatistic incomingMessagesThreadTimeTracking;
private readonly Func<Message, bool> tryResendMessage;
private readonly Action<Message> unregisterCallback;
// initTimeout used to be AzureTableDefaultPolicies.TableCreationTimeout, which was 3 min
private static readonly TimeSpan initTimeout = TimeSpan.FromMinutes(1);
private static readonly TimeSpan resetTimeout = TimeSpan.FromMinutes(1);
private const string BARS = "----------";
public IInternalGrainFactory InternalGrainFactory { get; private set; }
/// <summary>
/// Response timeout.
/// </summary>
private TimeSpan responseTimeout;
private AssemblyProcessor assemblyProcessor;
private MessageFactory messageFactory;
private IPAddress localAddress;
public SerializationManager SerializationManager { get; set; }
public Logger AppLogger { get; private set; }
public ActivationAddress CurrentActivationAddress
{
get;
private set;
}
public string CurrentActivationIdentity
{
get { return CurrentActivationAddress.ToString(); }
}
internal Task<IList<Uri>> GetGateways() =>
this.transport.GatewayManager.ListProvider.GetGateways();
public IStreamProviderManager CurrentStreamProviderManager { get; private set; }
public IStreamProviderRuntime CurrentStreamProviderRuntime
{
get { return clientProviderRuntime; }
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope",
Justification = "MessageCenter is IDisposable but cannot call Dispose yet as it lives past the end of this method call.")]
public OutsideRuntimeClient()
{
this.handshakeClientId = GrainId.NewClientId();
tryResendMessage = TryResendMessage;
unregisterCallback = msg => UnRegisterCallback(msg.Id);
callbacks = new ConcurrentDictionary<CorrelationId, CallbackData>();
localObjects = new ConcurrentDictionary<GuidId, LocalObjectData>();
}
internal void ConsumeServices(IServiceProvider services)
{
this.ServiceProvider = services;
var connectionLostHandlers = services.GetServices<ConnectionToClusterLostHandler>();
foreach (var handler in connectionLostHandlers)
{
this.ClusterConnectionLost += handler;
}
var clientInvokeCallbacks = services.GetServices<ClientInvokeCallback>();
foreach (var handler in clientInvokeCallbacks)
{
this.ClientInvokeCallback += handler;
}
this.InternalGrainFactory = this.ServiceProvider.GetRequiredService<IInternalGrainFactory>();
this.ClientStatistics = this.ServiceProvider.GetRequiredService<ClientStatisticsManager>();
this.SerializationManager = this.ServiceProvider.GetRequiredService<SerializationManager>();
this.messageFactory = this.ServiceProvider.GetService<MessageFactory>();
this.config = services.GetRequiredService<ClientConfiguration>();
if (!LogManager.IsInitialized) LogManager.Initialize(config);
StatisticsCollector.Initialize(config);
this.assemblyProcessor = this.ServiceProvider.GetRequiredService<AssemblyProcessor>();
this.assemblyProcessor.Initialize();
logger = LogManager.GetLogger("OutsideRuntimeClient", LoggerType.Runtime);
this.AppLogger = LogManager.GetLogger("Application", LoggerType.Application);
BufferPool.InitGlobalBufferPool(config);
try
{
LoadAdditionalAssemblies();
if (!UnobservedExceptionsHandlerClass.TrySetUnobservedExceptionHandler(UnhandledException))
{
logger.Warn(ErrorCode.Runtime_Error_100153, "Unable to set unobserved exception handler because it was already set.");
}
AppDomain.CurrentDomain.DomainUnload += CurrentDomain_DomainUnload;
clientProviderRuntime = this.ServiceProvider.GetRequiredService<ClientProviderRuntime>();
statisticsProviderManager = new StatisticsProviderManager("Statistics", clientProviderRuntime);
var statsProviderName = statisticsProviderManager.LoadProvider(config.ProviderConfigurations)
.WaitForResultWithThrow(initTimeout);
if (statsProviderName != null)
{
config.StatisticsProviderName = statsProviderName;
}
responseTimeout = Debugger.IsAttached ? Constants.DEFAULT_RESPONSE_TIMEOUT : config.ResponseTimeout;
this.localAddress = ClusterConfiguration.GetLocalIPAddress(config.PreferredFamily, config.NetInterface);
// Client init / sign-on message
logger.Info(ErrorCode.ClientInitializing, string.Format(
"{0} Initializing OutsideRuntimeClient on {1} at {2} Client Id = {3} {0}",
BARS, config.DNSHostName, localAddress, handshakeClientId));
string startMsg = string.Format("{0} Starting OutsideRuntimeClient with runtime Version='{1}' in AppDomain={2}",
BARS, RuntimeVersion.Current, PrintAppDomainDetails());
startMsg = string.Format("{0} Config= " + Environment.NewLine + " {1}", startMsg, config);
logger.Info(ErrorCode.ClientStarting, startMsg);
if (TestOnlyThrowExceptionDuringInit)
{
throw new InvalidOperationException("TestOnlyThrowExceptionDuringInit");
}
config.CheckGatewayProviderSettings();
if (StatisticsCollector.CollectThreadTimeTrackingStats)
{
incomingMessagesThreadTimeTracking = new ThreadTrackingStatistic("ClientReceiver");
}
}
catch (Exception exc)
{
if (logger != null) logger.Error(ErrorCode.Runtime_Error_100319, "OutsideRuntimeClient constructor failed.", exc);
ConstructorReset();
throw;
}
}
public IServiceProvider ServiceProvider { get; private set; }
private async Task StreamingInitialize()
{
var implicitSubscriberTable = await transport.GetImplicitStreamSubscriberTable(this.InternalGrainFactory);
clientProviderRuntime.StreamingInitialize(implicitSubscriberTable);
var streamProviderManager = this.ServiceProvider.GetRequiredService<StreamProviderManager>();
await streamProviderManager
.LoadStreamProviders(
this.config.ProviderConfigurations,
clientProviderRuntime);
CurrentStreamProviderManager = streamProviderManager;
}
private void LoadAdditionalAssemblies()
{
#if !NETSTANDARD_TODO
var logger = LogManager.GetLogger("AssemblyLoader.Client", LoggerType.Runtime);
var directories =
new Dictionary<string, SearchOption>
{
{
Path.GetDirectoryName(typeof(OutsideRuntimeClient).GetTypeInfo().Assembly.Location),
SearchOption.AllDirectories
}
};
var excludeCriteria =
new AssemblyLoaderPathNameCriterion[]
{
AssemblyLoaderCriteria.ExcludeResourceAssemblies,
AssemblyLoaderCriteria.ExcludeSystemBinaries()
};
var loadProvidersCriteria =
new AssemblyLoaderReflectionCriterion[]
{
AssemblyLoaderCriteria.LoadTypesAssignableFrom(typeof(IProvider))
};
this.assemblyProcessor.Initialize();
AssemblyLoader.LoadAssemblies(directories, excludeCriteria, loadProvidersCriteria, logger);
#endif
}
private void UnhandledException(ISchedulingContext context, Exception exception)
{
logger.Error(ErrorCode.Runtime_Error_100007, String.Format("OutsideRuntimeClient caught an UnobservedException."), exception);
logger.Assert(ErrorCode.Runtime_Error_100008, context == null, "context should be not null only inside OrleansRuntime and not on the client.");
}
public async Task Start()
{
// Deliberately avoid capturing the current synchronization context during startup and execute on the default scheduler.
// This helps to avoid any issues (such as deadlocks) caused by executing with the client's synchronization context/scheduler.
await Task.Run(this.StartInternal).ConfigureAwait(false);
logger.Info(ErrorCode.ProxyClient_StartDone, "{0} Started OutsideRuntimeClient with Global Client ID: {1}", BARS, CurrentActivationAddress.ToString() + ", client GUID ID: " + handshakeClientId);
}
// used for testing to (carefully!) allow two clients in the same process
private async Task StartInternal()
{
var gatewayListProvider = this.ServiceProvider.GetRequiredService<IGatewayListProvider>();
await gatewayListProvider.InitializeGatewayListProvider(config, LogManager.GetLogger(gatewayListProvider.GetType().Name))
.WithTimeout(initTimeout);
var generation = -SiloAddress.AllocateNewGeneration(); // Client generations are negative
transport = ActivatorUtilities.CreateInstance<ProxiedMessageCenter>(this.ServiceProvider, localAddress, generation, handshakeClientId);
transport.Start();
LogManager.MyIPEndPoint = transport.MyAddress.Endpoint; // transport.MyAddress is only set after transport is Started.
CurrentActivationAddress = ActivationAddress.NewActivationAddress(transport.MyAddress, handshakeClientId);
listeningCts = new CancellationTokenSource();
var ct = listeningCts.Token;
listenForMessages = true;
// Keeping this thread handling it very simple for now. Just queue task on thread pool.
Task.Run(
() =>
{
try
{
RunClientMessagePump(ct);
}
catch (Exception exc)
{
logger.Error(ErrorCode.Runtime_Error_100326, "RunClientMessagePump has thrown exception", exc);
}
},
ct).Ignore();
grainInterfaceMap = await transport.GetTypeCodeMap(this.InternalGrainFactory);
await ClientStatistics.Start(statisticsProviderManager, transport, clientId)
.WithTimeout(initTimeout);
await StreamingInitialize();
}
private void RunClientMessagePump(CancellationToken ct)
{
if (StatisticsCollector.CollectThreadTimeTrackingStats)
{
incomingMessagesThreadTimeTracking.OnStartExecution();
}
while (listenForMessages)
{
var message = transport.WaitMessage(Message.Categories.Application, ct);
if (message == null) // if wait was cancelled
break;
#if TRACK_DETAILED_STATS
if (StatisticsCollector.CollectThreadTimeTrackingStats)
{
incomingMessagesThreadTimeTracking.OnStartProcessing();
}
#endif
// when we receive the first message, we update the
// clientId for this client because it may have been modified to
// include the cluster name
if (!firstMessageReceived)
{
firstMessageReceived = true;
if (!handshakeClientId.Equals(message.TargetGrain))
{
clientId = message.TargetGrain;
transport.UpdateClientId(clientId);
CurrentActivationAddress = ActivationAddress.GetAddress(transport.MyAddress, clientId, CurrentActivationAddress.Activation);
}
else
{
clientId = handshakeClientId;
}
}
switch (message.Direction)
{
case Message.Directions.Response:
{
ReceiveResponse(message);
break;
}
case Message.Directions.OneWay:
case Message.Directions.Request:
{
this.DispatchToLocalObject(message);
break;
}
default:
logger.Error(ErrorCode.Runtime_Error_100327, String.Format("Message not supported: {0}.", message));
break;
}
#if TRACK_DETAILED_STATS
if (StatisticsCollector.CollectThreadTimeTrackingStats)
{
incomingMessagesThreadTimeTracking.OnStopProcessing();
incomingMessagesThreadTimeTracking.IncrementNumberOfProcessed();
}
#endif
}
if (StatisticsCollector.CollectThreadTimeTrackingStats)
{
incomingMessagesThreadTimeTracking.OnStopExecution();
}
}
private void DispatchToLocalObject(Message message)
{
LocalObjectData objectData;
GuidId observerId = message.TargetObserverId;
if (observerId == null)
{
logger.Error(
ErrorCode.ProxyClient_OGC_TargetNotFound_2,
String.Format("Did not find TargetObserverId header in the message = {0}. A request message to a client is expected to have an observerId.", message));
return;
}
if (localObjects.TryGetValue(observerId, out objectData))
this.InvokeLocalObjectAsync(objectData, message);
else
{
logger.Error(
ErrorCode.ProxyClient_OGC_TargetNotFound,
String.Format(
"Unexpected target grain in request: {0}. Message={1}",
message.TargetGrain,
message));
}
}
private void InvokeLocalObjectAsync(LocalObjectData objectData, Message message)
{
var obj = (IAddressable)objectData.LocalObject.Target;
if (obj == null)
{
//// Remove from the dictionary record for the garbage collected object? But now we won't be able to detect invalid dispatch IDs anymore.
logger.Warn(ErrorCode.Runtime_Error_100162,
String.Format("Object associated with Observer ID {0} has been garbage collected. Deleting object reference and unregistering it. Message = {1}", objectData.ObserverId, message));
LocalObjectData ignore;
// Try to remove. If it's not there, we don't care.
localObjects.TryRemove(objectData.ObserverId, out ignore);
return;
}
bool start;
lock (objectData.Messages)
{
objectData.Messages.Enqueue(message);
start = !objectData.Running;
objectData.Running = true;
}
if (logger.IsVerbose) logger.Verbose("InvokeLocalObjectAsync {0} start {1}", message, start);
if (start)
{
// we use Task.Run() to ensure that the message pump operates asynchronously
// with respect to the current thread. see
// http://channel9.msdn.com/Events/TechEd/Europe/2013/DEV-B317#fbid=aIWUq0ssW74
// at position 54:45.
//
// according to the information posted at:
// http://stackoverflow.com/questions/12245935/is-task-factory-startnew-guaranteed-to-use-another-thread-than-the-calling-thr
// this idiom is dependent upon the a TaskScheduler not implementing the
// override QueueTask as task inlining (as opposed to queueing). this seems
// implausible to the author, since none of the .NET schedulers do this and
// it is considered bad form (the OrleansTaskScheduler does not do this).
//
// if, for some reason this doesn't hold true, we can guarantee what we
// want by passing a placeholder continuation token into Task.StartNew()
// instead. i.e.:
//
// return Task.StartNew(() => ..., new CancellationToken());
Func<Task> asyncFunc =
async () =>
await this.LocalObjectMessagePumpAsync(objectData);
Task.Run(asyncFunc).Ignore();
}
}
private async Task LocalObjectMessagePumpAsync(LocalObjectData objectData)
{
while (true)
{
try
{
Message message;
lock (objectData.Messages)
{
if (objectData.Messages.Count == 0)
{
objectData.Running = false;
break;
}
message = objectData.Messages.Dequeue();
}
if (ExpireMessageIfExpired(message, MessagingStatisticsGroup.Phase.Invoke))
continue;
RequestContext.Import(message.RequestContextData);
var request = (InvokeMethodRequest)message.GetDeserializedBody(this.SerializationManager);
var targetOb = (IAddressable)objectData.LocalObject.Target;
object resultObject = null;
Exception caught = null;
try
{
// exceptions thrown within this scope are not considered to be thrown from user code
// and not from runtime code.
var resultPromise = objectData.Invoker.Invoke(targetOb, request);
if (resultPromise != null) // it will be null for one way messages
{
resultObject = await resultPromise;
}
}
catch (Exception exc)
{
// the exception needs to be reported in the log or propagated back to the caller.
caught = exc;
}
if (caught != null)
this.ReportException(message, caught);
else if (message.Direction != Message.Directions.OneWay)
await this.SendResponseAsync(message, resultObject);
}
catch (Exception)
{
// ignore, keep looping.
}
}
}
private static bool ExpireMessageIfExpired(Message message, MessagingStatisticsGroup.Phase phase)
{
if (message.IsExpired)
{
message.DropExpiredMessage(phase);
return true;
}
return false;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private Task
SendResponseAsync(
Message message,
object resultObject)
{
if (ExpireMessageIfExpired(message, MessagingStatisticsGroup.Phase.Respond))
return TaskDone.Done;
object deepCopy = null;
try
{
// we're expected to notify the caller if the deep copy failed.
deepCopy = this.SerializationManager.DeepCopy(resultObject);
}
catch (Exception exc2)
{
SendResponse(message, Response.ExceptionResponse(exc2));
logger.Warn(
ErrorCode.ProxyClient_OGC_SendResponseFailed,
"Exception trying to send a response.", exc2);
return TaskDone.Done;
}
// the deep-copy succeeded.
SendResponse(message, new Response(deepCopy));
return TaskDone.Done;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private void ReportException(Message message, Exception exception)
{
var request = (InvokeMethodRequest)message.GetDeserializedBody(this.SerializationManager);
switch (message.Direction)
{
default:
throw new InvalidOperationException();
case Message.Directions.OneWay:
{
logger.Error(
ErrorCode.ProxyClient_OGC_UnhandledExceptionInOneWayInvoke,
String.Format(
"Exception during invocation of notification method {0}, interface {1}. Ignoring exception because this is a one way request.",
request.MethodId,
request.InterfaceId),
exception);
break;
}
case Message.Directions.Request:
{
Exception deepCopy = null;
try
{
// we're expected to notify the caller if the deep copy failed.
deepCopy = (Exception)this.SerializationManager.DeepCopy(exception);
}
catch (Exception ex2)
{
SendResponse(message, Response.ExceptionResponse(ex2));
logger.Warn(
ErrorCode.ProxyClient_OGC_SendExceptionResponseFailed,
"Exception trying to send an exception response", ex2);
return;
}
// the deep-copy succeeded.
var response = Response.ExceptionResponse(deepCopy);
SendResponse(message, response);
break;
}
}
}
private void SendResponse(Message request, Response response)
{
var message = this.messageFactory.CreateResponseMessage(request);
message.BodyObject = response;
transport.SendMessage(message);
}
/// <summary>
/// For testing only.
/// </summary>
public void Disconnect()
{
transport.Disconnect();
}
/// <summary>
/// For testing only.
/// </summary>
public void Reconnect()
{
transport.Reconnect();
}
#region Implementation of IRuntimeClient
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope",
Justification = "CallbackData is IDisposable but instances exist beyond lifetime of this method so cannot Dispose yet.")]
public void SendRequest(GrainReference target, InvokeMethodRequest request, TaskCompletionSource<object> context, Action<Message, TaskCompletionSource<object>> callback, string debugContext = null, InvokeMethodOptions options = InvokeMethodOptions.None, string genericArguments = null)
{
var message = this.messageFactory.CreateMessage(request, options);
SendRequestMessage(target, message, context, callback, debugContext, options, genericArguments);
}
private void SendRequestMessage(GrainReference target, Message message, TaskCompletionSource<object> context, Action<Message, TaskCompletionSource<object>> callback, string debugContext = null, InvokeMethodOptions options = InvokeMethodOptions.None, string genericArguments = null)
{
var targetGrainId = target.GrainId;
var oneWay = (options & InvokeMethodOptions.OneWay) != 0;
message.SendingGrain = CurrentActivationAddress.Grain;
message.SendingActivation = CurrentActivationAddress.Activation;
message.TargetGrain = targetGrainId;
if (!String.IsNullOrEmpty(genericArguments))
message.GenericGrainType = genericArguments;
if (targetGrainId.IsSystemTarget)
{
// If the silo isn't be supplied, it will be filled in by the sender to be the gateway silo
message.TargetSilo = target.SystemTargetSilo;
if (target.SystemTargetSilo != null)
{
message.TargetActivation = ActivationId.GetSystemActivation(targetGrainId, target.SystemTargetSilo);
}
}
// Client sending messages to another client (observer). Yes, we support that.
if (target.IsObserverReference)
{
message.TargetObserverId = target.ObserverId;
}
if (debugContext != null)
{
message.DebugContext = debugContext;
}
if (message.IsExpirableMessage(config))
{
// don't set expiration for system target messages.
message.Expiration = DateTime.UtcNow + responseTimeout + Constants.MAXIMUM_CLOCK_SKEW;
}
if (!oneWay)
{
var callbackData = new CallbackData(
callback,
tryResendMessage,
context,
message,
unregisterCallback,
config);
callbacks.TryAdd(message.Id, callbackData);
callbackData.StartTimer(responseTimeout);
}
if (logger.IsVerbose2) logger.Verbose2("Send {0}", message);
transport.SendMessage(message);
}
private bool TryResendMessage(Message message)
{
if (!message.MayResend(config))
{
return false;
}
if (logger.IsVerbose) logger.Verbose("Resend {0}", message);
message.ResendCount = message.ResendCount + 1;
message.TargetHistory = message.GetTargetHistory();
if (!message.TargetGrain.IsSystemTarget)
{
message.TargetActivation = null;
message.TargetSilo = null;
message.ClearTargetAddress();
}
transport.SendMessage(message);
return true;
}
public void ReceiveResponse(Message response)
{
if (logger.IsVerbose2) logger.Verbose2("Received {0}", response);
// ignore duplicate requests
if (response.Result == Message.ResponseTypes.Rejection && response.RejectionType == Message.RejectionTypes.DuplicateRequest)
return;
CallbackData callbackData;
var found = callbacks.TryGetValue(response.Id, out callbackData);
if (found)
{
// We need to import the RequestContext here as well.
// Unfortunately, it is not enough, since CallContext.LogicalGetData will not flow "up" from task completion source into the resolved task.
// RequestContext.Import(response.RequestContextData);
callbackData.DoCallback(response);
}
else
{
logger.Warn(ErrorCode.Runtime_Error_100011, "No callback for response message: " + response);
}
}
private void UnRegisterCallback(CorrelationId id)
{
CallbackData ignore;
callbacks.TryRemove(id, out ignore);
}
public void Reset(bool cleanup)
{
Utils.SafeExecute(() =>
{
if (logger != null)
{
logger.Info("OutsideRuntimeClient.Reset(): client Id " + clientId);
}
});
Utils.SafeExecute(() =>
{
if (clientProviderRuntime != null)
{
clientProviderRuntime.Reset(cleanup).WaitWithThrow(resetTimeout);
}
}, logger, "Client.clientProviderRuntime.Reset");
Utils.SafeExecute(() =>
{
if (StatisticsCollector.CollectThreadTimeTrackingStats)
{
incomingMessagesThreadTimeTracking.OnStopExecution();
}
}, logger, "Client.incomingMessagesThreadTimeTracking.OnStopExecution");
Utils.SafeExecute(() =>
{
if (transport != null)
{
transport.PrepareToStop();
}
}, logger, "Client.PrepareToStop-Transport");
listenForMessages = false;
Utils.SafeExecute(() =>
{
if (listeningCts != null)
{
listeningCts.Cancel();
}
}, logger, "Client.Stop-ListeningCTS");
Utils.SafeExecute(() =>
{
if (transport != null)
{
transport.Stop();
}
}, logger, "Client.Stop-Transport");
Utils.SafeExecute(() =>
{
if (ClientStatistics != null)
{
ClientStatistics.Stop();
}
}, logger, "Client.Stop-ClientStatistics");
ConstructorReset();
}
private void ConstructorReset()
{
Utils.SafeExecute(() =>
{
if (logger != null)
{
logger.Info("OutsideRuntimeClient.ConstructorReset(): client Id " + clientId);
}
});
try
{
UnobservedExceptionsHandlerClass.ResetUnobservedExceptionHandler();
}
catch (Exception) { }
try
{
AppDomain.CurrentDomain.DomainUnload -= CurrentDomain_DomainUnload;
}
catch (Exception) { }
try
{
if (clientProviderRuntime != null)
{
clientProviderRuntime.Reset().WaitWithThrow(resetTimeout);
}
}
catch (Exception) { }
try
{
LogManager.UnInitialize();
}
catch (Exception) { }
}
public void SetResponseTimeout(TimeSpan timeout)
{
responseTimeout = timeout;
}
public TimeSpan GetResponseTimeout()
{
return responseTimeout;
}
public GrainReference CreateObjectReference(IAddressable obj, IGrainMethodInvoker invoker)
{
if (obj is GrainReference)
throw new ArgumentException("Argument obj is already a grain reference.");
GrainReference gr = GrainReference.NewObserverGrainReference(clientId, GuidId.GetNewGuidId(), this);
if (!localObjects.TryAdd(gr.ObserverId, new LocalObjectData(obj, gr.ObserverId, invoker)))
{
throw new ArgumentException(String.Format("Failed to add new observer {0} to localObjects collection.", gr), "gr");
}
return gr;
}
public void DeleteObjectReference(IAddressable obj)
{
if (!(obj is GrainReference))
throw new ArgumentException("Argument reference is not a grain reference.");
var reference = (GrainReference)obj;
LocalObjectData ignore;
if (!localObjects.TryRemove(reference.ObserverId, out ignore))
throw new ArgumentException("Reference is not associated with a local object.", "reference");
}
#endregion Implementation of IRuntimeClient
private void CurrentDomain_DomainUnload(object sender, EventArgs e)
{
try
{
logger.Warn(ErrorCode.ProxyClient_AppDomain_Unload,
String.Format("Current AppDomain={0} is unloading.", PrintAppDomainDetails()));
LogManager.Flush();
}
catch (Exception)
{
// just ignore, make sure not to throw from here.
}
}
private string PrintAppDomainDetails()
{
#if NETSTANDARD_TODO
return "N/A";
#else
return string.Format("<AppDomain.Id={0}, AppDomain.FriendlyName={1}>", AppDomain.CurrentDomain.Id, AppDomain.CurrentDomain.FriendlyName);
#endif
}
private class LocalObjectData
{
internal WeakReference LocalObject { get; private set; }
internal IGrainMethodInvoker Invoker { get; private set; }
internal GuidId ObserverId { get; private set; }
internal Queue<Message> Messages { get; private set; }
internal bool Running { get; set; }
internal LocalObjectData(IAddressable obj, GuidId observerId, IGrainMethodInvoker invoker)
{
LocalObject = new WeakReference(obj);
ObserverId = observerId;
Invoker = invoker;
Messages = new Queue<Message>();
Running = false;
}
}
public void Dispose()
{
if (listeningCts != null)
{
listeningCts.Dispose();
listeningCts = null;
this.assemblyProcessor?.Dispose();
}
transport?.Dispose();
if (ClientStatistics != null)
{
ClientStatistics.Dispose();
ClientStatistics = null;
}
GC.SuppressFinalize(this);
}
public IGrainTypeResolver GrainTypeResolver
{
get { return grainInterfaceMap; }
}
public void BreakOutstandingMessagesToDeadSilo(SiloAddress deadSilo)
{
foreach (var callback in callbacks)
{
if (deadSilo.Equals(callback.Value.Message.TargetSilo))
{
callback.Value.OnTargetSiloFail();
}
}
}
/// <inheritdoc />
public ClientInvokeCallback ClientInvokeCallback { get; set; }
/// <inheritdoc />
public event ConnectionToClusterLostHandler ClusterConnectionLost;
/// <inheritdoc />
public void NotifyClusterConnectionLost()
{
try
{
this.ClusterConnectionLost?.Invoke(this, EventArgs.Empty);
}
catch (Exception ex)
{
this.logger.Error(ErrorCode.ClientError, "Error when sending cluster disconnection notification", ex);
}
}
}
}