LuminaWebsite/includes/server_stats_collect.php

258 lines
11 KiB
PHP

<?php
declare(strict_types=1);
/**
* Sammelt die Zahlen fuer die Seite "Speicher & Traffic" (admin/server.php) - nur fuer die Lumina-Website:
* was ihre Dateien und ihre Datenbank belegen, wie viel auf dem Server noch frei ist und wie viel die Website
* uebertraegt. Nur von der Kommandozeile und als root (das Protokoll des Webservers darf sonst niemand 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):
*
* 1. Caddy zaehlt mit - im Block der Website (lumina-ascendens.de { ... }) in /etc/caddy/Caddyfile. Das Protokoll
* enthaelt nur Zeitpunkt, Statuscode und Datenmenge: keine IP-Adresse, keine Adresse der Seite, kein Browser.
* log {
* output file /var/log/caddy/lumina-traffic.log {
* roll_size 50MiB
* roll_keep 2
* roll_keep_for 48h
* roll_uncompressed
* }
* format filter {
* wrap json
* fields {
* request delete
* resp_headers delete
* user_id delete
* }
* }
* }
* Danach: systemctl reload caddy (caddy validate nicht als root laufen lassen - es legt die Protokolldatei
* sonst als root an und Caddy kann sie nicht mehr oeffnen).
*
* 2. Timer:
* /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
*/
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 Verlauf (Groesse der Website, Datenvolumen je Tag) aufgehoben werden. */
const SERVER_STATS_HISTORY_DAYS = 400;
/** 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'));
}
/**
* 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<int, array{key: string, bytes: int}>, uploads: array<int, array{dir: string, bytes: int, files: int}>}
*/
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<string, mixed> $previous Abschnitt traffic des letzten Laufs
* @return array{since: ?string, days: array<string, array{out: int, in: int, requests: int}>, 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-<Zeit>.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);
}