/dev/null')); } /** * Belegter Platz je Pfad in Bytes (du, ohne andere Dateisysteme). Pfade, die es nicht gibt, fehlen im Ergebnis. * * @param array $paths * @return array */ function stats_du(array $paths): array { $paths = array_values(array_filter(array_unique($paths), 'file_exists')); if (!$paths) { return []; } $sizes = []; foreach (explode("\n", stats_run('du -x -s -B1 -- ' . implode(' ', array_map('escapeshellarg', $paths)))) as $line) { if (preg_match('/^(\d+)\s+(.+)$/', $line, $m)) { $sizes[$m[2]] = (int) $m[1]; } } return $sizes; } /** * Die groessten Verzeichnisse: oberste Ebene mit ihren groessten Unterverzeichnissen. * * @return array}> */ function stats_tree(): array { $top = []; $children = []; foreach (explode("\n", stats_run('du -x -B1 --max-depth=2 /')) as $line) { if (!preg_match('/^(\d+)\s+(\/.+)$/', $line, $m)) { continue; } $bytes = (int) $m[1]; $parts = explode('/', trim($m[2], '/')); if (count($parts) === 1) { $top[$m[2]] = $bytes; } elseif (count($parts) === 2) { $children['/' . $parts[0]][] = ['path' => $m[2], 'bytes' => $bytes]; } } arsort($top); $tree = []; foreach ($top as $path => $bytes) { if ($bytes < 50 * 1024 * 1024) { continue; // Kleinkram (und leere Einhaengepunkte wie /proc) weglassen } $kids = array_values(array_filter($children[$path] ?? [], static fn (array $c): bool => $c['bytes'] >= 10 * 1024 * 1024)); usort($kids, static fn (array $a, array $b): int => $b['bytes'] <=> $a['bytes']); $tree[] = ['path' => $path, 'bytes' => $bytes, 'children' => array_slice($kids, 0, 10)]; } return $tree; } /** Groessenangabe von Docker ("85.51GB", "113MB", "88.02kB (0%)") in Bytes - Docker rechnet mit 1000. */ function stats_docker_bytes(string $text): int { if (!preg_match('/^\s*([\d.]+)\s*([kMGT]?)B/i', $text, $m)) { return 0; } $factor = ['' => 1, 'K' => 1e3, 'M' => 1e6, 'G' => 1e9, 'T' => 1e12][strtoupper($m[2])]; return (int) round((float) $m[1] * $factor); } /** @return array Docker-Speicher nach Art (leer ohne Docker) */ function stats_docker(): array { $rows = []; foreach (explode("\n", stats_run("docker system df --format '{{.Type}}|{{.Size}}|{{.Reclaimable}}'")) as $line) { $parts = explode('|', $line); if (count($parts) === 3) { $rows[] = ['type' => $parts[0], 'bytes' => stats_docker_bytes($parts[1]), 'reclaimable' => stats_docker_bytes($parts[2])]; } } return $rows; } /** * Datenvolumen der Netzwerkkarte: Zaehler seit dem Neustart und - mit vnstat - je Tag und Monat. * * @return array */ function stats_traffic(string $interface): array { if ($interface === '' && preg_match('/\bdev\s+(\S+)/', stats_run('ip -o -4 route show default'), $m)) { $interface = $m[1]; } $traffic = ['interface' => $interface, 'since_boot' => null, 'vnstat' => false, 'counting_since' => null, 'days' => [], 'months' => []]; if ($interface === '') { return $traffic; } foreach ((array) @file('/proc/net/dev', FILE_IGNORE_NEW_LINES) as $line) { if (preg_match('/^\s*' . preg_quote($interface, '/') . ':\s*(.+)$/', (string) $line, $m)) { $fields = preg_split('/\s+/', trim($m[1])) ?: []; $uptime = (float) strtok((string) @file_get_contents('/proc/uptime'), ' '); $traffic['since_boot'] = [ 'rx' => (int) ($fields[0] ?? 0), 'tx' => (int) ($fields[8] ?? 0), 'boot_time' => date('c', time() - (int) $uptime), ]; } } $iface = escapeshellarg($interface); $days = json_decode(stats_run("vnstat -i $iface --json d 31"), true); $months = json_decode(stats_run("vnstat -i $iface --json m 12"), true); if (is_array($days) && isset($days['interfaces'][0]['traffic'])) { $traffic['vnstat'] = true; $created = $days['interfaces'][0]['created']['date'] ?? null; if (is_array($created)) { $traffic['counting_since'] = sprintf('%04d-%02d-%02d', $created['year'], $created['month'], $created['day']); } foreach ((array) ($days['interfaces'][0]['traffic']['day'] ?? []) as $row) { $traffic['days'][] = [ 'date' => sprintf('%04d-%02d-%02d', $row['date']['year'], $row['date']['month'], $row['date']['day']), 'rx' => (int) $row['rx'], 'tx' => (int) $row['tx'], ]; } foreach ((array) ($months['interfaces'][0]['traffic']['month'] ?? []) as $row) { $traffic['months'][] = [ 'month' => sprintf('%04d-%02d', $row['date']['year'], $row['date']['month']), 'rx' => (int) $row['rx'], 'tx' => (int) $row['tx'], ]; } } return $traffic; } $config = server_stats_config(); $target = (string) ($argv[1] ?? server_stats_file()); $site = dirname(__DIR__); // ---- Speicherplatz des Dateisystems ---- $df = preg_split('/\s+/', trim((string) (explode("\n", stats_run('df -B1 --output=size,used,avail /'))[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); // ---- Wofuer: benannte Bereiche. Was hier nicht vorkommt (weitere Projekte auf dem Server, Bots, Git-Server), // kommt aus config.php: server_stats.groups = ['Name' => ['/pfad', ...]] ---- $siteParts = [ 'Website: hochgeladene Dateien' => [$site . '/assets/uploads'], 'Website: Karten-Daten' => [$site . '/assets/map/data'], 'Website: Git-Verlauf' => [$site . '/.git'], ]; $groupPaths = $siteParts + [ 'Datenbank (MariaDB)' => ['/var/lib/mysql'], 'Backups' => ['/var/backups'], 'Docker' => ['/var/lib/docker', '/var/lib/containerd'], 'Protokolle (Logs)' => ['/var/log'], 'Betriebssystem und Programme' => ['/usr', '/boot', '/etc', '/var/cache', '/var/lib/apt', '/var/lib/dpkg'], ]; foreach ((array) ($config['groups'] ?? []) as $label => $paths) { $groupPaths[(string) $label] = array_values(array_map('strval', (array) $paths)); } // Die Website als Ganzes in einem eigenen Aufruf: du zaehlt nichts doppelt und liesse ihre Unterverzeichnisse // (Uploads, Karten, .git) sonst weg, weil sie im selben Aufruf schon im Ganzen stecken $sizes = stats_du(array_merge(...array_values($groupPaths))) + stats_du([$site]); $groups = []; $sitePartsBytes = 0; foreach ($groupPaths as $label => $paths) { $existing = array_values(array_filter($paths, static fn (string $p): bool => isset($sizes[$p]))); if (!$existing) { continue; } $bytes = array_sum(array_map(static fn (string $p): int => $sizes[$p], $existing)); $groups[] = ['label' => $label, 'bytes' => $bytes, 'paths' => $existing]; if (isset($siteParts[$label])) { $sitePartsBytes += $bytes; } } $groups[] = ['label' => 'Website: Code und übrige Dateien', 'bytes' => max(0, ($sizes[$site] ?? 0) - $sitePartsBytes), 'paths' => [$site]]; $rest = $used - array_sum(array_column($groups, 'bytes')); if ($rest > 0) { $groups[] = ['label' => 'Sonstiges', 'bytes' => $rest, 'paths' => []]; } usort($groups, static fn (array $a, array $b): int => $b['bytes'] <=> $a['bytes']); // ---- Verlauf: ein Stand je Tag, damit die Seite den Zuwachs zeigen kann ---- $previous = is_file($target) ? json_decode((string) file_get_contents($target), true) : null; $history = is_array($previous['disk']['history'] ?? null) ? $previous['disk']['history'] : []; $history[date('Y-m-d')] = $used; ksort($history); $history = array_slice($history, -SERVER_STATS_HISTORY_DAYS, null, true); $data = [ 'generated_at' => date('c'), 'hostname' => (string) gethostname(), 'disk' => ['total' => $total, 'used' => $used, 'free' => $free, 'history' => $history], 'groups' => $groups, 'tree' => stats_tree(), 'docker' => stats_docker(), 'traffic' => stats_traffic((string) ($config['interface'] ?? '')), ]; // ---- 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); }