Skip to content

Instantly share code, notes, and snippets.

@rudiedirkx
Last active September 14, 2024 18:17
Show Gist options
  • Save rudiedirkx/72633ef295c7e80eb8336f8d0969e58a to your computer and use it in GitHub Desktop.
Save rudiedirkx/72633ef295c7e80eb8336f8d0969e58a to your computer and use it in GitHub Desktop.
<?php
$_debug = false;
$_uptime = 12;
if (!date_default_timezone_set($timezone = trim(file_get_contents('/etc/timezone')))) {
echo "Couldn't set timezone '$timezone'\n";
exit(1);
}
$logPath = $_SERVER['argv'][1] ?? null;
if (!$logPath || !file_exists($logPath)) {
echo "Invalid log file '$logPath'\n";
exit(2);
}
$uptime = trim(shell_exec('command uptime -s'));
if (strtotime($uptime) > strtotime("-$_uptime hours")) {
if ($_debug) echo "Uptime too recent ($uptime)\n";
exit(3);
}
$fp = fopen($logPath, 'r');
fseek($fp, -1000, SEEK_END);
$log = rtrim(fread($fp, 1002));
if ($idleTime = getLogIdleTime($log)) {
if ($idleTime < strtotime('-2 minutes')) {
if ($_debug) echo "Reboot!\n";
if (!$_debug) shell_exec('reboot');
exit(0);
}
}
if ($_debug) echo "Worker seems to be busy...\n";
exit(4);
function getLogIdleTime(string $log) : int {
if (preg_match('#(\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d) .+ DONE$#', $log, $match)) {
return strtotime($match[1]);
}
if (preg_match('#(\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d) Horizon started successfully\.$#', $log, $match)) {
return strtotime($match[1]);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment