-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMemoryGuard.php
More file actions
490 lines (425 loc) · 15.3 KB
/
Copy pathMemoryGuard.php
File metadata and controls
490 lines (425 loc) · 15.3 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
<?php
declare(strict_types=1);
namespace PivotPHP\ReactPHP\Security;
use React\EventLoop\LoopInterface;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
/**
* Memory Guard
*
* Automatic memory management to prevent leaks and excessive usage
*/
final class MemoryGuard
{
private LoopInterface $loop;
private LoggerInterface $logger;
/**
* Memory thresholds and limits
*/
private array $config = [
'max_memory' => 256 * 1024 * 1024, // 256MB max
'warning_threshold' => 200 * 1024 * 1024, // 200MB warning
'gc_threshold' => 100 * 1024 * 1024, // 100MB trigger GC
'check_interval' => 10.0, // Check every 10 seconds
'leak_detection_enabled' => true,
'auto_restart_threshold' => 300 * 1024 * 1024, // 300MB force restart
'cache_size_limits' => [
'default' => 10 * 1024 * 1024, // 10MB per cache
],
];
private array $memorySnapshots = [];
private array $trackedCaches = [];
private array $leakCallbacks = [];
private ?float $startTime = null;
private int $gcRuns = 0;
private bool $monitoring = false;
public function __construct(LoopInterface $loop, array $config = [], ?LoggerInterface $logger = null)
{
$this->loop = $loop;
$this->config = array_merge($this->config, $config);
$this->logger = $logger ?? new NullLogger();
$this->startTime = microtime(true);
}
/**
* Start memory monitoring
*/
public function startMonitoring(): void
{
if ($this->monitoring) {
return;
}
$this->monitoring = true;
// Periodic memory check
$this->loop->addPeriodicTimer($this->config['check_interval'], function () {
$this->performMemoryCheck();
});
// More frequent cache size check
$this->loop->addPeriodicTimer(2.0, function () {
$this->checkCacheSizes();
});
$this->logger->info('Memory guard started', [
'max_memory' => $this->formatBytes($this->config['max_memory']),
'check_interval' => $this->config['check_interval'],
]);
}
/**
* Register a cache to monitor
*
* @param string $name Cache identifier
* @param CacheInterface|mixed $cache Cache object (CacheInterface preferred, others will be wrapped)
* @param int|null $maxSize Maximum size in bytes before cleaning
* @throws \InvalidArgumentException If cache type is unsupported
*/
public function registerCache(string $name, mixed $cache, ?int $maxSize = null): void
{
// If already a CacheInterface, use directly
if ($cache instanceof CacheInterface) {
$this->trackedCaches[$name] = [
'object' => $cache,
'max_size' => $maxSize ?? $this->config['cache_size_limits']['default'],
'type' => 'interface',
];
return;
}
// Detect type and validate if we can wrap it
$type = $this->detectCacheType($cache);
if ($type === 'array') {
throw new \InvalidArgumentException(
'Plain arrays cannot be monitored effectively as they are passed by value. ' .
'Use ArrayObject, implement CacheInterface, or pass arrays by reference through a wrapper.'
);
}
if ($type === 'unknown') {
throw new \InvalidArgumentException(
'Unsupported cache type. Cache must implement CacheInterface or be ArrayObject/SplObjectStorage.'
);
}
// Wrap compatible cache types
$wrappedCache = new CacheWrapper($cache, $type);
$this->trackedCaches[$name] = [
'object' => $wrappedCache,
'max_size' => $maxSize ?? $this->config['cache_size_limits']['default'],
'type' => 'wrapped',
];
}
/**
* Register leak detection callback
*/
public function onMemoryLeak(callable $callback): void
{
$this->leakCallbacks[] = $callback;
}
/**
* Perform memory check
*/
private function performMemoryCheck(): void
{
$current = memory_get_usage(true);
$peak = memory_get_peak_usage(true);
// Take snapshot
$snapshot = [
'time' => microtime(true),
'current' => $current,
'peak' => $peak,
'gc_runs' => gc_collect_cycles(),
];
$this->memorySnapshots[] = $snapshot;
// Keep only last 60 snapshots (10 minutes worth)
if (count($this->memorySnapshots) > 60) {
array_shift($this->memorySnapshots);
}
// Check thresholds
if ($current > $this->config['auto_restart_threshold']) {
$this->handleCriticalMemory($current);
} elseif ($current > $this->config['warning_threshold']) {
$this->handleHighMemory($current);
} elseif ($current > $this->config['gc_threshold']) {
$this->triggerGarbageCollection();
}
// Detect leaks
if ($this->config['leak_detection_enabled']) {
$this->detectMemoryLeaks();
}
}
/**
* Check cache sizes and clean if necessary
*/
private function checkCacheSizes(): void
{
foreach ($this->trackedCaches as $name => $info) {
$cache = $info['object'];
$maxSize = $info['max_size'];
// Use CacheInterface methods for both wrapped and native implementations
if ($cache instanceof CacheInterface) {
$currentSize = $cache->getMemorySize();
if ($currentSize > $maxSize) {
$this->logger->warning('Cache size exceeded', [
'cache' => $name,
'current_size' => $this->formatBytes($currentSize),
'max_size' => $this->formatBytes($maxSize),
'stats' => $cache->getStats(),
]);
$cache->clean($maxSize);
}
} else {
// Fallback for legacy cache handling (should not happen with new API)
$currentSize = $this->getCacheSize($cache, $info['type']);
if ($currentSize > $maxSize) {
$this->logger->warning('Cache size exceeded (legacy)', [
'cache' => $name,
'current_size' => $this->formatBytes($currentSize),
'max_size' => $this->formatBytes($maxSize),
]);
$this->cleanCache($cache, $info['type'], $maxSize);
}
}
}
}
/**
* Detect cache type
*/
private function detectCacheType(mixed $cache): string
{
if (is_array($cache)) {
return 'array';
} elseif ($cache instanceof \ArrayObject) {
return 'ArrayObject';
} elseif ($cache instanceof \SplObjectStorage) {
return 'SplObjectStorage';
} elseif (is_object($cache) && method_exists($cache, 'count') && method_exists($cache, 'clear')) {
return 'countable';
} else {
return 'unknown';
}
}
/**
* Get cache size in bytes
*/
private function getCacheSize(mixed $cache, string $type): int
{
$size = 0;
switch ($type) {
case 'array':
if (is_array($cache)) {
foreach ($cache as $item) {
$size += strlen(serialize($item));
}
}
break;
case 'ArrayObject':
case 'countable':
if (is_object($cache) && method_exists($cache, 'count')) {
// Estimate based on count
$count = $cache->count();
$size = $count * 1024; // Assume 1KB average per item
}
break;
case 'SplObjectStorage':
if (is_object($cache) && method_exists($cache, 'count')) {
$size = $cache->count() * 2048; // Assume 2KB per object+data
}
break;
default:
// Try to serialize and measure
try {
$size = strlen(serialize($cache));
} catch (\Throwable $e) {
$size = 0;
}
}
return $size;
}
/**
* Clean cache to reduce size
*/
private function cleanCache(mixed $cache, string $type, int $targetSize): void
{
switch ($type) {
case 'array':
if (is_array($cache)) {
// Arrays passed by value, cannot modify directly
$this->logger->warning('Cannot clean array cache passed by value', [
'cache_type' => 'array',
'suggestion' => 'Use ArrayObject instead of plain arrays for mutable caches'
]);
}
break;
case 'countable':
if (is_object($cache) && method_exists($cache, 'clear')) {
$cache->clear();
} elseif (is_object($cache) && method_exists($cache, 'flush')) {
$cache->flush();
}
break;
case 'SplObjectStorage':
// Remove oldest 25% of objects
if (is_iterable($cache)) {
$all = iterator_to_array($cache);
$removeCount = (int) (count($all) * 0.25);
for ($i = 0; $i < $removeCount; $i++) {
if (isset($all[$i]) && is_object($cache) && method_exists($cache, 'detach')) {
$cache->detach($all[$i]);
}
}
}
break;
}
// Force garbage collection
gc_collect_cycles();
}
/**
* Handle high memory usage
*/
private function handleHighMemory(int $current): void
{
$this->logger->warning('High memory usage detected', [
'current' => $this->formatBytes($current),
'threshold' => $this->formatBytes($this->config['warning_threshold']),
'uptime' => $this->getUptime(),
]);
// Aggressive garbage collection
$this->triggerGarbageCollection();
// Clean all caches by 50%
foreach ($this->trackedCaches as $name => $info) {
$cache = $info['object'];
if ($cache instanceof CacheInterface) {
$cache->clean((int) ($info['max_size'] / 2));
} else {
$this->cleanCache($cache, $info['type'], (int) ($info['max_size'] / 2));
}
}
}
/**
* Handle critical memory usage
*/
private function handleCriticalMemory(int $current): void
{
$this->logger->error('Critical memory usage - restart required', [
'current' => $this->formatBytes($current),
'threshold' => $this->formatBytes($this->config['auto_restart_threshold']),
'uptime' => $this->getUptime(),
]);
// Notify callbacks
foreach ($this->leakCallbacks as $callback) {
$callback([
'type' => 'critical_memory',
'current' => $current,
'threshold' => $this->config['auto_restart_threshold'],
]);
}
// Clear all caches
foreach ($this->trackedCaches as $name => $info) {
$cache = $info['object'];
if ($cache instanceof CacheInterface) {
$cache->clear();
} elseif (is_object($cache) && method_exists($cache, 'clear')) {
$cache->clear();
}
}
// Final GC attempt
gc_collect_cycles();
// Schedule graceful restart
$this->loop->addTimer(1.0, function () {
$this->logger->emergency('Initiating graceful restart due to memory limit');
// This would trigger a graceful shutdown in production
// For now, just log it
});
}
/**
* Trigger garbage collection
*/
private function triggerGarbageCollection(): void
{
$before = memory_get_usage(true);
$cycles = gc_collect_cycles();
$after = memory_get_usage(true);
$freed = $before - $after;
$this->gcRuns++;
if ($freed > 1024 * 1024) { // Log if more than 1MB freed
$this->logger->info('Garbage collection completed', [
'cycles' => $cycles,
'freed' => $this->formatBytes($freed),
'total_runs' => $this->gcRuns,
]);
}
}
/**
* Detect memory leaks
*/
private function detectMemoryLeaks(): void
{
if (count($this->memorySnapshots) < 6) {
return; // Need at least 1 minute of data
}
// Calculate growth rate
$first = reset($this->memorySnapshots);
$last = end($this->memorySnapshots);
$timeElapsed = $last['time'] - $first['time'];
$memoryGrowth = $last['current'] - $first['current'];
$growthRate = $memoryGrowth / $timeElapsed; // Bytes per second
// If growing more than 1MB per minute
if ($growthRate > (1024 * 1024 / 60)) {
$this->logger->warning('Potential memory leak detected', [
'growth_rate' => $this->formatBytes((int) ($growthRate * 60)) . '/min',
'total_growth' => $this->formatBytes($memoryGrowth),
'time_elapsed' => round($timeElapsed) . 's',
]);
// Notify callbacks
foreach ($this->leakCallbacks as $callback) {
$callback([
'type' => 'memory_leak',
'growth_rate' => $growthRate,
'snapshots' => $this->memorySnapshots,
]);
}
}
}
/**
* Get uptime in human readable format
*/
private function getUptime(): string
{
if ($this->startTime === null) {
return 'unknown';
}
$seconds = (int) (microtime(true) - $this->startTime);
$days = floor($seconds / 86400);
$hours = floor(($seconds % 86400) / 3600);
$minutes = floor(($seconds % 3600) / 60);
if ($days > 0) {
return "{$days}d {$hours}h {$minutes}m";
} elseif ($hours > 0) {
return "{$hours}h {$minutes}m";
} else {
return "{$minutes}m";
}
}
/**
* Format bytes to human readable
*/
private function formatBytes(int $bytes): string
{
$units = ['B', 'KB', 'MB', 'GB'];
$i = 0;
while ($bytes >= 1024 && $i < count($units) - 1) {
$bytes /= 1024;
$i++;
}
return round($bytes, 2) . ' ' . $units[$i];
}
/**
* Get memory statistics
*/
public function getStats(): array
{
return [
'current_memory' => memory_get_usage(true),
'peak_memory' => memory_get_peak_usage(true),
'gc_runs' => $this->gcRuns,
'uptime' => $this->getUptime(),
'tracked_caches' => count($this->trackedCaches),
'snapshots' => count($this->memorySnapshots),
'monitoring' => $this->monitoring,
];
}
}