-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
1598 lines (1473 loc) · 58.2 KB
/
Copy pathProgram.cs
File metadata and controls
1598 lines (1473 loc) · 58.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
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
using System.Data;
using System.Text.Json;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using System.Net.Http;
using System.Net.Http.Headers;
using System.IO;
using System.Buffers;
using System.Threading.Channels;
using System.Linq;
using System.Net;
using System.Text;
using System.Diagnostics;
using System.Diagnostics.Metrics;
using Grpc.Core;
using Stress;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Server.Kestrel.Core;
using OpenTelemetry.Instrumentation.Runtime;
using OpenTelemetry.Metrics;
using OpenTelemetry.Resources;
using OpenTelemetry.Trace;
var cfg = AppConfig.Load();
var logLevel = Util.GetLogLevel("LOG_LEVEL", LogLevel.Information);
var builder = WebApplication.CreateBuilder(args);
builder.Logging.SetMinimumLevel(logLevel);
builder.WebHost.ConfigureKestrel(options =>
{
// Allow large payloads up to 60 MB (covers 50 MB payload + overhead)
options.Limits.MaxRequestBodySize = 60 * 1024 * 1024;
// HTTP/UI/probes on ListenPort (HTTP/1.1)
options.Listen(IPAddress.Any, cfg.ListenPort, listenOptions =>
{
listenOptions.Protocols = HttpProtocols.Http1;
});
// gRPC on GrpcPort (HTTP/2)
options.Listen(IPAddress.Any, cfg.GrpcPort, listenOptions =>
{
listenOptions.Protocols = HttpProtocols.Http2;
});
});
// Custom metrics / throttling
builder.Services.AddSingleton<MetricsRecorder>();
builder.Services.AddSingleton<SqlThrottle>();
builder.Services.AddCors(options =>
{
options.AddPolicy("any", policy =>
{
policy.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod();
});
});
builder.Services.AddGrpc(o =>
{
// Lift gRPC message limits for large payloads
o.MaxReceiveMessageSize = 60 * 1024 * 1024;
o.MaxSendMessageSize = 60 * 1024 * 1024;
});
builder.Services.AddSingleton(cfg);
builder.Services.AddSingleton<TrafficTracker>();
builder.Services.AddSingleton<RingRegistry>();
builder.Services.AddHttpClient();
builder.Services.AddHostedService<HeartbeatService>();
builder.Services.AddSingleton<WriteQueue>();
builder.Services.AddHostedService<SqlWriterService>();
// Configure OpenTelemetry if an OTLP endpoint is provided
var telemetry = builder.Services.AddOpenTelemetry();
telemetry.ConfigureResource(resource => resource.AddService(serviceName: "sql-stress", serviceVersion: "1.0.0"));
if (!string.IsNullOrWhiteSpace(cfg.OtlpEndpoint))
{
telemetry
.WithTracing(tracer =>
{
tracer.AddAspNetCoreInstrumentation();
tracer.AddHttpClientInstrumentation();
tracer.AddSqlClientInstrumentation(options =>
{
options.SetDbStatementForText = true;
options.RecordException = true;
});
tracer.AddOtlpExporter(options =>
{
options.Endpoint = new Uri(cfg.OtlpEndpoint);
if (!string.IsNullOrWhiteSpace(cfg.OtlpHeaders))
{
options.Headers = cfg.OtlpHeaders;
}
if (cfg.OtlpInsecure)
{
options.HttpClientFactory = () => new HttpClient(new HttpClientHandler
{
ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
});
}
});
})
.WithMetrics(metrics =>
{
metrics.AddRuntimeInstrumentation();
metrics.AddAspNetCoreInstrumentation();
metrics.AddMeter("sql-stress.custom");
metrics.AddOtlpExporter(options =>
{
options.Endpoint = new Uri(cfg.OtlpEndpoint);
if (!string.IsNullOrWhiteSpace(cfg.OtlpHeaders))
{
options.Headers = cfg.OtlpHeaders;
}
if (cfg.OtlpInsecure)
{
options.HttpClientFactory = () => new HttpClient(new HttpClientHandler
{
ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
});
}
});
});
}
var app = builder.Build();
app.UseCors("any");
try
{
await EnsureTableAsync(cfg, app.Logger);
}
catch (Exception ex)
{
app.Logger.LogError(ex, "SQL startup check failed. App will continue without SQL connectivity.");
}
var traffic = app.Services.GetRequiredService<TrafficTracker>();
app.MapGet("/healthz", async (CancellationToken ct) =>
{
await using var conn = new SqlConnection(cfg.ConnectionString);
await conn.OpenAsync(ct);
await using var cmd = conn.CreateCommand();
cmd.CommandText = "SELECT 1";
cmd.CommandTimeout = cfg.SqlTimeoutSeconds;
await cmd.ExecuteScalarAsync(ct);
return Results.Ok("ok");
});
app.MapGet("/status", () =>
{
var snap = traffic.LocalSnapshot(cfg);
return Results.Json(new
{
status = "ok",
pod = snap.PodName,
started = snap.Started,
totalRequests = snap.TotalRequests,
inFlight = snap.InFlight,
utc = DateTime.UtcNow
});
});
app.MapMethods("/write", new[] { "GET", "POST" }, async (HttpContext context) =>
{
var metrics = context.RequestServices.GetRequiredService<MetricsRecorder>();
var ip = context.Connection.RemoteIpAddress?.ToString() ?? "unknown";
var requestStart = DateTime.UtcNow;
// Decide payload mode: querystring "mode" overrides env SQL_INSERT_MODE. Supported: "random" (default), "body" (use client payload for POST), "hl7" (synthetic HL7 text).
var mode = context.Request.Query["mode"].ToString();
if (string.IsNullOrWhiteSpace(mode)) mode = cfg.SqlInsertMode;
var useBody = string.Equals(mode, "body", StringComparison.OrdinalIgnoreCase);
// Fast path when SQL is disabled
if (cfg.DisableSql)
{
traffic.IncrementInFlight();
try
{
await Task.Delay(1, context.RequestAborted);
var respBody = JsonSerializer.Serialize(new
{
bytes_written = 0,
duration_ms = 1,
table = cfg.TableName,
timestamp = DateTime.UtcNow,
sql_disabled = true
});
context.Response.ContentType = "application/json";
await context.Response.WriteAsync(respBody);
metrics.RecordHttp("/write", 200, 0, respBody.Length, 1);
metrics.RecordSql("http", mode, true, 0, 1);
traffic.Record(ip, 0, 1, true, protocol: "http");
}
finally
{
traffic.DecrementInFlight();
}
return;
}
traffic.IncrementInFlight();
byte[] payload;
int size;
if (useBody && string.Equals(context.Request.Method, "POST", StringComparison.OrdinalIgnoreCase))
{
var max = cfg.MaxBytes;
byte[] buffer;
int length;
try
{
(buffer, length) = await Util.ReadBodyPooledAsync(context.Request, max, context.RequestAborted);
}
catch (PayloadTooLargeException)
{
context.Response.StatusCode = StatusCodes.Status413PayloadTooLarge;
await context.Response.WriteAsJsonAsync(new { error = "payload too large", max_bytes = max });
traffic.DecrementInFlight();
return;
}
payload = buffer;
size = length;
}
else
{
var desired = cfg.RandomSize();
(payload, size, mode) = PayloadFactory.CreatePayload(mode, desired);
}
var queue = context.RequestServices.GetRequiredService<WriteQueue>();
var accepted = queue.TryEnqueue(new WriteJob
{
Payload = payload,
Length = size,
Mode = mode,
Protocol = "http",
Ip = ip,
RequestStartUtc = requestStart
});
if (!accepted)
{
ArrayPool<byte>.Shared.Return(payload);
traffic.DecrementInFlight();
context.Response.StatusCode = StatusCodes.Status429TooManyRequests;
await context.Response.WriteAsJsonAsync(new { error = "queue full, retry later" });
metrics.RecordHttp("/write", 429, size, 0, (DateTime.UtcNow - requestStart).TotalMilliseconds);
return;
}
context.Response.StatusCode = StatusCodes.Status202Accepted;
await context.Response.WriteAsJsonAsync(new
{
status = "queued",
bytes = size,
table = cfg.TableName,
mode,
sql_disabled = false
});
metrics.RecordHttp("/write", 202, size, 0, (DateTime.UtcNow - requestStart).TotalMilliseconds);
});
app.MapGet("/dashboard", (HttpContext context) =>
{
context.Response.Headers.CacheControl = "no-store, max-age=0";
context.Response.ContentType = "text/html";
return context.Response.WriteAsync(DashboardRenderer.Render(cfg.Role));
});
// SQL read dashboard (manual load buttons)
app.MapGet("/sqlread", (HttpContext context) =>
{
context.Response.Headers.CacheControl = "no-store, max-age=0";
context.Response.ContentType = "text/html";
return context.Response.WriteAsync(SqlReadRenderer.Render());
});
app.MapGet("/stats", async (HttpContext context) =>
{
var scope = context.Request.Query["scope"].ToString();
var local = traffic.LocalSnapshot(cfg);
var registry = app.Services.GetRequiredService<RingRegistry>();
if (string.Equals(scope, "local", StringComparison.OrdinalIgnoreCase))
{
return Results.Json(local);
}
// Prefer registry snapshots (aggregator) if available
registry.Upsert(local);
var registryPods = registry.GetActiveSnapshots();
List<PodSnapshot> pods;
if (registryPods.Any())
{
pods = registryPods;
}
else
{
var peers = await traffic.FetchPeerSnapshotsAsync(cfg, context.RequestAborted);
pods = new List<PodSnapshot> { local };
pods.AddRange(peers);
}
pods = pods.Where(p => p != null && !string.IsNullOrWhiteSpace(p.PodName)).ToList();
var aggregated = traffic.AggregateSeries(pods);
var response = new StatsResponse(
Pods: pods,
AggregatedSeries: aggregated,
TotalRequests: pods.Sum(p => p.TotalRequests),
InFlight: pods.Sum(p => p.InFlight),
// Only surface "SQL disabled" when every active pod has it disabled.
SqlDisabled: pods.Any() && pods.All(p => p.SqlDisabled)
);
return Results.Json(response);
});
// Latest messages (SQL read)
app.MapGet("/messages", async (HttpContext context) =>
{
int limit = 50;
if (int.TryParse(context.Request.Query["limit"], out var parsed))
{
limit = Math.Clamp(parsed, 1, 200);
}
var mode = context.Request.Query["mode"].ToString().ToLowerInvariant();
var full = string.Equals(mode, "full", StringComparison.OrdinalIgnoreCase);
const int maxFullBytes = 5 * 1024 * 1024; // cap full fetch to 5 MB per message to avoid OOM
var sw = Stopwatch.StartNew();
var items = new List<object>();
await using var conn = new SqlConnection(cfg.ConnectionString);
await conn.OpenAsync(context.RequestAborted);
await using var cmd = conn.CreateCommand();
cmd.CommandTimeout = cfg.SqlTimeoutSeconds;
cmd.CommandText = $"""
SELECT TOP (@lim) id, created_at, payload_size, payload
FROM [dbo].[{cfg.TableName}]
ORDER BY created_at DESC
""";
cmd.Parameters.Add(new SqlParameter("@lim", SqlDbType.Int) { Value = limit });
await using var reader = await cmd.ExecuteReaderAsync(CommandBehavior.SequentialAccess, context.RequestAborted);
while (await reader.ReadAsync(context.RequestAborted))
{
var id = reader.GetGuid(0);
var created = reader.GetDateTime(1);
var size = reader.GetInt32(2);
var msgSw = Stopwatch.StartNew();
string? payloadUtf8 = null;
bool truncated = false;
long readBytes = 0;
if (full)
{
const int chunk = 8192;
using var ms = new MemoryStream();
long offset = 0;
var buffer = new byte[chunk];
while (true)
{
var toRead = (int)Math.Min(chunk, maxFullBytes - ms.Length);
if (toRead <= 0) break;
var read = reader.GetBytes(3, offset, buffer, 0, toRead);
if (read == 0) break;
ms.Write(buffer, 0, (int)read);
readBytes += read;
offset += read;
if (ms.Length >= maxFullBytes) { truncated = true; break; }
}
var bytes = ms.ToArray();
payloadUtf8 = Util.SanitizeUtf8(bytes);
if (size > maxFullBytes) truncated = true;
}
msgSw.Stop();
var msgDurationMs = (long)Math.Max(1, Math.Ceiling(msgSw.Elapsed.TotalMilliseconds));
items.Add(new
{
id,
created_at = created,
payload_size = size,
duration_ms = msgDurationMs,
payload_utf8 = payloadUtf8,
payload_base64 = (string?)null, // omit base64 to keep response light
read_bytes = readBytes,
truncated
});
}
sw.Stop();
return Results.Json(new { items, note = $"Showing {items.Count} of latest messages", duration_ms = sw.ElapsedMilliseconds });
});
app.MapGrpcService<StressGrpcService>();
// Registry endpoints (aggregator consumption)
app.MapPost("/register", async (RingRegistry registry, HttpContext ctx) =>
{
try
{
var snapshot = await JsonSerializer.DeserializeAsync<PodSnapshot>(ctx.Request.Body, cancellationToken: ctx.RequestAborted);
if (snapshot != null && !string.IsNullOrWhiteSpace(snapshot.PodName))
{
registry.Upsert(snapshot);
}
return Results.Ok();
}
catch
{
return Results.BadRequest();
}
});
app.Run();
static async Task EnsureTableAsync(AppConfig cfg, ILogger logger)
{
await using var conn = new SqlConnection(cfg.ConnectionString);
await conn.OpenAsync();
await using var cmd = conn.CreateCommand();
cmd.CommandTimeout = cfg.SqlTimeoutSeconds;
cmd.CommandText = $"""
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[{cfg.TableName}]') AND type = N'U')
BEGIN
CREATE TABLE [dbo].[{cfg.TableName}] (
id UNIQUEIDENTIFIER NOT NULL DEFAULT NEWID() PRIMARY KEY,
created_at DATETIME2 NOT NULL DEFAULT SYSUTCDATETIME(),
payload_size INT NOT NULL,
payload VARBINARY(MAX) NULL
);
END;
""";
await cmd.ExecuteNonQueryAsync();
logger.LogInformation("Ensured table exists: {Table}", cfg.TableName);
}
public sealed class AppConfig
{
public required string ConnectionString { get; init; }
public required string TableName { get; init; }
public required int MinBytes { get; init; }
public required int MaxBytes { get; init; }
public required int SqlTimeoutSeconds { get; init; }
public required int ListenPort { get; init; }
public required int GrpcPort { get; init; }
public string Role { get; init; } = "ingester"; // ingester | aggregator | messages
public int MaxInflightSql { get; init; }
public int MaxQueueLength { get; init; }
public string SqlInsertMode { get; init; } = "random";
public string? RingEndpoint { get; init; }
public string? OtlpEndpoint { get; init; }
public string? OtlpHeaders { get; init; }
public bool OtlpInsecure { get; init; }
public bool DisableSql { get; init; }
public required string PodName { get; init; }
public List<string> PeerDashboardUrls { get; init; } = new();
public string? PeerServiceName { get; init; }
public string? PodNamespace { get; init; }
public int PeerServicePort { get; init; }
public static AppConfig Load()
{
var server = Require("SQL_SERVER");
var port = GetInt("SQL_PORT", 1433);
var database = Require("SQL_DATABASE");
var user = Require("SQL_USER");
var password = Require("SQL_PASSWORD");
var encrypt = GetBool("SQL_ENCRYPT", true);
var trustServerCert = GetBool("SQL_TRUST_SERVER_CERT", false);
var builder = new SqlConnectionStringBuilder
{
DataSource = $"{server},{port}",
InitialCatalog = database,
UserID = user,
Password = password,
Encrypt = encrypt,
TrustServerCertificate = trustServerCert,
ConnectTimeout = GetInt("SQL_CONNECT_TIMEOUT_SECONDS", 30),
MaxPoolSize = GetInt("SQL_MAX_POOL_SIZE", 200),
MinPoolSize = GetInt("SQL_MIN_POOL_SIZE", 10),
};
var minBytes = GetInt("PAYLOAD_MIN_BYTES", 1024);
var maxBytes = GetInt("PAYLOAD_MAX_BYTES", 50 * 1024 * 1024);
if (minBytes <= 0) throw new InvalidOperationException("PAYLOAD_MIN_BYTES must be > 0");
if (maxBytes < minBytes) throw new InvalidOperationException("PAYLOAD_MAX_BYTES must be >= PAYLOAD_MIN_BYTES");
return new AppConfig
{
ConnectionString = builder.ConnectionString,
TableName = Get("SQL_TABLE", "stress_writes")!,
MinBytes = minBytes,
MaxBytes = maxBytes,
SqlTimeoutSeconds = GetInt("SQL_TIMEOUT_SECONDS", 60),
ListenPort = GetInt("APP_PORT", 8080),
GrpcPort = GetInt("APP_GRPC_PORT", 8081),
MaxInflightSql = GetInt("MAX_INFLIGHT_SQL", 0),
MaxQueueLength = GetInt("MAX_QUEUE_LENGTH", 128),
SqlInsertMode = Get("SQL_INSERT_MODE", "random")!.ToLowerInvariant(),
Role = Get("APP_ROLE", "ingester")!.ToLowerInvariant(),
RingEndpoint = Get("RING_ENDPOINT", null),
OtlpEndpoint = Get("OTLP_ENDPOINT", null),
OtlpHeaders = Get("OTLP_HEADERS", null),
OtlpInsecure = GetBool("OTLP_INSECURE", false),
DisableSql = GetBool("DISABLE_SQL", false),
PodName = Get("POD_NAME", Environment.GetEnvironmentVariable("HOSTNAME") ?? "unknown")!,
PeerDashboardUrls = ParseList("PEER_DASHBOARD_URLS"),
PeerServiceName = Get("PEER_SERVICE_NAME", null),
PodNamespace = Get("POD_NAMESPACE", Environment.GetEnvironmentVariable("POD_NAMESPACE")),
PeerServicePort = GetInt("PEER_SERVICE_PORT", 8080)
};
}
public int RandomSize()
{
return MinBytes == MaxBytes ? MinBytes : Random.Shared.Next(MinBytes, MaxBytes + 1);
}
private static string Require(string key)
{
var value = Environment.GetEnvironmentVariable(key);
if (string.IsNullOrWhiteSpace(value))
throw new InvalidOperationException($"Missing required env var {key}");
return value;
}
private static string? Get(string key, string? defaultValue)
{
var env = Environment.GetEnvironmentVariable(key);
if (string.IsNullOrWhiteSpace(env))
{
return defaultValue;
}
return env;
}
private static int GetInt(string key, int defaultValue)
{
var raw = Environment.GetEnvironmentVariable(key);
if (string.IsNullOrWhiteSpace(raw)) return defaultValue;
return int.TryParse(raw, out var value) ? value : defaultValue;
}
private static bool GetBool(string key, bool defaultValue)
{
var raw = Environment.GetEnvironmentVariable(key);
if (string.IsNullOrWhiteSpace(raw)) return defaultValue;
return raw.ToLowerInvariant() switch
{
"1" or "true" or "yes" or "on" => true,
"0" or "false" or "no" or "off" => false,
_ => defaultValue
};
}
private static List<string> ParseList(string key)
{
var raw = Environment.GetEnvironmentVariable(key);
if (string.IsNullOrWhiteSpace(raw)) return new();
return raw.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).ToList();
}
}
public sealed class MetricsRecorder
{
private readonly Counter<long> _httpReqs;
private readonly Counter<long> _httpReqBytes;
private readonly Counter<long> _httpRespBytes;
private readonly Histogram<double> _httpDuration;
private readonly Counter<long> _grpcReqs;
private readonly Counter<long> _grpcReqBytes;
private readonly Counter<long> _grpcRespBytes;
private readonly Histogram<double> _grpcDuration;
private readonly Counter<long> _sqlSuccess;
private readonly Counter<long> _sqlFailure;
private readonly Counter<long> _sqlBytes;
private readonly Histogram<double> _sqlDuration;
public MetricsRecorder()
{
var meter = new Meter("sql-stress.custom", "1.0.0");
_httpReqs = meter.CreateCounter<long>("sqlstress.http.requests");
_httpReqBytes = meter.CreateCounter<long>("sqlstress.http.request_bytes");
_httpRespBytes = meter.CreateCounter<long>("sqlstress.http.response_bytes");
_httpDuration = meter.CreateHistogram<double>("sqlstress.http.duration_ms");
_grpcReqs = meter.CreateCounter<long>("sqlstress.grpc.requests");
_grpcReqBytes = meter.CreateCounter<long>("sqlstress.grpc.request_bytes");
_grpcRespBytes = meter.CreateCounter<long>("sqlstress.grpc.response_bytes");
_grpcDuration = meter.CreateHistogram<double>("sqlstress.grpc.duration_ms");
_sqlSuccess = meter.CreateCounter<long>("sqlstress.sql.success");
_sqlFailure = meter.CreateCounter<long>("sqlstress.sql.failure");
_sqlBytes = meter.CreateCounter<long>("sqlstress.sql.bytes");
_sqlDuration = meter.CreateHistogram<double>("sqlstress.sql.duration_ms");
}
public void RecordHttp(string route, int status, long reqBytes, long respBytes, double durationMs)
{
var tags = new TagList
{
{ "route", route },
{ "status", status },
{ "protocol", "http" }
};
_httpReqs.Add(1, tags);
_httpReqBytes.Add(reqBytes, tags);
_httpRespBytes.Add(respBytes, tags);
_httpDuration.Record(durationMs, tags);
}
public void RecordGrpc(string method, string status, long reqBytes, long respBytes, double durationMs)
{
var tags = new TagList
{
{ "method", method },
{ "status", status },
{ "protocol", "grpc" }
};
_grpcReqs.Add(1, tags);
_grpcReqBytes.Add(reqBytes, tags);
_grpcRespBytes.Add(respBytes, tags);
_grpcDuration.Record(durationMs, tags);
}
public void RecordSql(string protocol, string mode, bool success, long bytes, double durationMs)
{
var tags = new TagList
{
{ "protocol", protocol },
{ "mode", mode }
};
if (success)
{
_sqlSuccess.Add(1, tags);
}
else
{
_sqlFailure.Add(1, tags);
}
_sqlBytes.Add(bytes, tags);
_sqlDuration.Record(durationMs, tags);
}
}
public sealed class RingRegistry
{
private readonly ConcurrentDictionary<string, (PodSnapshot Snapshot, DateTime LastSeen)> _entries = new();
private readonly TimeSpan _ttl = TimeSpan.FromSeconds(15);
public void Upsert(PodSnapshot snapshot)
{
_entries[snapshot.PodName] = (snapshot, DateTime.UtcNow);
}
public List<PodSnapshot> GetActiveSnapshots()
{
var cutoff = DateTime.UtcNow - _ttl;
var stale = _entries.Where(kv => kv.Value.LastSeen < cutoff).Select(kv => kv.Key).ToList();
foreach (var key in stale)
{
_entries.TryRemove(key, out _);
}
return _entries.Values.Select(v => v.Snapshot).ToList();
}
}
public sealed class HeartbeatService : BackgroundService
{
private readonly AppConfig _cfg;
private readonly TrafficTracker _traffic;
private readonly IHttpClientFactory _httpFactory;
private readonly ILogger<HeartbeatService> _logger;
public HeartbeatService(AppConfig cfg, TrafficTracker traffic, IHttpClientFactory httpFactory, ILogger<HeartbeatService> logger)
{
_cfg = cfg;
_traffic = traffic;
_httpFactory = httpFactory;
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
if (string.IsNullOrWhiteSpace(_cfg.RingEndpoint))
{
_logger.LogInformation("RingEndpoint not set; heartbeat disabled");
return;
}
var client = _httpFactory.CreateClient();
while (!stoppingToken.IsCancellationRequested)
{
try
{
var snap = _traffic.LocalSnapshot(_cfg);
var json = JsonSerializer.Serialize(snap);
using var content = new StringContent(json, Encoding.UTF8, "application/json");
using var resp = await client.PostAsync(_cfg.RingEndpoint, content, stoppingToken);
if (!resp.IsSuccessStatusCode)
{
_logger.LogWarning("Heartbeat failed to {Endpoint} with status {Status}", _cfg.RingEndpoint, resp.StatusCode);
}
}
catch (Exception ex) when (!stoppingToken.IsCancellationRequested)
{
_logger.LogWarning(ex, "Heartbeat error to {Endpoint}", _cfg.RingEndpoint);
}
try
{
await Task.Delay(TimeSpan.FromSeconds(2), stoppingToken);
}
catch (TaskCanceledException) { }
}
}
}
public class StressGrpcService : StressTest.StressTestBase
{
private readonly AppConfig _cfg;
private readonly TrafficTracker _traffic;
private readonly MetricsRecorder _metrics;
public StressGrpcService(AppConfig cfg, TrafficTracker traffic, MetricsRecorder metrics)
{
_cfg = cfg;
_traffic = traffic;
_metrics = metrics;
}
public override async Task<WriteResponse> Write(WriteRequest request, ServerCallContext context)
{
var size = request.SizeBytes > 0 ? request.SizeBytes : _cfg.RandomSize();
(var payload, size, var mode) = PayloadFactory.CreatePayload(_cfg.SqlInsertMode, size);
_traffic.IncrementInFlight();
var requestStart = DateTime.UtcNow;
var sw = System.Diagnostics.Stopwatch.StartNew();
if (!_cfg.DisableSql)
{
var gate = context.GetHttpContext()?.RequestServices.GetRequiredService<SqlThrottle>()
?? throw new InvalidOperationException("SqlThrottle not available");
await using var lease = await gate.WaitAsync(context.CancellationToken);
await using var conn = new SqlConnection(_cfg.ConnectionString);
await conn.OpenAsync(context.CancellationToken);
await using var cmd = conn.CreateCommand();
cmd.CommandTimeout = _cfg.SqlTimeoutSeconds;
cmd.CommandText = $"INSERT INTO [dbo].[{_cfg.TableName}] (payload_size, payload) VALUES (@p1, @p2)";
cmd.Parameters.Add(new SqlParameter("@p1", System.Data.SqlDbType.Int) { Value = size });
cmd.Parameters.Add(new SqlParameter("@p2", System.Data.SqlDbType.VarBinary, -1) { Value = payload });
await cmd.ExecuteNonQueryAsync(context.CancellationToken);
}
else
{
await Task.Delay(1, context.CancellationToken);
}
sw.Stop();
var totalDurationMs = (DateTime.UtcNow - requestStart).TotalMilliseconds;
_traffic.Record(context.Peer, size, totalDurationMs, success: true, protocol: "grpc");
_metrics.RecordGrpc("Write", "OK", size, sizeof(long) + _cfg.TableName.Length, totalDurationMs);
_metrics.RecordSql("grpc", mode, true, size, totalDurationMs);
_traffic.DecrementInFlight();
return new WriteResponse
{
BytesWritten = size,
DurationMs = (long)sw.ElapsedMilliseconds,
Table = _cfg.TableName,
Timestamp = DateTime.UtcNow.ToString("O")
};
}
public override async Task<HealthResponse> Healthz(HealthRequest request, ServerCallContext context)
{
await using var conn = new SqlConnection(_cfg.ConnectionString);
await conn.OpenAsync(context.CancellationToken);
await using var cmd = conn.CreateCommand();
cmd.CommandText = "SELECT 1";
cmd.CommandTimeout = _cfg.SqlTimeoutSeconds;
await cmd.ExecuteScalarAsync(context.CancellationToken);
return new HealthResponse { Status = "ok" };
}
}
public sealed class TrafficTracker
{
private readonly ConcurrentDictionary<string, IpStats> _byIp = new();
private long _totalRequests;
private long _inFlight;
private long _httpRequests;
private long _grpcRequests;
private readonly DateTime _started = DateTime.UtcNow;
private readonly object _seriesLock = new();
private readonly Dictionary<DateTime, TimeBucket> _series = new();
private readonly HttpClient _httpClient = new();
private long _totalBytes;
public void Record(string ip, int bytes, double durationMs, bool success, string protocol)
{
Interlocked.Increment(ref _totalRequests);
Interlocked.Add(ref _totalBytes, bytes);
if (string.Equals(protocol, "grpc", StringComparison.OrdinalIgnoreCase))
{
Interlocked.Increment(ref _grpcRequests);
}
else
{
Interlocked.Increment(ref _httpRequests);
}
_byIp.AddOrUpdate(ip,
_ => new IpStats(ip, 1, bytes, durationMs, durationMs, DateTime.UtcNow),
(_, existing) => existing with
{
Requests = existing.Requests + 1,
TotalBytes = existing.TotalBytes + bytes,
TotalDurationMs = existing.TotalDurationMs + durationMs,
LastDurationMs = durationMs,
LastSeen = DateTime.UtcNow
});
var second = DateTime.UtcNow;
second = new DateTime(second.Year, second.Month, second.Day, second.Hour, second.Minute, second.Second, DateTimeKind.Utc);
lock (_seriesLock)
{
if (!_series.TryGetValue(second, out var bucket))
{
bucket = new TimeBucket(second, 0, 0);
_series[second] = bucket;
}
bucket.Requests += 1;
bucket.Bytes += bytes;
if (success) bucket.Success += 1; else bucket.Failures += 1;
// trim to last 30s
var cutoff = DateTime.UtcNow.AddSeconds(-30);
foreach (var key in _series.Keys.Where(k => k < cutoff).ToList())
{
_series.Remove(key);
}
}
}
public void IncrementInFlight() => Interlocked.Increment(ref _inFlight);
public void DecrementInFlight() => Interlocked.Decrement(ref _inFlight);
public PodSnapshot LocalSnapshot(AppConfig cfg)
{
List<TimeBucket> series;
lock (_seriesLock)
{
series = _series.Values.OrderBy(v => v.Timestamp).ToList();
}
return new PodSnapshot(
PodName: cfg.PodName,
Started: _started,
TotalRequests: Interlocked.Read(ref _totalRequests),
InFlight: Interlocked.Read(ref _inFlight),
TotalBytes: Interlocked.Read(ref _totalBytes),
PodIp: GetPodIp(),
CpuPct: GetCpuPercent(),
MemBytes: GC.GetTotalMemory(false),
HttpRequests: Interlocked.Read(ref _httpRequests),
GrpcRequests: Interlocked.Read(ref _grpcRequests),
SqlDisabled: cfg.DisableSql,
PerIp: _byIp.Values.OrderByDescending(v => v.Requests).ToList(),
Series: series
);
}
private IEnumerable<string> DiscoverPeers(AppConfig cfg)
{
if (string.IsNullOrWhiteSpace(cfg.PeerServiceName) || string.IsNullOrWhiteSpace(cfg.PodNamespace))
{
return Enumerable.Empty<string>();
}
try
{
var tokenPath = "/var/run/secrets/kubernetes.io/serviceaccount/token";
if (!File.Exists(tokenPath))
{
return Enumerable.Empty<string>();
}
var token = File.ReadAllText(tokenPath);
var handler = new HttpClientHandler
{
ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
};
using var client = new HttpClient(handler);
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
var url = $"https://kubernetes.default.svc/api/v1/namespaces/{cfg.PodNamespace}/endpoints/{cfg.PeerServiceName}";
var resp = client.GetAsync(url).GetAwaiter().GetResult();
if (!resp.IsSuccessStatusCode)
{
return Enumerable.Empty<string>();
}
var json = resp.Content.ReadAsStringAsync().GetAwaiter().GetResult();
using var doc = JsonDocument.Parse(json);
if (!doc.RootElement.TryGetProperty("subsets", out var subsets))
{
return Enumerable.Empty<string>();
}
var addresses = new List<string>();
foreach (var subset in subsets.EnumerateArray())
{
if (!subset.TryGetProperty("addresses", out var addrs)) continue;
foreach (var addr in addrs.EnumerateArray())
{
var ip = addr.GetProperty("ip").GetString();
if (!string.IsNullOrWhiteSpace(ip))
{
addresses.Add($"http://{ip}:{cfg.PeerServicePort}");
}
}
}
return addresses;
}
catch
{
return Enumerable.Empty<string>();
}
}
public async Task<List<PodSnapshot>> FetchPeerSnapshotsAsync(AppConfig cfg, CancellationToken ct)
{
var endpoints = DiscoverPeers(cfg).Concat(cfg.PeerDashboardUrls ?? new List<string>()).Distinct().ToList();
var results = new List<PodSnapshot>();
foreach (var ep in endpoints)
{
try
{
using var req = new HttpRequestMessage(HttpMethod.Get, $"{ep}/stats?scope=local");
var resp = await _httpClient.SendAsync(req, ct);
if (!resp.IsSuccessStatusCode) continue;
var json = await resp.Content.ReadAsStringAsync(ct);
var pod = JsonSerializer.Deserialize<PodSnapshot>(json);
if (pod != null)
{
results.Add(pod);
}
}
catch
{
// ignore peer errors
}
}
return results;
}
public List<TimeBucket> AggregateSeries(IEnumerable<PodSnapshot> pods)
{
if (pods == null)
{
return new List<TimeBucket>();
}
var map = new Dictionary<DateTime, TimeBucket>();
foreach (var pod in pods)
{
if (pod?.Series == null) continue;
foreach (var bucket in pod.Series)
{
if (!map.TryGetValue(bucket.Timestamp, out var agg))
{
agg = new TimeBucket(bucket.Timestamp, 0, 0);
map[bucket.Timestamp] = agg;
}
agg.Requests += bucket.Requests;
agg.Bytes += bucket.Bytes;
agg.Success += bucket.Success;
agg.Failures += bucket.Failures;
}
}
return map.Values.OrderBy(v => v.Timestamp).ToList();
}
private static string? GetPodIp()
{
try
{
var host = Dns.GetHostName();
var entry = Dns.GetHostEntry(host);
var ip = entry.AddressList.FirstOrDefault(a => a.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork && !IPAddress.IsLoopback(a));
return ip?.ToString();
}
catch
{
return null;
}
}
private double GetCpuPercent()
{
try
{
var proc = Process.GetCurrentProcess();
var uptime = DateTime.UtcNow - proc.StartTime.ToUniversalTime();
if (uptime.TotalSeconds <= 0) return 0;