feat(api): GPU-Leistung (power.draw) und Fehlerzustand der GPU-Abfrage (#1197, DASH-R1 AP3)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01GmHhg7qE8FdhchzsBrwgjZ
This commit is contained in:
@ -63,6 +63,25 @@ pub struct GpuSample {
|
||||
pub memory_total_mb: u64,
|
||||
pub utilization_percent: Option<u32>,
|
||||
pub temperature_c: Option<u32>,
|
||||
/// Leistungsaufnahme in Watt; `None`, wenn die Karte oder der Treiber sie nicht liefert.
|
||||
pub power_w: Option<f64>,
|
||||
}
|
||||
|
||||
/// Ergebnis der letzten GPU-Abfrage. Unterscheidet „keine GPU“ von „Messung
|
||||
/// fehlgeschlagen“, damit die Oberfläche nie eine Null erfindet.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
|
||||
#[serde(tag = "zustand", content = "text", rename_all = "snake_case")]
|
||||
pub enum GpuStatus {
|
||||
/// Noch keine Abfrage gelaufen.
|
||||
Unbekannt,
|
||||
/// Abfrage ausgeschaltet (`metrics_interval_secs = 0`).
|
||||
Aus,
|
||||
/// Das Programm (`nvidia-smi`) ist nicht vorhanden.
|
||||
KeinProgramm,
|
||||
/// Das Programm lief, lieferte aber einen Fehler oder keine Werte.
|
||||
Fehler(String),
|
||||
/// Werte gelesen (auch eine leere Liste, wenn das Programm keine GPU meldet).
|
||||
Ok,
|
||||
}
|
||||
|
||||
/// Summen seit dem Start des Gateways.
|
||||
@ -95,6 +114,7 @@ struct Inner {
|
||||
instance_losses: BTreeMap<String, u64>,
|
||||
instances: Vec<InstanceSample>,
|
||||
gpus: Vec<GpuSample>,
|
||||
gpu_status: Option<GpuStatus>,
|
||||
/// Scheduler: Verdrängungen und Leerlauf-Entladungen je Modell.
|
||||
evictions: BTreeMap<String, u64>,
|
||||
idle_unloads: BTreeMap<String, u64>,
|
||||
@ -269,6 +289,19 @@ impl Metrics {
|
||||
self.lock().gpus = gpus;
|
||||
}
|
||||
|
||||
/// Merkt sich, wie die letzte GPU-Abfrage ausgegangen ist.
|
||||
pub fn set_gpu_status(&self, status: GpuStatus) {
|
||||
self.lock().gpu_status = Some(status);
|
||||
}
|
||||
|
||||
/// Ergebnis der letzten GPU-Abfrage; vor der ersten Abfrage `Unbekannt`.
|
||||
pub fn gpu_status(&self) -> GpuStatus {
|
||||
self.lock()
|
||||
.gpu_status
|
||||
.clone()
|
||||
.unwrap_or(GpuStatus::Unbekannt)
|
||||
}
|
||||
|
||||
/// Letzte Messung der laufenden Instanzen.
|
||||
pub fn instances(&self) -> Vec<InstanceSample> {
|
||||
self.lock().instances.clone()
|
||||
@ -659,7 +692,8 @@ pub fn series_samples(metrics: &Metrics) -> Vec<(String, String, f64)> {
|
||||
}
|
||||
|
||||
/// Liest die Ausgabe von `nvidia-smi --query-gpu=index,name,memory.used,memory.total,
|
||||
/// utilization.gpu,temperature.gpu --format=csv,noheader,nounits`.
|
||||
/// utilization.gpu,temperature.gpu,power.draw --format=csv,noheader,nounits`.
|
||||
/// Das Feld `power.draw` darf fehlen oder `[N/A]` heißen; dann ist die Leistung unbekannt.
|
||||
pub fn parse_gpus(output: &str) -> Vec<GpuSample> {
|
||||
output
|
||||
.lines()
|
||||
@ -676,6 +710,10 @@ pub fn parse_gpus(output: &str) -> Vec<GpuSample> {
|
||||
memory_total_mb: f[3].parse().ok()?,
|
||||
utilization_percent: f.get(4).and_then(|v| v.parse().ok()),
|
||||
temperature_c: f.get(5).and_then(|v| v.parse().ok()),
|
||||
power_w: f
|
||||
.get(6)
|
||||
.and_then(|v| v.parse::<f64>().ok())
|
||||
.filter(|w| w.is_finite() && *w >= 0.0),
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
@ -820,6 +858,27 @@ mod tests {
|
||||
assert!(m.render().contains("nexus_instances_loaded 0"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gpu_leistung_wird_gelesen_und_fehlend_bleibt_unbekannt() {
|
||||
let g = parse_gpus(
|
||||
"0, A, 100, 12288, 5, 40, 45.23\n1, B, 100, 12288, 5, 40, [N/A]\n2, C, 100, 12288, 5, 40, [Not Supported]\n3, D, 100, 12288, 5, 40\n4, E, 100, 12288, 5, 40, -1\n",
|
||||
);
|
||||
assert_eq!(g.len(), 5);
|
||||
assert_eq!(g[0].power_w, Some(45.23));
|
||||
assert_eq!(g[1].power_w, None, "[N/A] ist keine 0 W");
|
||||
assert_eq!(g[2].power_w, None);
|
||||
assert_eq!(g[3].power_w, None, "alte Ausgabe ohne Feld");
|
||||
assert_eq!(g[4].power_w, None, "negativer Wert ist unplausibel");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gpu_status_beginnt_unbekannt_und_merkt_sich_das_ergebnis() {
|
||||
let m = Metrics::default();
|
||||
assert_eq!(m.gpu_status(), GpuStatus::Unbekannt);
|
||||
m.set_gpu_status(GpuStatus::Fehler("Exit 9".into()));
|
||||
assert_eq!(m.gpu_status(), GpuStatus::Fehler("Exit 9".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zeitreihen_zeilen_aus_gpus_und_instanzen() {
|
||||
let m = Metrics::default();
|
||||
|
||||
@ -578,7 +578,7 @@ impl Runtime {
|
||||
});
|
||||
}
|
||||
samples.sort_by(|a, b| a.model.cmp(&b.model));
|
||||
let gpus = read_gpus(nvidia_smi).await;
|
||||
let (gpus, gpu_status) = read_gpus(nvidia_smi).await;
|
||||
{
|
||||
let mut inner = self.shared.lock();
|
||||
// Inzwischen entladene Instanzen nicht wieder anzeigen.
|
||||
@ -598,6 +598,7 @@ impl Runtime {
|
||||
}
|
||||
self.metrics.set_instances(samples);
|
||||
self.metrics.set_gpus(gpus);
|
||||
self.metrics.set_gpu_status(gpu_status);
|
||||
}
|
||||
|
||||
/// Lehnt alle Wartenden ab und beendet alle Instanzen, auch solche, die
|
||||
@ -998,38 +999,125 @@ impl Shared {
|
||||
}
|
||||
}
|
||||
|
||||
/// Fragt `nvidia-smi` nach Speicher, Auslastung und Temperatur je GPU. Ohne
|
||||
/// das Programm oder bei einem Fehler bleibt die Liste leer.
|
||||
async fn read_gpus(nvidia_smi: &Path) -> Vec<crate::metrics::GpuSample> {
|
||||
/// Felder der GPU-Abfrage; `power.draw` zuletzt, damit alte Treiber ohne das Feld
|
||||
/// über die kürzere Abfrage trotzdem Werte liefern.
|
||||
const GPU_FELDER: &str = "index,name,memory.used,memory.total,utilization.gpu,temperature.gpu";
|
||||
|
||||
/// Führt eine `nvidia-smi`-Abfrage aus. `Err` enthält die Art des Fehlers.
|
||||
async fn gpu_abfrage(nvidia_smi: &Path, felder: &str) -> Result<String, crate::metrics::GpuStatus> {
|
||||
use crate::metrics::GpuStatus;
|
||||
let output = tokio::time::timeout(
|
||||
Duration::from_secs(5),
|
||||
tokio::process::Command::new(nvidia_smi)
|
||||
.args([
|
||||
"--query-gpu=index,name,memory.used,memory.total,utilization.gpu,temperature.gpu",
|
||||
"--format=csv,noheader,nounits",
|
||||
format!("--query-gpu={felder}"),
|
||||
"--format=csv,noheader,nounits".to_string(),
|
||||
])
|
||||
.output(),
|
||||
)
|
||||
.await;
|
||||
match output {
|
||||
Ok(Ok(out)) if out.status.success() => {
|
||||
let mut gpus = parse_gpus(&String::from_utf8_lossy(&out.stdout));
|
||||
let header = tokio::time::timeout(
|
||||
Duration::from_secs(5),
|
||||
tokio::process::Command::new(nvidia_smi).output(),
|
||||
)
|
||||
.await;
|
||||
let cuda = match header {
|
||||
Ok(Ok(out)) if out.status.success() => {
|
||||
crate::metrics::parse_cuda_version(&String::from_utf8_lossy(&out.stdout))
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
for gpu in &mut gpus {
|
||||
gpu.cuda_version = cuda.clone();
|
||||
}
|
||||
gpus
|
||||
Ok(String::from_utf8_lossy(&out.stdout).into_owned())
|
||||
}
|
||||
_ => Vec::new(),
|
||||
Ok(Ok(out)) => Err(GpuStatus::Fehler(format!("beendet mit {}", out.status))),
|
||||
Ok(Err(e)) if e.kind() == std::io::ErrorKind::NotFound => Err(GpuStatus::KeinProgramm),
|
||||
Ok(Err(e)) => Err(GpuStatus::Fehler(e.to_string())),
|
||||
Err(_) => Err(GpuStatus::Fehler(
|
||||
"keine Antwort innerhalb von 5 s".to_string(),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Fragt `nvidia-smi` nach Speicher, Auslastung, Temperatur und Leistung je GPU.
|
||||
/// Der Zustand sagt, ob „keine Werte“ heißt: Programm fehlt, Fehler oder wirklich
|
||||
/// keine GPU. Liefert die Abfrage mit `power.draw` einen Fehler (älterer
|
||||
/// Treiber), wird ohne das Feld wiederholt.
|
||||
async fn read_gpus(
|
||||
nvidia_smi: &Path,
|
||||
) -> (Vec<crate::metrics::GpuSample>, crate::metrics::GpuStatus) {
|
||||
use crate::metrics::GpuStatus;
|
||||
let mit_leistung = format!("{GPU_FELDER},power.draw");
|
||||
let text = match gpu_abfrage(nvidia_smi, &mit_leistung).await {
|
||||
Ok(text) => text,
|
||||
Err(GpuStatus::KeinProgramm) => return (Vec::new(), GpuStatus::KeinProgramm),
|
||||
Err(_) => match gpu_abfrage(nvidia_smi, GPU_FELDER).await {
|
||||
Ok(text) => text,
|
||||
Err(status) => return (Vec::new(), status),
|
||||
},
|
||||
};
|
||||
let mut gpus = parse_gpus(&text);
|
||||
let header = tokio::time::timeout(
|
||||
Duration::from_secs(5),
|
||||
tokio::process::Command::new(nvidia_smi).output(),
|
||||
)
|
||||
.await;
|
||||
let cuda = match header {
|
||||
Ok(Ok(out)) if out.status.success() => {
|
||||
crate::metrics::parse_cuda_version(&String::from_utf8_lossy(&out.stdout))
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
for gpu in &mut gpus {
|
||||
gpu.cuda_version = cuda.clone();
|
||||
}
|
||||
(gpus, GpuStatus::Ok)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod gpu_tests {
|
||||
use super::*;
|
||||
use crate::metrics::GpuStatus;
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
/// Legt ein Shell-Skript als `nvidia-smi`-Attrappe an.
|
||||
fn attrappe(name: &str, inhalt: &str) -> std::path::PathBuf {
|
||||
let dir =
|
||||
std::env::temp_dir().join(format!("nexus-gpu-test-{}-{name}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let pfad = dir.join("nvidia-smi");
|
||||
std::fs::write(&pfad, format!("#!/bin/sh\n{inhalt}\n")).unwrap();
|
||||
std::fs::set_permissions(&pfad, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
pfad
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn fehlendes_programm_ist_kein_programm_und_keine_nullwerte() {
|
||||
let (gpus, status) = read_gpus(Path::new("/nicht/vorhanden/nvidia-smi")).await;
|
||||
assert!(gpus.is_empty());
|
||||
assert_eq!(status, GpuStatus::KeinProgramm);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn fehlerhaftes_programm_ist_ein_fehler() {
|
||||
let pfad = attrappe("fehler", "exit 9");
|
||||
let (gpus, status) = read_gpus(&pfad).await;
|
||||
assert!(gpus.is_empty());
|
||||
assert!(matches!(status, GpuStatus::Fehler(_)), "{status:?}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn leistung_wird_gelesen_und_na_bleibt_unbekannt() {
|
||||
let pfad = attrappe(
|
||||
"leistung",
|
||||
"case \"$*\" in *power.draw*) echo '0, NVIDIA Test, 100, 12288, 5, 40, 45.2'; echo '1, NVIDIA Test, 100, 12288, 5, 40, [N/A]';; *) echo 'Treiber CUDA Version: 13.0';; esac",
|
||||
);
|
||||
let (gpus, status) = read_gpus(&pfad).await;
|
||||
assert_eq!(status, GpuStatus::Ok);
|
||||
assert_eq!(gpus.len(), 2);
|
||||
assert_eq!(gpus[0].power_w, Some(45.2));
|
||||
assert_eq!(gpus[1].power_w, None);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn alter_treiber_ohne_power_draw_faellt_auf_die_kurze_abfrage_zurueck() {
|
||||
let pfad = attrappe(
|
||||
"alt",
|
||||
"case \"$*\" in *power.draw*) exit 2;; *query-gpu*) echo '0, NVIDIA Alt, 100, 12288, 5, 40';; esac",
|
||||
);
|
||||
let (gpus, status) = read_gpus(&pfad).await;
|
||||
assert_eq!(status, GpuStatus::Ok);
|
||||
assert_eq!(gpus.len(), 1);
|
||||
assert_eq!(gpus[0].power_w, None);
|
||||
}
|
||||
}
|
||||
|
||||
@ -1561,6 +1561,7 @@ mod tests {
|
||||
memory_total_mb: 12288,
|
||||
utilization_percent: None,
|
||||
temperature_c: None,
|
||||
power_w: None,
|
||||
};
|
||||
assert!(gpu_table(&[gpu.clone()]).contains("NVIDIA GeForce RTX 3060 · 12 GB · CUDA 13.0"));
|
||||
gpu.cuda_version = None;
|
||||
|
||||
Reference in New Issue
Block a user