diff --git a/src/Checks/UptimeCheck.php b/src/Checks/UptimeCheck.php new file mode 100644 index 0000000..5b77401 --- /dev/null +++ b/src/Checks/UptimeCheck.php @@ -0,0 +1,71 @@ +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'), + ); + } +}