Skip to content

Commit

Permalink
Merge pull request #31 from vormkracht10/feature/uptime-check
Browse files Browse the repository at this point in the history
Feature/uptime check
  • Loading branch information
markvaneijk authored Sep 29, 2023
2 parents eea71fd + e43120d commit 284edc8
Showing 1 changed file with 71 additions and 0 deletions.
71 changes: 71 additions & 0 deletions src/Checks/UptimeCheck.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
<?php

namespace Vormkracht10\LaravelOK\Checks;

use Carbon\Carbon;
use Illuminate\Support\Facades\Process;
use RuntimeException;
use Vormkracht10\LaravelOK\Checks\Base\Check;
use Vormkracht10\LaravelOK\Checks\Base\Result;

class UptimeCheck extends Check
{
protected Carbon $maxTimeSinceRebootTimestamp;

public function setMaxTimeSinceRebootTimestamp(Carbon $time): static
{
$this->maxTimeSinceRebootTimestamp = $time;

return $this;
}

public function run(): Result
{
$result = Result::new();

$timestamp = $this->getSystemUptime();

if (! isset($this->maxTimeSinceRebootTimestamp)) {
throw new \Exception('The max time since reboot was not set.');
}

if ($this->maxTimeSinceRebootTimestamp > $timestamp) {
return $result->failed("Last reboot was at [{$timestamp}], the maximum uptime for this server was set to [{$this->maxTimeSinceRebootTimestamp}]");
}

return $result->ok("Last reboot {$timestamp->diffInDays()} days and {$timestamp->diffInMinutes()} ago");
}

protected function getSystemUptime(): Carbon
{
return match ($os = PHP_OS) {
'Linux' => $this->getSystemUptimeLinux(),
'Darwin' => $this->getSystemUptimeDarwin(),
default => throw new RuntimeException("This os ({$os}) is not supported by the UptimeCheck"),
};
}

protected function runProcess(string $command): string
{
$process = Process::run($command);

return match ($process->successful()) {
true => $process->output(),
false => throw new RuntimeException('Could not get system boot timestamp: '.$process->errorOutput()),
};
}

protected function getSystemUptimeLinux(): Carbon
{
return Carbon::createFromTimestamp(
$this->runProcess('date -d "$(who -b | awk \'{print $3, $4}\')" +%s'),
);
}

protected function getSystemUptimeDarwin(): Carbon
{
return Carbon::createFromTimestamp(
$this->runProcess('date -j -f "%b %d %H:%M" "$(who -b | awk \'{print $3,$4,$5}\')" +%s'),
);
}
}

0 comments on commit 284edc8

Please sign in to comment.