Engine::start_info meldet das Startkommando mit Platzhaltern. Die Karten "Planung ändern" weichen einem Dialog je Modell. Lokal mit Attrappen im Browser gesehen, auf srv04 nicht geprüft. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01GmHhg3osejhFSpUz472iQ1
851 lines
29 KiB
Rust
851 lines
29 KiB
Rust
//! 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).
|
|
//!
|
|
//! **Strata** (`serve/server.py` des Strata-Terminals) teilt sich Servercode und
|
|
//! Protokoll mit Maya (gemessen am 16.11.2026, `docs/m2-strata-messung.md`) und
|
|
//! läuft deshalb über denselben Adapter: [`MayaEngine::strata`] setzt
|
|
//! `--engine strata`, behält den Arbeitsordner der Konfiguration (die Engine
|
|
//! wird über `$XDG_DATA_HOME/strata/components` gefunden, das bei einem anderen
|
|
//! Benutzer als `svc-scotty` in `[strata.env]` gesetzt werden muss) und nennt
|
|
//! sich `strata`.
|
|
//!
|
|
//! 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, StartInfo, 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,
|
|
}
|
|
|
|
/// Welcher Server hinter dem Adapter steckt.
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
enum Flavor {
|
|
Maya,
|
|
Strata,
|
|
}
|
|
|
|
pub struct MayaEngine {
|
|
flavor: Flavor,
|
|
config: MayaConfig,
|
|
ports: PortPool,
|
|
next_id: AtomicU64,
|
|
children: tokio::sync::Mutex<HashMap<u64, Managed>>,
|
|
}
|
|
|
|
impl MayaEngine {
|
|
pub fn new(config: MayaConfig) -> Self {
|
|
Self::with_flavor(Flavor::Maya, config)
|
|
}
|
|
|
|
/// Derselbe Adapter für den Strata-Server (siehe Moduldokumentation).
|
|
pub fn strata(config: MayaConfig) -> Self {
|
|
Self::with_flavor(Flavor::Strata, config)
|
|
}
|
|
|
|
fn with_flavor(flavor: Flavor, config: MayaConfig) -> Self {
|
|
let ports = PortPool::new(config.port_from, config.port_to);
|
|
Self {
|
|
flavor,
|
|
config,
|
|
ports,
|
|
next_id: AtomicU64::new(1),
|
|
children: tokio::sync::Mutex::new(HashMap::new()),
|
|
}
|
|
}
|
|
|
|
/// Name der Engine im Gateway und in Dateinamen.
|
|
fn name(&self) -> &'static str {
|
|
match self.flavor {
|
|
Flavor::Maya => "maya",
|
|
Flavor::Strata => "strata",
|
|
}
|
|
}
|
|
|
|
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()];
|
|
if self.flavor == Flavor::Strata {
|
|
args.extend(["--engine".to_string(), "strata".to_string()]);
|
|
}
|
|
args.extend([
|
|
"--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 name = self.name();
|
|
let workdir = log_dir.join(format!("{name}-{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-{name}-{id}-engine.log"));
|
|
let keep_cwd = self.flavor == Flavor::Strata;
|
|
let copy = instance_config_for(
|
|
template,
|
|
port,
|
|
&engine_log,
|
|
&profile.gpus,
|
|
profile.context,
|
|
keep_cwd,
|
|
)?;
|
|
// Strata braucht seinen Arbeitsordner (Terminal), Maya läuft im eigenen.
|
|
let process_dir = copy
|
|
.get("cwd")
|
|
.and_then(Value::as_str)
|
|
.map(PathBuf::from)
|
|
.filter(|p| keep_cwd && p.is_dir())
|
|
.unwrap_or_else(|| workdir.clone());
|
|
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, process_dir))
|
|
}
|
|
|
|
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-{}-{id}.log", self.name()));
|
|
let io_err = |source| AdapterError::Io {
|
|
path: log_path.clone(),
|
|
source,
|
|
};
|
|
rotate_log(&log_path, self.config.log_keep).map_err(io_err)?;
|
|
// Im Anhängemodus: Wird das Log im Betrieb gekürzt (Größenbegrenzung),
|
|
// schreibt der Prozess danach am neuen Ende weiter statt hinter einer Lücke.
|
|
let log = std::fs::OpenOptions::new()
|
|
.create(true)
|
|
.append(true)
|
|
.open(&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).
|
|
#[cfg(test)]
|
|
pub(crate) fn instance_config(
|
|
template: Value,
|
|
port: u16,
|
|
engine_log: &Path,
|
|
gpus: &[u32],
|
|
context: Option<u32>,
|
|
) -> Result<Value> {
|
|
instance_config_for(template, port, engine_log, gpus, context, false)
|
|
}
|
|
|
|
/// Wie [`instance_config`]; `keep_cwd` behält den Arbeitsordner der Vorlage
|
|
/// (Strata).
|
|
pub(crate) fn instance_config_for(
|
|
template: Value,
|
|
port: u16,
|
|
engine_log: &Path,
|
|
gpus: &[u32],
|
|
context: Option<u32>,
|
|
keep_cwd: bool,
|
|
) -> 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(),
|
|
));
|
|
}
|
|
if !keep_cwd {
|
|
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 start_info(&self) -> StartInfo {
|
|
let c = &self.config;
|
|
let args = self
|
|
.build_args(Path::new("<Kopie der Konfiguration>"), c.port_from)
|
|
.join(" ")
|
|
.replace(&c.port_from.to_string(), "<Port>");
|
|
StartInfo {
|
|
executable: Some(c.script.clone()),
|
|
command: format!("{} {}", c.python.display(), args),
|
|
env: Vec::new(),
|
|
details: vec![
|
|
(
|
|
"Python".to_string(),
|
|
format!(
|
|
"{} ({})",
|
|
c.python.display(),
|
|
if c.python.exists() {
|
|
"vorhanden"
|
|
} else {
|
|
"fehlt"
|
|
}
|
|
),
|
|
),
|
|
(
|
|
"Konfigurationen".to_string(),
|
|
c.config_roots
|
|
.iter()
|
|
.map(|p| p.display().to_string())
|
|
.collect::<Vec<_>>()
|
|
.join(", "),
|
|
),
|
|
(
|
|
"Ports".to_string(),
|
|
format!("{} bis {}", c.port_from, c.port_to),
|
|
),
|
|
(
|
|
"Zeitlimit Start".to_string(),
|
|
format!("{} s", c.ready_timeout_secs),
|
|
),
|
|
],
|
|
}
|
|
}
|
|
|
|
fn describe(&self) -> EngineInfo {
|
|
EngineInfo {
|
|
name: self.name().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, in dem der Pack
|
|
/// (`--glm-pack`) liegt, 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" || x == "--pack")?;
|
|
a.get(i + 1)?.as_str().map(PathBuf::from)
|
|
});
|
|
found.push(DiscoveredArtifact {
|
|
name: name.to_string(),
|
|
path,
|
|
quantization,
|
|
// Gemessen auf srv04: Der Pack enthält nur den dichten Teil
|
|
// (0,9 GB), die Experten liegen in den GGUF-Dateien des
|
|
// Modellordners darüber (zusammen 71 GB). Gezählt wird deshalb
|
|
// der Modellordner.
|
|
size_bytes: pack
|
|
.as_deref()
|
|
.map(|p| dir_size(p.parent().unwrap_or(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()
|
|
// `fs::metadata` folgt Verweisen: Modellordner bestehen oft aus Links.
|
|
.map(|e| match std::fs::metadata(e.path()) {
|
|
Ok(m) if m.is_dir() => dir_size(&e.path(), depth + 1),
|
|
Ok(m) => m.len(),
|
|
Err(_) => 0,
|
|
})
|
|
.sum()
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod strata_tests {
|
|
use super::*;
|
|
use serde_json::json;
|
|
|
|
#[test]
|
|
fn strata_startet_den_server_mit_engine_strata_und_behaelt_den_arbeitsordner() {
|
|
let engine = MayaEngine::strata(MayaConfig::default());
|
|
let args = engine.build_args(Path::new("/c.json"), 18500);
|
|
assert_eq!(args[1..3], ["--engine", "strata"]);
|
|
assert!(args.windows(2).any(|w| w == ["--host", "127.0.0.1"]));
|
|
assert_eq!(engine.describe().name, "strata");
|
|
let maya = MayaEngine::new(MayaConfig::default());
|
|
assert!(
|
|
!maya
|
|
.build_args(Path::new("/c.json"), 1)
|
|
.contains(&"--engine".to_string())
|
|
);
|
|
assert_eq!(maya.describe().name, "maya");
|
|
|
|
let template =
|
|
json!({"exe": "component:strata-engine", "cwd": "/t", "api_key": "x", "args": []});
|
|
let kept =
|
|
instance_config_for(template.clone(), 1, Path::new("/l"), &[0, 1], None, true).unwrap();
|
|
assert_eq!(kept["cwd"], "/t");
|
|
assert!(kept.get("api_key").is_none());
|
|
let dropped = instance_config(template, 1, Path::new("/l"), &[0], None).unwrap();
|
|
assert!(dropped.get("cwd").is_none());
|
|
}
|
|
}
|
|
|
|
#[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());
|
|
}
|
|
}
|