feat: Maya-Adapter (Managed, gegen Attrappe), Engine-Wahl maya in Registry und CLI (M2.6b)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@ -40,7 +40,7 @@ Zeichen: ✓ fertig · ◐ teilweise · ✗ offen · ? nicht geprüft.
|
||||
- [#1044] **Version 0.1.1 auf srv04 einspielen.** Dort läuft noch der Build `0.1.0-dev` (gestoppt) ohne Ollama. Mit `scripts/deploy-srv04.sh` und dem Installationsskript (sudo durch den Menschen), `[ollama]` in die `config.toml` eintragen (Modellordner `/srv/models/ollama`), Ollama-Modelle registrieren, danach `nexus version` und einen kurzen Lauf als Dienst prüfen (auch `Restart=on-failure`). Tests: `client2antwort.1`. → #1003
|
||||
|
||||
**P2 – danach**
|
||||
- [#1037] **M2.6b Maya-Adapter** (Release `0.1.2`). Protokoll am 15.11.2026 gemessen (`docs/m2-maya-messung.md`), Adapter noch nicht gebaut. Tests: `client2antwort.1–.3` mit Maya; Merktext-Prüfung (→ #1043) und Risiko → #1047 beachten. Erst nach `0.1.0`. → #1003
|
||||
- [#1037] **M2.6b Maya-Adapter** (Release `0.1.2`). Protokoll am 15.11.2026 gemessen (`docs/m2-maya-messung.md`); Adapter `MayaEngine` gegen eine Attrappe gebaut und getestet (15.11.2026), echter Lauf auf srv04 und Klicktests fehlen noch. Tests: `client2antwort.1–.3` mit Maya; Merktext-Prüfung (→ #1043) und Risiko → #1047 beachten. Erst nach `0.1.0`. → #1003
|
||||
- [#1038] **M2.6c Strata-Adapter** (Release `0.1.3`). Protokoll zuerst messen, Strata nur auf `127.0.0.1` (→ #1029). Tests: `client2antwort.1–.3` mit Strata. Erst nach `0.1.0`. → #1003
|
||||
- [#1012] **M3 Scheduler und Queue umsetzen.** Erst nach M2. Klicktests: `anfrage2warteschlange.1–.3`. → #1004
|
||||
|
||||
|
||||
@ -4,6 +4,7 @@
|
||||
//! - [`LlamaCppEngine`]: startet `llama-server` als verwalteten Prozess (Managed).
|
||||
//! - [`OllamaEngine`]: Ollama, verwaltet (`ollama serve` als Prozess) oder angehängt
|
||||
//! (laufender Server).
|
||||
//! - [`MayaEngine`]: Project Maya (`maya.py`) als verwalteter Prozess.
|
||||
//! - [`MockEngine`]: Attrappe ohne Prozesse für Scheduler- und Vertragstests.
|
||||
//!
|
||||
//! Stand M2.2: Die Weiterleitung von Anfragen (`forward`) kommt mit der API
|
||||
@ -12,6 +13,7 @@
|
||||
|
||||
mod engine;
|
||||
mod llama;
|
||||
mod maya;
|
||||
mod mock;
|
||||
mod ollama;
|
||||
mod process;
|
||||
@ -19,6 +21,7 @@ mod types;
|
||||
|
||||
pub use engine::Engine;
|
||||
pub use llama::{LlamaCppConfig, LlamaCppEngine};
|
||||
pub use maya::{MayaConfig, MayaEngine};
|
||||
pub use mock::{MockConfig, MockEngine};
|
||||
pub use ollama::{OllamaConfig, OllamaEngine, OllamaMode};
|
||||
pub use process::process_exists;
|
||||
|
||||
690
crates/nexus-adapter/src/maya.rs
Normal file
690
crates/nexus-adapter/src/maya.rs
Normal file
@ -0,0 +1,690 @@
|
||||
//! Adapter für Project Maya (`maya.py`) im Modus Managed.
|
||||
//!
|
||||
//! Gemessen auf srv04 (15.11.2026, Maya 1.1.54, `docs/m2-maya-messung.md`):
|
||||
//! - Maya ist ein Python-Server (`maya.py --config <json> --host --port`) vor
|
||||
//! einer eigenen CUDA-Engine; er spricht OpenAI-HTTP (`/v1/models`,
|
||||
//! `/v1/chat/completions`, mit `reasoning_content` und SSE-Keep-alive-Zeilen).
|
||||
//! - Der Port öffnet sich erst, wenn das Modell geladen ist (etwa 70 s);
|
||||
//! `GET /health` liefert dann `{"status":"ok",...}` ohne Schlüssel.
|
||||
//! - `SIGTERM` an `maya.py` beendet Server, Engine und Hilfsprozesse in
|
||||
//! etwa 9 s und gibt VRAM und RAM frei.
|
||||
//! - Nach `POST /models/unload` oder einem Leerlauf-Entladen lädt der nächste
|
||||
//! Chat das Modell selbst nach (etwa 66 s).
|
||||
//!
|
||||
//! Das Modell ist bei Maya die Konfigurationsdatei (JSON). Der Adapter legt je
|
||||
//! Instanz eine Kopie an, in der er Port, Log, GPUs und Arbeitsordner setzt,
|
||||
//! damit weder die Originaldatei noch der Maya-Ordner verändert werden. Ein
|
||||
//! API-Schlüssel wird nicht gesetzt: Maya lauscht nur auf `127.0.0.1`, wie die
|
||||
//! anderen Adapter.
|
||||
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use serde::Deserialize;
|
||||
use serde_json::Value;
|
||||
use tokio::process::{Child, Command};
|
||||
|
||||
use crate::engine::Engine;
|
||||
use crate::llama::{parse_rss_mb, parse_vram_mb};
|
||||
use crate::process::{PortPool, log_tail, rotate_log, sigterm, terminate_group};
|
||||
use crate::types::{
|
||||
AdapterError, Capabilities, DiscoveredArtifact, Endpoint, EngineInfo, Health, InstanceHandle,
|
||||
Mode, ProfileSpec, Protocol, Result, Usage,
|
||||
};
|
||||
|
||||
/// Konfiguration des Maya-Adapters. Enthält keine Geheimnisse.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
|
||||
#[serde(default, deny_unknown_fields)]
|
||||
pub struct MayaConfig {
|
||||
/// Python-Programm aus der Umgebung von Maya.
|
||||
pub python: PathBuf,
|
||||
/// Skript `maya.py`.
|
||||
pub script: PathBuf,
|
||||
/// Ordner, in denen `discover` nach Maya-Konfigurationen (`*.json`) sucht.
|
||||
pub config_roots: Vec<PathBuf>,
|
||||
/// Port-Bereich für die Instanzen (nur `127.0.0.1`).
|
||||
pub port_from: u16,
|
||||
pub port_to: u16,
|
||||
/// Wie lange das Laden höchstens dauern darf (gemessen etwa 70 s).
|
||||
pub ready_timeout_secs: u64,
|
||||
/// Ordner für Logs, Konfigurationskopien und Arbeitsordner der Instanzen.
|
||||
pub log_dir: PathBuf,
|
||||
/// Wie viele aufgehobene Logs älterer Läufe erhalten bleiben.
|
||||
pub log_keep: usize,
|
||||
/// Zusätzliche Argumente für jeden Start.
|
||||
pub extra_args: Vec<String>,
|
||||
/// Zusätzliche Umgebungsvariablen (keine Geheimnisse).
|
||||
pub env: BTreeMap<String, String>,
|
||||
/// Programm zur VRAM-Messung.
|
||||
pub nvidia_smi: PathBuf,
|
||||
}
|
||||
|
||||
impl Default for MayaConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
python: PathBuf::from("/srv/apps/maya/.venv/bin/python"),
|
||||
script: PathBuf::from("/srv/apps/maya/maya.py"),
|
||||
config_roots: vec![PathBuf::from("/srv/apps/maya")],
|
||||
port_from: 18200,
|
||||
port_to: 18299,
|
||||
ready_timeout_secs: 240,
|
||||
log_dir: PathBuf::from("data/logs"),
|
||||
log_keep: 10,
|
||||
extra_args: Vec::new(),
|
||||
env: BTreeMap::new(),
|
||||
nvidia_smi: PathBuf::from("nvidia-smi"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Managed {
|
||||
child: Child,
|
||||
port: u16,
|
||||
}
|
||||
|
||||
pub struct MayaEngine {
|
||||
config: MayaConfig,
|
||||
ports: PortPool,
|
||||
next_id: AtomicU64,
|
||||
children: tokio::sync::Mutex<HashMap<u64, Managed>>,
|
||||
}
|
||||
|
||||
impl MayaEngine {
|
||||
pub fn new(config: MayaConfig) -> Self {
|
||||
let ports = PortPool::new(config.port_from, config.port_to);
|
||||
Self {
|
||||
config,
|
||||
ports,
|
||||
next_id: AtomicU64::new(1),
|
||||
children: tokio::sync::Mutex::new(HashMap::new()),
|
||||
}
|
||||
}
|
||||
|
||||
fn validate(profile: &ProfileSpec) -> Result<()> {
|
||||
if profile.gpus.is_empty() {
|
||||
return Err(AdapterError::InvalidProfile(
|
||||
"keine GPU angegeben".to_string(),
|
||||
));
|
||||
}
|
||||
if profile.model_alias.trim().is_empty() {
|
||||
return Err(AdapterError::InvalidProfile(
|
||||
"model_alias ist leer".to_string(),
|
||||
));
|
||||
}
|
||||
if !profile.model_path.is_file() {
|
||||
return Err(AdapterError::InvalidProfile(format!(
|
||||
"Maya-Konfiguration {} existiert nicht",
|
||||
profile.model_path.display()
|
||||
)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Kommandozeile für einen Start. Der Server lauscht nur auf `127.0.0.1`.
|
||||
pub(crate) fn build_args(&self, config_path: &Path, port: u16) -> Vec<String> {
|
||||
let mut args = vec![
|
||||
self.config.script.display().to_string(),
|
||||
"--config".to_string(),
|
||||
config_path.display().to_string(),
|
||||
"--host".to_string(),
|
||||
"127.0.0.1".to_string(),
|
||||
"--port".to_string(),
|
||||
port.to_string(),
|
||||
];
|
||||
args.extend(self.config.extra_args.iter().cloned());
|
||||
args
|
||||
}
|
||||
|
||||
/// Schreibt die Konfigurationskopie der Instanz und liefert ihren Pfad und
|
||||
/// den Arbeitsordner.
|
||||
fn write_instance_config(
|
||||
&self,
|
||||
id: u64,
|
||||
port: u16,
|
||||
profile: &ProfileSpec,
|
||||
) -> Result<(PathBuf, PathBuf)> {
|
||||
let io = |path: &Path| {
|
||||
let path = path.to_path_buf();
|
||||
move |source| AdapterError::Io { path, source }
|
||||
};
|
||||
let log_dir =
|
||||
std::path::absolute(&self.config.log_dir).map_err(io(&self.config.log_dir))?;
|
||||
let workdir = log_dir.join(format!("maya-{id}"));
|
||||
std::fs::create_dir_all(&workdir).map_err(io(&workdir))?;
|
||||
|
||||
let text = std::fs::read_to_string(&profile.model_path).map_err(io(&profile.model_path))?;
|
||||
let template: Value = serde_json::from_str(&text).map_err(|e| {
|
||||
AdapterError::InvalidProfile(format!(
|
||||
"{} ist kein JSON: {e}",
|
||||
profile.model_path.display()
|
||||
))
|
||||
})?;
|
||||
let engine_log = log_dir.join(format!("instance-maya-{id}-engine.log"));
|
||||
let copy = instance_config(template, port, &engine_log, &profile.gpus, profile.context)?;
|
||||
let config_path = workdir.join("config.json");
|
||||
std::fs::write(
|
||||
&config_path,
|
||||
serde_json::to_vec_pretty(©).unwrap_or_default(),
|
||||
)
|
||||
.map_err(io(&config_path))?;
|
||||
Ok((config_path, workdir))
|
||||
}
|
||||
|
||||
async fn spawn_and_wait(
|
||||
&self,
|
||||
id: u64,
|
||||
port: u16,
|
||||
profile: &ProfileSpec,
|
||||
) -> Result<InstanceHandle> {
|
||||
std::fs::create_dir_all(&self.config.log_dir).map_err(|source| AdapterError::Io {
|
||||
path: self.config.log_dir.clone(),
|
||||
source,
|
||||
})?;
|
||||
let (config_path, workdir) = self.write_instance_config(id, port, profile)?;
|
||||
let log_path = self.config.log_dir.join(format!("instance-maya-{id}.log"));
|
||||
let io_err = |source| AdapterError::Io {
|
||||
path: log_path.clone(),
|
||||
source,
|
||||
};
|
||||
rotate_log(&log_path, self.config.log_keep).map_err(io_err)?;
|
||||
let log = std::fs::File::create(&log_path).map_err(io_err)?;
|
||||
let log_err = log.try_clone().map_err(io_err)?;
|
||||
|
||||
let mut child = Command::new(&self.config.python)
|
||||
.args(self.build_args(&config_path, port))
|
||||
.current_dir(&workdir)
|
||||
.envs(&self.config.env)
|
||||
// Eigene Prozessgruppe: Server, Engine und Hilfsprozesse lassen sich
|
||||
// gemeinsam beenden.
|
||||
.process_group(0)
|
||||
.stdin(std::process::Stdio::null())
|
||||
.stdout(log)
|
||||
.stderr(log_err)
|
||||
.kill_on_drop(true)
|
||||
.spawn()
|
||||
.map_err(|e| AdapterError::Spawn(format!("{}: {e}", self.config.python.display())))?;
|
||||
|
||||
// Nach dem Beenden liefert `child.id()` nichts mehr; der Gruppenführer
|
||||
// hat die PID der Gruppe.
|
||||
let pgid = child.id();
|
||||
let timeout = Duration::from_secs(self.config.ready_timeout_secs);
|
||||
let started = Instant::now();
|
||||
loop {
|
||||
if let Ok(Some(status)) = child.try_wait() {
|
||||
tracing::warn!(
|
||||
instance_id = id,
|
||||
exit_code = status.code(),
|
||||
"Maya endete beim Start"
|
||||
);
|
||||
if let Some(pgid) = pgid {
|
||||
terminate_group(pgid, Duration::from_secs(5)).await;
|
||||
}
|
||||
return Err(AdapterError::ExitedEarly {
|
||||
code: status.code(),
|
||||
log_tail: log_tail(&log_path, 20),
|
||||
});
|
||||
}
|
||||
if matches!(fetch_health(port).await, Some(HealthState::Ok)) {
|
||||
break;
|
||||
}
|
||||
if started.elapsed() >= timeout {
|
||||
tracing::warn!(
|
||||
instance_id = id,
|
||||
seconds = self.config.ready_timeout_secs,
|
||||
"Maya wurde nicht rechtzeitig bereit"
|
||||
);
|
||||
let _ = child.start_kill();
|
||||
let _ = child.wait().await;
|
||||
if let Some(pgid) = pgid {
|
||||
terminate_group(pgid, Duration::from_secs(5)).await;
|
||||
}
|
||||
return Err(AdapterError::NotReady {
|
||||
seconds: self.config.ready_timeout_secs,
|
||||
log_tail: log_tail(&log_path, 20),
|
||||
});
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(500)).await;
|
||||
}
|
||||
tracing::info!(
|
||||
instance_id = id,
|
||||
port,
|
||||
duration_ms = started.elapsed().as_millis() as u64,
|
||||
"Maya ist bereit"
|
||||
);
|
||||
|
||||
let pid = child.id();
|
||||
self.children
|
||||
.lock()
|
||||
.await
|
||||
.insert(id, Managed { child, port });
|
||||
Ok(InstanceHandle { id, pid, port })
|
||||
}
|
||||
|
||||
async fn vram_mb(&self, pgid: u32) -> Option<u64> {
|
||||
let output = tokio::time::timeout(
|
||||
Duration::from_secs(5),
|
||||
Command::new(&self.config.nvidia_smi)
|
||||
.args([
|
||||
"--query-compute-apps=pid,used_memory",
|
||||
"--format=csv,noheader,nounits",
|
||||
])
|
||||
.output(),
|
||||
)
|
||||
.await
|
||||
.ok()?
|
||||
.ok()?;
|
||||
if !output.status.success() {
|
||||
return None;
|
||||
}
|
||||
let text = String::from_utf8_lossy(&output.stdout);
|
||||
let pids = group_pids(pgid);
|
||||
let mut total = None;
|
||||
for pid in pids {
|
||||
if let Some(mb) = parse_vram_mb(&text, pid) {
|
||||
*total.get_or_insert(0) += mb;
|
||||
}
|
||||
}
|
||||
total
|
||||
}
|
||||
}
|
||||
|
||||
/// Antwort von `GET /health`.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum HealthState {
|
||||
Ok,
|
||||
/// `reloading` oder `updating`: Anfragen bekommen 503.
|
||||
Busy,
|
||||
}
|
||||
|
||||
/// Fragt `GET /health` ab. `None` bei Verbindungsfehler oder Unlesbarem.
|
||||
pub(crate) async fn fetch_health(port: u16) -> Option<HealthState> {
|
||||
let client = reqwest::Client::builder()
|
||||
.timeout(Duration::from_secs(2))
|
||||
.build()
|
||||
.ok()?;
|
||||
let response = client
|
||||
.get(format!("http://127.0.0.1:{port}/health"))
|
||||
.send()
|
||||
.await
|
||||
.ok()?;
|
||||
if !response.status().is_success() {
|
||||
return None;
|
||||
}
|
||||
parse_health(&response.text().await.ok()?)
|
||||
}
|
||||
|
||||
pub(crate) fn parse_health(text: &str) -> Option<HealthState> {
|
||||
let value: Value = serde_json::from_str(text).ok()?;
|
||||
match value.get("status")?.as_str()? {
|
||||
"ok" => Some(HealthState::Ok),
|
||||
_ => Some(HealthState::Busy),
|
||||
}
|
||||
}
|
||||
|
||||
/// Setzt Port, Log, GPUs und Kontext in der Kopie der Maya-Konfiguration und
|
||||
/// entfernt, was die Instanz stören würde (Arbeitsordner, API-Schlüssel).
|
||||
pub(crate) fn instance_config(
|
||||
template: Value,
|
||||
port: u16,
|
||||
engine_log: &Path,
|
||||
gpus: &[u32],
|
||||
context: Option<u32>,
|
||||
) -> Result<Value> {
|
||||
let Value::Object(mut map) = template else {
|
||||
return Err(AdapterError::InvalidProfile(
|
||||
"Maya-Konfiguration ist kein JSON-Objekt".to_string(),
|
||||
));
|
||||
};
|
||||
if !map.contains_key("exe") {
|
||||
return Err(AdapterError::InvalidProfile(
|
||||
"Maya-Konfiguration ohne \"exe\"".to_string(),
|
||||
));
|
||||
}
|
||||
map.remove("cwd");
|
||||
// Der Server lauscht nur lokal; ein Schlüssel aus der Vorlage käme beim
|
||||
// Gateway nicht an und würde jede Anfrage mit 401 abweisen.
|
||||
map.remove("api_key");
|
||||
map.insert("port".to_string(), Value::from(port));
|
||||
map.insert(
|
||||
"log".to_string(),
|
||||
Value::String(engine_log.display().to_string()),
|
||||
);
|
||||
map.insert(
|
||||
"gpu".to_string(),
|
||||
Value::Array(gpus.iter().map(|g| Value::from(*g)).collect()),
|
||||
);
|
||||
if let Some(context) = context
|
||||
&& let Some(Value::Array(args)) = map.get_mut("args")
|
||||
{
|
||||
match args.iter().position(|a| a == "--max-context") {
|
||||
Some(i) if i + 1 < args.len() => args[i + 1] = Value::String(context.to_string()),
|
||||
_ => {
|
||||
args.push(Value::String("--max-context".to_string()));
|
||||
args.push(Value::String(context.to_string()));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(Value::Object(map))
|
||||
}
|
||||
|
||||
/// Alle Prozesse der Prozessgruppe `pgid` (aus `/proc`).
|
||||
fn group_pids(pgid: u32) -> Vec<u32> {
|
||||
let Ok(dir) = std::fs::read_dir("/proc") else {
|
||||
return vec![pgid];
|
||||
};
|
||||
let mut pids = Vec::new();
|
||||
for entry in dir.flatten() {
|
||||
let Some(pid) = entry
|
||||
.file_name()
|
||||
.to_str()
|
||||
.and_then(|n| n.parse::<u32>().ok())
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
if let Ok(stat) = std::fs::read_to_string(entry.path().join("stat"))
|
||||
&& parse_pgrp(&stat) == Some(pgid)
|
||||
{
|
||||
pids.push(pid);
|
||||
}
|
||||
}
|
||||
pids
|
||||
}
|
||||
|
||||
/// Liest die Prozessgruppe aus `/proc/<pid>/stat` (der Name in Klammern darf
|
||||
/// Leerzeichen enthalten, deshalb ab der letzten Klammer).
|
||||
pub(crate) fn parse_pgrp(stat: &str) -> Option<u32> {
|
||||
let rest = &stat[stat.rfind(')')? + 1..];
|
||||
// Felder danach: Status, Eltern-PID, Prozessgruppe, ...
|
||||
rest.split_whitespace().nth(2)?.parse().ok()
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Engine for MayaEngine {
|
||||
fn describe(&self) -> EngineInfo {
|
||||
EngineInfo {
|
||||
name: "maya".to_string(),
|
||||
mode: Mode::Managed,
|
||||
// Gemessen: Chat und Streaming. Embeddings, Tool Calling und Bilder
|
||||
// (Maya kann Bilder lesen) sind über das Gateway nicht geprüft.
|
||||
capabilities: Capabilities {
|
||||
chat: true,
|
||||
completions: false,
|
||||
embeddings: false,
|
||||
streaming: true,
|
||||
tool_calling: false,
|
||||
images: false,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
async fn discover(&self) -> Result<Vec<DiscoveredArtifact>> {
|
||||
let roots = self.config.config_roots.clone();
|
||||
tokio::task::spawn_blocking(move || scan_configs(&roots))
|
||||
.await
|
||||
.map_err(|e| AdapterError::Spawn(format!("Suche abgebrochen: {e}")))
|
||||
}
|
||||
|
||||
async fn start(&self, profile: &ProfileSpec) -> Result<InstanceHandle> {
|
||||
Self::validate(profile)?;
|
||||
let port = self.ports.acquire()?;
|
||||
let id = self.next_id.fetch_add(1, Ordering::SeqCst);
|
||||
match self.spawn_and_wait(id, port, profile).await {
|
||||
Ok(handle) => Ok(handle),
|
||||
Err(e) => {
|
||||
self.ports.release(port);
|
||||
Err(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn stop(&self, instance: &InstanceHandle, grace: Duration) -> Result<()> {
|
||||
let managed = self.children.lock().await.remove(&instance.id);
|
||||
let Some(mut managed) = managed else {
|
||||
return Ok(());
|
||||
};
|
||||
let pgid = managed.child.id();
|
||||
if let Some(pid) = pgid {
|
||||
sigterm(pid);
|
||||
}
|
||||
if tokio::time::timeout(grace, managed.child.wait())
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
tracing::warn!(
|
||||
instance_id = instance.id,
|
||||
"Maya reagierte nicht auf SIGTERM, wird beendet"
|
||||
);
|
||||
managed
|
||||
.child
|
||||
.kill()
|
||||
.await
|
||||
.map_err(|e| AdapterError::Stop(e.to_string()))?;
|
||||
}
|
||||
// Engine und Hilfsprozesse, die den Server überlebt haben.
|
||||
if let Some(pgid) = pgid {
|
||||
terminate_group(pgid, Duration::from_secs(5).min(grace)).await;
|
||||
}
|
||||
self.ports.release(managed.port);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn health(&self, instance: &InstanceHandle) -> Health {
|
||||
let port = {
|
||||
let mut children = self.children.lock().await;
|
||||
let Some(managed) = children.get_mut(&instance.id) else {
|
||||
return Health::Gone;
|
||||
};
|
||||
match managed.child.try_wait() {
|
||||
Ok(Some(status)) => {
|
||||
tracing::warn!(
|
||||
instance_id = instance.id,
|
||||
exit_code = status.code(),
|
||||
"Maya ist von selbst beendet"
|
||||
);
|
||||
let port = managed.port;
|
||||
let pgid = instance.pid;
|
||||
children.remove(&instance.id);
|
||||
self.ports.release(port);
|
||||
if let Some(pgid) = pgid {
|
||||
// Die Engine kann den Server überleben.
|
||||
terminate_group(pgid, Duration::from_secs(5)).await;
|
||||
}
|
||||
return Health::Gone;
|
||||
}
|
||||
Ok(None) => managed.port,
|
||||
Err(e) => return Health::Unhealthy(e.to_string()),
|
||||
}
|
||||
};
|
||||
match fetch_health(port).await {
|
||||
Some(HealthState::Ok) => Health::Ready,
|
||||
Some(HealthState::Busy) => Health::Starting,
|
||||
None => Health::Unhealthy("keine Antwort".to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
fn endpoint(&self, instance: &InstanceHandle) -> Endpoint {
|
||||
Endpoint {
|
||||
base_url: format!("http://127.0.0.1:{}", instance.port),
|
||||
protocol: Protocol::OpenAi,
|
||||
// Maya nimmt jeden Modellnamen an (gemessen: es hat nur ein Modell).
|
||||
upstream_model: None,
|
||||
}
|
||||
}
|
||||
|
||||
async fn measure(&self, instance: &InstanceHandle) -> Usage {
|
||||
let Some(pgid) = instance.pid else {
|
||||
return Usage::default();
|
||||
};
|
||||
let ram: u64 = group_pids(pgid)
|
||||
.into_iter()
|
||||
.filter_map(|pid| {
|
||||
std::fs::read_to_string(format!("/proc/{pid}/status"))
|
||||
.ok()
|
||||
.and_then(|t| parse_rss_mb(&t))
|
||||
})
|
||||
.sum();
|
||||
Usage {
|
||||
vram_mb: self.vram_mb(pgid).await,
|
||||
ram_mb: (ram > 0).then_some(ram),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Sucht Maya-Konfigurationen (`*.json` mit `exe` und `model_name`) direkt in
|
||||
/// den Ordnern. Die Größe ist die des Modellordners (`--glm-pack`), falls er
|
||||
/// lesbar ist. Verändert nichts.
|
||||
pub(crate) fn scan_configs(roots: &[PathBuf]) -> Vec<DiscoveredArtifact> {
|
||||
let mut found = Vec::new();
|
||||
for root in roots {
|
||||
let Ok(entries) = std::fs::read_dir(root) else {
|
||||
continue;
|
||||
};
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
if path.extension().and_then(|e| e.to_str()) != Some("json") {
|
||||
continue;
|
||||
}
|
||||
let Some(value) = std::fs::read_to_string(&path)
|
||||
.ok()
|
||||
.and_then(|t| serde_json::from_str::<Value>(&t).ok())
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let (Some(_), Some(name)) = (
|
||||
value.get("exe"),
|
||||
value.get("model_name").and_then(Value::as_str),
|
||||
) else {
|
||||
continue;
|
||||
};
|
||||
let quantization = value
|
||||
.pointer("/installer/quant")
|
||||
.and_then(Value::as_str)
|
||||
.map(str::to_string);
|
||||
let pack = value.get("args").and_then(Value::as_array).and_then(|a| {
|
||||
let i = a.iter().position(|x| x == "--glm-pack")?;
|
||||
a.get(i + 1)?.as_str().map(PathBuf::from)
|
||||
});
|
||||
found.push(DiscoveredArtifact {
|
||||
name: name.to_string(),
|
||||
path,
|
||||
quantization,
|
||||
size_bytes: pack.map(|p| dir_size(&p, 0)).unwrap_or(0),
|
||||
});
|
||||
}
|
||||
}
|
||||
found.sort_by(|a, b| a.name.cmp(&b.name));
|
||||
found
|
||||
}
|
||||
|
||||
fn dir_size(dir: &Path, depth: usize) -> u64 {
|
||||
if depth > 4 {
|
||||
return 0;
|
||||
}
|
||||
let Ok(entries) = std::fs::read_dir(dir) else {
|
||||
return 0;
|
||||
};
|
||||
entries
|
||||
.flatten()
|
||||
.map(|e| match e.metadata() {
|
||||
Ok(m) if m.is_dir() => dir_size(&e.path(), depth + 1),
|
||||
Ok(m) => m.len(),
|
||||
Err(_) => 0,
|
||||
})
|
||||
.sum()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
fn vorlage() -> Value {
|
||||
json!({
|
||||
"exe": "/srv/apps/maya/build/maya",
|
||||
"args": ["--glm-pack", "/pack", "--max-context", "32768"],
|
||||
"cwd": "/srv/apps/maya",
|
||||
"api_key": "geheim",
|
||||
"port": 8083,
|
||||
"log": "/alt.log",
|
||||
"gpu": [0, 1],
|
||||
"model_name": "glm-5.3-flash"
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn konfigurationskopie_setzt_port_log_gpus_und_entfernt_cwd_und_schluessel() {
|
||||
let copy = instance_config(vorlage(), 18201, Path::new("/x/log"), &[1], None).unwrap();
|
||||
assert_eq!(copy["port"], 18201);
|
||||
assert_eq!(copy["log"], "/x/log");
|
||||
assert_eq!(copy["gpu"], json!([1]));
|
||||
assert!(copy.get("cwd").is_none());
|
||||
assert!(copy.get("api_key").is_none());
|
||||
assert_eq!(copy["args"][3], "32768", "ohne Kontextangabe unverändert");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kontext_ersetzt_den_wert_in_den_argumenten() {
|
||||
let copy = instance_config(vorlage(), 1, Path::new("/l"), &[0], Some(8192)).unwrap();
|
||||
assert_eq!(copy["args"][3], "8192");
|
||||
let mut ohne = vorlage();
|
||||
ohne["args"] = json!(["--glm-pack", "/pack"]);
|
||||
let copy = instance_config(ohne, 1, Path::new("/l"), &[0], Some(4096)).unwrap();
|
||||
assert_eq!(
|
||||
copy["args"],
|
||||
json!(["--glm-pack", "/pack", "--max-context", "4096"])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vorlage_ohne_exe_oder_kein_objekt_wird_abgelehnt() {
|
||||
assert!(instance_config(json!({"port": 1}), 1, Path::new("/l"), &[0], None).is_err());
|
||||
assert!(instance_config(json!([1]), 1, Path::new("/l"), &[0], None).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kommandozeile_bindet_an_localhost() {
|
||||
let engine = MayaEngine::new(MayaConfig::default());
|
||||
let args = engine.build_args(Path::new("/c.json"), 18205);
|
||||
let line = args.join(" ");
|
||||
assert!(line.contains("--host 127.0.0.1"), "{line}");
|
||||
assert!(line.contains("--port 18205"), "{line}");
|
||||
assert!(line.contains("--config /c.json"), "{line}");
|
||||
assert!(!line.contains("api-key"), "{line}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn health_antwort_wird_gelesen() {
|
||||
assert_eq!(
|
||||
parse_health(r#"{"status":"ok","unloaded":true}"#),
|
||||
Some(HealthState::Ok)
|
||||
);
|
||||
assert_eq!(
|
||||
parse_health(r#"{"status":"reloading"}"#),
|
||||
Some(HealthState::Busy)
|
||||
);
|
||||
assert_eq!(
|
||||
parse_health(r#"{"status":"updating"}"#),
|
||||
Some(HealthState::Busy)
|
||||
);
|
||||
assert_eq!(parse_health("kein json"), None);
|
||||
assert_eq!(parse_health(r#"{"x":1}"#), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prozessgruppe_wird_auch_bei_klammern_im_namen_gelesen() {
|
||||
assert_eq!(parse_pgrp("4237 (maya.py) S 1 4237 4237 0 -1"), Some(4237));
|
||||
assert_eq!(parse_pgrp("5 (a (b) c) S 4237 4237 4237 0"), Some(4237));
|
||||
assert_eq!(parse_pgrp("kaputt"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn konfiguration_hat_standardwerte_und_lehnt_unbekanntes_ab() {
|
||||
let c: MayaConfig = toml::from_str("ready_timeout_secs = 5").unwrap();
|
||||
assert_eq!(c.ready_timeout_secs, 5);
|
||||
assert_eq!(c.port_from, 18200);
|
||||
assert!(toml::from_str::<MayaConfig>("tippfehler = 1").is_err());
|
||||
}
|
||||
}
|
||||
118
crates/nexus-adapter/tests/fake_maya.py
Executable file
118
crates/nexus-adapter/tests/fake_maya.py
Executable file
@ -0,0 +1,118 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Attrappe für `maya.py`, nur für Tests von nexus-adapter.
|
||||
|
||||
Versteht `--config <json> --host H --port P` wie Maya und verhält sich nach
|
||||
FAKE_MAYA_MODE (wie das echte Maya öffnet sie den Port erst, wenn das Modell
|
||||
"geladen" ist):
|
||||
ok öffnet den Port nach FAKE_MAYA_LOAD_SECONDS; /health liefert status ok
|
||||
crash schreibt einen Fehler nach stderr, Exit-Code 3
|
||||
hang öffnet den Port nie
|
||||
stubborn wie ok, ignoriert aber SIGTERM
|
||||
orphan wie ok; startet einen Kindprozess ("Engine") und lässt ihn bei
|
||||
SIGTERM zurück, wie es Ollamas Runner taten
|
||||
busy Port offen, aber /health meldet status reloading
|
||||
Außerdem /v1/models und /v1/chat/completions (mit und ohne SSE, mit
|
||||
reasoning_content und Keep-alive-Zeile wie Maya).
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
|
||||
args = sys.argv[1:]
|
||||
|
||||
|
||||
def opt(name):
|
||||
return args[args.index(name) + 1] if name in args else None
|
||||
|
||||
|
||||
mode = os.environ.get("FAKE_MAYA_MODE", "ok")
|
||||
config = json.load(open(opt("--config")))
|
||||
print("fake-maya: pid", os.getpid(), flush=True)
|
||||
print("fake-maya: cwd", os.getcwd(), flush=True)
|
||||
print("fake-maya: args", " ".join(args), flush=True)
|
||||
print("fake-maya: config-port", config.get("port"), flush=True)
|
||||
print("fake-maya: config-gpu", json.dumps(config.get("gpu")), flush=True)
|
||||
print("fake-maya: config-api-key", "api_key" in config, flush=True)
|
||||
print("fake-maya: config-max-context", config.get("args"), flush=True)
|
||||
|
||||
if mode == "crash":
|
||||
print("fake-maya: error: engine did not start", file=sys.stderr, flush=True)
|
||||
sys.exit(3)
|
||||
|
||||
if mode == "orphan":
|
||||
child = subprocess.Popen(["sleep", "300"])
|
||||
print("fake-maya: engine pid", child.pid, flush=True)
|
||||
|
||||
if mode == "stubborn":
|
||||
signal.signal(signal.SIGTERM, signal.SIG_IGN)
|
||||
else:
|
||||
signal.signal(signal.SIGTERM, lambda *_: os._exit(0))
|
||||
|
||||
load_seconds = float(os.environ.get("FAKE_MAYA_LOAD_SECONDS", "1"))
|
||||
if mode == "hang":
|
||||
time.sleep(3600)
|
||||
time.sleep(load_seconds) # der echte Server lauscht erst nach dem Laden
|
||||
|
||||
ANSWER = ["Hallo", " vom", " Maya-", "Modell."]
|
||||
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
def log_message(self, *_):
|
||||
pass
|
||||
|
||||
def _send_json(self, code, payload):
|
||||
body = json.dumps(payload).encode()
|
||||
self.send_response(code)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def do_GET(self):
|
||||
if self.path == "/health":
|
||||
status = "reloading" if mode == "busy" else "ok"
|
||||
self._send_json(200, {"status": status, "model": "fake-maya", "unloaded": False})
|
||||
elif self.path == "/v1/models":
|
||||
self._send_json(200, {"object": "list", "data": [{"id": "fake-maya", "object": "model"}]})
|
||||
else:
|
||||
self._send_json(404, {})
|
||||
|
||||
def do_POST(self):
|
||||
length = int(self.headers.get("Content-Length", "0"))
|
||||
request = json.loads(self.rfile.read(length) or b"{}")
|
||||
if self.path != "/v1/chat/completions":
|
||||
self._send_json(404, {})
|
||||
return
|
||||
model = request.get("model", "fake-maya")
|
||||
if request.get("stream"):
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "text/event-stream")
|
||||
self.end_headers()
|
||||
self.wfile.write(b": keep-alive\n\n")
|
||||
for i, part in enumerate(ANSWER):
|
||||
delta = {"reasoning_content": "denke"} if i == 0 else {"content": part}
|
||||
chunk = {"id": "chatcmpl-fake", "object": "chat.completion.chunk", "created": 1, "model": model,
|
||||
"choices": [{"index": 0, "delta": delta, "finish_reason": None}]}
|
||||
self.wfile.write(("data: " + json.dumps(chunk) + "\n\n").encode())
|
||||
self.wfile.flush()
|
||||
time.sleep(0.05)
|
||||
last = {"id": "chatcmpl-fake", "object": "chat.completion.chunk", "created": 1, "model": model,
|
||||
"choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}],
|
||||
"usage": {"prompt_tokens": 3, "completion_tokens": 4, "total_tokens": 7}}
|
||||
self.wfile.write(("data: " + json.dumps(last) + "\n\ndata: [DONE]\n\n").encode())
|
||||
self.wfile.flush()
|
||||
else:
|
||||
self._send_json(200, {
|
||||
"id": "chatcmpl-fake", "object": "chat.completion", "created": 1, "model": model,
|
||||
"choices": [{"index": 0, "finish_reason": "stop",
|
||||
"message": {"role": "assistant", "content": "".join(ANSWER),
|
||||
"reasoning_content": "denke"}}],
|
||||
"usage": {"prompt_tokens": 3, "completion_tokens": 4, "total_tokens": 7},
|
||||
})
|
||||
|
||||
|
||||
ThreadingHTTPServer((opt("--host"), int(opt("--port"))), Handler).serve_forever()
|
||||
266
crates/nexus-adapter/tests/maya_process.rs
Normal file
266
crates/nexus-adapter/tests/maya_process.rs
Normal file
@ -0,0 +1,266 @@
|
||||
//! Integrationstests des Maya-Adapters mit echten Prozessen.
|
||||
//!
|
||||
//! Statt `maya.py` läuft `tests/fake_maya.py`. Der Test prüft Prozessstart,
|
||||
//! Konfigurationskopie, Bereitschaft über `/health`, Beenden samt
|
||||
//! Prozessgruppe und Fehlerfälle. Er prüft **nicht**, ob das echte Maya lädt
|
||||
//! (das ist auf srv04 getrennt gemessen, `docs/m2-maya-messung.md`).
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicU16, AtomicU32, Ordering};
|
||||
use std::time::Duration;
|
||||
|
||||
use nexus_adapter::{
|
||||
AdapterError, Engine, Health, MayaConfig, MayaEngine, ProfileSpec, process_exists,
|
||||
};
|
||||
|
||||
static PORT_BLOCK: AtomicU16 = AtomicU16::new(19700);
|
||||
static DIR_COUNTER: AtomicU32 = AtomicU32::new(0);
|
||||
|
||||
struct Fixture {
|
||||
dir: PathBuf,
|
||||
config: MayaConfig,
|
||||
maya_config: PathBuf,
|
||||
}
|
||||
|
||||
impl Drop for Fixture {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.dir);
|
||||
}
|
||||
}
|
||||
|
||||
fn fixture(mode: &str, ready_timeout_secs: u64) -> Fixture {
|
||||
let n = DIR_COUNTER.fetch_add(1, Ordering::SeqCst);
|
||||
let dir = std::env::temp_dir().join(format!("nexus-maya-it-{}-{n}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let maya_config = dir.join("maya-test.json");
|
||||
std::fs::write(
|
||||
&maya_config,
|
||||
r#"{"exe":"/nicht/da/maya","args":["--glm-pack","/pack","--max-context","32768"],
|
||||
"cwd":"/nicht/da","api_key":"geheim","port":8083,"gpu":[0,1],
|
||||
"model_name":"fake-maya","installer":{"quant":"IQ1_S"}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let from = PORT_BLOCK.fetch_add(10, Ordering::SeqCst);
|
||||
let config = MayaConfig {
|
||||
python: PathBuf::from("python3"),
|
||||
script: Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fake_maya.py"),
|
||||
config_roots: vec![dir.clone()],
|
||||
port_from: from,
|
||||
port_to: from + 9,
|
||||
ready_timeout_secs,
|
||||
log_dir: dir.join("logs"),
|
||||
env: BTreeMap::from([("FAKE_MAYA_MODE".to_string(), mode.to_string())]),
|
||||
nvidia_smi: dir.join("kein-nvidia-smi"),
|
||||
..MayaConfig::default()
|
||||
};
|
||||
Fixture {
|
||||
dir,
|
||||
config,
|
||||
maya_config,
|
||||
}
|
||||
}
|
||||
|
||||
fn profile(f: &Fixture) -> ProfileSpec {
|
||||
ProfileSpec {
|
||||
model_alias: "glm".to_string(),
|
||||
model_path: f.maya_config.clone(),
|
||||
gpus: vec![1],
|
||||
context: Some(8192),
|
||||
extra_args: vec![],
|
||||
}
|
||||
}
|
||||
|
||||
fn log_of(f: &Fixture, id: u64) -> String {
|
||||
std::fs::read_to_string(f.dir.join(format!("logs/instance-maya-{id}.log"))).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn number_after(log: &str, prefix: &str) -> u32 {
|
||||
log.lines()
|
||||
.find_map(|l| l.strip_prefix(prefix))
|
||||
.and_then(|p| p.trim().parse().ok())
|
||||
.unwrap_or_else(|| panic!("{prefix} nicht im Log:\n{log}"))
|
||||
}
|
||||
|
||||
async fn wait_until_gone(pid: u32) -> bool {
|
||||
for _ in 0..80 {
|
||||
if !process_exists(pid) {
|
||||
return true;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn start_bereit_konfigurationskopie_und_stopp() {
|
||||
let f = fixture("ok", 20);
|
||||
let engine = MayaEngine::new(f.config.clone());
|
||||
let inst = engine.start(&profile(&f)).await.expect("Start");
|
||||
let pid = inst.pid.expect("PID");
|
||||
|
||||
assert_eq!(engine.health(&inst).await, Health::Ready);
|
||||
assert_eq!(
|
||||
engine.endpoint(&inst).base_url,
|
||||
format!("http://127.0.0.1:{}", inst.port)
|
||||
);
|
||||
|
||||
let log = log_of(&f, inst.id);
|
||||
assert!(log.contains("--host 127.0.0.1"), "{log}");
|
||||
assert!(log.contains(&format!("--port {}", inst.port)), "{log}");
|
||||
assert!(
|
||||
log.contains(&format!("config-port {}", inst.port)),
|
||||
"Port in der Kopie: {log}"
|
||||
);
|
||||
assert!(log.contains("config-gpu [1]"), "{log}");
|
||||
assert!(log.contains("config-api-key False"), "{log}");
|
||||
assert!(
|
||||
log.contains("'--max-context', '8192'"),
|
||||
"Kontext in der Kopie: {log}"
|
||||
);
|
||||
assert!(log.contains("maya-1"), "Arbeitsordner je Instanz: {log}");
|
||||
|
||||
// Die Vorlage bleibt unverändert.
|
||||
let original = std::fs::read_to_string(&f.maya_config).unwrap();
|
||||
assert!(original.contains("geheim") && original.contains("8083"));
|
||||
|
||||
let usage = engine.measure(&inst).await;
|
||||
assert!(usage.ram_mb.is_some(), "RAM muss messbar sein");
|
||||
assert_eq!(usage.vram_mb, None, "ohne nvidia-smi kein VRAM-Wert");
|
||||
|
||||
engine.stop(&inst, Duration::from_secs(5)).await.unwrap();
|
||||
assert!(wait_until_gone(pid).await, "Prozess läuft noch");
|
||||
assert_eq!(engine.health(&inst).await, Health::Gone);
|
||||
engine.stop(&inst, Duration::from_secs(1)).await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn kindprozess_der_den_server_ueberlebt_wird_mit_beendet() {
|
||||
let f = fixture("orphan", 20);
|
||||
let engine = MayaEngine::new(f.config.clone());
|
||||
let inst = engine.start(&profile(&f)).await.unwrap();
|
||||
let engine_pid = number_after(&log_of(&f, inst.id), "fake-maya: engine pid ");
|
||||
assert!(process_exists(engine_pid));
|
||||
engine.stop(&inst, Duration::from_secs(5)).await.unwrap();
|
||||
assert!(
|
||||
wait_until_gone(engine_pid).await,
|
||||
"die Engine blieb zurück (Prozessgruppe nicht beendet)"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn dauerhaft_beschaeftigter_server_gilt_nicht_als_bereit() {
|
||||
// Wie beim echten Maya (Neuladen, Update): Port offen, aber nicht bereit.
|
||||
let f = fixture("busy", 2);
|
||||
let engine = MayaEngine::new(f.config.clone());
|
||||
let err = engine.start(&profile(&f)).await.unwrap_err();
|
||||
assert!(matches!(err, AdapterError::NotReady { .. }), "{err}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn von_aussen_beendeter_prozess_wird_als_gone_erkannt() {
|
||||
let f = fixture("ok", 20);
|
||||
let engine = MayaEngine::new(f.config.clone());
|
||||
let inst = engine.start(&profile(&f)).await.unwrap();
|
||||
let pid = inst.pid.unwrap();
|
||||
// SAFETY: beendet gezielt den Prozess, den dieser Test selbst gestartet hat.
|
||||
assert_eq!(unsafe { libc::kill(pid as i32, libc::SIGKILL) }, 0);
|
||||
let mut health = engine.health(&inst).await;
|
||||
for _ in 0..50 {
|
||||
if health == Health::Gone {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
health = engine.health(&inst).await;
|
||||
}
|
||||
assert_eq!(health, Health::Gone);
|
||||
assert!(wait_until_gone(pid).await);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn absturz_beim_start_liefert_log_ende_und_exit_code() {
|
||||
let f = fixture("crash", 20);
|
||||
let engine = MayaEngine::new(f.config.clone());
|
||||
match engine.start(&profile(&f)).await.unwrap_err() {
|
||||
AdapterError::ExitedEarly { code, log_tail } => {
|
||||
assert_eq!(code, Some(3));
|
||||
assert!(log_tail.contains("engine did not start"), "{log_tail}");
|
||||
}
|
||||
other => panic!("falscher Fehler: {other}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn nie_bereit_fuehrt_zu_zeitueberschreitung_und_beendet_den_prozess() {
|
||||
let f = fixture("hang", 1);
|
||||
let engine = MayaEngine::new(f.config.clone());
|
||||
let err = engine.start(&profile(&f)).await.unwrap_err();
|
||||
assert!(
|
||||
matches!(err, AdapterError::NotReady { seconds: 1, .. }),
|
||||
"{err}"
|
||||
);
|
||||
let pid = number_after(&log_of(&f, 1), "fake-maya: pid ");
|
||||
assert!(wait_until_gone(pid).await, "Prozess blieb zurück");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sturer_prozess_wird_nach_der_gnadenfrist_beendet() {
|
||||
let f = fixture("stubborn", 20);
|
||||
let engine = MayaEngine::new(f.config.clone());
|
||||
let inst = engine.start(&profile(&f)).await.unwrap();
|
||||
let pid = inst.pid.unwrap();
|
||||
let t0 = std::time::Instant::now();
|
||||
engine
|
||||
.stop(&inst, Duration::from_millis(400))
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(t0.elapsed() < Duration::from_secs(5));
|
||||
assert!(wait_until_gone(pid).await, "SIGTERM ignoriert, läuft noch");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn fehlendes_programm_ist_spawn_fehler_und_gibt_den_port_frei() {
|
||||
let mut f = fixture("ok", 5);
|
||||
f.config.python = f.dir.join("gibt-es-nicht");
|
||||
f.config.port_to = f.config.port_from; // genau ein Port
|
||||
let engine = MayaEngine::new(f.config.clone());
|
||||
for _ in 0..2 {
|
||||
let err = engine.start(&profile(&f)).await.unwrap_err();
|
||||
assert!(matches!(err, AdapterError::Spawn(_)), "{err}");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn unbrauchbares_profil_wird_vor_dem_start_abgelehnt() {
|
||||
let f = fixture("ok", 5);
|
||||
let engine = MayaEngine::new(f.config.clone());
|
||||
let mut p = profile(&f);
|
||||
p.model_path = f.dir.join("fehlt.json");
|
||||
assert!(matches!(
|
||||
engine.start(&p).await,
|
||||
Err(AdapterError::InvalidProfile(_))
|
||||
));
|
||||
let mut p = profile(&f);
|
||||
std::fs::write(&p.model_path, "kein json").unwrap();
|
||||
assert!(matches!(
|
||||
engine.start(&p).await,
|
||||
Err(AdapterError::InvalidProfile(_))
|
||||
));
|
||||
p.gpus.clear();
|
||||
assert!(matches!(
|
||||
engine.start(&p).await,
|
||||
Err(AdapterError::InvalidProfile(_))
|
||||
));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn discover_findet_die_konfiguration() {
|
||||
let f = fixture("ok", 5);
|
||||
std::fs::write(f.dir.join("anderes.json"), r#"{"x":1}"#).unwrap();
|
||||
let engine = MayaEngine::new(f.config.clone());
|
||||
let found = engine.discover().await.unwrap();
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert_eq!(found[0].name, "fake-maya");
|
||||
assert_eq!(found[0].quantization.as_deref(), Some("IQ1_S"));
|
||||
assert_eq!(found[0].path, f.maya_config);
|
||||
}
|
||||
@ -23,6 +23,8 @@ pub struct Config {
|
||||
pub llama_cpp: toml::Table,
|
||||
/// Rohe Einstellungen des Ollama-Adapters (Abschnitt `[ollama]`).
|
||||
pub ollama: toml::Table,
|
||||
/// Rohe Einstellungen des Maya-Adapters (Abschnitt `[maya]`).
|
||||
pub maya: toml::Table,
|
||||
}
|
||||
|
||||
impl Default for Config {
|
||||
@ -33,6 +35,7 @@ impl Default for Config {
|
||||
log_level: "info".to_string(),
|
||||
llama_cpp: toml::Table::new(),
|
||||
ollama: toml::Table::new(),
|
||||
maya: toml::Table::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -11,14 +11,16 @@ use crate::{Store, db};
|
||||
pub const LLAMA_CPP: &str = "llama.cpp";
|
||||
/// Name der Engine-Zeile für Ollama.
|
||||
pub const OLLAMA: &str = "ollama";
|
||||
/// Name der Engine-Zeile für Maya.
|
||||
pub const MAYA: &str = "maya";
|
||||
|
||||
/// Eingabe für `register_llm`: ein Sprachmodell mit einem Startprofil.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct NewLlm {
|
||||
pub name: String,
|
||||
/// Engine: `llama.cpp` oder `ollama`.
|
||||
/// Engine: `llama.cpp`, `ollama` oder `maya`.
|
||||
pub engine: String,
|
||||
/// Pfad der Modelldatei (llama.cpp) oder Modellname der Engine (Ollama, zum Beispiel `qwen3:0.6b`).
|
||||
/// Pfad der Modelldatei (llama.cpp) Modellname der Engine (Ollama, zum Beispiel `qwen3:0.6b`) oder Maya-Konfigurationsdatei (JSON).
|
||||
pub path: PathBuf,
|
||||
pub quantization: Option<String>,
|
||||
pub size_bytes: Option<i64>,
|
||||
@ -67,9 +69,9 @@ impl Store {
|
||||
if new.gpus.is_empty() {
|
||||
return Err(Error::Db("mindestens eine GPU angeben".to_string()));
|
||||
}
|
||||
if new.engine != LLAMA_CPP && new.engine != OLLAMA {
|
||||
if new.engine != LLAMA_CPP && new.engine != OLLAMA && new.engine != MAYA {
|
||||
return Err(Error::Db(format!(
|
||||
"unbekannte Engine \"{}\" (llama.cpp oder ollama)",
|
||||
"unbekannte Engine \"{}\" (llama.cpp, ollama oder maya)",
|
||||
new.engine
|
||||
)));
|
||||
}
|
||||
@ -291,6 +293,26 @@ mod tests {
|
||||
assert_eq!(plan.extra_args, vec!["--flash-attn".to_string()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maya_modell_hat_die_konfigurationsdatei_als_pfad_und_eigene_engine() {
|
||||
let mut store = Store::open_in_memory().unwrap();
|
||||
let mut n = neu("glm");
|
||||
n.engine = "maya".to_string();
|
||||
n.path = PathBuf::from("/srv/apps/maya/maya-test.json");
|
||||
n.gpus = vec![0, 1];
|
||||
store.register_llm(&n).unwrap();
|
||||
let plan = store.start_plan("glm").unwrap().unwrap();
|
||||
assert_eq!(plan.engine_name, "maya");
|
||||
assert_eq!(
|
||||
plan.model_path,
|
||||
PathBuf::from("/srv/apps/maya/maya-test.json")
|
||||
);
|
||||
assert_eq!(plan.gpus, vec![0, 1]);
|
||||
let mut falsch = neu("x");
|
||||
falsch.engine = "gibtsnicht".to_string();
|
||||
assert!(store.register_llm(&falsch).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ollama_modell_hat_den_modellnamen_als_pfad_und_eigene_engine() {
|
||||
let mut store = Store::open_in_memory().unwrap();
|
||||
|
||||
@ -3,7 +3,7 @@
|
||||
use std::path::PathBuf;
|
||||
use std::process::ExitCode;
|
||||
|
||||
use nexus_adapter::{Engine, LlamaCppEngine, OllamaEngine};
|
||||
use nexus_adapter::{Engine, LlamaCppEngine, MayaEngine, OllamaEngine};
|
||||
use nexus_core::Priority;
|
||||
use nexus_store::{NewLlm, Rights};
|
||||
|
||||
@ -156,7 +156,16 @@ fn model_add(args: &[String]) -> Result<(), String> {
|
||||
let flags = Flags::parse(
|
||||
args,
|
||||
&[
|
||||
"name", "engine", "path", "tag", "gpus", "context", "vram-mb", "ram-mb", "quant",
|
||||
"name",
|
||||
"engine",
|
||||
"path",
|
||||
"tag",
|
||||
"maya-config",
|
||||
"gpus",
|
||||
"context",
|
||||
"vram-mb",
|
||||
"ram-mb",
|
||||
"quant",
|
||||
"config",
|
||||
],
|
||||
&["disabled"],
|
||||
@ -175,9 +184,17 @@ fn model_add(args: &[String]) -> Result<(), String> {
|
||||
}
|
||||
// Ollama verwaltet seine Modelle selbst; registriert wird nur der Name.
|
||||
"ollama" => (PathBuf::from(flags.require("tag")?), None),
|
||||
// Maya: das Modell ist die Konfigurationsdatei von Maya (JSON).
|
||||
"maya" => {
|
||||
let path = PathBuf::from(flags.require("maya-config")?);
|
||||
if !path.is_file() {
|
||||
return Err(format!("{} ist keine Datei.", path.display()));
|
||||
}
|
||||
(path, None)
|
||||
}
|
||||
other => {
|
||||
return Err(format!(
|
||||
"Unbekannte Engine \"{other}\" (llama.cpp oder ollama)."
|
||||
"Unbekannte Engine \"{other}\" (llama.cpp, ollama oder maya)."
|
||||
));
|
||||
}
|
||||
};
|
||||
@ -274,9 +291,14 @@ async fn model_discover(args: &[String]) -> Result<(), String> {
|
||||
.discover()
|
||||
.await
|
||||
}
|
||||
"maya" => {
|
||||
MayaEngine::new(crate::serve::maya_config(&config)?)
|
||||
.discover()
|
||||
.await
|
||||
}
|
||||
other => {
|
||||
return Err(format!(
|
||||
"Unbekannte Engine \"{other}\" (llama.cpp oder ollama)."
|
||||
"Unbekannte Engine \"{other}\" (llama.cpp, ollama oder maya)."
|
||||
));
|
||||
}
|
||||
}
|
||||
@ -297,6 +319,8 @@ async fn model_discover(args: &[String]) -> Result<(), String> {
|
||||
"\nRegistrieren mit: nexus model add --name <name> {} --gpus 0",
|
||||
if engine == "ollama" {
|
||||
"--engine ollama --tag <modellname>"
|
||||
} else if engine == "maya" {
|
||||
"--engine maya --maya-config <pfad> --gpus 0,1"
|
||||
} else {
|
||||
"--path <pfad>"
|
||||
}
|
||||
|
||||
@ -22,7 +22,8 @@ Aufruf:
|
||||
nexus key list | enable --name N | disable --name N
|
||||
nexus model add --name N --path PFAD [--gpus 0,1] [--context N] [--vram-mb N] [--ram-mb N] [--quant Q] [--disabled]
|
||||
nexus model add --name N --engine ollama --tag MODELLNAME [--gpus 0] [--disabled]
|
||||
nexus model list | enable --name N | disable --name N | discover [--engine llama.cpp|ollama]
|
||||
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 help Diese Hilfe
|
||||
|
||||
Die Konfiguration kommt aus --config, sonst NEXUS_CONFIG, sonst ./config.toml, sonst gelten Standardwerte.
|
||||
|
||||
@ -5,7 +5,9 @@ use std::collections::HashMap;
|
||||
use std::process::ExitCode;
|
||||
use std::sync::Arc;
|
||||
|
||||
use nexus_adapter::{Engine, LlamaCppConfig, LlamaCppEngine, OllamaConfig, OllamaEngine};
|
||||
use nexus_adapter::{
|
||||
Engine, LlamaCppConfig, LlamaCppEngine, MayaConfig, MayaEngine, OllamaConfig, OllamaEngine,
|
||||
};
|
||||
use nexus_api::{AppState, Runtime};
|
||||
use nexus_core::Config;
|
||||
|
||||
@ -42,6 +44,21 @@ pub fn ollama_config(config: &Config) -> Result<OllamaConfig, String> {
|
||||
.map_err(|e| format!("Konfiguration [ollama]: {e}"))
|
||||
}
|
||||
|
||||
/// Liest den Abschnitt `[maya]`; ohne eigenen `log_dir` landen die Logs im
|
||||
/// Datenverzeichnis.
|
||||
pub fn maya_config(config: &Config) -> Result<MayaConfig, String> {
|
||||
let mut table = config.maya.clone();
|
||||
if !table.contains_key("log_dir") {
|
||||
table.insert(
|
||||
"log_dir".to_string(),
|
||||
toml::Value::String(config.data_dir.join("logs").display().to_string()),
|
||||
);
|
||||
}
|
||||
table
|
||||
.try_into::<MayaConfig>()
|
||||
.map_err(|e| format!("Konfiguration [maya]: {e}"))
|
||||
}
|
||||
|
||||
pub async fn command(args: &[String]) -> ExitCode {
|
||||
match run(args).await {
|
||||
Ok(()) => ExitCode::SUCCESS,
|
||||
@ -67,6 +84,10 @@ async fn run(args: &[String]) -> Result<(), String> {
|
||||
"ollama".to_string(),
|
||||
Arc::new(OllamaEngine::new(ollama_config(&config)?)),
|
||||
);
|
||||
engines.insert(
|
||||
"maya".to_string(),
|
||||
Arc::new(MayaEngine::new(maya_config(&config)?)),
|
||||
);
|
||||
let state = AppState::new(store, Runtime::new(engines));
|
||||
|
||||
let listener = tokio::net::TcpListener::bind(&config.listen)
|
||||
|
||||
Binary file not shown.
@ -26,10 +26,12 @@ from openai import OpenAI
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
NEXUS = Path(os.environ.get("NEXUS_BIN", ROOT / "target" / "debug" / "nexus"))
|
||||
FAKE = ROOT / "crates" / "nexus-adapter" / "tests" / "fake_llama_server.py"
|
||||
FAKE_MAYA = ROOT / "crates" / "nexus-adapter" / "tests" / "fake_maya.py"
|
||||
FAKE_OLLAMA = ROOT / "crates" / "nexus-adapter" / "tests" / "fake_ollama.py"
|
||||
MODEL = "testmodell"
|
||||
OLLAMA_MODEL = "klein" # Name im Gateway
|
||||
OLLAMA_TAG = "qwen3:0.6b" # Name in Ollama
|
||||
MAYA_MODEL = "glm" # Maya-Modell im Gateway
|
||||
ANTWORT = "Hallo vom Attrappen-Modell."
|
||||
GEHEIMER_PROMPT = "GEHEIMER-PROMPT-4711"
|
||||
FALSCHER_KEY = "nx-FALSCHER-SCHLUESSEL-999"
|
||||
@ -63,6 +65,7 @@ class GatewayTest(unittest.TestCase):
|
||||
cls.port = free_port()
|
||||
llama_from = free_port()
|
||||
ollama_from = free_port()
|
||||
maya_from = free_port()
|
||||
cls.config = cls.tmp / "config.toml"
|
||||
cls.config.write_text(
|
||||
f'listen = "127.0.0.1:{cls.port}"\n'
|
||||
@ -82,12 +85,25 @@ class GatewayTest(unittest.TestCase):
|
||||
f"port_to = {ollama_from + 9}\n"
|
||||
f"ready_timeout_secs = 20\n\n"
|
||||
f"[ollama.env]\n"
|
||||
f'FAKE_OLLAMA_MODE = "ok"\n'
|
||||
f'FAKE_OLLAMA_MODE = "ok"\n\n'
|
||||
f"[maya]\n"
|
||||
f'python = "python3"\n'
|
||||
f'script = "{FAKE_MAYA}"\n'
|
||||
f'config_roots = ["{cls.tmp}"]\n'
|
||||
f"port_from = {maya_from}\n"
|
||||
f"port_to = {maya_from + 9}\n"
|
||||
f"ready_timeout_secs = 20\n\n"
|
||||
f"[maya.env]\n"
|
||||
f'FAKE_MAYA_MODE = "ok"\n'
|
||||
f'FAKE_MAYA_LOAD_SECONDS = "0.5"\n'
|
||||
)
|
||||
maya_json = cls.tmp / "maya-test.json"
|
||||
maya_json.write_text(json.dumps({"exe": "/nicht/da", "args": [], "model_name": "fake-maya", "port": 8083}))
|
||||
model_file = cls.tmp / "modell.gguf"
|
||||
model_file.write_bytes(b"gguf")
|
||||
cls.run_cli("model", "add", "--name", MODEL, "--path", str(model_file), "--gpus", "0")
|
||||
cls.run_cli("model", "add", "--name", OLLAMA_MODEL, "--engine", "ollama", "--tag", OLLAMA_TAG, "--gpus", "0")
|
||||
cls.run_cli("model", "add", "--name", MAYA_MODEL, "--engine", "maya", "--maya-config", str(maya_json), "--gpus", "0,1")
|
||||
cls.key = cls.create_key("sdk-normal")
|
||||
cls.key_vip = cls.create_key("sdk-vip", "--max-priority", "high")
|
||||
|
||||
@ -149,6 +165,9 @@ class GatewayTest(unittest.TestCase):
|
||||
def instance_log(self):
|
||||
return self.tmp / "data" / "logs" / "instance-1.log"
|
||||
|
||||
def maya_log(self):
|
||||
return self.tmp / "data" / "logs" / "instance-maya-1.log"
|
||||
|
||||
def ollama_log(self):
|
||||
return self.tmp / "data" / "logs" / "instance-ollama.log"
|
||||
|
||||
@ -252,6 +271,33 @@ class GatewayTest(unittest.TestCase):
|
||||
self.assertGreater(len(stuecke), 1)
|
||||
self.assertTrue("".join(stuecke).endswith(OLLAMA_TAG))
|
||||
|
||||
# --- Maya (Port öffnet erst nach dem Laden, reasoning_content, Keep-alive) -----
|
||||
|
||||
def test_12_maya_chat_startet_maya_und_reicht_reasoning_durch(self):
|
||||
self.assertFalse(self.maya_log().exists(), "Die Liste darf Maya nicht starten.")
|
||||
antwort = self.client.chat.completions.create(
|
||||
model=MAYA_MODEL, messages=[{"role": "user", "content": "Hallo"}]
|
||||
)
|
||||
nachricht = antwort.choices[0].message
|
||||
self.assertEqual(nachricht.content, "Hallo vom Maya-Modell.")
|
||||
self.assertEqual((nachricht.model_extra or {}).get("reasoning_content"), "denke")
|
||||
self.assertTrue(self.maya_log().exists(), "Maya muss gestartet worden sein.")
|
||||
self.assertIn("--host 127.0.0.1", self.maya_log().read_text())
|
||||
|
||||
def test_13_maya_streaming_mit_keep_alive_zeile(self):
|
||||
stuecke, denken = [], []
|
||||
for chunk in self.client.chat.completions.create(
|
||||
model=MAYA_MODEL, messages=[{"role": "user", "content": "Hallo"}], stream=True
|
||||
):
|
||||
if chunk.choices:
|
||||
delta = chunk.choices[0].delta
|
||||
if delta.content:
|
||||
stuecke.append(delta.content)
|
||||
if (delta.model_extra or {}).get("reasoning_content"):
|
||||
denken.append(delta.model_extra["reasoning_content"])
|
||||
self.assertEqual("".join(stuecke), " vom Maya-Modell.")
|
||||
self.assertEqual(denken, ["denke"])
|
||||
|
||||
# --- Herunterfahren -------------------------------------------------------
|
||||
|
||||
def test_99_herunterfahren_beendet_das_modell(self):
|
||||
@ -260,8 +306,15 @@ class GatewayTest(unittest.TestCase):
|
||||
self.assertTrue(pid_alive(pid), "Die Instanz sollte vor dem Herunterfahren laufen.")
|
||||
ollama_log = self.ollama_log().read_text()
|
||||
self.assertTrue(pid_alive(int(next(l for l in ollama_log.splitlines() if l.startswith("fake-ollama: pid ")).split()[-1])))
|
||||
maya_pid = int(next(l for l in self.maya_log().read_text().splitlines() if l.startswith("fake-maya: pid ")).split()[-1])
|
||||
self.assertTrue(pid_alive(maya_pid))
|
||||
self.server.send_signal(signal.SIGTERM)
|
||||
self.assertEqual(self.server.wait(timeout=20), 0)
|
||||
for _ in range(50):
|
||||
if not pid_alive(maya_pid):
|
||||
break
|
||||
time.sleep(0.1)
|
||||
self.assertFalse(pid_alive(maya_pid), "Maya läuft nach dem Herunterfahren noch.")
|
||||
for _ in range(50):
|
||||
if not pid_alive(pid):
|
||||
break
|
||||
|
||||
Reference in New Issue
Block a user