diff --git a/admin/server.php b/admin/server.php index 0676a5e..e70dd42 100644 --- a/admin/server.php +++ b/admin/server.php @@ -1,8 +1,9 @@ 'Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember']; -$dockerLabels = ['Images' => 'Images', 'Containers' => 'Container', 'Local Volumes' => 'Volumes', 'Build Cache' => 'Build-Cache']; -/** Balken fuer eine Groesse: Anteil an $max in Prozent, mindestens sichtbar, wenn ueberhaupt etwas da ist. */ +/** Breite eines Balkens: Anteil an $max in Prozent - sichtbar, sobald ueberhaupt etwas da ist. */ $barWidth = static fn (float $value, float $max): string => $max > 0 && $value > 0 - ? number_format(max(0.6, min(100, $value / $max * 100)), 2, '.', '') . '%' + ? number_format(max(0.8, min(100, $value / $max * 100)), 2, '.', '') . '%' : '0'; +$signed = static fn (float $bytes): string => ($bytes >= 0 ? '+' : '−') . format_bytes(abs($bytes)); -/** Empfangen und Gesendet als gestapelter Balken, gemessen am groessten Wert der Tabelle. */ -$trafficBar = static function (array $row, float $max) use ($barWidth): string { - return ''; -}; - -/** Kachel mit Datenvolumen: Summe gross, darunter Empfangen und Gesendet. */ -$trafficTile = static function (string $label, ?array $row): string { - if ($row === null) { - return '
' . e($label) . '' - . '–noch keine Zahlen
'; - } - return '
' . e($label) . '' - . '' . e(format_bytes($row['rx'] + $row['tx'])) . '' - . '↓ ' . e(format_bytes($row['rx'])) . ' empfangen · ↑ ' . e(format_bytes($row['tx'])) . ' gesendet
'; -}; - -$pageTitle = 'Server'; +$pageTitle = 'Speicher & Traffic'; +$containerWide = true; include __DIR__ . '/../includes/header.php'; ?> -
-

Server

+
-

- Speicherplatz und Datenvolumen des Servers – noch gibt es keine Zahlen. Die sammelt ein kleines Skript auf dem - Server (includes/server_stats_collect.php, als root per Timer; die Einrichtung steht im Kopf der Datei) - und legt sie hier ab: -

+
+

Speicher & Traffic

+

+ Noch gibt es keine Zahlen. Die sammelt ein kleines Skript auf dem Server + (includes/server_stats_collect.php, als root per Timer – die Einrichtung steht im Kopf der Datei) + und legt sie hier ab: +

+
0 ? $used / $total * 100 : 0; - $diskState = $usedPercent >= SERVER_STATS_DISK_CRITICAL ? 'critical' : ($usedPercent >= SERVER_STATS_DISK_WARN ? 'warning' : 'ok'); - $history = is_array($disk['history'] ?? null) ? $disk['history'] : []; + + // ---- Website: Dateien (Sammelskript) und Datenbank (hier abgefragt, sonst der Stand des Skripts) ---- + $site = $stats['site']; + $dbTables = server_stats_db_tables(); + $dbBytes = $dbTables ? (float) array_sum(array_column($dbTables, 'bytes')) : (float) ($site['db_bytes'] ?? 0); + $fileBytes = (float) $site['total']; + $siteTotal = $fileBytes + $dbBytes; + $partBytes = array_column($site['parts'], 'bytes', 'key') + ['db' => $dbBytes]; + $history = is_array($stats['history'] ?? null) ? $stats['history'] : []; $growthWeek = server_stats_growth($history, 7); $growthMonth = server_stats_growth($history, 30); - // Reicht der Platz? Nur wenn er in der letzten Woche spuerbar gewachsen ist - $daysLeft = $growthWeek !== null && $growthWeek > 100 * 1024 * 1024 ? (int) floor($free / ($growthWeek / 7)) : null; + + // ---- Server: nur, wie viel Platz noch ist ---- + $disk = $stats['disk']; + $diskTotal = (float) $disk['total']; + $diskUsed = (float) $disk['used']; + $diskFree = (float) $disk['free']; + $usedPercent = $diskTotal > 0 ? $diskUsed / $diskTotal * 100 : 0; + $diskState = $usedPercent >= SERVER_STATS_DISK_CRITICAL ? 'critical' : ($usedPercent >= SERVER_STATS_DISK_WARN ? 'warning' : 'ok'); + $diskOther = max(0, $diskUsed - $siteTotal); + + // ---- Traffic: Tageswerte, die letzten 30 Tage lueckenlos (ab dem ersten gezaehlten Tag) ---- $traffic = is_array($stats['traffic'] ?? null) ? $stats['traffic'] : []; - $docker = is_array($stats['docker'] ?? null) ? $stats['docker'] : []; - $buildCacheFree = 0; - foreach ($docker as $row) { - if ($row['type'] === 'Build Cache') { - $buildCacheFree = (int) $row['reclaimable']; + $trafficDays = is_array($traffic['days'] ?? null) ? $traffic['days'] : []; + $since = !empty($traffic['since']) ? (string) $traffic['since'] : null; + $today = date('Y-m-d'); + $chartDays = []; + for ($i = 29; $i >= 0; $i--) { + $date = date('Y-m-d', strtotime("-$i days")); + $row = $trafficDays[$date] ?? ['out' => 0, 'in' => 0, 'requests' => 0]; + $chartDays[$date] = $row + ['bytes' => (float) $row['out'] + (float) $row['in'], 'counted' => $since !== null && $date >= $since]; + } + $chartMax = server_stats_nice_max((float) max(array_column($chartDays, 'bytes'))); + $sumToday = server_stats_traffic_sum([$trafficDays[$today] ?? []]); + $sumYesterday = server_stats_traffic_sum([$trafficDays[date('Y-m-d', strtotime('-1 day'))] ?? []]); + $sumWeek = server_stats_traffic_sum(array_slice($chartDays, -7, null, true)); + $months = []; + foreach ($trafficDays as $date => $row) { + $key = substr((string) $date, 0, 7); + $months[$key] ??= ['out' => 0, 'in' => 0, 'requests' => 0]; + foreach (['out', 'in', 'requests'] as $field) { + $months[$key][$field] += (int) ($row[$field] ?? 0); } } + krsort($months); + $sumMonth = server_stats_traffic_sum([$months[date('Y-m')] ?? []]); ?> -

- Speicherplatz und Datenvolumen des ganzen Servers – - nicht nur der Website. Stand: Uhr, wird alle 15 Minuten aktualisiert. -

- -
Die Zahlen sind veraltet. - Das Sammelskript auf dem Server hat zuletzt geschrieben – läuft der Timer lumina-stats.timer noch?
- -

Speicherplatz

- -
- - % sind belegt, frei sind noch . - Ist die Platte voll, kann die Datenbank nicht mehr schreiben und die Website zeigt Fehler.
- -
-
- Frei - - von + +
+
+

Speicher & Traffic

+ Stand Uhr · alle 15 Minuten neu
-
- Belegt - - % des Speichers -
-
- Zuwachs in 7 Tagen - - – - Verlauf beginnt gerade erst - - = 0 ? '+' : '−') . e(format_bytes(abs($growthWeek))) ?> - = 0 ? '+' : '−') . e(format_bytes(abs($growthMonth))) : 'belegter Speicher' ?> - -
- -
- Reicht noch etwa - 730 ? 'über 2 Jahre' : e(number_format($daysLeft, 0, ',', '.')) . ' Tage' ?> - beim Tempo der letzten 7 Tage +

Was die Lumina-Website belegt und überträgt – Dateien, Datenbank und Datenvolumen.

+ +
Die Zahlen sind veraltet. + Das Sammelskript auf dem Server hat zuletzt geschrieben – läuft der Timer lumina-stats.timer noch?
+ + +
+ + % sind belegt, frei sind noch . + Ist die Platte voll, kann die Datenbank nicht mehr schreiben und die Website zeigt Fehler.
+ + +
+
+ +
+ Website belegt + + Dateien · Datenbank +
- -
- -
- belegt - frei +
+ +
+ Zuwachs in 7 Tagen + + – + Verlauf beginnt gerade erst + + + + +
+
+
+ +
+ Traffic heute + + Aufrufe +
+
+
+ +
+ Frei auf dem Server + + von · % belegt +
+
+
-

Wofür der Platz verbraucht wird

- - -
- - - - - - - - - - - - -
BereichAnteil als BalkenGrößeAnteil
-
- -

- Docker im Einzelnen: - e($dockerLabels[$row['type']] ?? (string) $row['type']) . ' ' . e(format_bytes($row['bytes'])), $docker)) ?> -

- = 10 * 1024 ** 3): ?> -
Vom Docker-Build-Cache lassen sich freigeben. - Er wächst mit jedem Docker-Build und wird nie von selbst geleert: docker builder prune -af
- - - - - -

Größte Verzeichnisse

-

Aufklappen zeigt die größten Unterverzeichnisse.

