-
-
Notifications
You must be signed in to change notification settings - Fork 295
Expand file tree
/
Copy pathProgram.cs
More file actions
453 lines (376 loc) · 13.1 KB
/
Program.cs
File metadata and controls
453 lines (376 loc) · 13.1 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
// -----------------------------------------------------------------------
// <copyright file="Program.cs" company="Asynkron AB">
// Copyright (C) 2015-2024 Asynkron AB All rights reserved
// </copyright>
// -----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using ClusterExperiment1.Messages;
using Microsoft.Extensions.Logging;
using Proto;
using Proto.Cluster;
using Proto.Utils;
namespace ClusterExperiment1;
public static class Program
{
private static TaskCompletionSource<bool> ts = null!;
private static int actorCount;
private static int memberCount;
private static int killTimeoutSeconds;
private static int requestCount;
private static int failureCount;
private static int successCount;
private static object Request = null!;
public static async Task Main(string[] args)
{
// ThreadPool.SetMinThreads(500, 500);
Request = new HelloRequest();
Configuration.SetupLogger(LogLevel.Error);
if (args.Length > 0)
{
// InteractiveOutput = args[0] == "1";
var l = typeof(Program).Assembly.Location;
Console.WriteLine($"Worker running {l}");
var worker = await Configuration.SpawnMember();
AppDomain.CurrentDomain.ProcessExit += (sender, args) =>
{
worker.ShutdownAsync().Wait();
};
await Task.Delay(Timeout.InfiniteTimeSpan);
return;
}
ts = new TaskCompletionSource<bool>();
// _ = DockerSupport.Run(ts.Task);
Console.WriteLine("Proto.Cluster chaos benchmark");
Console.WriteLine();
Console.WriteLine("Explanation:");
Console.WriteLine(". = 10 000 successful requests");
// Console.WriteLine("# = activation of a virtual actor");
// Console.WriteLine("+ = (deliberate) deactivation of virtual actor");
Console.WriteLine("X = NULL response, e.g. requests retried but got no response");
Console.WriteLine();
// Console.WriteLine("1) Run with interactive output");
// Console.WriteLine("2) Run silent");
//
// var res0 = Console.ReadLine();
// InteractiveOutput = res0 == "1";
Console.WriteLine("1) Run single process - graceful exit");
Console.WriteLine("2) Run single process");
Console.WriteLine("3) Run multi process - graceful exit");
Console.WriteLine("4) Run multi process");
Console.WriteLine(
"5) Run single process, single node, Batch(300), ProtoBuf, 10 actors, 60S"
);
var memberRunStrategy = Console.ReadLine();
var batchSize = 0;
string clientStrategy = "2";
if (memberRunStrategy == "5")
{
memberRunStrategy = "3";
actorCount = 10;
killTimeoutSeconds = 60;
memberCount = 1;
batchSize = 300;
}
else
{
Console.WriteLine("1) Protobuf serializer (default)");
Console.WriteLine("2) Json serializer");
if (Console.ReadLine() == "2")
{
Request = new HelloRequestPoco();
}
Console.WriteLine("1) Run single request client");
Console.WriteLine("2) Run batch requests client");
Console.WriteLine("3) Run fire and forget client");
Console.WriteLine("4) Run single request debug client");
Console.WriteLine("5) NoOp - Stability");
clientStrategy = Console.ReadLine() ?? "";
if (clientStrategy == "2")
{
Console.WriteLine("Batch size? default is 50");
if (!int.TryParse(Console.ReadLine(), out batchSize))
batchSize = 50;
Console.WriteLine($"Using batch size {batchSize}");
}
Console.WriteLine("Number of virtual actors? default 10000");
if (!int.TryParse(Console.ReadLine(), out actorCount))
actorCount = 10_000;
Console.WriteLine($"Using {actorCount} actors");
Console.WriteLine("Number of cluster members? default is 8");
if (!int.TryParse(Console.ReadLine(), out memberCount))
memberCount = 8;
Console.WriteLine($"Using {memberCount} members");
Console.WriteLine("Seconds to run before stopping members? default is 30");
if (!int.TryParse(Console.ReadLine(), out killTimeoutSeconds))
killTimeoutSeconds = 30;
Console.WriteLine($"Using {killTimeoutSeconds} seconds");
}
Action run = clientStrategy switch
{
"1" => () => RunClient(),
"2" => () => RunBatchClient(batchSize),
"3" => () => RunFireForgetClient(),
"4" => () => RunDebugClient(),
"5" => () => RunNoopClient(),
_ => throw new ArgumentOutOfRangeException()
};
var elapsed = await (
memberRunStrategy switch
{
"1" => RunWorkers(() => new RunMemberInProcGraceful(), run),
"2" => RunWorkers(() => new RunMemberInProc(), run),
"3" => RunWorkers(() => new RunMemberExternalProcGraceful(), run),
"4" => RunWorkers(() => new RunMemberExternalProc(), run),
_ => throw new ArgumentOutOfRangeException()
}
);
var tps = requestCount / elapsed.TotalMilliseconds * 1000;
Console.WriteLine();
Console.WriteLine($"Requests:\t{requestCount:N0}");
Console.WriteLine($"Successful:\t{successCount:N0}");
Console.WriteLine($"Failures:\t{failureCount:N0}");
Console.WriteLine($"Throughput:\t{tps:N0} requests/sec -> {(tps * 2):N0} msg/sec");
}
private static void RunNoopClient() { }
private static void RunFireForgetClient()
{
var logger = Log.CreateLogger(nameof(Program));
_ = SafeTask.Run(async () =>
{
var semaphore = new AsyncSemaphore(50);
var cluster = await Configuration.SpawnClient();
// var rnd = new Random();
var i = 0;
while (true)
{
var id = "myactor" + (i++ % actorCount);
await semaphore.WaitAsync(
() => SendRequest(cluster, id, CancellationTokens.FromSeconds(20))
);
}
});
}
private static async Task SendRequest(
Cluster cluster,
ClusterIdentity id,
CancellationToken cancellationToken,
ISenderContext? context = null
)
{
Interlocked.Increment(ref requestCount);
if (context == null)
{
context = cluster.System.Root;
}
try
{
try
{
await cluster.RequestAsync<object>(id, Request, context, cancellationToken);
var res = Interlocked.Increment(ref successCount);
if (res % 10000 == 0)
{
Console.ForegroundColor = ConsoleColor.DarkGreen;
Console.Write(".");
Console.ResetColor();
}
return;
}
catch (TimeoutException)
{
// ignored
}
OnError();
}
catch
{
OnError();
}
void OnError()
{
Interlocked.Increment(ref failureCount);
Console.ForegroundColor = ConsoleColor.Red;
Console.Write("X");
Console.ResetColor();
}
}
private static async Task<bool> SendRequest(
Cluster cluster,
string id,
CancellationToken cancellationToken,
ISenderContext? context = null
)
{
Interlocked.Increment(ref requestCount);
if (context == null)
{
context = cluster.System.Root;
}
try
{
try
{
await cluster.RequestAsync<object>(
id,
"hello",
Request,
context,
cancellationToken
);
var res = Interlocked.Increment(ref successCount);
if (res % 10000 == 0)
{
Console.ForegroundColor = ConsoleColor.DarkGreen;
Console.Write(".");
Console.ResetColor();
}
return true;
}
catch (TimeoutException)
{
// ignored
}
OnError();
}
catch
{
OnError();
}
return false;
void OnError()
{
Interlocked.Increment(ref failureCount);
Console.ForegroundColor = ConsoleColor.Red;
Console.Write("X");
Console.ResetColor();
}
}
private static void RunBatchClient(int batchSize)
{
var identities = new ClusterIdentity[actorCount];
for (var i = 0; i < actorCount; i++)
{
var id = "myactor" + i;
identities[i] = ClusterIdentity.Create(id, "hello");
}
var logger = Log.CreateLogger(nameof(Program));
_ = SafeTask.Run(async () =>
{
var cluster = await Configuration.SpawnClient();
// var rnd = new Random();
var semaphore = new AsyncSemaphore(5);
var i = 0;
while (true)
{
var b = i;
await semaphore.WaitAsync(() => RunBatch(b, cluster));
i = (i + batchSize) % actorCount;
}
});
async Task RunBatch(int startIndex, Cluster cluster)
{
var requests = new List<Task>();
try
{
var ct = CancellationTokens.FromSeconds(20);
var ctx = cluster.System.Root.CreateBatchContext(batchSize, ct);
for (var i = 0; i < batchSize; i++)
{
var id = identities[(startIndex + i) % identities.Length];
var request = SendRequest(cluster, id, ct, ctx);
requests.Add(request);
}
await Task.WhenAll(requests);
}
catch (Exception x)
{
logger.LogError(x, "Error...");
}
}
}
private static void RunDebugClient()
{
var logger = Log.CreateLogger(nameof(Program));
_ = SafeTask.Run(async () =>
{
var cluster = await Configuration.SpawnClient();
var rnd = new Random();
while (true)
{
var id = "myactor" + rnd.Next(0, actorCount);
var ct = CancellationTokens.FromSeconds(20);
var res = await SendRequest(cluster, id, ct);
if (!res)
{
var pid = await cluster.GetAsync(
ClusterIdentity.Create(id, "hello"),
CancellationTokens.FromSeconds(10)
);
if (pid != null)
{
logger.LogError("Failed call to {Id} - {Address}", id, pid.Address);
}
else
{
logger.LogError("Failed call to {Id} - Null PID", id);
}
}
}
});
}
private static void RunClient()
{
var logger = Log.CreateLogger(nameof(Program));
_ = SafeTask.Run(async () =>
{
var cluster = await Configuration.SpawnClient();
var rnd = new Random();
while (true)
{
var id = "myactor" + rnd.Next(0, actorCount);
var ct = CancellationTokens.FromSeconds(20);
await SendRequest(cluster, id, ct);
}
});
}
private static async Task<TimeSpan> RunWorkers(
Func<IRunMember> memberFactory,
Action startClient
)
{
var followers = new List<IRunMember>();
for (var i = 0; i < memberCount; i++)
{
var p = memberFactory();
await p.Start();
await Task.Delay(500);
Console.WriteLine("Worker started...");
followers.Add(p);
}
await Task.Delay(4000);
startClient();
Console.WriteLine("Client started...");
var sw = Stopwatch.StartNew();
await Task.Delay(killTimeoutSeconds * 1000);
bool first = true;
foreach (var t in followers)
{
if (first)
{
first = false;
}
else
{
await Task.Delay(killTimeoutSeconds * 1000);
}
Console.WriteLine("Stopping node...");
_ = t.Kill();
}
sw.Stop();
return sw.Elapsed;
}
}