Files
leleka/crates/deploy/tests/e2e_windows.rs
T

316 lines
10 KiB
Rust

//! The native supervisor on Windows processes, without a GPU or a model: `leleka.exe run` starts the gateway, the
//! engine and the API (test doubles named like the real programs), becomes ready, answers `status` and `reconfigure`
//! over HTTP, restarts the engine in place for a budget change, and stops by Ctrl-Break (the console signal) or by the
//! stop file of `leleka down`. Run with `cargo test -p leleka-deploy --features test-fakes --test e2e_windows`.
#![cfg(all(windows, feature = "test-fakes"))]
use leleka_deploy::{
config::{GATEWAY_TOKEN_ENV, Ports, RUNTIME_TOKEN_ENV, RunConfig, to_file_text},
layout::{BINARIES, Dirs},
profile::Profile,
};
use std::{
collections::BTreeMap,
fs,
io::{Read, Write},
net::TcpListener,
os::windows::process::CommandExt,
path::{Path, PathBuf},
process::{Child, Command, Stdio},
time::{Duration, Instant},
};
const FAKE: &str = env!("CARGO_BIN_EXE_leleka-fake-runtime");
const LELEKA: &str = env!("CARGO_BIN_EXE_leleka");
const KEY: &str = "fake-api-key-0123456789abcdef0123456789abcdef";
const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200;
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
#[path = "e2e_windows/checks.rs"]
mod checks;
use checks::*;
fn free_port() -> u16 {
TcpListener::bind(("127.0.0.1", 0))
.unwrap()
.local_addr()
.unwrap()
.port()
}
struct Fixture {
root: PathBuf,
dirs: Dirs,
ports: Ports,
}
impl Fixture {
fn new(name: &str) -> Fixture {
let root =
std::env::temp_dir().join(format!("leleka-e2e-win-{}-{name}", std::process::id()));
let _ = fs::remove_dir_all(&root);
fs::create_dir_all(&root).unwrap();
let dirs = Dirs {
prefix: root.join("prefix"),
state: root.join("state"),
assets: root.join("assets"),
};
let ports = Ports {
api: format!("127.0.0.1:{}", free_port()),
engine: format!("127.0.0.1:{}", free_port()),
daemon: format!("127.0.0.1:{}", free_port()),
};
let fixture = Fixture { root, dirs, ports };
fixture.install();
fixture
}
/// `PREFIX\bin` with the real `leleka.exe` and the test double under the names of the other four programs.
fn install(&self) {
let paths = self.dirs.paths();
fs::create_dir_all(paths.bin_dir()).unwrap();
for name in BINARIES {
let source = if name == "leleka.exe" { LELEKA } else { FAKE };
fs::copy(source, paths.bin_dir().join(name)).unwrap();
}
fs::create_dir_all(paths.logs()).unwrap();
fs::create_dir_all(paths.run_dir()).unwrap();
fs::write(
paths.env_file(),
format!(
"{RUNTIME_TOKEN_ENV}={}\n{GATEWAY_TOKEN_ENV}={}\n",
"r".repeat(40),
"g".repeat(40)
),
)
.unwrap();
fs::write(paths.api_key(), KEY).unwrap();
self.write_configs();
}
/// The run, daemon and gateway configuration files of the laptop profile.
fn write_configs(&self) {
let paths = self.dirs.paths();
// The laptop profile: the archive is a plain file, the experts are mapped. The double only checks that the file
// exists.
fs::create_dir_all(&self.dirs.assets).unwrap();
fs::write(paths.kar(), b"archive").unwrap();
let mut config = RunConfig::new(
&self.dirs,
self.ports.clone(),
0,
Profile::builtin("rtx3080-16g").unwrap(),
BTreeMap::new(),
);
config.shutdown_grace_s = 3;
fs::write(paths.run_config(), to_file_text(&config)).unwrap();
fs::write(paths.daemon_config(), to_file_text(&config.daemon_json())).unwrap();
fs::write(paths.strata_config(), to_file_text(&config.strata_json())).unwrap();
}
fn leleka(&self) -> PathBuf {
self.dirs.paths().bin("leleka")
}
/// `leleka.exe run --config ...` in its own process group (so that Ctrl-Break can be aimed at it), output to a
/// file.
fn start(&self) -> Child {
let log = fs::File::create(self.root.join("supervisor.out")).unwrap();
Command::new(self.leleka())
.args(["run", "--config"])
.arg(self.dirs.paths().run_config())
.stdin(Stdio::null())
.stdout(log.try_clone().unwrap())
.stderr(log)
.creation_flags(CREATE_NEW_PROCESS_GROUP)
.spawn()
.unwrap()
}
/// Run a `leleka` subcommand against this state directory and return (exit code, stdout, stderr).
fn cli(&self, args: &[&str]) -> (i32, String, String) {
let output = Command::new(self.leleka())
.args(args)
.arg("--native")
.arg("--state-dir")
.arg(&self.dirs.state)
.arg("--assets")
.arg(&self.dirs.assets)
.arg("--prefix")
.arg(&self.dirs.prefix)
.stdin(Stdio::null())
.creation_flags(CREATE_NO_WINDOW)
.output()
.unwrap();
(
output.status.code().unwrap_or(-1),
String::from_utf8_lossy(&output.stdout).into_owned(),
String::from_utf8_lossy(&output.stderr).into_owned(),
)
}
fn status(&self) -> Option<serde_json::Value> {
fs::read_to_string(self.dirs.paths().status_file())
.ok()
.and_then(|t| serde_json::from_str(&t).ok())
}
fn wait_for(
&self,
what: &str,
limit: Duration,
mut done: impl FnMut(&serde_json::Value) -> bool,
) -> serde_json::Value {
let started = Instant::now();
loop {
if let Some(status) = self.status()
&& done(&status)
{
return status;
}
assert!(
started.elapsed() < limit,
"timed out waiting for {what}; status {:?}\n{}",
self.status(),
self.logs()
);
std::thread::sleep(Duration::from_millis(200));
}
}
fn logs(&self) -> String {
let mut out = String::new();
for dir in [self.root.clone(), self.dirs.paths().logs()] {
if let Ok(entries) = fs::read_dir(dir) {
for entry in entries.flatten() {
if entry
.path()
.extension()
.is_some_and(|e| e == "log" || e == "out")
{
out.push_str(&format!(
"--- {} ---\n{}\n",
entry.path().display(),
fs::read_to_string(entry.path()).unwrap_or_default()
));
}
}
}
}
out
}
fn http_status(&self, path: &str) -> u16 {
let Ok(mut stream) = std::net::TcpStream::connect(&self.ports.api) else {
return 0;
};
let _ = stream.set_read_timeout(Some(Duration::from_secs(3)));
write!(
stream,
"GET {path} HTTP/1.1\r\nHost: x\r\nAuthorization: Bearer {KEY}\r\nConnection: \
close\r\n\r\n"
)
.unwrap();
let mut text = String::new();
let _ = stream.read_to_string(&mut text);
text.split_whitespace()
.nth(1)
.and_then(|s| s.parse().ok())
.unwrap_or(0)
}
fn engine_pid(&self) -> Option<u32> {
fs::read_to_string(self.dirs.prefix.join("fake").join("engine.pid"))
.ok()?
.trim()
.parse()
.ok()
}
}
impl Drop for Fixture {
fn drop(&mut self) {
// Anything that survived a failed assertion must not outlive the test.
if let Some(pid) = self.engine_pid() {
let _ = Command::new("taskkill")
.args(["/F", "/T", "/PID", &pid.to_string()])
.output();
}
let _ = fs::remove_dir_all(&self.root);
}
}
fn wait_exit(child: &mut Child, limit: Duration) -> Option<std::process::ExitStatus> {
let started = Instant::now();
while started.elapsed() < limit {
if let Some(status) = child.try_wait().unwrap() {
return Some(status);
}
std::thread::sleep(Duration::from_millis(100));
}
None
}
fn alive(pid: u32) -> bool {
leleka_deploy::winsys::process_alive(pid)
}
fn kill_tree(child: &mut Child) {
let _ = Command::new("taskkill")
.args(["/F", "/T", "/PID", &child.id().to_string()])
.output();
let _ = child.wait();
}
fn ready(fixture: &Fixture) -> serde_json::Value {
fixture.wait_for("ready", Duration::from_secs(90), |s| s["phase"] == "ready")
}
#[test]
fn the_supervisor_starts_serves_status_and_reconfigure_and_stops_by_ctrl_break() {
let fixture = Fixture::new("break");
let mut supervisor = fixture.start();
let status = ready(&fixture);
assert_eq!(status["engine_restarts"], 0);
assert_eq!(fixture.http_status("/ready"), 200, "{}", fixture.logs());
assert_eq!(fixture.http_status("/health"), 200);
let engine = fixture
.engine_pid()
.expect("the engine double wrote its pid");
assert!(alive(engine));
check_status_text_output(&fixture);
check_status_json_output(&fixture);
check_reconfigure_keeps_gateway_and_api_and_replaces_the_engine(&fixture, &status, engine);
check_ctrl_break_stops_everything(&fixture, &mut supervisor);
}
#[test]
fn leleka_down_stops_the_supervisor_through_the_stop_file() {
let fixture = Fixture::new("down");
let mut supervisor = fixture.start();
ready(&fixture);
let engine = fixture.engine_pid().unwrap();
let asked = Instant::now();
let (code, out, err) = fixture.cli(&["down"]);
assert_eq!(code, 0, "{out}{err}\n{}", fixture.logs());
// The children are stopped with Ctrl-Break in order; none has to be killed after its grace period (30 s each).
assert!(
asked.elapsed() < Duration::from_secs(25),
"stopping took {:?}",
asked.elapsed()
);
let exit = wait_exit(&mut supervisor, Duration::from_secs(60));
if exit.is_none() {
kill_tree(&mut supervisor);
panic!("the supervisor did not stop\n{}", fixture.logs());
}
assert_eq!(fixture.status().unwrap()["phase"], "stopped");
assert!(
!Path::new(&fixture.dirs.paths().run_dir().join("stop.request")).exists(),
"the request is consumed"
);
std::thread::sleep(Duration::from_millis(500));
assert!(!alive(engine));
check_nothing_runs_after_down(&fixture);
}