LuminaWebsite/includes/server_stats_collect.php

268 lines
11 KiB
PHP

<?php
declare(strict_types=1);
/**
* Sammelt die Zahlen fuer die Seite "Server" (admin/server.php): Speicherplatz des Servers, wofuer er verbraucht
* wird, und das Datenvolumen (Traffic). Nur von der Kommandozeile und als root - die Website (www-data) darf die
* meisten Verzeichnisse nicht lesen. Das Ergebnis ist eine JSON-Datei, die die Seite nur noch anzeigt.
*
* php /var/www/lumina/includes/server_stats_collect.php [Zieldatei]
*
* Ohne Zieldatei gilt config.php (server_stats.file), sonst SERVER_STATS_DEFAULT_FILE.
*
* Einrichtung auf dem Server (einmalig, als root):
* apt install vnstat # zaehlt das Datenvolumen je Tag und Monat (ab der Installation)
* /etc/systemd/system/lumina-stats.service:
* [Unit]
* Description=Lumina: Speicherplatz und Datenvolumen sammeln
* [Service]
* Type=oneshot
* ExecStart=/usr/bin/php /var/www/lumina/includes/server_stats_collect.php
* Nice=19
* IOSchedulingClass=idle
* /etc/systemd/system/lumina-stats.timer:
* [Unit]
* Description=Lumina: Speicherplatz und Datenvolumen alle 15 Minuten sammeln
* [Timer]
* OnBootSec=2min
* OnUnitActiveSec=15min
* [Install]
* WantedBy=timers.target
* systemctl daemon-reload && systemctl enable --now lumina-stats.timer
*
* Ohne vnstat zeigt die Seite nur das Datenvolumen seit dem letzten Neustart (Zaehler des Kernels).
*/
if (PHP_SAPI !== 'cli') {
http_response_code(404);
exit;
}
require __DIR__ . '/server_stats.php';
// Dieselbe Zeitzone wie die Website (includes/bootstrap.php) - auf der Kommandozeile gilt sonst UTC
date_default_timezone_set('Europe/Berlin');
/** Wie viele Tage der Verlauf des belegten Speichers zurueckreicht. */
const SERVER_STATS_HISTORY_DAYS = 90;
/** Ausgabe eines Befehls ("" bei Fehler) - Fehlermeldungen des Befehls werden verworfen. */
function stats_run(string $command): string
{
return trim((string) shell_exec($command . ' 2>/dev/null'));
}
/**
* Belegter Platz je Pfad in Bytes (du, ohne andere Dateisysteme). Pfade, die es nicht gibt, fehlen im Ergebnis.
*
* @param array<int, string> $paths
* @return array<string, int>
*/
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<int, array{path: string, bytes: int, children: array<int, array{path: string, bytes: int}>}>
*/
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<int, array{type: string, bytes: int, reclaimable: int}> 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<string, mixed>
*/
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);
}