GNMON-001 M3.3+M3.4: GPU-Detailseite und Braille-Verlaufschart (Betreiberwahl)

M3.3: GPU-Seite mit Karten-Discovery (gn_gpu_up), Live-Werten je Karte,
AsciiBar/Spinner-Komponenten (Luefter-Spinner RPM-gekoppelt), Reconnect-
Dialog deutsch. M3.4: Vergleich von ASCII-Sparkline, Block-Chart,
ApexCharts und Braille-Chart — Betreiberentscheidung: Braille-Chart
(btop-Stil, 8-Punkt-Dots, Hoehengradient gruen/gelb/rot, Liniengrid).
ApexCharts samt Paket und CDN-Referenz entfernt. DejaVu Sans Mono wird
mitgeliefert (volle Braille-/Box-Drawing-Abdeckung). CPU-Livepfad:
Scrape 5s + rate[10s] + EMA-Glaettung statt Fenster-Mittelung. Sechs
Implementierungsbefunde in GNMON-000 dokumentiert (CSS-Isolation ::deep,
kulturinvariantes Parsing, Intra-Zellen-Dotreihenfolge, U+2800-Metrik,
Breitenmessung-Persistenz, statisches Layout bei per-page Render Mode).

Generated by Mistral Vibe.
Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
This commit is contained in:
2026-11-04 09:15:24 +01:00
parent da4ff05bf5
commit 297acd182f
16 changed files with 1005 additions and 29 deletions
@@ -96,6 +96,50 @@ Betreiberentscheidung 04.11.2026: Benachrichtigung per E-Mail.
- Offen bis M5: echter SMTP-Versand gegen den Betreiber-Mailserver
(Operator-Schritt: secrets-Datei + Testmail).
### M3: Blazor-Dashboard (implementiert 04.11.2026, Workstation)
M3.1–M3.4 in kleinen visuell abnehmbaren Schritten umgesetzt
(Betreiberwunsch 04.11.2026):
- **M3.1 GUI-Gerüst** (.NET 10, Interactive Server): Layout/Nav im
Hacker-TUI-Stil, Catppuccin-Mocha-Palette, Monospace, ASCII-Button-Navi
mit invers-grünem Aktivzustand; Bootstrap restlos entfernt.
- **M3.2 Live-Ressourcen:** CPU/RAM/Disk-Kacheln mit ASCII-Progressbars
(Schwellenfarben passend zu den vmalert-Severities) im 2-s-Takt;
VictoriaMetricsClient (PromQL, kulturinvariantes Parsing).
- **M3.3 GPU-Detailseite:** Karten-Discovery über `gn_gpu_up`,
Live-Util/VRAM/Temp/Power/Lüfter je Karte; ASCII-Spinner-Komponente
(dots/braille/line, Lüfter-Spinner mit RPM-gekoppelter Rotation);
Reconnect-Dialog deutsch lokalisiert.
- **M3.4 Verläufe — Betreiberentscheidung: Braille-Chart** (btop-Stil).
Vergleichsvarianten ASCII-Sparkline, div-Block-Chart und ApexCharts
wurden bewertet und entfernt (ApexCharts-Paket inkl. CDN-Referenz
raus; null JS-Chart-Abhängigkeiten). Die `AsciiBrailleChart`-Komponente:
8-Punkt-Braille (2×4 Dots je Zeichen), vertikaler Farbgradient grün
(unten) → gelb → rot (oben), Liniengrid hinter der Grafik
(Betreiberentscheidung gegen Punkte- und Strichgrid), Breite per
JS-Messung von Containerbreite und echter Zeichenbreite
(Range-API, Font-Fallback-tolerant), Proben linear interpoliert.
- **Schrift:** DejaVu Sans Mono wird mit der Website ausgeliefert
(wwwroot/fonts, Bitstream-Vera-Lizenz beigelegt) — vollständige
Braille- und Box-Drawing-Abdeckung, deterministische Metriken.
- **Live-Verzögerung CPU:** statt Fenster-Mittelung läuft die Kette
Scrape 5 s (vorher 10 s) → `rate[10s]` roh → EMA-Glättung (α 0,65) im
Dashboard; Reaktion auf Lastsprünge < 10 s statt Minuten.
- **Fallendokumente (Implementierungsbefunde):**
- Blazor-CSS-Isolation greift nicht auf NavLink-Kindkomponenten;
Nav-Styles laufen über `::deep` (sonst stiller Regelverlust).
- `double.TryParse` von PromQL-Strings ist kulturabhängig: de-DE liest
den Punkt als Gruppentrenner; Parsing invariant.
- Braille-Dot-Füllung muss je Zeichen bottom-up erfolgen (Intra-Zellen-
Inversion macht Kurvenkanten verkehrt herum).
- Leere Chart-Zellen als U+2800 statt Leerzeichen: sonst driftet die
Zeile bei Font-Fallback (abweichende Vorschübe).
- Gemessene Containerbreite muss über Daten-Refresh persistiert
werden (Reset pro Update lies die Grafik zusammenschrumpfen).
- Per-page Render Mode hält das Layout statisch: Layout-Spinner nur
als CSS-Animation, Komponenten-Animation nur in Seiteninhalten.
## Noch offen
1. Punkte 1–6 aus GNMON-001 v2.0 Abschnitt 9 (Metrics-Account-Identität,
@@ -105,8 +149,7 @@ Betreiberentscheidung 04.11.2026: Benachrichtigung per E-Mail.
keinen Schwellwert-Alarm (Motivation des Vorfalls). Vorschlag:
`vmalert`-Regeln gegen VictoriaMetrics mit Notification-Kanal; Kanal-
Auswahl (Mail/ntfy/Matrix) ist eine Betreiberentscheidung.
3. M3 (Blazor-Dashboard) auf der Workstation; Journald-Ingestion nach
Laptop-Neustart verifizieren (M2-Operator-Schritt).
4. M5 Server-Rollout auf `ghostnet-ki` nach Behebung des GPU0-Kühldefekts
(GNAI-010 10.10): System-Scope-Rollen, Konten 983/984, nftables,
Abnahmekriterien aus GNMON-001 Abschnitt 10.
3. M5 Server-Rollout auf `ghostnet-ki` nach Behebung des GPU0-Kühldefekts
(GNAI-010 10.10): System-Scope-Rollen, Konten 983/984, nftables,
Abnahmekriterien aus GNMON-001 Abschnitt 10, Dashboard-Container
(Containerfile, Digest-Pin, OIDC/Keycloak, NPM-Ingress).
@@ -16,7 +16,7 @@ gnmon_victoria_metrics_data_dir: "{{ gnmon_victoria_metrics_user_home }}/.local/
gnmon_victoria_metrics_port: 8428
gnmon_victoria_metrics_retention_days: 60
gnmon_victoria_metrics_scrape_interval_seconds: 10
gnmon_victoria_metrics_scrape_interval_seconds: 5
# node_exporter target (same host; NetworkMode=host in the quadlet).
gnmon_victoria_metrics_node_target: "127.0.0.1:9100"
@@ -10,6 +10,7 @@
<link rel="stylesheet" href="@Assets["Ghostnet.Dashboard.styles.css"]" />
<ImportMap />
<link rel="icon" type="image/png" href="favicon.png" />
<script src="@Assets["js/gnmon-utils.js"]"></script>
<HeadOutlet />
</head>
@@ -0,0 +1,191 @@
@* btop-style braille chart: 2x4 dot cells per character, vertical color
gradient (green -> yellow -> red), one span per text row (cheap DOM).
The dot grid is interpolated to the measured container width so the
chart always spans the full panel. *@
@inject IJSRuntime JS
<div class="braille-chart @($"braille-grid-{GridStyle}")" @ref="_container" style="font-size: @(RowPx)px; line-height: @(RowPx)px">
@for (var r = 0; r < _rowStrings.Count; r++)
{
<span @ref="_rowSpans" style="color: @(_rowColors[r])">@_rowStrings[r]</span>
}
</div>
@code
{
/// <summary>Sample values in display order (oldest first).</summary>
[Parameter]
public IReadOnlyList<double>? Values { get; set; }
/// <summary>Number of text rows (4 dot levels each).</summary>
[Parameter]
public int Rows { get; set; } = 22;
/// <summary>Total pixel height of the chart.</summary>
[Parameter]
public int HeightPx { get; set; } = 220;
/// <summary>
/// Absolute scale maximum (e.g. 100 for percent metrics).
/// When null, the chart auto-scales to the window maximum.
/// </summary>
[Parameter]
public double? Max { get; set; }
/// <summary>Background grid style: lines (default), dots or none.</summary>
[Parameter]
public string GridStyle { get; set; } = "lines";
/// <summary>Fallback dot columns when the container width is unknown
/// (prerendering); replaced by the measured width after the first
/// interactive render.</summary>
[Parameter]
public int WidthDots { get; set; } = 160;
private ElementReference _container;
private ElementReference _rowSpans;
private List<string> _rowStrings = [];
private List<string> _rowColors = [];
private int _charCols = 40;
private bool _widthMeasured;
private int RowPx => Math.Max(6, HeightPx / Rows);
protected override void OnParametersSet()
{
// Only fall back before the first measurement; later data refreshes
// must keep the measured width (the reset shrank the chart back to
// half width every 10-second update).
if (!_widthMeasured)
{
_charCols = Math.Max(10, WidthDots / 2);
}
BuildRows();
}
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (!firstRender)
{
return;
}
try
{
// Measure the real container width AND the real per-glyph
// advance (font fallbacks can render braille wider than the
// 0.6em monospace default; fixed ratios under-filled panels).
var width = await JS.InvokeAsync<int>("gnmon.clientWidth", _container);
var advance = await JS.InvokeAsync<double>("gnmon.charAdvance", _rowSpans);
if (width > 0 && advance > 0)
{
_charCols = Math.Max(10, (int)(width / advance));
_widthMeasured = true;
BuildRows();
StateHasChanged();
}
}
catch (JSDisconnectedException)
{
// Circuit already gone; next render retries.
}
catch (InvalidOperationException)
{
}
}
private void BuildRows()
{
_rowStrings = [];
_rowColors = [];
var dotsHigh = Rows * 4;
var dotCols = _charCols * 2;
// Interpolate samples onto the dot grid (btop-style full-width).
var grid = new double[dotCols];
if (Values is not { Count: > 1 })
{
if (Values is { Count: 1 })
{
Array.Fill(grid, Values[0]);
}
}
else
{
for (var d = 0; d < dotCols; d++)
{
var t = dotCols == 1
? 0
: d / (double)(dotCols - 1) * (Values.Count - 1);
var i0 = (int)Math.Floor(t);
var i1 = Math.Min(i0 + 1, Values.Count - 1);
var frac = t - i0;
grid[d] = Values[i0] * (1 - frac) + Values[i1] * frac;
}
}
var max = Max;
if (max is null or 0)
{
max = Math.Max(grid.DefaultIfEmpty(1).Max(), 1e-9);
}
for (var visualRow = 0; visualRow < Rows; visualRow++)
{
_rowColors.Add(GradientColor(visualRow));
var row = new char[_charCols];
var charRowFromBottom = Rows - 1 - visualRow;
for (var cx = 0; cx < _charCols; cx++)
{
var pattern = 0;
for (var dx = 0; dx < 2; dx++)
{
var column = grid[cx * 2 + dx];
if (column <= 0 && charRowFromBottom > 0)
{
continue;
}
var heightDots = (int)Math.Clamp(column / max.Value * dotsHigh, 0, dotsHigh);
for (var k = 0; k < 4; k++)
{
// k=0 is the LOWEST dot of the cell: the fill grows
// bottom-up inside every character (inversion bug
// found 04.11.2026).
var dotLevel = charRowFromBottom * 4 + k + 1;
if (heightDots < dotLevel)
{
continue;
}
var cellRow = 3 - k; // cell row 0 = top of the glyph
pattern |= dx == 0
? (cellRow < 3 ? 1 << cellRow : 1 << 6)
: (cellRow < 3 ? 1 << (cellRow + 3) : 1 << 7);
}
}
// U+2800 for empty cells: uniform braille metrics per row
// (mixed space/braille fallback fonts shift bars).
row[cx] = pattern == 0 ? '\u2800' : (char)(0x2800 + pattern);
}
_rowStrings.Add(new string(row));
}
}
/// <summary>Green (bottom) -> yellow -> red (top), Catppuccin tones.</summary>
private string GradientColor(int visualRow)
{
var t = Rows <= 1 ? 1 : (Rows - visualRow) / (double)(Rows - 1);
return t <= 0.5
? Lerp(0xa6, 0xe3, 0xa1, 0xf9, 0xe2, 0xaf, t / 0.5)
: Lerp(0xf9, 0xe2, 0xaf, 0xf3, 0x8b, 0xa8, (t - 0.5) / 0.5);
}
private static string Lerp(int r1, int g1, int b1, int r2, int g2, int b2, double t)
{
var r = (int)Math.Round(r1 + (r2 - r1) * t);
var g = (int)Math.Round(g1 + (g2 - g1) * t);
var b = (int)Math.Round(b1 + (b2 - b1) * t);
return $"rgb({r},{g},{b})";
}
}
@@ -15,8 +15,8 @@
</section>
<footer class="statusline">
<span class="status-ok">● ONLINE</span>
Quelle: VictoriaMetrics · Loki · Alertmanager &mdash; M3.1a ASCII-Nav
<span class="status-ok"><span class="ascii-spin-css ascii-spin-green" aria-hidden="true"></span> LIVE</span>
Quelle: VictoriaMetrics · Loki · Alertmanager &mdash; M3.3 GPU-Detail
<span class="cursor">▮</span>
</footer>
</main>
@@ -7,22 +7,22 @@
<div></div>
</div>
<p class="components-reconnect-first-attempt-visible">
Rejoining the server...
Verbindung wird wiederhergestellt ...
</p>
<p class="components-reconnect-repeated-attempt-visible">
Rejoin failed... trying again in <span id="components-seconds-to-next-attempt"></span> seconds.
Wiederherstellung fehlgeschlagen ... neuer Versuch in <span id="components-seconds-to-next-attempt"></span> Sekunden.
</p>
<p class="components-reconnect-failed-visible">
Failed to rejoin.<br />Please retry or reload the page.
Wiederherstellung fehlgeschlagen.<br />Bitte erneut versuchen oder die Seite neu laden.
</p>
<button id="components-reconnect-button" class="components-reconnect-failed-visible">
Retry
</button>
<p class="components-pause-visible">
The session has been paused by the server.
Die Sitzung wurde vom Server pausiert.
</p>
<p class="components-resume-failed-visible">
Failed to resume the session.<br />Please retry or reload the page.
Sitzung konnte nicht fortgesetzt werden.<br />Bitte erneut versuchen oder die Seite neu laden.
</p>
<button id="components-resume-button" class="components-pause-visible components-resume-failed-visible">
Resume
@@ -1,25 +1,198 @@
@page "/gpus"
@rendermode InteractiveServer
@using Ghostnet.Dashboard.Services
@inject VictoriaMetricsClient Vm
@implements IDisposable
<PageTitle>GPUs - Ghostnet.AI Monitoring</PageTitle>
<h1>GPUs</h1>
<p class="hint">Detailansicht je Karte — Live-Werte folgen in M3.3.</p>
<p class="hint">Detailansicht je Karte — Live-Werte aus dem amdgpu-Textfile-Collector (2-s-Takt).</p>
@if (_error is not null)
{
<div class="note">VictoriaMetrics nicht erreichbar: @_error</div>
}
else if (!_loaded)
{
<div class="note"><Spinner Style="dots" Color="mauve" IntervalMs="90" /> Lade GPU-Metriken &hellip;</div>
}
@if (_cards.Count == 0 && _loaded)
{
<div class="note">Keine AMD-GPUs in VictoriaMetrics sichtbar — Collector oder Metrikpfad prüfen.</div>
}
<div class="tile-grid">
@for (var card = 0; card < 2; card++)
@foreach (var card in _cards)
{
<div class="panel">
<div class="panel-header">GPU @card</div>
<div class="panel-header">GPU @card.Id &middot; @card.Model</div>
<div class="value-grid">
<span class="tile-label">Auslastung</span><span class="val">-- %</span>
<span class="tile-label">VRAM</span><span class="val">-- / -- GB</span>
<span class="tile-label">Edge / Junction</span><span class="val">-- / -- °C</span>
<span class="tile-label">Leistung</span><span class="val">-- W</span>
<span class="tile-label">Auslastung</span><span class="val">@Val(card.Util, "%")</span>
<span class="tile-label">VRAM</span><span class="val">@Val(card.VramUsed, "GB") / @Val(card.VramTotal, "GB")</span>
<span class="tile-label">Edge / Junction</span><span class="val">@Temp(card.Edge) / @Temp(card.Junction)</span>
<span class="tile-label">Leistung</span><span class="val">@Val(card.Power, " W")</span>
</div>
<div class="bar-block">
<span class="tile-label">Util</span>
<AsciiBar Value="card.Util" />
</div>
<div class="bar-block">
<span class="tile-label">VRAM</span>
<AsciiBar Value="card.VramPct" />
</div>
<div class="panel-footer-line">
Lüfter: -- RPM (PWM -- %) &middot; Verläufe folgen mit M3.4
@if (card.FanRpm is > 0)
{
<Spinner Style="line" RatePerMinute="card.FanRpm" Color="teal" />
}
Lüfter: @Val(card.FanRpm, " RPM") (PWM @Val(card.FanPwm, " %"))
&middot; @MissingHint(card)
</div>
</div>
}
</div>
@code
{
private sealed class GpuCard
{
public required string Id { get; init; }
public required string Model { get; init; }
public double? Util;
public double? VramUsed;
public double? VramTotal;
public double? VramPct;
public double? Edge;
public double? Junction;
public double? Power;
public double? FanRpm;
public double? FanPwm;
}
private CancellationTokenSource? _cts;
private bool _loaded;
private string? _error;
private List<GpuCard> _cards = [];
protected override void OnInitialized()
{
_cts = new CancellationTokenSource();
_ = RunLoopAsync(_cts.Token);
}
private async Task RunLoopAsync(CancellationToken ct)
{
using var timer = new PeriodicTimer(TimeSpan.FromSeconds(2));
try
{
while (!ct.IsCancellationRequested)
{
await LoadAsync(ct);
await InvokeAsync(StateHasChanged);
if (!await timer.WaitForNextTickAsync(ct))
{
break;
}
}
}
catch (OperationCanceledException)
{
}
catch (InvalidOperationException)
{
}
}
private async Task LoadAsync(CancellationToken ct)
{
try
{
var up = await Vm.QuerySeriesAsync("gn_gpu_up", ct);
if (up.Count == 0)
{
_cards = [];
_error = null;
_loaded = true;
return;
}
var utilTask = Vm.QuerySeriesAsync("gn_gpu_utilization_percent", ct);
var vramUsedTask = Vm.QuerySeriesAsync("gn_gpu_vram_used_bytes", ct);
var vramTotalTask = Vm.QuerySeriesAsync("gn_gpu_vram_total_bytes", ct);
var edgeTask = Vm.QuerySeriesAsync("gn_gpu_edge_temp_celsius", ct);
var junctionTask = Vm.QuerySeriesAsync("gn_gpu_junction_temp_celsius", ct);
var powerTask = Vm.QuerySeriesAsync("gn_gpu_power_watts", ct);
var fanTask = Vm.QuerySeriesAsync("gn_gpu_fan_rpm", ct);
var pwmTask = Vm.QuerySeriesAsync("gn_gpu_fan_pwm_percent", ct);
await Task.WhenAll(utilTask, vramUsedTask, vramTotalTask, edgeTask,
junctionTask, powerTask, fanTask, pwmTask);
var util = utilTask.Result;
var vramUsed = vramUsedTask.Result;
var vramTotal = vramTotalTask.Result;
var edge = edgeTask.Result;
var junction = junctionTask.Result;
var power = powerTask.Result;
var fan = fanTask.Result;
var pwm = pwmTask.Result;
var cards = up
.OrderBy(s => s.Labels.TryGetValue("card", out var id) ? id : "")
.Select(s => new GpuCard
{
Id = s.Labels.GetValueOrDefault("card", "?"),
Model = s.Labels.GetValueOrDefault("gpu", "unknown"),
})
.ToList();
foreach (var card in cards)
{
card.Util = Lookup(util, card.Id);
card.VramUsed = Lookup(vramUsed, card.Id);
card.VramTotal = Lookup(vramTotal, card.Id);
card.VramPct = card.VramUsed is not null && card.VramTotal > 0
? card.VramUsed / card.VramTotal * 100.0
: null;
card.Edge = Lookup(edge, card.Id);
card.Junction = Lookup(junction, card.Id);
card.Power = Lookup(power, card.Id);
card.FanRpm = Lookup(fan, card.Id);
card.FanPwm = Lookup(pwm, card.Id);
}
_cards = cards;
_error = null;
_loaded = true;
}
catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException)
{
_error = ex.Message;
}
}
private static double? Lookup(IReadOnlyList<VictoriaMetricsClient.SeriesResult> series, string card)
=> series.FirstOrDefault(s => s.Labels.GetValueOrDefault("card") == card)?.Value;
private static string Val(double? value, string unit)
=> value is null ? "--" : unit switch
{
"%" => $"{value:F0} %",
"GB" => $"{value / 1024 / 1024 / 1024:F1} GB",
" W" => $"{value:F1} W",
" RPM" => $"{value:F0} RPM",
" %" => $"{value:F0} %",
_ => value.ToString() ?? "--",
};
private static string Temp(double? celsius)
=> celsius is null ? "--" : $"{celsius:F0} °C";
private static string MissingHint(GpuCard card)
=> card.Junction is null && card.FanRpm is null
? "Junction/Lüfter vom APU-Collector nicht geliefert"
: "Quelle: sysfs (amdgpu)";
public void Dispose() => _cts?.Cancel();
}
@@ -14,7 +14,7 @@
<span class="tile-label">CPU</span>
<span class="tile-value">@Pct(_cpu)</span>
<AsciiBar Value="_cpu" />
<span class="tile-sub">Auslastung gesamt (2-min-Rate)</span>
<span class="tile-sub">Auslastung gesamt (10-s-Rate, gleitend)</span>
</div>
<div class="tile">
<span class="tile-label">Arbeitsspeicher</span>
@@ -34,15 +34,44 @@
{
<div class="note">VictoriaMetrics nicht erreichbar: @_error</div>
}
else if (_loaded)
else if (!_loaded)
{
<div class="note"><Spinner Style="dots" Color="mauve" IntervalMs="90" /> Lade VictoriaMetrics-Daten &hellip;</div>
}
else
{
<div class="note note-accent">Datenquelle aktiv: node_exporter &rarr; VictoriaMetrics (Scrape 10 s).</div>
}
<h2 class="section-title">Verläufe &middot; CPU 1 h</h2>
@if (_cpuHistory.Count > 0)
{
<div class="tile-grid">
<div class="panel">
<div class="panel-header">CPU-Auslastung (auto-skaliert auf Fenstermaximum)</div>
<ErrorBoundary>
<AsciiBrailleChart Values="_cpuHistoryValues" HeightPx="220" />
</ErrorBoundary>
<div class="panel-footer-line">
min @F0(_cpuHistoryMin) % &middot; avg @F0(_cpuHistoryAvg) % &middot; max @F0(_cpuHistoryMax) %
&middot; 60 min, 30-s-Schritt &middot; Aktualisierung alle 10 s
</div>
</div>
</div>
}
else
{
<div class="note"><Spinner Style="dots" Color="mauve" IntervalMs="90" /> Sammle Verlaufsdaten &hellip;</div>
}
@code
{
// Short window for a near-instant counter rate; display smoothing
// happens client-side with an EMA (no window lag).
private const string CpuQuery =
"(1 - avg(rate(node_cpu_seconds_total{mode=\"idle\"}[2m]))) * 100";
"(1 - avg(rate(node_cpu_seconds_total{mode=\"idle\"}[10s]))) * 100";
private const double CpuEmaAlpha = 0.65;
private const string RamUsedQuery =
"node_memory_MemTotal_bytes - node_memory_MemAvailable_bytes";
private const string RamTotalQuery = "node_memory_MemTotal_bytes";
@@ -66,6 +95,14 @@ else if (_loaded)
private double? _diskUsedBytes;
private double? _diskTotalBytes;
private List<VictoriaMetricsClient.RangePoint> _cpuHistory = [];
private double _cpuHistoryMin;
private double _cpuHistoryAvg;
private double _cpuHistoryMax;
private int _tick;
private IReadOnlyList<double> _cpuHistoryValues = [];
protected override void OnInitialized()
{
_cts = new CancellationTokenSource();
@@ -79,7 +116,21 @@ else if (_loaded)
{
while (!ct.IsCancellationRequested)
{
await LoadAsync(ct);
try
{
await LoadAsync(ct);
_tick++;
if (_tick % 5 == 0)
{
await LoadHistoryAsync(ct);
}
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
// Never let a data error kill the circuit: surface it.
_error = $"{ex.GetType().Name}: {ex.Message}";
Console.Error.WriteLine($"[Home] {ex}");
}
await InvokeAsync(StateHasChanged);
if (!await timer.WaitForNextTickAsync(ct))
{
@@ -97,6 +148,20 @@ else if (_loaded)
}
}
private async Task LoadHistoryAsync(CancellationToken ct)
{
var end = DateTimeOffset.Now;
var start = end.AddMinutes(-60);
_cpuHistory = [.. await Vm.QueryRangeAsync(CpuQuery, start, end, TimeSpan.FromSeconds(30), ct)];
_cpuHistoryValues = [.. _cpuHistory.Select(p => p.Value)];
if (_cpuHistory.Count > 0)
{
_cpuHistoryMin = _cpuHistoryValues.Min();
_cpuHistoryMax = _cpuHistoryValues.Max();
_cpuHistoryAvg = _cpuHistoryValues.Average();
}
}
private async Task LoadAsync(CancellationToken ct)
{
try
@@ -112,7 +177,9 @@ else if (_loaded)
DiskPctQuery,
], ct);
_cpu = values[0];
_cpu = values[0] is { } rawCpu
? _loaded ? CpuEmaAlpha * rawCpu + (1 - CpuEmaAlpha) * (_cpu ?? rawCpu) : rawCpu
: null;
_ramUsedBytes = values[1];
_ramTotalBytes = values[2];
_ramPct = values[3];
@@ -131,6 +198,8 @@ else if (_loaded)
private static string Pct(double? value)
=> value is null ? "-- %" : $"{value:F0} %";
private static string F0(double value) => $"{value:F0}";
private static string GB(double? bytes)
=> bytes is null ? "--" : $"{bytes / 1024 / 1024 / 1024:F1} GB";
@@ -0,0 +1,74 @@
@* ASCII spinner (dots / braille / line) for TUI-style activity
indication. With RatePerMinute (e.g. fan RPM) the full rotation
follows the rate, clamped to a visible speed. Frames after
ascii-magic.com website-loaders (braille/dots) plus a rotating
line for fan visualisation. *@
<span class="@CssClass" aria-hidden="true">@_frames[_index]</span>
@code
{
private static readonly Dictionary<string, string[]> FrameSets = new()
{
["dots"] = ["⠁", "⠂", "⠄", "⡀", "⢀", "⠠", "⠐", "⠈"],
["braille"] = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"],
["line"] = ["─", "╲", "│", "╱"],
};
/// <summary>Frame set: dots, braille or line.</summary>
[Parameter]
public string Style { get; set; } = "braille";
/// <summary>Frame interval in milliseconds (ignored when RatePerMinute is set).</summary>
[Parameter]
public int IntervalMs { get; set; } = 120;
/// <summary>
/// Rotation rate per minute (e.g. fan RPM): one full frame cycle
/// follows the rate, clamped to 40-400 ms per frame to stay visible.
/// </summary>
[Parameter]
public double? RatePerMinute { get; set; }
/// <summary>Accent color: green (default), teal, mauve or yellow.</summary>
[Parameter]
public string Color { get; set; } = "green";
private string[] _frames = FrameSets["braille"];
private int _index;
private CancellationTokenSource? _cts;
private string CssClass => $"ascii-spin ascii-spin-{Color}";
protected override void OnInitialized()
{
_frames = FrameSets.GetValueOrDefault(Style, FrameSets["braille"]);
_cts = new CancellationTokenSource();
_ = RunAsync(_cts.Token);
}
private async Task RunAsync(CancellationToken ct)
{
while (!ct.IsCancellationRequested)
{
var delay = IntervalMs;
if (RatePerMinute is > 0 and { } rate)
{
var rotationMs = 60000.0 / rate;
delay = (int)Math.Clamp(rotationMs / _frames.Length, 40, 400);
}
try
{
await Task.Delay(delay, ct);
}
catch (TaskCanceledException)
{
break;
}
_index = (_index + 1) % _frames.Length;
await InvokeAsync(StateHasChanged);
}
}
public void Dispose() => _cts?.Cancel();
}
@@ -51,4 +51,98 @@ public sealed class VictoriaMetricsClient
/// </summary>
public Task<double?[]> QueryAllAsync(IEnumerable<string> queries, CancellationToken ct)
=> Task.WhenAll(queries.Select(q => QueryAsync(q, ct)));
/// <summary>
/// One result series with its labels (e.g. card, gpu).
/// </summary>
public sealed record SeriesResult(IReadOnlyDictionary<string, string> Labels, double Value);
/// <summary>
/// One point of a query_range result.
/// </summary>
public sealed record RangePoint(DateTimeOffset Timestamp, double Value);
/// <summary>
/// Runs a range query (Prometheus query_range API) over the first
/// result series.
/// </summary>
public async Task<IReadOnlyList<RangePoint>> QueryRangeAsync(
string promql, DateTimeOffset start, DateTimeOffset end, TimeSpan step,
CancellationToken ct)
{
var url = string.Create(CultureInfo.InvariantCulture,
$"/api/v1/query_range?query={Uri.EscapeDataString(promql)}"
+ $"&start={start.ToUnixTimeSeconds()}&end={end.ToUnixTimeSeconds()}"
+ $"&step={(int)step.TotalSeconds}");
using var response = await _http.GetAsync(url, ct);
response.EnsureSuccessStatusCode();
using var doc = await response.Content.ReadFromJsonAsync<JsonDocument>(ct);
var points = new List<RangePoint>();
if (doc is null)
{
return points;
}
var result = doc.RootElement
.GetProperty("data")
.GetProperty("result");
if (result.ValueKind != JsonValueKind.Array || result.GetArrayLength() == 0)
{
return points;
}
foreach (var point in result[0].GetProperty("values").EnumerateArray())
{
var raw = point[1].GetString();
if (!double.TryParse(raw, NumberStyles.Float,
CultureInfo.InvariantCulture, out var value))
{
continue;
}
points.Add(new RangePoint(
DateTimeOffset.FromUnixTimeSeconds(point[0].GetInt64()), value));
}
return points;
}
/// <summary>
/// Runs an instant query and returns every result series with its
/// label set (multi-card GPU metrics).
/// </summary>
public async Task<IReadOnlyList<SeriesResult>> QuerySeriesAsync(
string promql, CancellationToken ct)
{
using var response = await _http.GetAsync(
$"/api/v1/query?query={Uri.EscapeDataString(promql)}", ct);
response.EnsureSuccessStatusCode();
using var doc = await response.Content.ReadFromJsonAsync<JsonDocument>(ct);
var results = new List<SeriesResult>();
if (doc is null)
{
return results;
}
var result = doc.RootElement
.GetProperty("data")
.GetProperty("result");
if (result.ValueKind != JsonValueKind.Array)
{
return results;
}
foreach (var item in result.EnumerateArray())
{
var raw = item.GetProperty("value")[1].GetString();
if (!double.TryParse(raw, NumberStyles.Float,
CultureInfo.InvariantCulture, out var value))
{
continue;
}
var labels = new Dictionary<string, string>();
foreach (var label in item.GetProperty("metric").EnumerateObject())
{
labels[label.Name] = label.Value.GetString() ?? "";
}
results.Add(new SeriesResult(labels, value));
}
return results;
}
}
@@ -2,7 +2,8 @@
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
"Microsoft.AspNetCore": "Warning",
"System.Net.Http.HttpClient.VictoriaMetricsClient": "Warning"
}
}
}
@@ -26,13 +26,31 @@
--lavender: #b4befe;
}
/* Self-hosted DejaVu Sans Mono: complete braille (U+2800 block) and
box-drawing coverage, deterministic metrics on every client.
License: see fonts/DejaVu-LICENSE (Bitstream Vera / public domain). */
@font-face {
font-family: "DejaVu Sans Mono";
src: url("fonts/DejaVuSansMono.ttf") format("truetype");
font-weight: 400;
font-style: normal;
font-display: swap;
}
@font-face {
font-family: "DejaVu Sans Mono";
src: url("fonts/DejaVuSansMono-Bold.ttf") format("truetype");
font-weight: 700;
font-style: normal;
font-display: swap;
}
html, body {
margin: 0;
padding: 0;
background: var(--base);
color: var(--text);
font-family: ui-monospace, "JetBrains Mono", "FiraCode Nerd Font Mono",
"Cascadia Code", "Cousine", "DejaVu Sans Mono", monospace;
font-family: "DejaVu Sans Mono", ui-monospace, "JetBrains Mono", monospace;
font-size: 15px;
line-height: 1.45;
}
@@ -156,6 +174,105 @@ a {
color: var(--surface1);
}
/* ---- ascii sparkline ---- */
/* ---- braille chart (btop style) ---- */
.braille-chart {
font-family: "DejaVu Sans Mono", monospace;
letter-spacing: 0.02em;
overflow: hidden;
white-space: nowrap;
}
.braille-chart span {
display: block;
}
/* Grid variants behind the graph (coarser than the data resolution). */
.braille-grid-dots {
background-image: radial-gradient(circle, var(--surface0) 1px, transparent 1.5px);
background-size: 88px 44px;
background-position: left bottom;
}
.braille-grid-lines {
background-image:
repeating-linear-gradient(to bottom, var(--surface0) 0 1px, transparent 1px 44px),
repeating-linear-gradient(to right, var(--surface0) 0 1px, transparent 1px 88px);
background-position: left bottom;
}
.braille-grid-none {
background-image: none;
}
.section-title {
font-size: 0.95rem;
font-weight: 700;
letter-spacing: 0.06em;
text-transform: uppercase;
color: var(--sky);
margin: 1.6rem 0 0.9rem 0;
}
.section-title::before {
content: "── ";
color: var(--surface2);
}
/* ---- ascii spinners ---- */
.ascii-spin {
display: inline-block;
min-width: 1.1em;
text-align: center;
}
/* CSS-only braille spinner for the static layout (per-page render modes
keep MainLayout non-interactive; components there cannot animate). */
.ascii-spin-css {
display: inline-block;
min-width: 1.1em;
text-align: center;
}
.ascii-spin-css::before {
content: "⠋";
animation: ascii-spin-braille 0.9s steps(1) infinite;
}
@keyframes ascii-spin-braille {
0% { content: "⠋"; }
10% { content: "⠙"; }
20% { content: "⠹"; }
30% { content: "⠸"; }
40% { content: "⠼"; }
50% { content: "⠴"; }
60% { content: "⠦"; }
70% { content: "⠧"; }
80% { content: "⠇"; }
90% { content: "⠏"; }
}
.ascii-spin-green {
color: var(--green);
text-shadow: 0 0 8px rgba(166, 227, 161, 0.35);
}
.ascii-spin-teal {
color: var(--teal);
text-shadow: 0 0 8px rgba(148, 226, 213, 0.35);
}
.ascii-spin-mauve {
color: var(--mauve);
text-shadow: 0 0 8px rgba(203, 166, 247, 0.35);
}
.ascii-spin-yellow {
color: var(--yellow);
text-shadow: 0 0 8px rgba(249, 226, 175, 0.35);
}
/* ---- value grids (GPU cards) ---- */
.value-grid {
display: grid;
@@ -182,6 +299,15 @@ a {
padding-top: 0.45rem;
}
.bar-block {
margin-top: 0.6rem;
}
.bar-block .tile-label {
display: block;
margin-bottom: 0.2rem;
}
/* ---- notes, alerts, badges ---- */
.note {
border: 1px dashed var(--surface1);
@@ -0,0 +1,187 @@
Fonts are (c) Bitstream (see below). DejaVu changes are in public domain.
Glyphs imported from Arev fonts are (c) Tavmjong Bah (see below)
Bitstream Vera Fonts Copyright
------------------------------
Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved. Bitstream Vera is
a trademark of Bitstream, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of the fonts accompanying this license ("Fonts") and associated
documentation files (the "Font Software"), to reproduce and distribute the
Font Software, including without limitation the rights to use, copy, merge,
publish, distribute, and/or sell copies of the Font Software, and to permit
persons to whom the Font Software is furnished to do so, subject to the
following conditions:
The above copyright and trademark notices and this permission notice shall
be included in all copies of one or more of the Font Software typefaces.
The Font Software may be modified, altered, or added to, and in particular
the designs of glyphs or characters in the Fonts may be modified and
additional glyphs or characters may be added to the Fonts, only if the fonts
are renamed to names not containing either the words "Bitstream" or the word
"Vera".
This License becomes null and void to the extent applicable to Fonts or Font
Software that has been modified and is distributed under the "Bitstream
Vera" names.
The Font Software may be sold as part of a larger software package but no
copy of one or more of the Font Software typefaces may be sold by itself.
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT,
TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL BITSTREAM OR THE GNOME
FOUNDATION BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING
ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE
FONT SOFTWARE.
Except as contained in this notice, the names of Gnome, the Gnome
Foundation, and Bitstream Inc., shall not be used in advertising or
otherwise to promote the sale, use or other dealings in this Font Software
without prior written authorization from the Gnome Foundation or Bitstream
Inc., respectively. For further information, contact: fonts at gnome dot
org.
Arev Fonts Copyright
------------------------------
Copyright (c) 2006 by Tavmjong Bah. All Rights Reserved.
Permission is hereby granted, free of charge, to any person obtaining
a copy of the fonts accompanying this license ("Fonts") and
associated documentation files (the "Font Software"), to reproduce
and distribute the modifications to the Bitstream Vera Font Software,
including without limitation the rights to use, copy, merge, publish,
distribute, and/or sell copies of the Font Software, and to permit
persons to whom the Font Software is furnished to do so, subject to
the following conditions:
The above copyright and trademark notices and this permission notice
shall be included in all copies of one or more of the Font Software
typefaces.
The Font Software may be modified, altered, or added to, and in
particular the designs of glyphs or characters in the Fonts may be
modified and additional glyphs or characters may be added to the
Fonts, only if the fonts are renamed to names not containing either
the words "Tavmjong Bah" or the word "Arev".
This License becomes null and void to the extent applicable to Fonts
or Font Software that has been modified and is distributed under the
"Tavmjong Bah Arev" names.
The Font Software may be sold as part of a larger software package but
no copy of one or more of the Font Software typefaces may be sold by
itself.
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL
TAVMJONG BAH BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
Except as contained in this notice, the name of Tavmjong Bah shall not
be used in advertising or otherwise to promote the sale, use or other
dealings in this Font Software without prior written authorization
from Tavmjong Bah. For further information, contact: tavmjong @ free
. fr.
TeX Gyre DJV Math
-----------------
Fonts are (c) Bitstream (see below). DejaVu changes are in public domain.
Math extensions done by B. Jackowski, P. Strzelczyk and P. Pianowski
(on behalf of TeX users groups) are in public domain.
Letters imported from Euler Fraktur from AMSfonts are (c) American
Mathematical Society (see below).
Bitstream Vera Fonts Copyright
Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved. Bitstream Vera
is a trademark of Bitstream, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of the fonts accompanying this license (“Fonts”) and associated
documentation
files (the “Font Software”), to reproduce and distribute the Font Software,
including without limitation the rights to use, copy, merge, publish,
distribute,
and/or sell copies of the Font Software, and to permit persons to whom
the Font Software is furnished to do so, subject to the following
conditions:
The above copyright and trademark notices and this permission notice
shall be
included in all copies of one or more of the Font Software typefaces.
The Font Software may be modified, altered, or added to, and in particular
the designs of glyphs or characters in the Fonts may be modified and
additional
glyphs or characters may be added to the Fonts, only if the fonts are
renamed
to names not containing either the words “Bitstream” or the word “Vera”.
This License becomes null and void to the extent applicable to Fonts or
Font Software
that has been modified and is distributed under the “Bitstream Vera”
names.
The Font Software may be sold as part of a larger software package but
no copy
of one or more of the Font Software typefaces may be sold by itself.
THE FONT SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT,
TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL BITSTREAM OR THE GNOME
FOUNDATION
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL,
SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN
ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR
INABILITY TO USE
THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE.
Except as contained in this notice, the names of GNOME, the GNOME
Foundation,
and Bitstream Inc., shall not be used in advertising or otherwise to promote
the sale, use or other dealings in this Font Software without prior written
authorization from the GNOME Foundation or Bitstream Inc., respectively.
For further information, contact: fonts at gnome dot org.
AMSFonts (v. 2.2) copyright
The PostScript Type 1 implementation of the AMSFonts produced by and
previously distributed by Blue Sky Research and Y&Y, Inc. are now freely
available for general use. This has been accomplished through the
cooperation
of a consortium of scientific publishers with Blue Sky Research and Y&Y.
Members of this consortium include:
Elsevier Science IBM Corporation Society for Industrial and Applied
Mathematics (SIAM) Springer-Verlag American Mathematical Society (AMS)
In order to assure the authenticity of these fonts, copyright will be
held by
the American Mathematical Society. This is not meant to restrict in any way
the legitimate use of the fonts, such as (but not limited to) electronic
distribution of documents containing these fonts, inclusion of these fonts
into other public domain or commercial font collections or computer
applications, use of the outline data to create derivative fonts and/or
faces, etc. However, the AMS does require that the AMS copyright notice be
removed from any derivative versions of the fonts which have been altered in
any way. In addition, to ensure the fidelity of TeX documents using Computer
Modern fonts, Professor Donald Knuth, creator of the Computer Modern faces,
has requested that any alterations which yield different font metrics be
given a different name.
$Id$
@@ -0,0 +1,17 @@
// GNMON dashboard JS helpers (TUI charts).
window.gnmon = {
clientWidth: (element) => element ? element.clientWidth : 0,
// Exact per-glyph advance of a rendered monospace text row
// (includes letter-spacing and any font fallback metrics).
charAdvance: (span) => {
if (!span) {
return 0;
}
const range = document.createRange();
range.selectNodeContents(span);
const rect = range.getBoundingClientRect();
const chars = span.textContent ? span.textContent.length : 0;
return chars > 0 && rect.width > 0 ? rect.width / chars : 0;
},
};