Skip to content

Commit

Permalink
account for division by zero and check for PHP_OS
Browse files Browse the repository at this point in the history
  • Loading branch information
david-d-h committed Nov 6, 2023
1 parent 0112d87 commit 253c9f4
Showing 1 changed file with 13 additions and 2 deletions.
15 changes: 13 additions & 2 deletions src/Checks/MemoryUsageCheck.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Vormkracht10\LaravelOK\Checks;

use Exception;
use Vormkracht10\LaravelOK\Checks\Base\Check;
use Vormkracht10\LaravelOK\Checks\Base\Result;

Expand All @@ -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) {
Expand All @@ -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}%");
Expand Down

0 comments on commit 253c9f4

Please sign in to comment.