- -
- -
- - - - - - -
    - -
  • - - - -
  • - -
- -

Keine größeren Unterverzeichnisse.

+ +
+

Woraus die Website besteht

+

Dateien unter und die Datenbank – zusammen .

+
- +
- +
    + [$label, $color]): ?> + +
  • + + + + +
  • + +
+
- -

Lumina-Website

-

- Nur die Website selbst – ihre Dateien' . e((string) $site['path']) . ')' : '' ?> und ihre Datenbank. - Bots, Backups und alles andere auf dem Server zählen hier nicht mit. -

-
-
- Website gesamt - - des belegten Speichers + +
+
+

Hochgeladene Dateien

+ + +
    + +
  • +
    + + + +
    + +
  • + +
+ +

Noch nichts hochgeladen.

+
-
- Dateien - - Code, Bilder, Karten, Uploads -
-
- Datenbank - - Tabellen +
+

Datenbank

+ + +
    + +
  • +
    + + ca. Zeilen + +
    + +
  • + + +
  • +
    + Übrige Tabellen + +
    +
  • + +
+ +

Die Tabellengrößen lassen sich gerade nicht abfragen.

+
- -
Die Aufteilung der Dateien kommt mit dem nächsten Lauf des Sammelskripts (alle 15 Minuten).
- -

Dateien der Website

- -
- - - - - - - - - - - - -
ArtBalkenGrößeAnteil
-
- -

Hochgeladene Dateien nach Bereich

- -
- - - - - - - - - - - - -
BereichBalkenGrößeDateien
-
- - - -

Datenbank: größte Tabellen

- -
- - - - - - - - - - - - - - - - - - - - -
TabelleBalkenGrößeZeilen (ca.)
Übrige Tabellen
-
- -

Datenvolumen (Traffic)

- - -
Werte je Tag und Monat gibt es, sobald auf dem Server vnstat installiert ist – - bis dahin steht hier nur, was seit dem letzten Neustart übertragen wurde.
- -
- - - - -
- -

- - Seit dem letzten Neustart ( Uhr): - ↓ empfangen · ↑ gesendet. - - Gezählt wird alles, was über die Netzwerkkarte' . e((string) $traffic['interface']) . '' : '' ?> läuft – - Website, Bots und die anderen Dienste des Servers zusammen. -

- - -
+

Traffic der Website

+

+ Datenvolumen und Aufrufe von lumina-ascendens.de. + Der Server merkt sich dafür nur Zeitpunkt und Datenmenge jedes Aufrufs – keine IP-Adressen, keine Seiten.

- - -

Monate

- (float) $r['rx'] + (float) $r['tx'], $months)); ?> -
- - - - - - - - - - - - - - -
MonatBalkenEmpfangenGesendetGesamt
+ +
Noch nichts gezählt – die ersten Werte erscheinen mit dem nächsten Lauf des Sammelskripts.
+ +
+ $sumToday, 'Gestern' => $sumYesterday, 'Letzte 7 Tage' => $sumWeek, $monthNames[(int) date('n')] => $sumMonth] as $label => $sum): ?> +
+ + + Aufrufe +
+ +
+ +

Datenvolumen je Tag – letzte 30 Tage

+ + +
+ Als Tabelle anzeigen + 1): ?> +

Monate

+
+ + + + $row): ?> + + + + + + + + + +
MonatDatenvolumenGesendetEmpfangenAufrufe
+
+

Tage

+ +
+ + + + $row): ?> + + + + + + + + + + + +
TagDatenvolumenGesendetEmpfangenAufrufe
+
+
+ +
+ + +
+

Platz auf dem Server

+

Die Website teilt sich die Festplatte mit anderem – hier nur, wie viel davon noch frei ist.

+ - - -

Letzte Tage

- (float) $r['rx'] + (float) $r['tx'], $days)); ?> -
- - - - - - - - - - - - - - -
TagBalkenEmpfangenGesendetGesamt
-
- +
    +
  • Lumina-Website
  • +
  • Übriges auf dem Server
  • +
  • Frei
  • +
