1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace OldSound\RabbitMqBundle\MemoryChecker; |
4
|
|
|
|
5
|
|
|
/** |
6
|
|
|
* Help handling memory limits . |
7
|
|
|
* |
8
|
|
|
* @author Jonas Haouzi <[email protected]> |
9
|
|
|
*/ |
10
|
|
|
class MemoryConsumptionChecker |
11
|
|
|
{ |
12
|
|
|
/** @var NativeMemoryUsageProvider */ |
13
|
|
|
private $memoryUsageProvider; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* MemoryManager constructor. |
17
|
|
|
* |
18
|
|
|
* @param NativeMemoryUsageProvider $memoryUsageProvider |
19
|
|
|
*/ |
20
|
4 |
|
public function __construct(NativeMemoryUsageProvider $memoryUsageProvider) { |
21
|
4 |
|
$this->memoryUsageProvider = $memoryUsageProvider; |
22
|
4 |
|
} |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* @param int|string $allowedConsumptionUntil |
26
|
|
|
* @param int|string $maxConsumptionAllowed |
27
|
|
|
* |
28
|
|
|
* @return bool |
29
|
|
|
*/ |
30
|
4 |
|
public function isRamAlmostOverloaded($maxConsumptionAllowed, $allowedConsumptionUntil = 0) |
31
|
|
|
{ |
32
|
4 |
|
$allowedConsumptionUntil = $this->convertHumanUnitToNumerical($allowedConsumptionUntil); |
33
|
4 |
|
$maxConsumptionAllowed = $this->convertHumanUnitToNumerical($maxConsumptionAllowed); |
34
|
4 |
|
$currentUsage = $this->convertHumanUnitToNumerical($this->memoryUsageProvider->getMemoryUsage()); |
35
|
|
|
|
36
|
4 |
|
return $currentUsage > ($maxConsumptionAllowed - $allowedConsumptionUntil); |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* @param int|string $humanUnit |
41
|
|
|
* |
42
|
|
|
* @return int |
43
|
|
|
*/ |
44
|
4 |
|
private function convertHumanUnitToNumerical($humanUnit) |
45
|
|
|
{ |
46
|
4 |
|
$numerical = $humanUnit; |
47
|
4 |
|
if (!is_numeric($humanUnit)) { |
48
|
4 |
|
$numerical = (int) substr($numerical, 0, -1); |
49
|
4 |
|
switch (substr($humanUnit, -1)) { |
50
|
4 |
|
case 'G': |
51
|
|
|
$numerical *= pow(1024, 3); |
52
|
|
|
break; |
53
|
4 |
|
case 'M': |
54
|
4 |
|
$numerical *= pow(1024, 2); |
55
|
4 |
|
break; |
56
|
|
|
case 'K': |
57
|
|
|
$numerical *= 1024; |
58
|
|
|
break; |
59
|
|
|
} |
60
|
|
|
} |
61
|
|
|
|
62
|
4 |
|
return (int)$numerical; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
} |
66
|
|
|
|