Repository navigation
Expand file tree
/
Copy pathProcessResourceSampler.cs
More file actions
702 lines (617 loc) · 24.4 KB
/
Copy pathProcessResourceSampler.cs
File metadata and controls
702 lines (617 loc) · 24.4 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
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
namespace Titanium.Web.Proxy.RpsLoadProbe;
/// <summary>
/// Polls RSS and CPU% for a child PID during a measure window.
/// Columns stay named <c>proxy_*</c> even when the sampled PID is the origin (origin-direct arms).
/// Includes the full descendant process tree (serve-proxy → nginx master → workers).
/// </summary>
internal sealed record ProcessResourceSample(long PeakRssBytes, double AvgCpuPercent);
internal static class ProcessResourceSampler
{
private static readonly TimeSpan PollInterval = TimeSpan.FromMilliseconds(200);
/// <summary>
/// Sample <paramref name="pid"/> (plus direct children) for approximately <paramref name="duration"/>.
/// Returns null if the process cannot be opened or no samples succeed.
/// </summary>
public static async Task<ProcessResourceSample?> SampleDuringAsync(int pid, TimeSpan duration,
CancellationToken cancellationToken)
{
if (pid <= 0)
return null;
try
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
return await SampleWindowsAsync(pid, duration, cancellationToken).ConfigureAwait(false);
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
return await SampleLinuxAsync(pid, duration, cancellationToken).ConfigureAwait(false);
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
return await SampleMacAsync(pid, duration, cancellationToken).ConfigureAwait(false);
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
throw;
}
catch
{
// Sampling is best-effort; CSV columns stay empty.
}
return null;
}
/// <summary>
/// How often to re-walk the Darwin process tree via <c>pgrep</c>. Forking <c>pgrep</c> every
/// poll (200ms) during the measure window inflates p99 on 4-core macos-15-intel and made
/// compare-editions Plus arms look like "missing" SLO rows at c=64.
/// </summary>
private static readonly TimeSpan MacTreeRefreshInterval = TimeSpan.FromSeconds(2);
/// <summary>
/// Darwin: <see cref="Process.WorkingSet64"/> + <see cref="Process.TotalProcessorTime"/> over the
/// descendant tree (serve-proxy → nginx master → workers). Same shape as the Windows sampler.
/// Tree discovery is throttled — see <see cref="MacTreeRefreshInterval"/>.
/// </summary>
private static async Task<ProcessResourceSample?> SampleMacAsync(int rootPid, TimeSpan duration,
CancellationToken cancellationToken)
{
var handles = new Dictionary<int, Process>();
try
{
AttachMacPids(handles, rootPid, forceTreeRefresh: true);
if (handles.Count == 0)
return null;
long peakRss = 0;
var cpuSamples = new List<double>(capacity: 64);
var prevCpuByPid = new Dictionary<int, TimeSpan>();
long? prevWall = null;
var deadline = Stopwatch.GetTimestamp() + (long)(duration.TotalSeconds * Stopwatch.Frequency);
var processors = Math.Max(1, Environment.ProcessorCount);
var nextTreeRefresh = Stopwatch.GetTimestamp() +
(long)(MacTreeRefreshInterval.TotalSeconds * Stopwatch.Frequency);
while (Stopwatch.GetTimestamp() < deadline)
{
cancellationToken.ThrowIfCancellationRequested();
var refreshTree = Stopwatch.GetTimestamp() >= nextTreeRefresh;
AttachMacPids(handles, rootPid, forceTreeRefresh: refreshTree);
if (refreshTree)
{
nextTreeRefresh = Stopwatch.GetTimestamp() +
(long)(MacTreeRefreshInterval.TotalSeconds * Stopwatch.Frequency);
}
long rssSum = 0;
double cpuDeltaSec = 0;
var wallNow = Stopwatch.GetTimestamp();
var dead = new List<int>();
foreach (var (pid, process) in handles)
{
try
{
process.Refresh();
if (process.HasExited)
{
dead.Add(pid);
continue;
}
rssSum += process.WorkingSet64;
var cpu = process.TotalProcessorTime;
if (prevWall is not null && prevCpuByPid.TryGetValue(pid, out var prev))
cpuDeltaSec += (cpu - prev).TotalSeconds;
prevCpuByPid[pid] = cpu;
}
catch (InvalidOperationException)
{
dead.Add(pid);
}
catch (System.ComponentModel.Win32Exception)
{
dead.Add(pid);
}
}
foreach (var pid in dead)
{
if (handles.Remove(pid, out var gone))
gone.Dispose();
prevCpuByPid.Remove(pid);
}
if (handles.Count == 0)
break;
if (rssSum > peakRss)
peakRss = rssSum;
if (prevWall is { } wall)
{
var wallSec = (wallNow - wall) / (double)Stopwatch.Frequency;
if (wallSec > 0)
{
var pct = cpuDeltaSec / wallSec / processors * 100.0;
if (pct >= 0 && !double.IsNaN(pct) && !double.IsInfinity(pct))
cpuSamples.Add(pct);
}
}
prevWall = wallNow;
var remainingTicks = deadline - Stopwatch.GetTimestamp();
if (remainingTicks <= 0)
break;
var delay = TimeSpan.FromSeconds(Math.Min(PollInterval.TotalSeconds,
remainingTicks / (double)Stopwatch.Frequency));
if (delay > TimeSpan.Zero)
await Task.Delay(delay, cancellationToken).ConfigureAwait(false);
}
if (peakRss <= 0 && cpuSamples.Count == 0)
return null;
var avgCpu = cpuSamples.Count > 0 ? cpuSamples.Average() : 0;
return new ProcessResourceSample(peakRss, avgCpu);
}
finally
{
foreach (var process in handles.Values)
process.Dispose();
}
}
private static void AttachMacPids(Dictionary<int, Process> handles, int rootPid, bool forceTreeRefresh)
{
// Between tree refreshes, only ensure the root handle stays attached — avoid pgrep storms.
IEnumerable<int> pids = forceTreeRefresh || handles.Count == 0
? GetMacTreePids(rootPid)
: handles.Keys.Append(rootPid).Distinct();
foreach (var pid in pids)
{
if (handles.ContainsKey(pid))
continue;
try
{
handles[pid] = Process.GetProcessById(pid);
}
catch (ArgumentException)
{
// exited
}
}
}
/// <summary>
/// Root PID plus descendants via repeated <c>pgrep -P</c> (nginx workers under serve-proxy).
/// </summary>
private static List<int> GetMacTreePids(int rootPid)
{
var result = new List<int>();
var seen = new HashSet<int> { rootPid };
var queue = new Queue<int>();
queue.Enqueue(rootPid);
try
{
while (queue.Count > 0)
{
var current = queue.Dequeue();
result.Add(current);
foreach (var kid in TryPgrepChildren(current))
{
if (seen.Add(kid))
queue.Enqueue(kid);
}
}
}
catch
{
return [rootPid];
}
return result.Count > 0 ? result : [rootPid];
}
private static List<int> TryPgrepChildren(int parentPid)
{
var kids = new List<int>();
try
{
using var p = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "/usr/bin/pgrep",
ArgumentList = { "-P", parentPid.ToString(CultureInfo.InvariantCulture) },
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true,
},
};
p.Start();
var stdout = p.StandardOutput.ReadToEnd();
p.WaitForExit(2000);
foreach (var line in stdout.Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
{
if (int.TryParse(line, NumberStyles.Integer, CultureInfo.InvariantCulture, out var kid) && kid > 0)
kids.Add(kid);
}
}
catch
{
// best-effort
}
return kids;
}
private static async Task<ProcessResourceSample?> SampleWindowsAsync(int rootPid, TimeSpan duration,
CancellationToken cancellationToken)
{
// Hold Process handles for the window so TotalProcessorTime deltas stay consistent.
var handles = new Dictionary<int, Process>();
try
{
AttachWindowsPids(handles, rootPid);
if (handles.Count == 0)
return null;
long peakRss = 0;
var cpuSamples = new List<double>(capacity: 64);
var prevCpuByPid = new Dictionary<int, TimeSpan>();
long? prevWall = null;
var deadline = Stopwatch.GetTimestamp() + (long)(duration.TotalSeconds * Stopwatch.Frequency);
var processors = Math.Max(1, Environment.ProcessorCount);
while (Stopwatch.GetTimestamp() < deadline)
{
cancellationToken.ThrowIfCancellationRequested();
AttachWindowsPids(handles, rootPid);
long rssSum = 0;
double cpuDeltaSec = 0;
var wallNow = Stopwatch.GetTimestamp();
var dead = new List<int>();
foreach (var (pid, process) in handles)
{
try
{
process.Refresh();
if (process.HasExited)
{
dead.Add(pid);
continue;
}
rssSum += process.WorkingSet64;
var cpu = process.TotalProcessorTime;
if (prevWall is not null && prevCpuByPid.TryGetValue(pid, out var prev))
cpuDeltaSec += (cpu - prev).TotalSeconds;
prevCpuByPid[pid] = cpu;
}
catch (InvalidOperationException)
{
dead.Add(pid);
}
}
foreach (var pid in dead)
{
if (handles.Remove(pid, out var gone))
gone.Dispose();
prevCpuByPid.Remove(pid);
}
if (handles.Count == 0)
break;
if (rssSum > peakRss)
peakRss = rssSum;
if (prevWall is { } wall)
{
var wallSec = (wallNow - wall) / (double)Stopwatch.Frequency;
if (wallSec > 0)
{
var pct = cpuDeltaSec / wallSec / processors * 100.0;
if (pct >= 0 && !double.IsNaN(pct) && !double.IsInfinity(pct))
cpuSamples.Add(pct);
}
}
prevWall = wallNow;
var remainingTicks = deadline - Stopwatch.GetTimestamp();
if (remainingTicks <= 0)
break;
var delay = TimeSpan.FromSeconds(Math.Min(PollInterval.TotalSeconds,
remainingTicks / (double)Stopwatch.Frequency));
if (delay > TimeSpan.Zero)
await Task.Delay(delay, cancellationToken).ConfigureAwait(false);
}
if (peakRss <= 0 && cpuSamples.Count == 0)
return null;
var avgCpu = cpuSamples.Count > 0 ? cpuSamples.Average() : 0;
return new ProcessResourceSample(peakRss, avgCpu);
}
finally
{
foreach (var process in handles.Values)
process.Dispose();
}
}
private static void AttachWindowsPids(Dictionary<int, Process> handles, int rootPid)
{
foreach (var pid in GetWindowsTreePids(rootPid))
{
if (handles.ContainsKey(pid))
continue;
try
{
handles[pid] = Process.GetProcessById(pid);
}
catch (ArgumentException)
{
// exited
}
}
}
private static async Task<ProcessResourceSample?> SampleLinuxAsync(int rootPid, TimeSpan duration,
CancellationToken cancellationToken)
{
var hz = GetLinuxClockTicksPerSecond();
long peakRss = 0;
var cpuSamples = new List<double>(capacity: 64);
var prevTicksByPid = new Dictionary<int, long>();
var prevWall = Stopwatch.GetTimestamp();
var deadline = Stopwatch.GetTimestamp() + (long)(duration.TotalSeconds * Stopwatch.Frequency);
var processors = Math.Max(1, Environment.ProcessorCount);
while (Stopwatch.GetTimestamp() < deadline)
{
cancellationToken.ThrowIfCancellationRequested();
var pids = GetLinuxTreePids(rootPid);
if (pids.Count == 0)
break;
long rssSum = 0;
long ticksSum = 0;
var alive = new List<int>();
foreach (var pid in pids)
{
var rss = TryReadLinuxRssBytes($"/proc/{pid}/status");
var ticks = TryReadLinuxCpuTicks($"/proc/{pid}/stat");
if (rss is null && ticks is null)
continue;
alive.Add(pid);
if (rss is > 0)
rssSum += rss.Value;
if (ticks is { } t)
ticksSum += t;
}
if (alive.Count == 0)
break;
if (rssSum > peakRss)
peakRss = rssSum;
var wallNow = Stopwatch.GetTimestamp();
if (prevTicksByPid.Count > 0)
{
var wallSec = (wallNow - prevWall) / (double)Stopwatch.Frequency;
if (wallSec > 0 && hz > 0)
{
long tickDelta = 0;
foreach (var pid in alive)
{
var ticks = TryReadLinuxCpuTicks($"/proc/{pid}/stat");
if (ticks is { } now && prevTicksByPid.TryGetValue(pid, out var prev))
tickDelta += now - prev;
}
var cpuSec = tickDelta / (double)hz;
var pct = cpuSec / wallSec / processors * 100.0;
if (pct >= 0 && !double.IsNaN(pct) && !double.IsInfinity(pct))
cpuSamples.Add(pct);
}
}
prevTicksByPid.Clear();
foreach (var pid in alive)
{
var ticks = TryReadLinuxCpuTicks($"/proc/{pid}/stat");
if (ticks is { } t)
prevTicksByPid[pid] = t;
}
prevWall = wallNow;
var remainingTicks = deadline - Stopwatch.GetTimestamp();
if (remainingTicks <= 0)
break;
var delay = TimeSpan.FromSeconds(Math.Min(PollInterval.TotalSeconds,
remainingTicks / (double)Stopwatch.Frequency));
if (delay > TimeSpan.Zero)
await Task.Delay(delay, cancellationToken).ConfigureAwait(false);
}
if (peakRss <= 0 && cpuSamples.Count == 0)
return null;
var avgCpu = cpuSamples.Count > 0 ? cpuSamples.Average() : 0;
return new ProcessResourceSample(peakRss, avgCpu);
}
/// <summary>
/// Root PID plus all descendants (serve-proxy → nginx master → workers).
/// Direct-children-only misses nginx workers under the .NET proxy child.
/// </summary>
private static List<int> GetWindowsTreePids(int rootPid)
{
var result = new List<int>();
try
{
var snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (snapshot == INVALID_HANDLE_VALUE)
return [rootPid];
try
{
var childrenByParent = new Dictionary<int, List<int>>();
var entry = new PROCESSENTRY32 { dwSize = (uint)Marshal.SizeOf<PROCESSENTRY32>() };
if (!Process32First(snapshot, ref entry))
return [rootPid];
do
{
var pid = (int)entry.th32ProcessID;
var ppid = (int)entry.th32ParentProcessID;
if (pid <= 0 || pid == ppid)
continue;
if (!childrenByParent.TryGetValue(ppid, out var list))
{
list = [];
childrenByParent[ppid] = list;
}
list.Add(pid);
} while (Process32Next(snapshot, ref entry));
var queue = new Queue<int>();
var seen = new HashSet<int> { rootPid };
queue.Enqueue(rootPid);
while (queue.Count > 0)
{
var current = queue.Dequeue();
result.Add(current);
if (!childrenByParent.TryGetValue(current, out var kids))
continue;
foreach (var kid in kids)
{
if (seen.Add(kid))
queue.Enqueue(kid);
}
}
}
finally
{
CloseHandle(snapshot);
}
}
catch
{
return [rootPid];
}
return result.Count > 0 ? result : [rootPid];
}
private static List<int> GetLinuxTreePids(int rootPid)
{
var result = new List<int>();
var seen = new HashSet<int> { rootPid };
var queue = new Queue<int>();
queue.Enqueue(rootPid);
try
{
// Build ppid → children once when walking deep trees (nginx workers are grandchildren).
var childrenByParent = new Dictionary<int, List<int>>();
foreach (var dir in Directory.EnumerateDirectories("/proc"))
{
var name = Path.GetFileName(dir);
if (!int.TryParse(name, NumberStyles.Integer, CultureInfo.InvariantCulture, out var pid))
continue;
var ppid = TryReadLinuxPpid($"/proc/{pid}/stat");
if (ppid is null or <= 0 || ppid == pid)
continue;
if (!childrenByParent.TryGetValue(ppid.Value, out var list))
{
list = [];
childrenByParent[ppid.Value] = list;
}
list.Add(pid);
}
while (queue.Count > 0)
{
var current = queue.Dequeue();
result.Add(current);
if (!childrenByParent.TryGetValue(current, out var kids))
continue;
foreach (var kid in kids)
{
if (seen.Add(kid))
queue.Enqueue(kid);
}
}
}
catch
{
return [rootPid];
}
return result.Count > 0 ? result : [rootPid];
}
private static int? TryReadLinuxPpid(string statPath)
{
try
{
var line = File.ReadAllText(statPath);
var closeParen = line.LastIndexOf(')');
if (closeParen < 0 || closeParen + 2 >= line.Length)
return null;
var afterComm = line[(closeParen + 2)..].Split(' ', StringSplitOptions.RemoveEmptyEntries);
// After ") ": field 3=state (index 0), field 4=ppid (index 1)
if (afterComm.Length < 2)
return null;
if (int.TryParse(afterComm[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out var ppid))
return ppid;
}
catch
{
// ignore
}
return null;
}
private static long? TryReadLinuxRssBytes(string statusPath)
{
try
{
foreach (var line in File.ReadLines(statusPath))
{
if (!line.StartsWith("VmRSS:", StringComparison.Ordinal))
continue;
var parts = line.Split(' ', StringSplitOptions.RemoveEmptyEntries);
if (parts.Length >= 2 && long.TryParse(parts[1], NumberStyles.Integer, CultureInfo.InvariantCulture,
out var kb))
return kb * 1024;
}
}
catch
{
// process may have exited
}
return null;
}
/// <summary>
/// Reads utime+stime (fields 14+15, 1-based after comm) from <c>/proc/<pid>/stat</c>.
/// </summary>
private static long? TryReadLinuxCpuTicks(string statPath)
{
try
{
var line = File.ReadAllText(statPath);
var closeParen = line.LastIndexOf(')');
if (closeParen < 0 || closeParen + 2 >= line.Length)
return null;
var afterComm = line[(closeParen + 2)..].Split(' ', StringSplitOptions.RemoveEmptyEntries);
// After ") ": field 3 is state; fields 14/15 are indices 11/12 in this slice (1-based 14 = index 11).
if (afterComm.Length < 13)
return null;
if (!long.TryParse(afterComm[11], NumberStyles.Integer, CultureInfo.InvariantCulture, out var utime))
return null;
if (!long.TryParse(afterComm[12], NumberStyles.Integer, CultureInfo.InvariantCulture, out var stime))
return null;
return utime + stime;
}
catch
{
return null;
}
}
private static long GetLinuxClockTicksPerSecond()
{
try
{
var hz = sysconf(_SC_CLK_TCK);
if (hz > 0)
return hz;
}
catch
{
// fall through
}
return 100;
}
// ReSharper disable once InconsistentNaming
private const int _SC_CLK_TCK = 2;
[DllImport("libc", SetLastError = true)]
private static extern long sysconf(int name);
private const uint TH32CS_SNAPPROCESS = 0x00000002;
private static readonly IntPtr INVALID_HANDLE_VALUE = new(-1);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
private struct PROCESSENTRY32
{
public uint dwSize;
public uint cntUsage;
public uint th32ProcessID;
public IntPtr th32DefaultHeapID;
public uint th32ModuleID;
public uint cntThreads;
public uint th32ParentProcessID;
public int pcPriClassBase;
public uint dwFlags;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public string szExeFile;
}
[DllImport("kernel32.dll", SetLastError = true)]
private static extern IntPtr CreateToolhelp32Snapshot(uint dwFlags, uint th32ProcessID);
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern bool Process32First(IntPtr hSnapshot, ref PROCESSENTRY32 lppe);
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern bool Process32Next(IntPtr hSnapshot, ref PROCESSENTRY32 lppe);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool CloseHandle(IntPtr hObject);
}