+
diff --git a/assets/css/style.css b/assets/css/style.css index c0ad889..87fd133 100644 --- a/assets/css/style.css +++ b/assets/css/style.css @@ -10652,55 +10652,96 @@ a.perm-member:hover { border-color: var(--gold); color: var(--gold); text-decora .sanctuary-state form { margin-left: 0; } } -/* ---- Server: Speicherplatz und Datenvolumen (admin/server.php, nur Entwickler und Administratoren) ---- */ +/* ---- Speicher & Traffic (admin/server.php, nur Entwickler und Administratoren) ---- */ .visually-hidden { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; } -.server-page h2 { display: flex; align-items: center; gap: 0.5rem; margin-top: 2rem; } -.server-page h2 .icon { color: var(--gold); } -.server-page h3 { margin: 1.75rem 0 0.5rem; font-size: 1.05rem; } -.server-page code { overflow-wrap: anywhere; } -.server-tiles { display: grid; grid-template-columns: repeat(auto-fit, minmax(190px, 1fr)); gap: 0.75rem; margin: 0.75rem 0 1rem; } -.server-tile { display: flex; flex-direction: column; gap: 0.15rem; padding: 0.85rem 1rem; border: 1px solid var(--border); border-radius: 8px; background: rgba(46, 46, 46, 0.55); min-width: 0; } -.server-tile-label { font-size: 0.8rem; color: var(--text-muted); } -.server-tile-value { font-size: 1.55rem; font-weight: 700; line-height: 1.2; font-variant-numeric: tabular-nums; } -.server-tile-hero .server-tile-value { font-size: 2rem; color: var(--gold); } -.server-tile-note { font-size: 0.8rem; color: var(--text-muted); } -/* Fuellstand des Speichers: eine Farbe; erst bei Warnung/kritisch die Statusfarbe - der Hinweis darueber sagt es auch in Worten */ -.server-meter { height: 14px; border-radius: 7px; background: rgba(255, 255, 255, 0.08); overflow: hidden; } -.server-meter-fill { display: block; height: 100%; border-radius: 7px 4px 4px 7px; background: #b08d24; } -.server-meter-warning .server-meter-fill { background: #e8912d; } -.server-meter-critical .server-meter-fill { background: var(--danger); } -.server-meter-legend { display: flex; justify-content: space-between; gap: 1rem; margin-top: 0.3rem; font-size: 0.85rem; } -.server-notice { display: flex; align-items: flex-start; gap: 0.6rem; margin: 0.75rem 0; padding: 0.6rem 0.9rem; border: 1px solid var(--border); border-radius: 8px; background: rgba(255, 255, 255, 0.04); } -.server-notice .icon { flex-shrink: 0; margin-top: 0.1rem; color: var(--text-muted); } -.server-notice-warning { border-color: rgba(232, 145, 45, 0.6); background: rgba(232, 145, 45, 0.12); } -.server-notice-warning .icon { color: #e8912d; } -.server-notice-critical { border-color: rgba(217, 83, 79, 0.6); background: rgba(217, 83, 79, 0.14); } -.server-notice-critical .icon { color: var(--danger); } -.server-table { width: 100%; } -.server-page .table-scroll table { min-width: 480px; } -.server-table td, .server-table th { vertical-align: middle; } -.server-col-num { text-align: right; white-space: nowrap; font-variant-numeric: tabular-nums; } -.server-table .server-col-bar { width: 40%; min-width: 140px; } -/* Balken: Groessen in einer Farbe, Datenvolumen in zwei (Empfangen/Gesendet) mit 2px Abstand dazwischen */ -.server-bar { display: flex; gap: 2px; height: 10px; width: 100%; min-width: 80px; border-radius: 3px; background: rgba(255, 255, 255, 0.06); overflow: hidden; } -.server-bar-fill { display: block; height: 100%; border-radius: 0 3px 3px 0; background: #b08d24; } -.server-bar-rx { display: block; height: 100%; background: #4f9bd9; } -.server-bar-tx { display: block; height: 100%; border-radius: 0 3px 3px 0; background: #b08d24; } -.server-legend { display: flex; flex-wrap: wrap; gap: 0.4rem 1.2rem; margin: 1.25rem 0 0; font-size: 0.85rem; color: var(--text-muted); } -.server-legend span { display: inline-flex; align-items: center; gap: 0.4rem; } -.server-swatch { width: 12px; height: 12px; border-radius: 3px; } -.server-docker { margin: 0.5rem 0 0; font-size: 0.88rem; } -.server-tree { display: flex; flex-direction: column; gap: 0.35rem; } -.server-dir { border: 1px solid var(--border); border-radius: 8px; background: rgba(46, 46, 46, 0.4); } -.server-dir summary, .server-dir li { display: grid; grid-template-columns: minmax(120px, 1fr) minmax(80px, 2fr) 5.5rem; align-items: center; gap: 0.75rem; } -.server-dir summary { padding: 0.55rem 0.9rem; cursor: pointer; list-style: none; } -.server-dir summary::-webkit-details-marker { display: none; } -.server-dir summary code::before { content: "▸"; display: inline-block; width: 1em; color: var(--text-muted); } -.server-dir[open] summary code::before { content: "▾"; } -.server-dir ul { list-style: none; margin: 0; padding: 0 0.9rem 0.6rem 1.9rem; display: flex; flex-direction: column; gap: 0.3rem; font-size: 0.9rem; } -.server-dir > p { margin: 0; padding: 0 0.9rem 0.6rem 1.9rem; font-size: 0.9rem; } +.st-page { display: grid; gap: 1rem; } +.st-page .panel { margin: 0; min-width: 0; } +.st-page h2 { display: flex; align-items: center; gap: 0.55rem; margin: 0 0 0.35rem; font-size: 1.15rem; } +.st-page h3 { margin: 1.5rem 0 0.6rem; font-size: 0.95rem; color: var(--text); } +.st-page h2 + .text-muted { margin-top: 0; } +.st-page code { overflow-wrap: anywhere; } +.st-title { display: flex; flex-wrap: wrap; align-items: baseline; justify-content: space-between; gap: 0.25rem 1rem; } +.st-title h1 { margin: 0; } +.st-stand { font-size: 0.85rem; } +.st-head > .text-muted { margin: 0.35rem 0 0; } +/* Kennzahlen: Symbol, Bezeichnung, grosse Zahl, Erlaeuterung */ +.st-kpis { display: grid; grid-template-columns: repeat(auto-fit, minmax(215px, 1fr)); gap: 0.75rem; margin-top: 1.25rem; } +.st-kpi { display: flex; align-items: flex-start; gap: 0.85rem; padding: 1rem 1.1rem; border: 1px solid var(--border); border-radius: 10px; background: rgba(46, 46, 46, 0.5); min-width: 0; } +.st-kpi-main { border-color: rgba(201, 162, 39, 0.55); background: linear-gradient(135deg, rgba(201, 162, 39, 0.16), rgba(46, 46, 46, 0.5) 65%); } +.st-kpi-icon { display: flex; align-items: center; justify-content: center; width: 40px; height: 40px; flex-shrink: 0; border-radius: 10px; background: rgba(201, 162, 39, 0.14); color: var(--gold); } +.st-kpi > div { display: flex; flex-direction: column; gap: 0.1rem; min-width: 0; } +.st-kpi-label { font-size: 0.8rem; color: var(--text-muted); } +.st-kpi-value { font-size: 1.7rem; font-weight: 700; line-height: 1.15; font-variant-numeric: tabular-nums; } +.st-kpi-empty { color: var(--text-muted); } +.st-kpi-note { font-size: 0.8rem; color: var(--text-muted); } +.st-notice { display: flex; align-items: flex-start; gap: 0.6rem; margin: 0.9rem 0 0; padding: 0.65rem 0.9rem; border: 1px solid var(--border); border-radius: 8px; background: rgba(255, 255, 255, 0.04); } +.st-notice .icon { flex-shrink: 0; margin-top: 0.1rem; color: var(--text-muted); } +.st-notice-warning { border-color: rgba(232, 145, 45, 0.6); background: rgba(232, 145, 45, 0.12); } +.st-notice-warning .icon { color: #e8912d; } +.st-notice-critical { border-color: rgba(217, 83, 79, 0.6); background: rgba(217, 83, 79, 0.14); } +.st-notice-critical .icon { color: var(--danger); } +/* Aufteilung: ein Balken aus Abschnitten (2px Abstand), darunter die Legende mit den Werten */ +.st-stack { display: flex; gap: 2px; height: 22px; margin: 1rem 0 0.9rem; border-radius: 6px; overflow: hidden; } +.st-seg { flex: 1 0 4px; min-width: 4px; transition: filter 0.15s ease; } +.st-seg:hover { filter: brightness(1.2); } +.st-dot { display: inline-block; width: 11px; height: 11px; border-radius: 3px; flex-shrink: 0; } +.st-legend { list-style: none; margin: 0; padding: 0; display: grid; grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); gap: 0.15rem 1.5rem; } +.st-legend li { display: flex; align-items: center; gap: 0.55rem; padding: 0.4rem 0; border-bottom: 1px solid rgba(255, 255, 255, 0.06); min-width: 0; } +.st-legend-name { flex: 1; min-width: 0; } +.st-legend-value { font-weight: 600; font-variant-numeric: tabular-nums; white-space: nowrap; } +.st-legend-share { width: 3.2rem; text-align: right; color: var(--text-muted); font-size: 0.85rem; font-variant-numeric: tabular-nums; white-space: nowrap; } +.st-legend-inline { display: flex; flex-wrap: wrap; gap: 0.3rem 1.75rem; } +.st-legend-inline li { border: 0; padding: 0.15rem 0; } +.st-legend-inline .st-legend-name { flex: none; color: var(--text-muted); } +/* Zwei Karten nebeneinander: Listen mit duennem Balken unter jeder Zeile */ +.st-two { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 380px), 1fr)); gap: 1rem; align-items: start; } +.st-rows { list-style: none; margin: 0.9rem 0 0; padding: 0; display: flex; flex-direction: column; gap: 0.7rem; } +.st-row-head { display: flex; align-items: baseline; gap: 0.6rem; margin-bottom: 0.3rem; } +.st-row-name { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.st-row-name code { font-size: 0.88rem; } +.st-row-meta { font-size: 0.8rem; color: var(--text-muted); white-space: nowrap; } +.st-row-value { min-width: 4.2rem; text-align: right; font-weight: 600; font-variant-numeric: tabular-nums; white-space: nowrap; } +.st-track { display: block; height: 6px; border-radius: 3px; background: rgba(255, 255, 255, 0.07); overflow: hidden; } +.st-fill { display: block; height: 100%; border-radius: 0 3px 3px 0; } +.st-row-rest { padding-top: 0.6rem; border-top: 1px solid rgba(255, 255, 255, 0.06); color: var(--text-muted); } +.st-row-rest .st-row-head { margin: 0; } +/* Traffic: kleine Kennzahlen und Saeulen je Tag (eine Farbe; heute blasser, der Tag laeuft noch) */ +.st-minis { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 0.75rem; margin-top: 1rem; } +.st-mini { display: flex; flex-direction: column; gap: 0.1rem; padding: 0.75rem 0.95rem; border: 1px solid var(--border); border-radius: 10px; background: rgba(46, 46, 46, 0.5); } +.st-mini-value { font-size: 1.3rem; font-weight: 700; font-variant-numeric: tabular-nums; } +.st-chart { position: relative; height: 230px; margin: 0.5rem 0 0; padding: 14px 0 26px 4.2rem; } +.st-grid { position: absolute; inset: 14px 0 26px 4.2rem; pointer-events: none; } +.st-grid span { position: absolute; left: 0; right: 0; border-top: 1px dashed rgba(255, 255, 255, 0.1); } +.st-grid span:last-child { border-top: 1px solid rgba(255, 255, 255, 0.22); } +.st-grid i { position: absolute; right: 100%; top: -0.55rem; padding-right: 0.6rem; font-style: normal; font-size: 0.72rem; color: var(--text-muted); white-space: nowrap; font-variant-numeric: tabular-nums; } +.st-cols { position: relative; display: flex; align-items: stretch; gap: 3px; height: 100%; } +.st-col { position: relative; flex: 1 1 0; min-width: 0; display: flex; align-items: flex-end; justify-content: center; border-radius: 4px 4px 0 0; outline: none; } +.st-col-bar { display: block; width: 100%; max-width: 26px; border-radius: 4px 4px 0 0; background: #3987e5; transition: filter 0.15s ease; } +.st-col.is-today .st-col-bar { opacity: 0.55; } +.st-col:hover, .st-col:focus { background: rgba(255, 255, 255, 0.06); } +.st-col:hover .st-col-bar, .st-col:focus .st-col-bar { filter: brightness(1.25); } +.st-col-label { position: absolute; top: 100%; left: 50%; transform: translateX(-50%); margin-top: 6px; font-size: 0.72rem; color: var(--text-muted); white-space: nowrap; } +.st-tip { position: absolute; bottom: calc(100% + 6px); left: 50%; transform: translateX(-50%); z-index: 5; display: none; padding: 0.4rem 0.65rem; border: 1px solid var(--border); border-radius: 6px; background: #1a1a1a; box-shadow: 0 6px 18px rgba(0, 0, 0, 0.45); font-size: 0.8rem; white-space: nowrap; pointer-events: none; } +.st-tip strong { display: block; } +.st-col:hover .st-tip, .st-col:focus .st-tip { display: block; } +.st-col:nth-child(-n+5) .st-tip { left: 0; transform: none; } +.st-col:nth-last-child(-n+5) .st-tip { left: auto; right: 0; transform: none; } +.st-details { margin-top: 1rem; } +.st-details summary { cursor: pointer; color: var(--gold); font-size: 0.9rem; } +.st-table { width: 100%; } +.st-page .table-scroll table { min-width: 460px; } +.st-num { text-align: right; white-space: nowrap; font-variant-numeric: tabular-nums; } +/* Platz auf dem Server: Website, Uebriges, frei */ +.st-capacity { display: flex; gap: 2px; height: 14px; margin: 1rem 0 0.75rem; border-radius: 7px; background: rgba(255, 255, 255, 0.08); overflow: hidden; } +.st-capacity span { display: block; height: 100%; min-width: 4px; } +.st-cap-site { background: #c9a227; } +.st-cap-other { background: #7b8089; } +.st-capacity-warning .st-cap-other { background: #e8912d; } +.st-capacity-critical .st-cap-other { background: var(--danger); } +.st-cap-free { background: rgba(255, 255, 255, 0.14); } @media (max-width: 600px) { - .server-dir summary, .server-dir li { grid-template-columns: minmax(0, 1fr) 5.5rem; } - .server-dir .server-bar { display: none; } - .server-table .server-col-bar { width: auto; min-width: 90px; } + .st-chart { height: 190px; padding-left: 3.4rem; } + .st-grid { left: 3.4rem; } + .st-cols { gap: 2px; } + .st-row-meta { display: none; } } diff --git a/config.example.php b/config.example.php index e758767..5e16789 100644 --- a/config.example.php +++ b/config.example.php @@ -36,18 +36,14 @@ return [ 'bot_callback' => [ 'key' => 'langer-zufaelliger-schluessel', ], - // Optional - Seite "Server" (admin/server.php, nur Entwickler und Administratoren): Speicherplatz und Datenvolumen. - // Die Zahlen sammelt includes/server_stats_collect.php als root auf dem Server (Einrichtung im Kopf der Datei). + // Optional - Seite "Speicher & Traffic" (admin/server.php, nur Entwickler und Administratoren): was die Website + // belegt und uebertraegt. Die Zahlen sammelt includes/server_stats_collect.php als root auf dem Server + // (Einrichtung im Kopf der Datei). // 'server_stats' => [ // // Wohin das Sammelskript schreibt und woher die Seite liest (Standard: /var/lib/lumina-stats/server.json) // 'file' => '/var/lib/lumina-stats/server.json', - // // Weitere Bereiche fuer "Wofuer der Platz verbraucht wird" - alles, was sonst unter "Sonstiges" faellt - // 'groups' => [ - // 'Discord-Bots' => ['/root/luminabot', '/root/sielbot'], - // 'Git-Server' => ['/opt/forgejo'], - // ], - // // Netzwerkkarte fuer das Datenvolumen (Standard: die der Standardroute) - // // 'interface' => 'eth0', + // // Protokoll von Caddy fuer das Datenvolumen (Standard: /var/log/caddy/lumina-traffic.log) + // 'traffic_log' => '/var/log/caddy/lumina-traffic.log', // ], 'discord' => [ 'client_id' => 'deine-discord-client-id', diff --git a/includes/functions.php b/includes/functions.php index 380045e..b927c50 100644 --- a/includes/functions.php +++ b/includes/functions.php @@ -189,9 +189,10 @@ function icon(string $name): string 'coins' => '', // Raidplaner: Aufstellung mit Figuren und Laufweg 'tactic' => '', - // Server (admin/server.php): zwei Einschuebe, Warnung, Datenvolumen (Pfeile hoch/runter) + // Speicher & Traffic (admin/server.php): Server, Warnung, Zuwachs, Datenvolumen (Pfeile hoch/runter) 'server' => '', 'alert' => '', + 'trend' => '', 'transfer' => '', ]; diff --git a/includes/header.php b/includes/header.php index 334af4e..a2c320e 100644 --- a/includes/header.php +++ b/includes/header.php @@ -43,7 +43,7 @@ $canViewAudit = $currentUser && user_has_permission('audit.view'); $canModerate = $currentUser && user_has_permission('comments.moderate'); // Daten zuruecksetzen (Testdaten loeschen) nur fuer Entwickler $canResetData = $currentUser && is_developer($currentUser) && role_preview() === null; -// Server: Speicherplatz und Datenvolumen (admin/server.php) nur fuer Entwickler und Administratoren +// Speicher & Traffic der Website (admin/server.php) nur fuer Entwickler und Administratoren require_once __DIR__ . '/server_stats.php'; $canViewServer = $currentUser && server_stats_can_view(); // Vorschau "Ansicht als Gruppe" (includes/permissions.php): Hinweis oben auf jeder Seite, mit Knopf zum Beenden @@ -478,8 +478,8 @@ $brandLogo = $isConsiliumOnly - class="sidebar-link" title="Server: Speicherplatz und Datenvolumen"> - Server + class="sidebar-link" title="Speicher & Traffic der Website"> + Speicher & Traffic diff --git a/includes/server_stats.php b/includes/server_stats.php index 83fce67..0b19c7b 100644 --- a/includes/server_stats.php +++ b/includes/server_stats.php @@ -2,16 +2,19 @@ declare(strict_types=1); /** - * Serverauslastung (admin/server.php): Speicherplatz und Datenvolumen des Servers, nur fuer Entwickler und - * Administratoren. + * 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 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. + * 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). */ @@ -51,10 +54,25 @@ function server_stats_load(): ?array return null; } $data = json_decode((string) file_get_contents($file), true); - return is_array($data) && isset($data['generated_at'], $data['disk']) ? $data : null; + // "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; } -/** Upload-Ordner (assets/uploads/) mit lesbarem Namen fuer die Uebersicht "Lumina-Website". */ +/** + * 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/) mit lesbarem Namen . */ const SERVER_STATS_UPLOAD_LABELS = [ 'profiles' => 'Bilder der Profilseiten', 'avatars' => 'Profilbilder (Avatare)', @@ -112,7 +130,7 @@ function format_share(float $part, float $whole): string } /** - * Zuwachs des belegten Speichers ueber die letzten $days Tage aus dem Tagesverlauf (disk.history: Datum => Bytes). + * 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 $history @@ -134,3 +152,48 @@ function server_stats_growth(array $history, int $days): ?float } 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 $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]; +} diff --git a/includes/server_stats_collect.php b/includes/server_stats_collect.php index a675753..f9124d2 100644 --- a/includes/server_stats_collect.php +++ b/includes/server_stats_collect.php @@ -2,35 +2,56 @@ 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. + * 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): - * 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). + * 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') { @@ -43,8 +64,8 @@ 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; +/** 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 @@ -53,142 +74,10 @@ function stats_run(string $command): string } /** - * Belegter Platz je Pfad in Bytes (du, ohne andere Dateisysteme). Pfade, die es nicht gibt, fehlen im Ergebnis. + * Die Dateien der Website nach Art und die Upload-Ordner im Einzelnen. Ein du-Aufruf ueber das ganze Verzeichnis, + * daraus die einzelnen Pfade. * - * @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; -} - -/** - * Nur die Lumina-Website: ihre Dateien nach Art und die Upload-Ordner im Einzelnen (die Datenbank fragt die Seite - * selbst ab). Ein du-Aufruf ueber das ganze Verzeichnis, daraus die einzelnen Pfade. - * - * @return array{path: string, total: int, parts: array, uploads: array} + * @return array{path: string, total: int, parts: array, uploads: array} */ function stats_site(string $site): array { @@ -203,14 +92,14 @@ function stats_site(string $site): array $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 = [ - ['label' => 'Hochgeladene Dateien', 'bytes' => $uploadsBytes], - ['label' => 'Karten-Daten (Kacheln und Markierungen)', 'bytes' => $mapData], - ['label' => 'Bilder, Stile und Skripte der Website', 'bytes' => max(0, $assets - $uploadsBytes - $mapData)], - ['label' => 'Git-Verlauf', 'bytes' => $git], - ['label' => 'Programmcode', 'bytes' => max(0, $total - $assets - $git)], + ['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)], ]; - usort($parts, static fn (array $a, array $b): int => $b['bytes'] <=> $a['bytes']); $uploads = []; $prefix = $site . '/assets/uploads/'; @@ -227,75 +116,132 @@ function stats_site(string $site): array 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 $previous Abschnitt traffic des letzten Laufs + * @return array{since: ?string, days: array, 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-.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 ---- -$df = preg_split('/\s+/', trim((string) (explode("\n", stats_run('df -B1 --output=size,used,avail /'))[1] ?? ''))) ?: []; +// ---- 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); -// ---- 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: Dateien und Datenbank ---- +$siteStats = stats_site($site); +$siteStats['db_bytes'] = stats_db_bytes($site); -// 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; +// ---- 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'), - 'hostname' => (string) gethostname(), - 'disk' => ['total' => $total, 'used' => $used, 'free' => $free, 'history' => $history], - 'groups' => $groups, - 'site' => stats_site($site), - 'tree' => stats_tree(), - 'docker' => stats_docker(), - 'traffic' => stats_traffic((string) ($config['interface'] ?? '')), + '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 ----