Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/uptime check #31

Merged
merged 4 commits into from
Sep 29, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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'),
);
}
}