From 253c9f41c8400ca1583c3210bc77ca64119b8d49 Mon Sep 17 00:00:00 2001 From: David <75451291+dulkoss@users.noreply.github.com> Date: Mon, 6 Nov 2023 10:53:59 +0100 Subject: [PATCH] account for division by zero and check for PHP_OS --- src/Checks/MemoryUsageCheck.php | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/src/Checks/MemoryUsageCheck.php b/src/Checks/MemoryUsageCheck.php index 914e5c9..1f7b595 100644 --- a/src/Checks/MemoryUsageCheck.php +++ b/src/Checks/MemoryUsageCheck.php @@ -2,6 +2,7 @@ namespace Vormkracht10\LaravelOK\Checks; +use Exception; use Vormkracht10\LaravelOK\Checks\Base\Check; use Vormkracht10\LaravelOK\Checks\Base\Result; @@ -20,7 +21,7 @@ public function threshold(int $percentage): static public function getSystemMemInfo() { - $data = explode("\n", trim(file_get_contents('/proc/meminfo'))); + $data = explode("\n", trim(@file_get_contents('/proc/meminfo') or throw new Exception('Failed to read memory'))); $memInfo = []; foreach ($data as $line) { @@ -35,9 +36,19 @@ public function run(): Result { $result = Result::new(); + if (PHP_OS !== 'Linux') { + return $result->failed('The MemoryUsageCheck only works on Linux.'); + } + $data = $this->getSystemMemInfo(); - $usedPercentage = round(100 - (($data['MemAvailable'] / $data['MemTotal']) * 100), 2); + $usedPercentage = (int) $data['MemTotal'] !== 0 + ? round(100 - (($data['MemAvailable'] / $data['MemTotal']) * 100), 2) + : false; + + if ($usedPercentage === false) { + return $result->failed('Failed to measure memory usage.'); + } if ($usedPercentage > $this->limit) { return $result->failed("Memory usage is at {$usedPercentage}%, limit is configured to {$this->limit}%");