350 lines
11 KiB
Rust
350 lines
11 KiB
Rust
//! Integrationstests des Ollama-Adapters mit echten Prozessen.
|
|
//!
|
|
//! Statt `ollama` läuft `tests/fake_ollama.py`. Geprüft werden Serverstart,
|
|
//! Laden und Entladen, geteilter Server, Fehlerfälle und der Modus Attached.
|
|
//! Nicht geprüft wird, ob das echte Ollama sich genauso verhält (das ist auf
|
|
//! srv04 getrennt gemessen).
|
|
|
|
use std::collections::BTreeMap;
|
|
use std::path::{Path, PathBuf};
|
|
use std::process::{Child, Command, Stdio};
|
|
use std::sync::atomic::{AtomicU16, AtomicU32, Ordering};
|
|
use std::time::Duration;
|
|
|
|
use nexus_adapter::{
|
|
AdapterError, Engine, Health, OllamaConfig, OllamaEngine, OllamaMode, ProfileSpec,
|
|
process_exists,
|
|
};
|
|
|
|
static PORT_BLOCK: AtomicU16 = AtomicU16::new(19700);
|
|
static DIR_COUNTER: AtomicU32 = AtomicU32::new(0);
|
|
|
|
struct Fixture {
|
|
dir: PathBuf,
|
|
config: OllamaConfig,
|
|
}
|
|
|
|
impl Drop for Fixture {
|
|
fn drop(&mut self) {
|
|
let _ = std::fs::remove_dir_all(&self.dir);
|
|
}
|
|
}
|
|
|
|
fn fake_binary() -> PathBuf {
|
|
Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fake_ollama.py")
|
|
}
|
|
|
|
fn fixture(mode: &str, ready_timeout_secs: u64) -> Fixture {
|
|
let n = DIR_COUNTER.fetch_add(1, Ordering::SeqCst);
|
|
let dir = std::env::temp_dir().join(format!(
|
|
"nexus-adapter-ollama-it-{}-{n}",
|
|
std::process::id()
|
|
));
|
|
std::fs::create_dir_all(&dir).unwrap();
|
|
let from = PORT_BLOCK.fetch_add(10, Ordering::SeqCst);
|
|
let config = OllamaConfig {
|
|
binary: fake_binary(),
|
|
models_dir: dir.join("modelle"),
|
|
gpus: vec![0, 1],
|
|
port_from: from,
|
|
port_to: from + 9,
|
|
ready_timeout_secs,
|
|
log_dir: dir.join("logs"),
|
|
env: BTreeMap::from([("FAKE_OLLAMA_MODE".to_string(), mode.to_string())]),
|
|
..OllamaConfig::default()
|
|
};
|
|
Fixture { dir, config }
|
|
}
|
|
|
|
fn profile(alias: &str, tag: &str) -> ProfileSpec {
|
|
ProfileSpec {
|
|
model_alias: alias.to_string(),
|
|
model_path: PathBuf::from(tag),
|
|
gpus: vec![0],
|
|
context: None,
|
|
extra_args: vec![],
|
|
}
|
|
}
|
|
|
|
fn server_log(f: &Fixture) -> String {
|
|
std::fs::read_to_string(f.dir.join("logs/instance-ollama.log")).unwrap_or_default()
|
|
}
|
|
|
|
fn pid_from_log(log: &str) -> u32 {
|
|
log.lines()
|
|
.find_map(|l| l.strip_prefix("fake-ollama: pid "))
|
|
.and_then(|p| p.trim().parse().ok())
|
|
.expect("PID im Log")
|
|
}
|
|
|
|
async fn wait_until_gone(pid: u32) -> bool {
|
|
for _ in 0..50 {
|
|
if !process_exists(pid) {
|
|
return true;
|
|
}
|
|
tokio::time::sleep(Duration::from_millis(100)).await;
|
|
}
|
|
false
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn managed_start_endpoint_messung_und_stopp() {
|
|
let f = fixture("ok", 20);
|
|
let engine = OllamaEngine::new(f.config.clone());
|
|
let inst = engine
|
|
.start(&profile("klein", "qwen3:0.6b"))
|
|
.await
|
|
.expect("Start");
|
|
let pid = inst.pid.expect("PID des Servers");
|
|
|
|
assert_eq!(engine.health(&inst).await, Health::Ready);
|
|
let endpoint = engine.endpoint(&inst);
|
|
assert_eq!(endpoint.base_url, format!("http://127.0.0.1:{}", inst.port));
|
|
assert_eq!(endpoint.upstream_model.as_deref(), Some("qwen3:0.6b"));
|
|
|
|
let log = server_log(&f);
|
|
assert!(
|
|
log.contains(&format!("OLLAMA_HOST=127.0.0.1:{}", inst.port)),
|
|
"{log}"
|
|
);
|
|
assert!(
|
|
log.contains("OLLAMA_KEEP_ALIVE=-1") && log.contains("OLLAMA_NOPRUNE=1"),
|
|
"{log}"
|
|
);
|
|
assert!(log.contains("CUDA_VISIBLE_DEVICES=0,1"), "{log}");
|
|
assert!(log.contains("OLLAMA_MODELS="), "{log}");
|
|
|
|
let usage = engine.measure(&inst).await;
|
|
assert_eq!(usage.vram_mb, Some(500_000_000 / (1024 * 1024)));
|
|
assert_eq!(usage.ram_mb, Some(100_000_000 / (1024 * 1024)));
|
|
|
|
engine.stop(&inst, Duration::from_secs(5)).await.unwrap();
|
|
assert!(
|
|
wait_until_gone(pid).await,
|
|
"Der Server lief nach dem letzten Modell weiter"
|
|
);
|
|
assert_eq!(engine.health(&inst).await, Health::Gone);
|
|
engine.stop(&inst, Duration::from_secs(1)).await.unwrap();
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn zwei_modelle_teilen_sich_einen_server_der_mit_dem_letzten_endet() {
|
|
let f = fixture("ok", 20);
|
|
let engine = OllamaEngine::new(f.config.clone());
|
|
let a = engine.start(&profile("a", "qwen3:0.6b")).await.unwrap();
|
|
let b = engine.start(&profile("b", "llama3")).await.unwrap();
|
|
assert_eq!((a.port, a.pid), (b.port, b.pid), "ein Server für beide");
|
|
assert_ne!(a.id, b.id);
|
|
let pid = a.pid.unwrap();
|
|
|
|
engine.stop(&a, Duration::from_secs(5)).await.unwrap();
|
|
assert!(
|
|
process_exists(pid),
|
|
"Der Server muss für das zweite Modell weiterlaufen"
|
|
);
|
|
assert_eq!(engine.health(&a).await, Health::Gone);
|
|
assert_eq!(engine.health(&b).await, Health::Ready);
|
|
|
|
engine.stop(&b, Duration::from_secs(5)).await.unwrap();
|
|
assert!(wait_until_gone(pid).await);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn unbekanntes_modell_gibt_invalid_profile_und_hinterlaesst_keinen_server() {
|
|
let f = fixture("ok", 20);
|
|
let engine = OllamaEngine::new(f.config.clone());
|
|
let err = engine
|
|
.start(&profile("x", "gibt-es-nicht:1b"))
|
|
.await
|
|
.unwrap_err();
|
|
assert!(
|
|
matches!(&err, AdapterError::InvalidProfile(m) if m.contains("gibt-es-nicht:1b")),
|
|
"{err}"
|
|
);
|
|
let pid = pid_from_log(&server_log(&f));
|
|
assert!(
|
|
wait_until_gone(pid).await,
|
|
"Der Server blieb ohne Modell zurück"
|
|
);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn profil_mit_nicht_erlaubter_gpu_wird_abgelehnt_ohne_serverstart() {
|
|
let f = fixture("ok", 20);
|
|
let engine = OllamaEngine::new(f.config.clone());
|
|
let mut p = profile("x", "qwen3:0.6b");
|
|
p.gpus = vec![7];
|
|
assert!(matches!(
|
|
engine.start(&p).await,
|
|
Err(AdapterError::InvalidProfile(_))
|
|
));
|
|
assert!(
|
|
server_log(&f).is_empty(),
|
|
"Es darf kein Server gestartet worden sein"
|
|
);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn absturz_beim_start_liefert_log_ende_und_exit_code() {
|
|
let f = fixture("crash", 20);
|
|
let engine = OllamaEngine::new(f.config.clone());
|
|
match engine.start(&profile("x", "qwen3:0.6b")).await.unwrap_err() {
|
|
AdapterError::ExitedEarly { code, log_tail } => {
|
|
assert_eq!(code, Some(4));
|
|
assert!(log_tail.contains("could not bind"), "{log_tail}");
|
|
}
|
|
other => panic!("falscher Fehler: {other}"),
|
|
}
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn server_der_nie_bereit_wird_fuehrt_zur_zeitueberschreitung_und_wird_beendet() {
|
|
let f = fixture("hang", 1);
|
|
let engine = OllamaEngine::new(f.config.clone());
|
|
let err = engine.start(&profile("x", "qwen3:0.6b")).await.unwrap_err();
|
|
assert!(
|
|
matches!(err, AdapterError::NotReady { seconds: 1, .. }),
|
|
"{err}"
|
|
);
|
|
let pid = pid_from_log(&server_log(&f));
|
|
assert!(wait_until_gone(pid).await, "Prozess blieb zurück");
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn von_aussen_beendeter_server_wird_als_gone_erkannt_und_neu_gestartet() {
|
|
let f = fixture("ok", 20);
|
|
let engine = OllamaEngine::new(f.config.clone());
|
|
let inst = engine.start(&profile("a", "qwen3:0.6b")).await.unwrap();
|
|
let pid = inst.pid.unwrap();
|
|
// SAFETY: beendet gezielt den Prozess, den dieser Test selbst gestartet hat.
|
|
assert_eq!(unsafe { libc::kill(pid as i32, libc::SIGKILL) }, 0);
|
|
|
|
let mut health = engine.health(&inst).await;
|
|
for _ in 0..50 {
|
|
if health == Health::Gone {
|
|
break;
|
|
}
|
|
tokio::time::sleep(Duration::from_millis(100)).await;
|
|
health = engine.health(&inst).await;
|
|
}
|
|
assert_eq!(health, Health::Gone);
|
|
|
|
let neu = engine
|
|
.start(&profile("a", "qwen3:0.6b"))
|
|
.await
|
|
.expect("Neustart");
|
|
assert_ne!(neu.pid, inst.pid);
|
|
assert_eq!(engine.health(&neu).await, Health::Ready);
|
|
engine.stop(&neu, Duration::from_secs(5)).await.unwrap();
|
|
}
|
|
|
|
/// Startet die Attrappe als eigenständigen Server (nicht vom Adapter verwaltet).
|
|
fn external_server(port: u16) -> Child {
|
|
let child = Command::new(fake_binary())
|
|
.arg("serve")
|
|
.env("OLLAMA_HOST", format!("127.0.0.1:{port}"))
|
|
.stdout(Stdio::null())
|
|
.stderr(Stdio::null())
|
|
.spawn()
|
|
.expect("Attrappe starten");
|
|
for _ in 0..50 {
|
|
if std::net::TcpStream::connect(("127.0.0.1", port)).is_ok() {
|
|
break;
|
|
}
|
|
std::thread::sleep(Duration::from_millis(100));
|
|
}
|
|
child
|
|
}
|
|
|
|
fn attached(port: u16) -> OllamaEngine {
|
|
OllamaEngine::new(OllamaConfig {
|
|
mode: OllamaMode::Attached,
|
|
base_url: format!("http://127.0.0.1:{port}/"),
|
|
ready_timeout_secs: 10,
|
|
..OllamaConfig::default()
|
|
})
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn attached_laedt_und_entlaedt_ohne_den_server_zu_beenden() {
|
|
let port = PORT_BLOCK.fetch_add(10, Ordering::SeqCst);
|
|
let mut server = external_server(port);
|
|
let engine = attached(port);
|
|
|
|
let inst = engine
|
|
.start(&profile("a", "qwen3:0.6b"))
|
|
.await
|
|
.expect("Start");
|
|
assert_eq!(inst.pid, None);
|
|
assert_eq!(engine.health(&inst).await, Health::Ready);
|
|
assert_eq!(
|
|
engine.endpoint(&inst).base_url,
|
|
format!("http://127.0.0.1:{port}")
|
|
);
|
|
|
|
engine.stop(&inst, Duration::from_secs(5)).await.unwrap();
|
|
assert_eq!(engine.health(&inst).await, Health::Gone);
|
|
assert!(
|
|
server.try_wait().unwrap().is_none(),
|
|
"Der externe Server muss weiterlaufen"
|
|
);
|
|
|
|
// Ein neuer Start lädt das Modell wieder.
|
|
let neu = engine.start(&profile("a", "qwen3:0.6b")).await.unwrap();
|
|
assert_eq!(engine.health(&neu).await, Health::Ready);
|
|
|
|
let _ = server.kill();
|
|
let _ = server.wait();
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn attached_erkennt_ein_vom_server_entladenes_modell() {
|
|
let port = PORT_BLOCK.fetch_add(10, Ordering::SeqCst);
|
|
let mut server = external_server(port);
|
|
let engine = attached(port);
|
|
let inst = engine.start(&profile("a", "qwen3:0.6b")).await.unwrap();
|
|
|
|
// Der Server entlädt das Modell von sich aus (eigener Leerlauf-Timeout).
|
|
let http = reqwest::Client::new();
|
|
http.post(format!("http://127.0.0.1:{port}/api/generate"))
|
|
.header("content-type", "application/json")
|
|
.body(r#"{"model":"qwen3:0.6b","keep_alive":0}"#)
|
|
.send()
|
|
.await
|
|
.unwrap();
|
|
assert_eq!(engine.health(&inst).await, Health::Gone);
|
|
|
|
let _ = server.kill();
|
|
let _ = server.wait();
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn attached_ohne_erreichbaren_server_ist_not_ready() {
|
|
// Ein freier Port, auf dem niemand lauscht.
|
|
let port = {
|
|
let l = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap();
|
|
l.local_addr().unwrap().port()
|
|
};
|
|
let err = attached(port)
|
|
.start(&profile("a", "qwen3:0.6b"))
|
|
.await
|
|
.unwrap_err();
|
|
assert!(matches!(err, AdapterError::NotReady { .. }), "{err}");
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn discover_liest_die_manifeste_des_modellordners() {
|
|
let f = fixture("ok", 5);
|
|
let manifest = f
|
|
.config
|
|
.models_dir
|
|
.join("manifests/registry.ollama.ai/library/qwen3/0.6b");
|
|
std::fs::create_dir_all(manifest.parent().unwrap()).unwrap();
|
|
std::fs::write(&manifest, r#"{"config":{"size":1},"layers":[{"size":9}]}"#).unwrap();
|
|
let engine = OllamaEngine::new(f.config.clone());
|
|
let found = engine.discover().await.unwrap();
|
|
assert_eq!(found.len(), 1, "{found:?}");
|
|
assert_eq!(found[0].name, "qwen3:0.6b");
|
|
assert_eq!(found[0].size_bytes, 10);
|
|
}
|