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:
@ -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());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user