LuminaWebsite/includes/server_stats.php

199 lines
7.4 KiB
PHP

<?php
declare(strict_types=1);
/**
* Speicher & Traffic (admin/server.php): was die Lumina-Website belegt (Dateien, Datenbank), wie viel auf dem
* Server noch frei ist und wie viel die Website uebertraegt - nur fuer Entwickler und Administratoren. Anderes
* auf dem Server kommt hier bewusst nicht vor.
*
* Die Zahlen sammelt includes/server_stats_collect.php als root (systemd-Timer, alle 15 Minuten) und legt sie als
* JSON ab - das Protokoll des Webservers darf die Website (www-data) nicht lesen. Die Seite liest nur diese Datei
* und fragt die Tabellengroessen selbst ab. 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';
/** Protokoll von Caddy fuer die Website (nur Zeitpunkt, Statuscode, Datenmenge), wenn config.php (server_stats.traffic_log) nichts anderes sagt. */
const SERVER_STATS_DEFAULT_TRAFFIC_LOG = '/var/log/caddy/lumina-traffic.log';
/** 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);
// "site" gibt es erst seit der Fassung nur fuer Lumina - ein aelterer Stand zaehlt als "noch keine Zahlen"
return is_array($data) && isset($data['generated_at'], $data['disk'], $data['site']) ? $data : null;
}
/**
* Woraus die Website besteht - in fester Reihenfolge mit fester Farbe je Teil (Diagramm "Woraus die Website
* besteht"). Die Farben sind als Reihe auf dunklem Grund geprueft (auch bei Farbfehlsichtigkeit unterscheidbar);
* neue Teile hinten anfuegen, nicht umsortieren. Die Schluessel liefert das Sammelskript, "db" die Datenbank.
*/
const SERVER_STATS_PARTS = [
'map' => ['Karten-Daten', '#3987e5'],
'uploads' => ['Hochgeladene Dateien', '#d95926'],
'db' => ['Datenbank', '#199e70'],
'git' => ['Git-Verlauf', '#c98500'],
'assets' => ['Bilder, Stile und Skripte', '#d55181'],
'code' => ['Programmcode', '#0ca30c'],
];
/** Upload-Ordner (assets/uploads/<Ordner>) mit lesbarem Namen . */
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 der Website ueber die letzten $days Tage aus dem Tagesverlauf (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;
}
/** Zahl lesbar: 18230 -> "18.230". */
function format_count(int|float $number): string
{
return number_format((float) $number, 0, ',', '.');
}
/**
* Obergrenze fuer die Achse eines Diagramms: der naechste "runde" Wert ueber $max in der Einheit, in der
* format_bytes() ihn zeigt (1, 2, 5, 10, 20, 50 ... MB/GB).
*/
function server_stats_nice_max(float $max): float
{
if ($max <= 0) {
return 1024 * 1024;
}
$unit = 1.0;
while ($max / $unit >= 1024) {
$unit *= 1024;
}
$value = $max / $unit;
foreach ([1, 2, 5, 10, 20, 50, 100, 200, 500, 1024] as $step) {
if ($value <= $step) {
return $step * $unit;
}
}
return 1024 * $unit;
}
/**
* Summe mehrerer Tage Datenvolumen.
*
* @param array<int, array{out: int, in: int, requests: int}> $rows
* @return array{bytes: float, requests: int}
*/
function server_stats_traffic_sum(array $rows): array
{
$bytes = 0.0;
$requests = 0;
foreach ($rows as $row) {
$bytes += (float) ($row['out'] ?? 0) + (float) ($row['in'] ?? 0);
$requests += (int) ($row['requests'] ?? 0);
}
return ['bytes' => $bytes, 'requests' => $requests];
}