/dev/null')); } /** * Die Dateien der Website nach Art und die Upload-Ordner im Einzelnen. Ein du-Aufruf ueber das ganze Verzeichnis, * daraus die einzelnen Pfade. * * @return array{path: string, total: int, parts: array, uploads: array} */ function stats_site(string $site): array { $sizes = []; foreach (explode("\n", stats_run('du -B1 --max-depth=3 ' . escapeshellarg($site))) as $line) { if (preg_match('/^(\d+)\s+(.+)$/', $line, $m)) { $sizes[$m[2]] = (int) $m[1]; } } $total = $sizes[$site] ?? 0; $assets = $sizes[$site . '/assets'] ?? 0; $uploadsBytes = $sizes[$site . '/assets/uploads'] ?? 0; $mapData = $sizes[$site . '/assets/map/data'] ?? 0; $git = $sizes[$site . '/.git'] ?? 0; // Schluessel wie in SERVER_STATS_PARTS (Namen und Farben stehen dort) $parts = [ ['key' => 'uploads', 'bytes' => $uploadsBytes], ['key' => 'map', 'bytes' => $mapData], ['key' => 'assets', 'bytes' => max(0, $assets - $uploadsBytes - $mapData)], ['key' => 'git', 'bytes' => $git], ['key' => 'code', 'bytes' => max(0, $total - $assets - $git)], ]; $uploads = []; $prefix = $site . '/assets/uploads/'; foreach ($sizes as $path => $bytes) { if (str_starts_with($path, $prefix) && !str_contains(substr($path, strlen($prefix)), '/')) { $uploads[] = [ 'dir' => substr($path, strlen($prefix)), 'bytes' => $bytes, 'files' => (int) stats_run('find ' . escapeshellarg($path) . ' -type f | wc -l'), ]; } } usort($uploads, static fn (array $a, array $b): int => $b['bytes'] <=> $a['bytes']); return ['path' => $site, 'total' => $total, 'parts' => $parts, 'uploads' => $uploads]; } /** Groesse der Website-Datenbank (Daten + Indizes aller Tabellen) - null, wenn sie nicht erreichbar ist. */ function stats_db_bytes(string $site): ?int { $config = is_file($site . '/config.php') ? require $site . '/config.php' : []; $db = $config['db'] ?? null; if (!is_array($db)) { return null; } try { $pdo = new PDO("mysql:host={$db['host']};dbname={$db['name']};charset={$db['charset']}", $db['user'], $db['pass'], [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]); return (int) $pdo->query('SELECT COALESCE(SUM(data_length + index_length), 0) FROM information_schema.tables WHERE table_schema = DATABASE()')->fetchColumn(); } catch (PDOException $e) { return null; } } /** * Datenvolumen und Aufrufe der Website je Tag aus dem Protokoll von Caddy. Gelesen wird nur, was seit dem letzten * Lauf dazugekommen ist (Merker: Datei-Nummer und Position); wechselt Caddy die Datei (roll_size), wird erst die * alte zu Ende gelesen und dann die neue von vorn. * * @param array $previous Abschnitt traffic des letzten Laufs * @return array{since: ?string, days: array, cursor: array{inode: int, offset: int}} */ function stats_traffic(string $logFile, array $previous): array { if (!isset($previous['cursor'])) { $previous = []; // kein Stand dieses Skripts (erste Fassung zaehlte anders) - von vorn } $days = is_array($previous['days'] ?? null) ? $previous['days'] : []; $cursor = ['inode' => (int) ($previous['cursor']['inode'] ?? 0), 'offset' => (int) ($previous['cursor']['offset'] ?? 0)]; $since = isset($previous['since']) ? (string) $previous['since'] : null; if (!is_file($logFile)) { return ['since' => $since, 'days' => $days, 'cursor' => $cursor]; } clearstatcache(); $currentInode = (int) fileinode($logFile); // Was zu lesen ist: [Datei, ab Position] $queue = [[$logFile, 0]]; if ($cursor['inode'] === $currentInode) { $queue = [[$logFile, $cursor['offset'] <= filesize($logFile) ? $cursor['offset'] : 0]]; } elseif ($cursor['inode'] !== 0) { // Caddy hat die Datei gewechselt: die alte (lumina-traffic-.log) zu Ende lesen, dazu alle, die danach entstanden $base = preg_replace('/\.log$/', '', $logFile); $rolled = array_values(array_filter(glob($base . '-*.log') ?: [], 'is_file')); usort($rolled, static fn (string $a, string $b): int => filemtime($a) <=> filemtime($b)); $queue = []; $found = false; foreach ($rolled as $file) { if ((int) fileinode($file) === $cursor['inode']) { $queue[] = [$file, $cursor['offset']]; $found = true; } elseif ($found) { $queue[] = [$file, 0]; } } $queue[] = [$logFile, 0]; } $offset = 0; foreach ($queue as [$file, $start]) { $handle = @fopen($file, 'rb'); if ($handle === false) { continue; } fseek($handle, $start); $offset = $start; while (($line = fgets($handle)) !== false) { if (!str_ends_with($line, "\n")) { break; // Zeile wird gerade noch geschrieben - beim naechsten Lauf } $offset += strlen($line); $entry = json_decode($line, true); if (!is_array($entry) || !isset($entry['ts'])) { continue; } $day = date('Y-m-d', (int) $entry['ts']); $days[$day] ??= ['out' => 0, 'in' => 0, 'requests' => 0]; $days[$day]['out'] += (int) ($entry['size'] ?? 0); $days[$day]['in'] += (int) ($entry['bytes_read'] ?? 0); $days[$day]['requests']++; } fclose($handle); } ksort($days); $days = array_slice($days, -SERVER_STATS_HISTORY_DAYS, null, true); return [ 'since' => $since ?? (string) (array_key_first($days) ?? date('Y-m-d')), 'days' => $days, 'cursor' => ['inode' => $currentInode, 'offset' => $offset], ]; } $config = server_stats_config(); $target = (string) ($argv[1] ?? server_stats_file()); $site = dirname(__DIR__); $previous = is_file($target) ? json_decode((string) file_get_contents($target), true) : null; $previous = is_array($previous) ? $previous : []; // ---- Speicherplatz des Dateisystems, auf dem die Website liegt ---- $df = preg_split('/\s+/', trim((string) (explode("\n", stats_run('df -B1 --output=size,used,avail ' . escapeshellarg($site)))[1] ?? ''))) ?: []; if (count($df) < 3) { fwrite(STDERR, "df lieferte keine Zahlen - laeuft das Skript auf dem Server (Linux)?\n"); exit(1); } [$total, $used, $free] = array_map('intval', $df); // ---- Die Website: Dateien und Datenbank ---- $siteStats = stats_site($site); $siteStats['db_bytes'] = stats_db_bytes($site); // ---- Verlauf: ein Stand je Tag (Dateien + Datenbank), damit die Seite den Zuwachs zeigen kann ---- $history = is_array($previous['history'] ?? null) ? $previous['history'] : []; $history[date('Y-m-d')] = $siteStats['total'] + (int) $siteStats['db_bytes']; ksort($history); $history = array_slice($history, -SERVER_STATS_HISTORY_DAYS, null, true); $logFile = (string) ($config['traffic_log'] ?? ''); $data = [ 'generated_at' => date('c'), 'disk' => ['total' => $total, 'used' => $used, 'free' => $free], 'site' => $siteStats, 'history' => $history, 'traffic' => stats_traffic($logFile !== '' ? $logFile : SERVER_STATS_DEFAULT_TRAFFIC_LOG, is_array($previous['traffic'] ?? null) ? $previous['traffic'] : []), ]; // ---- Schreiben: erst daneben, dann umbenennen - die Seite liest nie eine halbe Datei ---- $dir = dirname($target); if (!is_dir($dir) && !mkdir($dir, 0755, true)) { fwrite(STDERR, "Verzeichnis $dir laesst sich nicht anlegen.\n"); exit(1); } $tmp = $target . '.tmp'; if (file_put_contents($tmp, json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)) === false || !chmod($tmp, 0644) || !rename($tmp, $target)) { fwrite(STDERR, "Datei $target laesst sich nicht schreiben.\n"); exit(1); }