diff --git a/crates/nexus-adapter/src/engine.rs b/crates/nexus-adapter/src/engine.rs index 9a1dd6d..ffda0c5 100644 --- a/crates/nexus-adapter/src/engine.rs +++ b/crates/nexus-adapter/src/engine.rs @@ -41,6 +41,30 @@ pub trait Engine: Send + Sync { true } + /// Wie der Dienst hinter der Engine gesteuert wird. Standard: gar nicht. + fn dienst(&self) -> crate::types::Dienst { + crate::types::Dienst::Keiner + } + + /// Beendet den Dienst hinter der Engine (nur wenn `dienst()` eine Einheit nennt). + async fn dienst_stoppen(&self) -> crate::types::Result<()> { + Err(crate::types::AdapterError::Stop( + "Das Gateway steuert den Dienst dieser Engine nicht.".to_string(), + )) + } + + /// Startet den Dienst hinter der Engine neu und wartet, bis er antwortet. + async fn dienst_neustarten(&self) -> crate::types::Result<()> { + Err(crate::types::AdapterError::Stop( + "Das Gateway steuert den Dienst dieser Engine nicht.".to_string(), + )) + } + + /// Version der Engine, wenn sie sich billig und ohne Eingriff ermitteln lässt (sonst `None`). + async fn version(&self) -> Option { + None + } + /// Wie die Engine gestartet wird (nur zur Anzeige, ohne Geheimnisse). fn start_info(&self) -> StartInfo { StartInfo::default() diff --git a/crates/nexus-adapter/src/lib.rs b/crates/nexus-adapter/src/lib.rs index 76a4750..952c4a1 100644 --- a/crates/nexus-adapter/src/lib.rs +++ b/crates/nexus-adapter/src/lib.rs @@ -33,6 +33,6 @@ pub use ollama::{OllamaConfig, OllamaEngine, OllamaMode}; pub use process::process_exists; pub use studio::{StudioConfig, StudioEngine}; pub use types::{ - AdapterError, Capabilities, DiscoveredArtifact, Endpoint, EngineInfo, Frontend, Health, + AdapterError, Capabilities, Dienst, DiscoveredArtifact, Endpoint, EngineInfo, Frontend, Health, InstanceHandle, Mode, ProfileSpec, Protocol, Result, StartInfo, Usage, Voice, }; diff --git a/crates/nexus-adapter/src/llama.rs b/crates/nexus-adapter/src/llama.rs index c17e5b3..719b198 100644 --- a/crates/nexus-adapter/src/llama.rs +++ b/crates/nexus-adapter/src/llama.rs @@ -294,6 +294,29 @@ impl LlamaCppEngine { #[async_trait] impl Engine for LlamaCppEngine { + async fn version(&self) -> Option { + // `llama-server --version` schreibt eine Zeile „version: ()“ auf stderr. + let out = tokio::time::timeout( + Duration::from_secs(5), + tokio::process::Command::new(&self.config.binary) + .arg("--version") + .stdin(std::process::Stdio::null()) + .output(), + ) + .await + .ok()? + .ok()?; + let text = format!( + "{}\n{}", + String::from_utf8_lossy(&out.stdout), + String::from_utf8_lossy(&out.stderr) + ); + text.lines() + .find_map(|l| l.trim().strip_prefix("version:")) + .map(|v| v.trim().to_string()) + .filter(|v| !v.is_empty()) + } + fn frontend(&self) -> crate::types::Frontend { // `llama-server` liefert seine Web-Oberfläche mit (`--webui`, Standard an; gelesen in der Hilfe // auf srv04, im Browser über das Gateway nicht erreichbar, #1101). @@ -593,6 +616,31 @@ pub(crate) fn parse_quantization(name: &str) -> Option { mod tests { use super::*; + #[tokio::test] + async fn version_kommt_aus_der_ausgabe_von_version_und_fehlt_ohne_programm() { + let dir = std::env::temp_dir().join(format!("nexus-llama-version-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let skript = dir.join("llama-server"); + std::fs::write( + &skript, + "#!/bin/sh\necho 'load_backend: x' >&2\necho 'version: 6543 (abc1234)' >&2\n", + ) + .unwrap(); + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&skript, std::fs::Permissions::from_mode(0o755)).unwrap(); + let e = LlamaCppEngine::new(LlamaCppConfig { + binary: skript, + ..LlamaCppConfig::default() + }); + assert_eq!(e.version().await.as_deref(), Some("6543 (abc1234)")); + let e = LlamaCppEngine::new(LlamaCppConfig { + binary: dir.join("gibt-es-nicht"), + ..LlamaCppConfig::default() + }); + assert_eq!(e.version().await, None); + let _ = std::fs::remove_dir_all(&dir); + } + fn profile() -> ProfileSpec { ProfileSpec { start_parameters: Default::default(), diff --git a/crates/nexus-adapter/src/mock.rs b/crates/nexus-adapter/src/mock.rs index e3e2e5b..2c31ec2 100644 --- a/crates/nexus-adapter/src/mock.rs +++ b/crates/nexus-adapter/src/mock.rs @@ -24,6 +24,10 @@ pub struct MockConfig { pub vram_mb: u64, pub ram_mb: u64, pub artifacts: Vec, + /// Wenn gesetzt, meldet die Attrappe einen steuerbaren Dienst mit dieser Einheit (→ #1198). + pub dienst_einheit: Option, + /// Version, die die Attrappe meldet. + pub version: Option, } impl Default for MockConfig { @@ -34,6 +38,8 @@ impl Default for MockConfig { vram_mb: 1024, ram_mb: 512, artifacts: Vec::new(), + dienst_einheit: None, + version: None, } } } @@ -43,6 +49,8 @@ pub struct MockEngine { next_id: AtomicU64, starts: AtomicUsize, alive: Mutex>, + /// Aufrufe der Dienststeuerung in der Reihenfolge („stop“, „restart“). + dienst_aufrufe: Mutex>, } impl MockEngine { @@ -52,9 +60,15 @@ impl MockEngine { next_id: AtomicU64::new(1), starts: AtomicUsize::new(0), alive: Mutex::new(HashMap::new()), + dienst_aufrufe: Mutex::new(Vec::new()), } } + /// Aufrufe der Dienststeuerung, für Tests. + pub fn dienst_aufrufe(&self) -> Vec<&'static str> { + self.dienst_aufrufe.lock().unwrap().clone() + } + /// Wie oft `start` aufgerufen wurde (auch gescheiterte Starts). pub fn start_count(&self) -> usize { self.starts.load(Ordering::SeqCst) @@ -75,6 +89,35 @@ impl MockEngine { #[async_trait] impl Engine for MockEngine { + fn dienst(&self) -> crate::types::Dienst { + match &self.config.dienst_einheit { + Some(einheit) => crate::types::Dienst::Systemd { + einheit: einheit.clone(), + }, + None => crate::types::Dienst::Keiner, + } + } + + async fn dienst_stoppen(&self) -> Result<()> { + if self.config.dienst_einheit.is_none() { + return Err(AdapterError::Stop("kein Dienst".to_string())); + } + self.dienst_aufrufe.lock().unwrap().push("stop"); + Ok(()) + } + + async fn dienst_neustarten(&self) -> Result<()> { + if self.config.dienst_einheit.is_none() { + return Err(AdapterError::Stop("kein Dienst".to_string())); + } + self.dienst_aufrufe.lock().unwrap().push("restart"); + Ok(()) + } + + async fn version(&self) -> Option { + self.config.version.clone() + } + fn describe(&self) -> EngineInfo { EngineInfo { name: "mock".to_string(), diff --git a/crates/nexus-adapter/src/ollama.rs b/crates/nexus-adapter/src/ollama.rs index 2ff131a..a58595d 100644 --- a/crates/nexus-adapter/src/ollama.rs +++ b/crates/nexus-adapter/src/ollama.rs @@ -478,6 +478,23 @@ impl Engine for OllamaEngine { } } + async fn version(&self) -> Option { + // Nur beim angeschlossenen Server: Der verwaltete läuft nur, solange ein Modell geladen ist. + if self.managed() { + return None; + } + let antwort = self + .http + .get(format!("{}/api/version", self.base_url(None))) + .timeout(Duration::from_secs(3)) + .send() + .await + .ok()?; + let text = antwort.text().await.ok()?; + let json: serde_json::Value = serde_json::from_str(&text).ok()?; + json["version"].as_str().map(str::to_string) + } + fn describe(&self) -> EngineInfo { EngineInfo { name: "ollama".to_string(), diff --git a/crates/nexus-adapter/src/studio.rs b/crates/nexus-adapter/src/studio.rs index 13c2af2..8360a07 100644 --- a/crates/nexus-adapter/src/studio.rs +++ b/crates/nexus-adapter/src/studio.rs @@ -475,6 +475,44 @@ impl Engine for StudioEngine { self.ensure_up_impl().await } + fn dienst(&self) -> crate::types::Dienst { + match self.config.systemd_unit.as_deref() { + Some(einheit) if !einheit.is_empty() => crate::types::Dienst::Systemd { + einheit: einheit.to_string(), + }, + _ => crate::types::Dienst::Keiner, + } + } + + async fn dienst_stoppen(&self) -> Result<()> { + if self.config.systemd_unit.is_none() { + return Err(AdapterError::Stop( + "Für das Studio ist keine systemd-Einheit eingestellt.".to_string(), + )); + } + self.systemctl("stop").await + } + + async fn dienst_neustarten(&self) -> Result<()> { + if self.config.systemd_unit.is_none() { + return Err(AdapterError::Stop( + "Für das Studio ist keine systemd-Einheit eingestellt.".to_string(), + )); + } + self.systemctl("restart").await?; + let ende = std::time::Instant::now() + Duration::from_secs(self.config.start_timeout_secs); + while std::time::Instant::now() < ende { + if self.reachable(Duration::from_secs(3)).await { + return Ok(()); + } + tokio::time::sleep(Duration::from_secs(2)).await; + } + Err(AdapterError::NotReady { + seconds: self.config.start_timeout_secs, + log_tail: format!("{} antwortet nach dem Neustart nicht", self.base()), + }) + } + async fn voices_reachable(&self) -> bool { self.reachable(Duration::from_secs(3)).await } @@ -1017,6 +1055,32 @@ mod tests { ); } + #[tokio::test] + async fn dienststeuerung_gibt_es_nur_mit_einheit() { + use crate::engine::Engine; + assert_eq!(engine(9).dienst(), crate::types::Dienst::Keiner); + assert!(engine(9).dienst_stoppen().await.is_err()); + let e = mit_systemctl(9, "true"); + assert_eq!( + e.dienst(), + crate::types::Dienst::Systemd { + einheit: "qwen-studio.service".to_string() + } + ); + // „true“ meldet Erfolg: Stopp gelingt, Neustart scheitert nach der Wartezeit (kein Studio auf Port 9). + assert!(e.dienst_stoppen().await.is_ok()); + assert!(matches!( + e.dienst_neustarten().await.unwrap_err(), + AdapterError::NotReady { .. } + )); + // Scheitert systemctl, steht das in der Meldung. + let err = mit_systemctl(9, "false") + .dienst_stoppen() + .await + .unwrap_err(); + assert!(err.to_string().contains("schlug fehl"), "{err}"); + } + #[tokio::test] async fn laeuft_das_studio_wird_systemctl_nicht_gerufen() { let port = fake_studio().await; diff --git a/crates/nexus-adapter/src/types.rs b/crates/nexus-adapter/src/types.rs index 269a274..749fc63 100644 --- a/crates/nexus-adapter/src/types.rs +++ b/crates/nexus-adapter/src/types.rs @@ -11,6 +11,18 @@ pub enum Mode { Attached, } +/// Wie ein Dienst hinter der Engine gesteuert werden kann (→ #1198, Engines-Leitstand). +/// Nur ein Dienst, den das Gateway nicht selbst als Prozess besitzt, hat hier eine Einheit; bei +/// Engines mit Prozessen je Modell-Instanz (llama.cpp, Maya, Strata) gibt es keinen Dienst. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub enum Dienst { + /// Das Gateway steuert keinen Dienst dieser Engine. + #[default] + Keiner, + /// systemd-Benutzereinheit (`systemctl --user`). + Systemd { einheit: String }, +} + /// Sprache, die eine Engine spricht. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Protocol {