feat: Studio bei Bedarf über systemd starten, Knopf Studio starten (#1106); Version 0.1.15-rc11

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GmHhg6k5Hxh8GpVW7od4Di
This commit is contained in:
2026-11-20 19:44:37 +01:00
parent dcd7971b96
commit 5e28b7117c
8 changed files with 204 additions and 11 deletions

View File

@ -40,6 +40,17 @@ pub struct StudioConfig {
/// `discover` blendet nicht installierte Modelle aus (das Studio nennt sie trotzdem, → #1110),
/// und `start` lehnt sie ab, statt Anfragen ins Leere laufen zu lassen. Ungesetzt: keine Prüfung.
pub local_models_dir: Option<std::path::PathBuf>,
/// Name der systemd-Benutzereinheit des Studios (auf srv04 `qwen-studio.service`, Quadlet von
/// `svc-scotty`). Ist sie gesetzt und das Studio antwortet nicht, startet das Gateway es mit
/// `systemctl --user start` (→ #1106). Ungesetzt: das Gateway startet nichts.
pub systemd_unit: Option<String>,
/// Wie lange nach dem Start auf das Studio gewartet wird (Container und Modell brauchen Zeit).
pub start_timeout_secs: u64,
/// Studio mit der letzten Instanz auch wieder beenden (`systemctl --user stop`). Standard: nein,
/// weil das Studio auch von Hand benutzt wird.
pub stop_unit: bool,
/// Programm für `systemctl` (nur für Tests ersetzbar).
pub systemctl: String,
}
impl Default for StudioConfig {
@ -48,6 +59,10 @@ impl Default for StudioConfig {
base_url: "http://127.0.0.1:8862".to_string(),
ready_timeout_secs: 15,
local_models_dir: None,
systemd_unit: None,
start_timeout_secs: 120,
stop_unit: false,
systemctl: "systemctl".to_string(),
}
}
}
@ -102,6 +117,77 @@ impl StudioEngine {
.unwrap_or(80)
}
/// `systemctl --user <aktion> <einheit>` als der Benutzer, unter dem das Gateway läuft.
async fn systemctl(&self, aktion: &str) -> Result<()> {
let Some(unit) = self.config.systemd_unit.as_deref() else {
return Ok(());
};
if unit.is_empty()
|| !unit
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b"@._-".contains(&b))
{
return Err(AdapterError::InvalidProfile(
"ungültiger Name der Studio-Einheit".to_string(),
));
}
let mut cmd = tokio::process::Command::new(&self.config.systemctl);
cmd.args(["--user", aktion, unit]);
if std::env::var_os("XDG_RUNTIME_DIR").is_none() {
// Dienste haben keine Anmeldesitzung; der Benutzerbus liegt unter /run/user/<uid>.
if let Some(uid) = std::fs::read_to_string("/proc/self/status")
.ok()
.and_then(|s| {
s.lines()
.find_map(|l| l.strip_prefix("Uid:"))
.and_then(|l| l.split_whitespace().next().map(str::to_string))
})
{
cmd.env("XDG_RUNTIME_DIR", format!("/run/user/{uid}"));
}
}
let out = tokio::time::timeout(Duration::from_secs(30), cmd.output())
.await
.map_err(|_| {
AdapterError::Spawn(format!("systemctl {aktion} {unit}: Zeitüberschreitung"))
})?
.map_err(|e| AdapterError::Spawn(format!("systemctl nicht ausführbar: {e}")))?;
if out.status.success() {
Ok(())
} else {
Err(AdapterError::Spawn(format!(
"systemctl --user {aktion} {unit} schlug fehl: {}",
String::from_utf8_lossy(&out.stderr).trim()
)))
}
}
/// Stellt sicher, dass das Studio antwortet; startet es bei Bedarf über systemd.
async fn ensure_up_impl(&self) -> Result<()> {
let kurz = Duration::from_secs(self.config.ready_timeout_secs);
if self.reachable(kurz).await {
return Ok(());
}
if self.config.systemd_unit.is_none() {
return Err(AdapterError::NotReady {
seconds: self.config.ready_timeout_secs,
log_tail: format!("{} antwortet nicht", self.base()),
});
}
self.systemctl("start").await?;
let ende = std::time::Instant::now() + Duration::from_secs(self.config.start_timeout_secs);
while std::time::Instant::now() < ende {
if self.reachable(Duration::from_secs(3)).await {
return Ok(());
}
tokio::time::sleep(Duration::from_secs(2)).await;
}
Err(AdapterError::NotReady {
seconds: self.config.start_timeout_secs,
log_tail: format!("{} antwortet nach dem Start nicht", self.base()),
})
}
async fn reachable(&self, timeout: Duration) -> bool {
matches!(
self.http
@ -191,6 +277,10 @@ impl Engine for StudioEngine {
}
}
async fn ensure_up(&self) -> Result<()> {
self.ensure_up_impl().await
}
async fn voices_reachable(&self) -> bool {
self.reachable(Duration::from_secs(3)).await
}
@ -249,13 +339,7 @@ impl Engine for StudioEngine {
if let Some(meldung) = self.missing_message(&model) {
return Err(AdapterError::InvalidProfile(meldung));
}
let timeout = Duration::from_secs(self.config.ready_timeout_secs);
if !self.reachable(timeout).await {
return Err(AdapterError::NotReady {
seconds: self.config.ready_timeout_secs,
log_tail: format!("{} antwortet nicht", self.base()),
});
}
self.ensure_up_impl().await?;
let id = self.next_id.fetch_add(1, Ordering::SeqCst);
self.models().insert(id, model);
Ok(InstanceHandle {
@ -266,7 +350,14 @@ impl Engine for StudioEngine {
}
async fn stop(&self, instance: &InstanceHandle, _grace: Duration) -> Result<()> {
self.models().remove(&instance.id);
let leer = {
let mut m = self.models();
m.remove(&instance.id);
m.is_empty()
};
if leer && self.config.stop_unit {
self.systemctl("stop").await?;
}
Ok(())
}
@ -296,6 +387,50 @@ impl Engine for StudioEngine {
#[cfg(test)]
mod tests {
fn mit_systemctl(port: u16, programm: &str) -> StudioEngine {
StudioEngine::new(StudioConfig {
base_url: format!("http://127.0.0.1:{port}/"),
ready_timeout_secs: 1,
start_timeout_secs: 2,
systemd_unit: Some("qwen-studio.service".to_string()),
systemctl: programm.to_string(),
..StudioConfig::default()
})
}
#[tokio::test]
async fn laeuft_das_studio_wird_systemctl_nicht_gerufen() {
let port = fake_studio().await;
// „false“ würde scheitern: Der Aufruf darf gar nicht erfolgen.
assert!(mit_systemctl(port, "false").ensure_up_impl().await.is_ok());
}
#[tokio::test]
async fn ist_das_studio_aus_wird_es_ueber_systemctl_gestartet() {
// Programm „true“ meldet Erfolg, das Studio kommt aber nicht: nach der Wartezeit „nicht bereit“.
let engine = mit_systemctl(9, "true");
let err = engine.ensure_up_impl().await.unwrap_err();
assert!(matches!(err, AdapterError::NotReady { .. }), "{err}");
// Scheitert systemctl, steht das in der Meldung.
let err = mit_systemctl(9, "false")
.ensure_up_impl()
.await
.unwrap_err();
assert!(err.to_string().contains("schlug fehl"), "{err}");
}
#[tokio::test]
async fn ohne_einheit_startet_das_gateway_nichts_und_ungueltige_namen_werden_abgelehnt() {
let err = engine(9).ensure_up_impl().await.unwrap_err();
assert!(matches!(err, AdapterError::NotReady { .. }));
let mut e = mit_systemctl(9, "true");
e.config.systemd_unit = Some("a b; rm".to_string());
assert!(matches!(
e.ensure_up_impl().await.unwrap_err(),
AdapterError::InvalidProfile(_)
));
}
#[tokio::test]
async fn studio_aus_ist_nicht_erreichbar_und_ohne_stimmen() {
// Port 9 (discard) ist lokal geschlossen: Die Liste ist leer und „nicht erreichbar“ wird gemeldet.
@ -358,7 +493,7 @@ mod tests {
StudioEngine::new(StudioConfig {
base_url: format!("http://127.0.0.1:{port}/"),
ready_timeout_secs: 3,
local_models_dir: None,
..StudioConfig::default()
})
}
@ -445,6 +580,7 @@ mod tests {
base_url: format!("http://127.0.0.1:{port}/"),
ready_timeout_secs: 3,
local_models_dir: Some(dir.clone()),
..StudioConfig::default()
});
let found = e.discover().await.unwrap();
assert_eq!(found.len(), 1, "nur das installierte Modell bleibt");