38753-vm/backend_monitor.php
2026-02-25 01:15:30 +00:00

48 lines
1.7 KiB
PHP

<?php
require_once __DIR__ . '/api/uptime.php';
// A simple CLI script that runs continuously on the server
// Usage: php backend_monitor.php &
if (php_sapi_name() !== 'cli') {
die("This script must be run from the command line.");
}
echo "Starting 24/7 Flatlogic Backend Monitor...\n";
echo "Monitoring URLs every 2 seconds...\n";
while (true) {
if (isMonitoringEnabled()) {
$stmt = db()->query("SELECT * FROM urls WHERE is_active = 1");
$urls = $stmt->fetchAll();
foreach ($urls as $row) {
$res = ping($row['url']);
// Log latency to ensure history exists
$ins = db()->prepare("INSERT INTO uptime_logs (url_id, status, latency) VALUES (?, ?, ?)");
$ins->execute([$row['id'], $res['status'], $res['latency']]);
// Notify on change
notifyStatusChange($row['url'], $row['last_status'], $res['status'], $res['error']);
// Update URL status
$upd = db()->prepare("UPDATE urls SET last_status = ?, last_latency = ?, last_checked_at = NOW() WHERE id = ?");
$upd->execute([$res['status'], $res['latency'], $row['id']]);
// Keep only last 500 logs per URL to save DB space
$del = db()->prepare(
"DELETE FROM uptime_logs
WHERE url_id = ?
AND id NOT IN (
SELECT id FROM (
SELECT id FROM uptime_logs WHERE url_id = ? ORDER BY id DESC LIMIT 500
) foo
)"
);
$del->execute([$row['id'], $row['id']]);
}
}
sleep(2); // Wait 2 seconds before the next check
}