From 6af356c17b0ccb0aa93a9f6c114b14e64c92c0f7 Mon Sep 17 00:00:00 2001 From: wlkns-dev Date: Sun, 15 Nov 2026 09:09:07 +0100 Subject: [PATCH] feat: nexus diag, Diagnose-Archiv ohne Prompts und Keys (#1050) Co-Authored-By: Claude Sonnet 5.5 --- crates/nexus/src/diag.rs | 454 +++++++++++++++++++++++++++++++++++++++ crates/nexus/src/main.rs | 5 +- 2 files changed, 458 insertions(+), 1 deletion(-) create mode 100644 crates/nexus/src/diag.rs diff --git a/crates/nexus/src/diag.rs b/crates/nexus/src/diag.rs new file mode 100644 index 0000000..3995bd3 --- /dev/null +++ b/crates/nexus/src/diag.rs @@ -0,0 +1,454 @@ +//! `nexus diag`: bündelt Angaben zur Fehlersuche in ein Archiv, das man +//! weitergeben kann. +//! +//! Enthalten: Version, Konfiguration (Zeilen mit `key`, `secret`, `token`, +//! `password` oder `passwort` im Namen geschwärzt), Registry, Namen und Rechte +//! der API-Keys (nie Hashes oder Klartext), die letzten Anfragen und +//! Audit-Einträge (nur Metadaten), GPU-Stand, Speicher und das Ende der +//! Engine-Logs. **Nie** enthalten: Prompts, Antworten, Key-Klartext. +//! +//! Die Engine-Logs stammen von den Engines selbst und werden unverändert +//! übernommen. Bei Standard-Ausführlichkeit enthalten die geprüften Engines +//! (llama.cpp, Ollama, Maya) keine Prompts; stellt man eine Engine auf +//! ausführliches Protokollieren, kann das anders sein. Mit +//! `--ohne-engine-logs` bleiben sie weg. + +use std::path::{Path, PathBuf}; +use std::process::{Command, ExitCode}; + +use nexus_core::{Config, now_iso8601}; +use nexus_store::Store; + +use crate::cli::{Flags, load_config}; + +/// Wie viele Anfragen und Audit-Einträge ins Archiv kommen. +const ROWS: u32 = 500; +/// Wie viele Zeilen vom Ende jedes Engine-Logs ins Archiv kommen. +const LOG_LINES: usize = 200; + +pub fn command(args: &[String]) -> ExitCode { + match run(args) { + Ok(message) => { + println!("{message}"); + ExitCode::SUCCESS + } + Err(message) => { + eprintln!("{message}"); + ExitCode::FAILURE + } + } +} + +fn run(args: &[String]) -> Result { + let flags = Flags::parse(args, &["out", "config"], &["ohne-engine-logs"])?; + let config = load_config(&flags)?; + let config_text = config_file_text(&flags); + let out = flags.get("out").map(PathBuf::from).unwrap_or_else(|| { + PathBuf::from(format!( + "nexus-diag-{}.tar.gz", + now_iso8601().replace([':', '-'], "") + )) + }); + let files = collect( + &config, + config_text.as_deref(), + !flags.has("ohne-engine-logs"), + ); + + let staging = std::env::temp_dir().join(format!("nexus-diag-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&staging); + for (name, content) in &files { + let path = staging.join(name); + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent).map_err(|e| format!("{}: {e}", parent.display()))?; + } + std::fs::write(&path, content).map_err(|e| format!("{}: {e}", path.display()))?; + } + let out_abs = std::path::absolute(&out).map_err(|e| format!("{}: {e}", out.display()))?; + let status = Command::new("tar") + .arg("-czf") + .arg(&out_abs) + .arg("-C") + .arg(&staging) + .arg(".") + .status(); + match status { + Ok(s) if s.success() => { + let _ = std::fs::remove_dir_all(&staging); + Ok(format!( + "Diagnose geschrieben: {} ({} Dateien). Sie enthält keine Prompts, Antworten oder Keys; die Engine-Logs stehen unverändert darin.", + out.display(), + files.len() + )) + } + other => Err(format!( + "Das Archiv konnte nicht mit `tar` erstellt werden ({other:?}). Die Dateien liegen unter {}.", + staging.display() + )), + } +} + +/// Text der Konfigurationsdatei, falls es eine gibt. +fn config_file_text(flags: &Flags) -> Option { + let path = flags + .get("config") + .map(PathBuf::from) + .or_else(|| std::env::var_os("NEXUS_CONFIG").map(PathBuf::from)) + .or_else(|| Some(PathBuf::from("config.toml")))?; + std::fs::read_to_string(path).ok() +} + +/// Stellt alle Dateien des Archivs zusammen: (Pfad im Archiv, Inhalt). +pub fn collect( + config: &Config, + config_text: Option<&str>, + with_engine_logs: bool, +) -> Vec<(String, String)> { + let mut files = Vec::new(); + files.push(( + "uebersicht.txt".to_string(), + format!( + "Nexus {}\nErstellt: {}\nDatenbank: {}\nSchema-Version: {}\n\nHinweis: Diese Diagnose enthält keine Prompts, Antworten oder Keys. Engine-Logs sind {}.\n", + nexus_core::VERSION, + now_iso8601(), + config.db_path().display(), + if config.db_path().is_file() { + Store::open(&config.db_path()) + .ok() + .and_then(|s| s.schema_version().ok()) + .map(|v| v.to_string()) + .unwrap_or_else(|| "unlesbar".to_string()) + } else { + "noch keine Datenbank".to_string() + }, + if with_engine_logs { + "unverändert übernommen (bei ausführlichem Protokollieren einer Engine können sie Inhalte enthalten)" + } else { + "nicht enthalten" + }, + ), + )); + files.push(( + "konfiguration.toml".to_string(), + match config_text { + Some(text) => redact_config(text), + None => { + "(keine Konfigurationsdatei gefunden, es gelten die Standardwerte)\n".to_string() + } + }, + )); + + if config.db_path().is_file() { + match Store::open(&config.db_path()) { + Ok(store) => database_files(&store, &mut files), + Err(e) => files.push(("datenbank.txt".to_string(), format!("Nicht lesbar: {e}\n"))), + } + } else { + files.push(( + "datenbank.txt".to_string(), + "Es gibt noch keine Datenbank.\n".to_string(), + )); + } + + files.push(("gpu.txt".to_string(), gpu_text())); + files.push(("system.txt".to_string(), system_text())); + + if with_engine_logs { + for dir in log_dirs(config) { + for (name, tail) in log_tails(&dir) { + files.push((format!("engine-logs/{name}"), tail)); + } + } + } + files +} + +fn database_files(store: &Store, files: &mut Vec<(String, String)>) { + let mut models = String::from("name;art;freigegeben;engine;gpus;kontext;pfad\n"); + for m in store.list_models(false).unwrap_or_default() { + let plan = store.start_plan(&m.name).ok().flatten(); + models.push_str(&format!( + "{};{};{};{};{};{};{}\n", + csv(&m.name), + csv(&m.kind), + m.enabled, + plan.as_ref() + .map(|p| csv(&p.engine_name)) + .unwrap_or_default(), + plan.as_ref() + .map(|p| p + .gpus + .iter() + .map(u32::to_string) + .collect::>() + .join(",")) + .unwrap_or_default(), + plan.as_ref() + .and_then(|p| p.context) + .map(|c| c.to_string()) + .unwrap_or_default(), + plan.as_ref() + .map(|p| csv(&p.model_path.display().to_string())) + .unwrap_or_default(), + )); + } + files.push(("modelle.csv".to_string(), models)); + + let mut keys = String::from("name;aktiv;standard;hoechstens;modelle;metriken\n"); + for k in store.list_api_keys().unwrap_or_default() { + keys.push_str(&format!( + "{};{};{};{};{};{}\n", + csv(&k.name), + k.active, + k.default_priority.as_str(), + k.max_priority.as_str(), + csv(&k.rights.models.join(",")), + k.rights.metrics + )); + } + files.push(("keys.csv".to_string(), keys)); + + let mut requests = String::from( + "zeit;korrelation;key_id;modell_id;status;wartezeit_ms;latenz_ms;dauer_ms;tokens_ein;tokens_aus;engine;instanz;abgebrochen\n", + ); + for r in store.recent_requests(ROWS).unwrap_or_default() { + requests.push_str(&format!( + "{};{};{};{};{};{};{};{};{};{};{};{};{}\n", + r.time, + csv(&r.correlation), + opt(r.api_key_id), + opt(r.model_id), + r.status, + opt(r.wait_ms), + opt(r.latency_ms), + opt(r.duration_ms), + opt(r.tokens_in), + opt(r.tokens_out), + r.engine.as_deref().map(csv).unwrap_or_default(), + opt(r.instance_id), + r.aborted + )); + } + files.push(("anfragen.csv".to_string(), requests)); + + let mut audit = String::from("zeit;akteur;aktion;ziel\n"); + for a in store.recent_audit(ROWS).unwrap_or_default() { + audit.push_str(&format!( + "{};{};{};{}\n", + a.time, + csv(&a.actor), + csv(&a.action), + a.target.as_deref().map(csv).unwrap_or_default() + )); + } + files.push(("audit.csv".to_string(), audit)); +} + +fn opt(value: Option) -> String { + value.map(|v| v.to_string()).unwrap_or_default() +} + +/// Macht einen Text CSV-tauglich (Trennzeichen `;`, keine Zeilenumbrüche). +fn csv(text: &str) -> String { + text.replace([';', '\n', '\r'], " ") +} + +/// Schwärzt Werte in Zeilen, deren Name auf ein Geheimnis hindeutet. +pub fn redact_config(text: &str) -> String { + text.lines() + .map(|line| { + let name = line.split('=').next().unwrap_or("").to_lowercase(); + let sensitive = ["key", "secret", "token", "password", "passwort"] + .iter() + .any(|w| name.contains(w)); + if line.contains('=') && sensitive && !name.trim_start().starts_with('#') { + format!("{}= \"\"", line.split('=').next().unwrap_or("")) + } else { + line.to_string() + } + }) + .collect::>() + .join("\n") + + "\n" +} + +fn log_dirs(config: &Config) -> Vec { + let mut dirs = Vec::new(); + for dir in [ + crate::serve::llama_config(config).map(|c| c.log_dir), + crate::serve::ollama_config(config).map(|c| c.log_dir), + crate::serve::maya_config(config).map(|c| c.log_dir), + ] + .into_iter() + .flatten() + { + if !dirs.contains(&dir) { + dirs.push(dir); + } + } + dirs +} + +/// Das Ende jedes aktuellen Engine-Logs (`instance-*.log`) im Ordner. +fn log_tails(dir: &Path) -> Vec<(String, String)> { + let Ok(entries) = std::fs::read_dir(dir) else { + return Vec::new(); + }; + let mut out = Vec::new(); + for entry in entries.flatten() { + let name = entry.file_name().to_string_lossy().into_owned(); + if !(name.starts_with("instance-") && name.ends_with(".log")) { + continue; + } + if let Ok(bytes) = std::fs::read(entry.path()) { + let start = bytes.len().saturating_sub(256 * 1024); + let text = String::from_utf8_lossy(&bytes[start..]); + let lines: Vec<&str> = text.lines().collect(); + let from = lines.len().saturating_sub(LOG_LINES); + out.push((name, lines[from..].join("\n") + "\n")); + } + } + out.sort(); + out +} + +fn gpu_text() -> String { + match Command::new("nvidia-smi").output() { + Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).into_owned(), + Ok(o) => format!("nvidia-smi endete mit {}\n", o.status), + Err(e) => format!("nvidia-smi nicht verfügbar: {e}\n"), + } +} + +fn system_text() -> String { + let mut text = String::new(); + for (title, path, max_lines) in [ + ("Kernel", "/proc/version", 1), + ("Laufzeit", "/proc/uptime", 1), + ("Last", "/proc/loadavg", 1), + ("Speicher", "/proc/meminfo", 6), + ] { + text.push_str(&format!("== {title}\n")); + match std::fs::read_to_string(path) { + Ok(t) => { + for line in t.lines().take(max_lines) { + text.push_str(line); + text.push('\n'); + } + } + Err(e) => text.push_str(&format!("nicht lesbar: {e}\n")), + } + } + text +} + +#[cfg(test)] +mod tests { + use super::*; + use nexus_core::Priority; + use nexus_store::{NewLlm, RequestLogEntry, Rights}; + + #[test] + fn config_zeilen_mit_geheimnisnamen_werden_geschwaerzt() { + let t = redact_config( + "listen = \"x\"\napi_key = \"nx-GEHEIM\"\n# key = \"nx-KOMMENTAR\"\n[maya]\nport_from = 1\nadmin_password = 'abc'", + ); + assert!(t.contains("listen = \"x\"")); + assert!(!t.contains("nx-GEHEIM") && !t.contains("abc"), "{t}"); + assert!( + t.contains("# key = \"nx-KOMMENTAR\""), + "Kommentare bleiben: {t}" + ); + assert!(t.contains("port_from = 1")); + } + + #[test] + fn archivinhalt_enthaelt_modelle_anfragen_und_kein_geheimnis() { + let dir = std::env::temp_dir().join(format!("nexus-diag-test-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let config = Config { + data_dir: dir.clone(), + ..Config::default() + }; + let klartext_key; + { + let mut store = Store::open(&config.db_path()).unwrap(); + store + .register_llm(&NewLlm { + name: "bonsai".to_string(), + engine: "llama.cpp".to_string(), + path: PathBuf::from("/m/b.gguf"), + quantization: None, + size_bytes: None, + gpus: vec![0], + context: Some(2048), + vram_mb: None, + ram_mb: None, + enabled: true, + }) + .unwrap(); + klartext_key = store + .create_api_key( + "client", + &Rights::default(), + Priority::Normal, + Priority::Normal, + ) + .unwrap(); + store + .log_request(&RequestLogEntry { + correlation: "req_diag".to_string(), + api_key_id: None, + model: Some("bonsai".to_string()), + status: 200, + wait_ms: None, + latency_ms: Some(5), + duration_ms: Some(50), + tokens_in: Some(3), + tokens_out: Some(4), + engine: Some("llama.cpp".to_string()), + instance_id: Some(1), + aborted: false, + }) + .unwrap(); + store.audit("cli", "key.create", Some("client")).unwrap(); + } + let files = collect(&config, Some("listen = \"127.0.0.1:1\"\n"), false); + let get = |name: &str| { + files + .iter() + .find(|(n, _)| n == name) + .unwrap_or_else(|| panic!("{name} fehlt")) + .1 + .clone() + }; + assert!(get("modelle.csv").contains("bonsai;llm;true;llama.cpp;0;2048;/m/b.gguf")); + assert!(get("anfragen.csv").contains("req_diag")); + assert!(get("anfragen.csv").contains(";3;4;llama.cpp;1;false")); + assert!(get("audit.csv").contains("key.create")); + assert!(get("keys.csv").contains("client;true;normal;normal;*;false")); + assert!(get("uebersicht.txt").contains("Schema-Version: 2")); + assert!(!files.iter().any(|(n, _)| n.starts_with("engine-logs/"))); + for (name, content) in &files { + assert!(!content.contains(&klartext_key), "Key-Klartext in {name}"); + } + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn engine_logs_kommen_mit_ihrem_ende_ins_archiv() { + let dir = std::env::temp_dir().join(format!("nexus-diag-logs-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let zeilen: String = (0..500).map(|i| format!("zeile {i}\n")).collect(); + std::fs::write(dir.join("instance-1.log"), zeilen).unwrap(); + std::fs::write(dir.join("instance-1.log.1700000000"), "alt").unwrap(); + std::fs::write(dir.join("nexus.db"), "binär").unwrap(); + let tails = log_tails(&dir); + assert_eq!(tails.len(), 1); + assert!(tails[0].1.contains("zeile 499") && !tails[0].1.contains("zeile 100\n")); + assert_eq!(tails[0].1.lines().count(), LOG_LINES); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/crates/nexus/src/main.rs b/crates/nexus/src/main.rs index aeca0e0..c087734 100644 --- a/crates/nexus/src/main.rs +++ b/crates/nexus/src/main.rs @@ -1,9 +1,10 @@ //! Nexus: AI Gateway für srv04. //! -//! Befehle: `version`, `selftest`, `serve`, `key ...`, `model ...`. +//! Befehle: `version`, `selftest`, `serve`, `key ...`, `model ...`, `diag`. mod admin; mod cli; +mod diag; mod logcap; mod logging; mod selftest; @@ -25,6 +26,7 @@ Aufruf: nexus model add --name N --engine ollama --tag MODELLNAME [--gpus 0] [--disabled] nexus model add --name N --engine maya --maya-config PFAD.json [--gpus 0,1] [--disabled] nexus model list | enable --name N | disable --name N | discover [--engine llama.cpp|ollama|maya] + nexus diag [--out DATEI.tar.gz] [--ohne-engine-logs] Diagnose-Archiv ohne Prompts und Keys nexus help Diese Hilfe Die Konfiguration kommt aus --config, sonst NEXUS_CONFIG, sonst ./config.toml, sonst gelten Standardwerte. @@ -42,6 +44,7 @@ async fn main() -> ExitCode { Some("serve") => serve::command(&args[1..]).await, Some("key") => admin::key(&args[1..]), Some("model") => admin::model(&args[1..]).await, + Some("diag") => diag::command(&args[1..]), Some("help") | Some("--help") | None => { print!("{HILFE}"); ExitCode::SUCCESS