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