exec("CREATE TABLE IF NOT EXISTS metrics ( hostname TEXT PRIMARY KEY, ip TEXT, cpu TEXT, mem_total INTEGER, mem_used INTEGER, disks TEXT, net_in INTEGER, net_out INTEGER, last_seen TIMESTAMP DEFAULT CURRENT_TIMESTAMP )"); function formatBytes($bytes, $precision = 2) { $units = ['B', 'KB', 'MB', 'GB', 'TB']; $bytes = max($bytes, 0); $pow = floor(($bytes ? log($bytes) : 0) / log(1024)); $pow = min($pow, count($units) - 1); $bytes /= pow(1024, $pow); return round($bytes, $precision) . ' ' . $units[$pow]; } if ($_SERVER['REQUEST_METHOD'] === 'POST') { $json = file_get_contents('php://input'); $data = json_decode($json, true); if ($data) { $stmt = $db->prepare("INSERT OR REPLACE INTO metrics (hostname, ip, cpu, mem_total, mem_used, disks, net_in, net_out, last_seen) VALUES (:host, :ip, :cpu, :mt, :mu, :disks, :ni, :no, datetime('now', 'localtime'))"); $stmt->bindValue(':host', $data['hostname']); $stmt->bindValue(':ip', $data['ip']); $stmt->bindValue(':cpu', $data['cpu']); $stmt->bindValue(':mt', $data['mem_total']); $stmt->bindValue(':mu', $data['mem_used']); $stmt->bindValue(':disks', json_encode($data['disks'])); $stmt->bindValue(':ni', $data['net_in']); $stmt->bindValue(':no', $data['net_out']); $stmt->execute(); } exit; } $results = $db->query("SELECT *, (strftime('%s', 'now', 'localtime') - strftime('%s', last_seen)) as diff FROM metrics ORDER BY hostname ASC"); ?>