Argon2id, Standard-Admin mit Einmalpasswort in Datei, eigener Admin bei der ersten Einrichtung, Rollen admin und nutzer, Benutzerverwaltung, Mein Konto, nexus user. Die Anmeldung mit API-Key an der Oberfläche entfällt. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01GmHhg3osejhFSpUz472iQ1
290 lines
10 KiB
Rust
290 lines
10 KiB
Rust
//! `nexus serve`: startet das Gateway und beendet beim Herunterfahren alle
|
|
//! Engine-Instanzen.
|
|
|
|
use std::collections::HashMap;
|
|
use std::process::ExitCode;
|
|
use std::sync::Arc;
|
|
use std::time::Duration;
|
|
|
|
use nexus_adapter::{
|
|
Engine, LlamaCppConfig, LlamaCppEngine, MayaConfig, MayaEngine, OllamaConfig, OllamaEngine,
|
|
};
|
|
use nexus_api::{AppState, Runtime, RuntimeOptions, SchedulerSettings};
|
|
use nexus_core::Config;
|
|
|
|
use crate::cli::{Flags, load_config, open_store};
|
|
use crate::logging;
|
|
|
|
/// Liest den Abschnitt `[llama_cpp]`; ohne eigenen `log_dir` landen die Logs
|
|
/// der Instanzen im Datenverzeichnis.
|
|
pub fn llama_config(config: &Config) -> Result<LlamaCppConfig, String> {
|
|
let mut table = config.llama_cpp.clone();
|
|
if !table.contains_key("log_dir") {
|
|
table.insert(
|
|
"log_dir".to_string(),
|
|
toml::Value::String(config.data_dir.join("logs").display().to_string()),
|
|
);
|
|
}
|
|
table
|
|
.try_into::<LlamaCppConfig>()
|
|
.map_err(|e| format!("Konfiguration [llama_cpp]: {e}"))
|
|
}
|
|
|
|
/// Liest den Abschnitt `[ollama]`; ohne eigenen `log_dir` landen die Logs im
|
|
/// Datenverzeichnis.
|
|
pub fn ollama_config(config: &Config) -> Result<OllamaConfig, String> {
|
|
let mut table = config.ollama.clone();
|
|
if !table.contains_key("log_dir") {
|
|
table.insert(
|
|
"log_dir".to_string(),
|
|
toml::Value::String(config.data_dir.join("logs").display().to_string()),
|
|
);
|
|
}
|
|
table
|
|
.try_into::<OllamaConfig>()
|
|
.map_err(|e| format!("Konfiguration [ollama]: {e}"))
|
|
}
|
|
|
|
/// Liest den Abschnitt `[maya]`; ohne eigenen `log_dir` landen die Logs im
|
|
/// Datenverzeichnis.
|
|
pub fn maya_config(config: &Config) -> Result<MayaConfig, String> {
|
|
let mut table = config.maya.clone();
|
|
if !table.contains_key("log_dir") {
|
|
table.insert(
|
|
"log_dir".to_string(),
|
|
toml::Value::String(config.data_dir.join("logs").display().to_string()),
|
|
);
|
|
}
|
|
table
|
|
.try_into::<MayaConfig>()
|
|
.map_err(|e| format!("Konfiguration [maya]: {e}"))
|
|
}
|
|
|
|
/// Übersetzt den Abschnitt `[scheduler]` (`0` heißt bei den Leerlaufzeiten „nie“).
|
|
pub fn runtime_options(config: &Config) -> RuntimeOptions {
|
|
let s = &config.scheduler;
|
|
let idle = |secs: u64| (secs > 0).then(|| Duration::from_secs(secs));
|
|
RuntimeOptions {
|
|
scheduler: SchedulerSettings {
|
|
reserve_mb: s.reserve_mb,
|
|
max_waiting: s.max_waiting,
|
|
max_wait: Duration::from_secs(s.max_wait_secs),
|
|
aging_step: Duration::from_secs(s.aging_secs),
|
|
evict_min_idle: Duration::from_secs(s.evict_min_idle_secs),
|
|
},
|
|
idle: idle(s.idle_secs),
|
|
exclusive_idle: idle(s.maya_idle_secs),
|
|
..RuntimeOptions::default()
|
|
}
|
|
}
|
|
|
|
/// Liest den Abschnitt `[strata]`. Ohne Angaben gelten die Pfade des
|
|
/// Strata-Terminals von `svc-scotty` und der Port-Bereich 18500 bis 18599.
|
|
pub fn strata_config(config: &Config) -> Result<MayaConfig, String> {
|
|
let mut table = config.strata.clone();
|
|
let base = "/home/svc-scotty/.local/share/strata";
|
|
for (key, value) in [
|
|
(
|
|
"python",
|
|
toml::Value::String(format!("{base}/terminal/current/python/bin/python3.12")),
|
|
),
|
|
(
|
|
"script",
|
|
toml::Value::String(format!("{base}/terminal/current/serve/server.py")),
|
|
),
|
|
(
|
|
"config_roots",
|
|
toml::Value::Array(vec![toml::Value::String(format!("{base}/install"))]),
|
|
),
|
|
("port_from", toml::Value::Integer(18500)),
|
|
("port_to", toml::Value::Integer(18599)),
|
|
(
|
|
"log_dir",
|
|
toml::Value::String(config.data_dir.join("logs").display().to_string()),
|
|
),
|
|
] {
|
|
table.entry(key).or_insert(value);
|
|
}
|
|
table
|
|
.try_into::<MayaConfig>()
|
|
.map_err(|e| format!("Konfiguration [strata]: {e}"))
|
|
}
|
|
|
|
pub async fn command(args: &[String]) -> ExitCode {
|
|
match run(args).await {
|
|
Ok(()) => ExitCode::SUCCESS,
|
|
Err(message) => {
|
|
eprintln!("{message}");
|
|
ExitCode::FAILURE
|
|
}
|
|
}
|
|
}
|
|
|
|
async fn run(args: &[String]) -> Result<(), String> {
|
|
let flags = Flags::parse(args, &["config"], &[])?;
|
|
let config = load_config(&flags)?;
|
|
logging::init(&config.log_level)?;
|
|
let store = open_store(&config)?;
|
|
|
|
let mut engines: HashMap<String, Arc<dyn Engine>> = HashMap::new();
|
|
engines.insert(
|
|
"llama.cpp".to_string(),
|
|
Arc::new(LlamaCppEngine::new(llama_config(&config)?)),
|
|
);
|
|
engines.insert(
|
|
"ollama".to_string(),
|
|
Arc::new(OllamaEngine::new(ollama_config(&config)?)),
|
|
);
|
|
engines.insert(
|
|
"maya".to_string(),
|
|
Arc::new(MayaEngine::new(maya_config(&config)?)),
|
|
);
|
|
engines.insert(
|
|
"strata".to_string(),
|
|
Arc::new(MayaEngine::strata(strata_config(&config)?)),
|
|
);
|
|
let state = AppState::new(
|
|
store,
|
|
Runtime::with_options(engines, runtime_options(&config)),
|
|
);
|
|
crate::bootstrap::ensure(&state, &config.data_dir)?;
|
|
// Der Scheduler braucht die Größe der GPUs, bevor die erste Anfrage kommt.
|
|
state.runtime.sample(&config.nvidia_smi).await;
|
|
let jobs = spawn_background_jobs(&state, &config)?;
|
|
|
|
let listener = tokio::net::TcpListener::bind(&config.listen)
|
|
.await
|
|
.map_err(|e| format!("Adresse {} nicht nutzbar: {e}", config.listen))?;
|
|
tracing::info!(
|
|
version = nexus_core::VERSION,
|
|
listen = %config.listen,
|
|
"Nexus lauscht"
|
|
);
|
|
|
|
let served = axum::serve(listener, nexus_api::router(state.clone()))
|
|
.with_graceful_shutdown(shutdown_signal())
|
|
.await;
|
|
|
|
for job in jobs {
|
|
job.abort();
|
|
}
|
|
tracing::info!("Nexus wird beendet, Instanzen werden gestoppt");
|
|
state.runtime.shutdown().await;
|
|
tracing::info!("Nexus beendet");
|
|
served.map_err(|e| format!("Serverfehler: {e}"))
|
|
}
|
|
|
|
/// Startet die Hintergrundjobs: Messung von Instanzen und GPUs, Aufbewahrung
|
|
/// der Logs in der Datenbank und Größenbegrenzung der Engine-Logs.
|
|
fn spawn_background_jobs(
|
|
state: &Arc<AppState>,
|
|
config: &Config,
|
|
) -> Result<Vec<tokio::task::JoinHandle<()>>, String> {
|
|
let mut jobs = Vec::new();
|
|
|
|
if config.metrics_interval_secs > 0 {
|
|
let state = state.clone();
|
|
let interval = Duration::from_secs(config.metrics_interval_secs);
|
|
let nvidia_smi = config.nvidia_smi.clone();
|
|
let store_every = Duration::from_secs(config.metrics_store_secs);
|
|
jobs.push(tokio::spawn(async move {
|
|
let mut last_stored: Option<std::time::Instant> = None;
|
|
loop {
|
|
state.runtime.sample(&nvidia_smi).await;
|
|
let due = !store_every.is_zero()
|
|
&& last_stored.is_none_or(|t| t.elapsed() >= store_every);
|
|
if due {
|
|
last_stored = Some(std::time::Instant::now());
|
|
let samples = nexus_api::series_samples(&state.runtime.metrics);
|
|
if let Err(e) = state.store().record_samples(&samples) {
|
|
tracing::error!(fehler = %e, "Messwerte konnten nicht gespeichert werden");
|
|
}
|
|
}
|
|
tokio::time::sleep(interval).await;
|
|
}
|
|
}));
|
|
}
|
|
|
|
{
|
|
let state = state.clone();
|
|
let (requests_days, audit_days, samples_days) = (
|
|
config.log_retention_days,
|
|
config.audit_retention_days,
|
|
config.metrics_retention_days,
|
|
);
|
|
jobs.push(tokio::spawn(async move {
|
|
loop {
|
|
let (requests, audit, samples) = {
|
|
let store = state.store();
|
|
(
|
|
store.purge_requests_older_than(requests_days),
|
|
store.purge_audit_older_than(audit_days),
|
|
store.purge_samples_older_than(samples_days),
|
|
)
|
|
};
|
|
for (what, result) in [
|
|
("anfrage_log", requests),
|
|
("audit", audit),
|
|
("metrik_probe", samples),
|
|
] {
|
|
match result {
|
|
Ok(0) => {}
|
|
Ok(n) => tracing::info!(
|
|
ereignis = "aufbewahrung",
|
|
tabelle = what,
|
|
geloescht = n,
|
|
"Alte Log-Zeilen gelöscht"
|
|
),
|
|
Err(e) => tracing::error!(tabelle = what, fehler = %e, "Aufbewahrung fehlgeschlagen"),
|
|
}
|
|
}
|
|
tokio::time::sleep(Duration::from_secs(3600)).await;
|
|
}
|
|
}));
|
|
}
|
|
|
|
if config.engine_log_max_mb > 0 {
|
|
let mut dirs = vec![
|
|
llama_config(config)?.log_dir,
|
|
ollama_config(config)?.log_dir,
|
|
maya_config(config)?.log_dir,
|
|
strata_config(config)?.log_dir,
|
|
];
|
|
dirs.sort();
|
|
dirs.dedup();
|
|
let max_bytes = config.engine_log_max_mb * 1024 * 1024;
|
|
let keep = config.engine_log_keep;
|
|
jobs.push(tokio::spawn(async move {
|
|
loop {
|
|
for dir in &dirs {
|
|
let dir = dir.clone();
|
|
let capped = tokio::task::spawn_blocking(move || {
|
|
crate::logcap::cap_logs(&dir, max_bytes, keep)
|
|
})
|
|
.await
|
|
.unwrap_or_default();
|
|
for c in capped {
|
|
tracing::info!(
|
|
ereignis = "log_gekuerzt",
|
|
datei = %c.file.display(),
|
|
bytes = c.bytes,
|
|
"Engine-Log war zu groß, Kopie aufgehoben und gekürzt"
|
|
);
|
|
}
|
|
}
|
|
tokio::time::sleep(Duration::from_secs(60)).await;
|
|
}
|
|
}));
|
|
}
|
|
Ok(jobs)
|
|
}
|
|
|
|
async fn shutdown_signal() {
|
|
use tokio::signal::unix::{SignalKind, signal};
|
|
let mut term = signal(SignalKind::terminate()).expect("SIGTERM-Handler");
|
|
tokio::select! {
|
|
_ = tokio::signal::ctrl_c() => {}
|
|
_ = term.recv() => {}
|
|
}
|
|
}
|