GNMON-001 M3.2: Live-Ressourcen aus VictoriaMetrics + ASCII-Bars

VictoriaMetricsClient (PromQL instant-query, 5s-Timeout), Home-Seite mit
2-s-Live-Takt: CPU (2-min-Rate), RAM und Root-Disk belegt/total/Prozent,
parallel abgefragt. AsciiBar-Komponente (18 Zeichen, Schwellenfarben
gruen/gelb/rot passend zu den vmalert-Severities). Fallendokument:
double.TryParse der PromQL-Strings lief kulturabhaengig — de-DE liest
den Punkt als Gruppentrenner (9.71 -> 9713020833333342); Parsing jetzt
invariant (NumberStyles.Float + InvariantCulture).

Generated by Mistral Vibe.
Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
This commit is contained in:
2026-11-04 07:19:46 +01:00
parent f518ebe97c
commit da4ff05bf5
6 changed files with 257 additions and 11 deletions
@@ -0,0 +1,40 @@
@* ASCII progress bar (TUI style, Catppuccin Mocha). Reusable across
pages; thresholds mirror the alert severities (warning 80, critical 90). *@
<span class="ascii-bar">
<span class="@FillClass">@FilledRun</span><span class="bar-empty">@EmptyRun</span>
</span>
@code
{
/// <summary>Percent value in 0..100; null renders an empty bar.</summary>
[Parameter]
public double? Value { get; set; }
/// <summary>Bar width in characters.</summary>
[Parameter]
public int Width { get; set; } = 18;
private string FilledRun => new('█', Filled);
private string EmptyRun => new('░', Width - Filled);
private int Filled
{
get
{
if (Value is not { } v)
{
return 0;
}
var filled = (int)Math.Round(Math.Clamp(v, 0, 100) / 100.0 * Width);
return Math.Clamp(filled, 0, Width);
}
}
private string FillClass => (Value ?? 0) switch
{
>= 90 => "bar-fill bar-fill-critical",
>= 80 => "bar-fill bar-fill-warning",
_ => "bar-fill",
};
}
@@ -1,29 +1,138 @@
@page "/"
@rendermode InteractiveServer
@using Ghostnet.Dashboard.Services
@inject VictoriaMetricsClient Vm
@implements IDisposable
<PageTitle>Ressourcen - Ghostnet.AI Monitoring</PageTitle>
<h1>Ressourcen</h1>
<p class="hint">Host-Übersicht — Live-Werte folgen in M3.2 (VictoriaMetrics-Anbindung).</p>
<p class="hint">Host-Übersicht — Live-Werte aus VictoriaMetrics (2-s-Takt).</p>
<div class="tile-grid">
<div class="tile">
<span class="tile-label">CPU</span>
<span class="tile-value">-- %</span>
<span class="tile-sub">Auslastung gesamt</span>
<span class="tile-value">@Pct(_cpu)</span>
<AsciiBar Value="_cpu" />
<span class="tile-sub">Auslastung gesamt (2-min-Rate)</span>
</div>
<div class="tile">
<span class="tile-label">Arbeitsspeicher</span>
<span class="tile-value">-- GB</span>
<span class="tile-sub">-- von -- GB belegt</span>
<span class="tile-value">@Pct(_ramPct)</span>
<AsciiBar Value="_ramPct" />
<span class="tile-sub">@GB(_ramUsedBytes) von @GB(_ramTotalBytes) belegt</span>
</div>
<div class="tile">
<span class="tile-label">Dateisystem (Root)</span>
<span class="tile-value">-- %</span>
<span class="tile-sub">-- von -- GB belegt</span>
<span class="tile-value">@Pct(_diskPct)</span>
<AsciiBar Value="_diskPct" />
<span class="tile-sub">@GB(_diskUsedBytes) von @GB(_diskTotalBytes) belegt</span>
</div>
</div>
<div class="note">
GPU-Kurzübersicht und Verläufe (1 h / 24 h / 7 d) folgen mit M3.4.
</div>
@if (_error is not null)
{
<div class="note">VictoriaMetrics nicht erreichbar: @_error</div>
}
else if (_loaded)
{
<div class="note note-accent">Datenquelle aktiv: node_exporter &rarr; VictoriaMetrics (Scrape 10 s).</div>
}
@code
{
private const string CpuQuery =
"(1 - avg(rate(node_cpu_seconds_total{mode=\"idle\"}[2m]))) * 100";
private const string RamUsedQuery =
"node_memory_MemTotal_bytes - node_memory_MemAvailable_bytes";
private const string RamTotalQuery = "node_memory_MemTotal_bytes";
private const string DiskUsedQuery =
"node_filesystem_size_bytes{mountpoint=\"/\"} - node_filesystem_avail_bytes{mountpoint=\"/\"}";
private const string DiskTotalQuery = "node_filesystem_size_bytes{mountpoint=\"/\"}";
private const string DiskPctQuery =
"100 - (node_filesystem_avail_bytes{mountpoint=\"/\"} / node_filesystem_size_bytes{mountpoint=\"/\"}) * 100";
private const string RamPctQuery =
"100 - (node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes) * 100";
private CancellationTokenSource? _cts;
private bool _loaded;
private string? _error;
private double? _cpu;
private double? _ramPct;
private double? _ramUsedBytes;
private double? _ramTotalBytes;
private double? _diskPct;
private double? _diskUsedBytes;
private double? _diskTotalBytes;
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)
{
// Circuit disposed; nothing to do.
}
catch (InvalidOperationException)
{
// Renderer already gone (e.g. tab closed mid-update).
}
}
private async Task LoadAsync(CancellationToken ct)
{
try
{
var values = await Vm.QueryAllAsync(
[
CpuQuery,
RamUsedQuery,
RamTotalQuery,
RamPctQuery,
DiskUsedQuery,
DiskTotalQuery,
DiskPctQuery,
], ct);
_cpu = values[0];
_ramUsedBytes = values[1];
_ramTotalBytes = values[2];
_ramPct = values[3];
_diskUsedBytes = values[4];
_diskTotalBytes = values[5];
_diskPct = values[6];
_error = null;
_loaded = true;
}
catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException)
{
_error = ex.Message;
}
}
private static string Pct(double? value)
=> value is null ? "-- %" : $"{value:F0} %";
private static string GB(double? bytes)
=> bytes is null ? "--" : $"{bytes / 1024 / 1024 / 1024:F1} GB";
public void Dispose() => _cts?.Cancel();
}
@@ -1,4 +1,5 @@
using Ghostnet.Dashboard.Components;
using Ghostnet.Dashboard.Services;
var builder = WebApplication.CreateBuilder(args);
@@ -6,6 +7,15 @@ var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRazorComponents()
.AddInteractiveServerComponents();
// Monitoring endpoints (GNMON-001 sections 4-7); host-local in the
// workstation development phase, quadlet-internal on the server.
builder.Services.AddHttpClient<VictoriaMetricsClient>(client =>
{
client.BaseAddress = new Uri(
builder.Configuration["Monitoring:VictoriaMetrics"] ?? "http://127.0.0.1:8428");
client.Timeout = TimeSpan.FromSeconds(5);
});
var app = builder.Build();
// Configure the HTTP request pipeline.
@@ -0,0 +1,54 @@
using System.Globalization;
using System.Net.Http.Json;
using System.Text.Json;
namespace Ghostnet.Dashboard.Services;
/// <summary>
/// Minimal PromQL client for the VictoriaMetrics instant-query API
/// (GNMON-001 section 4: /api/v1/query, Prometheus-compatible).
/// </summary>
public sealed class VictoriaMetricsClient
{
private readonly HttpClient _http;
public VictoriaMetricsClient(HttpClient http) => _http = http;
/// <summary>
/// Runs an instant query and returns the scalar value of the first
/// result series, or null when the query returns no series.
/// </summary>
public async Task<double?> QueryAsync(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);
if (doc is null)
{
return null;
}
var result = doc.RootElement
.GetProperty("data")
.GetProperty("result");
if (result.ValueKind != JsonValueKind.Array || result.GetArrayLength() == 0)
{
return null;
}
var value = result[0].GetProperty("value")[1].GetString();
// PromQL values are dot-decimal JSON strings; parsing must never
// depend on the host culture (de-DE would read "." as a group
// separator and turn 9.71 into 9713020833333342).
return double.TryParse(value, NumberStyles.Float,
CultureInfo.InvariantCulture, out var parsed)
? parsed
: null;
}
/// <summary>
/// Runs several instant queries in parallel (cadence-friendly).
/// </summary>
public Task<double?[]> QueryAllAsync(IEnumerable<string> queries, CancellationToken ct)
=> Task.WhenAll(queries.Select(q => QueryAsync(q, ct)));
}
@@ -5,5 +5,10 @@
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
"AllowedHosts": "*",
"Monitoring": {
"VictoriaMetrics": "http://127.0.0.1:8428",
"Loki": "http://127.0.0.1:3100",
"Alertmanager": "http://127.0.0.1:9093"
}
}
@@ -128,6 +128,34 @@ a {
font-size: 0.78rem;
}
/* ---- ascii progress bar ---- */
.ascii-bar {
display: block;
font-size: 0.82rem;
letter-spacing: 0.02em;
line-height: 1.2;
white-space: nowrap;
}
.bar-fill {
color: var(--green);
text-shadow: 0 0 6px rgba(166, 227, 161, 0.3);
}
.bar-fill-warning {
color: var(--yellow);
text-shadow: 0 0 6px rgba(249, 226, 175, 0.3);
}
.bar-fill-critical {
color: var(--red);
text-shadow: 0 0 6px rgba(243, 139, 168, 0.3);
}
.bar-empty {
color: var(--surface1);
}
/* ---- value grids (GPU cards) ---- */
.value-grid {
display: grid;