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:
@ -31,6 +31,11 @@ pub trait Engine: Send + Sync {
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
/// Bringt den Dienst hinter der Engine hoch, falls er extern läuft und das Gateway ihn starten darf.
|
||||
async fn ensure_up(&self) -> crate::types::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Antwortet der Dienst hinter der Stimmenliste? Unterscheidet „keine Stimmen“ von „Dienst aus“.
|
||||
async fn voices_reachable(&self) -> bool {
|
||||
true
|
||||
|
||||
@ -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");
|
||||
|
||||
@ -415,6 +415,14 @@ impl Runtime {
|
||||
}
|
||||
}
|
||||
|
||||
/// Startet den externen Dienst der Engine bei Bedarf (Studio über systemd). Fehlertext für die Oberfläche.
|
||||
pub async fn engine_ensure_up(&self, name: &str) -> Result<(), String> {
|
||||
match self.shared.engines.get(name) {
|
||||
Some(engine) => engine.ensure_up().await.map_err(|e| e.to_string()),
|
||||
None => Err("Die Engine gibt es nicht.".to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Antwortet der Dienst hinter den Stimmen der Engine (Studio läuft)?
|
||||
pub async fn engine_voices_reachable(&self, name: &str) -> bool {
|
||||
match self.shared.engines.get(name) {
|
||||
|
||||
@ -128,6 +128,7 @@ pub fn routes() -> Router<Arc<AppState>> {
|
||||
.route("/ui/benutzer/update-pruefen", post(benutzer::update_check))
|
||||
.route("/ui/modelle", get(verwaltung::models_page))
|
||||
.route("/ui/modelle/stimme", post(stimmen::save))
|
||||
.route("/ui/modelle/studio-start", post(stimmen::studio_start))
|
||||
.route(
|
||||
"/ui/modelle/systemprompt",
|
||||
post(verwaltung::model_systemprompt),
|
||||
|
||||
@ -51,6 +51,9 @@ pub(super) async fn page(state: &AppState, user: &super::Viewer) -> String {
|
||||
}
|
||||
if !studio_erreichbar {
|
||||
body.push_str("<p class=\"fehler\" role=\"alert\">Das Studio ist nicht erreichbar, deshalb gibt es keine Liste. Die Stimmen sind nicht gelöscht: Sobald das Studio läuft, stehen sie hier wieder, und bereits erteilte Freigaben bleiben erhalten.</p>");
|
||||
if user.admin() {
|
||||
body.push_str(&format!("<form method=\"post\" action=\"/ui/modelle/studio-start\">{}<button class=\"primary\" type=\"submit\">Studio starten</button> <span class=\"klein\">Das kann bis zu zwei Minuten dauern.</span></form>", csrf_field(user)));
|
||||
}
|
||||
} else if voices.is_empty() {
|
||||
body.push_str("<p class=\"leer\">Das Studio meldet keine Stimmen.</p>");
|
||||
}
|
||||
@ -113,6 +116,28 @@ pub(super) async fn save(
|
||||
}
|
||||
}
|
||||
|
||||
/// Startet das Studio über systemd (nur Administratoren; nur wenn `systemd_unit` gesetzt ist, → #1106).
|
||||
pub(super) async fn studio_start(
|
||||
State(state): State<Arc<AppState>>,
|
||||
headers: HeaderMap,
|
||||
body: Bytes,
|
||||
) -> Response {
|
||||
let user = match guard(&state, &headers, form_field(&body, "csrf").as_deref(), true) {
|
||||
Ok(user) => user,
|
||||
Err(r) => return *r,
|
||||
};
|
||||
match state.runtime.engine_ensure_up("tts").await {
|
||||
Ok(()) => {
|
||||
audit(&state, &user, "studio.start", "tts");
|
||||
redirect("/ui/modelle?art=sprache")
|
||||
}
|
||||
Err(meldung) => super::refused(
|
||||
StatusCode::BAD_GATEWAY,
|
||||
&format!("Das Studio ließ sich nicht starten: {meldung}"),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn script() -> Response {
|
||||
super::secure(Response::builder())
|
||||
.header(
|
||||
|
||||
@ -4607,3 +4607,21 @@ async fn chat_seite_laesst_sich_bei_kleinem_fenster_scrollen() {
|
||||
assert!(css.contains("body:has(#chat)>main{flex:1 1 auto;min-height:0;display:flex;flex-direction:column;overflow-y:auto}"));
|
||||
assert!(css.contains("body:has(#chat) .chat-rahmen{flex:1 1 auto;min-height:24rem}"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn studio_starten_braucht_admin_und_csrf() {
|
||||
// #1106: Ohne Recht und Token wird nichts gestartet.
|
||||
let gw = gateway(0, false).await;
|
||||
let (ui_cookie, ui_csrf) = ui_session(&gw, &gw.key_ui).await;
|
||||
let (admin_cookie, _) = ui_session(&gw, &gw.key_admin).await;
|
||||
let (status, _, _) = ui_post(
|
||||
&gw,
|
||||
"/ui/modelle/studio-start",
|
||||
&ui_cookie,
|
||||
&format!("csrf={ui_csrf}"),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, 403);
|
||||
let (status, _, _) = ui_post(&gw, "/ui/modelle/studio-start", &admin_cookie, "").await;
|
||||
assert_eq!(status, 403);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user