vLLM über den Agenten starten und stoppen
- Agent verwaltet die in seiner Konfiguration festgelegten vLLM-Instanzen: Start in eigener Prozessgruppe, Bereitschaft über /health, Stoppen der ganzen Gruppe, Absturzerkennung mit Log-Auszug, Stoppen aller beim Beenden - Proxy bindet vLLM unter /vllm an, leitet nach dem Feld model an die Instanz weiter und erfährt die Instanzen vom Agenten - Scheduler reserviert beim Verdrängen den Platz für das anfragende Modell, damit keine andere wartende Anfrage ihn belegt (kein Hin- und Herladen) - tools/fake_vllm.py zum Testen ohne GPU, agent.example.toml Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
c5d618ed09
commit
566405d12f
13 files changed
+1053
-199
No files matched your search
@@ -0,0 +1,373 @@
|
||||
//! Startet und stoppt die vLLM-Instanzen dieses Rechners.
|
||||
//!
|
||||
//! Welche Instanzen es gibt und wie sie gestartet werden, steht in der Konfiguration des
|
||||
//! Agenten. Der Proxy kann nur konfigurierte Instanzen beim Namen starten und stoppen,
|
||||
//! aber keine eigenen Befehle ausführen lassen.
|
||||
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
fs::OpenOptions,
|
||||
io::{Read, Seek, SeekFrom, Write},
|
||||
path::PathBuf,
|
||||
process::Stdio,
|
||||
sync::Arc,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tokio::{
|
||||
process::{Child, Command},
|
||||
sync::Mutex,
|
||||
};
|
||||
|
||||
#[derive(Debug, Deserialize, Clone)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct InstanceConfig {
|
||||
/// Modellname, den Clients im Feld "model" senden (bei vLLM --served-model-name)
|
||||
pub name: String,
|
||||
pub port: u16,
|
||||
/// Speicher, den die Instanz belegt; vLLM reserviert ihn beim Start fest
|
||||
pub memory_mb: u64,
|
||||
/// Startbefehl; {name} und {port} werden ersetzt
|
||||
pub command: Vec<String>,
|
||||
#[serde(default)]
|
||||
pub env: HashMap<String, String>,
|
||||
/// Befehl zum Stoppen, z. B. für Container; sonst SIGTERM an die Prozessgruppe
|
||||
pub stop_command: Option<Vec<String>>,
|
||||
#[serde(default = "default_startup_timeout")]
|
||||
pub startup_timeout_secs: u64,
|
||||
}
|
||||
|
||||
fn default_startup_timeout() -> u64 {
|
||||
900
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum State {
|
||||
Stopped,
|
||||
Starting,
|
||||
Running,
|
||||
Stopping,
|
||||
Failed,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct Status {
|
||||
pub name: String,
|
||||
pub port: u16,
|
||||
pub memory_mb: u64,
|
||||
pub state: State,
|
||||
pub error: Option<String>,
|
||||
pub pid: Option<u32>,
|
||||
}
|
||||
|
||||
struct Instance {
|
||||
cfg: InstanceConfig,
|
||||
state: State,
|
||||
error: Option<String>,
|
||||
child: Option<Child>,
|
||||
pid: Option<u32>,
|
||||
/// Zählt die Starts, damit eine alte Überwachung eine neue nicht stört
|
||||
generation: u64,
|
||||
}
|
||||
|
||||
impl Instance {
|
||||
fn status(&self) -> Status {
|
||||
Status {
|
||||
name: self.cfg.name.clone(),
|
||||
port: self.cfg.port,
|
||||
memory_mb: self.cfg.memory_mb,
|
||||
state: self.state,
|
||||
error: self.error.clone(),
|
||||
pid: self.pid,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Manager {
|
||||
instances: Vec<Arc<Mutex<Instance>>>,
|
||||
log_dir: PathBuf,
|
||||
http: reqwest::Client,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum Error {
|
||||
NotFound(String),
|
||||
Conflict(String),
|
||||
Internal(anyhow::Error),
|
||||
}
|
||||
|
||||
const STOP_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
|
||||
/// Signal an die ganze Prozessgruppe, denn vLLM startet eigene Kindprozesse (EngineCore).
|
||||
fn kill_group(pid: u32, signal: i32) {
|
||||
// SAFETY: kill() hat keine Vorbedingungen; eine negative PID adressiert die Gruppe.
|
||||
unsafe {
|
||||
libc::kill(-(pid as i32), signal);
|
||||
}
|
||||
}
|
||||
|
||||
impl Manager {
|
||||
pub fn new(configs: Vec<InstanceConfig>, log_dir: PathBuf) -> Result<Arc<Self>> {
|
||||
for (i, a) in configs.iter().enumerate() {
|
||||
if a.command.is_empty() {
|
||||
bail!("vLLM-Instanz {}: command ist leer", a.name);
|
||||
}
|
||||
if configs[..i].iter().any(|b| b.name == a.name || b.port == a.port) {
|
||||
bail!("vLLM-Instanz {}: Name oder Port doppelt", a.name);
|
||||
}
|
||||
}
|
||||
std::fs::create_dir_all(&log_dir)
|
||||
.with_context(|| format!("Log-Verzeichnis {} anlegen", log_dir.display()))?;
|
||||
let instances = configs
|
||||
.into_iter()
|
||||
.map(|cfg| {
|
||||
Arc::new(Mutex::new(Instance {
|
||||
cfg,
|
||||
state: State::Stopped,
|
||||
error: None,
|
||||
child: None,
|
||||
pid: None,
|
||||
generation: 0,
|
||||
}))
|
||||
})
|
||||
.collect();
|
||||
let http = reqwest::Client::builder().timeout(Duration::from_secs(2)).build()?;
|
||||
Ok(Arc::new(Self { instances, log_dir, http }))
|
||||
}
|
||||
|
||||
async fn get(&self, name: &str) -> Result<Arc<Mutex<Instance>>, Error> {
|
||||
for inst in &self.instances {
|
||||
if inst.lock().await.cfg.name == name {
|
||||
return Ok(inst.clone());
|
||||
}
|
||||
}
|
||||
Err(Error::NotFound(format!("keine vLLM-Instanz {name}")))
|
||||
}
|
||||
|
||||
pub async fn list(&self) -> Vec<Status> {
|
||||
let mut list = Vec::new();
|
||||
for inst in &self.instances {
|
||||
list.push(inst.lock().await.status());
|
||||
}
|
||||
list
|
||||
}
|
||||
|
||||
fn log_path(&self, name: &str) -> PathBuf {
|
||||
let file: String = name
|
||||
.chars()
|
||||
.map(|c| if c.is_ascii_alphanumeric() || c == '.' || c == '-' { c } else { '_' })
|
||||
.collect();
|
||||
self.log_dir.join(format!("{file}.log"))
|
||||
}
|
||||
|
||||
/// Letzte Zeilen des Logs, damit eine Fehlermeldung zeigt, woran der Start scheiterte
|
||||
fn log_tail(&self, name: &str) -> String {
|
||||
let read = || -> std::io::Result<String> {
|
||||
let mut f = std::fs::File::open(self.log_path(name))?;
|
||||
let len = f.metadata()?.len();
|
||||
f.seek(SeekFrom::Start(len.saturating_sub(4096)))?;
|
||||
let mut buf = Vec::new();
|
||||
f.read_to_end(&mut buf)?;
|
||||
let text = String::from_utf8_lossy(&buf);
|
||||
let lines: Vec<&str> = text.lines().collect();
|
||||
Ok(lines[lines.len().saturating_sub(10)..].join("\n"))
|
||||
};
|
||||
read().unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Startet eine Instanz. Kehrt sofort zurück; bereit ist sie, wenn der Zustand "running" ist.
|
||||
pub async fn start(self: &Arc<Self>, name: &str) -> Result<Status, Error> {
|
||||
let inst = self.get(name).await?;
|
||||
let mut i = inst.lock().await;
|
||||
match i.state {
|
||||
State::Starting | State::Running => return Ok(i.status()),
|
||||
State::Stopping => return Err(Error::Conflict(format!("{name} wird gerade gestoppt"))),
|
||||
State::Stopped | State::Failed => {}
|
||||
}
|
||||
// Sonst hielte die Überwachung einen fremden Dienst auf dem Port für die Instanz.
|
||||
if tokio::net::TcpStream::connect(("127.0.0.1", i.cfg.port)).await.is_ok() {
|
||||
return Err(Error::Conflict(format!("Port {} ist bereits belegt", i.cfg.port)));
|
||||
}
|
||||
|
||||
let port = i.cfg.port.to_string();
|
||||
let args: Vec<String> = i
|
||||
.cfg
|
||||
.command
|
||||
.iter()
|
||||
.map(|a| a.replace("{name}", &i.cfg.name).replace("{port}", &port))
|
||||
.collect();
|
||||
let mut log = OpenOptions::new()
|
||||
.create(true)
|
||||
.append(true)
|
||||
.open(self.log_path(name))
|
||||
.map_err(|e| Error::Internal(e.into()))?;
|
||||
let _ = writeln!(log, "=== omega-agent: Start {} ===", args.join(" "));
|
||||
let stderr = log.try_clone().map_err(|e| Error::Internal(e.into()))?;
|
||||
|
||||
let spawned = Command::new(&args[0])
|
||||
.args(&args[1..])
|
||||
.envs(&i.cfg.env)
|
||||
.stdin(Stdio::null())
|
||||
.stdout(log)
|
||||
.stderr(stderr)
|
||||
.process_group(0)
|
||||
.kill_on_drop(true)
|
||||
.spawn();
|
||||
let child = match spawned {
|
||||
Ok(child) => child,
|
||||
Err(e) => {
|
||||
i.state = State::Failed;
|
||||
i.error = Some(format!("{} lässt sich nicht starten: {e}", args[0]));
|
||||
return Ok(i.status());
|
||||
}
|
||||
};
|
||||
tracing::info!("{name}: gestartet (PID {:?})", child.id());
|
||||
i.pid = child.id();
|
||||
i.child = Some(child);
|
||||
i.state = State::Starting;
|
||||
i.error = None;
|
||||
i.generation += 1;
|
||||
let generation = i.generation;
|
||||
let status = i.status();
|
||||
drop(i);
|
||||
|
||||
tokio::spawn(self.clone().monitor(inst, generation));
|
||||
Ok(status)
|
||||
}
|
||||
|
||||
/// Überwacht eine gestartete Instanz: Bereitschaft über /health, Ende des Prozesses.
|
||||
async fn monitor(self: Arc<Self>, inst: Arc<Mutex<Instance>>, generation: u64) {
|
||||
let started = Instant::now();
|
||||
loop {
|
||||
tokio::time::sleep(Duration::from_millis(500)).await;
|
||||
let mut i = inst.lock().await;
|
||||
if i.generation != generation {
|
||||
return;
|
||||
}
|
||||
let name = i.cfg.name.clone();
|
||||
|
||||
let exited = match i.child.as_mut().map(Child::try_wait) {
|
||||
Some(Ok(Some(status))) => Some(status.to_string()),
|
||||
Some(Err(e)) => Some(e.to_string()),
|
||||
Some(Ok(None)) => None,
|
||||
None => Some("kein Prozess".into()),
|
||||
};
|
||||
if let Some(exit) = exited {
|
||||
// Zurückgebliebene Kindprozesse mitbeenden
|
||||
if let Some(pid) = i.pid.take() {
|
||||
kill_group(pid, libc::SIGKILL);
|
||||
}
|
||||
i.child = None;
|
||||
match i.state {
|
||||
State::Stopping => {
|
||||
i.state = State::Stopped;
|
||||
tracing::info!("{name}: gestoppt");
|
||||
}
|
||||
State::Failed => {}
|
||||
_ => {
|
||||
i.state = State::Failed;
|
||||
i.error = Some(format!("Prozess beendet ({exit}):\n{}", self.log_tail(&name)));
|
||||
tracing::warn!("{name}: Prozess unerwartet beendet ({exit})");
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if i.state == State::Starting {
|
||||
let url = format!("http://127.0.0.1:{}/health", i.cfg.port);
|
||||
let timeout = Duration::from_secs(i.cfg.startup_timeout_secs);
|
||||
drop(i);
|
||||
let healthy = self.http.get(&url).send().await.is_ok_and(|r| r.status().is_success());
|
||||
let mut i = inst.lock().await;
|
||||
if i.generation != generation || i.state != State::Starting {
|
||||
continue;
|
||||
}
|
||||
if healthy {
|
||||
i.state = State::Running;
|
||||
tracing::info!("{name}: bereit nach {:.1} s", started.elapsed().as_secs_f64());
|
||||
} else if started.elapsed() > timeout {
|
||||
i.state = State::Failed;
|
||||
i.error = Some(format!(
|
||||
"nicht bereit nach {} s:\n{}",
|
||||
timeout.as_secs(),
|
||||
self.log_tail(&name)
|
||||
));
|
||||
tracing::warn!("{name}: Start dauert zu lange, wird beendet");
|
||||
if let Some(pid) = i.pid {
|
||||
kill_group(pid, libc::SIGKILL);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Stoppt eine Instanz und wartet, bis der Prozess beendet ist.
|
||||
pub async fn stop(&self, name: &str) -> Result<Status, Error> {
|
||||
let inst = self.get(name).await?;
|
||||
let mut i = inst.lock().await;
|
||||
if i.child.is_none() {
|
||||
i.state = State::Stopped;
|
||||
i.error = None;
|
||||
return Ok(i.status());
|
||||
}
|
||||
i.state = State::Stopping;
|
||||
let pid = i.pid;
|
||||
let port = i.cfg.port.to_string();
|
||||
let stop_command: Option<Vec<String>> = i.cfg.stop_command.as_ref().map(|c| {
|
||||
c.iter().map(|a| a.replace("{name}", &i.cfg.name).replace("{port}", &port)).collect()
|
||||
});
|
||||
drop(i);
|
||||
|
||||
tracing::info!("{name}: stoppe");
|
||||
match (stop_command, pid) {
|
||||
(Some(cmd), _) if !cmd.is_empty() => {
|
||||
let out = Command::new(&cmd[0]).args(&cmd[1..]).output().await;
|
||||
if let Err(e) = out {
|
||||
tracing::warn!("{name}: Stoppbefehl gescheitert: {e}");
|
||||
}
|
||||
}
|
||||
(_, Some(pid)) => kill_group(pid, libc::SIGTERM),
|
||||
_ => {}
|
||||
}
|
||||
|
||||
// Die Überwachung bemerkt das Ende des Prozesses; bei Bedarf hart nachhelfen.
|
||||
let deadline = Instant::now() + STOP_TIMEOUT;
|
||||
let mut killed = false;
|
||||
loop {
|
||||
tokio::time::sleep(Duration::from_millis(250)).await;
|
||||
let i = inst.lock().await;
|
||||
if i.child.is_none() {
|
||||
return Ok(i.status());
|
||||
}
|
||||
if Instant::now() > deadline {
|
||||
if killed {
|
||||
return Err(Error::Internal(anyhow::anyhow!("{name} lässt sich nicht beenden")));
|
||||
}
|
||||
tracing::warn!("{name}: reagiert nicht auf SIGTERM, sende SIGKILL");
|
||||
if let Some(pid) = i.pid {
|
||||
kill_group(pid, libc::SIGKILL);
|
||||
}
|
||||
killed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Beim Beenden des Agenten sollen keine verwaisten Instanzen Speicher belegen.
|
||||
pub async fn stop_all(&self) {
|
||||
let mut names = Vec::new();
|
||||
for inst in &self.instances {
|
||||
let i = inst.lock().await;
|
||||
if i.child.is_some() {
|
||||
names.push(i.cfg.name.clone());
|
||||
}
|
||||
}
|
||||
for name in names {
|
||||
if let Err(e) = self.stop(&name).await {
|
||||
tracing::warn!("{name}: {e:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user