LuminaWebsite/includes/server_stats.php

136 lines
5.1 KiB
PHP

<?php
declare(strict_types=1);
/**
* Serverauslastung (admin/server.php): Speicherplatz und Datenvolumen des Servers, nur fuer Entwickler und
* Administratoren.
*
* Die Website selbst darf auf dem Server fast nichts lesen (PHP laeuft als www-data) - die Zahlen sammelt deshalb
* includes/server_stats_collect.php als root (systemd-Timer, alle 15 Minuten) und legt sie als JSON ab. Die Seite
* liest nur diese Datei. Einrichtung: siehe Kopf von server_stats_collect.php.
*/
/** Hier legt das Sammelskript die Zahlen ab, wenn config.php (server_stats.file) nichts anderes sagt. */
const SERVER_STATS_DEFAULT_FILE = '/var/lib/lumina-stats/server.json';
/** Aelter als so viele Minuten: Das Sammelskript laeuft offenbar nicht mehr - die Seite weist darauf hin. */
const SERVER_STATS_STALE_MINUTES = 60;
/** Ab diesen Anteilen belegten Speichers warnt die Seite (Prozent). */
const SERVER_STATS_DISK_WARN = 80;
const SERVER_STATS_DISK_CRITICAL = 90;
/** @return array<string, mixed> Abschnitt server_stats aus config.php (leer, wenn es ihn nicht gibt) */
function server_stats_config(): array
{
$configPath = __DIR__ . '/../config.php';
$config = file_exists($configPath) ? require $configPath : [];
return is_array($config['server_stats'] ?? null) ? $config['server_stats'] : [];
}
function server_stats_file(): string
{
$file = (string) (server_stats_config()['file'] ?? '');
return $file !== '' ? $file : SERVER_STATS_DEFAULT_FILE;
}
/**
* Nur Entwickler und Administratoren - es geht um den ganzen Server, nicht nur um die Website. Bewusst kein
* vergebbares Recht. In der Vorschau "Ansicht als Gruppe" ausgeblendet, wie alles, was nicht an Gruppen haengt.
*/
function server_stats_can_view(): bool
{
$user = current_user();
return $user !== null && $user['status'] === 'active' && role_preview() === null
&& (!empty($user['is_admin']) || is_developer($user));
}
/** @return array<string, mixed>|null Die gesammelten Zahlen - null, wenn die Datei fehlt oder unlesbar ist */
function server_stats_load(): ?array
{
$file = server_stats_file();
if (!is_file($file) || !is_readable($file)) {
return null;
}
$data = json_decode((string) file_get_contents($file), true);
return is_array($data) && isset($data['generated_at'], $data['disk']) ? $data : null;
}
/** Upload-Ordner (assets/uploads/<Ordner>) mit lesbarem Namen fuer die Uebersicht "Lumina-Website". */
const SERVER_STATS_UPLOAD_LABELS = [
'profiles' => 'Bilder der Profilseiten',
'avatars' => 'Profilbilder (Avatare)',
'armory' => 'Symbole und Portraits aus dem Spiel',
'gear' => 'Gear-Planer',
'skills' => 'Skill-Symbole',
'hunt' => 'Schnitzeljagd',
'bugs' => 'Fehlermeldungen (Screenshots)',
'maps' => 'Karten',
'wiki' => 'Wiki',
'roles' => 'Symbole der Gruppen',
];
/**
* Tabellen der Website-Datenbank nach Groesse (Daten + Indizes), groesste zuerst. Die Zeilenzahl ist bei InnoDB
* eine Schaetzung. Leer, wenn die Abfrage nicht erlaubt ist.
*
* @return array<int, array{name: string, bytes: int, rows: int}>
*/
function server_stats_db_tables(): array
{
try {
$rows = db()->query(
'SELECT table_name AS name, COALESCE(data_length, 0) + COALESCE(index_length, 0) AS bytes, COALESCE(table_rows, 0) AS row_count
FROM information_schema.tables WHERE table_schema = DATABASE() ORDER BY bytes DESC, name'
)->fetchAll();
} catch (PDOException $e) {
return [];
}
return array_map(static fn (array $r): array => ['name' => (string) $r['name'], 'bytes' => (int) $r['bytes'], 'rows' => (int) $r['row_count']], $rows);
}
/** Groesse lesbar: "512 MB", "63,4 GB" (1 GB = 1024 MB, wie df -h und die Angabe des Hosters). */
function format_bytes(int|float $bytes): string
{
$bytes = max(0, (float) $bytes);
$units = ['B', 'KB', 'MB', 'GB', 'TB'];
$i = 0;
while ($bytes >= 1024 && $i < count($units) - 1) {
$bytes /= 1024;
$i++;
}
$decimals = $i < 3 || $bytes >= 100 ? 0 : 1;
return number_format($bytes, $decimals, ',', '.') . ' ' . $units[$i];
}
/** Anteil in Prozent als Text: "34 %", unter 1 % "< 1 %". */
function format_share(float $part, float $whole): string
{
if ($whole <= 0 || $part <= 0) {
return '0 %';
}
$percent = $part / $whole * 100;
return $percent < 1 ? '< 1 %' : number_format($percent, 0, ',', '.') . ' %';
}
/**
* Zuwachs des belegten Speichers ueber die letzten $days Tage aus dem Tagesverlauf (disk.history: Datum => Bytes).
* Null, wenn der Verlauf noch nicht so weit zurueckreicht.
*
* @param array<string, int|float> $history
*/
function server_stats_growth(array $history, int $days): ?float
{
if (count($history) < 2) {
return null;
}
ksort($history);
$latestDate = (string) array_key_last($history);
$target = date('Y-m-d', strtotime($latestDate . ' -' . $days . ' days'));
// Der juengste Stand, der mindestens $days Tage alt ist
$base = null;
foreach ($history as $date => $used) {
if ((string) $date <= $target) {
$base = (float) $used;
}
}
return $base === null ? null : (float) $history[$latestDate] - $base;
}