497 lines
15 KiB
Rust
497 lines
15 KiB
Rust
//! Metriken im Speicher und ihre Ausgabe im Prometheus-Textformat
|
|
//! (`GET /gateway/v1/metrics`).
|
|
//!
|
|
//! Gezählt wird nur, was keine Inhalte verrät: Anzahl, Dauer, Tokens, Status.
|
|
//! Als Label dient der Name eines **registrierten** Modells; unbekannte, vom
|
|
//! Client erfundene Namen laufen unter `unbekannt`, damit die Zahl der Reihen
|
|
//! begrenzt bleibt.
|
|
|
|
use std::collections::BTreeMap;
|
|
use std::fmt::Write;
|
|
use std::sync::Mutex;
|
|
|
|
/// Obergrenzen der Zeit-Verteilungen in Sekunden.
|
|
const BUCKETS: [f64; 12] = [
|
|
0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0, 30.0, 60.0, 120.0, 300.0,
|
|
];
|
|
|
|
#[derive(Debug, Clone, Default)]
|
|
struct Histogram {
|
|
counts: [u64; BUCKETS.len()],
|
|
sum: f64,
|
|
count: u64,
|
|
}
|
|
|
|
impl Histogram {
|
|
fn observe(&mut self, seconds: f64) {
|
|
for (i, upper) in BUCKETS.iter().enumerate() {
|
|
if seconds <= *upper {
|
|
self.counts[i] += 1;
|
|
}
|
|
}
|
|
self.sum += seconds;
|
|
self.count += 1;
|
|
}
|
|
}
|
|
|
|
/// Eine laufende Instanz mit gemessenem Verbrauch.
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
pub struct InstanceSample {
|
|
pub model: String,
|
|
pub engine: String,
|
|
pub instance_id: u64,
|
|
pub vram_mb: Option<u64>,
|
|
pub ram_mb: Option<u64>,
|
|
}
|
|
|
|
/// Gesamtwerte einer GPU (aus `nvidia-smi`).
|
|
#[derive(Debug, Clone, PartialEq)]
|
|
pub struct GpuSample {
|
|
pub index: u32,
|
|
pub memory_used_mb: u64,
|
|
pub memory_total_mb: u64,
|
|
pub utilization_percent: Option<u32>,
|
|
pub temperature_c: Option<u32>,
|
|
}
|
|
|
|
#[derive(Default)]
|
|
struct Inner {
|
|
/// (Modell, Status) -> Anzahl
|
|
requests: BTreeMap<(String, u16), u64>,
|
|
aborted: BTreeMap<String, u64>,
|
|
tokens_in: BTreeMap<String, u64>,
|
|
tokens_out: BTreeMap<String, u64>,
|
|
duration: BTreeMap<String, Histogram>,
|
|
/// (Modell, Engine) -> Ladezeiten
|
|
load: BTreeMap<(String, String), Histogram>,
|
|
start_failures: BTreeMap<String, u64>,
|
|
instance_losses: BTreeMap<String, u64>,
|
|
instances: Vec<InstanceSample>,
|
|
gpus: Vec<GpuSample>,
|
|
}
|
|
|
|
#[derive(Default)]
|
|
pub struct Metrics {
|
|
inner: Mutex<Inner>,
|
|
}
|
|
|
|
impl Metrics {
|
|
fn lock(&self) -> std::sync::MutexGuard<'_, Inner> {
|
|
self.inner.lock().unwrap_or_else(|e| e.into_inner())
|
|
}
|
|
|
|
/// Eine abgeschlossene Anfrage. `model` ist ein registrierter Name oder `-`.
|
|
pub fn record_request(
|
|
&self,
|
|
model: &str,
|
|
status: u16,
|
|
duration_ms: u64,
|
|
tokens_in: Option<u64>,
|
|
tokens_out: Option<u64>,
|
|
aborted: bool,
|
|
) {
|
|
let mut m = self.lock();
|
|
*m.requests.entry((model.to_string(), status)).or_default() += 1;
|
|
m.duration
|
|
.entry(model.to_string())
|
|
.or_default()
|
|
.observe(duration_ms as f64 / 1000.0);
|
|
if let Some(n) = tokens_in {
|
|
*m.tokens_in.entry(model.to_string()).or_default() += n;
|
|
}
|
|
if let Some(n) = tokens_out {
|
|
*m.tokens_out.entry(model.to_string()).or_default() += n;
|
|
}
|
|
if aborted {
|
|
*m.aborted.entry(model.to_string()).or_default() += 1;
|
|
}
|
|
}
|
|
|
|
pub fn record_load(&self, model: &str, engine: &str, duration_ms: u64) {
|
|
self.lock()
|
|
.load
|
|
.entry((model.to_string(), engine.to_string()))
|
|
.or_default()
|
|
.observe(duration_ms as f64 / 1000.0);
|
|
}
|
|
|
|
pub fn record_start_failure(&self, model: &str) {
|
|
*self
|
|
.lock()
|
|
.start_failures
|
|
.entry(model.to_string())
|
|
.or_default() += 1;
|
|
}
|
|
|
|
/// Eine Instanz verschwand von selbst (Absturz oder von außen beendet).
|
|
pub fn record_instance_loss(&self, model: &str) {
|
|
*self
|
|
.lock()
|
|
.instance_losses
|
|
.entry(model.to_string())
|
|
.or_default() += 1;
|
|
}
|
|
|
|
/// Ersetzt die Messwerte der laufenden Instanzen.
|
|
pub fn set_instances(&self, instances: Vec<InstanceSample>) {
|
|
self.lock().instances = instances;
|
|
}
|
|
|
|
/// Ersetzt die GPU-Werte.
|
|
pub fn set_gpus(&self, gpus: Vec<GpuSample>) {
|
|
self.lock().gpus = gpus;
|
|
}
|
|
|
|
/// Ausgabe im Prometheus-Textformat.
|
|
pub fn render(&self) -> String {
|
|
let m = self.lock();
|
|
let mut out = String::new();
|
|
|
|
header(
|
|
&mut out,
|
|
"nexus_up",
|
|
"gauge",
|
|
"Das Gateway läuft (immer 1).",
|
|
);
|
|
let _ = writeln!(out, "nexus_up 1");
|
|
header(
|
|
&mut out,
|
|
"nexus_build_info",
|
|
"gauge",
|
|
"Version des Gateways.",
|
|
);
|
|
let _ = writeln!(
|
|
out,
|
|
"nexus_build_info{{version=\"{}\"}} 1",
|
|
nexus_core::VERSION
|
|
);
|
|
|
|
header(
|
|
&mut out,
|
|
"nexus_requests_total",
|
|
"counter",
|
|
"Abgeschlossene Anfragen nach Modell und HTTP-Status.",
|
|
);
|
|
for ((model, status), n) in &m.requests {
|
|
let _ = writeln!(
|
|
out,
|
|
"nexus_requests_total{{model=\"{}\",status=\"{status}\"}} {n}",
|
|
esc(model)
|
|
);
|
|
}
|
|
header(
|
|
&mut out,
|
|
"nexus_requests_aborted_total",
|
|
"counter",
|
|
"Anfragen, deren Antwort nicht zu Ende geliefert wurde (Client getrennt).",
|
|
);
|
|
counter_by_model(&mut out, "nexus_requests_aborted_total", &m.aborted);
|
|
header(
|
|
&mut out,
|
|
"nexus_tokens_in_total",
|
|
"counter",
|
|
"Prompt-Tokens laut usage-Angabe der Engine.",
|
|
);
|
|
counter_by_model(&mut out, "nexus_tokens_in_total", &m.tokens_in);
|
|
header(
|
|
&mut out,
|
|
"nexus_tokens_out_total",
|
|
"counter",
|
|
"Erzeugte Tokens laut usage-Angabe der Engine.",
|
|
);
|
|
counter_by_model(&mut out, "nexus_tokens_out_total", &m.tokens_out);
|
|
|
|
header(
|
|
&mut out,
|
|
"nexus_request_duration_seconds",
|
|
"histogram",
|
|
"Gesamtdauer einer Anfrage bis zum Ende der Antwort.",
|
|
);
|
|
for (model, h) in &m.duration {
|
|
histogram(
|
|
&mut out,
|
|
"nexus_request_duration_seconds",
|
|
&format!("model=\"{}\"", esc(model)),
|
|
h,
|
|
);
|
|
}
|
|
header(
|
|
&mut out,
|
|
"nexus_model_load_seconds",
|
|
"histogram",
|
|
"Dauer des Modellstarts bis zur Bereitschaft.",
|
|
);
|
|
for ((model, engine), h) in &m.load {
|
|
histogram(
|
|
&mut out,
|
|
"nexus_model_load_seconds",
|
|
&format!("model=\"{}\",engine=\"{}\"", esc(model), esc(engine)),
|
|
h,
|
|
);
|
|
}
|
|
header(
|
|
&mut out,
|
|
"nexus_model_start_failures_total",
|
|
"counter",
|
|
"Fehlgeschlagene Modellstarts.",
|
|
);
|
|
counter_by_model(
|
|
&mut out,
|
|
"nexus_model_start_failures_total",
|
|
&m.start_failures,
|
|
);
|
|
header(
|
|
&mut out,
|
|
"nexus_instance_losses_total",
|
|
"counter",
|
|
"Instanzen, die von selbst verschwunden sind.",
|
|
);
|
|
counter_by_model(&mut out, "nexus_instance_losses_total", &m.instance_losses);
|
|
|
|
header(
|
|
&mut out,
|
|
"nexus_instances_loaded",
|
|
"gauge",
|
|
"Zahl der geladenen Instanzen.",
|
|
);
|
|
let _ = writeln!(out, "nexus_instances_loaded {}", m.instances.len());
|
|
header(
|
|
&mut out,
|
|
"nexus_instance_vram_megabytes",
|
|
"gauge",
|
|
"Gemessener VRAM einer Instanz.",
|
|
);
|
|
for i in &m.instances {
|
|
if let Some(v) = i.vram_mb {
|
|
let _ = writeln!(
|
|
out,
|
|
"nexus_instance_vram_megabytes{{{}}} {v}",
|
|
inst_labels(i)
|
|
);
|
|
}
|
|
}
|
|
header(
|
|
&mut out,
|
|
"nexus_instance_ram_megabytes",
|
|
"gauge",
|
|
"Gemessener Arbeitsspeicher einer Instanz (resident).",
|
|
);
|
|
for i in &m.instances {
|
|
if let Some(v) = i.ram_mb {
|
|
let _ = writeln!(
|
|
out,
|
|
"nexus_instance_ram_megabytes{{{}}} {v}",
|
|
inst_labels(i)
|
|
);
|
|
}
|
|
}
|
|
|
|
header(
|
|
&mut out,
|
|
"nexus_gpu_memory_used_megabytes",
|
|
"gauge",
|
|
"Belegter GPU-Speicher laut nvidia-smi.",
|
|
);
|
|
for g in &m.gpus {
|
|
let _ = writeln!(
|
|
out,
|
|
"nexus_gpu_memory_used_megabytes{{gpu=\"{}\"}} {}",
|
|
g.index, g.memory_used_mb
|
|
);
|
|
}
|
|
header(
|
|
&mut out,
|
|
"nexus_gpu_memory_total_megabytes",
|
|
"gauge",
|
|
"Gesamter GPU-Speicher laut nvidia-smi.",
|
|
);
|
|
for g in &m.gpus {
|
|
let _ = writeln!(
|
|
out,
|
|
"nexus_gpu_memory_total_megabytes{{gpu=\"{}\"}} {}",
|
|
g.index, g.memory_total_mb
|
|
);
|
|
}
|
|
header(
|
|
&mut out,
|
|
"nexus_gpu_utilization_percent",
|
|
"gauge",
|
|
"Auslastung der GPU laut nvidia-smi.",
|
|
);
|
|
for g in &m.gpus {
|
|
if let Some(u) = g.utilization_percent {
|
|
let _ = writeln!(
|
|
out,
|
|
"nexus_gpu_utilization_percent{{gpu=\"{}\"}} {u}",
|
|
g.index
|
|
);
|
|
}
|
|
}
|
|
header(
|
|
&mut out,
|
|
"nexus_gpu_temperature_celsius",
|
|
"gauge",
|
|
"Temperatur der GPU laut nvidia-smi.",
|
|
);
|
|
for g in &m.gpus {
|
|
if let Some(t) = g.temperature_c {
|
|
let _ = writeln!(
|
|
out,
|
|
"nexus_gpu_temperature_celsius{{gpu=\"{}\"}} {t}",
|
|
g.index
|
|
);
|
|
}
|
|
}
|
|
out
|
|
}
|
|
}
|
|
|
|
fn header(out: &mut String, name: &str, kind: &str, help: &str) {
|
|
let _ = writeln!(out, "# HELP {name} {help}");
|
|
let _ = writeln!(out, "# TYPE {name} {kind}");
|
|
}
|
|
|
|
fn counter_by_model(out: &mut String, name: &str, values: &BTreeMap<String, u64>) {
|
|
for (model, n) in values {
|
|
let _ = writeln!(out, "{name}{{model=\"{}\"}} {n}", esc(model));
|
|
}
|
|
}
|
|
|
|
fn histogram(out: &mut String, name: &str, labels: &str, h: &Histogram) {
|
|
for (i, upper) in BUCKETS.iter().enumerate() {
|
|
let _ = writeln!(
|
|
out,
|
|
"{name}_bucket{{{labels},le=\"{upper}\"}} {}",
|
|
h.counts[i]
|
|
);
|
|
}
|
|
let _ = writeln!(out, "{name}_bucket{{{labels},le=\"+Inf\"}} {}", h.count);
|
|
let _ = writeln!(out, "{name}_sum{{{labels}}} {}", h.sum);
|
|
let _ = writeln!(out, "{name}_count{{{labels}}} {}", h.count);
|
|
}
|
|
|
|
fn inst_labels(i: &InstanceSample) -> String {
|
|
format!(
|
|
"model=\"{}\",engine=\"{}\",instance=\"{}\"",
|
|
esc(&i.model),
|
|
esc(&i.engine),
|
|
i.instance_id
|
|
)
|
|
}
|
|
|
|
/// Maskiert einen Label-Wert (Textformat: `\`, `"` und Zeilenumbruch).
|
|
fn esc(value: &str) -> String {
|
|
value
|
|
.replace('\\', "\\\\")
|
|
.replace('"', "\\\"")
|
|
.replace('\n', "\\n")
|
|
}
|
|
|
|
/// Liest die Ausgabe von `nvidia-smi --query-gpu=index,memory.used,memory.total,
|
|
/// utilization.gpu,temperature.gpu --format=csv,noheader,nounits`.
|
|
pub fn parse_gpus(output: &str) -> Vec<GpuSample> {
|
|
output
|
|
.lines()
|
|
.filter_map(|line| {
|
|
let f: Vec<&str> = line.split(',').map(str::trim).collect();
|
|
if f.len() < 3 {
|
|
return None;
|
|
}
|
|
Some(GpuSample {
|
|
index: f[0].parse().ok()?,
|
|
memory_used_mb: f[1].parse().ok()?,
|
|
memory_total_mb: f[2].parse().ok()?,
|
|
utilization_percent: f.get(3).and_then(|v| v.parse().ok()),
|
|
temperature_c: f.get(4).and_then(|v| v.parse().ok()),
|
|
})
|
|
})
|
|
.collect()
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn anfragen_tokens_und_verteilung_erscheinen_im_textformat() {
|
|
let m = Metrics::default();
|
|
m.record_request("bonsai", 200, 120, Some(10), Some(20), false);
|
|
m.record_request("bonsai", 200, 3000, Some(5), Some(7), true);
|
|
m.record_request("bonsai", 500, 10, None, None, false);
|
|
let text = m.render();
|
|
assert!(
|
|
text.contains("nexus_requests_total{model=\"bonsai\",status=\"200\"} 2"),
|
|
"{text}"
|
|
);
|
|
assert!(text.contains("nexus_requests_total{model=\"bonsai\",status=\"500\"} 1"));
|
|
assert!(text.contains("nexus_tokens_in_total{model=\"bonsai\"} 15"));
|
|
assert!(text.contains("nexus_tokens_out_total{model=\"bonsai\"} 27"));
|
|
assert!(text.contains("nexus_requests_aborted_total{model=\"bonsai\"} 1"));
|
|
// 120 ms und 10 ms liegen unter 0,25 s, 3 s nicht.
|
|
assert!(
|
|
text.contains("nexus_request_duration_seconds_bucket{model=\"bonsai\",le=\"0.25\"} 2")
|
|
);
|
|
assert!(
|
|
text.contains("nexus_request_duration_seconds_bucket{model=\"bonsai\",le=\"+Inf\"} 3")
|
|
);
|
|
assert!(text.contains("nexus_request_duration_seconds_count{model=\"bonsai\"} 3"));
|
|
}
|
|
|
|
#[test]
|
|
fn ladezeiten_fehlstarts_und_verluste_werden_gezaehlt() {
|
|
let m = Metrics::default();
|
|
m.record_load("glm", "maya", 70_000);
|
|
m.record_start_failure("glm");
|
|
m.record_instance_loss("glm");
|
|
let text = m.render();
|
|
assert!(text.contains(
|
|
"nexus_model_load_seconds_bucket{model=\"glm\",engine=\"maya\",le=\"60\"} 0"
|
|
));
|
|
assert!(text.contains(
|
|
"nexus_model_load_seconds_bucket{model=\"glm\",engine=\"maya\",le=\"120\"} 1"
|
|
));
|
|
assert!(text.contains("nexus_model_start_failures_total{model=\"glm\"} 1"));
|
|
assert!(text.contains("nexus_instance_losses_total{model=\"glm\"} 1"));
|
|
}
|
|
|
|
#[test]
|
|
fn instanzen_und_gpus_ersetzen_den_alten_stand() {
|
|
let m = Metrics::default();
|
|
m.set_instances(vec![InstanceSample {
|
|
model: "glm".to_string(),
|
|
engine: "maya".to_string(),
|
|
instance_id: 2,
|
|
vram_mb: Some(22_800),
|
|
ram_mb: None,
|
|
}]);
|
|
m.set_gpus(parse_gpus(
|
|
"0, 11415, 12288, 87, 61\n1, 11391, 12288, 90, 63\n",
|
|
));
|
|
let text = m.render();
|
|
assert!(text.contains("nexus_instances_loaded 1"));
|
|
assert!(text.contains(
|
|
"nexus_instance_vram_megabytes{model=\"glm\",engine=\"maya\",instance=\"2\"} 22800"
|
|
));
|
|
assert!(!text.contains("nexus_instance_ram_megabytes{"));
|
|
assert!(text.contains("nexus_gpu_memory_used_megabytes{gpu=\"1\"} 11391"));
|
|
assert!(text.contains("nexus_gpu_temperature_celsius{gpu=\"0\"} 61"));
|
|
m.set_instances(Vec::new());
|
|
assert!(m.render().contains("nexus_instances_loaded 0"));
|
|
}
|
|
|
|
#[test]
|
|
fn label_werte_werden_maskiert() {
|
|
let m = Metrics::default();
|
|
m.record_request("a\"b\\c\nd", 200, 1, None, None, false);
|
|
assert!(m.render().contains("model=\"a\\\"b\\\\c\\nd\""));
|
|
}
|
|
|
|
#[test]
|
|
fn gpu_ausgabe_wird_gelesen_und_kaputtes_uebersprungen() {
|
|
let g = parse_gpus("0, 9, 12288, 0, 35\nkaputt\n1, 10, 12288\n");
|
|
assert_eq!(g.len(), 2);
|
|
assert_eq!(g[0].utilization_percent, Some(0));
|
|
assert_eq!(g[1].temperature_c, None);
|
|
}
|
|
}
|