-
Notifications
You must be signed in to change notification settings - Fork 2k
/
TestCluster.cs
710 lines (623 loc) · 26.2 KB
/
TestCluster.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
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Orleans.Runtime;
using Orleans.Serialization;
using Orleans.TestingHost.Utils;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Memory;
using Orleans.Configuration;
using Microsoft.Extensions.Options;
namespace Orleans.TestingHost
{
/// <summary>
/// A host class for local testing with Orleans using in-process silos.
/// Runs a Primary and optionally secondary silos in separate app domains, and client in the main app domain.
/// Additional silos can also be started in-process on demand if required for particular test cases.
/// </summary>
/// <remarks>
/// Make sure that your test project references your test grains and test grain interfaces
/// projects, and has CopyLocal=True set on those references [which should be the default].
/// </remarks>
public class TestCluster : IDisposable, IAsyncDisposable
{
private readonly List<SiloHandle> additionalSilos = new List<SiloHandle>();
private readonly TestClusterOptions options;
private readonly StringBuilder log = new StringBuilder();
private bool _disposed;
private int startedInstances;
/// <summary>
/// Primary silo handle, if applicable.
/// </summary>
/// <remarks>This handle is valid only when using Grain-based membership.</remarks>
public SiloHandle Primary { get; private set; }
/// <summary>
/// List of handles to the secondary silos.
/// </summary>
public IReadOnlyList<SiloHandle> SecondarySilos
{
get
{
lock (this.additionalSilos)
{
return new List<SiloHandle>(this.additionalSilos);
}
}
}
/// <summary>
/// Collection of all known silos.
/// </summary>
public ReadOnlyCollection<SiloHandle> Silos
{
get
{
var result = new List<SiloHandle>();
if (this.Primary != null)
{
result.Add(this.Primary);
}
lock (this.additionalSilos)
{
result.AddRange(this.additionalSilos);
}
return result.AsReadOnly();
}
}
/// <summary>
/// Options used to configure the test cluster.
/// </summary>
/// <remarks>This is the options you configured your test cluster with, or the default one.
/// If the cluster is being configured via ClusterConfiguration, then this object may not reflect the true settings.
/// </remarks>
public TestClusterOptions Options => this.options;
/// <summary>
/// The internal client interface.
/// </summary>
internal IInternalClusterClient InternalClient { get; private set; }
/// <summary>
/// The client.
/// </summary>
public IClusterClient Client => this.InternalClient;
/// <summary>
/// GrainFactory to use in the tests
/// </summary>
public IGrainFactory GrainFactory => this.Client;
/// <summary>
/// GrainFactory to use in the tests
/// </summary>
internal IInternalGrainFactory InternalGrainFactory => this.InternalClient;
/// <summary>
/// Client-side <see cref="IServiceProvider"/> to use in the tests.
/// </summary>
public IServiceProvider ServiceProvider => this.Client.ServiceProvider;
/// <summary>
/// SerializationManager to use in the tests
/// </summary>
public SerializationManager SerializationManager { get; private set; }
/// <summary>
/// Delegate used to create and start an individual silo.
/// </summary>
public Func<string, IList<IConfigurationSource>, Task<SiloHandle>> CreateSiloAsync { private get; set; } = InProcessSiloHandle.CreateAsync;
/// <summary>
/// The port allocator.
/// </summary>
public ITestClusterPortAllocator PortAllocator { get; }
/// <summary>
/// Configures the test cluster plus client in-process.
/// </summary>
public TestCluster(
TestClusterOptions options,
IReadOnlyList<IConfigurationSource> configurationSources,
ITestClusterPortAllocator portAllocator)
{
this.options = options;
this.ConfigurationSources = configurationSources.ToArray();
this.PortAllocator = portAllocator;
}
/// <summary>
/// Deploys the cluster using the specified configuration and starts the client in-process.
/// It will start the number of silos defined in <see cref="TestClusterOptions.InitialSilosCount"/>.
/// </summary>
public void Deploy()
{
this.DeployAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Deploys the cluster using the specified configuration and starts the client in-process.
/// </summary>
public async Task DeployAsync()
{
if (this.Primary != null || this.additionalSilos.Count > 0) throw new InvalidOperationException("Cluster host already deployed.");
AppDomain.CurrentDomain.UnhandledException += ReportUnobservedException;
try
{
string startMsg = "----------------------------- STARTING NEW UNIT TEST SILO HOST: " + GetType().FullName + " -------------------------------------";
WriteLog(startMsg);
await InitializeAsync();
if (this.options.InitializeClientOnDeploy)
{
await WaitForInitialStabilization();
}
}
catch (TimeoutException te)
{
FlushLogToConsole();
throw new TimeoutException("Timeout during test initialization", te);
}
catch (Exception ex)
{
await StopAllSilosAsync();
Exception baseExc = ex.GetBaseException();
FlushLogToConsole();
if (baseExc is TimeoutException)
{
throw new TimeoutException("Timeout during test initialization", ex);
}
// IMPORTANT:
// Do NOT re-throw the original exception here, also not as an internal exception inside AggregateException
// Due to the way MS tests works, if the original exception is an Orleans exception,
// it's assembly might not be loaded yet in this phase of the test.
// As a result, we will get "MSTest: Unit Test Adapter threw exception: Type is not resolved for member XXX"
// and will loose the original exception. This makes debugging tests super hard!
// The root cause has to do with us initializing our tests from Test constructor and not from TestInitialize method.
// More details: http://dobrzanski.net/2010/09/20/mstest-unit-test-adapter-threw-exception-type-is-not-resolved-for-member/
//throw new Exception(
// string.Format("Exception during test initialization: {0}",
// LogFormatter.PrintException(baseExc)));
throw;
}
}
private async Task WaitForInitialStabilization()
{
// Poll each silo to check that it knows the expected number of active silos.
// If any silo does not have the expected number of active silos in its cluster membership oracle, try again.
// If the cluster membership has not stabilized after a certain period of time, give up and continue anyway.
var totalWait = Stopwatch.StartNew();
while (true)
{
var silos = this.Silos;
var expectedCount = silos.Count;
var remainingSilos = expectedCount;
foreach (var silo in silos)
{
var hooks = this.InternalClient.GetTestHooks(silo);
var statuses = await hooks.GetApproximateSiloStatuses();
var activeCount = statuses.Count(s => s.Value == SiloStatus.Active);
if (activeCount != expectedCount) break;
remainingSilos--;
}
if (remainingSilos == 0)
{
totalWait.Stop();
break;
}
WriteLog($"{remainingSilos} silos do not have a consistent cluster view, waiting until stabilization.");
await Task.Delay(TimeSpan.FromMilliseconds(100));
if (totalWait.Elapsed < TimeSpan.FromSeconds(60))
{
WriteLog($"Warning! {remainingSilos} silos do not have a consistent cluster view after {totalWait.ElapsedMilliseconds}ms, continuing without stabilization.");
break;
}
}
}
/// <summary>
/// Get the list of current active silos.
/// </summary>
/// <returns>List of current silos.</returns>
public IEnumerable<SiloHandle> GetActiveSilos()
{
var additional = new List<SiloHandle>();
lock (additionalSilos)
{
additional.AddRange(additionalSilos);
}
WriteLog("GetActiveSilos: Primary={0} + {1} Additional={2}",
Primary, additional.Count, Runtime.Utils.EnumerableToString(additional));
if (Primary?.IsActive == true) yield return Primary;
if (additional.Count > 0)
foreach (var s in additional)
if (s?.IsActive == true)
yield return s;
}
/// <summary>
/// Find the silo handle for the specified silo address.
/// </summary>
/// <param name="siloAddress">Silo address to be found.</param>
/// <returns>SiloHandle of the appropriate silo, or <c>null</c> if not found.</returns>
public SiloHandle GetSiloForAddress(SiloAddress siloAddress)
{
var activeSilos = GetActiveSilos().ToList();
var ret = activeSilos.FirstOrDefault(s => s.SiloAddress.Equals(siloAddress));
return ret;
}
/// <summary>
/// Wait for the silo liveness sub-system to detect and act on any recent cluster membership changes.
/// </summary>
/// <param name="didKill">Whether recent membership changes we done by graceful Stop.</param>
public async Task WaitForLivenessToStabilizeAsync(bool didKill = false)
{
var clusterMembershipOptions = this.ServiceProvider.GetRequiredService<IOptions<ClusterMembershipOptions>>().Value;
TimeSpan stabilizationTime = GetLivenessStabilizationTime(clusterMembershipOptions, didKill);
WriteLog(Environment.NewLine + Environment.NewLine + "WaitForLivenessToStabilize is about to sleep for {0}", stabilizationTime);
await Task.Delay(stabilizationTime);
WriteLog("WaitForLivenessToStabilize is done sleeping");
}
/// <summary>
/// Get the timeout value to use to wait for the silo liveness sub-system to detect and act on any recent cluster membership changes.
/// <seealso cref="WaitForLivenessToStabilizeAsync"/>
/// </summary>
public static TimeSpan GetLivenessStabilizationTime(ClusterMembershipOptions clusterMembershipOptions, bool didKill = false)
{
TimeSpan stabilizationTime = TimeSpan.Zero;
if (didKill)
{
// in case of hard kill (kill and not Stop), we should give silos time to detect failures first.
stabilizationTime = TestingUtils.Multiply(clusterMembershipOptions.ProbeTimeout, clusterMembershipOptions.NumMissedProbesLimit);
}
if (clusterMembershipOptions.UseLivenessGossip)
{
stabilizationTime += TimeSpan.FromSeconds(5);
}
else
{
stabilizationTime += TestingUtils.Multiply(clusterMembershipOptions.TableRefreshTimeout, 2);
}
return stabilizationTime;
}
/// <summary>
/// Start an additional silo, so that it joins the existing cluster.
/// </summary>
/// <returns>SiloHandle for the newly started silo.</returns>
public SiloHandle StartAdditionalSilo(bool startAdditionalSiloOnNewPort = false)
{
return StartAdditionalSiloAsync(startAdditionalSiloOnNewPort).GetAwaiter().GetResult();
}
/// <summary>
/// Start an additional silo, so that it joins the existing cluster.
/// </summary>
/// <returns>SiloHandle for the newly started silo.</returns>
public async Task<SiloHandle> StartAdditionalSiloAsync(bool startAdditionalSiloOnNewPort = false)
{
return (await this.StartAdditionalSilosAsync(1, startAdditionalSiloOnNewPort)).Single();
}
/// <summary>
/// Start a number of additional silo, so that they join the existing cluster.
/// </summary>
/// <param name="silosToStart">Number of silos to start.</param>
/// <param name="startAdditionalSiloOnNewPort"></param>
/// <returns>List of SiloHandles for the newly started silos.</returns>
public async Task<List<SiloHandle>> StartAdditionalSilosAsync(int silosToStart, bool startAdditionalSiloOnNewPort = false)
{
var instances = new List<SiloHandle>();
if (silosToStart > 0)
{
var siloStartTasks = Enumerable.Range(this.startedInstances, silosToStart)
.Select(instanceNumber => Task.Run(() => StartSiloAsync((short)instanceNumber, this.options, startSiloOnNewPort: startAdditionalSiloOnNewPort))).ToArray();
try
{
await Task.WhenAll(siloStartTasks);
}
catch (Exception)
{
lock (additionalSilos)
{
this.additionalSilos.AddRange(siloStartTasks.Where(t => t.Exception == null).Select(t => t.Result));
}
throw;
}
instances.AddRange(siloStartTasks.Select(t => t.Result));
lock (additionalSilos)
{
this.additionalSilos.AddRange(instances);
}
}
return instances;
}
/// <summary>
/// Stop any additional silos, not including the default Primary silo.
/// </summary>
public async Task StopSecondarySilosAsync()
{
foreach (var instance in this.additionalSilos.ToList())
{
await StopSiloAsync(instance);
}
}
/// <summary>
/// Stops the default Primary silo.
/// </summary>
public async Task StopPrimarySiloAsync()
{
if (Primary == null) throw new InvalidOperationException("There is no primary silo");
await StopClusterClientAsync();
await StopSiloAsync(Primary);
}
private async Task StopClusterClientAsync()
{
var client = this.InternalClient;
try
{
if (client != null)
{
await client.Close().ConfigureAwait(false);
}
}
catch (Exception exc)
{
WriteLog("Exception stopping client: {0}", exc);
}
finally
{
if (client is object)
{
await client.DisposeAsync().ConfigureAwait(false);
}
this.InternalClient = null;
}
}
/// <summary>
/// Stop all current silos.
/// </summary>
public void StopAllSilos()
{
StopAllSilosAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Stop all current silos.
/// </summary>
public async Task StopAllSilosAsync()
{
await StopClusterClientAsync();
await StopSecondarySilosAsync();
if (Primary != null)
{
await StopPrimarySiloAsync();
}
AppDomain.CurrentDomain.UnhandledException -= ReportUnobservedException;
}
/// <summary>
/// Do a semi-graceful Stop of the specified silo.
/// </summary>
/// <param name="instance">Silo to be stopped.</param>
public async Task StopSiloAsync(SiloHandle instance)
{
if (instance != null)
{
await StopSiloAsync(instance, true);
if (Primary == instance)
{
Primary = null;
}
else
{
lock (additionalSilos)
{
additionalSilos.Remove(instance);
}
}
}
}
/// <summary>
/// Do an immediate Kill of the specified silo.
/// </summary>
/// <param name="instance">Silo to be killed.</param>
public async Task KillSiloAsync(SiloHandle instance)
{
if (instance != null)
{
// do NOT stop, just kill directly, to simulate crash.
await StopSiloAsync(instance, false);
if (Primary == instance)
{
Primary = null;
}
else
{
lock (additionalSilos)
{
additionalSilos.Remove(instance);
}
}
}
}
/// <summary>
/// Performs a hard kill on client. Client will not cleanup resources.
/// </summary>
public async Task KillClientAsync()
{
if (InternalClient != null)
{
await this.InternalClient.AbortAsync();
this.InternalClient = null;
}
}
/// <summary>
/// Do a Stop or Kill of the specified silo, followed by a restart.
/// </summary>
/// <param name="instance">Silo to be restarted.</param>
public async Task<SiloHandle> RestartSiloAsync(SiloHandle instance)
{
if (instance != null)
{
var instanceNumber = instance.InstanceNumber;
var siloName = instance.Name;
await StopSiloAsync(instance);
var newInstance = await StartSiloAsync(instanceNumber, this.options);
if (siloName == Silo.PrimarySiloName)
{
Primary = newInstance;
}
else
{
lock (additionalSilos)
{
additionalSilos.Add(newInstance);
}
}
return newInstance;
}
return null;
}
/// <summary>
/// Restart a previously stopped.
/// </summary>
/// <param name="siloName">Silo to be restarted.</param>
public async Task<SiloHandle> RestartStoppedSecondarySiloAsync(string siloName)
{
if (siloName == null) throw new ArgumentNullException(nameof(siloName));
var siloHandle = this.Silos.Single(s => s.Name.Equals(siloName, StringComparison.Ordinal));
var newInstance = await this.StartSiloAsync(this.Silos.IndexOf(siloHandle), this.options);
lock (additionalSilos)
{
additionalSilos.Add(newInstance);
}
return newInstance;
}
/// <summary>
/// Initialize the grain client. This should be already done by <see cref="Deploy()"/> or <see cref="DeployAsync"/>
/// </summary>
public void InitializeClient()
{
WriteLog("Initializing Cluster Client");
this.InternalClient = (IInternalClusterClient)TestClusterHostFactory.CreateClusterClient("MainClient", this.ConfigurationSources);
this.InternalClient.Connect().GetAwaiter().GetResult();
this.SerializationManager = this.ServiceProvider.GetRequiredService<SerializationManager>();
}
public IReadOnlyList<IConfigurationSource> ConfigurationSources { get; }
private async Task InitializeAsync()
{
short silosToStart = this.options.InitialSilosCount;
if (this.options.UseTestClusterMembership)
{
this.Primary = await StartSiloAsync(this.startedInstances, this.options);
silosToStart--;
}
if (silosToStart > 0)
{
await this.StartAdditionalSilosAsync(silosToStart);
}
WriteLog("Done initializing cluster");
if (this.options.InitializeClientOnDeploy)
{
InitializeClient();
}
}
/// <summary>
/// Start a new silo in the target cluster
/// </summary>
/// <param name="cluster">The TestCluster in which the silo should be deployed</param>
/// <param name="instanceNumber">The instance number to deploy</param>
/// <param name="clusterOptions">The options to use.</param>
/// <param name="configurationOverrides">Configuration overrides.</param>
/// <param name="startSiloOnNewPort">Whether we start this silo on a new port, instead of the default one</param>
/// <returns>A handle to the silo deployed</returns>
public static async Task<SiloHandle> StartSiloAsync(TestCluster cluster, int instanceNumber, TestClusterOptions clusterOptions, IReadOnlyList<IConfigurationSource> configurationOverrides = null, bool startSiloOnNewPort = false)
{
if (cluster == null) throw new ArgumentNullException(nameof(cluster));
return await cluster.StartSiloAsync(instanceNumber, clusterOptions, configurationOverrides, startSiloOnNewPort);
}
/// <summary>
/// Starts a new silo.
/// </summary>
/// <param name="instanceNumber">The instance number to deploy</param>
/// <param name="clusterOptions">The options to use.</param>
/// <param name="configurationOverrides">Configuration overrides.</param>
/// <param name="startSiloOnNewPort">Whether we start this silo on a new port, instead of the default one</param>
/// <returns>A handle to the deployed silo.</returns>
public async Task<SiloHandle> StartSiloAsync(int instanceNumber, TestClusterOptions clusterOptions, IReadOnlyList<IConfigurationSource> configurationOverrides = null, bool startSiloOnNewPort = false)
{
var configurationSources = this.ConfigurationSources.ToList();
// Add overrides.
if (configurationOverrides != null) configurationSources.AddRange(configurationOverrides);
var siloSpecificOptions = TestSiloSpecificOptions.Create(this, clusterOptions, instanceNumber, startSiloOnNewPort);
configurationSources.Add(new MemoryConfigurationSource
{
InitialData = siloSpecificOptions.ToDictionary()
});
var handle = await this.CreateSiloAsync(siloSpecificOptions.SiloName, configurationSources);
handle.InstanceNumber = (short)instanceNumber;
Interlocked.Increment(ref this.startedInstances);
return handle;
}
private async Task StopSiloAsync(SiloHandle instance, bool stopGracefully)
{
try
{
await instance.StopSiloAsync(stopGracefully).ConfigureAwait(false);
}
finally
{
await instance.DisposeAsync().ConfigureAwait(false);
Interlocked.Decrement(ref this.startedInstances);
}
}
public string GetLog()
{
return this.log.ToString();
}
private void ReportUnobservedException(object sender, UnhandledExceptionEventArgs eventArgs)
{
Exception exception = (Exception)eventArgs.ExceptionObject;
this.WriteLog("Unobserved exception: {0}", exception);
}
private void WriteLog(string format, params object[] args)
{
log.AppendFormat(format + Environment.NewLine, args);
}
private void FlushLogToConsole()
{
Console.WriteLine(GetLog());
}
public async ValueTask DisposeAsync()
{
if (_disposed)
{
return;
}
await Task.Run(async () =>
{
foreach (var handle in this.SecondarySilos)
{
await handle.DisposeAsync().ConfigureAwait(false);
}
if (this.Primary is object)
{
await this.Primary.DisposeAsync().ConfigureAwait(false);
}
if (this.Client is object)
{
await this.Client.DisposeAsync().ConfigureAwait(false);
}
if (this.PortAllocator is object)
{
this.PortAllocator.Dispose();
}
});
_disposed = true;
}
public void Dispose()
{
if (_disposed)
{
return;
}
foreach (var handle in this.SecondarySilos)
{
handle.Dispose();
}
this.Primary?.Dispose();
this.Client?.Dispose();
if (this.PortAllocator is object)
{
this.PortAllocator.Dispose();
}
_disposed = true;
}
}
}