diff --git a/crates/deploy/build.rs b/crates/deploy/build.rs index 8b217bce..3f98f5fc 100644 --- a/crates/deploy/build.rs +++ b/crates/deploy/build.rs @@ -38,37 +38,14 @@ fn main() { std::env::var_os("CARGO_MANIFEST_DIR").expect("cargo sets CARGO_MANIFEST_DIR"), ); let repo = manifest.join("..").join(".."); - - println!("cargo:rerun-if-env-changed=LELEKA_GIT_COMMIT"); - println!("cargo:rerun-if-env-changed=LELEKA_GIT_DIRTY"); let doc = repo.join("docs").join("upstream.md"); - println!("cargo:rerun-if-changed={}", doc.display()); - // A commit moves the reflog of HEAD; a branch switch moves HEAD itself. - for name in ["HEAD", "logs/HEAD"] { - if let Some(path) = git(&repo, &["rev-parse", "--git-path", name]) { - println!("cargo:rerun-if-changed={}", repo.join(path).display()); - } - } - + emit_reruns(&repo, &doc); let commit = std::env::var("LELEKA_GIT_COMMIT") .ok() .filter(|value| !value.trim().is_empty()) .or_else(|| git(&repo, &["rev-parse", "HEAD"])) .unwrap_or_else(|| "unknown".to_owned()); - let dirty = match std::env::var("LELEKA_GIT_DIRTY") - .ok() - .filter(|value| !value.trim().is_empty()) - { - Some(value) => match value.trim() { - "0" | "no" | "false" | "clean" => "clean", - _ => "dirty", - }, - None => match git(&repo, &["status", "--porcelain", "--untracked-files=no"]) { - Some(status) if status.is_empty() => "clean", - Some(_) => "dirty", - None => "unknown", - }, - }; + let dirty = tree_state(&repo); let pin = upstream_pin(&doc).unwrap_or_else(|| "unknown".to_owned()); println!("cargo:rustc-env=LELEKA_BUILD_COMMIT={commit}"); @@ -83,3 +60,34 @@ fn main() { std::env::var("PROFILE").unwrap_or_else(|_| "unknown".to_owned()) ); } + +/// When cargo has to run this script again: the packager variables, the pin document, a commit or a branch switch. +fn emit_reruns(repo: &Path, doc: &Path) { + println!("cargo:rerun-if-env-changed=LELEKA_GIT_COMMIT"); + println!("cargo:rerun-if-env-changed=LELEKA_GIT_DIRTY"); + println!("cargo:rerun-if-changed={}", doc.display()); + // A commit moves the reflog of HEAD; a branch switch moves HEAD itself. + for name in ["HEAD", "logs/HEAD"] { + if let Some(path) = git(repo, &["rev-parse", "--git-path", name]) { + println!("cargo:rerun-if-changed={}", repo.join(path).display()); + } + } +} + +/// `clean`, `dirty` or `unknown`: from the packager variable, else from git. +fn tree_state(repo: &Path) -> &'static str { + match std::env::var("LELEKA_GIT_DIRTY") + .ok() + .filter(|value| !value.trim().is_empty()) + { + Some(value) => match value.trim() { + "0" | "no" | "false" | "clean" => "clean", + _ => "dirty", + }, + None => match git(repo, &["status", "--porcelain", "--untracked-files=no"]) { + Some(status) if status.is_empty() => "clean", + Some(_) => "dirty", + None => "unknown", + }, + } +} diff --git a/crates/deploy/src/app.rs b/crates/deploy/src/app.rs index 0fa777a0..3f99f3fb 100644 --- a/crates/deploy/src/app.rs +++ b/crates/deploy/src/app.rs @@ -29,20 +29,23 @@ mod status_tests; mod entry; mod install_flow; +mod machine_view; mod preflight_report; +mod quick_health; mod settings_change; mod status_report; mod stop_flow; mod verify_flow; pub use entry::{env_var, main_native, main_with, version_text}; pub use install_flow::{powershell_try, run_up, summary, summary_json, up}; +pub use machine_view::render_machine; #[cfg(unix)] use preflight_report::seal_probe; #[cfg(not(unix))] use preflight_report::seal_probe; use preflight_report::{json_plan, preflight, print_report}; use settings_change::reconfigure; -pub use settings_change::{render_effective, render_machine, render_settings, send_reconfigure}; +pub use settings_change::{render_effective, render_settings, send_reconfigure}; pub use status_report::{age_text, print_status, render_supervisor}; use status_report::{installed_scope, status, unix_now}; use stop_flow::down; diff --git a/crates/deploy/src/app/entry.rs b/crates/deploy/src/app/entry.rs index 73cf7d4a..2799464a 100644 --- a/crates/deploy/src/app/entry.rs +++ b/crates/deploy/src/app/entry.rs @@ -69,13 +69,32 @@ pub async fn main_native(mut args: Vec) -> i32 { home: home_dir(), var: &var, }; - let command = match parse(&args, &environment) { - Ok(command) => command, + match parse(&args, &environment) { + Ok(command) => run_command(command).await, Err(message) => { eprintln!("leleka: {message}"); - return 2; + 2 } - }; + } +} + +/// The commands that work on the installation; the others are the small ones of [`run_local_command`]. +async fn run_command(command: Command) -> i32 { + match command { + Command::Preflight(opts) => preflight(opts).await, + Command::Up(opts) => up(opts).await, + Command::Status(opts) => status(opts).await, + Command::Down(opts) => down(opts).await, + Command::Reconfigure(opts, args) => reconfigure(opts, args).await, + Command::Verify(opts) => verify(opts).await, + Command::Logs(opts, args) => crate::logview::run_logs(&opts, &args), + Command::Report(opts, args) => crate::logview::run_report(&opts, &args), + Command::Service(action, opts) => crate::winservice::run_native(action, opts).await, + other => run_local_command(other).await, + } +} + +async fn run_local_command(command: Command) -> i32 { match command { Command::Help => { print!("{USAGE}"); @@ -92,42 +111,46 @@ pub async fn main_native(mut args: Vec) -> i32 { } 0 } - Command::Profiles(Some(name)) => match Profile::builtin(&name) { - Some(profile) => { - print!("{}", crate::config::to_file_text(&profile)); - 0 - } - None => { - eprintln!("leleka: unknown profile {name:?}"); - 2 - } - }, - Command::Preflight(opts) => preflight(opts).await, - Command::Up(opts) => up(opts).await, - Command::Status(opts) => status(opts).await, - Command::Down(opts) => down(opts).await, - Command::Reconfigure(opts, args) => reconfigure(opts, args).await, - Command::Verify(opts) => verify(opts).await, - Command::Logs(opts, args) => crate::logview::run_logs(&opts, &args), - Command::Report(opts, args) => crate::logview::run_report(&opts, &args), - Command::Service(action, opts) => crate::winservice::run_native(action, opts).await, + Command::Profiles(Some(name)) => show_profile(&name), Command::Run { config, kar_fd } => { supervisor::run(supervisor::Options { config, kar_fd }).await } Command::SealProbe(file) => seal_probe(&file), - Command::ExecInherit(rest) => match crate::sealed::exec_inherit(&rest) { - Ok(never) => match never {}, - Err(message) => { - eprintln!("leleka exec-inherit: {message}"); - 2 - } - }, - Command::SealExec(rest) => match crate::sealed::seal_exec(&rest) { - Ok(never) => match never {}, - Err(message) => { - eprintln!("leleka seal-exec: {message}"); - 2 - } - }, + Command::ExecInherit(rest) => exec_inherit_command(&rest), + Command::SealExec(rest) => seal_exec_command(&rest), + _ => unreachable!("run_command takes the commands of the installation"), + } +} + +fn show_profile(name: &str) -> i32 { + match Profile::builtin(name) { + Some(profile) => { + print!("{}", crate::config::to_file_text(&profile)); + 0 + } + None => { + eprintln!("leleka: unknown profile {name:?}"); + 2 + } + } +} + +fn exec_inherit_command(rest: &[String]) -> i32 { + match crate::sealed::exec_inherit(rest) { + Ok(never) => match never {}, + Err(message) => { + eprintln!("leleka exec-inherit: {message}"); + 2 + } + } +} + +fn seal_exec_command(rest: &[String]) -> i32 { + match crate::sealed::seal_exec(rest) { + Ok(never) => match never {}, + Err(message) => { + eprintln!("leleka seal-exec: {message}"); + 2 + } } } diff --git a/crates/deploy/src/app/install_flow.rs b/crates/deploy/src/app/install_flow.rs index dd09871f..b92c86e6 100644 --- a/crates/deploy/src/app/install_flow.rs +++ b/crates/deploy/src/app/install_flow.rs @@ -18,22 +18,9 @@ pub async fn up(opts: UpOptions) -> i32 { } let fs = gather_fs(&ctx).await; let steps = plan_steps(&ctx, &fs); - let blocked = steps - .iter() - .any(|s| matches!(s.state, StepState::Blocked(_)) && s.id != "preflight"); + let blocked = has_blocked_step(&steps); if opts.dry_run { - if opts.json { - println!( - "{}", - serde_json::to_string_pretty(&json_plan(&ctx, &steps)).expect("serializable") - ); - } else { - print!("{}", render_plan(&ctx, &steps)); - println!( - "mode: {}; nothing was changed (--dry-run)", - ctx.mode.label() - ); - } + print_dry_run(&ctx, &steps); return i32::from(report.failed() || blocked); } if report.failed() { @@ -43,7 +30,18 @@ pub async fn up(opts: UpOptions) -> i32 { return 1; } eprint!("{}", render_plan(&ctx, &steps)); - match run_up(&ctx, &steps).await { + finish_up(run_up(&ctx, &steps).await) +} + +/// A step other than the preflight that cannot run. +fn has_blocked_step(steps: &[Step]) -> bool { + steps + .iter() + .any(|s| matches!(s.state, StepState::Blocked(_)) && s.id != "preflight") +} + +fn finish_up(result: Result) -> i32 { + match result { Ok(code) => code, Err(message) => { eprintln!("leleka: {message}"); @@ -55,6 +53,21 @@ pub async fn up(opts: UpOptions) -> i32 { } } +fn print_dry_run(ctx: &Context, steps: &[Step]) { + if ctx.opts.json { + println!( + "{}", + serde_json::to_string_pretty(&json_plan(ctx, steps)).expect("serializable") + ); + } else { + print!("{}", render_plan(ctx, steps)); + println!( + "mode: {}; nothing was changed (--dry-run)", + ctx.mode.label() + ); + } +} + pub async fn run_up(ctx: &Context, steps: &[Step]) -> Result { let changes = steps::prepare(ctx, steps).await?; let config = steps::config_of(ctx)?; @@ -67,62 +80,87 @@ pub async fn run_up(ctx: &Context, steps: &[Step]) -> Result { )); Ok(0) } - Mode::Systemd(scope) => { - #[cfg(unix)] - if scope == UnitScopeTag::System { - steps::ensure_service_user(ctx).await?; - steps::hand_over_to_service_user(ctx)?; - } - let changed = steps::install_unit(ctx, scope).await?; - steps::start_unit(ctx, scope, changed || changes.needs_restart()).await?; - steps::wait_ready(ctx, Some(scope)).await?; - summary(ctx, config); - Ok(0) - } - Mode::Foreground => { - if let Some(fd) = ctx.opts.kar_fd { - if config.profile.kar_source == crate::profile::KarSource::None { - return Err(format!( - "--kar-fd {fd} was given but profile {} has kar_source none (no archive is used); drop --kar-fd", - config.profile.name - )); - } - crate::sealed::check_inherited_archive(fd, crate::profile::ARCHIVE_BYTES)?; - } - if steps::probe_ready(ctx).await { - say("a supervisor for this state directory is already ready"); - summary(ctx, config); - return Ok(0); - } - if crate::plan::service_running(&ctx.paths) { - return Err(format!( - "another supervisor is running for {} (not ready yet); wait for it or stop it first", - ctx.opts.dirs.state.display() - )); - } - let options = supervisor::Options { - config: ctx.paths.run_config(), - kar_fd: ctx.opts.kar_fd, - }; - let run = supervisor::run(options); - tokio::pin!(run); - let mut printed = false; - loop { - tokio::select! { - code = &mut run => return Ok(code), - ready = steps::wait_ready(ctx, None), if !printed => { - printed = true; - match ready { - Ok(()) => summary(ctx, config), - Err(message) => say(&message), - } - } + Mode::Systemd(scope) => run_systemd(ctx, scope, config, changes.needs_restart()).await, + Mode::Foreground => run_foreground(ctx, config).await, + } +} + +/// Install the unit, start it (again when something changed) and wait until it answers. +async fn run_systemd( + ctx: &Context, + scope: UnitScopeTag, + config: &crate::config::RunConfig, + restart_needed: bool, +) -> Result { + #[cfg(unix)] + if scope == UnitScopeTag::System { + steps::ensure_service_user(ctx).await?; + steps::hand_over_to_service_user(ctx)?; + } + let changed = steps::install_unit(ctx, scope).await?; + steps::start_unit(ctx, scope, changed || restart_needed).await?; + steps::wait_ready(ctx, Some(scope)).await?; + summary(ctx, config); + Ok(0) +} + +/// Run the supervisor in this process; the summary is printed as soon as the service answers. +async fn run_foreground(ctx: &Context, config: &crate::config::RunConfig) -> Result { + check_inherited_descriptor(ctx, config)?; + if steps::probe_ready(ctx).await { + say("a supervisor for this state directory is already ready"); + summary(ctx, config); + return Ok(0); + } + if crate::plan::service_running(&ctx.paths) { + return Err(format!( + "another supervisor is running for {} (not ready yet); wait for it or stop it first", + ctx.opts.dirs.state.display() + )); + } + Ok(serve_until_exit(ctx, config).await) +} + +/// The supervisor runs here; its exit code ends the call, and the summary is printed once the service answers. +async fn serve_until_exit(ctx: &Context, config: &crate::config::RunConfig) -> i32 { + let options = supervisor::Options { + config: ctx.paths.run_config(), + kar_fd: ctx.opts.kar_fd, + }; + let run = supervisor::run(options); + tokio::pin!(run); + let mut printed = false; + loop { + tokio::select! { + code = &mut run => return code, + ready = steps::wait_ready(ctx, None), if !printed => { + printed = true; + match ready { + Ok(()) => summary(ctx, config), + Err(message) => say(&message), } } } } } +/// A descriptor passed with `--kar-fd` must suit the profile and be what the engine accepts. +fn check_inherited_descriptor( + ctx: &Context, + config: &crate::config::RunConfig, +) -> Result<(), String> { + let Some(fd) = ctx.opts.kar_fd else { + return Ok(()); + }; + if config.profile.kar_source == crate::profile::KarSource::None { + return Err(format!( + "--kar-fd {fd} was given but profile {} has kar_source none (no archive is used); drop --kar-fd", + config.profile.name + )); + } + crate::sealed::check_inherited_archive(fd, crate::profile::ARCHIVE_BYTES) +} + pub fn summary_json(ctx: &Context, config: &crate::config::RunConfig) -> Value { let gpu = ctx.facts.gpus.iter().find(|g| g.index == ctx.opts.gpu); json!({ @@ -146,8 +184,11 @@ pub fn summary_json(ctx: &Context, config: &crate::config::RunConfig) -> Value { }) } +fn gib(bytes: u64) -> String { + format!("{:.1} GiB", bytes as f64 / (1u64 << 30) as f64) +} + pub fn summary(ctx: &Context, config: &crate::config::RunConfig) { - let gib = |bytes: u64| format!("{:.1} GiB", bytes as f64 / (1u64 << 30) as f64); if ctx.opts.json { println!( "{}", @@ -155,13 +196,21 @@ pub fn summary(ctx: &Context, config: &crate::config::RunConfig) { ); return; } - let gpu = ctx.facts.gpus.iter().find(|g| g.index == ctx.opts.gpu); let key_file = ctx.paths.api_key().display().to_string(); let mut text = String::from("\nLeleka is ready.\n"); - text.push_str(&format!( + text.push_str(&endpoint_lines(ctx, config, &key_file)); + text.push_str(&profile_line(config)); + text.push_str(&host_lines(ctx, config)); + text.push_str(&try_line(ctx, config, &key_file)); + eprintln!("{text}"); +} + +fn endpoint_lines(ctx: &Context, config: &crate::config::RunConfig, key_file: &str) -> String { + let gpu = ctx.facts.gpus.iter().find(|g| g.index == ctx.opts.gpu); + let mut text = format!( " endpoint http://{} (loopback only; reach it from elsewhere through an SSH tunnel)\n", ctx.opts.ports.api - )); + ); text.push_str(&format!( " model {} {}\n", config.model_id, config.model_digest @@ -179,58 +228,76 @@ pub fn summary(ctx: &Context, config: &crate::config::RunConfig) { gpu.driver )); } - text.push_str(&format!( + text +} + +fn profile_line(config: &crate::config::RunConfig) -> String { + format!( " profile {}: VRAM budget {}, context {} tokens, KAR archive as {}\n", config.profile.name, gib(config.profile.gpu_budget_bytes), config.profile.context_tokens, - match config.profile.kar_source { - crate::profile::KarSource::Memfd => format!( - "a sealed memfd ({} of RAM held for the life of the service{})", - gib(config.profile.memfd_bytes()), - if config.profile.memfd_extents == crate::profile::MemfdExtents::PleOnly { - "; sparse copy: only the byte ranges the serve path reads, holes elsewhere" - } else { - "" - } - ), - crate::profile::KarSource::File => "a read-only file (page cache only)".to_owned(), - crate::profile::KarSource::None => - "none (EXPERIMENTAL: no archive; the PLE rows are read from the GGUF shard, qwen4exp-native-mtp-v1)".to_owned(), - } - )); - text.push_str(&format!( + archive_form(config) + ) +} + +/// How the profile holds the KAR archive, in words. +fn archive_form(config: &crate::config::RunConfig) -> String { + match config.profile.kar_source { + crate::profile::KarSource::Memfd => format!( + "a sealed memfd ({} of RAM held for the life of the service{})", + gib(config.profile.memfd_bytes()), + if config.profile.memfd_extents == crate::profile::MemfdExtents::PleOnly { + "; sparse copy: only the byte ranges the serve path reads, holes elsewhere" + } else { + "" + } + ), + crate::profile::KarSource::File => "a read-only file (page cache only)".to_owned(), + crate::profile::KarSource::None => concat!( + "none (EXPERIMENTAL: no archive; the PLE rows are read from the GGUF ", + "shard, qwen4exp-native-mtp-v1)" + ) + .to_owned(), + } +} + +fn host_lines(ctx: &Context, config: &crate::config::RunConfig) -> String { + let mut text = format!( " host RAM {} total, {} available before start\n", gib(ctx.facts.memory.total), gib(ctx.facts.memory.available) - )); + ); text.push_str(&format!( " expert {}\n", crate::expert_profile::tier_report(config, &ctx.opts.dirs.assets).line() )); text.push_str(&format!(" service {}\n", ctx.mode.label())); if ctx.mode == Mode::Systemd(UnitScopeTag::User) { - text.push_str(" a user unit runs while you have a session; `loginctl enable-linger $USER` starts it at boot -"); + text.push_str(concat!( + " a user unit runs while you have a session; `loginctl ", + "enable-linger $USER` starts it at boot\n" + )); } text.push_str(&format!( " logs {} (leleka.log, engine.log, gateway.log, api.log)\n", ctx.paths.logs().display() )); + text +} + +/// The command that sends one request: PowerShell on Windows, `curl` elsewhere. +fn try_line(ctx: &Context, config: &crate::config::RunConfig, key_file: &str) -> String { if ctx.facts.os == "windows" { - text.push_str(&format!( - " try {} -", - powershell_try(&key_file, &ctx.opts.ports.api, &config.model_id) - )); - eprintln!("{text}"); - return; + return format!( + " try {}\n", + powershell_try(key_file, &ctx.opts.ports.api, &config.model_id) + ); } - text.push_str(&format!( + format!( " try curl -s -H \"Authorization: Bearer $(cat {key_file})\" -H 'content-type: application/json' \\\n -d '{{\"model\":\"{}\",\"input\":\"hello\",\"max_output_tokens\":32}}' http://{}/v1/responses\n", config.model_id, ctx.opts.ports.api - )); - eprintln!("{text}"); + ) } /// A PowerShell one-liner that sends one request to the API (the key file may be a UNC path into WSL). diff --git a/crates/deploy/src/app/machine_view.rs b/crates/deploy/src/app/machine_view.rs new file mode 100644 index 00000000..d1901a40 --- /dev/null +++ b/crates/deploy/src/app/machine_view.rs @@ -0,0 +1,114 @@ +//! The human view of the engine telemetry (`machine` of `/v1/status`). + +use super::*; + +fn gib(mib: &Value) -> String { + mib.as_f64() + .map_or("?".to_owned(), |m| format!("{:.1}", m / 1024.0)) +} + +fn num(value: &Value) -> String { + value.as_f64().map_or("-".to_owned(), |v| format!("{v:.0}")) +} + +fn pct(value: &Value) -> String { + value + .as_f64() + .map_or("-".to_owned(), |v| format!("{:.0}%", v * 100.0)) +} + +/// The human view of the engine telemetry document (`machine` of `/v1/status`): GPU, CPU, RAM, throughput, cache, +/// context. +pub fn render_machine(machine: &Value) -> String { + let mut out = format!( + "engine load ({}):\n", + machine["phase"].as_str().unwrap_or("?") + ); + if machine["gpu"].is_object() { + out.push_str(&gpu_line(&machine["gpu"])); + } + let cpu = &machine["cpu"]; + if cpu.is_object() { + out.push_str(&format!( + " cpu {} of {} cores busy in the engine (whole system {}%)\n", + cpu["process_busy_cores"], cpu["cores"], cpu["system_busy_pct"] + )); + } + if machine["ram"].is_object() { + out.push_str(&ram_line(&machine["ram"])); + } + out.push_str(&throughput_lines(&machine["throughput"])); + out.push_str(&cache_line(&machine["cache"])); + out.push_str(&context_line(&machine["context"])); + if machine["settings"].is_object() { + out.push_str("settings in force:\n"); + out.push_str(&render_settings(&machine["settings"])); + } + out +} + +fn gpu_line(gpu: &Value) -> String { + format!( + " gpu {}% busy (memory bus {}%), VRAM {} of {} GiB{}{}{}\n", + gpu["util_pct"], + gpu["mem_util_pct"], + gib(&gpu["vram_used_mib"]), + gib(&gpu["vram_total_mib"]), + gpu["power_w"] + .as_f64() + .map_or(String::new(), |w| format!(", {w:.0} W")), + gpu["sm_clock_mhz"] + .as_u64() + .map_or(String::new(), |m| format!(", {m} MHz")), + gpu["temp_c"] + .as_u64() + .map_or(String::new(), |t| format!(", {t} C")), + ) +} + +fn ram_line(ram: &Value) -> String { + format!( + " ram {} of {} GiB available, engine {} GiB resident ({} GiB pinned), swap in use {} GiB\n", + gib(&ram["available_mib"]), + gib(&ram["total_mib"]), + gib(&ram["process_rss_mib"]), + gib(&ram["process_pinned_mib"]), + gib(&ram["swap_used_mib"]) + ) +} + +fn throughput_lines(rates: &Value) -> String { + format!( + " prefill {} tok/s last, {} average, {} lifetime\n decode {} tok/s last, {} average, {} lifetime{}\n", + num(&rates["prefill_tok_s_last"]), + num(&rates["prefill_tok_s_avg"]), + num(&rates["prefill_tok_s_lifetime"]), + num(&rates["decode_tok_s_last"]), + num(&rates["decode_tok_s_avg"]), + num(&rates["decode_tok_s_lifetime"]), + rates["decode_tok_s_live"] + .as_f64() + .map_or(String::new(), |v| format!(", {v:.0} now")) + ) +} + +fn cache_line(cache: &Value) -> String { + format!( + " cache {} of requests hit, {} of prompt tokens reused (last request {} of {})\n", + pct(&cache["hit_ratio"]), + pct(&cache["token_hit_ratio"]), + cache["last_reused_tokens"], + cache["last_prompt_tokens"] + ) +} + +fn context_line(context: &Value) -> String { + format!( + " context {} of {} tokens{}\n", + context["live_tokens"], + context["max_tokens"], + context["used_pct"] + .as_f64() + .map_or(String::new(), |p| format!(" ({p:.1}%)")) + ) +} diff --git a/crates/deploy/src/app/preflight_report.rs b/crates/deploy/src/app/preflight_report.rs index 5f079590..b873758b 100644 --- a/crates/deploy/src/app/preflight_report.rs +++ b/crates/deploy/src/app/preflight_report.rs @@ -5,17 +5,9 @@ use super::*; /// `leleka seal-probe FILE`: the archive copy of `leleka run` on any file, and the proof that the memfd equals the file. #[cfg(unix)] pub(super) fn seal_probe(file: &std::path::Path) -> i32 { - use sha2::{Digest, Sha256}; - use std::os::unix::fs::FileExt; let started = std::time::Instant::now(); let (memfd, _identity, report) = - match crate::sealed::seal_file_report(file, None, &mut |done, total| { - eprintln!( - "sealing: {:.1} of {:.1} GiB", - done as f64 / 1073741824.0, - total as f64 / 1073741824.0 - ); - }) { + match crate::sealed::seal_file_report(file, None, &mut sealing_progress) { Ok(done) => done, Err(message) => { eprintln!("leleka seal-probe: {message}"); @@ -24,7 +16,6 @@ pub(super) fn seal_probe(file: &std::path::Path) -> i32 { }; let sealed_s = started.elapsed().as_secs_f64(); let length = memfd.metadata().map_or(0, |m| m.len()); - let (mut from_memfd, mut from_file) = (Sha256::new(), Sha256::new()); let source = match std::fs::File::open(file) { Ok(f) => f, Err(error) => { @@ -32,6 +23,36 @@ pub(super) fn seal_probe(file: &std::path::Path) -> i32 { return 1; } }; + let (a, b) = match digests_of(&memfd, &source, length) { + Ok(pair) => pair, + Err(offset) => { + eprintln!("leleka seal-probe: read failed at {offset}"); + return 1; + } + }; + print_probe(file, length, (report.strategy.as_str(), sealed_s), (&a, &b)); + i32::from(a != b) +} + +#[cfg(unix)] +fn sealing_progress(done: u64, total: u64) { + eprintln!( + "sealing: {:.1} of {:.1} GiB", + done as f64 / 1073741824.0, + total as f64 / 1073741824.0 + ); +} + +/// The SHA-256 of the memfd and of the file, read side by side; `Err` is the offset where a read failed. +#[cfg(unix)] +fn digests_of( + memfd: &std::fs::File, + source: &std::fs::File, + length: u64, +) -> Result<(String, String), u64> { + use sha2::{Digest, Sha256}; + use std::os::unix::fs::FileExt; + let (mut from_memfd, mut from_file) = (Sha256::new(), Sha256::new()); let mut block = vec![0u8; 8 << 20]; let mut other = vec![0u8; 8 << 20]; let mut offset = 0u64; @@ -40,29 +61,37 @@ pub(super) fn seal_probe(file: &std::path::Path) -> i32 { if memfd.read_exact_at(&mut block[..n], offset).is_err() || source.read_exact_at(&mut other[..n], offset).is_err() { - eprintln!("leleka seal-probe: read failed at {offset}"); - return 1; + return Err(offset); } from_memfd.update(&block[..n]); from_file.update(&other[..n]); offset += n as u64; } - let (a, b) = ( + Ok(( hex::encode(from_memfd.finalize()), hex::encode(from_file.finalize()), - ); + )) +} + +/// The one line of the probe: how the copy was read, how long it took and whether the two digests agree. +#[cfg(unix)] +fn print_probe( + file: &std::path::Path, + length: u64, + (strategy, sealed_s): (&str, f64), + (a, b): (&str, &str), +) { println!( "seal-probe {} bytes {} read={} sealed in {:.1} s ({:.0} MB/s) sha256(memfd)={} sha256(file)={} {}", file.display(), length, - report.strategy.as_str(), + strategy, sealed_s, length as f64 / sealed_s.max(1e-9) / 1e6, a, b, if a == b { "IDENTICAL" } else { "DIFFERENT" } ); - i32::from(a != b) } #[cfg(not(unix))] diff --git a/crates/deploy/src/app/quick_health.rs b/crates/deploy/src/app/quick_health.rs new file mode 100644 index 00000000..6a454fd8 --- /dev/null +++ b/crates/deploy/src/app/quick_health.rs @@ -0,0 +1,214 @@ +//! The sections of `leleka verify --quick`: model files, service, logs and requests. + +use super::*; +use crate::{config::RunConfig, layout::Paths, profile::KarSource}; +use leleka_model_format::verify_stamp::{FileIdentity, VerifyStamps}; +use std::path::Path; + +/// What the quick check found: problems fail it, notes are only shown. +#[derive(Default)] +pub(super) struct Health { + problems: Vec, + notes: Vec, +} + +impl Health { + fn problem(&mut self, text: String) { + self.problems.push(text); + } + + fn wrong_archive_size(&mut self, size: u64) { + let pinned = crate::profile::ARCHIVE_BYTES; + self.problem(format!( + "the archive has {size} bytes, the pinned archive {pinned}" + )); + } + + /// Print the notes and the verdict; the exit code (0 only when there is no problem). + pub(super) fn conclude(&self) -> i32 { + for note in &self.notes { + println!("note: {note}"); + } + if self.problems.is_empty() { + println!("health: OK"); + 0 + } else { + for problem in &self.problems { + println!("PROBLEM: {problem}"); + } + println!("health: NOT OK"); + 1 + } + } +} + +fn decode_digest(hex_text: &str) -> Option<[u8; 32]> { + let mut out = [0u8; 32]; + hex::decode_to_slice(hex_text, &mut out).ok().map(|()| out) +} + +fn identity_of(path: &Path) -> Option { + std::fs::File::open(path) + .and_then(|f| f.metadata()) + .ok() + .and_then(|m| FileIdentity::of(&m)) +} + +pub(super) fn report_model_files(paths: &Paths, config: &RunConfig, health: &mut Health) { + let stamps = VerifyStamps::new(paths.engine_stamps(), false); + println!( + "model files (a file that matched its pinned digest and is unchanged is not hashed again at a start):" + ); + for index in 0..2 { + report_shard(paths, &stamps, index, health); + } + let kar = paths.kar(); + let kar_state = archive_state(&kar, config, &stamps, health); + println!(" archive: {kar_state} {}", kar.display()); +} + +fn report_shard(paths: &Paths, stamps: &VerifyStamps, index: usize, health: &mut Health) { + let path = paths.shard(index); + let state = match ( + decode_digest(crate::profile::SHARD_SHA256_HEX[index]), + identity_of(&path), + ) { + (_, None) => { + health + .problems + .push(format!("shard {index} is missing: {}", path.display())); + "MISSING" + } + (Some(digest), Some(id)) if stamps.trusts("gguf", &digest, &id) => { + "stamped (verified in its present state)" + } + _ => { + health.notes.push(format!( + concat!( + "shard {index} is not stamped: the next start hashes it (minutes); ", + "`leleka verify` renews the stamp" + ), + index = index + )); + "not stamped" + } + }; + println!(" shard {index}: {state} {}", path.display()); +} + +const ARCHIVE_NOT_STAMPED: &str = concat!( + "the archive is not stamped: the next start of the engine hashes the sealed copy ", + "(about a minute)" +); + +fn archive_state( + kar: &Path, + config: &RunConfig, + stamps: &VerifyStamps, + health: &mut Health, +) -> String { + match identity_of(kar) { + _ if config.profile.kar_source == KarSource::None => { + "not used (kar_source none)".to_owned() + } + None => { + health.problem(format!("the archive is missing: {}", kar.display())); + "MISSING".to_owned() + } + Some(id) if id.size != crate::profile::ARCHIVE_BYTES => { + health.wrong_archive_size(id.size); + "WRONG SIZE".to_owned() + } + Some(id) if stamps.trusts("kar-source", &crate::profile::archive_sha256(), &id) => { + "stamped (verified in its present state)".to_owned() + } + Some(_) => { + health.notes.push(ARCHIVE_NOT_STAMPED.into()); + "not stamped".to_owned() + } + } +} + +/// The supervisor status file, the answer of `/ready` and what they say about the service. +pub(super) async fn report_service(paths: &Paths, config: &RunConfig, health: &mut Health) { + let api = config.ports.api.clone(); + let supervisor: Option = std::fs::read_to_string(paths.status_file()) + .ok() + .and_then(|t| serde_json::from_str(&t).ok()); + let ready = steps::probe_ready_at(paths, &api).await; + println!("service:"); + match &supervisor { + Some(s) => print!( + " {}", + render_supervisor(s, unix_now()) + .replace('\n', "\n ") + .trim_end_matches(' ') + ), + None => println!( + " no status file in {} (the service has not run)", + paths.run_dir().display() + ), + } + println!(" API answers /ready: {}", if ready { "yes" } else { "NO" }); + if !ready { + health + .problems + .push("the API does not answer /ready".into()); + } + if let Some(s) = &supervisor { + check_supervisor(s, health); + } +} + +fn check_supervisor(s: &Value, health: &mut Health) { + let age = unix_now().saturating_sub(s["updated_unix"].as_u64().unwrap_or(0)); + if age > 120 && !matches!(s["phase"].as_str(), Some("stopped" | "failed")) { + health.problems.push(format!( + "the supervisor's status is {age} s old: it is not running" + )); + } + if s["phase"].as_str() == Some("failed") { + health.problems.push(format!( + "the supervisor failed: {}", + s["message"].as_str().unwrap_or("") + )); + } +} + +/// The size of the logs and the recent requests, with a note when too many of them failed. +pub(super) fn report_logs_and_requests(paths: &Paths, config: &RunConfig, health: &mut Health) { + let log_bytes = crate::logs::total_bytes(&paths.logs()); + println!( + " logs: {} MiB in {} (rotated at {} MiB per file, {} generations)", + log_bytes >> 20, + paths.logs().display(), + config.logs.limit_mib, + config.logs.keep + ); + match crate::logview::recent_requests_line(&paths.logs(), leleka_obs::now_ms()) { + Some(line) => println!(" {line}"), + None => println!( + " requests: no request record yet in {} (`leleka logs --source requests`)", + paths.logs().join("requests.log").display() + ), + } + note_failed_requests(health, &crate::logview::recent_requests(&paths.logs(), 200)); +} + +/// A note when a fifth or more of the last requests (at least ten were made) failed or were rejected. +fn note_failed_requests(health: &mut Health, recent: &[Value]) { + let failed = recent + .iter() + .filter(|r| matches!(r["fin"].as_str(), Some("error" | "rejected"))) + .count(); + if recent.len() >= 10 && failed * 5 > recent.len() { + health.notes.push(format!( + concat!( + "{failed} of the last {} requests failed or were rejected: ", + "see `leleka logs --level warn --since 1h`" + ), + recent.len(), + failed = failed + )); + } +} diff --git a/crates/deploy/src/app/settings_change.rs b/crates/deploy/src/app/settings_change.rs index 4f36890e..5375e7a2 100644 --- a/crates/deploy/src/app/settings_change.rs +++ b/crates/deploy/src/app/settings_change.rs @@ -47,52 +47,16 @@ pub async fn send_reconfigure( eprintln!( "leleka: reconfiguring {settings}; the engine reopens its serve stack (tens of seconds, requests wait meanwhile)" ); - let response = crate::http::post_json( - address, - "/v1/reconfigure", - Some(key), - settings, - std::time::Duration::from_secs(1900), - ) - .await; + let response = post_settings(address, key, settings).await; match response { Ok(response) => { - let document: Value = serde_json::from_str(&response.body).unwrap_or(Value::Null); - let mut persisted = None; - if response.status == 200 - && let Some(target) = &persist - { - persisted = - Some(persist_settings(target.paths, target.settings, target.supervised).await); - } - if json { - let mut shown = document.clone(); - if let (Some(object), Some(result)) = (shown.as_object_mut(), &persisted) { - object.insert("persisted".into(), json!(result.is_ok())); + let persisted = match &persist { + Some(target) if response.status == 200 => { + Some(persist_settings(target.paths, target.settings, target.supervised).await) } - println!( - "{}", - serde_json::to_string_pretty(&shown).unwrap_or(response.body) - ); - } else if response.status == 200 { - println!("reconfigured; the engine runs with:"); - print!("{}", render_settings(&document["settings"])); - match &persisted { - Some(Ok(note)) => println!("persisted: {note}"), - Some(Err(why)) => eprintln!( - "leleka: the engine runs with the new settings, but they were not persisted: {why}" - ), - None => {} - } - } else { - let message = document["error"]["message"] - .as_str() - .unwrap_or(&response.body); - eprintln!( - "leleka: the change was refused (HTTP {}): {message}", - response.status - ); - } + _ => None, + }; + print_reconfigure_answer(&response, persisted.as_ref(), json); i32::from(response.status != 200 || persisted.is_some_and(|result| result.is_err())) } Err(message) => { @@ -102,6 +66,62 @@ pub async fn send_reconfigure( } } +async fn post_settings( + address: std::net::SocketAddr, + key: &str, + settings: &str, +) -> Result { + crate::http::post_json( + address, + "/v1/reconfigure", + Some(key), + settings, + std::time::Duration::from_secs(1900), + ) + .await +} + +/// The answer of the gateway: the JSON document with `persisted` added, or the settings in force, or why it was refused. +fn print_reconfigure_answer( + response: &crate::http::Response, + persisted: Option<&Result>, + json: bool, +) { + let document: Value = serde_json::from_str(&response.body).unwrap_or(Value::Null); + if json { + let mut shown = document.clone(); + if let (Some(object), Some(result)) = (shown.as_object_mut(), persisted) { + object.insert("persisted".into(), json!(result.is_ok())); + } + println!( + "{}", + serde_json::to_string_pretty(&shown).unwrap_or_else(|_| response.body.clone()) + ); + } else if response.status == 200 { + println!("reconfigured; the engine runs with:"); + print!("{}", render_settings(&document["settings"])); + print_persisted(persisted); + } else { + let message = document["error"]["message"] + .as_str() + .unwrap_or(&response.body); + eprintln!( + "leleka: the change was refused (HTTP {}): {message}", + response.status + ); + } +} + +fn print_persisted(persisted: Option<&Result>) { + match persisted { + Some(Ok(note)) => println!("persisted: {note}"), + Some(Err(why)) => eprintln!( + "leleka: the engine runs with the new settings, but they were not persisted: {why}" + ), + None => {} + } +} + /// `--persist` after a runtime change: the supervisor records it in the configuration it holds (so that a restart of the engine /// keeps it) and writes the file; with no supervisor the file is edited directly. pub(super) async fn persist_settings( @@ -156,15 +176,17 @@ pub(super) async fn ask_supervisor( return Err("the supervisor stopped before it answered; see the service log".into()); } if started.elapsed() > limit { - let _ = std::fs::remove_file(paths.reconfigure_request()); - return Err(format!( - "the supervisor did not answer within {} s", - limit.as_secs() - )); + return Err(give_up_waiting(paths, limit)); } } } +/// The supervisor did not answer in time: withdraw the request. +fn give_up_waiting(paths: &crate::layout::Paths, limit: std::time::Duration) -> String { + let _ = std::fs::remove_file(paths.reconfigure_request()); + format!("the supervisor did not answer within {} s", limit.as_secs()) +} + /// A budget or preset change: the supervisor restarts the engine process with the new numbers. pub(super) async fn reconfigure_by_restart( opts: &UpOptions, @@ -181,30 +203,37 @@ pub(super) async fn reconfigure_by_restart( } let load_timeout = crate::config::RunConfig::read(&paths.run_config()) .map_or(1800, |config| config.load_timeout_s); - let request = crate::reconfigure::Request { - id: crate::reconfigure::new_request_id(), - gpu_budget_gib: args.gpu_budget_gib, - preset: args.preset, - settings: args.settings.clone(), - persist: args.persist, - }; + let request = restart_request(args); eprintln!( "leleka: asking the supervisor to restart the engine with the new settings (the model loads again; the gateway and the API keep their ports)" ); // two engine starts at worst (the new one fails, the previous one is restored), plus the stop and the host checks let limit = std::time::Duration::from_secs(2 * load_timeout + 300); - let outcome = match ask_supervisor(&paths, &request, limit, !opts.json).await { - Ok(outcome) => outcome, + match ask_supervisor(&paths, &request, limit, !opts.json).await { + Ok(outcome) => print_restart_outcome(&outcome, opts.json), Err(why) => { eprintln!("leleka: {why}"); - return 1; + 1 } - }; + } +} + +fn restart_request(args: &ReconfigureArgs) -> crate::reconfigure::Request { + crate::reconfigure::Request { + id: crate::reconfigure::new_request_id(), + gpu_budget_gib: args.gpu_budget_gib, + preset: args.preset, + settings: args.settings.clone(), + persist: args.persist, + } +} + +fn print_restart_outcome(outcome: &crate::reconfigure::Outcome, json: bool) -> i32 { let done = outcome.state == crate::reconfigure::State::Done; - if opts.json { + if json { println!( "{}", - serde_json::to_string_pretty(&outcome).unwrap_or_default() + serde_json::to_string_pretty(outcome).unwrap_or_default() ); } else if done { println!("reconfigured: {}", outcome.message); @@ -257,92 +286,3 @@ pub fn render_settings(settings: &Value) -> String { } out } - -/// The human view of the engine telemetry document (`machine` of `/v1/status`): GPU, CPU, RAM, throughput, cache, context. -pub fn render_machine(machine: &Value) -> String { - let gib = |mib: &Value| { - mib.as_f64() - .map_or("?".to_owned(), |m| format!("{:.1}", m / 1024.0)) - }; - let num = |value: &Value| value.as_f64().map_or("-".to_owned(), |v| format!("{v:.0}")); - let pct = |value: &Value| { - value - .as_f64() - .map_or("-".to_owned(), |v| format!("{:.0}%", v * 100.0)) - }; - let mut out = format!( - "engine load ({}):\n", - machine["phase"].as_str().unwrap_or("?") - ); - let gpu = &machine["gpu"]; - if gpu.is_object() { - out.push_str(&format!( - " gpu {}% busy (memory bus {}%), VRAM {} of {} GiB{}{}{}\n", - gpu["util_pct"], - gpu["mem_util_pct"], - gib(&gpu["vram_used_mib"]), - gib(&gpu["vram_total_mib"]), - gpu["power_w"] - .as_f64() - .map_or(String::new(), |w| format!(", {w:.0} W")), - gpu["sm_clock_mhz"] - .as_u64() - .map_or(String::new(), |m| format!(", {m} MHz")), - gpu["temp_c"] - .as_u64() - .map_or(String::new(), |t| format!(", {t} C")), - )); - } - let cpu = &machine["cpu"]; - if cpu.is_object() { - out.push_str(&format!( - " cpu {} of {} cores busy in the engine (whole system {}%)\n", - cpu["process_busy_cores"], cpu["cores"], cpu["system_busy_pct"] - )); - } - let ram = &machine["ram"]; - if ram.is_object() { - out.push_str(&format!( - " ram {} of {} GiB available, engine {} GiB resident ({} GiB pinned), swap in use {} GiB\n", - gib(&ram["available_mib"]), gib(&ram["total_mib"]), gib(&ram["process_rss_mib"]), gib(&ram["process_pinned_mib"]), gib(&ram["swap_used_mib"]) - )); - } - let rates = &machine["throughput"]; - out.push_str(&format!( - " prefill {} tok/s last, {} average, {} lifetime\n", - num(&rates["prefill_tok_s_last"]), - num(&rates["prefill_tok_s_avg"]), - num(&rates["prefill_tok_s_lifetime"]) - )); - out.push_str(&format!( - " decode {} tok/s last, {} average, {} lifetime{}\n", - num(&rates["decode_tok_s_last"]), - num(&rates["decode_tok_s_avg"]), - num(&rates["decode_tok_s_lifetime"]), - rates["decode_tok_s_live"] - .as_f64() - .map_or(String::new(), |v| format!(", {v:.0} now")) - )); - let cache = &machine["cache"]; - out.push_str(&format!( - " cache {} of requests hit, {} of prompt tokens reused (last request {} of {})\n", - pct(&cache["hit_ratio"]), - pct(&cache["token_hit_ratio"]), - cache["last_reused_tokens"], - cache["last_prompt_tokens"] - )); - let context = &machine["context"]; - out.push_str(&format!( - " context {} of {} tokens{}\n", - context["live_tokens"], - context["max_tokens"], - context["used_pct"] - .as_f64() - .map_or(String::new(), |p| format!(" ({p:.1}%)")) - )); - if machine["settings"].is_object() { - out.push_str("settings in force:\n"); - out.push_str(&render_settings(&machine["settings"])); - } - out -} diff --git a/crates/deploy/src/app/status_report.rs b/crates/deploy/src/app/status_report.rs index a7f295e6..2def2a9c 100644 --- a/crates/deploy/src/app/status_report.rs +++ b/crates/deploy/src/app/status_report.rs @@ -31,21 +31,7 @@ pub(super) async fn status(opts: UpOptions) -> i32 { } else { None }; - let unit = match installed_scope(&paths) { - Some(scope) => { - let mut command = tokio::process::Command::new("systemctl"); - if scope == UnitScopeTag::User { - command.arg("--user"); - } - command.args(["is-active", paths.unit_name()]); - command - .output() - .await - .ok() - .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_owned()) - } - None => None, - }; + let unit = unit_state(&paths).await; let requests = crate::logview::recent_requests_line(&paths.logs(), leleka_obs::now_ms()); print_status( opts.json, @@ -59,6 +45,21 @@ pub(super) async fn status(opts: UpOptions) -> i32 { ) } +/// `systemctl is-active` of the installed unit, when there is one. +async fn unit_state(paths: &crate::layout::Paths) -> Option { + let scope = installed_scope(paths)?; + let mut command = tokio::process::Command::new("systemctl"); + if scope == UnitScopeTag::User { + command.arg("--user"); + } + command.args(["is-active", paths.unit_name()]); + command + .output() + .await + .ok() + .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_owned()) +} + /// The `leleka status` output from the pieces gathered on this host or through the WSL bridge. Exit code 1 when not ready. #[allow(clippy::too_many_arguments)] pub fn print_status( @@ -71,42 +72,61 @@ pub fn print_status( run_dir: &str, requests: Option<&str>, ) -> i32 { - let machine = gateway - .map(|g| g["machine"].clone()) - .filter(Value::is_object); + let machine = machine_of(gateway); if json { + let document = json!({"ready": ready, "unit": unit.as_ref().map(|(_, state)| state), + "supervisor": supervisor, "machine": machine, "prefix_cache": gateway.map(|g| g["prefix_cache"].clone()), + "expert_tier": expert_tier, "requests": requests}); println!( "{}", - serde_json::to_string_pretty( - &json!({"ready": ready, "unit": unit.as_ref().map(|(_, state)| state), "supervisor": supervisor, "machine": machine, - "prefix_cache": gateway.map(|g| g["prefix_cache"].clone()), "expert_tier": expert_tier, "requests": requests}) - ) - .expect("serializable") + serde_json::to_string_pretty(&document).expect("serializable") ); } else { println!("ready: {ready}"); if let Some((name, state)) = unit { println!("systemd unit {name}: {state}"); } - match supervisor { - Some(s) => print!("{}", render_supervisor(&s, unix_now())), - None => println!("supervisor: no status file in {run_dir} (never started?)"), - } - if let Some(tier) = expert_tier { - println!("{}", tier.line()); - } - if let Some(line) = requests { - println!("{line}"); - } - if let Some(machine) = &machine { - print!("{}", render_machine(machine)); - } else if ready { - println!("engine load: the engine reports no telemetry yet"); - } + print_status_text(supervisor, expert_tier, run_dir, requests); + print_machine(machine.as_ref(), ready); } i32::from(!ready) } +/// The engine telemetry block of the gateway status, when it has one. +fn machine_of(gateway: Option<&Value>) -> Option { + gateway + .map(|g| g["machine"].clone()) + .filter(Value::is_object) +} + +/// The telemetry of the engine, or why there is none. +fn print_machine(machine: Option<&Value>, ready: bool) { + if let Some(machine) = machine { + print!("{}", render_machine(machine)); + } else if ready { + println!("engine load: the engine reports no telemetry yet"); + } +} + +/// The supervisor document, the expert tier and the request line of the text form. +fn print_status_text( + supervisor: Option, + expert_tier: Option<&crate::expert_profile::TierReport>, + run_dir: &str, + requests: Option<&str>, +) { + match supervisor { + Some(s) => print!("{}", render_supervisor(&s, unix_now())), + None => println!("supervisor: no status file in {run_dir} (never started?)"), + } + if let Some(tier) = expert_tier { + println!("{}", tier.line()); + } + if let Some(line) = requests { + println!("{line}"); + } +} + pub(super) fn unix_now() -> u64 { std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) @@ -148,29 +168,7 @@ pub fn render_supervisor(s: &Value, now: u64) -> String { s["phase"].as_str().unwrap_or("?") )); } - if let Some(started) = s["started_unix"].as_u64() { - out.push_str(&format!( - " up {}", - duration_text(now.saturating_sub(started)) - )); - out.push_str(&format!( - ", engine restarts {} in total ({} in a row)", - s["restarts_total"].as_u64().unwrap_or(0), - s["engine_restarts"].as_u64().unwrap_or(0) - )); - if let (Some(at), Some(why)) = ( - s["last_restart_unix"].as_u64(), - s["last_restart_reason"].as_str(), - ) { - out.push_str(&format!( - "\n last restart {} ago: {why}", - duration_text(now.saturating_sub(at)) - )); - } - out.push('\n'); - } else { - out.push_str(&format!(" engine restarts {}\n", s["engine_restarts"])); - } + out.push_str(&uptime_lines(s, now)); if let Some(health) = s["health"].as_str() { out.push_str(&format!( " health: {health}; logs {} MiB\n", @@ -179,3 +177,27 @@ pub fn render_supervisor(s: &Value, now: u64) -> String { } out } + +/// How long the service has been up and what it restarted, or just the restart count of an older status file. +fn uptime_lines(s: &Value, now: u64) -> String { + let Some(started) = s["started_unix"].as_u64() else { + return format!(" engine restarts {}\n", s["engine_restarts"]); + }; + let mut out = format!(" up {}", duration_text(now.saturating_sub(started))); + out.push_str(&format!( + ", engine restarts {} in total ({} in a row)", + s["restarts_total"].as_u64().unwrap_or(0), + s["engine_restarts"].as_u64().unwrap_or(0) + )); + if let (Some(at), Some(why)) = ( + s["last_restart_unix"].as_u64(), + s["last_restart_reason"].as_str(), + ) { + out.push_str(&format!( + "\n last restart {} ago: {why}", + duration_text(now.saturating_sub(at)) + )); + } + out.push('\n'); + out +} diff --git a/crates/deploy/src/app/stop_flow.rs b/crates/deploy/src/app/stop_flow.rs index 0e0be65b..7ab4180a 100644 --- a/crates/deploy/src/app/stop_flow.rs +++ b/crates/deploy/src/app/stop_flow.rs @@ -5,26 +5,7 @@ use super::*; pub(super) async fn down(opts: UpOptions) -> i32 { let paths = opts.dirs.paths(); match installed_scope(&paths) { - Some(scope) => { - let mut command = tokio::process::Command::new("systemctl"); - if scope == UnitScopeTag::User { - command.arg("--user"); - } - match command.args(["stop", paths.unit_name()]).status().await { - Ok(status) if status.success() => { - eprintln!("leleka: stopped {}", paths.unit_name()); - 0 - } - Ok(status) => { - eprintln!("leleka: systemctl stop failed ({status})"); - 1 - } - Err(error) => { - eprintln!("leleka: cannot run systemctl: {error}"); - 1 - } - } - } + Some(scope) => stop_unit(scope, &paths).await, None => { #[cfg(windows)] { @@ -41,6 +22,28 @@ pub(super) async fn down(opts: UpOptions) -> i32 { } } +/// `systemctl stop` of the installed unit. +async fn stop_unit(scope: UnitScopeTag, paths: &crate::layout::Paths) -> i32 { + let mut command = tokio::process::Command::new("systemctl"); + if scope == UnitScopeTag::User { + command.arg("--user"); + } + match command.args(["stop", paths.unit_name()]).status().await { + Ok(status) if status.success() => { + eprintln!("leleka: stopped {}", paths.unit_name()); + 0 + } + Ok(status) => { + eprintln!("leleka: systemctl stop failed ({status})"); + 1 + } + Err(error) => { + eprintln!("leleka: cannot run systemctl: {error}"); + 1 + } + } +} + /// Windows: a supervisor in another console cannot be sent Ctrl-C, so it watches for a stop file in its run directory. #[cfg(windows)] pub async fn stop_foreground(paths: &crate::layout::Paths) -> i32 { diff --git a/crates/deploy/src/app/verify_flow.rs b/crates/deploy/src/app/verify_flow.rs index 2e65077c..9e9a8ef6 100644 --- a/crates/deploy/src/app/verify_flow.rs +++ b/crates/deploy/src/app/verify_flow.rs @@ -1,6 +1,18 @@ //! `leleka verify`: the quick offline check and the full verification against a running engine. +use super::quick_health::{Health, report_logs_and_requests, report_model_files, report_service}; use super::*; +use crate::{config::RunConfig, layout::Paths}; +use leleka_model_format::verify_stamp::{FileIdentity, VerifyStamps, sha256_of_file}; +use std::path::Path; + +/// The run configuration of the installation, or the exit code of the refusal (already printed). +fn read_run_config(paths: &Paths) -> Result { + RunConfig::read(&paths.run_config()).map_err(|message| { + eprintln!("leleka: {message}"); + 2 + }) +} /// `leleka verify`: full hashing of both shards and the archive, in parallel, against the pinned digests; renews the /// stamps (`STATE/stamps/engine`) that let the next start skip the hashing. Nothing is loaded and no GPU is touched. @@ -8,272 +20,188 @@ use super::*; /// service says: whether each model file is stamped as verified in its present state (a stamped file is not hashed again at a start), /// whether the service runs and answers, how old and how restarted it is, and how big the logs are. Exit 0 only when all is well. pub(super) async fn verify_quick(opts: &UpOptions) -> i32 { - use leleka_model_format::verify_stamp::{FileIdentity, VerifyStamps}; let paths = opts.dirs.paths(); - let config = match crate::config::RunConfig::read(&paths.run_config()) { + let config = match read_run_config(&paths) { Ok(config) => config, - Err(message) => { - eprintln!("leleka: {message}"); - return 2; - } + Err(code) => return code, }; - let stamps = VerifyStamps::new(paths.engine_stamps(), false); - let mut problems: Vec = Vec::new(); - let mut notes: Vec = Vec::new(); - let decode = |hex_text: &str| { - let mut out = [0u8; 32]; - hex::decode_to_slice(hex_text, &mut out).ok().map(|()| out) - }; - let identity_of = |path: &std::path::Path| { - std::fs::File::open(path) - .and_then(|f| f.metadata()) - .ok() - .and_then(|m| FileIdentity::of(&m)) - }; - println!( - "model files (a file that matched its pinned digest and is unchanged is not hashed again at a start):" - ); - for index in 0..2 { - let path = paths.shard(index); - let state = match ( - decode(crate::profile::SHARD_SHA256_HEX[index]), - identity_of(&path), - ) { - (_, None) => { - problems.push(format!("shard {index} is missing: {}", path.display())); - "MISSING" - } - (Some(digest), Some(id)) if stamps.trusts("gguf", &digest, &id) => { - "stamped (verified in its present state)" - } - _ => { - notes.push(format!("shard {index} is not stamped: the next start hashes it (minutes); `leleka verify` renews the stamp")); - "not stamped" - } - }; - println!(" shard {index}: {state} {}", path.display()); - } - let kar = paths.kar(); - let kar_state = match identity_of(&kar) { - _ if config.profile.kar_source == crate::profile::KarSource::None => { - "not used (kar_source none)".to_owned() - } - None => { - problems.push(format!("the archive is missing: {}", kar.display())); - "MISSING".to_owned() - } - Some(id) if id.size != crate::profile::ARCHIVE_BYTES => { - problems.push(format!( - "the archive has {} bytes, the pinned archive {}", - id.size, - crate::profile::ARCHIVE_BYTES - )); - "WRONG SIZE".to_owned() - } - Some(id) if stamps.trusts("kar-source", &crate::profile::archive_sha256(), &id) => { - "stamped (verified in its present state)".to_owned() - } - Some(_) => { - notes.push("the archive is not stamped: the next start of the engine hashes the sealed copy (about a minute)".into()); - "not stamped".to_owned() - } - }; - println!(" archive: {kar_state} {}", kar.display()); - let api = config.ports.api.clone(); - let supervisor: Option = std::fs::read_to_string(paths.status_file()) - .ok() - .and_then(|t| serde_json::from_str(&t).ok()); - let ready = steps::probe_ready_at(&paths, &api).await; - println!("service:"); - match &supervisor { - Some(s) => print!( - " {}", - render_supervisor(s, unix_now()) - .replace('\n', "\n ") - .trim_end_matches(' ') - ), - None => println!( - " no status file in {} (the service has not run)", - paths.run_dir().display() - ), - } - println!(" API answers /ready: {}", if ready { "yes" } else { "NO" }); - if !ready { - problems.push("the API does not answer /ready".into()); - } - if let Some(s) = &supervisor { - let age = unix_now().saturating_sub(s["updated_unix"].as_u64().unwrap_or(0)); - if age > 120 && !matches!(s["phase"].as_str(), Some("stopped" | "failed")) { - problems.push(format!( - "the supervisor's status is {age} s old: it is not running" - )); - } - if s["phase"].as_str() == Some("failed") { - problems.push(format!( - "the supervisor failed: {}", - s["message"].as_str().unwrap_or("") - )); - } - } - let log_bytes = crate::logs::total_bytes(&paths.logs()); - println!( - " logs: {} MiB in {} (rotated at {} MiB per file, {} generations)", - log_bytes >> 20, - paths.logs().display(), - config.logs.limit_mib, - config.logs.keep - ); - match crate::logview::recent_requests_line(&paths.logs(), leleka_obs::now_ms()) { - Some(line) => println!(" {line}"), - None => println!( - " requests: no request record yet in {} (`leleka logs --source requests`)", - paths.logs().join("requests.log").display() - ), - } - let recent = crate::logview::recent_requests(&paths.logs(), 200); - let failed = recent - .iter() - .filter(|r| matches!(r["fin"].as_str(), Some("error" | "rejected"))) - .count(); - if recent.len() >= 10 && failed * 5 > recent.len() { - notes.push(format!("{failed} of the last {} requests failed or were rejected: see `leleka logs --level warn --since 1h`", recent.len())); - } - for note in ¬es { - println!("note: {note}"); - } - if problems.is_empty() { - println!("health: OK"); - 0 - } else { - for problem in &problems { - println!("PROBLEM: {problem}"); - } - println!("health: NOT OK"); - 1 - } + let mut health = Health::default(); + report_model_files(&paths, &config, &mut health); + report_service(&paths, &config, &mut health).await; + report_logs_and_requests(&paths, &config, &mut health); + health.conclude() } pub(super) async fn verify(opts: UpOptions) -> i32 { - use crate::{config::RUNTIME_TOKEN_ENV, facts::parse_env_file, profile::KarSource}; if opts.quick { return verify_quick(&opts).await; } - use leleka_model_format::verify_stamp::{FileIdentity, VerifyStamps, sha256_of_file}; let paths = opts.dirs.paths(); - let config = match crate::config::RunConfig::read(&paths.run_config()) { - Ok(config) => config, - Err(message) => { - eprintln!("leleka: {message}"); - return 2; - } + let (config, stamp_dir, token) = match verify_inputs(&paths) { + Ok(inputs) => inputs, + Err(code) => return code, }; - let stamp_dir = paths.engine_stamps(); - if let Err(error) = std::fs::create_dir_all(&stamp_dir) { - eprintln!("leleka: cannot create {}: {error}", stamp_dir.display()); - return 1; - } - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt; - let _ = std::fs::set_permissions(&stamp_dir, std::fs::Permissions::from_mode(0o700)); - } - let env = std::fs::read_to_string(paths.env_file()) - .map(|text| parse_env_file(&text)) - .unwrap_or_default(); - let Some(token) = env.get(RUNTIME_TOKEN_ENV).cloned() else { - eprintln!( - "leleka: {} has no {RUNTIME_TOKEN_ENV}; run `leleka up`", - paths.env_file().display() - ); - return 2; - }; - // The expert tier's table is 192 KiB: checked first, loudly, because losing it is a silent large slowdown. - let tier = crate::expert_profile::tier_report(&config, &paths.dirs.assets); - say(&tier.line()); - let tier_failed = !tier.on && !tier.opted_out && config.profile.expert_profile.is_some(); + let tier_failed = tier_has_failed(&config, &paths); let started = std::time::Instant::now(); - say( - "hashing both shards (and the archive, when it is a file) in full, in parallel; this renews the stamps", - ); - let engine = tokio::process::Command::new(paths.bin("leleka-inference")) - .args(config.verify_args(true)) - .env(RUNTIME_TOKEN_ENV, token) - .env_remove("HF_TOKEN") - .stdin(std::process::Stdio::null()) - .status(); - // A sealed-memfd profile cannot hand the engine the file (it must be read-only and owned); the archive file is - // hashed here instead, against the pinned digest, and stamped for the supervisor (kind `kar-source`). - let archive = tokio::task::spawn_blocking({ - let kar = paths.kar(); - let memfd = config.profile.kar_source == KarSource::Memfd; - let stamps = VerifyStamps::new(stamp_dir.clone(), true); - move || -> Result, String> { - if !memfd { - return Ok(None); - } - let begun = std::time::Instant::now(); - let file = std::fs::File::open(&kar) - .map_err(|e| format!("cannot open {}: {e}", kar.display()))?; - let before = file.metadata().ok().and_then(|m| FileIdentity::of(&m)); - let digest = - sha256_of_file(&file).map_err(|e| format!("cannot read {}: {e}", kar.display()))?; - if digest != crate::profile::archive_sha256() { - return Err(format!( - "{} does not match the pinned archive digest", - kar.display() - )); - } - let after = file.metadata().ok().and_then(|m| FileIdentity::of(&m)); - if let (Some(before), true) = (before, before == after) { - stamps - .record("kar-source", &crate::profile::archive_sha256(), &before) - .map_err(|e| format!("cannot record the archive stamp: {e}"))?; - } - Ok(Some(begun.elapsed().as_secs_f64())) - } - }); + say(concat!( + "hashing both shards (and the archive, when it is a file) in full, in parallel; ", + "this renews the stamps" + )); + let engine = run_engine_verification(&paths, &config, token); + let archive = hash_archive_file(&paths, &config, stamp_dir); let (engine, archive) = tokio::join!(engine, archive); - let mut code = 0; - match engine { - Ok(status) if status.success() => {} - Ok(status) => { - eprintln!( - "leleka: the engine's verification failed ({status}); a file does not match its pinned digest" - ); - code = 1; - } - Err(error) => { - eprintln!( - "leleka: cannot run {}: {error}", - paths.bin("leleka-inference").display() - ); - code = 1; - } - } - match archive { - Ok(Ok(Some(seconds))) => say(&format!( - "archive file matches the pinned SHA-256 ({seconds:.1}s); stamped" - )), - Ok(Ok(None)) => {} - Ok(Err(message)) => { - eprintln!("leleka: {message}"); - code = 1; - } - Err(error) => { - eprintln!("leleka: archive verification failed to run: {error}"); - code = 1; - } - } + let mut code = engine_outcome(engine, &paths) | archive_outcome(archive); if tier_failed { eprintln!( "leleka: the expert profile is missing or does not match its pinned digest; rerun `leleka up` (or pass --no-expert-tier to accept the slower decode)" ); code = 1; } + say_verdict(code, started); + code +} + +fn say_verdict(code: i32, started: std::time::Instant) { say(&format!( "verification {} in {:.1}s", if code == 0 { "passed" } else { "FAILED" }, started.elapsed().as_secs_f32() )); - code +} + +/// The configuration, the stamp directory and the token the verification needs, or the exit code of the refusal. +fn verify_inputs(paths: &Paths) -> Result<(RunConfig, PathBuf, String), i32> { + let config = read_run_config(paths)?; + let stamp_dir = prepare_stamp_dir(paths)?; + let token = runtime_token(paths)?; + Ok((config, stamp_dir, token)) +} + +/// The expert tier's table is 192 KiB: checked first, loudly, because losing it is a silent large slowdown. +fn tier_has_failed(config: &RunConfig, paths: &Paths) -> bool { + let tier = crate::expert_profile::tier_report(config, &paths.dirs.assets); + say(&tier.line()); + !tier.on && !tier.opted_out && config.profile.expert_profile.is_some() +} + +fn prepare_stamp_dir(paths: &Paths) -> Result { + let stamp_dir = paths.engine_stamps(); + if let Err(error) = std::fs::create_dir_all(&stamp_dir) { + eprintln!("leleka: cannot create {}: {error}", stamp_dir.display()); + return Err(1); + } + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let _ = std::fs::set_permissions(&stamp_dir, std::fs::Permissions::from_mode(0o700)); + } + Ok(stamp_dir) +} + +/// The token the engine needs, from the environment file of the installation. +fn runtime_token(paths: &Paths) -> Result { + use crate::{config::RUNTIME_TOKEN_ENV, facts::parse_env_file}; + let env = std::fs::read_to_string(paths.env_file()) + .map(|text| parse_env_file(&text)) + .unwrap_or_default(); + env.get(RUNTIME_TOKEN_ENV).cloned().ok_or_else(|| { + eprintln!( + "leleka: {} has no {RUNTIME_TOKEN_ENV}; run `leleka up`", + paths.env_file().display() + ); + 2 + }) +} + +async fn run_engine_verification( + paths: &Paths, + config: &RunConfig, + token: String, +) -> std::io::Result { + tokio::process::Command::new(paths.bin("leleka-inference")) + .args(config.verify_args(true)) + .env(crate::config::RUNTIME_TOKEN_ENV, token) + .env_remove("HF_TOKEN") + .stdin(std::process::Stdio::null()) + .status() + .await +} + +fn engine_outcome(engine: std::io::Result, paths: &Paths) -> i32 { + match engine { + Ok(status) if status.success() => 0, + Ok(status) => { + eprintln!( + "leleka: the engine's verification failed ({status}); a file does not match its pinned digest" + ); + 1 + } + Err(error) => { + eprintln!( + "leleka: cannot run {}: {error}", + paths.bin("leleka-inference").display() + ); + 1 + } + } +} + +type ArchiveHash = Result, String>, tokio::task::JoinError>; + +/// A sealed-memfd profile cannot hand the engine the file (it must be read-only and owned); the archive file is +/// hashed here instead, against the pinned digest, and stamped for the supervisor (kind `kar-source`). +async fn hash_archive_file(paths: &Paths, config: &RunConfig, stamp_dir: PathBuf) -> ArchiveHash { + let kar = paths.kar(); + let memfd = config.profile.kar_source == crate::profile::KarSource::Memfd; + let stamps = VerifyStamps::new(stamp_dir, true); + tokio::task::spawn_blocking(move || hash_and_stamp_archive(&kar, memfd, &stamps)).await +} + +fn hash_and_stamp_archive( + kar: &Path, + memfd: bool, + stamps: &VerifyStamps, +) -> Result, String> { + if !memfd { + return Ok(None); + } + let begun = std::time::Instant::now(); + let file = + std::fs::File::open(kar).map_err(|e| format!("cannot open {}: {e}", kar.display()))?; + let before = file.metadata().ok().and_then(|m| FileIdentity::of(&m)); + let digest = + sha256_of_file(&file).map_err(|e| format!("cannot read {}: {e}", kar.display()))?; + if digest != crate::profile::archive_sha256() { + return Err(format!( + "{} does not match the pinned archive digest", + kar.display() + )); + } + let after = file.metadata().ok().and_then(|m| FileIdentity::of(&m)); + if let (Some(before), true) = (before, before == after) { + stamps + .record("kar-source", &crate::profile::archive_sha256(), &before) + .map_err(|e| format!("cannot record the archive stamp: {e}"))?; + } + Ok(Some(begun.elapsed().as_secs_f64())) +} + +fn archive_outcome(archive: ArchiveHash) -> i32 { + match archive { + Ok(Ok(Some(seconds))) => { + say(&format!( + "archive file matches the pinned SHA-256 ({seconds:.1}s); stamped" + )); + 0 + } + Ok(Ok(None)) => 0, + Ok(Err(message)) => { + eprintln!("leleka: {message}"); + 1 + } + Err(error) => { + eprintln!("leleka: archive verification failed to run: {error}"); + 1 + } + } } diff --git a/crates/deploy/src/bin/fake_runtime/cli_double.rs b/crates/deploy/src/bin/fake_runtime/cli_double.rs index 2e0c65f2..057311ad 100644 --- a/crates/deploy/src/bin/fake_runtime/cli_double.rs +++ b/crates/deploy/src/bin/fake_runtime/cli_double.rs @@ -17,42 +17,11 @@ pub(super) fn cli(fake: &Path, args: &[String]) { .to_owned(); let rest: Vec<&str> = args.iter().skip(2).map(String::as_str).collect(); match rest.as_slice() { - ["status"] => { - let connected = alive(&engine_address); - let ready = connected && fake.join("loaded").exists(); - println!( - "{}", - serde_json::json!({"schema_version":1,"runtimes":[{"id":id,"connected":connected,"epoch":"e","loaded_handle":null,"model_ready":ready,"configuration_action_required":false}]}) - ); - } + ["status"] => status_answer(fake, &engine_address, &id), ["load-mtp", model, profile] => { - if *model != id || *profile != "qwen4exp-kar-ple-mtp-v1" || !alive(&engine_address) { - eprintln!("Error: \"runtime_not_connected\""); - std::process::exit(1); - } - // Like the real CLI: the operation id and epoch are printed before the command is sent. - println!("{{\"operation_id\":\"op-1\",\"epoch\":\"e\",\"model\":\"{id}\"}}"); - // Loading takes a moment in the real engine. - std::thread::sleep(Duration::from_millis(700)); - if !fake.join("fail-load").exists() { - let _ = fs::write(fake.join("loaded"), "1"); - } - println!("{{\"state\":1}}"); - } - ["operation", model, "op-1", "e"] if *model == id => { - let state = if fake.join("fail-load").exists() { - 3 - } else if fake.join("loaded").exists() { - 2 - } else { - 1 - }; - println!( - "{{ - \"state\": {state} -}}" - ); + load_mtp_answer(fake, &engine_address, &id, (*model, *profile)) } + ["operation", model, "op-1", "e"] if *model == id => operation_answer(fake), _ => { eprintln!("fake cli: unsupported {rest:?}"); std::process::exit(2); @@ -60,6 +29,41 @@ pub(super) fn cli(fake: &Path, args: &[String]) { } } +fn status_answer(fake: &Path, engine_address: &str, id: &str) { + let connected = alive(engine_address); + let ready = connected && fake.join("loaded").exists(); + println!( + "{}", + serde_json::json!({"schema_version":1,"runtimes":[{"id":id,"connected":connected,"epoch":"e","loaded_handle":null,"model_ready":ready,"configuration_action_required":false}]}) + ); +} + +fn load_mtp_answer(fake: &Path, engine_address: &str, id: &str, (model, profile): (&str, &str)) { + if model != id || profile != "qwen4exp-kar-ple-mtp-v1" || !alive(engine_address) { + eprintln!("Error: \"runtime_not_connected\""); + std::process::exit(1); + } + // Like the real CLI: the operation id and epoch are printed before the command is sent. + println!("{{\"operation_id\":\"op-1\",\"epoch\":\"e\",\"model\":\"{id}\"}}"); + // Loading takes a moment in the real engine. + std::thread::sleep(Duration::from_millis(700)); + if !fake.join("fail-load").exists() { + let _ = fs::write(fake.join("loaded"), "1"); + } + println!("{{\"state\":1}}"); +} + +fn operation_answer(fake: &Path) { + let state = if fake.join("fail-load").exists() { + 3 + } else if fake.join("loaded").exists() { + 2 + } else { + 1 + }; + println!("{{\n \"state\": {state}\n}}"); +} + pub(super) fn fetch_shards(dir: &str) { fs::create_dir_all(dir).expect("model dir"); for (name, size) in [ diff --git a/crates/deploy/src/bin/fake_runtime/engine_double.rs b/crates/deploy/src/bin/fake_runtime/engine_double.rs index 959fb239..17f0e760 100644 --- a/crates/deploy/src/bin/fake_runtime/engine_double.rs +++ b/crates/deploy/src/bin/fake_runtime/engine_double.rs @@ -10,18 +10,51 @@ pub(super) fn alive(address: &str) -> bool { pub(super) fn engine(fake: &Path, args: &[String]) { if args.iter().any(|a| a == "--verify-only") { - // `--verify-only`: the load-time source verification, no listener, no model. - if fake.join("fail-verify").exists() { - eprintln!("fake engine: a file does not match its pinned digest"); - std::process::exit(1); - } - eprintln!("leleka-load-time phase=all_sources_verified seconds=0.01 total=0.01"); + verify_only(fake); return; } if fake.join("fail-engine").exists() { eprintln!("fake engine: failing on request"); std::process::exit(7); } + check_environment(fake, args); + let listen = flag(args, "--listen").unwrap_or("127.0.0.1:0").to_owned(); + check_archive(args); + let listener = TcpListener::bind(&listen).unwrap_or_else(|e| { + eprintln!("fake engine: cannot bind {listen}: {e}"); + std::process::exit(6); + }); + announce_listening(fake, &listen); + if fake.join("fail-load").exists() { + // The real engine reports a failed load on its own stderr and stays up. + eprintln!("leleka-load phase=OriginalStack class=BackendUnavailable"); + } + crash_once_if_asked(fake); + for stream in listener.incoming() { + drop(stream); + } +} + +fn announce_listening(fake: &Path, listen: &str) { + let _ = fs::remove_file(fake.join("loaded")); + let _ = fs::write(fake.join("engine.pid"), std::process::id().to_string()); + eprintln!( + "fake engine: listening on {listen} pid {}", + std::process::id() + ); +} + +/// `--verify-only`: the load-time source verification, no listener, no model. +fn verify_only(fake: &Path) { + if fake.join("fail-verify").exists() { + eprintln!("fake engine: a file does not match its pinned digest"); + std::process::exit(1); + } + eprintln!("leleka-load-time phase=all_sources_verified seconds=0.01 total=0.01"); +} + +/// The token must be there, the Hugging Face token must not, and a refused budget stops the start. +fn check_environment(fake: &Path, args: &[String]) { let token = std::env::var("LELEKA_RUNTIME_TOKEN").unwrap_or_default(); if token.len() < 32 { eprintln!("fake engine: LELEKA_RUNTIME_TOKEN missing"); @@ -41,7 +74,10 @@ pub(super) fn engine(fake: &Path, args: &[String]) { eprintln!("fake engine: refusing a budget of {budget} bytes"); std::process::exit(9); } - let listen = flag(args, "--listen").unwrap_or("127.0.0.1:0").to_owned(); +} + +/// The archive argument: an inherited sealed descriptor or a file; one of them must be there. +fn check_archive(args: &[String]) { if let Some(fd) = flag(args, "--kar-archive-fd") { // The shim must have moved the descriptor to >= 3 and the engine must find a sealed, unlinked memfd. let number: u32 = fd.parse().unwrap_or(0); @@ -65,20 +101,9 @@ pub(super) fn engine(fake: &Path, args: &[String]) { eprintln!("fake engine: no archive argument"); std::process::exit(5); } - let listener = TcpListener::bind(&listen).unwrap_or_else(|e| { - eprintln!("fake engine: cannot bind {listen}: {e}"); - std::process::exit(6); - }); - let _ = fs::remove_file(fake.join("loaded")); - let _ = fs::write(fake.join("engine.pid"), std::process::id().to_string()); - eprintln!( - "fake engine: listening on {listen} pid {}", - std::process::id() - ); - if fake.join("fail-load").exists() { - // The real engine reports a failed load on its own stderr and stays up. - eprintln!("leleka-load phase=OriginalStack class=BackendUnavailable"); - } +} + +fn crash_once_if_asked(fake: &Path) { if fake.join("crash-engine-once").exists() { let _ = fs::remove_file(fake.join("crash-engine-once")); std::thread::spawn(|| { @@ -87,7 +112,4 @@ pub(super) fn engine(fake: &Path, args: &[String]) { std::process::exit(9); }); } - for stream in listener.incoming() { - drop(stream); - } } diff --git a/crates/deploy/src/bin/fake_runtime/gateway_double.rs b/crates/deploy/src/bin/fake_runtime/gateway_double.rs index cdf5f3ba..6b1e67f3 100644 --- a/crates/deploy/src/bin/fake_runtime/gateway_double.rs +++ b/crates/deploy/src/bin/fake_runtime/gateway_double.rs @@ -5,26 +5,8 @@ use super::*; pub(super) fn strata(fake: &Path, args: &[String]) { let args: Vec<&str> = args.iter().map(String::as_str).collect(); match args.as_slice() { - ["api-key", "init", "--file", file] => { - if !Path::new(file).exists() { - let key = "fake-api-key-0123456789abcdef0123456789abcdef"; - let mut options = fs::OpenOptions::new(); - options.create_new(true).write(true); - #[cfg(unix)] - { - use std::os::unix::fs::OpenOptionsExt; - options.mode(0o600); - } - let _ = options - .open(file) - .and_then(|mut f| f.write_all(key.as_bytes())); - } - println!("{{\"created\":false}}"); - } - ["model", "fetch", _, "--output", dir] => { - fetch_shards(dir); - println!("fetched"); - } + ["api-key", "init", "--file", file] => init_api_key(file), + ["model", "fetch", _, "--output", dir] => fetch_and_say(dir), ["model", "verify", _, "--output", _] => println!("verified"), [ "model", @@ -36,22 +18,8 @@ pub(super) fn strata(fake: &Path, args: &[String]) { kar, "--levels", "2", - ] => { - // Like the real tool: fetch and verify the shards first. - fetch_shards(source_dir); - if !Path::new(kar).exists() { - fs::File::create(kar) - .and_then(|f| f.set_len(55_295_529_472)) - .expect("sparse archive"); - fs::write(format!("{kar}.provenance.json"), "{}").expect("provenance"); - } - println!("created and verified experimental streamed KAR-2: {kar}"); - } - ["model", "extract-tokenizer", _, "--output", dir] => { - fs::create_dir_all(Path::new(dir).join("tokenizer")).expect("tokenizer dir"); - fs::write(Path::new(dir).join("tokenizer/tokenizer.json"), "{}") - .expect("tokenizer file"); - } + ] => ensure_streamed_archive(source_dir, kar), + ["model", "extract-tokenizer", _, "--output", dir] => extract_tokenizer(dir), ["serve", "--config", config] => api(fake, config), other => { eprintln!("fake strata-next: unsupported {other:?}"); @@ -60,6 +28,45 @@ pub(super) fn strata(fake: &Path, args: &[String]) { } } +fn fetch_and_say(dir: &str) { + fetch_shards(dir); + println!("fetched"); +} + +fn extract_tokenizer(dir: &str) { + fs::create_dir_all(Path::new(dir).join("tokenizer")).expect("tokenizer dir"); + fs::write(Path::new(dir).join("tokenizer/tokenizer.json"), "{}").expect("tokenizer file"); +} + +fn init_api_key(file: &str) { + if !Path::new(file).exists() { + let key = "fake-api-key-0123456789abcdef0123456789abcdef"; + let mut options = fs::OpenOptions::new(); + options.create_new(true).write(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); + } + let _ = options + .open(file) + .and_then(|mut f| f.write_all(key.as_bytes())); + } + println!("{{\"created\":false}}"); +} + +fn ensure_streamed_archive(source_dir: &str, kar: &str) { + // Like the real tool: fetch and verify the shards first. + fetch_shards(source_dir); + if !Path::new(kar).exists() { + fs::File::create(kar) + .and_then(|f| f.set_len(55_295_529_472)) + .expect("sparse archive"); + fs::write(format!("{kar}.provenance.json"), "{}").expect("provenance"); + } + println!("created and verified experimental streamed KAR-2: {kar}"); +} + pub(super) fn api(fake: &Path, config: &str) { let config: serde_json::Value = fs::read_to_string(config) .ok() @@ -76,14 +83,7 @@ pub(super) fn api(fake: &Path, config: &str) { .unwrap_or_default() .trim() .to_owned(); - if std::env::var("LELEKA_RUNTIME_TOKEN") - .unwrap_or_default() - .len() - < 32 - { - eprintln!("fake api: LELEKA_RUNTIME_TOKEN missing"); - std::process::exit(2); - } + require_runtime_token(); let listener = TcpListener::bind(&bind).unwrap_or_else(|e| { eprintln!("fake api: cannot bind {bind}: {e}"); std::process::exit(6); @@ -94,77 +94,124 @@ pub(super) fn api(fake: &Path, config: &str) { } } -pub(super) fn respond(mut stream: TcpStream, fake: &Path, engine_address: &str, key: &str) { - // The head and the body of a POST may arrive in separate segments: read until Content-Length bytes of body are in. - let _ = stream.set_read_timeout(Some(Duration::from_secs(2))); - let mut raw: Vec = Vec::new(); - let mut buffer = [0u8; 4096]; - loop { - let count = stream.read(&mut buffer).unwrap_or(0); - raw.extend_from_slice(&buffer[..count]); - let text = String::from_utf8_lossy(&raw).into_owned(); - let complete = text.split_once("\r\n\r\n").is_some_and(|(head, body)| { - let wanted = head - .lines() - .find_map(|l| { - l.to_ascii_lowercase() - .strip_prefix("content-length:") - .and_then(|v| v.trim().parse::().ok()) - }) - .unwrap_or(0); - body.len() >= wanted - }); - if count == 0 || complete { - break; - } +fn require_runtime_token() { + if std::env::var("LELEKA_RUNTIME_TOKEN") + .unwrap_or_default() + .len() + < 32 + { + eprintln!("fake api: LELEKA_RUNTIME_TOKEN missing"); + std::process::exit(2); } - let request = String::from_utf8_lossy(&raw).into_owned(); +} + +pub(super) fn respond(mut stream: TcpStream, fake: &Path, engine_address: &str, key: &str) { + let request = read_request(&mut stream); let path = request.split_whitespace().nth(1).unwrap_or("/").to_owned(); let authorized = request.contains(&format!("Authorization: Bearer {key}\r\n")); let ready = alive(engine_address) && fake.join("loaded").exists(); - let (status, body) = match path.as_str() { - "/health" => ("200 OK", "{\"ok\":true}".to_owned()), - _ if !authorized => ( - "401 Unauthorized", - "{\"error\":\"unauthorized\"}".to_owned(), - ), - "/ready" if ready => ( - "200 OK", - "{\"service\":\"strata-control\",\"ready\":true}".to_owned(), - ), - "/ready" => ( - "503 Service Unavailable", - "{\"service\":\"strata-control\",\"ready\":false}".to_owned(), - ), - // The gateway status document with an engine telemetry block, as `leleka status` renders it. - // The control plane's own view: the worker state and the request that is active (a switch file makes one stay active). - // One-shot: the next answer after it is a healthy one (the restarted engine is not hung). - "/metrics" if fake.join("hang-decode").exists() => { - let _ = fs::remove_file(fake.join("hang-decode")); - ( - "200 OK", - "{\"worker\":\"ready\",\"up\":true,\"active\":true,\"active_elapsed_ms\":600000}".to_owned(), - ) - } - "/metrics" => ( - "200 OK", - format!("{{\"worker\":\"{}\",\"up\":{ready},\"active\":false,\"active_elapsed_ms\":null}}", if ready { "ready" } else { "failed" }), - ), - "/v1/status" if ready => ( - "200 OK", - "{\"loaded\":true,\"machine\":{\"phase\":\"idle\",\"gpu\":null,\"cpu\":null,\"ram\":null,\"throughput\":{},\"cache\":{},\"context\":{\"live_tokens\":0,\"max_tokens\":8192}},\"prefix_cache\":null}".to_owned(), - ), - // `POST /v1/reconfigure`: accept and echo the settings the way the real gateway answers. - "/v1/reconfigure" if request.starts_with("POST") && ready => { - let body = request.split("\r\n\r\n").nth(1).unwrap_or("{}"); - let settings: serde_json::Value = serde_json::from_str(body).unwrap_or_default(); - ("200 OK", serde_json::json!({"settings": settings}).to_string()) - } - _ => ("404 Not Found", "{}".to_owned()), - }; + let (status, body) = answer(&request, &path, fake, (authorized, ready)); let _ = write!( stream, "HTTP/1.1 {status}\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}", body.len() ); } + +/// The head and the body of a POST may arrive in separate segments: read until Content-Length bytes of body are in. +fn read_request(stream: &mut TcpStream) -> String { + let _ = stream.set_read_timeout(Some(Duration::from_secs(2))); + let mut raw: Vec = Vec::new(); + let mut buffer = [0u8; 4096]; + loop { + let count = stream.read(&mut buffer).unwrap_or(0); + raw.extend_from_slice(&buffer[..count]); + if count == 0 || request_complete(&raw) { + break; + } + } + String::from_utf8_lossy(&raw).into_owned() +} + +/// Is the whole body, as far as `Content-Length` says, in `raw`? +fn request_complete(raw: &[u8]) -> bool { + let text = String::from_utf8_lossy(raw).into_owned(); + text.split_once("\r\n\r\n").is_some_and(|(head, body)| { + let wanted = head + .lines() + .find_map(|l| { + l.to_ascii_lowercase() + .strip_prefix("content-length:") + .and_then(|v| v.trim().parse::().ok()) + }) + .unwrap_or(0); + body.len() >= wanted + }) +} + +/// The status line and the body for `path`. `state`: whether the key was sent, and whether the engine is loaded. +fn answer(request: &str, path: &str, fake: &Path, state: (bool, bool)) -> (&'static str, String) { + let (authorized, ready) = state; + match path { + "/health" => ("200 OK", "{\"ok\":true}".to_owned()), + _ if !authorized => ( + "401 Unauthorized", + "{\"error\":\"unauthorized\"}".to_owned(), + ), + "/ready" => ready_answer(ready), + "/metrics" => metrics_answer(fake, ready), + "/v1/status" if ready => ( + "200 OK", + "{\"loaded\":true,\"machine\":{\"phase\":\"idle\",\"gpu\":null,\"cpu\":null,\"ram\":null,\"throughput\":{},\"cache\":{},\"context\":{\"live_tokens\":0,\"max_tokens\":8192}},\"prefix_cache\":null}".to_owned(), + ), + "/v1/reconfigure" => reconfigure_answer(request, ready), + _ => ("404 Not Found", "{}".to_owned()), + } +} + +fn ready_answer(ready: bool) -> (&'static str, String) { + if ready { + ( + "200 OK", + "{\"service\":\"strata-control\",\"ready\":true}".to_owned(), + ) + } else { + ( + "503 Service Unavailable", + "{\"service\":\"strata-control\",\"ready\":false}".to_owned(), + ) + } +} + +/// `POST /v1/reconfigure`: accept and echo the settings the way the real gateway answers. +fn reconfigure_answer(request: &str, ready: bool) -> (&'static str, String) { + if !(request.starts_with("POST") && ready) { + return ("404 Not Found", "{}".to_owned()); + } + let body = request.split("\r\n\r\n").nth(1).unwrap_or("{}"); + let settings: serde_json::Value = serde_json::from_str(body).unwrap_or_default(); + ( + "200 OK", + serde_json::json!({"settings": settings}).to_string(), + ) +} + +/// The control plane's own view: the worker state and the request that is active (a switch file makes one stay active). +/// One-shot: the next answer after it is a healthy one (the restarted engine is not hung). +fn metrics_answer(fake: &Path, ready: bool) -> (&'static str, String) { + if fake.join("hang-decode").exists() { + let _ = fs::remove_file(fake.join("hang-decode")); + return ( + "200 OK", + "{\"worker\":\"ready\",\"up\":true,\"active\":true,\"active_elapsed_ms\":600000}" + .to_owned(), + ); + } + ( + "200 OK", + format!( + "{{\"worker\":\"{}\",\"up\":{ready},\"active\":false,\"active_elapsed_ms\":null}}", + if ready { "ready" } else { "failed" } + ), + ) +} diff --git a/crates/deploy/src/bin/fake_runtime/main.rs b/crates/deploy/src/bin/fake_runtime/main.rs index b45ff9e1..d3ec3307 100644 --- a/crates/deploy/src/bin/fake_runtime/main.rs +++ b/crates/deploy/src/bin/fake_runtime/main.rs @@ -23,14 +23,7 @@ fn main() { .trim_end_matches(".exe") .to_owned(); let args: Vec = args.collect(); - let bin_dir = Path::new(&invoked) - .parent() - .map(Path::to_path_buf) - .unwrap_or_default(); - let fake = bin_dir - .parent() - .map(|p| p.join("fake")) - .unwrap_or_else(|| PathBuf::from("fake")); + let fake = fake_dir(&invoked); let _ = fs::create_dir_all(&fake); log_call(&fake, &name, &args); match name.as_str() { @@ -45,6 +38,18 @@ fn main() { } } +/// `PREFIX/fake`, found from the invocation path `PREFIX/bin/NAME`. +fn fake_dir(invoked: &str) -> PathBuf { + let bin_dir = Path::new(invoked) + .parent() + .map(Path::to_path_buf) + .unwrap_or_default(); + bin_dir + .parent() + .map(|p| p.join("fake")) + .unwrap_or_else(|| PathBuf::from("fake")) +} + fn log_call(fake: &Path, name: &str, args: &[String]) { // Tokens never appear on a command line; the log is for call counting. if let Ok(mut file) = fs::OpenOptions::new() diff --git a/crates/deploy/src/cli/dispatch.rs b/crates/deploy/src/cli/dispatch.rs index 4c85c144..259eeff5 100644 --- a/crates/deploy/src/cli/dispatch.rs +++ b/crates/deploy/src/cli/dispatch.rs @@ -9,49 +9,41 @@ pub fn parse(args: &[String], env: &Environment) -> Result { match command.as_str() { "-h" | "--help" | "help" => Ok(Command::Help), "version" | "--version" | "-V" => Ok(Command::Version), - "up" => up_options(rest, env).map(Command::Up), - "preflight" => up_options(rest, env).map(Command::Preflight), - "status" => up_options(rest, env).map(Command::Status), - "down" => up_options(rest, env).map(Command::Down), + "up" | "preflight" | "status" | "down" | "verify" | "reconfigure" | "logs" | "report" + | "service" => parse_installation_command(command, rest, env), + other => parse_small_command(other, rest), + } +} + +/// The commands that work on an installation: they locate it with the options of `up`. +fn parse_installation_command( + command: &str, + rest: &[String], + env: &Environment, +) -> Result { + match command { "reconfigure" => reconfigure_command(rest, env), - "verify" => up_options(rest, env).map(Command::Verify), "logs" => logs_command(rest, env), "report" => report_command(rest, env), - "profiles" => match rest { - [] => Ok(Command::Profiles(None)), - [show, name] if show == "show" => Ok(Command::Profiles(Some(name.clone()))), - _ => Err("usage: leleka profiles [show NAME]".into()), - }, - "run" => { - let flags = parse_flags(rest, &[("--config", true), ("--kar-fd", true)])?; - let config = text(&flags, "--config").ok_or("leleka run needs --config FILE")?; - Ok(Command::Run { - config: PathBuf::from(config), - kar_fd: flags - .get("--kar-fd") - .map(|_| number(&flags, "--kar-fd", 0u32)) - .transpose()?, + "service" => parse_service(rest, env), + _ => { + let options = up_options(rest, env)?; + Ok(match command { + "up" => Command::Up(options), + "preflight" => Command::Preflight(options), + "status" => Command::Status(options), + "down" => Command::Down(options), + _ => Command::Verify(options), }) } - "service" => { - let Some((action, rest)) = rest.split_first() else { - return Err("usage: leleka service install|uninstall|status|start|stop".into()); - }; - let action = match action.as_str() { - "install" => ServiceAction::Install, - "uninstall" => ServiceAction::Uninstall, - "status" => ServiceAction::Status, - "start" => ServiceAction::Start, - "stop" => ServiceAction::Stop, - "hold" => ServiceAction::Hold, - other => { - return Err(format!( - "unknown service action {other:?}; use install, uninstall, status, start or stop" - )); - } - }; - up_options(rest, env).map(|options| Command::Service(action, options)) - } + } +} + +/// The commands with a few arguments of their own. +fn parse_small_command(command: &str, rest: &[String]) -> Result { + match command { + "profiles" => parse_profiles(rest), + "run" => parse_run(rest), "exec-inherit" => Ok(Command::ExecInherit(rest.to_vec())), "seal-exec" => Ok(Command::SealExec(rest.to_vec())), "seal-probe" => match rest { @@ -61,3 +53,43 @@ pub fn parse(args: &[String], env: &Environment) -> Result { other => Err(format!("unknown command {other:?}; see `leleka --help`")), } } + +fn parse_profiles(rest: &[String]) -> Result { + match rest { + [] => Ok(Command::Profiles(None)), + [show, name] if show == "show" => Ok(Command::Profiles(Some(name.clone()))), + _ => Err("usage: leleka profiles [show NAME]".into()), + } +} + +fn parse_run(rest: &[String]) -> Result { + let flags = parse_flags(rest, &[("--config", true), ("--kar-fd", true)])?; + let config = text(&flags, "--config").ok_or("leleka run needs --config FILE")?; + Ok(Command::Run { + config: PathBuf::from(config), + kar_fd: flags + .get("--kar-fd") + .map(|_| number(&flags, "--kar-fd", 0u32)) + .transpose()?, + }) +} + +fn parse_service(rest: &[String], env: &Environment) -> Result { + let Some((action, rest)) = rest.split_first() else { + return Err("usage: leleka service install|uninstall|status|start|stop".into()); + }; + let action = match action.as_str() { + "install" => ServiceAction::Install, + "uninstall" => ServiceAction::Uninstall, + "status" => ServiceAction::Status, + "start" => ServiceAction::Start, + "stop" => ServiceAction::Stop, + "hold" => ServiceAction::Hold, + other => { + return Err(format!( + "unknown service action {other:?}; use install, uninstall, status, start or stop" + )); + } + }; + up_options(rest, env).map(|options| Command::Service(action, options)) +} diff --git a/crates/deploy/src/cli/flag_parsing.rs b/crates/deploy/src/cli/flag_parsing.rs index 0196d391..581a9de6 100644 --- a/crates/deploy/src/cli/flag_parsing.rs +++ b/crates/deploy/src/cli/flag_parsing.rs @@ -9,35 +9,58 @@ impl ReconfigureArgs { } } +/// `--name=value` split at the first `=` when it follows a long option; otherwise the argument is the name. +pub(super) fn split_inline(arg: &str) -> (&str, Option) { + match arg.split_once('=') { + Some((name, value)) if name.starts_with("--") => (name, Some(value.to_owned())), + _ => (arg, None), + } +} + +/// The value of a flag: inline, or the next argument (which `index` then points at). +pub(super) fn next_value( + args: &[String], + index: &mut usize, + name: &str, + inline: Option, +) -> Result { + match inline { + Some(value) => Ok(value), + None => { + *index += 1; + args.get(*index) + .cloned() + .ok_or_else(|| format!("{name} needs a value")) + } + } +} + +/// The value of a flag of the table: `None` for a flag without one, which must not be given one. +fn flag_value( + args: &[String], + index: &mut usize, + name: &str, + takes_value: bool, + inline: Option, +) -> Result, String> { + if takes_value { + return next_value(args, index, name, inline).map(Some); + } + if inline.is_some() { + return Err(format!("{name} takes no value")); + } + Ok(None) +} + pub(super) fn parse_flags(args: &[String], table: &[(&str, bool)]) -> Result { let mut flags = Flags::new(); let mut index = 0; while index < args.len() { - let arg = &args[index]; - let (name, inline) = match arg.split_once('=') { - Some((name, value)) if name.starts_with("--") => (name, Some(value.to_owned())), - _ => (arg.as_str(), None), - }; + let (name, inline) = split_inline(&args[index]); let Some((_, takes_value)) = table.iter().find(|(flag, _)| *flag == name) else { return Err(format!("unknown option {name:?}; see `leleka --help`")); }; - let value = if *takes_value { - match inline { - Some(value) => Some(value), - None => { - index += 1; - Some( - args.get(index) - .ok_or_else(|| format!("{name} needs a value"))? - .clone(), - ) - } - } - } else if inline.is_some() { - return Err(format!("{name} takes no value")); - } else { - None - }; + let value = flag_value(args, &mut index, name, *takes_value, inline)?; if flags.insert(name.to_owned(), value).is_some() { return Err(format!("{name} given twice")); } @@ -108,9 +131,76 @@ pub(super) fn is_absolute(path: &std::path::Path) -> bool { pub(super) fn up_options(args: &[String], env: &Environment) -> Result { let flags = parse_flags(args, UP_FLAGS)?; + let dirs = up_dirs(&flags, env)?; + let mode = up_mode(&flags)?; + let kar_fd = up_kar_fd(&flags, mode)?; + check_mode_for_host(mode, env)?; + let ports = up_ports(&flags)?; + let (cublas_dir, expert_profile_file) = up_files(&flags)?; + let numbers = UpNumbers::read(&flags, env)?; + let chosen = Chosen { + dirs, + mode, + kar_fd, + ports, + cublas_dir, + expert_profile_file, + }; + Ok(assemble_up_options(&flags, chosen, numbers)) +} + +/// `--cublas-dir` (absolute) and `--expert-profile-file` (not together with `--no-expert-tier`). +fn up_files(flags: &Flags) -> Result<(Option, Option), String> { + let cublas_dir = text(flags, "--cublas-dir").map(PathBuf::from); + if let Some(dir) = &cublas_dir + && !is_absolute(dir) + { + return Err("--cublas-dir must be an absolute path".into()); + } + let expert_profile_file = text(flags, "--expert-profile-file").map(PathBuf::from); + if expert_profile_file.is_some() && flags.contains_key("--no-expert-tier") { + return Err("--expert-profile-file and --no-expert-tier contradict each other".into()); + } + Ok((cublas_dir, expert_profile_file)) +} + +/// The options of `up` that are checked against the host or each other. +struct Chosen { + dirs: Dirs, + mode: ModeChoice, + kar_fd: Option, + ports: Ports, + cublas_dir: Option, + expert_profile_file: Option, +} + +/// The numeric options of `up` and the preset. +struct UpNumbers { + gpu: u32, + preset: crate::resources::Preset, + gpu_budget_gib: Option, + context_tokens: Option, + timeout_s: u64, +} + +impl UpNumbers { + fn read(flags: &Flags, env: &Environment) -> Result { + let gpu = number(flags, "--gpu", 0u32)?; + let preset = up_preset(flags, env)?; + Ok(Self { + gpu, + preset, + gpu_budget_gib: ranged(flags, "--gpu-budget-gib", 1u64..=1024)?, + context_tokens: ranged(flags, "--context-tokens", 1u32..=262_144)?, + timeout_s: up_timeout(flags)?, + }) + } +} + +fn up_dirs(flags: &Flags, env: &Environment) -> Result { let defaults = Dirs::defaults(env.root, env.home.as_deref(), env.var); let abs = |name: &str, fallback: PathBuf| -> Result { - let path = text(&flags, name).map(PathBuf::from).unwrap_or(fallback); + let path = text(flags, name).map(PathBuf::from).unwrap_or(fallback); if !is_absolute(&path) { return Err(format!( "{name} must be an absolute path (got {})", @@ -119,109 +209,116 @@ pub(super) fn up_options(args: &[String], env: &Environment) -> Result Result { + if flags.contains_key("--foreground") { if flags.contains_key("--mode") { return Err("use either --foreground or --mode".into()); } - ModeChoice::Foreground - } else { - match text(&flags, "--mode").unwrap_or("auto") { - "auto" => ModeChoice::Auto, - "system" => ModeChoice::System, - "user" => ModeChoice::User, - "foreground" => ModeChoice::Foreground, - "none" => ModeChoice::None, - other => { - return Err(format!( - "--mode must be auto, system, user, foreground or none, not {other:?}" - )); - } - } - }; - let kar_fd = match flags.get("--kar-fd") { - None => None, - Some(_) => { - let fd: u32 = number(&flags, "--kar-fd", 0u32)?; - if !(3..=1_048_576).contains(&fd) { - return Err( - "--kar-fd must be an inherited descriptor number of 3 or higher".into(), - ); - } - if matches!(mode, ModeChoice::System | ModeChoice::User) { - return Err("--kar-fd belongs to a process that holds the descriptor; use it with --foreground or --mode none, not with a systemd unit".into()); - } - Some(fd) - } - }; + return Ok(ModeChoice::Foreground); + } + match text(flags, "--mode").unwrap_or("auto") { + "auto" => Ok(ModeChoice::Auto), + "system" => Ok(ModeChoice::System), + "user" => Ok(ModeChoice::User), + "foreground" => Ok(ModeChoice::Foreground), + "none" => Ok(ModeChoice::None), + other => Err(format!( + "--mode must be auto, system, user, foreground or none, not {other:?}" + )), + } +} + +fn up_kar_fd(flags: &Flags, mode: ModeChoice) -> Result, String> { + if flags.get("--kar-fd").is_none() { + return Ok(None); + } + let fd: u32 = number(flags, "--kar-fd", 0u32)?; + if !(3..=1_048_576).contains(&fd) { + return Err("--kar-fd must be an inherited descriptor number of 3 or higher".into()); + } + if matches!(mode, ModeChoice::System | ModeChoice::User) { + return Err(concat!( + "--kar-fd belongs to a process that holds the descriptor; use it with ", + "--foreground or --mode none, not with a systemd unit" + ) + .into()); + } + Ok(Some(fd)) +} + +/// A systemd mode needs systemd, and the system one needs root. +fn check_mode_for_host(mode: ModeChoice, env: &Environment) -> Result<(), String> { if cfg!(windows) && matches!(mode, ModeChoice::System | ModeChoice::User) { return Err("--mode system/user need systemd; on Windows use --foreground (or --mode none to only prepare)".into()); } if mode == ModeChoice::System && !env.root { return Err("--mode system needs root (use sudo), or --mode user / --foreground".into()); } + Ok(()) +} + +fn up_ports(flags: &Flags) -> Result { let ports = Ports { - api: format!( - "{}:{}", - api_bind(&flags)?, - port(&flags, "--api-port", 8081)? - ), - engine: format!("127.0.0.1:{}", port(&flags, "--engine-port", 18766)?), - daemon: format!("127.0.0.1:{}", port(&flags, "--daemon-port", 18080)?), + api: format!("{}:{}", api_bind(flags)?, port(flags, "--api-port", 8081)?), + engine: format!("127.0.0.1:{}", port(flags, "--engine-port", 18766)?), + daemon: format!("127.0.0.1:{}", port(flags, "--daemon-port", 18080)?), }; let distinct = [&ports.api, &ports.engine, &ports.daemon]; if distinct[0] == distinct[1] || distinct[0] == distinct[2] || distinct[1] == distinct[2] { return Err("the API, engine and gateway ports must differ".into()); } - let cublas_dir = text(&flags, "--cublas-dir").map(PathBuf::from); - if let Some(dir) = &cublas_dir - && !is_absolute(dir) - { - return Err("--cublas-dir must be an absolute path".into()); + Ok(ports) +} + +fn up_preset(flags: &Flags, env: &Environment) -> Result { + match text(flags, "--preset") { + Some(value) => crate::resources::Preset::parse(value), + None => match (env.var)("LELEKA_PRESET") { + Some(value) if !value.is_empty() => crate::resources::Preset::parse(&value), + _ => Ok(crate::resources::Preset::Dedicated), + }, } - let expert_profile_file = text(&flags, "--expert-profile-file").map(PathBuf::from); - if expert_profile_file.is_some() && flags.contains_key("--no-expert-tier") { - return Err("--expert-profile-file and --no-expert-tier contradict each other".into()); +} + +fn up_timeout(flags: &Flags) -> Result { + let value: u64 = number(flags, "--timeout-s", 3600)?; + if !(1..=86_400).contains(&value) { + return Err("--timeout-s must be 1..86400".into()); } - Ok(UpOptions { + Ok(value) +} + +fn assemble_up_options(flags: &Flags, chosen: Chosen, numbers: UpNumbers) -> UpOptions { + UpOptions { dry_run: flags.contains_key("--dry-run"), json: flags.contains_key("--json"), - profile: text(&flags, "--profile").map(str::to_owned), - gpu: number(&flags, "--gpu", 0u32)?, - dirs, - bin_src: text(&flags, "--bin-src").map(PathBuf::from), - mode, - preset: match text(&flags, "--preset") { - Some(value) => crate::resources::Preset::parse(value)?, - None => match (env.var)("LELEKA_PRESET") { - Some(value) if !value.is_empty() => crate::resources::Preset::parse(&value)?, - _ => crate::resources::Preset::Dedicated, - }, - }, - ports, - gpu_budget_gib: ranged(&flags, "--gpu-budget-gib", 1u64..=1024)?, - context_tokens: ranged(&flags, "--context-tokens", 1u32..=262_144)?, - service_user: text(&flags, "--service-user").map(str::to_owned), - kar_fd, + profile: text(flags, "--profile").map(str::to_owned), + gpu: numbers.gpu, + dirs: chosen.dirs, + bin_src: text(flags, "--bin-src").map(PathBuf::from), + mode: chosen.mode, + preset: numbers.preset, + ports: chosen.ports, + gpu_budget_gib: numbers.gpu_budget_gib, + context_tokens: numbers.context_tokens, + service_user: text(flags, "--service-user").map(str::to_owned), + kar_fd: chosen.kar_fd, fetch: !flags.contains_key("--no-fetch"), reverify: flags.contains_key("--reverify"), quick: flags.contains_key("--quick"), trust_archive: flags.contains_key("--trust-archive"), - mtp_pack: text(&flags, "--mtp-pack").map(PathBuf::from), - expert_profile_file, + mtp_pack: text(flags, "--mtp-pack").map(PathBuf::from), + expert_profile_file: chosen.expert_profile_file, no_expert_tier: flags.contains_key("--no-expert-tier"), - cublas_dir, + cublas_dir: chosen.cublas_dir, install_cublas: !flags.contains_key("--no-install-cublas"), - timeout_s: { - let value: u64 = number(&flags, "--timeout-s", 3600)?; - if !(1..=86_400).contains(&value) { - return Err("--timeout-s must be 1..86400".into()); - } - value - }, - }) + timeout_s: numbers.timeout_s, + } } diff --git a/crates/deploy/src/cli/subcommands.rs b/crates/deploy/src/cli/subcommands.rs index 0552b607..963e2d44 100644 --- a/crates/deploy/src/cli/subcommands.rs +++ b/crates/deploy/src/cli/subcommands.rs @@ -1,96 +1,97 @@ //! The `logs`, `report` and `reconfigure` commands and the splitting of their flags. +use super::flag_parsing::{next_value, split_inline}; use super::*; /// The settings flags of a `reconfigure` command line: returns the other arguments (they locate the service) and the JSON /// document the engine validates. Numbers stay numbers; the two cache members stay text. pub fn split_reconfigure(args: &[String]) -> Result<(Vec, ReconfigureArgs), String> { - let mut rest: Vec = Vec::new(); - let mut document = serde_json::Map::new(); - let mut extra = ReconfigureArgs::default(); + let mut parse = ReconfigureParse { + rest: Vec::new(), + document: serde_json::Map::new(), + extra: ReconfigureArgs::default(), + }; let mut index = 0; while index < args.len() { - let arg = &args[index]; - let (name, inline) = match arg.split_once('=') { - Some((name, value)) if name.starts_with("--") => (name, Some(value.to_owned())), - _ => (arg.as_str(), None), - }; + parse.take(args, &mut index)?; + index += 1; + } + if parse.document.is_empty() && !parse.extra.needs_restart() { + return Err("leleka reconfigure needs at least one setting; see `leleka --help`".into()); + } + parse.extra.settings = parse.document; + Ok((parse.rest, parse.extra)) +} + +/// What `split_reconfigure` has collected so far. +struct ReconfigureParse { + rest: Vec, + document: serde_json::Map, + extra: ReconfigureArgs, +} + +impl ReconfigureParse { + /// The argument at `index` (and its value, which moves `index` on): a settings flag is kept, anything else is + /// passed on. + fn take(&mut self, args: &[String], index: &mut usize) -> Result<(), String> { + let arg = &args[*index]; + let (name, inline) = split_inline(arg); if name == "--persist" { if inline.is_some() { return Err("--persist takes no value".into()); } - extra.persist = true; - index += 1; - continue; + self.extra.persist = true; + } else if name == "--gpu-budget-gib" || name == "--preset" { + let value = next_value(args, index, name, inline)?; + self.budget_or_preset(name, value)?; + } else if let Some((_, member)) = RECONFIGURE_FLAGS.iter().find(|(flag, _)| *flag == name) { + let value = next_value(args, index, name, inline)?; + self.setting(name, member, value)?; + } else { + self.rest.push(arg.clone()); } - if name == "--gpu-budget-gib" || name == "--preset" { - let value = match inline { - Some(value) => value, - None => { - index += 1; - args.get(index) - .ok_or_else(|| format!("{name} needs a value"))? - .clone() - } - }; - if name == "--preset" { - if extra - .preset - .replace(crate::resources::Preset::parse(&value)?) - .is_some() - { - return Err(format!("{name} given twice")); - } - } else { - let gib: u64 = value - .parse() - .map_err(|_| format!("{name} needs a whole number of GiB"))?; - if !(1..=1024).contains(&gib) { - return Err(format!("{name} must be 1..1024")); - } - if extra.gpu_budget_gib.replace(gib).is_some() { - return Err(format!("{name} given twice")); - } - } - index += 1; - continue; - } - if let Some((_, member)) = RECONFIGURE_FLAGS.iter().find(|(flag, _)| *flag == name) { - let value = match inline { - Some(value) => value, - None => { - index += 1; - args.get(index) - .ok_or_else(|| format!("{name} needs a value"))? - .clone() - } - }; - let json = match *member { - "prefix_cache_mib" | "prefix_cache_tail" => serde_json::Value::String(value), - "spec_min_p" => serde_json::Value::from( - value - .parse::() - .map_err(|_| format!("{name} needs a number"))?, - ), - _ => serde_json::Value::from( - value - .parse::() - .map_err(|_| format!("{name} needs a whole number"))?, - ), - }; - if document.insert((*member).to_owned(), json).is_some() { + Ok(()) + } + + fn budget_or_preset(&mut self, name: &str, value: String) -> Result<(), String> { + if name == "--preset" { + let preset = crate::resources::Preset::parse(&value)?; + if self.extra.preset.replace(preset).is_some() { return Err(format!("{name} given twice")); } - } else { - rest.push(arg.clone()); + return Ok(()); } - index += 1; + let gib: u64 = value + .parse() + .map_err(|_| format!("{name} needs a whole number of GiB"))?; + if !(1..=1024).contains(&gib) { + return Err(format!("{name} must be 1..1024")); + } + if self.extra.gpu_budget_gib.replace(gib).is_some() { + return Err(format!("{name} given twice")); + } + Ok(()) } - if document.is_empty() && !extra.needs_restart() { - return Err("leleka reconfigure needs at least one setting; see `leleka --help`".into()); + + fn setting(&mut self, name: &str, member: &str, value: String) -> Result<(), String> { + let json = match member { + "prefix_cache_mib" | "prefix_cache_tail" => serde_json::Value::String(value), + "spec_min_p" => serde_json::Value::from( + value + .parse::() + .map_err(|_| format!("{name} needs a number"))?, + ), + _ => serde_json::Value::from( + value + .parse::() + .map_err(|_| format!("{name} needs a whole number"))?, + ), + }; + if self.document.insert(member.to_owned(), json).is_some() { + return Err(format!("{name} given twice")); + } + Ok(()) } - extra.settings = document; - Ok((rest, extra)) } /// Take the flags of `table` out of `args`; the other arguments (they locate the service) are returned for `up_options`. @@ -103,21 +104,10 @@ pub(super) fn split_flags( let mut index = 0; while index < args.len() { let arg = &args[index]; - let (name, inline) = match arg.split_once('=') { - Some((name, value)) if name.starts_with("--") => (name, Some(value.to_owned())), - _ => (arg.as_str(), None), - }; + let (name, inline) = split_inline(arg); match table.iter().find(|(flag, _)| *flag == name) { Some((_, true)) => { - let value = match inline { - Some(value) => value, - None => { - index += 1; - args.get(index) - .ok_or_else(|| format!("{name} needs a value"))? - .clone() - } - }; + let value = next_value(args, &mut index, name, inline)?; if flags.insert(name.to_owned(), Some(value)).is_some() { return Err(format!("{name} given twice")); } @@ -135,20 +125,19 @@ pub(super) fn split_flags( Ok((rest, flags)) } +const LOGS_FLAGS: &[(&str, bool)] = &[ + ("--tail", true), + ("--since", true), + ("--level", true), + ("--component", true), + ("--source", true), + ("--request", true), + ("--follow", false), + ("-f", false), +]; + pub(super) fn logs_command(args: &[String], env: &Environment) -> Result { - let (rest, flags) = split_flags( - args, - &[ - ("--tail", true), - ("--since", true), - ("--level", true), - ("--component", true), - ("--source", true), - ("--request", true), - ("--follow", false), - ("-f", false), - ], - )?; + let (rest, flags) = split_flags(args, LOGS_FLAGS)?; let logs = crate::logview::LogsArgs { tail: flags .get("--tail") diff --git a/crates/deploy/src/cli/tests/flags.rs b/crates/deploy/src/cli/tests/flags.rs index 5fa084b2..3c839ca3 100644 --- a/crates/deploy/src/cli/tests/flags.rs +++ b/crates/deploy/src/cli/tests/flags.rs @@ -43,6 +43,10 @@ fn logs_and_report_take_their_own_flags_and_the_locating_ones() { assert!(parse_as(false, &["logs", "--tail", "x"]).is_err()); assert!(parse_as(false, &["logs", "-f", "--request", "abcdef"]).is_err()); assert!(parse_as(false, &["logs", "--bogus"]).is_err()); + check_report_flags(); +} + +fn check_report_flags() { let Ok(Command::Report(_, report)) = parse_as(false, &["report"]) else { panic!() }; @@ -140,6 +144,10 @@ fn flags_accept_both_forms_and_reject_mistakes() { (1, ModeChoice::Foreground, true, true, false) ); assert_eq!(options.ports.api, "127.0.0.1:9000"); + check_mistakes_are_rejected(); +} + +fn check_mistakes_are_rejected() { for bad in [ &["up", "--nope"][..], &["up", "--gpu"], diff --git a/crates/deploy/src/cli/tests/reconfigure_args.rs b/crates/deploy/src/cli/tests/reconfigure_args.rs index 02be77a0..8cb6ccec 100644 --- a/crates/deploy/src/cli/tests/reconfigure_args.rs +++ b/crates/deploy/src/cli/tests/reconfigure_args.rs @@ -77,7 +77,11 @@ fn reconfigure_takes_the_budget_the_preset_and_persist_out_of_the_up_flags() { assert_eq!(options.dirs.state, std::path::PathBuf::from("/s")); assert_eq!(options.gpu_budget_gib, None); assert_eq!(options.preset, crate::resources::Preset::Dedicated); - // the budget or the preset alone is a request; nothing at all is not + check_what_is_a_request_and_what_is_refused(); +} + +/// The budget or the preset alone is a request; nothing at all is not, and the mistakes are named. +fn check_what_is_a_request_and_what_is_refused() { assert!(matches!( parse_as(false, &["reconfigure", "--preset", "dedicated"]), Ok(Command::Reconfigure(..)) @@ -86,46 +90,29 @@ fn reconfigure_takes_the_budget_the_preset_and_persist_out_of_the_up_flags() { parse_as(false, &["reconfigure", "--gpu-budget-gib", "20"]), Ok(Command::Reconfigure(..)) )); - assert!( - parse_as(false, &["reconfigure", "--persist"]) - .unwrap_err() - .contains("at least one setting") + check_mistakes_are_named(); +} + +fn check_mistakes_are_named() { + let refused = |args: &[&str], needle: &str| { + assert!(parse_as(false, args).unwrap_err().contains(needle)); + }; + refused(&["reconfigure", "--persist"], "at least one setting"); + refused(&["reconfigure", "--gpu-budget-gib", "0"], "1..1024"); + refused(&["reconfigure", "--gpu-budget-gib", "many"], "whole number"); + refused(&["reconfigure", "--preset", "shared"], "unknown preset"); + refused( + &["reconfigure", "--persist=yes", "--cpu-workers", "2"], + "no value", ); - assert!( - parse_as(false, &["reconfigure", "--gpu-budget-gib", "0"]) - .unwrap_err() - .contains("1..1024") - ); - assert!( - parse_as(false, &["reconfigure", "--gpu-budget-gib", "many"]) - .unwrap_err() - .contains("whole number") - ); - assert!( - parse_as(false, &["reconfigure", "--preset", "shared"]) - .unwrap_err() - .contains("unknown preset") - ); - assert!( - parse_as( - false, - &["reconfigure", "--persist=yes", "--cpu-workers", "2"] - ) - .unwrap_err() - .contains("no value") - ); - assert!( - parse_as( - false, - &[ - "reconfigure", - "--gpu-budget-gib", - "20", - "--gpu-budget-gib", - "21" - ] - ) - .unwrap_err() - .contains("twice") + refused( + &[ + "reconfigure", + "--gpu-budget-gib", + "20", + "--gpu-budget-gib", + "21", + ], + "twice", ); } diff --git a/crates/deploy/src/config.rs b/crates/deploy/src/config.rs index 82bf96dc..7eee8932 100644 --- a/crates/deploy/src/config.rs +++ b/crates/deploy/src/config.rs @@ -176,14 +176,11 @@ pub enum KarArg { None, } +/// The environment variables the engine is started with. +type Env = BTreeMap; + impl RunConfig { - pub fn new( - dirs: &Dirs, - ports: Ports, - gpu: u32, - profile: Profile, - engine_env: BTreeMap, - ) -> Self { + pub fn new(dirs: &Dirs, ports: Ports, gpu: u32, profile: Profile, engine_env: Env) -> Self { RunConfig { schema_version: SCHEMA_VERSION, leleka_version: env!("CARGO_PKG_VERSION").to_owned(), diff --git a/crates/deploy/src/config/engine_launch.rs b/crates/deploy/src/config/engine_launch.rs index 6e6c3f11..077d61c1 100644 --- a/crates/deploy/src/config/engine_launch.rs +++ b/crates/deploy/src/config/engine_launch.rs @@ -7,8 +7,37 @@ impl RunConfig { /// operator-source tuples). `{FD}` stays literal for [`KarArg::Fd`]. pub fn engine_args(&self, kar: KarArg) -> Vec { let paths = self.paths(); + let mut args = self.fixed_engine_args(&paths); + args.extend(archive_engine_args(&paths, kar)); + args.extend([ + "--mtp-pack".into(), + paths.mtp_pack().display().to_string(), + "--mtp-staging".into(), + paths.mtp_staging().display().to_string(), + "--backend-mode".into(), + "original".into(), + "--expert-source".into(), + self.profile.expert_source.as_str().into(), + // The Original drafts over the MTP pack's draft vocabulary (draft_vocab.bin, 106k rows); without this the engine + // drafts over the full 248k-row head, about 0.2 ms more per draft step. + "--mtp-rt-dir".into(), + paths.mtp_pack().display().to_string(), + ]); + args.extend(self.optional_engine_args()); + args.extend(self.profile.memory.args()); + if self.verify_stamps { + args.extend([ + "--verify-stamps".into(), + paths.engine_stamps().display().to_string(), + ]); + } + args + } + + /// The seven fixed pairs. + fn fixed_engine_args(&self, paths: &Paths) -> Vec { let profile = &self.profile; - let mut args: Vec = vec![ + vec![ "--listen".into(), self.ports.engine.clone(), "--token-env".into(), @@ -23,35 +52,13 @@ impl RunConfig { profile.gpu_budget_bytes.to_string(), "--context-tokens".into(), profile.context_tokens.to_string(), - ]; - match kar { - KarArg::Fd => args.extend(["--kar-archive-fd".into(), "{FD}".into()]), - KarArg::File => args.extend([ - "--kar-archive-file".into(), - paths.kar().display().to_string(), - ]), - KarArg::None => {} - } - if kar != KarArg::None { - args.extend([ - "--kar-provenance".into(), - paths.kar_provenance().display().to_string(), - ]); - } - args.extend([ - "--mtp-pack".into(), - paths.mtp_pack().display().to_string(), - "--mtp-staging".into(), - paths.mtp_staging().display().to_string(), - "--backend-mode".into(), - "original".into(), - "--expert-source".into(), - profile.expert_source.as_str().into(), - // The Original drafts over the MTP pack's draft vocabulary (draft_vocab.bin, 106k rows); without this the engine - // drafts over the full 248k-row head, about 0.2 ms more per draft step. - "--mtp-rt-dir".into(), - paths.mtp_pack().display().to_string(), - ]); + ] + } + + /// The pairs that appear only when the profile sets them. + fn optional_engine_args(&self) -> Vec { + let profile = &self.profile; + let mut args = Vec::new(); if let Some(value) = profile.prefill_capacity { args.extend(["--original-prefill-capacity".into(), value.to_string()]); } @@ -67,13 +74,6 @@ impl RunConfig { if let Some(value) = profile.spec_min_p { args.extend(["--spec-min-p".into(), value.to_string()]); } - args.extend(profile.memory.args()); - if self.verify_stamps { - args.extend([ - "--verify-stamps".into(), - paths.engine_stamps().display().to_string(), - ]); - } args } @@ -129,3 +129,23 @@ impl RunConfig { env } } + +/// The archive arguments: the descriptor or the file, and the provenance file that goes with an archive. +fn archive_engine_args(paths: &Paths, kar: KarArg) -> Vec { + let mut args = Vec::new(); + match kar { + KarArg::Fd => args.extend(["--kar-archive-fd".into(), "{FD}".into()]), + KarArg::File => args.extend([ + "--kar-archive-file".into(), + paths.kar().display().to_string(), + ]), + KarArg::None => {} + } + if kar != KarArg::None { + args.extend([ + "--kar-provenance".into(), + paths.kar_provenance().display().to_string(), + ]); + } + args +} diff --git a/crates/deploy/src/doctor.rs b/crates/deploy/src/doctor.rs index 9815a1e6..5fce383c 100644 --- a/crates/deploy/src/doctor.rs +++ b/crates/deploy/src/doctor.rs @@ -24,15 +24,9 @@ impl Finding { /// What is wrong with the model volume `paths.dirs.assets`, one line per missing or wrong file. pub fn volume_missing(paths: &Paths) -> Vec { let mut missing = Vec::new(); - let size = |path: &Path| { - std::fs::metadata(path) - .ok() - .filter(|m| m.is_file()) - .map(|m| m.len()) - }; for (index, expected) in SHARD_BYTES.iter().enumerate() { let path = paths.shard(index); - match size(&path) { + match file_size(&path) { Some(len) if len == *expected => {} Some(len) => missing.push(format!( "{} has {len} bytes, expected {expected}", @@ -41,29 +35,12 @@ pub fn volume_missing(paths: &Paths) -> Vec { None => missing.push(format!("{} is missing", path.display())), } } - match size(&paths.kar()) { - Some(len) if len == ARCHIVE_BYTES => {} - Some(len) => missing.push(format!( - "{} has {len} bytes, expected {ARCHIVE_BYTES}", - paths.kar().display() - )), - None => { - let misplaced = paths.model_dir().join(crate::layout::KAR_NAME); - if misplaced.is_file() { - missing.push(format!( - "{} is inside model\\; it must be at the root of the volume", - misplaced.display() - )); - } else { - missing.push(format!("{} is missing", paths.kar().display())); - } - } - } - if size(&paths.kar_provenance()).is_none() { + missing.extend(archive_problem(paths)); + if file_size(&paths.kar_provenance()).is_none() { missing.push(format!("{} is missing", paths.kar_provenance().display())); } for name in MTP_FILES { - if size(&paths.mtp_pack().join(name)).is_none_or(|len| len == 0) { + if file_size(&paths.mtp_pack().join(name)).is_none_or(|len| len == 0) { missing.push(format!( "{} is missing", paths.mtp_pack().join(name).display() @@ -73,6 +50,36 @@ pub fn volume_missing(paths: &Paths) -> Vec { missing } +/// The size of a regular file. +fn file_size(path: &Path) -> Option { + std::fs::metadata(path) + .ok() + .filter(|m| m.is_file()) + .map(|m| m.len()) +} + +/// What is wrong with the archive file, if anything (an archive left inside `model\` is named as such). +fn archive_problem(paths: &Paths) -> Option { + match file_size(&paths.kar()) { + Some(len) if len == ARCHIVE_BYTES => None, + Some(len) => Some(format!( + "{} has {len} bytes, expected {ARCHIVE_BYTES}", + paths.kar().display() + )), + None => { + let misplaced = paths.model_dir().join(crate::layout::KAR_NAME); + if misplaced.is_file() { + Some(format!( + "{} is inside model\\; it must be at the root of the volume", + misplaced.display() + )) + } else { + Some(format!("{} is missing", paths.kar().display())) + } + } + } +} + /// The pinned expert profile is at `data/expert-profile.bin` (the engine runs without the ranked VRAM tier otherwise, much slower). pub fn expert_profile_present(paths: &Paths) -> bool { use crate::expert_profile::{FileState, PINNED_SHA256, file_state}; @@ -111,19 +118,34 @@ fn script(repo: &Option, name: &str) -> String { } pub fn advise(inputs: &Inputs) -> Vec { - let mut findings = Vec::new(); - findings.push(Finding { + vec![ + gpu_finding(inputs), + binaries_finding(inputs), + cublas_finding(inputs), + volume_finding(inputs), + wsl_finding(inputs), + ] +} + +fn gpu_finding(inputs: &Inputs) -> Finding { + Finding { what: "NVIDIA GPU and driver (nvidia-smi.exe)", missing: if inputs.gpu_found { vec![] } else { vec!["no GPU was listed by nvidia-smi.exe".into()] }, fix: (!inputs.gpu_found).then(|| "install the current NVIDIA Game Ready/Studio driver (>= 595), then rerun `leleka doctor`".to_owned()), - }); - findings.push(Finding { + } +} + +fn binaries_finding(inputs: &Inputs) -> Finding { + Finding { what: "native programs (five .exe files next to leleka.exe or in dist\\bin)", missing: inputs.native_binaries_missing.clone(), fix: (!inputs.native_binaries_missing.is_empty()) .then(|| script(&inputs.repo, "build-release.ps1")), - }); - findings.push(Finding { + } +} + +fn cublas_finding(inputs: &Inputs) -> Finding { + Finding { what: "CUDA 12 cuBLAS DLLs", missing: inputs .cublas_missing @@ -131,8 +153,11 @@ pub fn advise(inputs: &Inputs) -> Vec { .map(|s| (*s).to_owned()) .collect(), fix: (!inputs.cublas_missing.is_empty()).then(|| script(&inputs.repo, "fetch-cublas.ps1")), - }); - findings.push(Finding { + } +} + +fn volume_finding(inputs: &Inputs) -> Finding { + Finding { what: "model volume", missing: inputs.volume_missing.clone(), fix: (!inputs.volume_missing.is_empty()).then(|| { @@ -142,8 +167,11 @@ pub fn advise(inputs: &Inputs) -> Vec { inputs.assets.display() ) }), - }); - findings.push(Finding { + } +} + +fn wsl_finding(inputs: &Inputs) -> Finding { + Finding { what: "WSL2 and the Linux leleka (route A only)", missing: match (inputs.wsl_found, inputs.linux_leleka_found) { (false, _) => vec!["wsl.exe was not found".into()], @@ -157,8 +185,7 @@ pub fn advise(inputs: &Inputs) -> Vec { ), _ => None, }, - }); - findings + } } /// The one command to run next for the native route, or `None` when it is ready to start. diff --git a/crates/deploy/src/expert_profile/provisioning.rs b/crates/deploy/src/expert_profile/provisioning.rs index a8e86603..5cfe38f8 100644 --- a/crates/deploy/src/expert_profile/provisioning.rs +++ b/crates/deploy/src/expert_profile/provisioning.rs @@ -103,55 +103,87 @@ pub fn provision( let part = with_suffix(request.dest, ".part"); let _ = std::fs::remove_file(&part); if let Some(local) = request.local { - let size = std::fs::metadata(local) - .map_err(|e| format!("--expert-profile-file {}: {e}", local.display()))? - .len(); - if size > MAX_BYTES { - return Err(format!( - "--expert-profile-file {} has {size} bytes; the expert profile is {PINNED_BYTES}", - local.display() - )); - } - std::fs::copy(local, &part).map_err(|e| format!("cannot copy {}: {e}", local.display()))?; - let moved_aside = commit(&part, request.dest, request.expected) - .map_err(|e| format!("--expert-profile-file {}: {e}; only the pinned upstream table is accepted (a table of your own needs a profile with its own expert_profile_sha256 and a quality gate)", local.display()))?; - return Ok(Outcome::Installed { - origin: local.display().to_string(), - moved_aside, - }); + return install_local(request, local, &part); } let mut failures = Vec::new(); - if let Some(bytes) = request.embedded { - let result = std::fs::write(&part, bytes) - .map_err(|e| format!("cannot write {}: {e}", part.display())) - .and_then(|()| commit(&part, request.dest, request.expected)); - match result { - Ok(moved_aside) => { - return Ok(Outcome::Installed { - origin: EMBEDDED_ORIGIN.to_owned(), - moved_aside, - }); - } - Err(message) => { - let _ = std::fs::remove_file(&part); - failures.push(format!("{EMBEDDED_ORIGIN}: {message}")); - } - } + if let Some(outcome) = install_embedded(request, &part, &mut failures) { + return Ok(outcome); } if request.sources.is_empty() { + return Err(no_source_error(request, &failures)); + } + download_sources(request, fetch, &part, failures) +} + +/// `--expert-profile-file`: copy the file given by the operator, which must be the pinned table. +fn install_local(request: &Request, local: &Path, part: &Path) -> Result { + let size = std::fs::metadata(local) + .map_err(|e| format!("--expert-profile-file {}: {e}", local.display()))? + .len(); + if size > MAX_BYTES { return Err(format!( - "no download source is known for sha256 {}{}; copy the file to {} or pass --expert-profile-file PATH", - request.expected, - if failures.is_empty() { - String::new() - } else { - format!(" ({})", failures.join("; ")) - }, - request.dest.display() + "--expert-profile-file {} has {size} bytes; the expert profile is {PINNED_BYTES}", + local.display() )); } + std::fs::copy(local, part).map_err(|e| format!("cannot copy {}: {e}", local.display()))?; + let moved_aside = commit(part, request.dest, request.expected).map_err(|e| { + format!( + concat!( + "--expert-profile-file {}: {e}; only the pinned upstream table is accepted ", + "(a table of your own needs a profile with its own expert_profile_sha256 and a quality gate)" + ), + local.display(), + e = e + ) + })?; + Ok(Outcome::Installed { + origin: local.display().to_string(), + moved_aside, + }) +} + +/// The table embedded in this binary; `None` (with the reason in `failures`) when there is none or it does not install. +fn install_embedded(request: &Request, part: &Path, failures: &mut Vec) -> Option { + let bytes = request.embedded?; + let result = std::fs::write(part, bytes) + .map_err(|e| format!("cannot write {}: {e}", part.display())) + .and_then(|()| commit(part, request.dest, request.expected)); + match result { + Ok(moved_aside) => Some(Outcome::Installed { + origin: EMBEDDED_ORIGIN.to_owned(), + moved_aside, + }), + Err(message) => { + let _ = std::fs::remove_file(part); + failures.push(format!("{EMBEDDED_ORIGIN}: {message}")); + None + } + } +} + +fn no_source_error(request: &Request, failures: &[String]) -> String { + format!( + "no download source is known for sha256 {}{}; copy the file to {} or pass --expert-profile-file PATH", + request.expected, + if failures.is_empty() { + String::new() + } else { + format!(" ({})", failures.join("; ")) + }, + request.dest.display() + ) +} + +/// Try the sources in order; the first that downloads and verifies is installed. +fn download_sources( + request: &Request, + mut fetch: impl FnMut(&str, &Path) -> Result<(), String>, + part: &Path, + mut failures: Vec, +) -> Result { for url in request.sources { - let result = fetch(url, &part).and_then(|()| commit(&part, request.dest, request.expected)); + let result = fetch(url, part).and_then(|()| commit(part, request.dest, request.expected)); match result { Ok(moved_aside) => { return Ok(Outcome::Installed { @@ -160,7 +192,7 @@ pub fn provision( }); } Err(message) => { - let _ = std::fs::remove_file(&part); + let _ = std::fs::remove_file(part); failures.push(format!("{url}: {message}")); } } diff --git a/crates/deploy/src/expert_profile/tests/report.rs b/crates/deploy/src/expert_profile/tests/report.rs index af26a091..15302248 100644 --- a/crates/deploy/src/expert_profile/tests/report.rs +++ b/crates/deploy/src/expert_profile/tests/report.rs @@ -28,21 +28,25 @@ fn the_report_says_on_with_the_digest_or_off_with_the_reason() { "{}", report.line() ); + check_other_states(&dir, &path); +} + +fn check_other_states(dir: &Path, path: &Path) { // valid file but a configuration written without the switches - let report = tier_report(&config(&dir, true, false), &dir); + let report = tier_report(&config(dir, true, false), dir); assert!( !report.on && report.reason.contains("rerun `leleka up`"), "{report:?}" ); // explicit opt-out - let report = tier_report(&config(&dir, false, false), &dir); + let report = tier_report(&config(dir, false, false), dir); assert!( !report.on && report.opted_out && report.reason.contains("--no-expert-tier"), "{report:?}" ); // a replaced file - std::fs::write(&path, b"something else").unwrap(); - let report = tier_report(&config(&dir, true, true), &dir); + std::fs::write(path, b"something else").unwrap(); + let report = tier_report(&config(dir, true, true), dir); assert!( !report.on && report.reason.contains("not the pinned") && report.sha256.is_some(), "{report:?}" diff --git a/crates/deploy/src/expert_profile/tests/sources.rs b/crates/deploy/src/expert_profile/tests/sources.rs index 99b90120..3c7917e8 100644 --- a/crates/deploy/src/expert_profile/tests/sources.rs +++ b/crates/deploy/src/expert_profile/tests/sources.rs @@ -112,22 +112,7 @@ fn a_local_file_is_installed_offline_and_a_wrong_one_is_refused() { let mut never = |_: &str, _: &Path| -> Result<(), String> { panic!("offline: no download may be attempted") }; - let refused = provision( - &Request { - dest: &dest, - expected: &digest, - local: Some(&bad), - embedded: None, - sources: &["https://x.test/p"], - }, - &mut never, - ) - .unwrap_err(); - assert!( - refused.contains("only the pinned upstream table"), - "{refused}" - ); - assert!(!dest.exists()); + check_wrong_local_file_is_refused(&dest, &bad, &digest, &mut never); let outcome = provision( &Request { dest: &dest, @@ -147,19 +132,51 @@ fn a_local_file_is_installed_offline_and_a_wrong_one_is_refused() { } )); assert_eq!(std::fs::read(&dest).unwrap(), FIXTURE); + check_missing_local_file(&dir, &digest, &mut never); + let _ = std::fs::remove_dir_all(dir); +} + +fn check_wrong_local_file_is_refused( + dest: &Path, + bad: &Path, + digest: &str, + never: &mut impl FnMut(&str, &Path) -> Result<(), String>, +) { + let refused = provision( + &Request { + dest, + expected: digest, + local: Some(bad), + embedded: None, + sources: &["https://x.test/p"], + }, + never, + ) + .unwrap_err(); + assert!( + refused.contains("only the pinned upstream table"), + "{refused}" + ); + assert!(!dest.exists()); +} + +fn check_missing_local_file( + dir: &Path, + digest: &str, + never: &mut impl FnMut(&str, &Path) -> Result<(), String>, +) { let missing = provision( &Request { dest: &dir.join("other.bin"), - expected: &digest, + expected: digest, local: Some(&dir.join("nope.bin")), embedded: None, sources: &[], }, - &mut never, + never, ) .unwrap_err(); assert!(missing.contains("--expert-profile-file"), "{missing}"); - let _ = std::fs::remove_dir_all(dir); } #[test] diff --git a/crates/deploy/src/expert_profile/tier_report.rs b/crates/deploy/src/expert_profile/tier_report.rs index fecfe6c4..3e47d3c1 100644 --- a/crates/deploy/src/expert_profile/tier_report.rs +++ b/crates/deploy/src/expert_profile/tier_report.rs @@ -8,79 +8,90 @@ pub fn tier_report_with( shown: &str, state: impl FnOnce() -> FileState, ) -> TierReport { - let profile = &config.profile; - let expected = expected_digest(profile).to_owned(); - let off = |reason: String, opted_out: bool, path: Option, sha256: Option| { - TierReport { - on: false, - opted_out, - path, - sha256, - expected_sha256: Some(expected.clone()), - reason, - } - }; - if profile.expert_profile.is_none() { + let expected = expected_digest(&config.profile).to_owned(); + if config.profile.expert_profile.is_none() { return TierReport { expected_sha256: None, - ..off( - format!("profile {} names no expert profile", profile.name), - false, - None, - None, + ..tier_off( + &expected, + format!("profile {} names no expert profile", config.profile.name), + (false, None, None), ) }; } let shown = shown.to_owned(); if !config.expert_tier { - return off( + return tier_off( + &expected, "--no-expert-tier was given to `leleka up` (explicit opt-out)".into(), - true, - Some(shown), - None, + (true, Some(shown), None), ); } - match state() { - FileState::Absent => off( + report_for_state(config, shown, expected, state()) +} + +/// A report for a tier that is off. `found`: whether the operator opted out, the path shown and the digest found. +fn tier_off( + expected: &str, + reason: String, + found: (bool, Option, Option), +) -> TierReport { + let (opted_out, path, sha256) = found; + TierReport { + on: false, + opted_out, + path, + sha256, + expected_sha256: Some(expected.to_owned()), + reason, + } +} + +/// The report of a tier that is configured and not opted out, from the state of its table. +fn report_for_state( + config: &RunConfig, + shown: String, + expected: String, + state: FileState, +) -> TierReport { + match state { + FileState::Absent => tier_off( + &expected, format!( "{shown} is missing; run `leleka up` (it installs the pinned table) or pass --expert-profile-file PATH" ), - false, - Some(shown), - None, + (false, Some(shown), None), ), - FileState::WrongDigest { actual } => off( + FileState::WrongDigest { actual } => tier_off( + &expected, format!( "{shown} has sha256 {actual}, not the pinned {}; it is not used", short_digest(&expected) ), - false, - Some(shown), - Some(actual), + (false, Some(shown), Some(actual)), ), - FileState::Valid => { - if config.engine_env.contains_key(PROFILE_ENV) { - TierReport { - on: true, - opted_out: false, - path: Some(shown), - sha256: Some(expected.clone()), - expected_sha256: Some(expected), - reason: String::new(), - } - } else { - off( - "the file is valid but leleka.json was written without it; rerun `leleka up`" - .into(), - false, - Some(shown), - Some(expected.clone()), - ) - } - } + FileState::Valid => valid_table_report(config, shown, expected), } } +fn valid_table_report(config: &RunConfig, shown: String, expected: String) -> TierReport { + if config.engine_env.contains_key(PROFILE_ENV) { + return TierReport { + on: true, + opted_out: false, + path: Some(shown), + sha256: Some(expected.clone()), + expected_sha256: Some(expected), + reason: String::new(), + }; + } + tier_off( + &expected, + "the file is valid but leleka.json was written without it; rerun `leleka up`".into(), + (false, Some(shown), Some(expected.clone())), + ) +} + /// The engine environment for a start, and the tier report it was built from: the configured environment minus the /// expert-tier switches when the table is not valid. `up` only sets them for a verified file; this keeps the engine from /// reading a file that went missing or changed since, and the report is what the supervisor logs. diff --git a/crates/deploy/src/facts/linux.rs b/crates/deploy/src/facts/linux.rs index b1e37412..37eed115 100644 --- a/crates/deploy/src/facts/linux.rs +++ b/crates/deploy/src/facts/linux.rs @@ -58,6 +58,17 @@ pub fn probe(request: &ProbeRequest) -> Facts { facts.proc_fd = Path::new("/proc/self/fd").is_dir(); facts.memfd_ok = memfd_works(); + probe_nvidia_smi(&mut facts); + probe_libraries(&mut facts, request); + + probe_tools(&mut facts); + probe_dirs(&mut facts, request); + probe_ports(&mut facts, request); + probe_binaries(&mut facts, request); + facts +} + +fn probe_nvidia_smi(facts: &mut Facts) { let smi = which( "nvidia-smi", &["/usr/lib/wsl/lib", "/usr/bin", "/usr/local/bin"], @@ -68,44 +79,52 @@ pub fn probe(request: &ProbeRequest) -> Facts { } Some(smi) => { facts.nvidia_smi_found = true; - match Command::new(smi) - .args([ - "--query-gpu=index,name,driver_version,memory.total,memory.free,compute_cap", - "--format=csv,noheader,nounits", - ]) - .output() - { - Ok(output) if output.status.success() => { - facts.gpus = parse_nvidia_smi(&String::from_utf8_lossy(&output.stdout)); - } - Ok(output) => { - // compute_cap is unknown to old drivers: retry without it. - let retry = Command::new("nvidia-smi") - .args([ - "--query-gpu=index,name,driver_version,memory.total,memory.free", - "--format=csv,noheader,nounits", - ]) - .output(); - match retry { - Ok(second) if second.status.success() => { - facts.gpus = parse_nvidia_smi(&String::from_utf8_lossy(&second.stdout)); - } - _ => { - let text = String::from_utf8_lossy(&output.stderr); - facts.nvidia_smi_error = Some( - text.lines() - .next() - .unwrap_or("nvidia-smi failed") - .to_owned(), - ); - } - } - } - Err(error) => facts.nvidia_smi_error = Some(error.to_string()), - } + query_gpus(facts, smi); } } +} +fn query_gpus(facts: &mut Facts, smi: PathBuf) { + let output = Command::new(smi) + .args([ + "--query-gpu=index,name,driver_version,memory.total,memory.free,compute_cap", + "--format=csv,noheader,nounits", + ]) + .output(); + match output { + Ok(output) if output.status.success() => { + facts.gpus = parse_nvidia_smi(&String::from_utf8_lossy(&output.stdout)); + } + Ok(output) => retry_without_compute_cap(facts, &output), + Err(error) => facts.nvidia_smi_error = Some(error.to_string()), + } +} + +/// compute_cap is unknown to old drivers: retry without it. +fn retry_without_compute_cap(facts: &mut Facts, first: &std::process::Output) { + let retry = Command::new("nvidia-smi") + .args([ + "--query-gpu=index,name,driver_version,memory.total,memory.free", + "--format=csv,noheader,nounits", + ]) + .output(); + match retry { + Ok(second) if second.status.success() => { + facts.gpus = parse_nvidia_smi(&String::from_utf8_lossy(&second.stdout)); + } + _ => { + let text = String::from_utf8_lossy(&first.stderr); + facts.nvidia_smi_error = Some( + text.lines() + .next() + .unwrap_or("nvidia-smi failed") + .to_owned(), + ); + } + } +} + +fn probe_libraries(facts: &mut Facts, request: &ProbeRequest) { let ldconfig = Command::new("ldconfig") .arg("-p") .output() @@ -129,14 +148,9 @@ pub fn probe(request: &ProbeRequest) -> Facts { find_library(soname, &library_dirs, &ldconfig), ); } +} - for tool in ["curl", "wget", "tar", "xz", "systemctl", "ldd"] { - facts.tools.insert( - tool.to_owned(), - which(tool, &["/usr/sbin", "/sbin"]).is_some(), - ); - } - +fn probe_dirs(facts: &mut Facts, request: &ProbeRequest) { let mounts = read("/proc/mounts"); for (key, path) in &request.dirs { facts.dirs.insert( @@ -148,11 +162,26 @@ pub fn probe(request: &ProbeRequest) -> Facts { }, ); } +} + +fn probe_tools(facts: &mut Facts) { + for tool in ["curl", "wget", "tar", "xz", "systemctl", "ldd"] { + facts.tools.insert( + tool.to_owned(), + which(tool, &["/usr/sbin", "/sbin"]).is_some(), + ); + } +} + +fn probe_ports(facts: &mut Facts, request: &ProbeRequest) { for port in &request.ports { if TcpListener::bind(("127.0.0.1", *port)).is_err() { facts.busy_ports.push(*port); } } +} + +fn probe_binaries(facts: &mut Facts, request: &ProbeRequest) { if let Some(dir) = &request.binary_dir { for name in &request.binaries { facts @@ -160,7 +189,6 @@ pub fn probe(request: &ProbeRequest) -> Facts { .insert(name.clone(), is_executable(&dir.join(name))); } } - facts } fn is_executable(path: &Path) -> bool { diff --git a/crates/deploy/src/facts/windows.rs b/crates/deploy/src/facts/windows.rs index e8997190..3071d6cd 100644 --- a/crates/deploy/src/facts/windows.rs +++ b/crates/deploy/src/facts/windows.rs @@ -36,40 +36,56 @@ pub fn probe(request: &ProbeRequest) -> Facts { facts.cpu_cores = std::thread::available_parallelism().map_or(0, |n| n.get() as u32); facts.cpu_physical_cores = crate::winsys::physical_cores().unwrap_or(0); + probe_nvidia_smi(&mut facts); + probe_libraries(&mut facts, request); + + probe_dirs(&mut facts, request); + probe_ports(&mut facts, request); + probe_binaries(&mut facts, request); + facts +} + +fn probe_nvidia_smi(facts: &mut Facts) { match nvidia_smi() { None => { facts.nvidia_smi_error = Some("nvidia-smi.exe was not found in PATH or System32".into()) } Some(smi) => { facts.nvidia_smi_found = true; - match query( - &smi, - "index,name,driver_version,memory.total,memory.free,compute_cap", - ) { - Ok(output) if output.status.success() => { - facts.gpus = parse_nvidia_smi(&String::from_utf8_lossy(&output.stdout)); - } - Ok(output) => { - match query(&smi, "index,name,driver_version,memory.total,memory.free") { - Ok(second) if second.status.success() => { - facts.gpus = parse_nvidia_smi(&String::from_utf8_lossy(&second.stdout)); - } - _ => { - let text = String::from_utf8_lossy(&output.stderr); - facts.nvidia_smi_error = Some( - text.lines() - .next() - .unwrap_or("nvidia-smi failed") - .to_owned(), - ); - } - } - } - Err(error) => facts.nvidia_smi_error = Some(error.to_string()), - } + query_gpus(facts, &smi); } } +} +fn query_gpus(facts: &mut Facts, smi: &Path) { + let first = query( + smi, + "index,name,driver_version,memory.total,memory.free,compute_cap", + ); + match first { + Ok(output) if output.status.success() => { + facts.gpus = parse_nvidia_smi(&String::from_utf8_lossy(&output.stdout)); + } + Ok(output) => match query(smi, "index,name,driver_version,memory.total,memory.free") { + Ok(second) if second.status.success() => { + facts.gpus = parse_nvidia_smi(&String::from_utf8_lossy(&second.stdout)); + } + _ => { + let text = String::from_utf8_lossy(&output.stderr); + facts.nvidia_smi_error = Some( + text.lines() + .next() + .unwrap_or("nvidia-smi failed") + .to_owned(), + ); + } + }, + Err(error) => facts.nvidia_smi_error = Some(error.to_string()), + } +} + +/// The directories the CUDA libraries are looked for in, in order, and the DLLs found there. +fn probe_libraries(facts: &mut Facts, request: &ProbeRequest) { let mut library_dirs: Vec = request.extra_library_dirs.clone(); if let Some(binary_dir) = &request.binary_dir { library_dirs.push(binary_dir.clone()); @@ -96,7 +112,9 @@ pub fn probe(request: &ProbeRequest) -> Facts { .libs .insert(soname.to_owned(), find_in_dirs(dll, &library_dirs)); } +} +fn probe_dirs(facts: &mut Facts, request: &ProbeRequest) { for (key, path) in &request.dirs { facts.dirs.insert( key.clone(), @@ -107,11 +125,17 @@ pub fn probe(request: &ProbeRequest) -> Facts { }, ); } +} + +fn probe_ports(facts: &mut Facts, request: &ProbeRequest) { for port in &request.ports { if TcpListener::bind(("127.0.0.1", *port)).is_err() { facts.busy_ports.push(*port); } } +} + +fn probe_binaries(facts: &mut Facts, request: &ProbeRequest) { if let Some(dir) = &request.binary_dir { for name in &request.binaries { facts @@ -119,5 +143,4 @@ pub fn probe(request: &ProbeRequest) -> Facts { .insert(name.clone(), dir.join(name).is_file()); } } - facts } diff --git a/crates/deploy/src/http.rs b/crates/deploy/src/http.rs index bbf3ebea..2d4a768e 100644 --- a/crates/deploy/src/http.rs +++ b/crates/deploy/src/http.rs @@ -54,38 +54,12 @@ async fn request( let mut stream = TcpStream::connect(address) .await .map_err(|e| e.to_string())?; - let mut request = format!( - "{method} {path} HTTP/1.1\r\nHost: {address}\r\nConnection: close\r\nAccept: application/json\r\n" - ); - if let Some(token) = bearer { - request.push_str(&format!("Authorization: Bearer {token}\r\n")); - } - if let Some(body) = body { - request.push_str(&format!( - "Content-Type: application/json\r\nContent-Length: {}\r\n", - body.len() - )); - } - request.push_str("\r\n"); - if let Some(body) = body { - request.push_str(body); - } + let request = request_text(address, (method, path), bearer, body); stream .write_all(request.as_bytes()) .await .map_err(|e| e.to_string())?; - let mut raw = Vec::new(); - let mut chunk = [0u8; 4096]; - loop { - let count = stream.read(&mut chunk).await.map_err(|e| e.to_string())?; - if count == 0 { - break; - } - raw.extend_from_slice(&chunk[..count]); - if raw.len() > MAX_RESPONSE { - return Err("response exceeds 64 KiB".to_owned()); - } - } + let raw = read_limited(&mut stream).await?; parse_response(&raw) }; timeout(limit, exchange) @@ -93,6 +67,49 @@ async fn request( .map_err(|_| "request timed out".to_owned())? } +/// The request head (and the JSON body when there is one) as HTTP/1.1 text. +fn request_text( + address: SocketAddr, + (method, path): (&str, &str), + bearer: Option<&str>, + body: Option<&str>, +) -> String { + let mut request = format!( + "{method} {path} HTTP/1.1\r\nHost: {address}\r\nConnection: close\r\nAccept: application/json\r\n" + ); + if let Some(token) = bearer { + request.push_str(&format!("Authorization: Bearer {token}\r\n")); + } + if let Some(body) = body { + request.push_str(&format!( + "Content-Type: application/json\r\nContent-Length: {}\r\n", + body.len() + )); + } + request.push_str("\r\n"); + if let Some(body) = body { + request.push_str(body); + } + request +} + +/// Everything the peer sends until it closes, at most [`MAX_RESPONSE`] bytes. +async fn read_limited(stream: &mut TcpStream) -> Result, String> { + let mut raw = Vec::new(); + let mut chunk = [0u8; 4096]; + loop { + let count = stream.read(&mut chunk).await.map_err(|e| e.to_string())?; + if count == 0 { + break; + } + raw.extend_from_slice(&chunk[..count]); + if raw.len() > MAX_RESPONSE { + return Err("response exceeds 64 KiB".to_owned()); + } + } + Ok(raw) +} + pub fn parse_response(raw: &[u8]) -> Result { let text = String::from_utf8_lossy(raw); let (head, body) = text diff --git a/crates/deploy/src/logs.rs b/crates/deploy/src/logs.rs index 845eff8e..2dd4b762 100644 --- a/crates/deploy/src/logs.rs +++ b/crates/deploy/src/logs.rs @@ -77,29 +77,9 @@ pub fn rotate_if_needed(path: &Path, policy: Policy) -> io::Result { if len <= policy.limit { return Ok(false); } - // Shift the older generations (the oldest falls off the end). if policy.keep > 0 { - let _ = std::fs::remove_file(generation(path, policy.keep)); - for n in (1..policy.keep).rev() { - let from = generation(path, n); - if from.exists() { - std::fs::rename(&from, generation(path, n + 1))?; - } - } - // The newest `limit` bytes of the live file, snapped to the start of a line (at most `limit` bytes in memory). - let start = len - policy.limit; - let mut window = Vec::with_capacity(policy.limit as usize); - let mut live_read = live.try_clone()?; - live_read.seek(SeekFrom::Start(start))?; - live_read.take(policy.limit).read_to_end(&mut window)?; - let skip = if start > 0 { - window.iter().position(|&b| b == b'\n').map_or(0, |i| i + 1) - } else { - 0 - }; - let mut copy = private_create(&generation(path, 1))?; - copy.write_all(&window[skip..])?; - copy.flush()?; + shift_generations(path, policy.keep)?; + copy_newest(&live, path, len, policy.limit)?; } else { let _ = std::fs::remove_file(generation(path, 1)); } @@ -108,6 +88,36 @@ pub fn rotate_if_needed(path: &Path, policy: Policy) -> io::Result { Ok(true) } +/// Shift the older generations (the oldest falls off the end). +fn shift_generations(path: &Path, keep: usize) -> io::Result<()> { + let _ = std::fs::remove_file(generation(path, keep)); + for n in (1..keep).rev() { + let from = generation(path, n); + if from.exists() { + std::fs::rename(&from, generation(path, n + 1))?; + } + } + Ok(()) +} + +/// The newest `limit` bytes of the live file, snapped to the start of a line (at most `limit` bytes in memory), as +/// generation 1. +fn copy_newest(live: &File, path: &Path, len: u64, limit: u64) -> io::Result<()> { + let start = len - limit; + let mut window = Vec::with_capacity(limit as usize); + let mut live_read = live.try_clone()?; + live_read.seek(SeekFrom::Start(start))?; + live_read.take(limit).read_to_end(&mut window)?; + let skip = if start > 0 { + window.iter().position(|&b| b == b'\n').map_or(0, |i| i + 1) + } else { + 0 + }; + let mut copy = private_create(&generation(path, 1))?; + copy.write_all(&window[skip..])?; + copy.flush() +} + /// Apply the policy to every `*.log` in `dir`. Returns the paths that were rotated. pub fn enforce(dir: &Path, policy: Policy) -> Vec<(PathBuf, io::Result)> { let Ok(entries) = std::fs::read_dir(dir) else { diff --git a/crates/deploy/src/logview/collection.rs b/crates/deploy/src/logview/collection.rs index 17cf4fa1..fe8f02e2 100644 --- a/crates/deploy/src/logview/collection.rs +++ b/crates/deploy/src/logview/collection.rs @@ -9,36 +9,45 @@ pub fn collect(dir: &Path, filter: &Filter) -> Vec { if filter.source.as_deref().is_some_and(|s| s != source) { continue; } - let mut kept: VecDeque = VecDeque::new(); - // a time-less line takes the time of the line before it, so that it sorts next to its neighbours - let mut last_ts: Option = None; - for path in generations(dir, &source) { - let limit = if filter.request.is_some() { - None - } else { - Some(TAIL_SCAN_BYTES) - }; - let _ = for_each_line(&path, limit, |line| { - let mut entry = parse_line(line, &source); - match entry.ts_ms { - Some(ts) => last_ts = Some(ts), - None => entry.ts_ms = last_ts, - } - if filter.matches(&entry) { - if kept.len() == filter.tail.max(1) { - kept.pop_front(); - } - kept.push_back(entry); - } - }); - } - all.extend(kept); + all.extend(kept_entries(dir, filter, &source)); } all.sort_by_key(|entry| entry.ts_ms.unwrap_or(0)); let skip = all.len().saturating_sub(filter.tail.max(1)); all.split_off(skip) } +/// The newest `filter.tail` entries of one source that pass the filter, over all its generations, oldest first. +fn kept_entries(dir: &Path, filter: &Filter, source: &str) -> VecDeque { + let mut kept: VecDeque = VecDeque::new(); + // a time-less line takes the time of the line before it, so that it sorts next to its neighbours + let mut last_ts: Option = None; + for path in generations(dir, source) { + let limit = if filter.request.is_some() { + None + } else { + Some(TAIL_SCAN_BYTES) + }; + let _ = for_each_line(&path, limit, |line| { + let mut entry = parse_line(line, source); + match entry.ts_ms { + Some(ts) => last_ts = Some(ts), + None => entry.ts_ms = last_ts, + } + if filter.matches(&entry) { + keep_newest(&mut kept, entry, filter.tail); + } + }); + } + kept +} + +fn keep_newest(kept: &mut VecDeque, entry: Entry, tail: usize) { + if kept.len() == tail.max(1) { + kept.pop_front(); + } + kept.push_back(entry); +} + pub(super) fn merge_fields(base: &mut Map, engine: &Map) { for (key, value) in engine { if key == "rid" { @@ -86,12 +95,7 @@ pub fn recent_requests(dir: &Path, last: usize) -> Vec { for source in ["requests", "api", "engine"] { for path in generations(dir, source) { let _ = for_each_line(&path, Some(RECORDS_SCAN_BYTES), |line| { - if line.contains("\"ev\":\"request\"") { - let entry = parse_line(line, source); - if entry.ev == "request" { - entries.push(entry); - } - } + push_request_entry(&mut entries, line, source); }); } } @@ -101,6 +105,15 @@ pub fn recent_requests(dir: &Path, last: usize) -> Vec { records.split_off(skip) } +fn push_request_entry(entries: &mut Vec, line: &str, source: &str) { + if line.contains("\"ev\":\"request\"") { + let entry = parse_line(line, source); + if entry.ev == "request" { + entries.push(entry); + } + } +} + pub(super) fn percentile(sorted: &[f64], p: f64) -> Option { if sorted.is_empty() { return None; @@ -118,18 +131,31 @@ pub(super) fn number_list(records: &[Value], key: &str) -> Vec { values } -/// Counts, percentiles and the error mix of a set of request records. -pub fn summarize(records: &[Value]) -> Value { - let mut outcomes: Map = Map::new(); - let mut errors: Map = Map::new(); - let (mut restarts, mut prompt, mut cached) = (0u64, 0u64, 0u64); +/// What `summarize` counts over the request records. +struct Tally { + outcomes: Map, + errors: Map, + restarts: u64, + prompt: u64, + cached: u64, +} + +fn bump(map: &mut Map, key: &str) { + let n = map.get(key).and_then(Value::as_u64).unwrap_or(0); + map.insert(key.to_owned(), json!(n + 1)); +} + +fn tally(records: &[Value]) -> Tally { + let mut tally = Tally { + outcomes: Map::new(), + errors: Map::new(), + restarts: 0, + prompt: 0, + cached: 0, + }; for r in records { - let bump = |map: &mut Map, key: &str| { - let n = map.get(key).and_then(Value::as_u64).unwrap_or(0); - map.insert(key.to_owned(), json!(n + 1)); - }; bump( - &mut outcomes, + &mut tally.outcomes, r.get("fin").and_then(Value::as_str).unwrap_or("?"), ); if let Some(class) = r @@ -137,12 +163,24 @@ pub fn summarize(records: &[Value]) -> Value { .and_then(Value::as_str) .filter(|c| *c != "none") { - bump(&mut errors, class); + bump(&mut tally.errors, class); } - restarts += u64::from(r.get("restart").and_then(Value::as_bool).unwrap_or(false)); - prompt += r.get("ptok").and_then(Value::as_u64).unwrap_or(0); - cached += r.get("ctok").and_then(Value::as_u64).unwrap_or(0); + tally.restarts += u64::from(r.get("restart").and_then(Value::as_bool).unwrap_or(false)); + tally.prompt += r.get("ptok").and_then(Value::as_u64).unwrap_or(0); + tally.cached += r.get("ctok").and_then(Value::as_u64).unwrap_or(0); } + tally +} + +/// Counts, percentiles and the error mix of a set of request records. +pub fn summarize(records: &[Value]) -> Value { + let Tally { + outcomes, + errors, + restarts, + prompt, + cached, + } = tally(records); let stat = |key: &str| { let values = number_list(records, key); json!({"n": values.len(), "p50": percentile(&values, 0.5), "p95": percentile(&values, 0.95), "max": values.last()}) @@ -177,11 +215,11 @@ pub fn recent_requests_line(dir: &Path, now: u64) -> Option { }) .cloned() .collect(); - let last_ts = records - .last() - .and_then(|r| r.get("ts").and_then(Value::as_str)) - .and_then(parse_utc_ms); if recent.is_empty() { + let last_ts = records + .last() + .and_then(|r| r.get("ts").and_then(Value::as_str)) + .and_then(parse_utc_ms); return last_ts.map(|t| { format!( "requests: none in the last 15 min (the last one {} ago)", @@ -189,7 +227,12 @@ pub fn recent_requests_line(dir: &Path, now: u64) -> Option { ) }); } - let s = summarize(&recent); + Some(describe_recent(&recent)) +} + +/// The line about the requests of the last quarter hour: how many failed, the latencies, the cache hits. +fn describe_recent(recent: &[Value]) -> String { + let s = summarize(recent); let failed = recent .iter() .filter(|r| { @@ -200,7 +243,7 @@ pub fn recent_requests_line(dir: &Path, now: u64) -> Option { }) .count(); let p = |group: &str, which: &str| s[group][which].as_f64(); - Some(format!( + format!( "requests: {} in the last 15 min ({} failed), time to first token p50 {} / p95 {} ms, decode p50 {} tok/s, prefix cache hit {}", recent.len(), failed, @@ -210,7 +253,7 @@ pub fn recent_requests_line(dir: &Path, now: u64) -> Option { s["cache_hit_ratio"] .as_f64() .map_or("?".into(), |v| format!("{:.0}%", v * 100.0)), - )) + ) } /// `--since` is a duration (`15m`, `2h`, `1d`) back from now or a UTC time (`2026-11-02T10:00:00Z`). diff --git a/crates/deploy/src/logview/entries.rs b/crates/deploy/src/logview/entries.rs index 8abfecf9..5cda44d2 100644 --- a/crates/deploy/src/logview/entries.rs +++ b/crates/deploy/src/logview/entries.rs @@ -26,45 +26,11 @@ pub(super) fn legacy_level(raw: &str) -> Level { /// supervisor's older form; anything else is free text of `source`. pub fn parse_line(raw: &str, source: &str) -> Entry { let raw = raw.trim_end_matches(['\r', '\n']); - if raw.starts_with('{') - && let Ok(Value::Object(mut object)) = serde_json::from_str::(raw) - { - let take = |object: &mut Map, key: &str| { - object - .remove(key) - .and_then(|v| v.as_str().map(str::to_owned)) - }; - let ts_ms = take(&mut object, "ts").and_then(|t| parse_utc_ms(&t)); - let level = take(&mut object, "lvl") - .and_then(|l| Level::parse(&l)) - .unwrap_or(Level::Info); - let comp = take(&mut object, "comp").unwrap_or_else(|| source.to_owned()); - let ev = take(&mut object, "ev").unwrap_or_else(|| "msg".to_owned()); - return Entry { - ts_ms, - level, - comp, - ev, - fields: object, - raw: raw.to_owned(), - source: source.to_owned(), - }; + if let Some(entry) = parse_structured(raw, source) { + return entry; } - if let Some((stamp, rest)) = raw.split_once(' ') - && let Some(ts_ms) = parse_utc_ms(stamp) - { - let text = rest.strip_prefix("leleka: ").unwrap_or(rest); - let mut fields = Map::new(); - fields.insert("msg".into(), Value::String(text.to_owned())); - return Entry { - ts_ms: Some(ts_ms), - level: legacy_level(text), - comp: source.to_owned(), - ev: "msg".into(), - fields, - raw: raw.to_owned(), - source: source.to_owned(), - }; + if let Some(entry) = parse_supervisor_line(raw, source) { + return entry; } let mut fields = Map::new(); fields.insert("msg".into(), Value::String(raw.to_owned())); @@ -79,6 +45,54 @@ pub fn parse_line(raw: &str, source: &str) -> Entry { } } +/// A JSON object line with `ts`, `lvl`, `comp` and `ev`; everything else in it stays a field. +fn parse_structured(raw: &str, source: &str) -> Option { + if !raw.starts_with('{') { + return None; + } + let Ok(Value::Object(mut object)) = serde_json::from_str::(raw) else { + return None; + }; + let take = |object: &mut Map, key: &str| { + object + .remove(key) + .and_then(|v| v.as_str().map(str::to_owned)) + }; + let ts_ms = take(&mut object, "ts").and_then(|t| parse_utc_ms(&t)); + let level = take(&mut object, "lvl") + .and_then(|l| Level::parse(&l)) + .unwrap_or(Level::Info); + let comp = take(&mut object, "comp").unwrap_or_else(|| source.to_owned()); + let ev = take(&mut object, "ev").unwrap_or_else(|| "msg".to_owned()); + Some(Entry { + ts_ms, + level, + comp, + ev, + fields: object, + raw: raw.to_owned(), + source: source.to_owned(), + }) +} + +/// The supervisor's older form: `YYYY-MM-DDTHH:MM:SSZ leleka: text`. +fn parse_supervisor_line(raw: &str, source: &str) -> Option { + let (stamp, rest) = raw.split_once(' ')?; + let ts_ms = parse_utc_ms(stamp)?; + let text = rest.strip_prefix("leleka: ").unwrap_or(rest); + let mut fields = Map::new(); + fields.insert("msg".into(), Value::String(text.to_owned())); + Some(Entry { + ts_ms: Some(ts_ms), + level: legacy_level(text), + comp: source.to_owned(), + ev: "msg".into(), + fields, + raw: raw.to_owned(), + source: source.to_owned(), + }) +} + /// `ts LEVEL comp ev key=value ...` for a person. pub fn render_entry(entry: &Entry) -> String { let stamp = entry @@ -156,13 +170,7 @@ pub fn for_each_line( ) -> std::io::Result<()> { let mut file = std::fs::File::open(path)?; let len = file.metadata()?.len(); - let mut skip_first = false; - if let Some(limit) = limit - && len > limit - { - file.seek(SeekFrom::Start(len - limit))?; - skip_first = true; - } + let mut skip_first = seek_to_tail(&mut file, len, limit)?; let mut reader = std::io::BufReader::with_capacity(1 << 16, file); let mut buffer = Vec::new(); loop { @@ -183,6 +191,17 @@ pub fn for_each_line( Ok(()) } +/// Move to the last `limit` bytes of a longer file; true when that cut into a line (the first one is partial). +fn seek_to_tail(file: &mut std::fs::File, len: u64, limit: Option) -> std::io::Result { + if let Some(limit) = limit + && len > limit + { + file.seek(SeekFrom::Start(len - limit))?; + return Ok(true); + } + Ok(false) +} + impl Default for Filter { fn default() -> Self { Filter { diff --git a/crates/deploy/src/logview/logs_command.rs b/crates/deploy/src/logview/logs_command.rs index a8bb052f..01de3a0a 100644 --- a/crates/deploy/src/logview/logs_command.rs +++ b/crates/deploy/src/logview/logs_command.rs @@ -49,50 +49,14 @@ pub(super) fn print_entries(entries: &[Entry], raw: bool) { } pub fn run_logs(opts: &UpOptions, args: &LogsArgs) -> i32 { - let dir = opts.dirs.paths().logs(); let now = now_ms(); - let filter = match filter_from(args, now) { - Ok(filter) => filter, - Err(message) => { - eprintln!("leleka: {message}"); - return 2; - } + let (dir, filter) = match log_directory_and_filter(opts, args, now) { + Ok(found) => found, + Err(code) => return code, }; - if !dir.is_dir() { - eprintln!( - "leleka: no log directory {} (the service has not run with this --state-dir)", - dir.display() - ); - return 1; - } let entries = collect(&dir, &filter); if args.request.is_some() { - let joined = join_requests(&entries); - print_entries(&entries, opts.json); - match joined.as_slice() { - [] if entries.is_empty() => { - eprintln!( - "leleka: no line mentions that request id in the retained logs (rotation keeps the newest {} MiB per file)", - crate::logs::DEFAULT_LIMIT_BYTES >> 20 - ); - return 1; - } - [] => {} - records => { - if !opts.json { - for record in records { - println!( - "-- the request as one record (API figures, engine figures prefixed eng_):" - ); - println!( - "{}", - serde_json::to_string_pretty(record).unwrap_or_default() - ); - } - } - } - } - return 0; + return show_request(&entries, opts.json); } print_entries(&entries, opts.json); if entries.is_empty() && !args.follow { @@ -109,6 +73,62 @@ pub fn run_logs(opts: &UpOptions, args: &LogsArgs) -> i32 { 0 } +/// The log directory (it must exist) and the filter of the flags, or the exit code of the refusal. +fn log_directory_and_filter( + opts: &UpOptions, + args: &LogsArgs, + now: u64, +) -> Result<(PathBuf, Filter), i32> { + let dir = opts.dirs.paths().logs(); + let filter = filter_from(args, now).map_err(|message| { + eprintln!("leleka: {message}"); + 2 + })?; + if !dir.is_dir() { + eprintln!( + "leleka: no log directory {} (the service has not run with this --state-dir)", + dir.display() + ); + return Err(1); + } + Ok((dir, filter)) +} + +/// The lines that mention a request, and the request as one record (the API and the engine figures joined). +fn show_request(entries: &[Entry], json: bool) -> i32 { + let joined = join_requests(entries); + print_entries(entries, json); + match joined.as_slice() { + [] if entries.is_empty() => { + eprintln!( + concat!( + "leleka: no line mentions that request id in the retained logs ", + "(rotation keeps the newest {} MiB per file)" + ), + crate::logs::DEFAULT_LIMIT_BYTES >> 20 + ); + return 1; + } + [] => {} + records => { + if !json { + print_joined_records(records); + } + } + } + 0 +} + +fn print_joined_records(records: &[Value]) { + for record in records { + println!("-- the request as one record (API figures, engine figures prefixed eng_):"); + println!( + "{}", + serde_json::to_string_pretty(record).unwrap_or_default() + ); + } +} + /// `--follow`: poll the live files once a second and print what was appended (until interrupted). pub(super) fn follow(dir: &Path, filter: &Filter, raw: bool, mut after_ms: u64) -> i32 { let mut offsets: std::collections::HashMap = std::collections::HashMap::new(); @@ -122,43 +142,7 @@ pub(super) fn follow(dir: &Path, filter: &Filter, raw: bool, mut after_ms: u64) } loop { std::thread::sleep(std::time::Duration::from_secs(1)); - let mut fresh: Vec = Vec::new(); - for source in sources_in(dir) { - if filter.source.as_deref().is_some_and(|s| s != source) { - continue; - } - let Some(path) = generations(dir, &source).pop() else { - continue; - }; - let len = std::fs::metadata(&path).map_or(0, |m| m.len()); - let offset = offsets.entry(path.clone()).or_insert(0); - if len < *offset { - *offset = 0; // rotated (copy-truncated): start again - } - if len == *offset { - continue; - } - if let Ok(mut file) = std::fs::File::open(&path) - && file.seek(SeekFrom::Start(*offset)).is_ok() - { - let mut text = String::new(); - let mut limited = (&mut file).take(len - *offset); - if limited.read_to_string(&mut text).is_ok() { - // only whole lines; a partial last line is read again next time - let whole = text.rfind('\n').map_or(0, |i| i + 1); - *offset += whole as u64; - for line in text[..whole].lines().filter(|l| !l.is_empty()) { - let entry = parse_line(line, &source); - if filter.matches(&Entry { - ts_ms: entry.ts_ms.or(Some(after_ms)), - ..entry.clone() - }) { - fresh.push(entry); - } - } - } - } - } + let mut fresh = appended_entries(dir, filter, &mut offsets, after_ms); fresh.sort_by_key(|e| e.ts_ms.unwrap_or(0)); if let Some(ts) = fresh.iter().filter_map(|e| e.ts_ms).max() { after_ms = after_ms.max(ts); @@ -168,6 +152,65 @@ pub(super) fn follow(dir: &Path, filter: &Filter, raw: bool, mut after_ms: u64) } } +/// The entries that the live files gained since `offsets`, which move on. +fn appended_entries( + dir: &Path, + filter: &Filter, + offsets: &mut std::collections::HashMap, + after_ms: u64, +) -> Vec { + let mut fresh: Vec = Vec::new(); + for source in sources_in(dir) { + if filter.source.as_deref().is_some_and(|s| s != source) { + continue; + } + let Some(path) = generations(dir, &source).pop() else { + continue; + }; + let len = std::fs::metadata(&path).map_or(0, |m| m.len()); + let offset = offsets.entry(path.clone()).or_insert(0); + if len < *offset { + *offset = 0; // rotated (copy-truncated): start again + } + if len == *offset { + continue; + } + if let Some(text) = read_appended(&path, offset, len) { + fresh.extend(matching_entries(&text, &source, filter, after_ms)); + } + } + fresh +} + +/// The whole lines between `offset` and `len`; `offset` moves past them. A partial last line is read again next time. +fn read_appended(path: &Path, offset: &mut u64, len: u64) -> Option { + let mut file = std::fs::File::open(path).ok()?; + file.seek(SeekFrom::Start(*offset)).ok()?; + let mut text = String::new(); + (&mut file) + .take(len - *offset) + .read_to_string(&mut text) + .ok()?; + let whole = text.rfind('\n').map_or(0, |i| i + 1); + *offset += whole as u64; + text.truncate(whole); + Some(text) +} + +fn matching_entries(text: &str, source: &str, filter: &Filter, after_ms: u64) -> Vec { + let mut found = Vec::new(); + for line in text.lines().filter(|l| !l.is_empty()) { + let entry = parse_line(line, source); + if filter.matches(&Entry { + ts_ms: entry.ts_ms.or(Some(after_ms)), + ..entry.clone() + }) { + found.push(entry); + } + } + found +} + impl Default for ReportArgs { fn default() -> Self { ReportArgs { @@ -206,20 +249,28 @@ pub fn sanitize(value: &mut Value, home: Option<&str>) { } } +/// One warning of the logs as it goes into the report: the fields and a clipped text. +fn warning_record(e: &Entry) -> Value { + let mut v = json!({"ts": e.ts_ms.map(format_utc_ms), "lvl": e.level.as_str(), "comp": e.comp, "ev": e.ev}); + let text = e + .fields + .get("msg") + .and_then(Value::as_str) + .map(str::to_owned) + .unwrap_or_else(|| { + // a structured event: its scalar fields, no free text beyond the engine's own reason strings + e.fields + .iter() + .map(|(k, v)| format!("{k}={v}")) + .collect::>() + .join(" ") + }); + v["text"] = Value::String(redact::clip(&text, 300).to_owned()); + v +} + pub fn build_report(inputs: &ReportInputs, home: Option<&str>) -> Value { - let warnings: Vec = inputs - .warnings - .iter() - .map(|e| { - let mut v = json!({"ts": e.ts_ms.map(format_utc_ms), "lvl": e.level.as_str(), "comp": e.comp, "ev": e.ev}); - let text = e.fields.get("msg").and_then(Value::as_str).map(str::to_owned).unwrap_or_else(|| { - // a structured event: its scalar fields, no free text beyond the engine's own reason strings - e.fields.iter().map(|(k, v)| format!("{k}={v}")).collect::>().join(" ") - }); - v["text"] = Value::String(redact::clip(&text, 300).to_owned()); - v - }) - .collect(); + let warnings: Vec = inputs.warnings.iter().map(warning_record).collect(); let mut report = json!({ "report_version": 1, "created_utc": format_utc_ms(inputs.now_ms), diff --git a/crates/deploy/src/logview/report.rs b/crates/deploy/src/logview/report.rs index 829825de..7281fe67 100644 --- a/crates/deploy/src/logview/report.rs +++ b/crates/deploy/src/logview/report.rs @@ -63,37 +63,15 @@ pub fn gather_report(opts: &UpOptions, last: usize) -> (ReportInputs, Option(&t).ok()) .map(|s| service_summary(&s, now / 1000)); let logs_dir = paths.logs(); - let warnings = collect( - &logs_dir, - &Filter { - min_level: Level::Warn, - tail: 50, - ..Filter::default() - }, - ); - let mut log_files = Vec::new(); - if let Ok(read) = std::fs::read_dir(&logs_dir) { - for item in read.flatten() { - if let Ok(meta) = item.metadata() - && meta.is_file() - { - log_files.push((item.file_name().to_string_lossy().into_owned(), meta.len())); - } - } - } - log_files.sort(); - let home = std::env::var("HOME") - .or_else(|_| std::env::var("USERPROFILE")) - .ok(); + let warnings = recent_warnings(&logs_dir); + let log_files = list_log_files(&logs_dir); + let home = home_directory(); ( ReportInputs { now_ms: now, @@ -110,6 +88,46 @@ pub fn gather_report(opts: &UpOptions, last: usize) -> (ReportInputs, Option Value { + serde_json::to_value(crate::expert_profile::tier_report(c, &c.dirs().assets)) + .unwrap_or(Value::Null) +} + +/// The home directory, which the report replaces by `~`. +fn home_directory() -> Option { + std::env::var("HOME") + .or_else(|_| std::env::var("USERPROFILE")) + .ok() +} + +/// The newest 50 warning and error entries of the logs. +fn recent_warnings(logs_dir: &Path) -> Vec { + collect( + logs_dir, + &Filter { + min_level: Level::Warn, + tail: 50, + ..Filter::default() + }, + ) +} + +/// The names and sizes of the files in the log directory, sorted. +fn list_log_files(logs_dir: &Path) -> Vec<(String, u64)> { + let mut log_files = Vec::new(); + if let Ok(read) = std::fs::read_dir(logs_dir) { + for item in read.flatten() { + if let Ok(meta) = item.metadata() + && meta.is_file() + { + log_files.push((item.file_name().to_string_lossy().into_owned(), meta.len())); + } + } + } + log_files.sort(); + log_files +} + pub fn run_report(opts: &UpOptions, args: &ReportArgs) -> i32 { let paths = opts.dirs.paths(); let (inputs, home) = gather_report(opts, args.last); @@ -119,7 +137,28 @@ pub fn run_report(opts: &UpOptions, args: &ReportArgs) -> i32 { .replace([':', '.'], "") .replace("T", "-") .replace('Z', ""); - let destination = match args.out.as_deref() { + let destination = report_destination(args, &paths, &stamp); + if !args.yes { + print_preview(args, &inputs, &text, destination.as_deref()); + return 3; + } + match destination { + None => { + print!("{text}"); + 0 + } + Some(path) => write_and_say(&path, &text), + } +} + +/// Where the report goes: `-` is standard output, a path is a file, and the default is a stamped file in the state +/// directory. +fn report_destination( + args: &ReportArgs, + paths: &crate::layout::Paths, + stamp: &str, +) -> Option { + match args.out.as_deref() { Some("-") => None, Some(path) => Some(PathBuf::from(path)), None => Some( @@ -129,64 +168,69 @@ pub fn run_report(opts: &UpOptions, args: &ReportArgs) -> i32 { .join("reports") .join(format!("leleka-report-{stamp}.json")), ), - }; - if !args.yes { - println!("leleka report: nothing has been written or sent. A report would contain:"); - println!( - " build {} lines (version, commit, Strata pin, target)", - inputs.version.lines().count() - ); - println!( - " install profile, preset, model digest, expert tier ON/OFF with the table's digest" - ); - println!(" host OS, CPU cores, RAM, GPU names and VRAM"); - println!( - " service phase, uptime, engine restarts and the last restart's reason, health" - ); - println!( - " requests statistics and the last {} request records ({} found): ids, token counts, timings, outcome", - args.last, - inputs.recent.len() - ); - println!( - " warnings {} recent warning and error lines of the logs (secrets removed, text clipped)", - inputs.warnings.len() - ); - println!( - " never prompts, model output, tool arguments, the API key, tokens, host name" - ); - println!(" size {} bytes", text.len()); - match &destination { - Some(path) => println!(" would write {}", path.display()), - None => println!(" would write standard output"), - } - println!( - "The file stays on this machine; you attach it to your feedback yourself. Nothing is ever uploaded by Leleka." - ); - println!( - "Run `leleka report --yes` to write it (add --out FILE to choose where, --last N for more request records)." - ); - return 3; } +} + +/// What a report would contain, without writing anything (the answer to a `leleka report` without `--yes`). +fn print_preview(args: &ReportArgs, inputs: &ReportInputs, text: &str, destination: Option<&Path>) { + println!("leleka report: nothing has been written or sent. A report would contain:"); + println!( + " build {} lines (version, commit, Strata pin, target)", + inputs.version.lines().count() + ); + println!( + " install profile, preset, model digest, expert tier ON/OFF with the table's digest" + ); + println!(" host OS, CPU cores, RAM, GPU names and VRAM"); + println!( + " service phase, uptime, engine restarts and the last restart's reason, health" + ); + print_record_counts(args, inputs); + println!( + " never prompts, model output, tool arguments, the API key, tokens, host name" + ); + println!(" size {} bytes", text.len()); match destination { - None => { - print!("{text}"); + Some(path) => println!(" would write {}", path.display()), + None => println!(" would write standard output"), + } + println!( + "The file stays on this machine; you attach it to your feedback yourself. Nothing is ever uploaded by Leleka." + ); + println!( + "Run `leleka report --yes` to write it (add --out FILE to choose where, --last N for more request records)." + ); +} + +fn print_record_counts(args: &ReportArgs, inputs: &ReportInputs) { + println!( + " requests statistics and the last {} request records ({} found): ids, token counts, timings, outcome", + args.last, + inputs.recent.len() + ); + println!( + " warnings {} recent warning and error lines of the logs (secrets removed, text clipped)", + inputs.warnings.len() + ); +} + +fn write_and_say(path: &Path, text: &str) -> i32 { + match write_report(path, text) { + Ok(()) => { + println!( + concat!( + "leleka report: wrote {} ({} bytes). Attach that file to your ", + "feedback; review it first if you like, it is plain JSON." + ), + path.display(), + text.len() + ); 0 } - Some(path) => match write_report(&path, &text) { - Ok(()) => { - println!( - "leleka report: wrote {} ({} bytes). Attach that file to your feedback; review it first if you like, it is plain JSON.", - path.display(), - text.len() - ); - 0 - } - Err(error) => { - eprintln!("leleka: cannot write {}: {error}", path.display()); - 1 - } - }, + Err(error) => { + eprintln!("leleka: cannot write {}: {error}", path.display()); + 1 + } } } diff --git a/crates/deploy/src/logview/tests.rs b/crates/deploy/src/logview/tests.rs index 60284196..5fcf5d59 100644 --- a/crates/deploy/src/logview/tests.rs +++ b/crates/deploy/src/logview/tests.rs @@ -50,6 +50,14 @@ fn json_lines_old_supervisor_lines_and_free_text_all_parse() { #[test] fn rotated_generations_are_read_oldest_first_and_filters_apply() { let dir = scratch("gens"); + write_generations(&dir); + check_order_and_levels(&dir); + check_since_tail_and_request(&dir); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Three generations of `api.log`, the live one with a warning and a line of free text. +fn write_generations(dir: &Path) { let name = |s: &str| dir.join(s); std::fs::write( name("api.log.2"), @@ -75,8 +83,11 @@ fn rotated_generations_are_read_oldest_first_and_filters_apply() { ), ) .unwrap(); +} + +fn check_order_and_levels(dir: &Path) { let all = collect( - &dir, + dir, &Filter { tail: 100, ..Filter::default() @@ -93,7 +104,7 @@ fn rotated_generations_are_read_oldest_first_and_filters_apply() { "the free-text line is kept, next to its neighbours in time" ); let warn = collect( - &dir, + dir, &Filter { min_level: Level::Warn, tail: 100, @@ -103,9 +114,12 @@ fn rotated_generations_are_read_oldest_first_and_filters_apply() { assert!( warn.iter().all(|e| e.level >= Level::Warn) && warn.iter().any(|e| e.ev == "engine_lost") ); +} + +fn check_since_tail_and_request(dir: &Path) { let since = parse_utc_ms("2026-11-02T09:45:00Z").unwrap(); let recent = collect( - &dir, + dir, &Filter { since_ms: Some(since), tail: 100, @@ -116,8 +130,12 @@ fn rotated_generations_are_read_oldest_first_and_filters_apply() { recent.iter().all(|e| e.ts_ms.unwrap() >= since) && recent.len() == 3, "{recent:?}" ); + check_tail_and_request(dir); +} + +fn check_tail_and_request(dir: &Path) { let tail = collect( - &dir, + dir, &Filter { tail: 2, ..Filter::default() @@ -125,7 +143,7 @@ fn rotated_generations_are_read_oldest_first_and_filters_apply() { ); assert_eq!(tail.len(), 2); let by_id = collect( - &dir, + dir, &Filter { request: Some("REQ-b".into()), tail: 100, @@ -133,7 +151,6 @@ fn rotated_generations_are_read_oldest_first_and_filters_apply() { }, ); assert_eq!(by_id.len(), 1); - let _ = std::fs::remove_dir_all(&dir); } #[test] diff --git a/crates/deploy/src/plan/gather_state.rs b/crates/deploy/src/plan/gather_state.rs index 25f2ce8e..47c808f0 100644 --- a/crates/deploy/src/plan/gather_state.rs +++ b/crates/deploy/src/plan/gather_state.rs @@ -57,161 +57,17 @@ pub fn gather(opts: &UpOptions, var: &dyn Fn(&str) -> Option) -> Context let paths = opts.dirs.paths(); let bin_src = opts.bin_src.clone().unwrap_or_else(current_bin_dir); let installed = paths.bin_dir(); - // Probe the source of the binaries, or the installed copy when the source has none (re-run after install). - let binary_dir = if BINARIES.iter().all(|b| bin_src.join(b).is_file()) { - bin_src.clone() - } else { - installed.clone() - }; - let mut extra_library_dirs: Vec = Vec::new(); - if let Some(dir) = &opts.cublas_dir { - extra_library_dirs.push(dir.clone()); - } else { - extra_library_dirs.push(paths.cublas_dir()); - } - let ports: Vec = [&opts.ports.api, &opts.ports.engine, &opts.ports.daemon] - .iter() - .filter_map(|p| p.rsplit(':').next()?.parse().ok()) - .collect(); - let request = ProbeRequest { - dirs: vec![ - ("assets".into(), opts.dirs.assets.clone()), - ("state".into(), opts.dirs.state.clone()), - ("prefix".into(), opts.dirs.prefix.clone()), - ], - ports, - binary_dir: Some(binary_dir.clone()), - binaries: BINARIES.iter().map(|b| b.to_string()).collect(), - extra_library_dirs, - }; - let facts = probe(&request); + let binary_dir = probed_binary_dir(&bin_src, &installed); + let facts = probe(&probe_request(opts, &paths, &binary_dir)); let manifest = Manifest::find(&binary_dir); let gpu = facts.gpus.iter().find(|g| g.index == opts.gpu); - let mut profile = resolve(opts.profile.as_deref(), gpu); - if let Ok(p) = &mut profile { - if let Some(gib) = opts.gpu_budget_gib { - p.gpu_budget_bytes = gib << 30; - } - if let Some(tokens) = opts.context_tokens { - p.context_tokens = tokens; - } - if let Err(message) = p.validate() { - profile = Err(message); - } - } - let choice = if opts.kar_fd.is_some() && opts.mode == ModeChoice::Auto { - ModeChoice::Foreground - } else { - opts.mode - }; - let mode = resolve_mode(choice, &facts, user_session_available(var)); - let service_user = if matches!(mode, Mode::Systemd(UnitScopeTag::System)) { - opts.service_user - .clone() - .unwrap_or_else(|| "leleka".to_owned()) - } else { - var("USER") - .or_else(|| var("LOGNAME")) - .unwrap_or_else(|| "root".to_owned()) - }; - let (shards, kar) = missing_asset_bytes(&paths); - let installed_same_dir = same_dir(&bin_src, &installed); - let mut needs = Needs { - gpu_index: opts.gpu, - assets_dir: opts.dirs.assets.clone(), - state_dir: opts.dirs.state.clone(), - prefix_dir: opts.dirs.prefix.clone(), - // Windows never fetches or builds: the model volume is copied in (the plan blocks with the reason when it is not). - shard_bytes_missing: if opts.fetch && facts.os != "windows" { - shards - } else { - 0 - }, - kar_bytes_missing: if opts.fetch && facts.os != "windows" { - kar - } else { - 0 - }, - install_binaries: !installed_same_dir, - may_install_cublas: opts.install_cublas - && opts.cublas_dir.is_none() - && facts.os != "windows", - cublas_download_bytes: CUBLAS_BYTES, - wants_systemd: matches!(mode, Mode::Systemd(_)), - service_ports: vec![ - ("api".into(), port_of(&opts.ports.api)), - ("engine".into(), port_of(&opts.ports.engine)), - ("gateway".into(), port_of(&opts.ports.daemon)), - ], - require_binaries: true, - binary_has_sm86: manifest - .as_ref() - .and_then(|m| m.as_ref().ok()) - .map(Manifest::has_sm86), - service_running: service_running(&paths), - kar_fd_inherited: opts.kar_fd.is_some(), - api_bind_open: crate::config::probe_address(&opts.ports.api) - .is_some_and(|a| !a.ip().is_loopback()), - expert_profile: None, - resources: None, - }; - let (config, report) = match &mut profile { - Ok(p) => { - // `kar_source: none` never needs the archive (and never builds it) - if p.kar_source == KarSource::None { - needs.kar_bytes_missing = 0; - } - needs.expert_profile = if opts.no_expert_tier && p.expert_profile.is_some() { - Some(ExpertProfileState::OptedOut) - } else { - expert_profile_state(p, &opts.dirs.assets) - }; - let mut engine_env = BTreeMap::new(); - let base_profile = p.clone(); - // An inherited sealed archive is already resident: it is not part of what the engine still needs from the host. - let planned_host = if opts.kar_fd.is_some() { - crate::resources::with_resident_bytes(&facts, p.memfd_bytes()) - } else { - facts.clone() - }; - let resources = crate::resources::compute(&planned_host, gpu, p, opts.preset); - crate::resources::apply( - &resources, - p, - &mut engine_env, - opts.gpu_budget_gib.is_some(), - ); - needs.resources = Some(resources); - // The tier is configured whenever it is intended (any state but the explicit opt-out): a missing or wrong table is - // provisioned by the `expert-profile` step, which runs before the configuration is written and blocks `up` - // when it cannot succeed. At every start the supervisor re-checks the digest (`expert_profile::start_environment`). - if needs.expert_profile != Some(ExpertProfileState::OptedOut) - && let Some(relative) = &p.expert_profile - { - engine_env.insert( - crate::expert_profile::SLOTS_ENV.to_owned(), - "auto".to_owned(), - ); - engine_env.insert( - crate::expert_profile::PROFILE_ENV.to_owned(), - opts.dirs.assets.join(relative).display().to_string(), - ); - } - let mut config = RunConfig::new( - &opts.dirs, - opts.ports.clone(), - opts.gpu, - p.clone(), - engine_env, - ); - config.preset = opts.preset; - config.expert_tier = !opts.no_expert_tier; - config.base_profile = Some(base_profile); - let report = evaluate(&facts, p, &needs); - (Some(config), Some(report)) - } - Err(_) => (None, None), - }; + let mut profile = tuned_profile(opts, gpu); + let mode = resolve_mode(chosen_mode(opts), &facts, user_session_available(var)); + let service_user = service_user_of(opts, &mode, var); + let has_sm86 = sm86_of(&manifest); + let installs = !same_dir(&bin_src, &installed); + let mut needs = base_needs(opts, &paths, &facts, &mode, (installs, has_sm86)); + let (config, report) = configured(opts, &facts, gpu, &mut profile, &mut needs); Context { opts: opts.clone(), facts, @@ -227,6 +83,256 @@ pub fn gather(opts: &UpOptions, var: &dyn Fn(&str) -> Option) -> Context } } +/// Probe the source of the binaries, or the installed copy when the source has none (re-run after install). +fn probed_binary_dir(bin_src: &Path, installed: &Path) -> PathBuf { + if BINARIES.iter().all(|b| bin_src.join(b).is_file()) { + bin_src.to_path_buf() + } else { + installed.to_path_buf() + } +} + +/// Does the build carry sm_86 kernels, when a manifest says? +fn sm86_of(manifest: &Option>) -> Option { + manifest + .as_ref() + .and_then(|m| m.as_ref().ok()) + .map(Manifest::has_sm86) +} + +/// The configuration and the preflight report, when the profile is usable. +fn configured( + opts: &UpOptions, + facts: &Facts, + gpu: Option<&crate::facts::Gpu>, + profile: &mut Result, + needs: &mut Needs, +) -> (Option, Option) { + match profile { + Ok(p) => { + let (config, report) = configure_engine(opts, facts, gpu, p, needs); + (Some(config), Some(report)) + } + Err(_) => (None, None), + } +} + +fn probe_request(opts: &UpOptions, paths: &Paths, binary_dir: &Path) -> ProbeRequest { + let mut extra_library_dirs: Vec = Vec::new(); + if let Some(dir) = &opts.cublas_dir { + extra_library_dirs.push(dir.clone()); + } else { + extra_library_dirs.push(paths.cublas_dir()); + } + let ports: Vec = [&opts.ports.api, &opts.ports.engine, &opts.ports.daemon] + .iter() + .filter_map(|p| p.rsplit(':').next()?.parse().ok()) + .collect(); + ProbeRequest { + dirs: vec![ + ("assets".into(), opts.dirs.assets.clone()), + ("state".into(), opts.dirs.state.clone()), + ("prefix".into(), opts.dirs.prefix.clone()), + ], + ports, + binary_dir: Some(binary_dir.to_path_buf()), + binaries: BINARIES.iter().map(|b| b.to_string()).collect(), + extra_library_dirs, + } +} + +/// The profile of the options with the budget and context overrides applied, or why it is refused. +fn tuned_profile(opts: &UpOptions, gpu: Option<&crate::facts::Gpu>) -> Result { + let mut profile = resolve(opts.profile.as_deref(), gpu); + if let Ok(p) = &mut profile { + if let Some(gib) = opts.gpu_budget_gib { + p.gpu_budget_bytes = gib << 30; + } + if let Some(tokens) = opts.context_tokens { + p.context_tokens = tokens; + } + if let Err(message) = p.validate() { + profile = Err(message); + } + } + profile +} + +/// An inherited sealed archive means the service runs in the foreground under whoever holds the descriptor. +fn chosen_mode(opts: &UpOptions) -> ModeChoice { + if opts.kar_fd.is_some() && opts.mode == ModeChoice::Auto { + ModeChoice::Foreground + } else { + opts.mode + } +} + +fn service_user_of(opts: &UpOptions, mode: &Mode, var: impl Fn(&str) -> Option) -> String { + if matches!(mode, Mode::Systemd(UnitScopeTag::System)) { + opts.service_user + .clone() + .unwrap_or_else(|| "leleka".to_owned()) + } else { + var("USER") + .or_else(|| var("LOGNAME")) + .unwrap_or_else(|| "root".to_owned()) + } +} + +/// The needs of the host checks before a profile is considered. `binaries`: whether the binaries are installed from +/// another directory, and whether the build carries sm_86 kernels (when a manifest says). +fn base_needs( + opts: &UpOptions, + paths: &Paths, + facts: &Facts, + mode: &Mode, + binaries: (bool, Option), +) -> Needs { + let (shards, kar) = missing_asset_bytes(paths); + Needs { + gpu_index: opts.gpu, + assets_dir: opts.dirs.assets.clone(), + state_dir: opts.dirs.state.clone(), + prefix_dir: opts.dirs.prefix.clone(), + shard_bytes_missing: missing_bytes(opts, facts, shards), + kar_bytes_missing: missing_bytes(opts, facts, kar), + install_binaries: binaries.0, + may_install_cublas: cublas_installable(opts, facts), + cublas_download_bytes: CUBLAS_BYTES, + wants_systemd: matches!(mode, Mode::Systemd(_)), + service_ports: service_ports(opts), + require_binaries: true, + binary_has_sm86: binaries.1, + service_running: service_running(paths), + kar_fd_inherited: opts.kar_fd.is_some(), + api_bind_open: api_bind_is_open(opts), + expert_profile: None, + resources: None, + } +} + +/// The bytes of an asset that `up` has to fetch: none where it does not fetch. +fn missing_bytes(opts: &UpOptions, facts: &Facts, bytes: u64) -> u64 { + if fetches_assets(opts, facts) { + bytes + } else { + 0 + } +} + +fn cublas_installable(opts: &UpOptions, facts: &Facts) -> bool { + opts.install_cublas && opts.cublas_dir.is_none() && facts.os != "windows" +} + +/// Does the API listen on an address other than loopback? +fn api_bind_is_open(opts: &UpOptions) -> bool { + crate::config::probe_address(&opts.ports.api).is_some_and(|a| !a.ip().is_loopback()) +} + +/// Windows never fetches or builds: the model volume is copied in (the plan blocks with the reason when it is not). +fn fetches_assets(opts: &UpOptions, facts: &Facts) -> bool { + opts.fetch && facts.os != "windows" +} + +fn service_ports(opts: &UpOptions) -> Vec<(String, u16)> { + vec![ + ("api".into(), port_of(&opts.ports.api)), + ("engine".into(), port_of(&opts.ports.engine)), + ("gateway".into(), port_of(&opts.ports.daemon)), + ] +} + +/// With a usable profile: the resources the host leaves it, the engine environment, the configuration and the +/// preflight report. +fn configure_engine( + opts: &UpOptions, + facts: &Facts, + gpu: Option<&crate::facts::Gpu>, + p: &mut Profile, + needs: &mut Needs, +) -> (RunConfig, Report) { + // `kar_source: none` never needs the archive (and never builds it) + if p.kar_source == KarSource::None { + needs.kar_bytes_missing = 0; + } + needs.expert_profile = expert_tier_need(opts, p); + let mut engine_env = BTreeMap::new(); + let base_profile = p.clone(); + let planned_host = host_for_planning(opts, facts, p); + let resources = crate::resources::compute(&planned_host, gpu, p, opts.preset); + crate::resources::apply( + &resources, + p, + &mut engine_env, + opts.gpu_budget_gib.is_some(), + ); + needs.resources = Some(resources); + add_expert_tier_environment(opts, p, needs, &mut engine_env); + let config = run_config(opts, p, engine_env, base_profile); + let report = evaluate(facts, p, needs); + (config, report) +} + +/// The state of the expert table, unless the operator opted out of the tier. +fn expert_tier_need(opts: &UpOptions, p: &Profile) -> Option { + if opts.no_expert_tier && p.expert_profile.is_some() { + Some(ExpertProfileState::OptedOut) + } else { + expert_profile_state(p, &opts.dirs.assets) + } +} + +/// An inherited sealed archive is already resident: it is not part of what the engine still needs from the host. +fn host_for_planning(opts: &UpOptions, facts: &Facts, p: &Profile) -> Facts { + if opts.kar_fd.is_some() { + crate::resources::with_resident_bytes(facts, p.memfd_bytes()) + } else { + facts.clone() + } +} + +fn run_config( + opts: &UpOptions, + p: &Profile, + engine_env: BTreeMap, + base_profile: Profile, +) -> RunConfig { + let mut config = RunConfig::new( + &opts.dirs, + opts.ports.clone(), + opts.gpu, + p.clone(), + engine_env, + ); + config.preset = opts.preset; + config.expert_tier = !opts.no_expert_tier; + config.base_profile = Some(base_profile); + config +} + +/// The tier is configured whenever it is intended (any state but the explicit opt-out): a missing or wrong table is +/// provisioned by the `expert-profile` step, which runs before the configuration is written and blocks `up` +/// when it cannot succeed. At every start the supervisor re-checks the digest (`expert_profile::start_environment`). +fn add_expert_tier_environment( + opts: &UpOptions, + p: &Profile, + needs: &Needs, + engine_env: &mut BTreeMap, +) { + if needs.expert_profile != Some(ExpertProfileState::OptedOut) + && let Some(relative) = &p.expert_profile + { + engine_env.insert( + crate::expert_profile::SLOTS_ENV.to_owned(), + "auto".to_owned(), + ); + engine_env.insert( + crate::expert_profile::PROFILE_ENV.to_owned(), + opts.dirs.assets.join(relative).display().to_string(), + ); + } +} + pub(super) fn port_of(address: &str) -> u16 { address .rsplit(':') diff --git a/crates/deploy/src/plan/render.rs b/crates/deploy/src/plan/render.rs index 2bf4f781..24b48a15 100644 --- a/crates/deploy/src/plan/render.rs +++ b/crates/deploy/src/plan/render.rs @@ -21,33 +21,39 @@ pub fn render_plan(ctx: &Context, steps: &[Step]) -> String { } } if let Some(config) = &ctx.config { - let kar = match config.profile.kar_source { - KarSource::Memfd => KarArg::Fd, - KarSource::File => KarArg::File, - KarSource::None => KarArg::None, - }; + out.push_str(&engine_command_text(ctx, config)); + } + out +} + +/// The engine command line and environment of the configuration, as the service will run them. +fn engine_command_text(ctx: &Context, config: &RunConfig) -> String { + let kar = match config.profile.kar_source { + KarSource::Memfd => KarArg::Fd, + KarSource::File => KarArg::File, + KarSource::None => KarArg::None, + }; + let mut out = format!( + "engine command the service runs:\n {} {}\n", + ctx.paths.bin("leleka-inference").display(), + config.engine_args(kar).join(" ") + ); + out.push_str(&format!( + " (profile {}: budget {:.1} GiB, context {}, KAR {})\n", + config.profile.name, + config.profile.gpu_budget_bytes as f64 / (1u64 << 30) as f64, + config.profile.context_tokens, + config.profile.kar_source.as_str() + )); + let env = config.engine_environment(); + if !env.is_empty() { out.push_str(&format!( - "engine command the service runs:\n {} {}\n", - ctx.paths.bin("leleka-inference").display(), - config.engine_args(kar).join(" ") + " engine environment: {}\n", + env.iter() + .map(|(k, v)| format!("{k}={v}")) + .collect::>() + .join(" ") )); - out.push_str(&format!( - " (profile {}: budget {:.1} GiB, context {}, KAR {})\n", - config.profile.name, - config.profile.gpu_budget_bytes as f64 / (1u64 << 30) as f64, - config.profile.context_tokens, - config.profile.kar_source.as_str() - )); - let env = config.engine_environment(); - if !env.is_empty() { - out.push_str(&format!( - " engine environment: {}\n", - env.iter() - .map(|(k, v)| format!("{k}={v}")) - .collect::>() - .join(" ") - )); - } } out } diff --git a/crates/deploy/src/plan/tests.rs b/crates/deploy/src/plan/tests.rs index 491cd600..692dadde 100644 --- a/crates/deploy/src/plan/tests.rs +++ b/crates/deploy/src/plan/tests.rs @@ -44,60 +44,9 @@ fn context(opts: UpOptions, mode: Mode, gpu_name: &str, sm: u32) -> Context { vram_free_mib: if sm == 120 { 32000 } else { 15500 }, sm: Some(sm), }; - let mut facts = Facts { - os: "linux".into(), - arch: "x86_64".into(), - gpus: vec![gpu.clone()], - memory: Memory { - total: 128 << 30, - available: 100 << 30, - swap_total: 0, - }, - root: true, - systemd_system: true, - proc_fd: true, - memfd_ok: true, - ..Facts::default() - }; - facts - .libs - .insert("libcublas.so.12".into(), Some("/x/libcublas.so.12".into())); - facts.libs.insert( - "libcublasLt.so.12".into(), - Some("/x/libcublasLt.so.12".into()), - ); - facts - .libs - .insert("libcuda.so.1".into(), Some("/x/libcuda.so.1".into())); - for tool in ["curl", "tar", "xz", "systemctl"] { - facts.tools.insert(tool.into(), true); - } - for name in BINARIES { - facts.binaries.insert(name.into(), true); - } - for key in ["assets", "state", "prefix"] { - facts.dirs.insert( - key.into(), - crate::facts::DirFact { - path: format!("/{key}").into(), - free_bytes: Some(2 << 40), - fs_type: Some("ext4".into()), - }, - ); - } + let facts = finished_host(gpu.clone()); let profile = resolve(opts.profile.as_deref(), Some(&gpu)); - // A finished host by default: the pinned table is in place (tests of the other states set `needs.expert_profile`). - let expert_profile = profile - .as_ref() - .ok() - .filter(|p| p.expert_profile.is_some()) - .map(|_| { - if opts.no_expert_tier { - ExpertProfileState::OptedOut - } else { - ExpertProfileState::Valid - } - }); + let expert_profile = expert_state(&profile, &opts); let needs = Needs { shard_bytes_missing: 83_617_662_656, kar_bytes_missing: ARCHIVE_BYTES * 12 / 10, @@ -129,6 +78,72 @@ fn context(opts: UpOptions, mode: Mode, gpu_name: &str, sm: u32) -> Context { } } +/// A server host with the GPU, every library, tool and binary, and the three directories with room. +fn finished_host(gpu: Gpu) -> Facts { + let mut facts = Facts { + os: "linux".into(), + arch: "x86_64".into(), + gpus: vec![gpu], + memory: Memory { + total: 128 << 30, + available: 100 << 30, + swap_total: 0, + }, + root: true, + systemd_system: true, + proc_fd: true, + memfd_ok: true, + ..Facts::default() + }; + add_libraries_tools_binaries_and_dirs(&mut facts); + facts +} + +/// The three CUDA libraries, the tools, every binary, and the three directories with room. +fn add_libraries_tools_binaries_and_dirs(facts: &mut Facts) { + facts + .libs + .insert("libcublas.so.12".into(), Some("/x/libcublas.so.12".into())); + facts.libs.insert( + "libcublasLt.so.12".into(), + Some("/x/libcublasLt.so.12".into()), + ); + facts + .libs + .insert("libcuda.so.1".into(), Some("/x/libcuda.so.1".into())); + for tool in ["curl", "tar", "xz", "systemctl"] { + facts.tools.insert(tool.into(), true); + } + for name in BINARIES { + facts.binaries.insert(name.into(), true); + } + for key in ["assets", "state", "prefix"] { + facts.dirs.insert( + key.into(), + crate::facts::DirFact { + path: format!("/{key}").into(), + free_bytes: Some(2 << 40), + fs_type: Some("ext4".into()), + }, + ); + } +} + +/// A finished host by default: the pinned table is in place (tests of the other states set `needs.expert_profile`). +fn expert_state(profile: &Result, opts: &UpOptions) -> Option { + profile + .as_ref() + .ok() + .filter(|p| p.expert_profile.is_some()) + .map(|_| { + if opts.no_expert_tier { + ExpertProfileState::OptedOut + } else { + ExpertProfileState::Valid + } + }) +} + fn state_of<'a>(steps: &'a [Step], id: &str) -> &'a StepState { &steps.iter().find(|s| s.id == id).unwrap().state } diff --git a/crates/deploy/src/plan/tests/install_steps.rs b/crates/deploy/src/plan/tests/install_steps.rs index b3521d62..ffa04cf4 100644 --- a/crates/deploy/src/plan/tests/install_steps.rs +++ b/crates/deploy/src/plan/tests/install_steps.rs @@ -2,6 +2,40 @@ use super::*; +/// The steps a fresh server plans: every one of them but the preflight. +const EVERY_STEP: [&str; 11] = [ + "layout", + "binaries", + "expert-profile", + "secrets", + "model", + "kar", + "tokenizer", + "config", + "service", + "start", + "ready", +]; + +/// A deployment in which everything is in place and the service answers. +fn finished_fs() -> FsState { + FsState { + dirs_exist: true, + binaries_current: true, + binaries_source_ok: true, + cublas_ready: true, + secrets_present: true, + shards_stamp_ok: true, + kar_stamp_ok: true, + kar_present: true, + mtp_present: true, + tokenizer_present: true, + configs_current: true, + unit_current: true, + service_ready: true, + } +} + #[test] fn fresh_server_plans_every_step() { let mut ctx = context( @@ -19,19 +53,7 @@ fn fresh_server_plans_every_step() { ..FsState::default() }, ); - for id in [ - "layout", - "binaries", - "expert-profile", - "secrets", - "model", - "kar", - "tokenizer", - "config", - "service", - "start", - "ready", - ] { + for id in EVERY_STEP { assert!( matches!(state_of(&steps, id), StepState::Todo(_)), "{id}: {:?}", @@ -39,7 +61,11 @@ fn fresh_server_plans_every_step() { ); } let text = render_plan(&ctx, &steps).replace('\\', "/"); - assert!(text.contains("model ensure-sharded-streamed qwen-iq3-s --source-dir /data/leleka/model --output /data/leleka/qwen-iq3-s-l2-v4.kar --levels 2"), "{text}"); + let derive = concat!( + "model ensure-sharded-streamed qwen-iq3-s --source-dir /data/leleka/model ", + "--output /data/leleka/qwen-iq3-s-l2-v4.kar --levels 2" + ); + assert!(text.contains(derive), "{text}"); assert!(text.contains("--kar-archive-fd {FD}"), "{text}"); } @@ -51,22 +77,7 @@ fn finished_deployment_is_done_except_nothing_to_do() { "NVIDIA GeForce RTX 5090", 120, ); - let fs = FsState { - dirs_exist: true, - binaries_current: true, - binaries_source_ok: true, - cublas_ready: true, - secrets_present: true, - shards_stamp_ok: true, - kar_stamp_ok: true, - kar_present: true, - mtp_present: true, - tokenizer_present: true, - configs_current: true, - unit_current: true, - service_ready: true, - }; - let steps = plan_steps(&ctx, &fs); + let steps = plan_steps(&ctx, &finished_fs()); for step in &steps { if step.id != "preflight" { assert!( diff --git a/crates/deploy/src/preflight/tests.rs b/crates/deploy/src/preflight/tests.rs index bc343cb8..1ccc0b14 100644 --- a/crates/deploy/src/preflight/tests.rs +++ b/crates/deploy/src/preflight/tests.rs @@ -26,6 +26,12 @@ fn server_facts() -> Facts { memfd_ok: true, ..Facts::default() }; + add_libraries_tools_and_dirs(&mut facts); + facts +} + +/// The three CUDA libraries, the download and unpack tools, and the three directories with room. +fn add_libraries_tools_and_dirs(facts: &mut Facts) { facts.libs.insert( "libcublas.so.12".into(), Some("/opt/c/libcublas.so.12".into()), @@ -51,7 +57,6 @@ fn server_facts() -> Facts { }, ); } - facts } fn needs() -> Needs { diff --git a/crates/deploy/src/preflight/tests/windows_host.rs b/crates/deploy/src/preflight/tests/windows_host.rs index 08b7206f..2a4694fe 100644 --- a/crates/deploy/src/preflight/tests/windows_host.rs +++ b/crates/deploy/src/preflight/tests/windows_host.rs @@ -24,6 +24,12 @@ pub(super) fn windows_laptop() -> Facts { nvidia_smi_found: true, ..Facts::default() }; + add_dirs_and_binaries(&mut facts); + facts +} + +/// The three directories on a roomy NTFS volume and every native program. +fn add_dirs_and_binaries(facts: &mut Facts) { for key in ["assets", "state", "prefix"] { facts.dirs.insert( key.into(), @@ -37,7 +43,6 @@ pub(super) fn windows_laptop() -> Facts { for name in crate::layout::BINARIES { facts.binaries.insert(name.into(), true); } - facts } #[test] diff --git a/crates/deploy/src/profile/catalog.rs b/crates/deploy/src/profile/catalog.rs index ecb98472..f60cc3c1 100644 --- a/crates/deploy/src/profile/catalog.rs +++ b/crates/deploy/src/profile/catalog.rs @@ -45,17 +45,7 @@ impl Profile { pub fn resolve(spec: Option<&str>, gpu: Option<&Gpu>) -> Result { let spec = spec.unwrap_or("auto"); if spec != "auto" { - if let Some(profile) = Profile::builtin(spec) { - return Ok(profile); - } - if spec.contains('/') || spec.contains('\\') || spec.ends_with(".json") { - return Profile::from_file(Path::new(spec)); - } - let names: Vec<_> = BUILTIN.iter().map(|(name, _)| *name).collect(); - return Err(format!( - "unknown profile {spec:?}; built-in profiles: {}; or pass a JSON file (see `leleka profiles show NAME`)", - names.join(", ") - )); + return resolve_named(spec); } let gpu = gpu.ok_or( "no NVIDIA GPU was detected, so no profile can be selected automatically; pass --profile NAME|FILE", @@ -80,3 +70,18 @@ pub fn resolve(spec: Option<&str>, gpu: Option<&Gpu>) -> Result _ => Err("more than one built-in profile matches; pass --profile NAME".into()), } } + +/// A built-in profile by name, or a profile file. +fn resolve_named(spec: &str) -> Result { + if let Some(profile) = Profile::builtin(spec) { + return Ok(profile); + } + if spec.contains('/') || spec.contains('\\') || spec.ends_with(".json") { + return Profile::from_file(Path::new(spec)); + } + let names: Vec<_> = BUILTIN.iter().map(|(name, _)| *name).collect(); + Err(format!( + "unknown profile {spec:?}; built-in profiles: {}; or pass a JSON file (see `leleka profiles show NAME`)", + names.join(", ") + )) +} diff --git a/crates/deploy/src/profile/memory_budget.rs b/crates/deploy/src/profile/memory_budget.rs index 32b977e0..dcfefe3c 100644 --- a/crates/deploy/src/profile/memory_budget.rs +++ b/crates/deploy/src/profile/memory_budget.rs @@ -2,8 +2,33 @@ use super::*; +const SHARE_ENV: &str = "LELEKA_MEMORY_CACHE_SHARE_PERCENT"; +const RETENTION_ENV: &str = "LELEKA_PREFIX_RETENTION_S"; +const HEAL_ENV: &str = "LELEKA_MEMORY_HEAL"; +const RESIDENT_ENV: &str = "LELEKA_ORIGINAL_SERVE_RESIDENT_BUDGET_GIB"; + impl MemoryBudget { pub fn validate(&self) -> Result<(), String> { + self.validate_prefix_cache()?; + if let (Some(soft), Some(hard)) = (self.soft_floor_mib, self.hard_floor_mib) + && hard >= soft + { + return Err("memory.hard_floor_mib must be below memory.soft_floor_mib".into()); + } + if let Some(percent) = self.cache_share_percent + && !(1..=100).contains(&percent) + { + return Err("memory.cache_share_percent must be 1..=100".into()); + } + if let Some(lock) = &self.lock + && !matches!(lock.as_str(), "off" | "try" | "require") + { + return Err("memory.lock must be off, try or require".into()); + } + Ok(()) + } + + fn validate_prefix_cache(&self) -> Result<(), String> { if let Some(value) = &self.prefix_cache_mib && value != "auto" && value.parse::().ok().is_none_or(|mib| mib > (1 << 30)) @@ -20,21 +45,6 @@ impl MemoryBudget { { return Err("memory.prefix_cache_block must be a multiple of 256, at most 8192 (0 = the prefill chunk)".into()); } - if let (Some(soft), Some(hard)) = (self.soft_floor_mib, self.hard_floor_mib) - && hard >= soft - { - return Err("memory.hard_floor_mib must be below memory.soft_floor_mib".into()); - } - if let Some(percent) = self.cache_share_percent - && !(1..=100).contains(&percent) - { - return Err("memory.cache_share_percent must be 1..=100".into()); - } - if let Some(lock) = &self.lock - && !matches!(lock.as_str(), "off" | "try" | "require") - { - return Err("memory.lock must be off, try or require".into()); - } Ok(()) } @@ -75,44 +85,33 @@ impl MemoryBudget { /// The engine environment this section adds. pub fn env(&self) -> BTreeMap { + fn text(value: Option) -> Option { + value.map(|v| v.to_string()) + } let mut env = BTreeMap::new(); let mut put = |key: &str, value: Option| { if let Some(value) = value { env.insert(key.to_owned(), value); } }; - put( - "LELEKA_MEMORY_SOFT_FLOOR_MIB", - self.soft_floor_mib.map(|v| v.to_string()), - ); - put( - "LELEKA_MEMORY_HARD_FLOOR_MIB", - self.hard_floor_mib.map(|v| v.to_string()), - ); - put( - "LELEKA_MEMORY_RESERVE_MIB", - self.reserve_mib.map(|v| v.to_string()), - ); - put( - "LELEKA_MEMORY_CACHE_SHARE_PERCENT", - self.cache_share_percent.map(|v| v.to_string()), - ); + put("LELEKA_MEMORY_SOFT_FLOOR_MIB", text(self.soft_floor_mib)); + put("LELEKA_MEMORY_HARD_FLOOR_MIB", text(self.hard_floor_mib)); + put("LELEKA_MEMORY_RESERVE_MIB", text(self.reserve_mib)); + put(SHARE_ENV, text(self.cache_share_percent)); put("LELEKA_MEMORY_LOCK", self.lock.clone()); if self.prefix_cache_on() { - put( - "LELEKA_PREFIX_RETENTION_S", - self.prefix_retention_min - .map(|minutes| minutes.saturating_mul(60).to_string()), - ); + put(RETENTION_ENV, self.retention_seconds()); } put( - "LELEKA_MEMORY_HEAL", + HEAL_ENV, self.heal.map(|v| if v { "1" } else { "0" }.to_owned()), ); - put( - "LELEKA_ORIGINAL_SERVE_RESIDENT_BUDGET_GIB", - self.resident_budget_gib.map(|v| v.to_string()), - ); + put(RESIDENT_ENV, text(self.resident_budget_gib)); env } + + fn retention_seconds(&self) -> Option { + self.prefix_retention_min + .map(|minutes| minutes.saturating_mul(60).to_string()) + } } diff --git a/crates/deploy/src/profile/tests/builtin_profiles.rs b/crates/deploy/src/profile/tests/builtin_profiles.rs index b8001bba..8e19879e 100644 --- a/crates/deploy/src/profile/tests/builtin_profiles.rs +++ b/crates/deploy/src/profile/tests/builtin_profiles.rs @@ -2,6 +2,17 @@ use super::*; +/// The field `$($field).+` of both profiles is the same. +macro_rules! assert_same { + ($a:expr, $b:expr, $($field:tt).+) => { + assert!( + $a.$($field).+ == $b.$($field).+, + "{} must match rtx5090-32g", + stringify!($($field).+) + ) + }; +} + #[test] fn built_in_profiles_parse_and_validate() { for profile in Profile::builtins() { @@ -19,57 +30,43 @@ fn the_file_variant_of_the_server_profile_differs_only_where_the_archive_form_ma (file.kar_source, file.expert_source), (KarSource::File, ExpertSource::Resident) ); - // same engine configuration: only the archive form, the RAM it needs and the cache budget (explicit, so that the RAM the memfd no longer - // holds is not handed to the prefix cache) and the memfd-only lock/heal switches differ - for (name, same) in [ - ( - "gpu_budget_bytes", - server.gpu_budget_bytes == file.gpu_budget_bytes, - ), - ( - "context_tokens", - server.context_tokens == file.context_tokens, - ), - ( - "prefill_capacity", - server.prefill_capacity == file.prefill_capacity, - ), - ("spec_min_p", server.spec_min_p == file.spec_min_p), - ( - "expert_profile", - server.expert_profile == file.expert_profile, - ), - ("engine_env", server.engine_env == file.engine_env), - ( - "prefix_cache_tail", - server.memory.prefix_cache_tail == file.memory.prefix_cache_tail, - ), - ( - "prefix_cache_block", - server.memory.prefix_cache_block == file.memory.prefix_cache_block, - ), - ( - "floors", - ( - server.memory.soft_floor_mib, - server.memory.hard_floor_mib, - server.memory.reserve_mib, - ) == ( - file.memory.soft_floor_mib, - file.memory.hard_floor_mib, - file.memory.reserve_mib, - ), - ), - ] { - assert!(same, "{name} must match rtx5090-32g"); - } + check_same_engine_configuration(&server, &file); assert_eq!(file.memory.prefix_cache_mib.as_deref(), Some("6144")); assert!( file.min_ram_available_bytes + ARCHIVE_BYTES - 5_000_000_000 <= server.min_ram_available_bytes, "the file form does not need the archive's RAM" ); - // an experimental profile: no GPU is ever matched to it, so `auto` keeps choosing exactly one profile + check_never_auto_selected(&file); +} + +/// Same engine configuration: only the archive form, the RAM it needs and the cache budget (explicit, so that the RAM +/// the memfd no longer +/// holds is not handed to the prefix cache) and the memfd-only lock/heal switches differ. +fn check_same_engine_configuration(server: &Profile, file: &Profile) { + assert_same!(server, file, gpu_budget_bytes); + assert_same!(server, file, context_tokens); + assert_same!(server, file, prefill_capacity); + assert_same!(server, file, spec_min_p); + assert_same!(server, file, expert_profile); + assert_same!(server, file, engine_env); + assert_same!(server, file, memory.prefix_cache_tail); + assert_same!(server, file, memory.prefix_cache_block); + let floors = |p: &Profile| { + ( + p.memory.soft_floor_mib, + p.memory.hard_floor_mib, + p.memory.reserve_mib, + ) + }; + assert!( + floors(server) == floors(file), + "floors must match rtx5090-32g" + ); +} + +/// An experimental profile: no GPU is ever matched to it, so `auto` keeps choosing exactly one profile. +fn check_never_auto_selected(file: &Profile) { assert!(!file.matches(&gpu("NVIDIA GeForce RTX 5090", 120, 32607))); assert_eq!( resolve(None, Some(&gpu("NVIDIA GeForce RTX 5090", 120, 32607))) @@ -91,40 +88,7 @@ fn the_gguf_ple_variant_differs_from_the_server_profile_only_in_the_ple_source() assert_eq!(ggufp.kar_source, KarSource::None); assert_eq!(ggufp.memfd_bytes(), 0); assert_eq!(KarSource::None.as_str(), "none"); - for (name, same) in [ - ( - "gpu_budget_bytes", - server.gpu_budget_bytes == ggufp.gpu_budget_bytes, - ), - ( - "context_tokens", - server.context_tokens == ggufp.context_tokens, - ), - ( - "prefill_capacity", - server.prefill_capacity == ggufp.prefill_capacity, - ), - ("spec_min_p", server.spec_min_p == ggufp.spec_min_p), - ( - "expert_profile", - server.expert_profile == ggufp.expert_profile, - ), - ("expert_source", server.expert_source == ggufp.expert_source), - ( - "prefix_cache_mib", - server.memory.prefix_cache_mib == ggufp.memory.prefix_cache_mib, - ), - ( - "prefix_cache_tail", - server.memory.prefix_cache_tail == ggufp.memory.prefix_cache_tail, - ), - ( - "prefix_cache_block", - server.memory.prefix_cache_block == ggufp.memory.prefix_cache_block, - ), - ] { - assert!(same, "{name} must match rtx5090-32g"); - } + check_same_serve_configuration(&server, &ggufp); // the engine switches are the server's plus the page-cache form of the PLE reader let mut expected = server.engine_env.clone(); expected.insert("LELEKA_PLE_DIRECT".into(), "0".into()); @@ -138,11 +102,27 @@ fn the_gguf_ple_variant_differs_from_the_server_profile_only_in_the_ple_source() .name, "rtx5090-32g" ); - // only the PLE reader family is let through next to the serve-stack switches + check_ple_reader_family_only(&ggufp); +} + +fn check_same_serve_configuration(server: &Profile, ggufp: &Profile) { + assert_same!(server, ggufp, gpu_budget_bytes); + assert_same!(server, ggufp, context_tokens); + assert_same!(server, ggufp, prefill_capacity); + assert_same!(server, ggufp, spec_min_p); + assert_same!(server, ggufp, expert_profile); + assert_same!(server, ggufp, expert_source); + assert_same!(server, ggufp, memory.prefix_cache_mib); + assert_same!(server, ggufp, memory.prefix_cache_tail); + assert_same!(server, ggufp, memory.prefix_cache_block); +} + +/// Only the PLE reader family is let through next to the serve-stack switches; the JSON form round-trips. +fn check_ple_reader_family_only(ggufp: &Profile) { let mut bad = ggufp.clone(); bad.engine_env.insert("LELEKA_PLEX".into(), "1".into()); assert!(bad.validate().is_err()); - let mut json: serde_json::Value = serde_json::to_value(&ggufp).unwrap(); + let mut json: serde_json::Value = serde_json::to_value(ggufp).unwrap(); assert_eq!(json["kar_source"], "none"); json["kar_source"] = "memfd".into(); let back: Profile = serde_json::from_value(json).unwrap(); diff --git a/crates/deploy/src/profile/tests/sparse_memfd.rs b/crates/deploy/src/profile/tests/sparse_memfd.rs index 0b34fc54..e57b83d5 100644 --- a/crates/deploy/src/profile/tests/sparse_memfd.rs +++ b/crates/deploy/src/profile/tests/sparse_memfd.rs @@ -20,6 +20,10 @@ fn only_the_5090_profile_uses_a_sparse_memfd_and_full_is_never_serialized() { profile.name ); } + check_serialization_round_trip(); +} + +fn check_serialization_round_trip() { let mut full = sparse_server(); full.memfd_extents = MemfdExtents::Full; assert!( diff --git a/crates/deploy/src/reconfigure/plan_and_persist.rs b/crates/deploy/src/reconfigure/plan_and_persist.rs index 733ff95e..d18b4b42 100644 --- a/crates/deploy/src/reconfigure/plan_and_persist.rs +++ b/crates/deploy/src/reconfigure/plan_and_persist.rs @@ -15,6 +15,69 @@ pub fn plan( archive_resident: bool, ) -> Result { let preset = request.preset.unwrap_or(config.preset); + let base = requested_base(config, request, preset)?; + let mut profile = base.clone(); + let seen = seen_host(facts, &profile, archive_resident); + let gpu = gpu_of(&seen, config.gpu).cloned(); + let resources = resources::compute(&seen, gpu.as_ref(), &profile, preset); + check_resources(&resources, request, preset, archive_resident)?; + let mut env = config.engine_env.clone(); + env.remove(CPU_WORKERS_ENV); + resources::apply( + &resources, + &mut profile, + &mut env, + request.gpu_budget_gib.is_some(), + ); + profile.validate()?; + if let Some(gpu) = &gpu { + check_gpu_fits(&profile, gpu)?; + } + Ok(planned(config, (profile, base, env, preset), resources)) +} + +/// The host as the planner sees it: the archive memfd the supervisor holds already counts against the available RAM. +fn seen_host(facts: &Facts, profile: &Profile, archive_resident: bool) -> Facts { + if archive_resident { + resources::with_resident_bytes(facts, profile.memfd_bytes()) + } else { + facts.clone() + } +} + +/// The new configuration, and whether it differs from the one in force. +fn planned( + config: &RunConfig, + (profile, base, env, preset): ( + Profile, + Profile, + std::collections::BTreeMap, + Preset, + ), + resources: ResourcePlan, +) -> Planned { + let mut next = config.clone(); + next.profile = profile; + next.base_profile = Some(base); + next.preset = preset; + next.engine_env = env; + let unchanged = next.profile == config.profile + && next.preset == config.preset + && next.engine_env == config.engine_env; + Planned { + config: next, + resources, + unchanged, + } +} + +/// The profile the request starts from: the recorded base (or the profile in force), with the settings and the budget +/// applied. +fn requested_base( + config: &RunConfig, + request: &Request, + preset: Preset, +) -> Result { let mut base = match &config.base_profile { Some(base) => base.clone(), None if config.preset == Preset::Workstation && preset != Preset::Workstation => { @@ -37,15 +100,17 @@ pub fn plan( base.min_vram_free_mib = base.min_vram_free_mib.map(|need| need.min(gib * 1024)); } base.validate()?; - let mut profile = base.clone(); + Ok(base) +} - let seen = if archive_resident { - resources::with_resident_bytes(facts, profile.memfd_bytes()) - } else { - facts.clone() - }; - let gpu = gpu_of(&seen, config.gpu).cloned(); - let resources = resources::compute(&seen, gpu.as_ref(), &profile, preset); +/// What the host leaves to the engine must hold the request: no problems, the budget asked for, the form of the +/// archive. +fn check_resources( + resources: &ResourcePlan, + request: &Request, + preset: Preset, + archive_resident: bool, +) -> Result<(), String> { if !resources.problems.is_empty() { return Err(resources.problems.join("; ")); } @@ -65,44 +130,26 @@ pub fn plan( preset.as_str() )); } - let mut env = config.engine_env.clone(); - env.remove(CPU_WORKERS_ENV); - resources::apply( - &resources, - &mut profile, - &mut env, - request.gpu_budget_gib.is_some(), - ); - profile.validate()?; - if let Some(gpu) = &gpu { - let budget_mib = profile.gpu_budget_bytes / MIB; - if budget_mib > gpu.vram_total_mib { - return Err(format!( - "GPU memory: a budget of {} MiB does not fit the {} MiB of {}", - budget_mib, gpu.vram_total_mib, gpu.name - )); - } - let need = profile.min_vram_free_mib.unwrap_or(budget_mib); - if gpu.vram_free_mib < need { - return Err(format!( - "GPU memory: {} MiB free but the engine needs {need} MiB (another process holds VRAM; see nvidia-smi)", - gpu.vram_free_mib - )); - } + Ok(()) +} + +/// The budget of the profile must fit the card and what is free on it. +fn check_gpu_fits(profile: &Profile, gpu: &Gpu) -> Result<(), String> { + let budget_mib = profile.gpu_budget_bytes / MIB; + if budget_mib > gpu.vram_total_mib { + return Err(format!( + "GPU memory: a budget of {} MiB does not fit the {} MiB of {}", + budget_mib, gpu.vram_total_mib, gpu.name + )); } - let mut next = config.clone(); - next.profile = profile; - next.base_profile = Some(base); - next.preset = preset; - next.engine_env = env; - let unchanged = next.profile == config.profile - && next.preset == config.preset - && next.engine_env == config.engine_env; - Ok(Planned { - config: next, - resources, - unchanged, - }) + let need = profile.min_vram_free_mib.unwrap_or(budget_mib); + if gpu.vram_free_mib < need { + return Err(format!( + "GPU memory: {} MiB free but the engine needs {need} MiB (another process holds VRAM; see nvidia-smi)", + gpu.vram_free_mib + )); + } + Ok(()) } /// `--persist` without a restart: the live engine already runs with `settings`; fold them into the configuration. Returns diff --git a/crates/deploy/src/reconfigure/settings.rs b/crates/deploy/src/reconfigure/settings.rs index 34761996..45b92295 100644 --- a/crates/deploy/src/reconfigure/settings.rs +++ b/crates/deploy/src/reconfigure/settings.rs @@ -40,101 +40,9 @@ pub fn apply_settings( } } for (name, value) in settings { - match name.as_str() { - "context_tokens" => { - let tokens = whole(value, name)?; - if !(1..=262_144).contains(&tokens) { - return Err("context_tokens must be 1..=262144".into()); - } - next.context_tokens = tokens as u32; - } - "prefill_capacity" => { - let chunk = whole(value, name)?; - if !PREFILL_CAPACITIES.contains(&chunk) { - return Err(format!( - "prefill_capacity must be one of {PREFILL_CAPACITIES:?}" - )); - } - next.prefill_capacity = Some(chunk as u32); - } - "kv_resident" => { - let cells = whole(value, name)?; - if cells != 0 && !(20_480..=u64::from(u32::MAX)).contains(&cells) { - return Err( - "kv_resident must be 0 (the whole context) or at least 20480".into(), - ); - } - next.kv_resident = Some(cells as u32); - } - "prefix_cache_mib" => { - let text = match value { - Value::String(text) => text.trim().to_ascii_lowercase(), - Value::Number(number) => number.to_string(), - _ => { - return Err( - "prefix_cache_mib must be \"auto\", \"off\" or a size in MiB".into(), - ); - } - }; - next.memory.prefix_cache_mib = Some(match text.as_str() { - "auto" => "auto".to_owned(), - "off" | "0" => "0".to_owned(), - mib => mib - .parse::() - .ok() - .filter(|m| *m <= 1 << 30) - .ok_or("prefix_cache_mib must be \"auto\", \"off\" or a size in MiB")? - .to_string(), - }); - } - "prefix_cache_tail" => { - let tail = value - .as_str() - .filter(|t| matches!(*t, "off" | "prompt" | "reply")); - next.memory.prefix_cache_tail = Some( - tail.ok_or("prefix_cache_tail must be off, prompt or reply")? - .to_owned(), - ); - enable_prefix_cache(&mut next); - } - "prefix_cache_block" => { - let block = whole(value, name)?; - if block % 256 != 0 || block > 8192 { - return Err("prefix_cache_block must be a multiple of 256, at most 8192 (0 = the prefill chunk)".into()); - } - next.memory.prefix_cache_block = Some(block as u32); - enable_prefix_cache(&mut next); - } - "prefix_retention_min" => { - next.memory.prefix_retention_min = Some(whole(value, name)?); - enable_prefix_cache(&mut next); - } - "cpu_workers" => { - let workers = whole(value, name)?; - if !(1..=64).contains(&workers) { - return Err("cpu_workers must be 1..=64".into()); - } - next.engine_env - .insert(CPU_WORKERS_ENV.to_owned(), workers.to_string()); - } - "spec_min_p" => { - let p = value - .as_f64() - .filter(|p| p.is_finite() && (0.0..=1.0).contains(p)); - next.spec_min_p = Some(p.ok_or("spec_min_p must be within 0..=1")?); - } - _ => unreachable!("checked above"), - } - } - let chunk = next.prefill_capacity.unwrap_or(DEFAULT_PREFILL_CHUNK); - if next.memory.prefix_cache_on() - && let Some(block) = next.memory.prefix_cache_block - && block > chunk - { - return Err(format!( - "prefix_cache_block {block} is larger than the prefill chunk {chunk}" - )); + apply_setting(&mut next, name, value)?; } + check_block_fits_chunk(&next)?; next.validate()?; let changed = SETTINGS .iter() @@ -148,6 +56,134 @@ pub fn apply_settings( Ok(changed) } +fn apply_setting(next: &mut Profile, name: &str, value: &Value) -> Result<(), String> { + match name { + "context_tokens" => set_context_tokens(next, value, name), + "prefill_capacity" => set_prefill_capacity(next, value, name), + "kv_resident" => set_kv_resident(next, value, name), + "prefix_cache_mib" => set_prefix_cache_mib(next, value), + "prefix_cache_tail" => set_prefix_cache_tail(next, value), + "prefix_cache_block" => set_prefix_cache_block(next, value, name), + "prefix_retention_min" => set_prefix_retention_min(next, value, name), + "cpu_workers" => set_cpu_workers(next, value, name), + "spec_min_p" => set_spec_min_p(next, value), + _ => unreachable!("checked above"), + } +} + +fn set_prefix_retention_min(next: &mut Profile, value: &Value, name: &str) -> Result<(), String> { + next.memory.prefix_retention_min = Some(whole(value, name)?); + enable_prefix_cache(next); + Ok(()) +} + +fn set_context_tokens(next: &mut Profile, value: &Value, name: &str) -> Result<(), String> { + let tokens = whole(value, name)?; + if !(1..=262_144).contains(&tokens) { + return Err("context_tokens must be 1..=262144".into()); + } + next.context_tokens = tokens as u32; + Ok(()) +} + +fn set_prefill_capacity(next: &mut Profile, value: &Value, name: &str) -> Result<(), String> { + let chunk = whole(value, name)?; + if !PREFILL_CAPACITIES.contains(&chunk) { + return Err(format!( + "prefill_capacity must be one of {PREFILL_CAPACITIES:?}" + )); + } + next.prefill_capacity = Some(chunk as u32); + Ok(()) +} + +fn set_kv_resident(next: &mut Profile, value: &Value, name: &str) -> Result<(), String> { + let cells = whole(value, name)?; + if cells != 0 && !(20_480..=u64::from(u32::MAX)).contains(&cells) { + return Err("kv_resident must be 0 (the whole context) or at least 20480".into()); + } + next.kv_resident = Some(cells as u32); + Ok(()) +} + +fn set_prefix_cache_mib(next: &mut Profile, value: &Value) -> Result<(), String> { + let text = match value { + Value::String(text) => text.trim().to_ascii_lowercase(), + Value::Number(number) => number.to_string(), + _ => { + return Err("prefix_cache_mib must be \"auto\", \"off\" or a size in MiB".into()); + } + }; + next.memory.prefix_cache_mib = Some(match text.as_str() { + "auto" => "auto".to_owned(), + "off" | "0" => "0".to_owned(), + mib => mib + .parse::() + .ok() + .filter(|m| *m <= 1 << 30) + .ok_or("prefix_cache_mib must be \"auto\", \"off\" or a size in MiB")? + .to_string(), + }); + Ok(()) +} + +fn set_prefix_cache_tail(next: &mut Profile, value: &Value) -> Result<(), String> { + let tail = value + .as_str() + .filter(|t| matches!(*t, "off" | "prompt" | "reply")); + next.memory.prefix_cache_tail = Some( + tail.ok_or("prefix_cache_tail must be off, prompt or reply")? + .to_owned(), + ); + enable_prefix_cache(next); + Ok(()) +} + +fn set_prefix_cache_block(next: &mut Profile, value: &Value, name: &str) -> Result<(), String> { + let block = whole(value, name)?; + if block % 256 != 0 || block > 8192 { + return Err( + "prefix_cache_block must be a multiple of 256, at most 8192 (0 = the prefill chunk)" + .into(), + ); + } + next.memory.prefix_cache_block = Some(block as u32); + enable_prefix_cache(next); + Ok(()) +} + +fn set_cpu_workers(next: &mut Profile, value: &Value, name: &str) -> Result<(), String> { + let workers = whole(value, name)?; + if !(1..=64).contains(&workers) { + return Err("cpu_workers must be 1..=64".into()); + } + next.engine_env + .insert(CPU_WORKERS_ENV.to_owned(), workers.to_string()); + Ok(()) +} + +fn set_spec_min_p(next: &mut Profile, value: &Value) -> Result<(), String> { + let p = value + .as_f64() + .filter(|p| p.is_finite() && (0.0..=1.0).contains(p)); + next.spec_min_p = Some(p.ok_or("spec_min_p must be within 0..=1")?); + Ok(()) +} + +/// A prefix-cache block larger than the prefill chunk cannot be filled. +fn check_block_fits_chunk(next: &Profile) -> Result<(), String> { + let chunk = next.prefill_capacity.unwrap_or(DEFAULT_PREFILL_CHUNK); + if next.memory.prefix_cache_on() + && let Some(block) = next.memory.prefix_cache_block + && block > chunk + { + return Err(format!( + "prefix_cache_block {block} is larger than the prefill chunk {chunk}" + )); + } + Ok(()) +} + /// One runtime setting of a profile, for comparison and display. pub(super) fn setting_view(profile: &Profile, name: &str) -> Value { match name { diff --git a/crates/deploy/src/reconfigure/tests/planning.rs b/crates/deploy/src/reconfigure/tests/planning.rs index 67e31455..c296d9ee 100644 --- a/crates/deploy/src/reconfigure/tests/planning.rs +++ b/crates/deploy/src/reconfigure/tests/planning.rs @@ -36,10 +36,15 @@ fn a_budget_change_is_planned_against_the_host_and_keeps_everything_else() { args.contains(&format!("--gpu-budget {}", 24 * GIB)), "{args}" ); - // the same budget again is a no-op, not a five-minute restart - // (the shipped 5090 budget is 31,299 MiB, which a whole-GiB request cannot restate: the no-op is checked on the 24 GiB just planned) + check_same_budget_is_a_noop(&planned.config); +} + +/// The same budget again is a no-op, not a five-minute restart +/// (the shipped 5090 budget is 31,299 MiB, which a whole-GiB request cannot restate: the no-op is checked on the 24 +/// GiB just planned). +fn check_same_budget_is_a_noop(planned: &RunConfig) { let same = plan( - &planned.config, + planned, &request(Some(24), None, json!({})), &big_host(), true, diff --git a/crates/deploy/src/reconfigure/tests/recording.rs b/crates/deploy/src/reconfigure/tests/recording.rs index 494055af..ca0ad3c6 100644 --- a/crates/deploy/src/reconfigure/tests/recording.rs +++ b/crates/deploy/src/reconfigure/tests/recording.rs @@ -36,6 +36,10 @@ fn recording_settings_updates_the_profile_and_the_base_and_lets_an_explicit_work .map(String::as_str), Some("5") ); + check_invalid_leaves_alone_and_preset_keeps_setting(config); +} + +fn check_invalid_leaves_alone_and_preset_keeps_setting(mut config: RunConfig) { // an invalid document leaves the configuration alone let before = config.clone(); assert!( @@ -67,13 +71,7 @@ fn recording_settings_updates_the_profile_and_the_base_and_lets_an_explicit_work #[test] fn the_request_and_answer_files_round_trip_and_a_request_runs_once() { - let root = std::env::temp_dir().join(format!("leleka-reconf-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&root); - let dirs = Dirs { - prefix: root.join("p"), - state: root.join("s"), - assets: root.join("a"), - }; + let (root, dirs) = scratch_dirs("leleka-reconf"); let paths = dirs.paths(); std::fs::create_dir_all(paths.run_dir()).unwrap(); assert!(take_request(&paths).is_none()); @@ -90,10 +88,15 @@ fn the_request_and_answer_files_round_trip_and_a_request_runs_once() { ); assert_eq!(take_request(&paths).unwrap().unwrap(), asked); assert!(take_request(&paths).is_none(), "the file is consumed"); + check_corrupt_request_and_outcome(&paths, &asked); + let _ = std::fs::remove_dir_all(&root); +} + +fn check_corrupt_request_and_outcome(paths: &Paths, asked: &Request) { // a corrupt request is reported, not retried forever std::fs::write(paths.reconfigure_request(), "{not json").unwrap(); assert!( - take_request(&paths) + take_request(paths) .unwrap() .unwrap_err() .contains("invalid") @@ -106,21 +109,26 @@ fn the_request_and_answer_files_round_trip_and_a_request_runs_once() { effective: None, persisted: false, }; - write_outcome(&paths, &outcome).unwrap(); - assert_eq!(read_outcome(&paths, &asked.id), Some(outcome)); - assert_eq!(read_outcome(&paths, "other"), None); - let _ = std::fs::remove_dir_all(&root); + write_outcome(paths, &outcome).unwrap(); + assert_eq!(read_outcome(paths, &asked.id), Some(outcome)); + assert_eq!(read_outcome(paths, "other"), None); } -#[test] -fn persisting_writes_a_private_config_that_reads_back_and_refreshes_the_api_context() { - let root = std::env::temp_dir().join(format!("leleka-persist-{}", std::process::id())); +/// A fresh scratch directory with the three directories of an installation under it. +fn scratch_dirs(prefix: &str) -> (std::path::PathBuf, Dirs) { + let root = std::env::temp_dir().join(format!("{prefix}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&root); let dirs = Dirs { prefix: root.join("p"), state: root.join("s"), assets: root.join("a"), }; + (root, dirs) +} + +#[test] +fn persisting_writes_a_private_config_that_reads_back_and_refreshes_the_api_context() { + let (root, dirs) = scratch_dirs("leleka-persist"); let paths = dirs.paths(); std::fs::create_dir_all(paths.run_dir()).unwrap(); let mut config = server_config(); @@ -142,6 +150,11 @@ fn persisting_writes_a_private_config_that_reads_back_and_refreshes_the_api_cont back.profile.memory.prefix_cache_tail.as_deref(), Some("prompt") ); + check_strata_and_mode(&paths); + let _ = std::fs::remove_dir_all(&root); +} + +fn check_strata_and_mode(paths: &Paths) { let strata: Value = serde_json::from_str(&std::fs::read_to_string(paths.strata_config()).unwrap()).unwrap(); assert_eq!(strata["runtime"]["max_context"], 100000); @@ -155,7 +168,6 @@ fn persisting_writes_a_private_config_that_reads_back_and_refreshes_the_api_cont & 0o777; assert_eq!(mode, 0o600); } - let _ = std::fs::remove_dir_all(&root); } #[test] diff --git a/crates/deploy/src/reconfigure/tests/settings_ranges.rs b/crates/deploy/src/reconfigure/tests/settings_ranges.rs index a008cf1f..850f5cdd 100644 --- a/crates/deploy/src/reconfigure/tests/settings_ranges.rs +++ b/crates/deploy/src/reconfigure/tests/settings_ranges.rs @@ -21,6 +21,18 @@ fn runtime_settings_become_profile_fields_with_the_engines_ranges() { ] { assert!(changed.iter().any(|c| c == name), "{name} in {changed:?}"); } + check_profile_fields(&profile); + // the same document again changes nothing + assert!( + apply_settings(&mut profile, settings.as_object().unwrap()) + .unwrap() + .is_empty() + ); + // and they reach the engine as flags and environment + check_engine_flags(profile); +} + +fn check_profile_fields(profile: &Profile) { assert_eq!( ( profile.context_tokens, @@ -43,13 +55,9 @@ fn runtime_settings_become_profile_fields_with_the_engines_ranges() { Some("6") ); assert_eq!(profile.spec_min_p, Some(0.5)); - // the same document again changes nothing - assert!( - apply_settings(&mut profile, settings.as_object().unwrap()) - .unwrap() - .is_empty() - ); - // and they reach the engine as flags and environment +} + +fn check_engine_flags(profile: Profile) { let config = RunConfig::new( &Dirs { prefix: "/p".into(), @@ -65,6 +73,10 @@ fn runtime_settings_become_profile_fields_with_the_engines_ranges() { profile, BTreeMap::new(), ); + check_flags_and_environment(&config); +} + +fn check_flags_and_environment(config: &RunConfig) { let args = config.engine_args(crate::config::KarArg::Fd).join(" "); assert!( args.contains("--context-tokens 131072") diff --git a/crates/deploy/src/resources.rs b/crates/deploy/src/resources.rs index 4b96e768..031a88b8 100644 --- a/crates/deploy/src/resources.rs +++ b/crates/deploy/src/resources.rs @@ -133,8 +133,17 @@ impl ResourcePlan { self.vram_free_after_mib .map_or(String::new(), |free| format!(", ~{} MiB stay free", free)) )); + out.push_str(&self.host_ram_line(facts)); + for warning in &self.warnings { + out.push_str(&format!(" warning {warning}\n")); + } + out + } + + /// The line about the host RAM: the floors the caches shed at, or what stays free with the engine defaults. + fn host_ram_line(&self, facts: &Facts) -> String { match (self.ram_floors_mib, self.ram_expected_free_after_bytes) { - (Some((soft, hard)), after) => out.push_str(&format!( + (Some((soft, hard)), after) => format!( " host ram caches shed below {} MiB available, requests refused below {} MiB{}\n", soft, hard, @@ -142,18 +151,14 @@ impl ResourcePlan { "; ~{} free after the start", gib_text(b) )) - )), - (None, Some(after)) => out.push_str(&format!( + ), + (None, Some(after)) => format!( " host ram engine defaults; ~{} of {} free after the start\n", gib_text(after), gib_text(facts.memory.total) - )), - (None, None) => {} + ), + (None, None) => String::new(), } - for warning in &self.warnings { - out.push_str(&format!(" warning {warning}\n")); - } - out } } diff --git a/crates/deploy/src/resources/sizing.rs b/crates/deploy/src/resources/sizing.rs index c74109f3..649d66b3 100644 --- a/crates/deploy/src/resources/sizing.rs +++ b/crates/deploy/src/resources/sizing.rs @@ -282,47 +282,60 @@ pub fn apply( profile.memory.hard_floor_mib = raised(profile.memory.hard_floor_mib, hard); } if let Some(resident) = plan.mapped_resident_gib { - // `kar_source: none` has no archive to map: it stays none (the PLE table is read from the shard either way) - if profile.kar_source != KarSource::None { - profile.kar_source = KarSource::File; - profile.memfd_extents = crate::profile::MemfdExtents::Full; - } - profile.expert_source = ExpertSource::Mapped; - profile.memory.resident_budget_gib.get_or_insert(resident); - profile.memory.lock = Some("off".into()); - profile.memory.heal = Some(false); - profile.min_ram_total_bytes = profile.min_ram_total_bytes.min(16 * GIB); - profile.min_ram_available_bytes = profile - .min_ram_available_bytes - .min(MAPPED_MIN_AVAILABLE_BYTES); + apply_mapped_form(profile, resident); } if let Some(resident) = plan.resident_budget_gib { profile.memory.resident_budget_gib.get_or_insert(resident); } - // The prompt chunk borrows its buffers from the expert cache, so a smaller VRAM budget (the workstation preset's, or `--gpu-budget-gib`) - // that cannot hold the profile's chunk would stop the engine from starting: lower the chunk (and the grid with it) to what the budget carries. - if let Some(chunk) = profile.prefill_capacity { - let fits = prefill_capacity_for_budget(profile.gpu_budget_bytes); - if chunk > fits { - profile.prefill_capacity = Some(fits); - if let Some(block) = profile.memory.prefix_cache_block - && block > fits - { - profile.memory.prefix_cache_block = Some(fits); - } - } - } + fit_prefill_chunk(profile); if let Some((soft, hard)) = plan.windows_floors_mib { - // only ever lowered, and only when the profile asks for more than the Windows values - if profile - .memory - .soft_floor_mib - .is_none_or(|current| current > soft) + lower_windows_floors(profile, soft, hard); + } + apply_environment(plan, profile, engine_env); +} + +/// The file-backed form: the archive is mapped, the experts are mapped, the RAM floors of a host that cannot hold both. +fn apply_mapped_form(profile: &mut Profile, resident: u32) { + // `kar_source: none` has no archive to map: it stays none (the PLE table is read from the shard either way) + if profile.kar_source != KarSource::None { + profile.kar_source = KarSource::File; + profile.memfd_extents = crate::profile::MemfdExtents::Full; + } + profile.expert_source = ExpertSource::Mapped; + profile.memory.resident_budget_gib.get_or_insert(resident); + profile.memory.lock = Some("off".into()); + profile.memory.heal = Some(false); + profile.min_ram_total_bytes = profile.min_ram_total_bytes.min(16 * GIB); + profile.min_ram_available_bytes = profile + .min_ram_available_bytes + .min(MAPPED_MIN_AVAILABLE_BYTES); +} + +/// The prompt chunk borrows its buffers from the expert cache, so a smaller VRAM budget (the workstation preset's, or +/// `--gpu-budget-gib`) +/// that cannot hold the profile's chunk would stop the engine from starting: lower the chunk (and the grid with it) +/// to what the budget carries. +fn fit_prefill_chunk(profile: &mut Profile) { + let Some(chunk) = profile.prefill_capacity else { + return; + }; + let fits = prefill_capacity_for_budget(profile.gpu_budget_bytes); + if chunk > fits { + profile.prefill_capacity = Some(fits); + if let Some(block) = profile.memory.prefix_cache_block + && block > fits { - profile.memory.soft_floor_mib = Some(soft); - profile.memory.hard_floor_mib = Some(hard); + profile.memory.prefix_cache_block = Some(fits); } } +} + +/// The working-set and worker count the plan asks for, unless the profile already names them. +fn apply_environment( + plan: &ResourcePlan, + profile: &Profile, + engine_env: &mut BTreeMap, +) { if let Some(gib) = plan.mapped_working_set_gib && !profile.engine_env.contains_key(MAPPED_WORKING_SET_ENV) { @@ -334,3 +347,15 @@ pub fn apply( engine_env.insert(CPU_WORKERS_ENV.to_owned(), workers.to_string()); } } + +/// The Windows RAM floors: only ever lowered, and only when the profile asks for more than the Windows values. +fn lower_windows_floors(profile: &mut Profile, soft: u64, hard: u64) { + if profile + .memory + .soft_floor_mib + .is_none_or(|current| current > soft) + { + profile.memory.soft_floor_mib = Some(soft); + profile.memory.hard_floor_mib = Some(hard); + } +} diff --git a/crates/deploy/src/resources/tests/ram_fit.rs b/crates/deploy/src/resources/tests/ram_fit.rs index e915e074..58a4ba81 100644 --- a/crates/deploy/src/resources/tests/ram_fit.rs +++ b/crates/deploy/src/resources/tests/ram_fit.rs @@ -20,6 +20,11 @@ fn a_sparse_memfd_fits_a_host_the_full_copy_does_not_and_a_resident_one_is_credi Some(80 * GIB - (SPARSE_MEMFD_BYTES_ESTIMATE + ENGINE_FIXED_RESIDENT_BYTES)), "the footprint is the sparse memfd plus the engine's own memory" ); + check_resident_memfd_is_credited_by_its_own_size(&sparse); + check_fallback_drops_the_sparse_switch(&sparse, &gpu); +} + +fn check_resident_memfd_is_credited_by_its_own_size(sparse: &Profile) { // a resident sparse memfd is credited with its own size, not the archive's let resident = host(32, 121, 66); let credited = with_resident_bytes(&resident, sparse.memfd_bytes()); @@ -31,10 +36,13 @@ fn a_sparse_memfd_fits_a_host_the_full_copy_does_not_and_a_resident_one_is_credi with_resident_archive(&resident).memory.available, 66 * GIB + ARCHIVE_BYTES ); +} + +fn check_fallback_drops_the_sparse_switch(sparse: &Profile, gpu: &crate::facts::Gpu) { // a plan that falls back to the mapped form is a different machine: the sparse switch is dropped with the memfd let tiny = host(32, 121, 2); let mut profile = sparse.clone(); - let fallback = compute(&tiny, Some(&gpu), &profile, Preset::Dedicated); + let fallback = compute(&tiny, Some(gpu), &profile, Preset::Dedicated); assert!(fallback.mapped_resident_gib.is_some()); apply(&fallback, &mut profile, &mut BTreeMap::new(), false); assert_eq!( diff --git a/crates/deploy/src/resources/tests/windows_presets.rs b/crates/deploy/src/resources/tests/windows_presets.rs index e0d39fe3..e6c1517b 100644 --- a/crates/deploy/src/resources/tests/windows_presets.rs +++ b/crates/deploy/src/resources/tests/windows_presets.rs @@ -26,11 +26,15 @@ fn the_windows_file_backed_form_sizes_its_page_locked_experts_from_the_free_ram( (Some(3072), Some(1536)), "Windows lowers the Linux floors of the laptop profile" ); + check_explicit_value_wins_and_squeezed_host(&windows); +} + +fn check_explicit_value_wins_and_squeezed_host(windows: &Facts) { // an explicit profile value wins, and Linux hosts are left alone let mut explicit = laptop(); explicit.memory.resident_budget_gib = Some(16); assert_eq!( - compute(&windows, None, &explicit, Preset::Dedicated).resident_budget_gib, + compute(windows, None, &explicit, Preset::Dedicated).resident_budget_gib, None ); assert_eq!( @@ -79,8 +83,12 @@ fn the_windows_workstation_preset_leaves_the_desktop_more_and_keeps_its_floors() env.get(MAPPED_WORKING_SET_ENV).map(String::as_str), Some("8") ); + check_dedicated_preset_is_unchanged(&windows); +} + +fn check_dedicated_preset_is_unchanged(windows: &Facts) { // the dedicated preset on the same host is unchanged - let dedicated = compute(&windows, None, &laptop(), Preset::Dedicated); + let dedicated = compute(windows, None, &laptop(), Preset::Dedicated); assert_eq!( ( dedicated.resident_budget_gib, diff --git a/crates/deploy/src/sealed/exec_arguments.rs b/crates/deploy/src/sealed/exec_arguments.rs index 0d95175b..68c56419 100644 --- a/crates/deploy/src/sealed/exec_arguments.rs +++ b/crates/deploy/src/sealed/exec_arguments.rs @@ -26,37 +26,27 @@ pub fn archive_serve_extents( .map_err(|e| format!("cannot derive the sparse extents of {}: {e}", kar.display())) } +const SEAL_EXEC_USAGE: &str = concat!( + "usage: leleka seal-exec --file PATH [--expect-bytes N] [--sparse-ple] ", + "-- COMMAND ARG... ({FD} marks the sealed descriptor)" +); + /// `--file PATH [--expect-bytes N] [--sparse-ple] -- COMMAND ARG...` pub fn parse_seal_exec(args: &[String]) -> Result { - let usage = "usage: leleka seal-exec --file PATH [--expect-bytes N] [--sparse-ple] -- COMMAND ARG... ({FD} marks the sealed descriptor)"; + let usage = SEAL_EXEC_USAGE; let (mut file, mut expect_bytes, mut sparse_ple) = (None, None, false); let mut i = 0; while i < args.len() { match args[i].as_str() { "--" => break, - "--file" => { - i += 1; - file = Some(std::path::PathBuf::from( - args.get(i).filter(|v| !v.is_empty()).ok_or(usage)?, - )); - } - "--expect-bytes" => { - i += 1; - expect_bytes = Some( - args.get(i) - .and_then(|v| v.parse::().ok()) - .ok_or(usage)?, - ); - } + "--file" => file = Some(path_value(args, &mut i)?), + "--expect-bytes" => expect_bytes = Some(bytes_value(args, &mut i)?), "--sparse-ple" => sparse_ple = true, _ => return Err(usage.into()), } i += 1; } - let command: Vec = args.get(i + 1..).unwrap_or_default().to_vec(); - if args.get(i).map(String::as_str) != Some("--") || command.is_empty() { - return Err(usage.into()); - } + let command = seal_command(args, i)?; Ok(SealExecPlan { file: file.ok_or(usage)?, expect_bytes, @@ -65,6 +55,32 @@ pub fn parse_seal_exec(args: &[String]) -> Result { }) } +/// The value of `--file`: the next argument, which must not be empty. +fn path_value(args: &[String], i: &mut usize) -> Result { + *i += 1; + args.get(*i) + .filter(|v| !v.is_empty()) + .map(std::path::PathBuf::from) + .ok_or_else(|| SEAL_EXEC_USAGE.to_owned()) +} + +/// The value of `--expect-bytes`: the next argument, a number of bytes. +fn bytes_value(args: &[String], i: &mut usize) -> Result { + *i += 1; + args.get(*i) + .and_then(|v| v.parse::().ok()) + .ok_or_else(|| SEAL_EXEC_USAGE.to_owned()) +} + +/// The command after the `--` at `args[i]`, which must be there and not empty. +fn seal_command(args: &[String], i: usize) -> Result, String> { + let command: Vec = args.get(i + 1..).unwrap_or_default().to_vec(); + if args.get(i).map(String::as_str) != Some("--") || command.is_empty() { + return Err(SEAL_EXEC_USAGE.into()); + } + Ok(command) +} + /// Replace every `{FD}` in `args`. pub fn substitute(args: &[String], number: i32) -> Vec { args.iter() diff --git a/crates/deploy/src/sealed/linux.rs b/crates/deploy/src/sealed/linux.rs index 33fb013b..a63cb5d8 100644 --- a/crates/deploy/src/sealed/linux.rs +++ b/crates/deploy/src/sealed/linux.rs @@ -8,16 +8,16 @@ use std::{ fs::File, os::{ fd::{AsFd, IntoRawFd}, - unix::{fs::FileExt, process::CommandExt}, + unix::process::CommandExt, }, path::Path, process::Command, - sync::{ - Mutex, - atomic::{AtomicBool, AtomicU64, Ordering}, - }, }; +mod copy; +#[cfg(test)] +use std::os::unix::fs::FileExt; + pub const SEALS: SealFlags = SealFlags::from_bits_truncate( SealFlags::WRITE.bits() | SealFlags::GROW.bits() @@ -116,19 +116,51 @@ fn check_extents(extents: &[Extent], total: u64) -> Result<(), String> { Ok(()) } -fn seal_ranges( - path: &Path, - expect_bytes: Option, - extents: Option<&[Extent]>, - progress: &mut dyn FnMut(u64, u64), -) -> Result< +/// A sealed memfd, the identity of the file it was copied from and how the copy was read. +type SealedArchive = Result< ( File, Option, leleka_model_format::bulk_read::Report, ), String, -> { +>; + +fn seal_ranges( + path: &Path, + expect_bytes: Option, + extents: Option<&[Extent]>, + progress: &mut dyn FnMut(u64, u64), +) -> SealedArchive { + let (source, metadata) = open_archive(path, expect_bytes)?; + let identity_before = FileIdentity::of(&metadata); + let total = metadata.len(); + let whole = [Extent::new(0, total)]; + let ranges: &[Extent] = match extents { + Some(extents) => { + check_extents(extents, total)?; + extents + } + None => &whole, + }; + let want = copy::ranges_len(ranges); + let memory = create_memfd(total)?; + let report = copy::copy_ranges(&source, &memory, ranges, &mut *progress)?; + let identity_after = source.metadata().ok().and_then(|m| FileIdentity::of(&m)); + if identity_before != identity_after { + return Err("the archive changed while it was being copied".into()); + } + seal_memfd(&memory)?; + progress(want, want); + let report = report.ok_or("the archive copy did not report")?; + Ok((memory, identity_before, report)) +} + +/// The archive file, which must be a regular file of the expected length. +fn open_archive( + path: &Path, + expect_bytes: Option, +) -> Result<(File, std::fs::Metadata), String> { let source = File::open(path).map_err(|e| format!("cannot open {}: {e}", path.display()))?; let metadata = source .metadata() @@ -144,120 +176,32 @@ fn seal_ranges( metadata.len() )); } - let identity_before = FileIdentity::of(&metadata); - let total = metadata.len(); - let whole = [Extent::new(0, total)]; - let ranges: &[Extent] = match extents { - Some(extents) => { - check_extents(extents, total)?; - extents - } - None => &whole, - }; - let want: u64 = ranges.iter().map(|r| r.len).sum(); + Ok((source, metadata)) +} + +fn create_memfd(total: u64) -> Result { let fd = memfd_create( "leleka-sealed-archive", MemfdFlags::ALLOW_SEALING | MemfdFlags::CLOEXEC, ) .map_err(|e| format!("memfd_create failed: {e}"))?; let memory = File::from(fd); - let report: Mutex> = Mutex::new(None); // The final size first (before the GROW seal exists), so that workers write disjoint ranges. memory .set_len(total) .map_err(|e| format!("cannot size the memfd (out of memory?): {e}"))?; - // Large blocks on many threads (O_DIRECT where the file system allows it): the device sees a deep queue - // instead of one 128 KiB readahead window at a time, and what is copied never enters the page cache, so the - // memfd is the only copy of it in RAM (a sparse copy reads each of its extents the same way and nothing else). - let plan = leleka_model_format::bulk_read::Plan::from_env(); - let copied = AtomicU64::new(0); - let finished = AtomicBool::new(false); - let failure: Mutex> = Mutex::new(None); - std::thread::scope(|scope| { - scope.spawn(|| { - // Set on every exit, a panic included, so that the progress loop below ends. - struct Finished<'a>(&'a AtomicBool); - impl Drop for Finished<'_> { - fn drop(&mut self) { - self.0.store(true, Ordering::Release); - } - } - let _finished = Finished(&finished); - let mut strategy = None; - let mut elapsed = std::time::Duration::ZERO; - for range in ranges { - let outcome = leleka_model_format::bulk_read::for_each_chunk( - &source, - range.offset, - range.len, - plan, - |offset, data| { - memory.write_all_at(data, offset).map_err(|e| { - std::io::Error::other(format!( - "write to memfd failed (out of memory?): {e}" - )) - })?; - copied.fetch_add(data.len() as u64, Ordering::Relaxed); - Ok(()) - }, - ); - match outcome { - Ok(done) => { - strategy = Some(done.strategy); - elapsed += done.elapsed; - } - Err(e) => { - if let Ok(mut f) = failure.lock() { - f.get_or_insert(format!("read failed: {e}")); - } - return; - } - } - } - // No extents at all is a valid (empty) sparse copy: nothing was read. - let strategy = strategy.unwrap_or(leleka_model_format::bulk_read::Strategy::Plain); - if let Ok(mut slot) = report.lock() { - *slot = Some(leleka_model_format::bulk_read::Report { - strategy, - bytes: want, - elapsed, - }); - } - }); - let mut reported = 0u64; - while !finished.load(Ordering::Acquire) { - std::thread::sleep(std::time::Duration::from_millis(100)); - let now = copied.load(Ordering::Relaxed); - if now - reported >= 4 << 30 { - reported = now; - progress(now, want); - } - } - }); - if let Some(message) = failure.into_inner().ok().flatten() { - return Err(message); - } - if copied.load(Ordering::Relaxed) != want { - return Err("the archive changed while it was being copied".into()); - } - let identity_after = source.metadata().ok().and_then(|m| FileIdentity::of(&m)); - if identity_before != identity_after { - return Err("the archive changed while it was being copied".into()); - } - fcntl_add_seals(&memory, SEALS).map_err(|e| format!("sealing failed: {e}"))?; - if !fcntl_get_seals(&memory) + Ok(memory) +} + +fn seal_memfd(memory: &File) -> Result<(), String> { + fcntl_add_seals(memory, SEALS).map_err(|e| format!("sealing failed: {e}"))?; + if !fcntl_get_seals(memory) .map_err(|e| format!("cannot read seals: {e}"))? .contains(SEALS) { return Err("the kernel did not apply every seal".into()); } - progress(want, want); - let report = report - .into_inner() - .ok() - .flatten() - .ok_or("the archive copy did not report")?; - Ok((memory, identity_before, report)) + Ok(()) } /// A descriptor inherited from the parent (a holder, for example), reopened through `/proc/self/fd/N` as an @@ -329,45 +273,61 @@ pub fn exec_inherit(args: &[String]) -> Result { pub fn seal_exec(args: &[String]) -> Result { let plan = super::parse_seal_exec(args)?; let started = std::time::Instant::now(); - let mut progress = |done: u64, total: u64| { + let progress = |done: u64, total: u64| { eprintln!( "leleka seal-exec: {:.1} of {:.1} GiB", done as f64 / 1073741824.0, total as f64 / 1073741824.0 ); }; - let (memory, extents) = if plan.sparse_ple { - let expect = plan - .expect_bytes - .ok_or("--sparse-ple needs --expect-bytes (the pinned archive length)")?; - let extents = super::archive_serve_extents(&plan.file, expect)?; - let (memory, _) = seal_extents(&plan.file, Some(expect), &extents, &mut progress)?; - (memory, Some(extents)) - } else { - ( - seal_file(&plan.file, plan.expect_bytes, &mut progress)?, - None, - ) - }; + let (memory, extents) = seal_for_exec(&plan, progress)?; let moved = rustix::io::dup(memory.as_fd()) .map_err(|e| format!("cannot duplicate the sealed descriptor: {e}"))?; let number = moved.into_raw_fd(); if number < 3 { return Err("the sealed descriptor landed on a standard stream".into()); } + report_sealed(&memory, number, extents.as_deref(), started); + let arguments = substitute(&plan.command[1..], number); + let error = Command::new(&plan.command[0]).args(arguments).exec(); + Err(format!("cannot execute {:?}: {error}", plan.command[0])) +} + +/// The sealed memfd of the plan: the whole file, or only the extents the serve path reads (returned too). +fn seal_for_exec( + plan: &super::SealExecPlan, + mut progress: impl FnMut(u64, u64), +) -> Result<(File, Option>), String> { + if !plan.sparse_ple { + return Ok(( + seal_file(&plan.file, plan.expect_bytes, &mut progress)?, + None, + )); + } + let expect = plan + .expect_bytes + .ok_or("--sparse-ple needs --expect-bytes (the pinned archive length)")?; + let extents = super::archive_serve_extents(&plan.file, expect)?; + let (memory, _) = seal_extents(&plan.file, Some(expect), &extents, &mut progress)?; + Ok((memory, Some(extents))) +} + +fn report_sealed( + memory: &File, + number: i32, + extents: Option<&[Extent]>, + started: std::time::Instant, +) { let length = memory.metadata().map(|m| m.len()).unwrap_or(0); eprintln!( "leleka seal-exec: sealed memfd fd={number} bytes={length}{} in {:.1}s", - extents.as_ref().map_or(String::new(), |e| format!( + extents.map_or(String::new(), |e| format!( " (SPARSE: {} extents, {:.3} GiB held, the rest is a hole)", e.len(), leleka_model_format::kar::extents_bytes(e) as f64 / 1073741824.0 )), started.elapsed().as_secs_f64() ); - let arguments = substitute(&plan.command[1..], number); - let error = Command::new(&plan.command[0]).args(arguments).exec(); - Err(format!("cannot execute {:?}: {error}", plan.command[0])) } #[cfg(test)] diff --git a/crates/deploy/src/sealed/linux/copy.rs b/crates/deploy/src/sealed/linux/copy.rs new file mode 100644 index 00000000..9781ae8e --- /dev/null +++ b/crates/deploy/src/sealed/linux/copy.rs @@ -0,0 +1,126 @@ +//! The copy of the archive ranges into the memfd: a reader thread, and the progress loop of the caller. + +use leleka_model_format::{ + bulk_read::{Plan, Report, Strategy, for_each_chunk}, + kar::Extent, +}; +use std::{ + fs::File, + os::unix::fs::FileExt, + sync::{ + Mutex, + atomic::{AtomicBool, AtomicU64, Ordering}, + }, +}; + +/// What the reader thread and the progress loop share. +struct CopyState { + copied: AtomicU64, + finished: AtomicBool, + failure: Mutex>, + report: Mutex>, +} + +/// Set on every exit, a panic included, so that the progress loop ends. +struct Finished<'a>(&'a AtomicBool); + +impl Drop for Finished<'_> { + fn drop(&mut self) { + self.0.store(true, Ordering::Release); + } +} + +/// Copy `ranges` of `source` to the same offsets of `memory`, reporting (copied, wanted) about every 4 GiB. The +/// report of the +/// read (`None` when the reader did not leave one) once every wanted byte is in. +pub(super) fn copy_ranges( + source: &File, + memory: &File, + ranges: &[Extent], + mut progress: impl FnMut(u64, u64), +) -> Result, String> { + let want = ranges_len(ranges); + // Large blocks on many threads (O_DIRECT where the file system allows it): the device sees a deep queue + // instead of one 128 KiB readahead window at a time, and what is copied never enters the page cache, so the + // memfd is the only copy of it in RAM (a sparse copy reads each of its extents the same way and nothing else). + let plan = Plan::from_env(); + let state = CopyState { + copied: AtomicU64::new(0), + finished: AtomicBool::new(false), + failure: Mutex::new(None), + report: Mutex::new(None), + }; + std::thread::scope(|scope| { + scope.spawn(|| copy_worker(source, memory, ranges, plan, &state)); + report_progress(&state, want, &mut progress); + }); + if let Some(message) = state.failure.into_inner().ok().flatten() { + return Err(message); + } + if state.copied.load(Ordering::Relaxed) != want { + return Err("the archive changed while it was being copied".into()); + } + Ok(state.report.into_inner().ok().flatten()) +} + +/// The bytes the ranges add up to. +pub(super) fn ranges_len(ranges: &[Extent]) -> u64 { + ranges.iter().map(|r| r.len).sum() +} + +fn copy_worker(source: &File, memory: &File, ranges: &[Extent], plan: Plan, state: &CopyState) { + let _finished = Finished(&state.finished); + let mut strategy = None; + let mut elapsed = std::time::Duration::ZERO; + for range in ranges { + match copy_range(source, memory, range, plan, &state.copied) { + Ok(done) => { + strategy = Some(done.strategy); + elapsed += done.elapsed; + } + Err(e) => { + if let Ok(mut f) = state.failure.lock() { + f.get_or_insert(format!("read failed: {e}")); + } + return; + } + } + } + // No extents at all is a valid (empty) sparse copy: nothing was read. + let strategy = strategy.unwrap_or(Strategy::Plain); + if let Ok(mut slot) = state.report.lock() { + *slot = Some(Report { + strategy, + bytes: ranges_len(ranges), + elapsed, + }); + } +} + +fn copy_range( + source: &File, + memory: &File, + range: &Extent, + plan: Plan, + copied: &AtomicU64, +) -> std::io::Result { + for_each_chunk(source, range.offset, range.len, plan, |offset, data| { + memory.write_all_at(data, offset).map_err(|e| { + std::io::Error::other(format!("write to memfd failed (out of memory?): {e}")) + })?; + copied.fetch_add(data.len() as u64, Ordering::Relaxed); + Ok(()) + }) +} + +fn report_progress(state: &CopyState, want: u64, progress: &mut impl FnMut(u64, u64)) { + let mut reported = 0u64; + while !state.finished.load(Ordering::Acquire) { + std::thread::sleep(std::time::Duration::from_millis(100)); + let now = state.copied.load(Ordering::Relaxed); + if now - reported >= 4 << 30 { + reported = now; + progress(now, want); + } + } +} diff --git a/crates/deploy/src/service.rs b/crates/deploy/src/service.rs index 8016f151..87b18220 100644 --- a/crates/deploy/src/service.rs +++ b/crates/deploy/src/service.rs @@ -66,11 +66,9 @@ pub fn quote_arg(arg: &str) -> String { out } -/// The Task Scheduler XML (schema 1.4): at logon of `user`, interactive token, least privilege, no time limit, restart up to -/// three times a minute apart when it fails, one instance only, battery and idle do not matter. -pub fn task_xml(spec: &TaskSpec) -> String { - let e = xml_escape; - format!( +/// The text of the task definition; the `{name}` holes are filled by [`task_xml`]. +macro_rules! task_xml_template { + () => { r#" @@ -122,7 +120,17 @@ pub fn task_xml(spec: &TaskSpec) -> String { -"#, +"# + }; +} + +/// The Task Scheduler XML (schema 1.4): at logon of `user`, interactive token, least privilege, no time limit, +/// restart up to +/// three times a minute apart when it fails, one instance only, battery and idle do not matter. +pub fn task_xml(spec: &TaskSpec) -> String { + let e = xml_escape; + format!( + task_xml_template!(), description = e(&spec.description), name = e(&spec.name), user = e(&spec.user), diff --git a/crates/deploy/src/steps/downloads.rs b/crates/deploy/src/steps/downloads.rs index 22fac008..51966190 100644 --- a/crates/deploy/src/steps/downloads.rs +++ b/crates/deploy/src/steps/downloads.rs @@ -2,18 +2,16 @@ use super::*; -/// Download `url` to `part` with curl (or wget), https only, at most 1 MiB; output goes to `log`. -pub(super) fn download_small(tool: &str, url: &str, part: &Path, log: &Path) -> Result<(), String> { - use std::io::Write; - let part_text = part.display().to_string(); - let args: Vec<&str> = if tool == "wget" { +/// The command line of the download: `wget` or `curl`, https only, at most 1 MiB. +fn small_download_args<'a>(tool: &str, url: &'a str, part_text: &'a str) -> Vec<&'a str> { + if tool == "wget" { vec![ "-q", "--tries=3", "--timeout=60", "--https-only", "-O", - &part_text, + part_text, url, ] } else { @@ -30,43 +28,54 @@ pub(super) fn download_small(tool: &str, url: &str, part: &Path, log: &Path) -> "--max-filesize", "1048576", "-o", - &part_text, + part_text, url, ] - }; + } +} + +/// Download `url` to `part` with curl (or wget), https only, at most 1 MiB; output goes to `log`. +pub(super) fn download_small(tool: &str, url: &str, part: &Path, log: &Path) -> Result<(), String> { + let part_text = part.display().to_string(); + let args = small_download_args(tool, url, &part_text); let output = std::process::Command::new(tool) .args(&args) .stdin(Stdio::null()) .output() .map_err(|e| format!("cannot run {tool}: {e}"))?; + append_to_log(log, &format!("$ {tool} {}", args.join(" ")), &output.stderr); + if output.status.success() { + return Ok(()); + } + let detail = String::from_utf8_lossy(&output.stderr); + Err(format!( + "{tool} failed ({}){}", + output.status, + if detail.trim().is_empty() { + String::new() + } else { + format!(": {}", detail.trim()) + } + )) +} + +/// The command and what it printed on standard error, appended to the install log (best effort). +fn append_to_log(log: &Path, command: &str, stderr: &[u8]) { + use std::io::Write; if let Ok(mut file) = std::fs::OpenOptions::new() .create(true) .append(true) .open(log) { - let _ = writeln!(file, "$ {tool} {}", args.join(" ")); - let _ = file.write_all(&output.stderr); - } - if output.status.success() { - Ok(()) - } else { - let detail = String::from_utf8_lossy(&output.stderr); - Err(format!( - "{tool} failed ({}){}", - output.status, - if detail.trim().is_empty() { - String::new() - } else { - format!(": {}", detail.trim()) - } - )) + let _ = writeln!(file, "{command}"); + let _ = file.write_all(stderr); } } /// The `expert-profile` step: install the pinned upstream table from `--expert-profile-file`, else from the bytes embedded in /// this binary, else by download, verified against the profile's digest, atomically; fails closed (`expert_profile::provision`). pub fn provision_expert_profile(ctx: &Context) -> Result<(), String> { - use crate::expert_profile::{Outcome, Request, SOURCES, expected_digest, provision}; + use crate::expert_profile::{Request, SOURCES, expected_digest, provision}; let profile = ctx.profile.as_ref().map_err(String::clone)?; let relative = profile .expert_profile @@ -74,11 +83,7 @@ pub fn provision_expert_profile(ctx: &Context) -> Result<(), String> { .ok_or("the profile has no expert profile")?; let dest = ctx.opts.dirs.assets.join(relative); let expected = expected_digest(profile); - let tool = if cfg!(windows) || ctx.facts.tool("curl") { - "curl" - } else { - "wget" - }; + let tool = small_download_tool(ctx); let log = ctx.paths.logs().join("install.log"); let sources: &[&str] = if expected == crate::expert_profile::PINNED_SHA256 { &SOURCES @@ -96,7 +101,21 @@ pub fn provision_expert_profile(ctx: &Context) -> Result<(), String> { say(&format!("downloading {url}")); download_small(tool, url, part, &log) }; - match provision(&request, &mut fetch)? { + report_provisioned(provision(&request, &mut fetch)?, &dest, expected); + Ok(()) +} + +fn small_download_tool(ctx: &Context) -> &'static str { + if cfg!(windows) || ctx.facts.tool("curl") { + "curl" + } else { + "wget" + } +} + +fn report_provisioned(outcome: crate::expert_profile::Outcome, dest: &Path, expected: &str) { + use crate::expert_profile::Outcome; + match outcome { Outcome::AlreadyPresent => say(&format!( "{} already has the expected digest", dest.display() @@ -118,7 +137,6 @@ pub fn provision_expert_profile(ctx: &Context) -> Result<(), String> { } } } - Ok(()) } pub async fn install_cublas(ctx: &Context) -> Result<(), String> { @@ -126,43 +144,85 @@ pub async fn install_cublas(ctx: &Context) -> Result<(), String> { let lib_dir = paths.dirs.prefix.join("lib"); std::fs::create_dir_all(&lib_dir).map_err(|e| e.to_string())?; let tar_path = lib_dir.join(format!("libcublas-{CUBLAS_VERSION}.tar.xz")); - let part = lib_dir.join(format!("libcublas-{CUBLAS_VERSION}.tar.xz.part")); let log = paths.logs().join("install.log"); let have = sha256_file(&tar_path) .ok() .is_some_and(|d| d == CUBLAS_SHA256); if !have { - let downloader = if ctx.facts.tool("curl") { - "curl" - } else { - "wget" - }; - let args: Vec = if downloader == "curl" { - ["-fL", "--retry", "5", "--retry-delay", "3", "-C", "-", "-o"] - .iter() - .map(|s| s.to_string()) - .chain([part.display().to_string(), CUBLAS_URL.to_owned()]) - .collect() - } else { - ["-c", "-O"] - .iter() - .map(|s| s.to_string()) - .chain([part.display().to_string(), CUBLAS_URL.to_owned()]) - .collect() - }; - run_tool("cuBLAS download", Path::new(downloader), &args, &log).await?; - let digest = sha256_file(&part).map_err(|e| format!("cannot hash the download: {e}"))?; - if digest != CUBLAS_SHA256 { - let _ = std::fs::remove_file(&part); - return Err(format!( - "the cuBLAS download has SHA-256 {digest}, expected {CUBLAS_SHA256}; it was deleted, rerun to download again" - )); - } - std::fs::rename(&part, &tar_path).map_err(|e| e.to_string())?; + download_cublas(ctx, &lib_dir, &tar_path, &log).await?; } let staging = lib_dir.join(".cublas-extract"); let _ = std::fs::remove_dir_all(&staging); std::fs::create_dir_all(&staging).map_err(|e| e.to_string())?; + unpack_cublas(&tar_path, &staging, &log).await?; + move_unpacked_cublas(&paths.cublas_dir(), &staging, &tar_path) +} + +/// Replace the installed libraries by the unpacked ones and check that both are there. +fn move_unpacked_cublas(target: &Path, staging: &Path, tar_path: &Path) -> Result<(), String> { + let _ = std::fs::remove_dir_all(target); + std::fs::rename(staging.join("lib"), target) + .map_err(|e| format!("cannot move the unpacked libraries: {e}"))?; + if staging.join("LICENSE").is_file() { + let _ = std::fs::rename(staging.join("LICENSE"), target.join("LICENSE-cublas.txt")); + } + let _ = std::fs::remove_dir_all(staging); + let _ = std::fs::remove_file(tar_path); + for soname in ["libcublas.so.12", "libcublasLt.so.12"] { + if !target.join(soname).exists() { + return Err(format!( + "{soname} is missing after unpacking the cuBLAS archive" + )); + } + } + Ok(()) +} + +/// Download the cuBLAS archive to `tar_path` and check it against the pinned digest. +async fn download_cublas( + ctx: &Context, + lib_dir: &Path, + tar_path: &Path, + log: &Path, +) -> Result<(), String> { + let part = lib_dir.join(format!("libcublas-{CUBLAS_VERSION}.tar.xz.part")); + let downloader = if ctx.facts.tool("curl") { + "curl" + } else { + "wget" + }; + let args = cublas_download_args(downloader, &part); + run_tool("cuBLAS download", Path::new(downloader), &args, log).await?; + let digest = sha256_file(&part).map_err(|e| format!("cannot hash the download: {e}"))?; + if digest != CUBLAS_SHA256 { + let _ = std::fs::remove_file(&part); + return Err(format!( + concat!( + "the cuBLAS download has SHA-256 {digest}, expected {CUBLAS_SHA256}; ", + "it was deleted, rerun to download again" + ), + digest = digest, + CUBLAS_SHA256 = CUBLAS_SHA256 + )); + } + std::fs::rename(&part, tar_path).map_err(|e| e.to_string()) +} + +fn cublas_download_args(downloader: &str, part: &Path) -> Vec { + let options: &[&str] = if downloader == "curl" { + &["-fL", "--retry", "5", "--retry-delay", "3", "-C", "-", "-o"] + } else { + &["-c", "-O"] + }; + options + .iter() + .map(|s| s.to_string()) + .chain([part.display().to_string(), CUBLAS_URL.to_owned()]) + .collect() +} + +/// Unpack the two libraries and the license of the archive into `staging`. +async fn unpack_cublas(tar_path: &Path, staging: &Path, log: &Path) -> Result<(), String> { let args: Vec = [ "-xJf", &tar_path.display().to_string(), @@ -177,24 +237,7 @@ pub async fn install_cublas(ctx: &Context) -> Result<(), String> { .iter() .map(|s| s.to_string()) .collect(); - run_tool("cuBLAS unpack", Path::new("tar"), &args, &log).await?; - let target = paths.cublas_dir(); - let _ = std::fs::remove_dir_all(&target); - std::fs::rename(staging.join("lib"), &target) - .map_err(|e| format!("cannot move the unpacked libraries: {e}"))?; - if staging.join("LICENSE").is_file() { - let _ = std::fs::rename(staging.join("LICENSE"), target.join("LICENSE-cublas.txt")); - } - let _ = std::fs::remove_dir_all(&staging); - let _ = std::fs::remove_file(&tar_path); - for soname in ["libcublas.so.12", "libcublasLt.so.12"] { - if !target.join(soname).exists() { - return Err(format!( - "{soname} is missing after unpacking the cuBLAS archive" - )); - } - } - Ok(()) + run_tool("cuBLAS unpack", Path::new("tar"), &args, log).await } pub fn write_secrets_and_env(ctx: &Context) -> Result<(), String> { diff --git a/crates/deploy/src/steps/model_assets.rs b/crates/deploy/src/steps/model_assets.rs index 8a2fc418..d21fb998 100644 --- a/crates/deploy/src/steps/model_assets.rs +++ b/crates/deploy/src/steps/model_assets.rs @@ -10,13 +10,7 @@ pub async fn fetch_and_verify_model(ctx: &Context) -> Result<(), String> { run_tool( "model fetch", &strata, - &[ - "model".into(), - "fetch".into(), - MANIFEST.into(), - "--output".into(), - model_dir.clone(), - ], + &model_args("fetch", &model_dir), &log, ) .await?; @@ -24,13 +18,7 @@ pub async fn fetch_and_verify_model(ctx: &Context) -> Result<(), String> { run_tool( "model verify", &strata, - &[ - "model".into(), - "verify".into(), - MANIFEST.into(), - "--output".into(), - model_dir, - ], + &model_args("verify", &model_dir), &log, ) .await?; @@ -41,36 +29,63 @@ pub async fn fetch_and_verify_model(ctx: &Context) -> Result<(), String> { ) } +/// `strata-next model VERB MANIFEST --output DIR`. +fn model_args(verb: &str, model_dir: &str) -> Vec { + vec![ + "model".into(), + verb.into(), + MANIFEST.into(), + "--output".into(), + model_dir.to_owned(), + ] +} + pub async fn ensure_kar(ctx: &Context) -> Result<(), String> { - let strata = ctx.paths.bin("strata-next"); - let log = ctx.paths.logs().join("install.log"); let present = std::fs::metadata(ctx.paths.kar()).is_ok_and(|m| m.len() == ARCHIVE_BYTES) && ctx.paths.kar_provenance().is_file(); if ctx.opts.trust_archive && present { say("--trust-archive: the existing archive is accepted without the strict re-derivation"); } else { - let args: Vec = [ - "model", - "ensure-sharded-streamed", - MANIFEST, - "--source-dir", - &ctx.paths.model_dir().display().to_string(), - "--output", - &ctx.paths.kar().display().to_string(), - "--levels", - "2", - ] - .iter() - .map(|s| s.to_string()) - .collect(); - run_tool("KAR archive", &strata, &args, &log).await?; - // The tool fetched and verified the shards before it touched the archive. - write_stamp( - &stamp_path(&ctx.paths, "model"), - "gguf shards verified by `ensure-sharded-streamed`", - &[ctx.paths.shard(0), ctx.paths.shard(1)], - )?; + derive_archive(ctx).await?; } + check_archive_built(ctx)?; + make_archive_read_only(ctx)?; + write_stamp( + &stamp_path(&ctx.paths, "kar"), + "level-2 KAR archive verified by `ensure-sharded-streamed`", + &[ctx.paths.kar(), ctx.paths.kar_provenance()], + ) +} + +/// Build the level-2 archive from the shards with the strict re-derivation. +async fn derive_archive(ctx: &Context) -> Result<(), String> { + let strata = ctx.paths.bin("strata-next"); + let log = ctx.paths.logs().join("install.log"); + let args: Vec = [ + "model", + "ensure-sharded-streamed", + MANIFEST, + "--source-dir", + &ctx.paths.model_dir().display().to_string(), + "--output", + &ctx.paths.kar().display().to_string(), + "--levels", + "2", + ] + .iter() + .map(|s| s.to_string()) + .collect(); + run_tool("KAR archive", &strata, &args, &log).await?; + // The tool fetched and verified the shards before it touched the archive. + write_stamp( + &stamp_path(&ctx.paths, "model"), + "gguf shards verified by `ensure-sharded-streamed`", + &[ctx.paths.shard(0), ctx.paths.shard(1)], + ) +} + +/// The archive exists with the pinned length and its provenance file next to it. +fn check_archive_built(ctx: &Context) -> Result<(), String> { let size = std::fs::metadata(ctx.paths.kar()) .map_err(|e| format!("the archive is missing after the build: {e}"))? .len(); @@ -86,6 +101,10 @@ pub async fn ensure_kar(ctx: &Context) -> Result<(), String> { ctx.paths.kar_provenance().display() )); } + Ok(()) +} + +fn make_archive_read_only(ctx: &Context) -> Result<(), String> { #[cfg(unix)] if ctx .config @@ -97,11 +116,9 @@ pub async fn ensure_kar(ctx: &Context) -> Result<(), String> { std::fs::set_permissions(ctx.paths.kar(), std::fs::Permissions::from_mode(0o400)) .map_err(|e| format!("cannot make the archive read-only: {e}"))?; } - write_stamp( - &stamp_path(&ctx.paths, "kar"), - "level-2 KAR archive verified by `ensure-sharded-streamed`", - &[ctx.paths.kar(), ctx.paths.kar_provenance()], - ) + #[cfg(not(unix))] + let _ = ctx; + Ok(()) } pub async fn import_mtp_pack(ctx: &Context) -> Result<(), String> { @@ -110,43 +127,7 @@ pub async fn import_mtp_pack(ctx: &Context) -> Result<(), String> { let staging = ctx.paths.dirs.assets.join("data/.mtp-import"); let _ = std::fs::remove_dir_all(&staging); std::fs::create_dir_all(&staging).map_err(|e| e.to_string())?; - let name = source - .file_name() - .and_then(|n| n.to_str()) - .unwrap_or("") - .to_owned(); - if source.is_dir() { - copy_dir(&source, &staging)?; - } else if name.ends_with(".tar") - || name.ends_with(".tar.gz") - || name.ends_with(".tgz") - || name.ends_with(".tar.xz") - { - let flag = if name.ends_with(".tar") { - "-xf" - } else if name.ends_with(".tar.xz") { - "-xJf" - } else { - "-xzf" - }; - run_tool( - "unpack the MTP pack", - Path::new("tar"), - &[ - flag.into(), - source.display().to_string(), - "-C".into(), - staging.display().to_string(), - ], - &ctx.paths.logs().join("install.log"), - ) - .await?; - } else { - return Err(format!( - "--mtp-pack {} must be a directory or a .tar/.tar.gz/.tgz/.tar.xz archive", - source.display() - )); - } + unpack_pack(ctx, &source, &staging).await?; // The pack may sit in a sub-directory (data/mtp-rt/ inside the tarball). let root = find_pack_root(&staging).ok_or_else(|| { format!( @@ -163,6 +144,49 @@ pub async fn import_mtp_pack(ctx: &Context) -> Result<(), String> { Ok(()) } +/// Copy the pack directory, or unpack the tarball, into `staging`. +async fn unpack_pack(ctx: &Context, source: &Path, staging: &Path) -> Result<(), String> { + let name = source + .file_name() + .and_then(|n| n.to_str()) + .unwrap_or("") + .to_owned(); + if source.is_dir() { + return copy_dir(source, staging); + } + let Some(flag) = tar_flag(&name) else { + return Err(format!( + "--mtp-pack {} must be a directory or a .tar/.tar.gz/.tgz/.tar.xz archive", + source.display() + )); + }; + run_tool( + "unpack the MTP pack", + Path::new("tar"), + &[ + flag.into(), + source.display().to_string(), + "-C".into(), + staging.display().to_string(), + ], + &ctx.paths.logs().join("install.log"), + ) + .await +} + +/// The `tar` option that unpacks an archive of this name; `None` for a name that is not a tarball. +fn tar_flag(name: &str) -> Option<&'static str> { + if name.ends_with(".tar") { + Some("-xf") + } else if name.ends_with(".tar.xz") { + Some("-xJf") + } else if name.ends_with(".tar.gz") || name.ends_with(".tgz") { + Some("-xzf") + } else { + None + } +} + pub(super) fn find_pack_root(dir: &Path) -> Option { if MTP_FILES.iter().all(|f| dir.join(f).is_file()) { return Some(dir.to_path_buf()); diff --git a/crates/deploy/src/steps/preparation.rs b/crates/deploy/src/steps/preparation.rs index a9d3ffcb..ae1ea6ef 100644 --- a/crates/deploy/src/steps/preparation.rs +++ b/crates/deploy/src/steps/preparation.rs @@ -6,52 +6,15 @@ pub async fn prepare(ctx: &Context, steps: &[Step]) -> Result { let mut changes = Changes::default(); let total = steps.len(); for (index, step) in steps.iter().enumerate() { - match &step.state { - StepState::Blocked(why) => { - return Err(format!( - "step {} ({}) is blocked: {why}", - step.id, step.title - )); - } - StepState::Done(_) | StepState::Skip(_) => continue, - StepState::Todo(_) => {} - } - if matches!(step.id, "preflight" | "service" | "start" | "ready") { - continue; - } - if step.id == "model" && kar_runs_tool(ctx, steps) { - say("the shards are fetched and verified by the archive step below"); + if !step_runs(ctx, steps, step)? { continue; } say(&format!("[{}/{}] {}", index + 1, total, step.title)); let started = Instant::now(); - let result: Result<(), String> = match step.id { - "layout" => make_dirs(ctx), - "binaries" => install_binaries(ctx).map(|n| { - changes.binaries += n; - say(&format!( - "installed {n} binaries into {}", - ctx.paths.bin_dir().display() - )) - }), - "expert-profile" => provision_expert_profile(ctx), - "cublas" => install_cublas(ctx).await, - "secrets" => { - write_secrets_and_env(ctx)?; - init_api_key(ctx).await - } - "model" => fetch_and_verify_model(ctx).await, - "kar" => ensure_kar(ctx).await, - "mtp-pack" => import_mtp_pack(ctx).await, - "tokenizer" => extract_tokenizer(ctx).await, - "config" => write_configs(ctx).map(|n| { - changes.configs += n; - say(&format!( - "wrote {n} configuration file(s) in {}", - ctx.paths.dirs.state.display() - )) - }), - other => Err(format!("internal error: no executor for step {other}")), + let result: Result<(), String> = if step.id == "secrets" { + prepare_secrets(ctx).await? + } else { + run_step(ctx, step.id, &mut changes).await }; result.map_err(|e| format!("step {} failed: {e}", step.id))?; say(&format!( @@ -64,6 +27,74 @@ pub async fn prepare(ctx: &Context, steps: &[Step]) -> Result { Ok(changes) } +/// Does `prepare` execute this step? A blocked step ends the run; done, skipped and later steps are not executed here. +fn step_runs(ctx: &Context, steps: &[Step], step: &Step) -> Result { + match &step.state { + StepState::Blocked(why) => { + return Err(format!( + "step {} ({}) is blocked: {why}", + step.id, step.title + )); + } + StepState::Done(_) | StepState::Skip(_) => return Ok(false), + StepState::Todo(_) => {} + } + if matches!(step.id, "preflight" | "service" | "start" | "ready") { + return Ok(false); + } + if step.id == "model" && kar_runs_tool(ctx, steps) { + say("the shards are fetched and verified by the archive step below"); + return Ok(false); + } + Ok(true) +} + +/// The secrets file is written first; its failure ends the run as it is, the API key follows as an ordinary step +/// result. +async fn prepare_secrets(ctx: &Context) -> Result, String> { + write_secrets_and_env(ctx)?; + Ok(init_api_key(ctx).await) +} + +async fn run_step(ctx: &Context, id: &str, changes: &mut Changes) -> Result<(), String> { + match id { + "model" | "kar" | "mtp-pack" | "tokenizer" => run_model_step(ctx, id).await, + _ => run_host_step(ctx, id, changes).await, + } +} + +async fn run_host_step(ctx: &Context, id: &str, changes: &mut Changes) -> Result<(), String> { + match id { + "layout" => make_dirs(ctx), + "binaries" => install_binaries(ctx).map(|n| { + changes.binaries += n; + say(&format!( + "installed {n} binaries into {}", + ctx.paths.bin_dir().display() + )) + }), + "expert-profile" => provision_expert_profile(ctx), + "cublas" => install_cublas(ctx).await, + "config" => write_configs(ctx).map(|n| { + changes.configs += n; + say(&format!( + "wrote {n} configuration file(s) in {}", + ctx.paths.dirs.state.display() + )) + }), + other => Err(format!("internal error: no executor for step {other}")), + } +} + +async fn run_model_step(ctx: &Context, id: &str) -> Result<(), String> { + match id { + "model" => fetch_and_verify_model(ctx).await, + "kar" => ensure_kar(ctx).await, + "mtp-pack" => import_mtp_pack(ctx).await, + _ => extract_tokenizer(ctx).await, + } +} + /// Re-plan with the current state of the disk (after `prepare`), used to decide what `start` has to do. pub async fn replan(ctx: &Context) -> Vec { let fs = gather_fs(ctx).await; diff --git a/crates/deploy/src/steps/probes_and_tools.rs b/crates/deploy/src/steps/probes_and_tools.rs index 5f8128cc..8c26d05d 100644 --- a/crates/deploy/src/steps/probes_and_tools.rs +++ b/crates/deploy/src/steps/probes_and_tools.rs @@ -65,12 +65,7 @@ pub async fn run_tool( log: &Path, ) -> Result<(), String> { say(&format!("$ {} {}", program.display(), args.join(" "))); - let mut log_file = tokio::fs::OpenOptions::new() - .create(true) - .append(true) - .open(log) - .await - .map_err(|e| format!("cannot open {}: {e}", log.display()))?; + let mut log_file = open_install_log(log).await?; let mut child = Command::new(program) .args(args) .stdin(Stdio::null()) @@ -79,22 +74,9 @@ pub async fn run_tool( .kill_on_drop(true) .spawn() .map_err(|e| format!("cannot start {}: {e}", program.display()))?; - let mut stdout = child.stdout.take().expect("piped"); - let mut stderr = child.stderr.take().expect("piped"); - let (mut out_buf, mut err_buf) = (vec![0u8; 8192], vec![0u8; 8192]); - let (mut out_open, mut err_open) = (true, true); - while out_open || err_open { - tokio::select! { - read = stdout.read(&mut out_buf), if out_open => match read { - Ok(0) | Err(_) => out_open = false, - Ok(n) => { forward(&mut log_file, &out_buf[..n]).await; } - }, - read = stderr.read(&mut err_buf), if err_open => match read { - Ok(0) | Err(_) => err_open = false, - Ok(n) => { forward(&mut log_file, &err_buf[..n]).await; } - }, - } - } + let stdout = child.stdout.take().expect("piped"); + let stderr = child.stderr.take().expect("piped"); + forward_both(stdout, stderr, &mut log_file).await; let status = child .wait() .await @@ -106,6 +88,37 @@ pub async fn run_tool( } } +async fn open_install_log(log: &Path) -> Result { + tokio::fs::OpenOptions::new() + .create(true) + .append(true) + .open(log) + .await + .map_err(|e| format!("cannot open {}: {e}", log.display())) +} + +/// Copy what the tool prints on both streams to standard error and the log, until both are closed. +async fn forward_both( + mut stdout: tokio::process::ChildStdout, + mut stderr: tokio::process::ChildStderr, + log_file: &mut tokio::fs::File, +) { + let (mut out_buf, mut err_buf) = (vec![0u8; 8192], vec![0u8; 8192]); + let (mut out_open, mut err_open) = (true, true); + while out_open || err_open { + tokio::select! { + read = stdout.read(&mut out_buf), if out_open => match read { + Ok(0) | Err(_) => out_open = false, + Ok(n) => { forward(log_file, &out_buf[..n]).await; } + }, + read = stderr.read(&mut err_buf), if err_open => match read { + Ok(0) | Err(_) => err_open = false, + Ok(n) => { forward(log_file, &err_buf[..n]).await; } + }, + } + } +} + pub(super) async fn forward(log: &mut tokio::fs::File, bytes: &[u8]) { use std::io::Write; let _ = std::io::stderr().write_all(bytes); @@ -125,15 +138,13 @@ pub fn make_dirs(ctx: &Context) -> Result<(), String> { paths.engine_stamps(), paths.mtp_staging(), ]; - for dir in private.iter().chain( - [ - paths.bin_dir(), - paths.dirs.assets.clone(), - paths.model_dir(), - paths.dirs.assets.join("data"), - ] - .iter(), - ) { + let shared = [ + paths.bin_dir(), + paths.dirs.assets.clone(), + paths.model_dir(), + paths.dirs.assets.join("data"), + ]; + for dir in private.iter().chain(shared.iter()) { std::fs::create_dir_all(dir) .map_err(|e| format!("cannot create {}: {e}", dir.display()))?; } @@ -153,42 +164,62 @@ pub fn install_binaries(ctx: &Context) -> Result { let manifest = ctx.manifest.as_ref().and_then(|m| m.as_ref().ok()); let mut installed = 0; for name in BINARIES { - let (src, dst) = (src_dir.join(name), dst_dir.join(name)); - if !src.is_file() { - if dst.is_file() { - continue; - } - return Err(format!( - "{} is missing (looked in {} and {})", - name, - src_dir.display(), - dst_dir.display() - )); + if install_binary(name, src_dir, &dst_dir, manifest)? { + installed += 1; } - let digest = - sha256_file(&src).map_err(|e| format!("cannot read {}: {e}", src.display()))?; - if let Some(expected) = manifest.and_then(|m| m.binaries.get(name)) - && *expected != digest - { - return Err(format!( - "{} does not match MANIFEST.json (corrupt download?)", - src.display() - )); - } - if dst.is_file() && sha256_file(&dst).ok().as_deref() == Some(digest.as_str()) { - continue; - } - let tmp = dst_dir.join(format!(".{name}.new")); - std::fs::copy(&src, &tmp).map_err(|e| format!("cannot copy {name}: {e}"))?; - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt; - std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(0o755)) - .map_err(|e| e.to_string())?; - } - // rename over a running binary is safe (a new inode); a plain overwrite would fail with ETXTBSY. - std::fs::rename(&tmp, &dst).map_err(|e| format!("cannot install {name}: {e}"))?; - installed += 1; } Ok(installed) } + +/// Copy one binary next to the others when it differs; true when it was installed. +fn install_binary( + name: &str, + src_dir: &Path, + dst_dir: &Path, + manifest: Option<&crate::manifest::Manifest>, +) -> Result { + let (src, dst) = (src_dir.join(name), dst_dir.join(name)); + if !src.is_file() { + if dst.is_file() { + return Ok(false); + } + return Err(missing_binary(name, src_dir, dst_dir)); + } + let digest = sha256_file(&src).map_err(|e| format!("cannot read {}: {e}", src.display()))?; + if let Some(expected) = manifest.and_then(|m| m.binaries.get(name)) + && *expected != digest + { + return Err(format!( + "{} does not match MANIFEST.json (corrupt download?)", + src.display() + )); + } + if dst.is_file() && sha256_file(&dst).ok().as_deref() == Some(digest.as_str()) { + return Ok(false); + } + copy_into_place(name, &src, &dst, dst_dir)?; + Ok(true) +} + +fn missing_binary(name: &str, src_dir: &Path, dst_dir: &Path) -> String { + format!( + "{} is missing (looked in {} and {})", + name, + src_dir.display(), + dst_dir.display() + ) +} + +/// Copy `src` to a temporary name next to `dst`, make it executable and rename it over `dst`. +fn copy_into_place(name: &str, src: &Path, dst: &Path, dst_dir: &Path) -> Result<(), String> { + let tmp = dst_dir.join(format!(".{name}.new")); + std::fs::copy(src, &tmp).map_err(|e| format!("cannot copy {name}: {e}"))?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(0o755)) + .map_err(|e| e.to_string())?; + } + // rename over a running binary is safe (a new inode); a plain overwrite would fail with ETXTBSY. + std::fs::rename(&tmp, dst).map_err(|e| format!("cannot install {name}: {e}")) +} diff --git a/crates/deploy/src/steps/service_unit.rs b/crates/deploy/src/steps/service_unit.rs index ebd65b90..b49117f6 100644 --- a/crates/deploy/src/steps/service_unit.rs +++ b/crates/deploy/src/steps/service_unit.rs @@ -144,38 +144,13 @@ pub async fn wait_ready(ctx: &Context, scope: Option) -> Result<() if probe_ready(ctx).await { return Ok(()); } - let status: Option = std::fs::read_to_string(ctx.paths.status_file()) - .ok() - .and_then(|t| serde_json::from_str(&t).ok()); - let phase = status - .as_ref() - .and_then(|s| s.get("phase")) - .and_then(|v| v.as_str()) - .unwrap_or("not started") - .to_owned(); - if phase == "failed" { - let message = status - .as_ref() - .and_then(|s| s.get("message")) - .and_then(|v| v.as_str()) - .unwrap_or(""); - return Err(format!("the service failed: {message}\n{}", log_tail(ctx))); - } + let (status, phase) = supervisor_phase(ctx); + check_not_failed(ctx, status.as_ref(), &phase)?; if let Some(scope) = scope { - let active = systemctl_query(scope, &["is-active", ctx.paths.unit_name()]).await; - if active == "failed" { - return Err(format!( - "{} failed\n{}", - ctx.paths.unit_name(), - log_tail(ctx) - )); - } + check_unit_not_failed(ctx, scope).await?; } if phase != last_phase || last_print.elapsed() >= Duration::from_secs(30) { - say(&format!( - "waiting for ready: {phase} ({:.0}s)", - started.elapsed().as_secs_f32() - )); + say_waiting(&phase, started); last_phase = phase; last_print = Instant::now(); } @@ -190,6 +165,55 @@ pub async fn wait_ready(ctx: &Context, scope: Option) -> Result<() } } +/// The status document of the supervisor and its phase (`not started` without one). +fn supervisor_phase(ctx: &Context) -> (Option, String) { + let status: Option = std::fs::read_to_string(ctx.paths.status_file()) + .ok() + .and_then(|t| serde_json::from_str(&t).ok()); + let phase = status + .as_ref() + .and_then(|s| s.get("phase")) + .and_then(|v| v.as_str()) + .unwrap_or("not started") + .to_owned(); + (status, phase) +} + +/// The supervisor says it failed: end the wait with its message and the log tail. +fn check_not_failed( + ctx: &Context, + status: Option<&serde_json::Value>, + phase: &str, +) -> Result<(), String> { + if phase != "failed" { + return Ok(()); + } + let message = status + .and_then(|s| s.get("message")) + .and_then(|v| v.as_str()) + .unwrap_or(""); + Err(format!("the service failed: {message}\n{}", log_tail(ctx))) +} + +async fn check_unit_not_failed(ctx: &Context, scope: UnitScopeTag) -> Result<(), String> { + let active = systemctl_query(scope, &["is-active", ctx.paths.unit_name()]).await; + if active == "failed" { + return Err(format!( + "{} failed\n{}", + ctx.paths.unit_name(), + log_tail(ctx) + )); + } + Ok(()) +} + +fn say_waiting(phase: &str, started: Instant) { + say(&format!( + "waiting for ready: {phase} ({:.0}s)", + started.elapsed().as_secs_f32() + )); +} + pub(super) fn log_tail(ctx: &Context) -> String { let mut out = String::new(); for name in ["leleka.log", "engine.log"] { diff --git a/crates/deploy/src/steps/stamps_and_state.rs b/crates/deploy/src/steps/stamps_and_state.rs index f391d406..ee4aa134 100644 --- a/crates/deploy/src/steps/stamps_and_state.rs +++ b/crates/deploy/src/steps/stamps_and_state.rs @@ -180,35 +180,11 @@ pub async fn gather_fs(ctx: &Context) -> FsState { let model_files: Vec = vec![paths.shard(0), paths.shard(1)]; let kar_files: Vec = vec![paths.kar(), paths.kar_provenance()]; let kar_size_ok = std::fs::metadata(paths.kar()).is_ok_and(|m| m.len() == ARCHIVE_BYTES); - let configs = render_configs(ctx); - let configs_current = !configs.is_empty() - && configs - .iter() - .all(|(path, text)| std::fs::read_to_string(path).is_ok_and(|t| &t == text)) - && std::fs::read_to_string(paths.env_file()) - .ok() - .map(|t| parse_env_file(&t)) - .is_some_and(|env| { - env.get("LD_LIBRARY_PATH").map(String::as_str).unwrap_or("") - == desired_ld_library_path(ctx) - }); - let unit_current = match ctx.mode { - Mode::Systemd(scope) => unit_text(ctx, scope) - .ok() - .is_some_and(|(path, text)| std::fs::read_to_string(path).is_ok_and(|t| t == text)), - _ => false, - }; + let configs_current = configs_are_current(ctx); + let unit_current = unit_is_current(ctx); let service_ready = probe_ready(ctx).await; FsState { - dirs_exist: [ - paths.dirs.state.clone(), - paths.logs(), - paths.stamps(), - paths.bin_dir(), - paths.dirs.assets.clone(), - ] - .iter() - .all(|d| d.is_dir()), + dirs_exist: directories_exist(paths), binaries_current, binaries_source_ok, cublas_ready: ctx.facts.lib("libcublas.so.12").is_some() @@ -225,6 +201,43 @@ pub async fn gather_fs(ctx: &Context) -> FsState { } } +fn directories_exist(paths: &Paths) -> bool { + [ + paths.dirs.state.clone(), + paths.logs(), + paths.stamps(), + paths.bin_dir(), + paths.dirs.assets.clone(), + ] + .iter() + .all(|d| d.is_dir()) +} + +/// Every configuration file has the text that `up` would write, and the environment file the library path it would set. +fn configs_are_current(ctx: &Context) -> bool { + let configs = render_configs(ctx); + !configs.is_empty() + && configs + .iter() + .all(|(path, text)| std::fs::read_to_string(path).is_ok_and(|t| &t == text)) + && std::fs::read_to_string(ctx.paths.env_file()) + .ok() + .map(|t| parse_env_file(&t)) + .is_some_and(|env| { + env.get("LD_LIBRARY_PATH").map(String::as_str).unwrap_or("") + == desired_ld_library_path(ctx) + }) +} + +fn unit_is_current(ctx: &Context) -> bool { + match ctx.mode { + Mode::Systemd(scope) => unit_text(ctx, scope) + .ok() + .is_some_and(|(path, text)| std::fs::read_to_string(path).is_ok_and(|t| t == text)), + _ => false, + } +} + pub async fn probe_ready(ctx: &Context) -> bool { probe_ready_at(&ctx.paths, &ctx.opts.ports.api).await } diff --git a/crates/deploy/src/supervisor.rs b/crates/deploy/src/supervisor.rs index 1248bb36..73b5bbc0 100644 --- a/crates/deploy/src/supervisor.rs +++ b/crates/deploy/src/supervisor.rs @@ -158,10 +158,12 @@ pub const STOP_REQUEST_FILE: &str = "stop.request"; mod tests; mod api; +mod archive; mod children; mod cli_output; mod engine; mod live_reconfigure; +mod load; mod logfile; mod signals; mod sparse; diff --git a/crates/deploy/src/supervisor/api.rs b/crates/deploy/src/supervisor/api.rs index e8761b68..e6ddd9e2 100644 --- a/crates/deploy/src/supervisor/api.rs +++ b/crates/deploy/src/supervisor/api.rs @@ -9,29 +9,9 @@ impl Supervisor { if self.stopping() { return Err(Flow::Stopped); } - if let Ok(Some(status)) = api.try_wait() { - return fail( - 1, - format!( - "the API exited ({status}); see {}", - self.paths.logs().join("api.log").display() - ), - ); - } - if let Ok(response) = http::get( - self.api_addr, - "/ready", - Some(&self.api_key), - Duration::from_secs(5), - ) - .await - { - if response.status == 200 { - return Ok(()); - } - if response.status == 401 || response.status == 403 { - return fail(1, "the API rejected the key in the api-key file"); - } + self.check_api_running(api)?; + if let Some(answer) = self.ready_answer().await { + return answer; } if started.elapsed() > Duration::from_secs(180) { return fail( @@ -45,6 +25,38 @@ impl Supervisor { } } + fn check_api_running(&self, api: &mut Child) -> Result<(), Flow> { + if let Ok(Some(status)) = api.try_wait() { + return fail( + 1, + format!( + "the API exited ({status}); see {}", + self.paths.logs().join("api.log").display() + ), + ); + } + Ok(()) + } + + /// One look at `/ready`: `Some` when it settles the wait (ready, or the key is rejected), `None` to keep waiting. + async fn ready_answer(&self) -> Option> { + let response = http::get( + self.api_addr, + "/ready", + Some(&self.api_key), + Duration::from_secs(5), + ) + .await + .ok()?; + if response.status == 200 { + return Some(Ok(())); + } + if response.status == 401 || response.status == 403 { + return Some(fail(1, "the API rejected the key in the api-key file")); + } + None + } + /// Leave the supervisor answer to a reconfigure request (best effort: the CLI times out without one). pub(super) fn answer( &self, diff --git a/crates/deploy/src/supervisor/archive.rs b/crates/deploy/src/supervisor/archive.rs new file mode 100644 index 00000000..6417c7f7 --- /dev/null +++ b/crates/deploy/src/supervisor/archive.rs @@ -0,0 +1,207 @@ +//! The sealed archive the engine inherits: opened from a descriptor, copied into a memfd, or absent. + +use super::*; + +type SealedCopy = Result< + ( + File, + Option, + leleka_model_format::bulk_read::Report, + ), + String, +>; + +/// What the archive file looked like before the copy: its identity and whether a stamp vouches for it. +struct SourceState { + before: Option, + stamped: bool, +} + +impl Supervisor { + /// Stage 1 of `drive`: the archive descriptor (`None` when the profile reads the PLE rows from the GGUF shard). + pub(super) async fn prepare_archive( + &mut self, + kar_fd: Option, + ) -> Result, Flow> { + match (kar_fd, self.config.profile.kar_source) { + (Some(fd), KarSource::None) => fail( + 2, + format!( + "descriptor {fd} was inherited but profile {} has kar_source none (no archive is used)", + self.config.profile.name + ), + ), + (None, KarSource::None) => { + self.log.line(concat!( + "kar_source none: no KAR archive; the PLE rows are read from the GGUF ", + "shard (qwen4exp-native-mtp-v1)" + )); + Ok(None) + } + (Some(fd), _) => self.open_inherited_archive(fd).map(Some), + (None, KarSource::Memfd) => self.seal_archive().await.map(Some), + (None, KarSource::File) => Ok(None), + } + } + + fn open_inherited_archive(&mut self, fd: u32) -> Result { + self.log.line(&format!( + "using the sealed archive descriptor {fd} inherited from the parent" + )); + self.archive_sparse_pin = self.sparse_pin()?; + sealed::open_inherited(fd).map_err(|message| Flow::Fatal(Failure { code: 2, message })) + } + + async fn seal_archive(&mut self) -> Result { + let kar = self.paths.kar(); + // `memfd_extents: ple_only`: only the byte ranges the serve path reads (about 16 GB of 55) go into the memfd. + let sparse = self.sparse_pin()?; + let extents = match sparse { + Some(_) => Some(Self::serve_extents(&kar)?), + None => None, + }; + self.announce_sealing(&kar, extents.as_deref()); + let started = Instant::now(); + let mut preverify = self.spawn_shard_preverify(); + let source = self.source_state(&kar); + let sealed = self.copy_archive(&kar, extents.as_deref()); + self.await_preverify(preverify.as_mut()).await?; + self.accept_sealed(sealed, sparse, &source, started) + } + + fn announce_sparse_sealing(&mut self, kar: &Path, list: &[leleka_model_format::kar::Extent]) { + self.set_phase( + Phase::Sealing, + "copying the archive extents the serve path reads into a sealed memfd", + ); + self.log.line(&format!( + concat!( + "sealing {} extents ({:.2} GiB of {:.2} GiB) of {} into RAM; the rest ", + "of the memfd is a hole (once per service life)" + ), + list.len(), + leleka_model_format::kar::extents_bytes(list) as f64 / 1073741824.0, + ARCHIVE_BYTES as f64 / 1073741824.0, + kar.display() + )); + } + + fn announce_sealing( + &mut self, + kar: &Path, + extents: Option<&[leleka_model_format::kar::Extent]>, + ) { + match extents { + Some(list) => self.announce_sparse_sealing(kar, list), + None => { + self.set_phase(Phase::Sealing, "copying the archive into a sealed memfd"); + self.log.line(&format!( + "sealing {} into RAM (once per service life)", + kar.display() + )); + } + } + } + + /// A stamp of the archive file (written after a start whose engine hashed the copy) lets the engine + /// skip the hash of the memfd; it applies only if the file is still in the stamped state before + /// AND after the copy. + fn source_state(&self, kar: &Path) -> SourceState { + let before = std::fs::File::open(kar) + .and_then(|f| f.metadata()) + .ok() + .and_then(|m| FileIdentity::of(&m)); + let stamped = self.config.verify_stamps + && before.is_some_and(|id| self.stamps.trusts("kar-source", &archive_sha256(), &id)); + SourceState { before, stamped } + } + + fn copy_archive( + &self, + kar: &Path, + extents: Option<&[leleka_model_format::kar::Extent]>, + ) -> SealedCopy { + let log = &self.log; + let mut progress = |done: u64, total: u64| { + log.line(&format!( + "sealing archive: {:.1} of {:.1} GiB", + done as f64 / 1073741824.0, + total as f64 / 1073741824.0 + )); + }; + match extents { + Some(list) => { + sealed::seal_extents_report(kar, Some(ARCHIVE_BYTES), list, &mut progress) + } + None => sealed::seal_file_report(kar, Some(ARCHIVE_BYTES), &mut progress), + } + } + + async fn await_preverify(&self, preverify: Option<&mut Child>) -> Result<(), Flow> { + let Some(child) = preverify else { + return Ok(()); + }; + let waited = Instant::now(); + match child.wait().await { + Ok(status) if status.success() => { + self.log.line(&format!( + "shards verified ({:.1}s after the copy ended)", + waited.elapsed().as_secs_f32() + )); + Ok(()) + } + Ok(status) => fail( + 1, + format!( + "a shard does not match its pinned digest ({status}); see {}", + self.paths.logs().join("preverify.log").display() + ), + ), + Err(error) => fail(1, format!("shard verification did not finish: {error}")), + } + } + + fn accept_sealed( + &mut self, + sealed: SealedCopy, + sparse: Option<[u8; 32]>, + source: &SourceState, + started: Instant, + ) -> Result { + let (file, identity, read) = match sealed { + Ok(copy) => copy, + Err(message) => return fail(1, format!("cannot seal the archive: {message}")), + }; + self.log.line(&format!( + "sealed memfd ready in {:.1}s (read: {} blocks, {:.0} MB/s)", + started.elapsed().as_secs_f32(), + read.strategy.as_str(), + read.mb_per_s() + )); + self.record_source_state(sparse, identity, source); + if self.archive_attested { + self.log.line(concat!( + "the archive file matches its verification stamp: ", + "the engine will not hash the copy again" + )); + } + Ok(file) + } + + fn record_source_state( + &mut self, + sparse: Option<[u8; 32]>, + identity: Option, + source: &SourceState, + ) { + if sparse.is_some() { + // A sparse copy says nothing about the archive file as a whole: no identity, no stamp, no attestation. + self.archive_sparse_pin = sparse; + self.source_identity = None; + self.archive_attested = false; + } else { + self.source_identity = identity; + self.archive_attested = source.stamped && identity == source.before; + } + } +} diff --git a/crates/deploy/src/supervisor/children.rs b/crates/deploy/src/supervisor/children.rs index afa51384..0314ed17 100644 --- a/crates/deploy/src/supervisor/children.rs +++ b/crates/deploy/src/supervisor/children.rs @@ -36,7 +36,14 @@ impl Supervisor { command.env(key, value); } } - #[cfg(windows)] + self.library_path_env(command); + for (key, value) in extra { + command.env(key, value); + } + } + + #[cfg(windows)] + fn library_path_env(&self, command: &mut Command) { if let Some(extra_path) = self.env.get("LD_LIBRARY_PATH").filter(|p| !p.is_empty()) { // The loader flags of the engine search the application directory and System32 plus the directories named // here (`leleka-libc-shim` registers them), so the cuBLAS DLLs can stay where the operator keeps them. @@ -44,7 +51,10 @@ impl Supervisor { let existing = std::env::var("PATH").unwrap_or_default(); command.env("PATH", format!("{extra_path};{existing}")); } - #[cfg(not(windows))] + } + + #[cfg(not(windows))] + fn library_path_env(&self, command: &mut Command) { if let Some(extra_path) = self.env.get("LD_LIBRARY_PATH") { let existing = std::env::var("LD_LIBRARY_PATH").unwrap_or_default(); let joined = if existing.is_empty() { @@ -54,9 +64,6 @@ impl Supervisor { }; command.env("LD_LIBRARY_PATH", joined); } - for (key, value) in extra { - command.env(key, value); - } } pub(super) fn spawn( @@ -67,10 +74,7 @@ impl Supervisor { extra: &BTreeMap, stdin: Option, ) -> Result { - let log = private_append(&self.paths.logs().join(format!("{name}.log"))) - .and_then(|f| f.try_clone().map(|g| (f, g))) - .map_err(|e| format!("cannot open the {name} log: {e}")); - let (out, err) = match log { + let (out, err) = match self.open_child_log(name) { Ok(pair) => pair, Err(message) => return fail(1, message), }; @@ -81,10 +85,7 @@ impl Supervisor { .stdout(Stdio::from(out)) .stderr(Stdio::from(err)) .kill_on_drop(true); - command.stdin(match stdin { - Some(file) => Stdio::from(file), - None => Stdio::null(), - }); + command.stdin(stdin.map_or_else(Stdio::null, Stdio::from)); self.child_env(&mut command, extra); match command.spawn() { Ok(child) => Ok(child), @@ -95,6 +96,13 @@ impl Supervisor { } } + /// The log file of the child, opened twice: for its standard output and its standard error. + fn open_child_log(&self, name: &str) -> Result<(File, File), String> { + private_append(&self.paths.logs().join(format!("{name}.log"))) + .and_then(|f| f.try_clone().map(|g| (f, g))) + .map_err(|e| format!("cannot open the {name} log: {e}")) + } + /// End a hung engine without ceremony: SIGKILL, and wait for the kernel to reap it (which frees the pinned memory /// and the VRAM). A process that stays in uninterruptible sleep cannot be removed from here: that ends the service /// with a message, because only a reboot helps. diff --git a/crates/deploy/src/supervisor/engine.rs b/crates/deploy/src/supervisor/engine.rs index d017829f..0c107969 100644 --- a/crates/deploy/src/supervisor/engine.rs +++ b/crates/deploy/src/supervisor/engine.rs @@ -1,4 +1,4 @@ -//! Starting the engine, loading the model through `leleka-cli` and recovering a dead engine. +//! Starting the engine, waiting for its port, the `leleka-cli` calls and recovering a dead engine. use super::*; @@ -11,40 +11,9 @@ impl Supervisor { let (env, tier) = crate::expert_profile::start_environment(&self.config, &self.paths.dirs.assets); self.log.line(&tier.line()); - let inference = self.paths.bin("leleka-inference"); - let (kar_arg, stdin) = match &self.archive { - Some(file) => ( - KarArg::Fd, - Some(file.try_clone().map_err(|e| { - Flow::Fatal(Failure { - code: 1, - message: format!("cannot duplicate the sealed descriptor: {e}"), - }) - })?), - ), - None if self.config.profile.kar_source == KarSource::None => (KarArg::None, None), - None => (KarArg::File, None), - }; - let mut engine_args = self.config.engine_args(kar_arg); - if let Some(pin) = self.archive_sparse_pin - && stdin.is_some() - { - engine_args.push("--kar-sparse-extents-sha256".into()); - engine_args.push(pin.iter().map(|b| format!("{b:02x}")).collect()); - } else if self.archive_attested && stdin.is_some() { - engine_args.push("--kar-attested-by-stamp".into()); - } - let mut engine = if stdin.is_some() { - let mut args = vec![ - "exec-inherit".to_owned(), - "--".to_owned(), - inference.display().to_string(), - ]; - args.extend(engine_args); - self.spawn("engine", &self.paths.bin("leleka"), &args, &env, stdin)? - } else { - self.spawn("engine", &inference, &engine_args, &env, None)? - }; + let (kar_arg, stdin) = self.archive_handoff()?; + let engine_args = self.engine_arguments(kar_arg, stdin.is_some()); + let mut engine = self.spawn_engine(engine_args, &env, stdin)?; self.pids[0] = engine.id(); self.log.line(&format!( "engine started (pid {:?}); the log is {}", @@ -57,29 +26,89 @@ impl Supervisor { self.pids[0] = None; return Err(flow); } - // The engine hashed the sealed copy (or was told it matched). Either way this memfd is known good for the - // life of this supervisor, so a restarted engine need not hash it again; and when the copy came from a file - // in a stable state, record that state so the next start of the service can skip the hash too. + self.remember_verified_archive(); + Ok(engine) + } + + /// How the engine gets the archive: a duplicate of the sealed descriptor on its standard input, the file, or + /// nothing. + fn archive_handoff(&self) -> Result<(KarArg, Option), Flow> { + match &self.archive { + Some(file) => { + let stdin = file.try_clone().map_err(|e| { + Flow::Fatal(Failure { + code: 1, + message: format!("cannot duplicate the sealed descriptor: {e}"), + }) + })?; + Ok((KarArg::Fd, Some(stdin))) + } + None if self.config.profile.kar_source == KarSource::None => Ok((KarArg::None, None)), + None => Ok((KarArg::File, None)), + } + } + + fn engine_arguments(&self, kar_arg: KarArg, has_descriptor: bool) -> Vec { + let mut engine_args = self.config.engine_args(kar_arg); + if let Some(pin) = self.archive_sparse_pin + && has_descriptor + { + engine_args.push("--kar-sparse-extents-sha256".into()); + engine_args.push(pin.iter().map(|b| format!("{b:02x}")).collect()); + } else if self.archive_attested && has_descriptor { + engine_args.push("--kar-attested-by-stamp".into()); + } + engine_args + } + + /// With a descriptor the engine runs through `leleka exec-inherit`, which hands the memfd on as its input. + fn spawn_engine( + &self, + engine_args: Vec, + env: &BTreeMap, + stdin: Option, + ) -> Result { + let inference = self.paths.bin("leleka-inference"); + if stdin.is_some() { + let mut args = vec![ + "exec-inherit".to_owned(), + "--".to_owned(), + inference.display().to_string(), + ]; + args.extend(engine_args); + self.spawn("engine", &self.paths.bin("leleka"), &args, env, stdin) + } else { + self.spawn("engine", &inference, &engine_args, env, None) + } + } + + /// The engine hashed the sealed copy (or was told it matched). Either way this memfd is known good for the + /// life of this supervisor, so a restarted engine need not hash it again; and when the copy came from a file + /// in a stable state, record that state so the next start of the service can skip the hash too. + fn remember_verified_archive(&mut self) { if self.config.verify_stamps && self.archive.is_some() && self.archive_sparse_pin.is_none() { if !self.archive_attested && let Some(identity) = self.source_identity { - match self - .stamps - .record("kar-source", &archive_sha256(), &identity) - { - Ok(()) => self - .log - .line("recorded the verification stamp of the archive file"), - Err(error) => self - .log - .line(&format!("could not record the archive stamp: {error}")), - } + self.record_archive_stamp(&identity); } self.archive_attested = true; } - Ok(engine) + } + + fn record_archive_stamp(&self, identity: &FileIdentity) { + match self + .stamps + .record("kar-source", &archive_sha256(), identity) + { + Ok(()) => self + .log + .line("recorded the verification stamp of the archive file"), + Err(error) => self + .log + .line(&format!("could not record the archive stamp: {error}")), + } } pub(super) async fn wait_port( @@ -94,15 +123,7 @@ impl Supervisor { if self.stopping() { return Err(Flow::Stopped); } - if let Ok(Some(status)) = watched.try_wait() { - return fail( - 1, - format!( - "{what} exited ({status}) before listening on {address}; see {}", - self.paths.logs().display() - ), - ); - } + self.check_not_exited(watched, what, address)?; if tokio::net::TcpStream::connect(address).await.is_ok() { return Ok(()); } @@ -121,6 +142,24 @@ impl Supervisor { } } + fn check_not_exited( + &self, + watched: &mut Child, + what: &str, + address: SocketAddr, + ) -> Result<(), Flow> { + if let Ok(Some(status)) = watched.try_wait() { + return fail( + 1, + format!( + "{what} exited ({status}) before listening on {address}; see {}", + self.paths.logs().display() + ), + ); + } + Ok(()) + } + pub(super) async fn cli(&self, args: &[&str]) -> Result<(bool, String), String> { let mut command = Command::new(self.paths.bin("leleka-cli")); command @@ -142,136 +181,12 @@ impl Supervisor { )) } - pub(super) async fn load_model( - &mut self, - engine: &mut Child, - gateway: &mut Child, - ) -> Result<(), Flow> { - let engine_addr = self.engine_addr; - self.wait_port(engine_addr, engine, "the engine", Duration::from_secs(300)) - .await?; - let daemon_addr = self.daemon_addr; - self.wait_port(daemon_addr, gateway, "the gateway", Duration::from_secs(60)) - .await?; - let id = self.config.model_id.clone(); - // The gateway connects to the engine lazily; wait until it reports the runtime connected. - let started = Instant::now(); - loop { - if self.stopping() { - return Err(Flow::Stopped); - } - if let Ok(Some(status)) = engine.try_wait() { - return fail( - 1, - format!("the engine exited ({status}) before the gateway connected"), - ); - } - if let Ok((true, text)) = self.cli(&["status"]).await - && parse_runtime_status(&text, &id).is_some_and(|(connected, _)| connected) - { - break; - } - if started.elapsed() > Duration::from_secs(120) { - return fail(1, "the gateway did not connect to the engine within 120 s"); - } - if !self.pause(Duration::from_secs(2)).await { - return Err(Flow::Stopped); - } - } - self.set_phase( - Phase::Loading, - "loading the model (verifies the shards and the archive)", - ); - self.log.line("loading the model: leleka-cli load-mtp (the engine verifies SHA-256 of shards and archive; this takes minutes)"); - let operation: Option<(String, String)> = match self - .cli(&["load-mtp", &id, self.config.mtp_profile()]) - .await - { - Ok((true, text)) => parse_operation(&text), - // The CLI never retries an uncertain command; neither do we. - Ok((false, text)) => { - return fail( - 1, - format!( - "load-mtp was refused: {}", - text.lines().last().unwrap_or("no output") - ), - ); - } - Err(message) => return fail(1, message), - }; - let started = Instant::now(); - let mut last_report = Instant::now(); - loop { - if self.stopping() { - return Err(Flow::Stopped); - } - if let Ok(Some(status)) = engine.try_wait() { - return fail( - 1, - format!( - "the engine exited ({status}) while loading; see {}", - self.paths.logs().join("engine.log").display() - ), - ); - } - if let Ok((true, text)) = self.cli(&["status"]).await - && parse_runtime_status(&text, &id).is_some_and(|(_, ready)| ready) - { - self.log.line(&format!( - "model loaded in {:.0}s", - started.elapsed().as_secs_f32() - )); - return Ok(()); - } - // The engine process stays up when its load fails; the operation record says so. Do not wait - // out the timeout for a load that has already been refused. - if let Some((operation_id, epoch)) = &operation - && let Ok((true, text)) = self.cli(&["operation", &id, operation_id, epoch]).await - && let Some(state) = parse_operation_state(&text) - && matches!(state, OPERATION_FAILED | OPERATION_INDETERMINATE) - { - return fail( - 1, - format!( - "the engine {} the load; the last lines of {}: -{}", - if state == OPERATION_FAILED { - "refused" - } else { - "lost" - }, - self.paths.logs().join("engine.log").display(), - tail_of(&self.paths.logs().join("engine.log"), 8) - ), - ); - } - if started.elapsed() > Duration::from_secs(self.config.load_timeout_s) { - return fail( - 1, - format!( - "the model was not ready within {} s; see {}", - self.config.load_timeout_s, - self.paths.logs().join("engine.log").display() - ), - ); - } - if last_report.elapsed() >= Duration::from_secs(30) { - last_report = Instant::now(); - self.log.line(&format!( - "still loading ({:.0}s)", - started.elapsed().as_secs_f32() - )); - } - if !self.pause(Duration::from_secs(3)).await { - return Err(Flow::Stopped); - } - } - } - - /// The engine process is gone (it exited, or `hard_kill` ended it): start it again, waiting longer after each attempt in a - /// row, until it is ready, or give up after `restart.max_engine_restarts` and let the caller end the service (systemd - /// then starts everything afresh). A start that fails (the load is refused, the port is taken) counts as an attempt. + /// The engine process is gone (it exited, or `hard_kill` ended it): start it again, waiting longer after each + /// attempt in a + /// row, until it is ready, or give up after `restart.max_engine_restarts` and let the caller end the service + /// (systemd + /// then starts everything afresh). A start that fails (the load is refused, the port is taken) counts as an + /// attempt. pub(super) async fn recover_engine( &mut self, engine: &mut Child, @@ -279,52 +194,72 @@ impl Supervisor { ready_since: &mut Instant, reason: String, ) -> Result<(), Flow> { - self.pids[0] = None; - self.restarts_total += 1; - self.last_restart = Some((unix_now(), reason.clone())); - if ready_since.elapsed() >= Duration::from_secs(self.config.restart.stable_after_s) { - self.engine_restarts = 0; - } + self.begin_recovery(ready_since, &reason); loop { - if self.engine_restarts >= self.config.restart.max_engine_restarts { - return fail( - 1, - format!( - "the engine failed {} times in a row (last: {reason}); see {}", - self.engine_restarts, - self.paths.logs().join("engine.log").display() - ), - ); - } + self.check_restart_budget(&reason)?; self.engine_restarts += 1; let wait = self.config.restart.backoff(self.engine_restarts); - self.set_phase( - Phase::EngineRestarting, - &format!( - "restarting the engine (attempt {} of {}, in {} s): {reason}", - self.engine_restarts, - self.config.restart.max_engine_restarts, - wait.as_secs() - ), - ); + self.announce_restart(wait, &reason); if !self.pause(wait).await { return Err(Flow::Stopped); } - match self.start_engine(gateway).await { - Ok(child) => { - *engine = child; - self.set_phase(Phase::Ready, "ready (engine restarted)"); - *ready_since = Instant::now(); - return Ok(()); - } - Err(Flow::Stopped) => return Err(Flow::Stopped), - Err(Flow::Fatal(failure)) => { - self.log.line(&format!( - "the engine did not come back: {}", - failure.message - )); - } + if let Some(child) = self.try_start_engine(gateway).await? { + *engine = child; + self.set_phase(Phase::Ready, "ready (engine restarted)"); + *ready_since = Instant::now(); + return Ok(()); } } } + + /// The engine is gone: count the restart, and forget the attempts in a row when the service was stable. + fn begin_recovery(&mut self, ready_since: &Instant, reason: &str) { + self.pids[0] = None; + self.restarts_total += 1; + self.last_restart = Some((unix_now(), reason.to_owned())); + if ready_since.elapsed() >= Duration::from_secs(self.config.restart.stable_after_s) { + self.engine_restarts = 0; + } + } + + /// One start: the engine, or `None` after a failure that is logged (the next attempt follows); a stop ends it. + async fn try_start_engine(&mut self, gateway: &mut Child) -> Result, Flow> { + match self.start_engine(gateway).await { + Ok(child) => Ok(Some(child)), + Err(Flow::Stopped) => Err(Flow::Stopped), + Err(Flow::Fatal(failure)) => { + self.log.line(&format!( + "the engine did not come back: {}", + failure.message + )); + Ok(None) + } + } + } + + fn check_restart_budget(&self, reason: &str) -> Result<(), Flow> { + if self.engine_restarts >= self.config.restart.max_engine_restarts { + return fail( + 1, + format!( + "the engine failed {} times in a row (last: {reason}); see {}", + self.engine_restarts, + self.paths.logs().join("engine.log").display() + ), + ); + } + Ok(()) + } + + fn announce_restart(&mut self, wait: Duration, reason: &str) { + self.set_phase( + Phase::EngineRestarting, + &format!( + "restarting the engine (attempt {} of {}, in {} s): {reason}", + self.engine_restarts, + self.config.restart.max_engine_restarts, + wait.as_secs() + ), + ); + } } diff --git a/crates/deploy/src/supervisor/live_reconfigure.rs b/crates/deploy/src/supervisor/live_reconfigure.rs index db7d60fd..b3d0601f 100644 --- a/crates/deploy/src/supervisor/live_reconfigure.rs +++ b/crates/deploy/src/supervisor/live_reconfigure.rs @@ -18,71 +18,129 @@ impl Supervisor { gateway: &mut Child, api: &mut Child, ) -> Result<(), Flow> { - let id = request.id.clone(); + if self.settings_only(&request) { + return Ok(()); + } + let resident = self.archive.is_some(); + if self.refused_before_stopping(&request, resident) { + return Ok(()); + } + self.stop_engine_for(&request, engine).await; + let verdict = self.plan_on_stopped_host(&request, resident).await?; + let previous = self.config.clone(); + let failure = match verdict { + Ok(planned) => { + self.start_reconfigured(planned.config, &request, &previous, (engine, gateway, api)) + .await? + } + Err(why) => Some(why), + }; + let Some(refusal) = failure else { + return Ok(()); + }; + self.restore_previous(previous, &request, refusal, engine, gateway) + .await + } + + /// Log the request; a request without a budget or preset change is recorded and done. True when it was. + fn settings_only(&mut self, request: &reconfigure::Request) -> bool { + self.log_request(request); + if request.needs_restart() { + return false; + } + self.record_settings_only(request); + true + } + + fn log_request(&self, request: &reconfigure::Request) { self.log.line(&format!( - "reconfigure {id}: budget {:?} GiB, preset {:?}, settings {}, persist {}", + "reconfigure {}: budget {:?} GiB, preset {:?}, settings {}, persist {}", + request.id, request.gpu_budget_gib, request.preset.map(|p| p.as_str()), serde_json::Value::Object(request.settings.clone()), request.persist )); - if !request.needs_restart() { - let mut next = self.config.clone(); - match reconfigure::record_settings(&mut next, &request.settings) { - Err(why) => self.answer(&id, reconfigure::State::Refused, why, false), - Ok(changed) => { - self.config = next; - let (persisted, note) = if request.persist { - match reconfigure::persist(&self.paths, &self.config) { - Ok(()) => (true, "written to leleka.json".to_owned()), - Err(why) => (false, format!("not persisted: {why}")), - } - } else { - (false, "in force until the service restarts".to_owned()) - }; - self.answer( - &id, - reconfigure::State::Done, - format!("recorded {changed:?}; {note}"), - persisted, - ); - } + } + + /// Settings alone: only the configuration in force changes (and the file, when asked). + fn record_settings_only(&mut self, request: &reconfigure::Request) { + let id = &request.id; + let mut next = self.config.clone(); + match reconfigure::record_settings(&mut next, &request.settings) { + Err(why) => self.answer(id, reconfigure::State::Refused, why, false), + Ok(changed) => { + self.config = next; + let (persisted, note) = self.persist_note(request.persist); + self.answer( + id, + reconfigure::State::Done, + format!("recorded {changed:?}; {note}"), + persisted, + ); } - return Ok(()); } - let resident = self.archive.is_some(); - let facts = self.host_facts(); - match reconfigure::plan( - &self.config, - &request, - &reconfigure::optimistic(&facts), - resident, - ) { + } + + /// Write the configuration when asked: whether it was written, and the words for the answer. + fn persist_note(&self, persist: bool) -> (bool, String) { + if !persist { + return (false, "in force until the service restarts".to_owned()); + } + match reconfigure::persist(&self.paths, &self.config) { + Ok(()) => (true, "written to leleka.json".to_owned()), + Err(why) => (false, format!("not persisted: {why}")), + } + } + + /// The first planning, without disturbing the service. True when the request was answered (refused or already in + /// force). + fn refused_before_stopping(&mut self, request: &reconfigure::Request, resident: bool) -> bool { + let id = &request.id; + match self.plan_on_optimistic_host(request, resident) { Err(why) => { self.log.line(&format!( "reconfigure {id} refused before any change: {why}" )); self.answer( - &id, + id, reconfigure::State::Refused, format!("{why}; nothing was changed"), false, ); - return Ok(()); + true } Ok(planned) if planned.unchanged => { self.answer( - &id, + id, reconfigure::State::Done, "the engine already runs with these settings", false, ); - return Ok(()); + true } - Ok(_) => {} + Ok(_) => false, } + } + + /// The plan against what the host would offer once the engine is stopped. + fn plan_on_optimistic_host( + &self, + request: &reconfigure::Request, + resident: bool, + ) -> Result { + let facts = self.host_facts(); + reconfigure::plan( + &self.config, + request, + &reconfigure::optimistic(&facts), + resident, + ) + } + + async fn stop_engine_for(&mut self, request: &reconfigure::Request, engine: &mut Child) { self.answer( - &id, + &request.id, reconfigure::State::Running, "stopping the engine", false, @@ -96,79 +154,105 @@ impl Supervisor { ); self.kill_children(&mut [Some(&mut *engine)]).await; self.pids[0] = None; - // The memory of the card returns when the process is gone; give the driver a moment before asking what is free. + } + + /// The memory of the card returns when the process is gone; give the driver a moment before asking what is free. + async fn plan_on_stopped_host( + &mut self, + request: &reconfigure::Request, + resident: bool, + ) -> Result, Flow> { let mut verdict = Err(String::new()); for attempt in 0..10 { if !self.pause(Duration::from_secs(1)).await { return Err(Flow::Stopped); } - verdict = reconfigure::plan(&self.config, &request, &self.host_facts(), resident); + verdict = reconfigure::plan(&self.config, request, &self.host_facts(), resident); let waiting_for_vram = matches!(&verdict, Err(why) if why.starts_with("GPU memory")); if !waiting_for_vram || attempt == 9 { break; } } - let previous = self.config.clone(); - let refusal = match verdict { - Ok(planned) => { - self.config = planned.config; - self.log.line(&format!( - "reconfigure: starting the engine with {}", - reconfigure::effective(&self.config) - )); - match self.start_engine(gateway).await { - Ok(child) => { - *engine = child; - let mut persisted = false; - let mut note = "in force until the service restarts".to_owned(); - if request.persist { - match reconfigure::persist(&self.paths, &self.config) { - Ok(()) => { - persisted = true; - note = "written to leleka.json".to_owned(); - // the API advertises the context of strata.json: follow it - if self.config.profile.context_tokens - != previous.profile.context_tokens - { - self.restart_api(api).await?; - } - } - Err(why) => note = format!("not persisted: {why}"), - } - } - self.set_phase(Phase::Ready, "ready (engine reconfigured)"); - self.log.line("reconfigure: done"); - self.answer( - &id, - reconfigure::State::Done, - format!("the engine runs with the new settings; {note}"), - persisted, - ); - return Ok(()); - } - Err(Flow::Stopped) => return Err(Flow::Stopped), - Err(Flow::Fatal(failure)) => failure.message, - } + Ok(verdict) + } + + /// Start the engine with the planned configuration. `None`: it runs and the request is answered; `Some`: why it + /// did not. + async fn start_reconfigured( + &mut self, + planned: RunConfig, + request: &reconfigure::Request, + previous: &RunConfig, + (engine, gateway, api): (&mut Child, &mut Child, &mut Child), + ) -> Result, Flow> { + self.config = planned; + self.log.line(&format!( + "reconfigure: starting the engine with {}", + reconfigure::effective(&self.config) + )); + match self.start_engine(gateway).await { + Ok(child) => { + *engine = child; + self.announce_reconfigured(request, previous, api).await?; + Ok(None) } - Err(why) => why, - }; - // Refused on the stopped host, or the new engine did not come up: put the previous engine back. + Err(Flow::Stopped) => Err(Flow::Stopped), + Err(Flow::Fatal(failure)) => Ok(Some(failure.message)), + } + } + + /// The new engine runs: write the configuration when asked, follow a new context in the API, and answer. + async fn announce_reconfigured( + &mut self, + request: &reconfigure::Request, + previous: &RunConfig, + api: &mut Child, + ) -> Result<(), Flow> { + let (persisted, note) = self.persist_note(request.persist); + // the API advertises the context of strata.json: follow it + if persisted && self.config.profile.context_tokens != previous.profile.context_tokens { + self.restart_api(api).await?; + } + self.set_phase(Phase::Ready, "ready (engine reconfigured)"); + self.log.line("reconfigure: done"); + self.answer( + &request.id, + reconfigure::State::Done, + format!("the engine runs with the new settings; {note}"), + persisted, + ); + Ok(()) + } + + /// Not even the previous engine starts: answer `failed` and give the flow back to end the service. + fn restore_failed(&self, id: &str, refusal: &str, flow: Flow) -> Flow { + let why = format!("{refusal}; the previous settings could not be restored either"); + self.answer(id, reconfigure::State::Failed, why, false); + flow + } + + /// Refused on the stopped host, or the new engine did not come up: put the previous engine back. + async fn restore_previous( + &mut self, + previous: RunConfig, + request: &reconfigure::Request, + refusal: String, + engine: &mut Child, + gateway: &mut Child, + ) -> Result<(), Flow> { self.config = previous; self.log.line(&format!( - "reconfigure {id}: {refusal}; restoring the previous settings" + "reconfigure {}: {refusal}; restoring the previous settings", + request.id )); let child = match self.start_engine(gateway).await { Ok(child) => child, - Err(flow) => { - let why = format!("{refusal}; the previous settings could not be restored either"); - self.answer(&id, reconfigure::State::Failed, why, false); - return Err(flow); - } + Err(flow) => return Err(self.restore_failed(&request.id, &refusal, flow)), }; *engine = child; self.set_phase(Phase::Ready, "ready (previous settings restored)"); self.answer( - &id, + &request.id, reconfigure::State::Refused, format!("{refusal}; the previous settings are back"), false, diff --git a/crates/deploy/src/supervisor/load.rs b/crates/deploy/src/supervisor/load.rs new file mode 100644 index 00000000..d16a4375 --- /dev/null +++ b/crates/deploy/src/supervisor/load.rs @@ -0,0 +1,187 @@ +//! Loading the model into a started engine through `leleka-cli` and waiting until it is ready. + +use super::*; + +/// The id and epoch of a `load-mtp` operation, as the CLI reports them. +type Operation = (String, String); + +impl Supervisor { + pub(super) async fn load_model( + &mut self, + engine: &mut Child, + gateway: &mut Child, + ) -> Result<(), Flow> { + let engine_addr = self.engine_addr; + self.wait_port(engine_addr, engine, "the engine", Duration::from_secs(300)) + .await?; + let daemon_addr = self.daemon_addr; + self.wait_port(daemon_addr, gateway, "the gateway", Duration::from_secs(60)) + .await?; + let id = self.config.model_id.clone(); + self.wait_gateway_connected(engine, &id).await?; + let operation = self.request_load(&id).await?; + self.wait_model_ready(engine, &id, operation.as_ref()).await + } + + /// The gateway connects to the engine lazily; wait until it reports the runtime connected. + async fn wait_gateway_connected(&mut self, engine: &mut Child, id: &str) -> Result<(), Flow> { + let started = Instant::now(); + loop { + if self.stopping() { + return Err(Flow::Stopped); + } + if let Ok(Some(status)) = engine.try_wait() { + return fail( + 1, + format!("the engine exited ({status}) before the gateway connected"), + ); + } + if let Ok((true, text)) = self.cli(&["status"]).await + && parse_runtime_status(&text, id).is_some_and(|(connected, _)| connected) + { + return Ok(()); + } + if started.elapsed() > Duration::from_secs(120) { + return fail(1, "the gateway did not connect to the engine within 120 s"); + } + if !self.pause(Duration::from_secs(2)).await { + return Err(Flow::Stopped); + } + } + } + + /// The typed `load-mtp`; the operation it started, when the CLI printed one. + async fn request_load(&mut self, id: &str) -> Result, Flow> { + self.set_phase( + Phase::Loading, + "loading the model (verifies the shards and the archive)", + ); + self.log.line(concat!( + "loading the model: leleka-cli load-mtp (the engine verifies SHA-256 ", + "of shards and archive; this takes minutes)" + )); + match self.cli(&["load-mtp", id, self.config.mtp_profile()]).await { + Ok((true, text)) => Ok(parse_operation(&text)), + // The CLI never retries an uncertain command; neither do we. + Ok((false, text)) => fail( + 1, + format!( + "load-mtp was refused: {}", + text.lines().last().unwrap_or("no output") + ), + ), + Err(message) => fail(1, message), + } + } + + async fn wait_model_ready( + &mut self, + engine: &mut Child, + id: &str, + operation: Option<&Operation>, + ) -> Result<(), Flow> { + let started = Instant::now(); + let mut last_report = Instant::now(); + loop { + if self.stopping() { + return Err(Flow::Stopped); + } + self.check_engine_loading(engine)?; + if self.model_is_ready(id).await { + self.log.line(&format!( + "model loaded in {:.0}s", + started.elapsed().as_secs_f32() + )); + return Ok(()); + } + self.check_load_progress(id, operation, started).await?; + if last_report.elapsed() >= Duration::from_secs(30) { + last_report = Instant::now(); + self.say_still_loading(started); + } + if !self.pause(Duration::from_secs(3)).await { + return Err(Flow::Stopped); + } + } + } + + /// The load has not been refused, and its time is not up. + async fn check_load_progress( + &self, + id: &str, + operation: Option<&Operation>, + started: Instant, + ) -> Result<(), Flow> { + self.check_load_not_failed(id, operation).await?; + self.check_load_deadline(started) + } + + fn say_still_loading(&self, started: Instant) { + self.log.line(&format!( + "still loading ({:.0}s)", + started.elapsed().as_secs_f32() + )); + } + + fn check_engine_loading(&self, engine: &mut Child) -> Result<(), Flow> { + if let Ok(Some(status)) = engine.try_wait() { + return fail( + 1, + format!( + "the engine exited ({status}) while loading; see {}", + self.paths.logs().join("engine.log").display() + ), + ); + } + Ok(()) + } + + async fn model_is_ready(&self, id: &str) -> bool { + matches!(self.cli(&["status"]).await, Ok((true, text)) + if parse_runtime_status(&text, id).is_some_and(|(_, ready)| ready)) + } + + /// The engine process stays up when its load fails; the operation record says so. Do not wait + /// out the timeout for a load that has already been refused. + async fn check_load_not_failed( + &self, + id: &str, + operation: Option<&Operation>, + ) -> Result<(), Flow> { + if let Some((operation_id, epoch)) = operation + && let Ok((true, text)) = self.cli(&["operation", id, operation_id, epoch]).await + && let Some(state) = parse_operation_state(&text) + && matches!(state, OPERATION_FAILED | OPERATION_INDETERMINATE) + { + return fail( + 1, + format!( + "the engine {} the load; the last lines of {}: +{}", + if state == OPERATION_FAILED { + "refused" + } else { + "lost" + }, + self.paths.logs().join("engine.log").display(), + tail_of(&self.paths.logs().join("engine.log"), 8) + ), + ); + } + Ok(()) + } + + fn check_load_deadline(&self, started: Instant) -> Result<(), Flow> { + if started.elapsed() > Duration::from_secs(self.config.load_timeout_s) { + return fail( + 1, + format!( + "the model was not ready within {} s; see {}", + self.config.load_timeout_s, + self.paths.logs().join("engine.log").display() + ), + ); + } + Ok(()) + } +} diff --git a/crates/deploy/src/supervisor/logfile.rs b/crates/deploy/src/supervisor/logfile.rs index ebc7a2b5..621b5661 100644 --- a/crates/deploy/src/supervisor/logfile.rs +++ b/crates/deploy/src/supervisor/logfile.rs @@ -94,14 +94,9 @@ impl Log { fields: &[leleka_obs::Field<'_>], ) { let now = leleka_obs::now_ms(); - let file_format = leleka_obs::Settings { - min_level: leleka_obs::Level::Debug, - format: leleka_obs::Format::Json, - debug: false, - legacy: false, - }; let file_line = - leleka_obs::format_line(&file_format, now, level, "supervisor", ev, fields, 0) + "\n"; + leleka_obs::format_line(&file_settings(), now, level, "supervisor", ev, fields, 0) + + "\n"; if level >= leleka_obs::settings().min_level { let shown = leleka_obs::format_line( leleka_obs::settings(), @@ -119,3 +114,13 @@ impl Log { } } } + +/// The format of `leleka.log`: JSON lines, every level. +fn file_settings() -> leleka_obs::Settings { + leleka_obs::Settings { + min_level: leleka_obs::Level::Debug, + format: leleka_obs::Format::Json, + debug: false, + legacy: false, + } +} diff --git a/crates/deploy/src/supervisor/signals.rs b/crates/deploy/src/supervisor/signals.rs index fc8a2c24..27debe44 100644 --- a/crates/deploy/src/supervisor/signals.rs +++ b/crates/deploy/src/supervisor/signals.rs @@ -3,33 +3,58 @@ use super::*; pub(super) fn spawn_signal_task(stop: watch::Sender, run_dir: PathBuf) { - // Windows: Ctrl-C / Ctrl-Break / console close in this terminal, or `leleka down` from another one (a stop file). #[cfg(windows)] + stop_on_console_events(stop, run_dir); + #[cfg(unix)] { - let request = run_dir.join(STOP_REQUEST_FILE); - let _ = std::fs::remove_file(&request); - tokio::spawn(async move { - let mut ctrl_break = tokio::signal::windows::ctrl_break().ok(); - let mut ctrl_close = tokio::signal::windows::ctrl_close().ok(); - loop { - tokio::select! { - _ = tokio::signal::ctrl_c() => break, - _ = async { match ctrl_break.as_mut() { Some(s) => { s.recv().await; } None => std::future::pending::<()>().await } } => break, - _ = async { match ctrl_close.as_mut() { Some(s) => { s.recv().await; } None => std::future::pending::<()>().await } } => break, - _ = tokio::time::sleep(Duration::from_millis(500)) => { - if request.exists() { - let _ = std::fs::remove_file(&request); - break; - } + let _ = run_dir; + stop_on_unix_signals(stop); + } + #[cfg(not(any(unix, windows)))] + { + let _ = run_dir; + drop(stop); + } +} + +/// Windows: Ctrl-C / Ctrl-Break / console close in this terminal, or `leleka down` from another one (a stop file). +#[cfg(windows)] +fn stop_on_console_events(stop: watch::Sender, run_dir: PathBuf) { + let request = run_dir.join(STOP_REQUEST_FILE); + let _ = std::fs::remove_file(&request); + tokio::spawn(async move { + let mut ctrl_break = tokio::signal::windows::ctrl_break().ok(); + let mut ctrl_close = tokio::signal::windows::ctrl_close().ok(); + loop { + tokio::select! { + _ = tokio::signal::ctrl_c() => break, + _ = recv_or_never(ctrl_break.as_mut().map(|s| s.recv())) => break, + _ = recv_or_never(ctrl_close.as_mut().map(|s| s.recv())) => break, + _ = tokio::time::sleep(Duration::from_millis(500)) => { + if request.exists() { + let _ = std::fs::remove_file(&request); + break; } } } - let _ = stop.send(true); - }); + } + let _ = stop.send(true); + }); +} + +/// Wait for the event when the signal could be registered; never ends when it could not. +#[cfg(windows)] +async fn recv_or_never(event: Option>>) { + match event { + Some(event) => { + event.await; + } + None => std::future::pending::<()>().await, } - #[cfg(not(windows))] - let _ = run_dir; - #[cfg(unix)] +} + +#[cfg(unix)] +fn stop_on_unix_signals(stop: watch::Sender) { tokio::spawn(async move { use tokio::signal::unix::{SignalKind, signal}; let (Ok(mut term), Ok(mut int)) = ( @@ -44,8 +69,6 @@ pub(super) fn spawn_signal_task(stop: watch::Sender, run_dir: PathBuf) { } let _ = stop.send(true); }); - #[cfg(not(any(unix, windows)))] - drop(stop); } #[cfg(target_os = "linux")] diff --git a/crates/deploy/src/supervisor/startup.rs b/crates/deploy/src/supervisor/startup.rs index 295c6999..07b912c7 100644 --- a/crates/deploy/src/supervisor/startup.rs +++ b/crates/deploy/src/supervisor/startup.rs @@ -12,10 +12,50 @@ pub async fn run(options: Options) -> i32 { } } +/// A failure of the setup before the service runs: exit code 2. +fn setup_failure(message: String) -> Failure { + Failure { code: 2, message } +} + pub(super) async fn run_inner(options: Options) -> Result<(), Failure> { - let config = - RunConfig::read(&options.config).map_err(|message| Failure { code: 2, message })?; + let config = RunConfig::read(&options.config).map_err(setup_failure)?; let paths = config.paths(); + create_directories(&paths)?; + let env = read_environment(&paths)?; + let api_key = read_api_key(&paths)?; + check_binaries(&paths)?; + let addresses = parse_addresses(&config)?; + register_secrets(&api_key, &env); + let log_file = open_log(&paths.logs().join("leleka.log")) + .map_err(|e| setup_failure(format!("cannot open the log: {e}")))?; + + let (stop_tx, stop_rx) = watch::channel(false); + spawn_signal_task(stop_tx, paths.run_dir()); + let mut supervisor = Supervisor::assemble( + Assembly { + config, + paths, + env, + api_key, + log_file, + shutdown: stop_rx, + }, + addresses, + ); + supervisor.set_phase(Phase::Starting, "starting"); + let outcome = supervisor.drive(options.kar_fd).await; + supervisor.conclude(outcome) +} + +/// No log line of this process or of its children may ever contain the key or a token. +fn register_secrets(api_key: &str, env: &BTreeMap) { + leleka_obs::register_secret(api_key); + for value in env.values() { + leleka_obs::register_secret(value); + } +} + +fn create_directories(paths: &Paths) -> Result<(), Failure> { let stamps_dir = paths.engine_stamps(); for dir in [ paths.logs(), @@ -23,10 +63,8 @@ pub(super) async fn run_inner(options: Options) -> Result<(), Failure> { paths.mtp_staging(), stamps_dir.clone(), ] { - std::fs::create_dir_all(&dir).map_err(|e| Failure { - code: 2, - message: format!("cannot create {}: {e}", dir.display()), - })?; + std::fs::create_dir_all(&dir) + .map_err(|e| setup_failure(format!("cannot create {}: {e}", dir.display())))?; } #[cfg(unix)] { @@ -35,34 +73,40 @@ pub(super) async fn run_inner(options: Options) -> Result<(), Failure> { let _ = std::fs::set_permissions(private, std::fs::Permissions::from_mode(0o700)); } } - let env_text = std::fs::read_to_string(paths.env_file()).map_err(|e| Failure { - code: 2, - message: format!( + Ok(()) +} + +/// The environment file with the two service tokens, which must be valid and different. +fn read_environment(paths: &Paths) -> Result, Failure> { + let env_text = std::fs::read_to_string(paths.env_file()).map_err(|e| { + setup_failure(format!( "cannot read {}: {e}; run `leleka up`", paths.env_file().display() - ), + )) })?; let env = parse_env_file(&env_text); let (runtime_token, gateway_token) = (env.get(RUNTIME_TOKEN_ENV), env.get(GATEWAY_TOKEN_ENV)); match (runtime_token, gateway_token) { - (Some(a), Some(b)) if valid_token(a) && valid_token(b) && a != b => {} - _ => { - return Err(Failure { - code: 2, - message: format!( - "{} must define two different {RUNTIME_TOKEN_ENV}/{GATEWAY_TOKEN_ENV} values of 32..4096 printable ASCII bytes", - paths.env_file().display() - ), - }); - } + (Some(a), Some(b)) if valid_token(a) && valid_token(b) && a != b => Ok(env), + _ => Err(setup_failure(format!( + concat!( + "{} must define two different {RUNTIME_TOKEN_ENV}/{GATEWAY_TOKEN_ENV} ", + "values of 32..4096 printable ASCII bytes" + ), + paths.env_file().display(), + RUNTIME_TOKEN_ENV = RUNTIME_TOKEN_ENV, + GATEWAY_TOKEN_ENV = GATEWAY_TOKEN_ENV + ))), } - let api_key = std::fs::read_to_string(paths.api_key()) - .map_err(|e| Failure { - code: 2, - message: format!("cannot read {}: {e}", paths.api_key().display()), - })? - .trim_end_matches(['\r', '\n']) - .to_owned(); +} + +fn read_api_key(paths: &Paths) -> Result { + let text = std::fs::read_to_string(paths.api_key()) + .map_err(|e| setup_failure(format!("cannot read {}: {e}", paths.api_key().display())))?; + Ok(text.trim_end_matches(['\r', '\n']).to_owned()) +} + +fn check_binaries(paths: &Paths) -> Result<(), Failure> { for name in [ "leleka", "strata-next", @@ -71,87 +115,93 @@ pub(super) async fn run_inner(options: Options) -> Result<(), Failure> { "leleka-cli", ] { if !paths.bin(name).is_file() { - return Err(Failure { - code: 2, - message: format!("{} is missing; run `leleka up`", paths.bin(name).display()), - }); + return Err(setup_failure(format!( + "{} is missing; run `leleka up`", + paths.bin(name).display() + ))); } } + Ok(()) +} + +/// The API, engine and daemon addresses of the configuration. +fn parse_addresses(config: &RunConfig) -> Result<(SocketAddr, SocketAddr, SocketAddr), Failure> { let parse = |label: &str, text: &str| -> Result { - text.parse().map_err(|_| Failure { - code: 2, - message: format!("ports.{label} is not an ip:port"), - }) + text.parse() + .map_err(|_| setup_failure(format!("ports.{label} is not an ip:port"))) }; - let (api_addr, engine_addr, daemon_addr) = ( - crate::config::probe_address(&config.ports.api).ok_or(Failure { - code: 2, - message: "ports.api is not an ip:port".into(), - })?, + Ok(( + crate::config::probe_address(&config.ports.api) + .ok_or_else(|| setup_failure("ports.api is not an ip:port".into()))?, parse("engine", &config.ports.engine)?, parse("daemon", &config.ports.daemon)?, - ); - // No log line of this process or of its children may ever contain the key or a token. - leleka_obs::register_secret(&api_key); - for value in env.values() { - leleka_obs::register_secret(value); - } - let log_file = open_log(&paths.logs().join("leleka.log")).map_err(|e| Failure { - code: 2, - message: format!("cannot open the log: {e}"), - })?; + )) +} - let (stop_tx, stop_rx) = watch::channel(false); - spawn_signal_task(stop_tx, paths.run_dir()); - let mut supervisor = Supervisor { - status_path: paths.status_file(), - config, - paths, - env, - api_key, - log: Log { - file: std::sync::Mutex::new(log_file), - }, - shutdown: stop_rx, - archive: None, - source_identity: None, - archive_attested: false, - archive_sparse_pin: None, - stamps: VerifyStamps::new(stamps_dir, false), - api_addr, - engine_addr, - daemon_addr, - engine_restarts: 0, - pids: [None; 3], - phase: Phase::Starting, - message: String::new(), - beats: 0, - started_unix: unix_now(), - restarts_total: 0, - last_restart: None, - health_note: "starting".into(), - }; - supervisor.set_phase(Phase::Starting, "starting"); - let outcome = supervisor.drive(options.kar_fd).await; - let result = match outcome { - Ok(()) | Err(Flow::Stopped) => Ok(()), - Err(Flow::Fatal(failure)) => { - supervisor.log.event( - leleka_obs::Level::Error, - "fatal", - &[ - ("code", failure.code.into()), - ("msg", format!("fatal: {}", failure.message).as_str().into()), - ], - ); - supervisor.set_phase(Phase::Failed, &failure.message); - Err(failure) +/// What `run_inner` has read and opened for the supervisor. +struct Assembly { + config: RunConfig, + paths: Paths, + env: BTreeMap, + api_key: String, + log_file: File, + shutdown: watch::Receiver, +} + +impl Supervisor { + fn assemble(parts: Assembly, addresses: (SocketAddr, SocketAddr, SocketAddr)) -> Self { + Supervisor { + status_path: parts.paths.status_file(), + stamps: VerifyStamps::new(parts.paths.engine_stamps(), false), + config: parts.config, + paths: parts.paths, + env: parts.env, + api_key: parts.api_key, + log: Log { + file: std::sync::Mutex::new(parts.log_file), + }, + shutdown: parts.shutdown, + archive: None, + source_identity: None, + archive_attested: false, + archive_sparse_pin: None, + api_addr: addresses.0, + engine_addr: addresses.1, + daemon_addr: addresses.2, + engine_restarts: 0, + pids: [None; 3], + phase: Phase::Starting, + message: String::new(), + beats: 0, + started_unix: unix_now(), + restarts_total: 0, + last_restart: None, + health_note: "starting".into(), } - }; - if result.is_ok() { - supervisor.set_phase(Phase::Stopped, "stopped"); } - result + + /// Record how the run ended: a stop is a success, a failure is logged and shown as the final phase. + fn conclude(&mut self, outcome: Result<(), Flow>) -> Result<(), Failure> { + let result = match outcome { + Ok(()) | Err(Flow::Stopped) => Ok(()), + Err(Flow::Fatal(failure)) => { + self.log.event( + leleka_obs::Level::Error, + "fatal", + &[ + ("code", failure.code.into()), + ("msg", format!("fatal: {}", failure.message).as_str().into()), + ], + ); + self.set_phase(Phase::Failed, &failure.message); + Err(failure) + } + }; + if result.is_ok() { + self.set_phase(Phase::Stopped, "stopped"); + } + result + } } #[cfg(windows)] diff --git a/crates/deploy/src/supervisor/status.rs b/crates/deploy/src/supervisor/status.rs index ebaa86e2..c896dd6f 100644 --- a/crates/deploy/src/supervisor/status.rs +++ b/crates/deploy/src/supervisor/status.rs @@ -16,13 +16,12 @@ impl Supervisor { } pub(super) fn write_status(&self) { - let (phase, message) = (self.phase, self.message.as_str()); let endpoint = format!("http://{}", self.api_addr); let doc = StatusDoc { schema_version: 1, - phase, - ready: phase == Phase::Ready, - message, + phase: self.phase, + ready: self.phase == Phase::Ready, + message: &self.message, updated_unix: unix_now(), supervisor_pid: std::process::id(), engine_pid: self.pids[0], diff --git a/crates/deploy/src/supervisor/supervise.rs b/crates/deploy/src/supervisor/supervise.rs index 47922904..120d32da 100644 --- a/crates/deploy/src/supervisor/supervise.rs +++ b/crates/deploy/src/supervisor/supervise.rs @@ -1,155 +1,146 @@ //! The supervision loop of a running service and its health sampling. use super::*; +use std::process::ExitStatus; + +/// What a branch of the supervision loop decided: carry on, or leave with this result (after the drain). +enum Step { + Go, + End(Result<(), Flow>), +} + +/// A stop ends the loop cleanly, anything else ends it with the failure. +fn end_of(flow: Flow) -> Step { + match flow { + Flow::Stopped => Step::End(Ok(())), + flow => Step::End(Err(flow)), + } +} + +fn describe_exit(status: std::io::Result) -> String { + status.map_or_else(|e| e.to_string(), |s| s.to_string()) +} + +/// The three children and the clocks the loop keeps about them. +struct Running { + engine: Child, + gateway: Child, + api: Child, + ready_since: Instant, + // Gateway and API restarts in a row; like the engine ones they are forgotten after a stable period, so that a + // service that + // runs for weeks is not ended by the sixth API crash of the month. + gateway_restarts: u32, + api_restarts: u32, + gateway_since: Instant, + api_since: Instant, + stable: Duration, + // `leleka reconfigure` leaves a request file; look for it once a second. + requests: tokio::time::Interval, + logs_tick: tokio::time::Interval, + health_tick: tokio::time::Interval, + watchdog: watchdog::Watchdog, +} + +fn skipping_interval(period: Duration) -> tokio::time::Interval { + let mut tick = tokio::time::interval(period); + tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); + tick +} + +impl Running { + fn new(config: &RunConfig, engine: Child, gateway: Child, api: Child) -> Self { + let health = config.health.clone(); + Self { + engine, + gateway, + api, + ready_since: Instant::now(), + gateway_restarts: 0, + api_restarts: 0, + gateway_since: Instant::now(), + api_since: Instant::now(), + stable: Duration::from_secs(config.restart.stable_after_s), + requests: skipping_interval(Duration::from_secs(1)), + logs_tick: skipping_interval(Duration::from_secs(10)), + health_tick: skipping_interval(Duration::from_secs(health.interval_s.max(1))), + watchdog: watchdog::Watchdog::new(watchdog::Limits { + fail: Duration::from_secs(health.fail_s), + max_request: Duration::from_secs(health.max_request_s), + }), + } + } + + /// A recovery that succeeded forgets what the watchdog suspected; one that did not ends the loop. + fn recovered(&mut self, result: Result<(), Flow>) -> Step { + match result { + Ok(()) => { + self.watchdog.reset(); + Step::Go + } + Err(flow) => end_of(flow), + } + } +} impl Supervisor { pub(super) async fn drive(&mut self, kar_fd: Option) -> Result<(), Flow> { // 1. the archive - self.archive = match (kar_fd, self.config.profile.kar_source) { - (Some(fd), KarSource::None) => { - return fail( - 2, - format!( - "descriptor {fd} was inherited but profile {} has kar_source none (no archive is used)", - self.config.profile.name - ), - ); - } - (None, KarSource::None) => { - self.log.line("kar_source none: no KAR archive; the PLE rows are read from the GGUF shard (qwen4exp-native-mtp-v1)"); - None - } - (Some(fd), _) => { - self.log.line(&format!( - "using the sealed archive descriptor {fd} inherited from the parent" - )); - self.archive_sparse_pin = self.sparse_pin()?; - Some( - sealed::open_inherited(fd) - .map_err(|message| Flow::Fatal(Failure { code: 2, message }))?, - ) - } - (None, KarSource::Memfd) => { - let kar = self.paths.kar(); - // `memfd_extents: ple_only`: only the byte ranges the serve path reads (about 16 GB of 55) go into the memfd. - let sparse = self.sparse_pin()?; - let extents = match sparse { - Some(_) => Some(Self::serve_extents(&kar)?), - None => None, - }; - match &extents { - Some(list) => { - self.set_phase( - Phase::Sealing, - "copying the archive extents the serve path reads into a sealed memfd", - ); - self.log.line(&format!( - "sealing {} extents ({:.2} GiB of {:.2} GiB) of {} into RAM; the rest of the memfd is a hole (once per service life)", - list.len(), - leleka_model_format::kar::extents_bytes(list) as f64 / 1073741824.0, - ARCHIVE_BYTES as f64 / 1073741824.0, - kar.display() - )); - } - None => { - self.set_phase(Phase::Sealing, "copying the archive into a sealed memfd"); - self.log.line(&format!( - "sealing {} into RAM (once per service life)", - kar.display() - )); - } - } - let started = Instant::now(); - let mut preverify = self.spawn_shard_preverify(); - // A stamp of the archive file (written after a start whose engine hashed the copy) lets the engine - // skip the hash of the memfd; it applies only if the file is still in the stamped state before - // AND after the copy. - let before = std::fs::File::open(&kar) - .and_then(|f| f.metadata()) - .ok() - .and_then(|m| FileIdentity::of(&m)); - let stamped = self.config.verify_stamps - && before - .is_some_and(|id| self.stamps.trusts("kar-source", &archive_sha256(), &id)); - let log = &self.log; - let mut progress = |done: u64, total: u64| { - log.line(&format!( - "sealing archive: {:.1} of {:.1} GiB", - done as f64 / 1073741824.0, - total as f64 / 1073741824.0 - )); - }; - let sealed = match &extents { - Some(list) => { - sealed::seal_extents_report(&kar, Some(ARCHIVE_BYTES), list, &mut progress) - } - None => sealed::seal_file_report(&kar, Some(ARCHIVE_BYTES), &mut progress), - }; - if let Some(child) = preverify.as_mut() { - let waited = Instant::now(); - match child.wait().await { - Ok(status) if status.success() => self.log.line(&format!( - "shards verified ({:.1}s after the copy ended)", - waited.elapsed().as_secs_f32() - )), - Ok(status) => { - return fail( - 1, - format!( - "a shard does not match its pinned digest ({status}); see {}", - self.paths.logs().join("preverify.log").display() - ), - ); - } - Err(error) => { - return fail(1, format!("shard verification did not finish: {error}")); - } - } - } - match sealed { - Ok((file, identity, read)) => { - self.log.line(&format!( - "sealed memfd ready in {:.1}s (read: {} blocks, {:.0} MB/s)", - started.elapsed().as_secs_f32(), - read.strategy.as_str(), - read.mb_per_s() - )); - if sparse.is_some() { - // A sparse copy says nothing about the archive file as a whole: no identity, no stamp, no attestation. - self.archive_sparse_pin = sparse; - self.source_identity = None; - self.archive_attested = false; - } else { - self.source_identity = identity; - self.archive_attested = stamped && identity == before; - } - if self.archive_attested { - self.log.line("the archive file matches its verification stamp: the engine will not hash the copy again"); - } - Some(file) - } - Err(message) => return fail(1, format!("cannot seal the archive: {message}")), - } - } - (None, KarSource::File) => None, - }; + self.archive = self.prepare_archive(kar_fd).await?; if self.stopping() { return Err(Flow::Stopped); } + // 2. gateway (needed for the typed load), engine, 3. public API + let mut running = self.start_children().await?; + // 4. supervise + let result = self.supervise(&mut running).await?; + // 5. drain: API first so streams end with a terminal event, then the gateway and the engine. + self.set_phase(Phase::Draining, "draining"); + self.log.line("stopping: API, gateway, engine"); + self.kill_children(&mut [ + Some(&mut running.api), + Some(&mut running.gateway), + Some(&mut running.engine), + ]) + .await; + self.pids = [None; 3]; + result + } - // 2. gateway (needed for the typed load) - self.set_phase(Phase::StartingGateway, "starting the gateway"); - let daemon_args = vec![ + fn daemon_args(&self) -> Vec { + vec![ "--config".to_owned(), self.paths.daemon_config().display().to_string(), - ]; - let mut gateway = self.spawn( + ] + } + + fn api_args(&self) -> Vec { + vec![ + "serve".to_owned(), + "--config".to_owned(), + self.paths.strata_config().display().to_string(), + ] + } + + fn spawn_gateway(&self) -> Result { + let program = self.paths.bin("leleka-daemon"); + self.spawn( "gateway", - &self.paths.bin("leleka-daemon"), - &daemon_args, + &program, + &self.daemon_args(), &BTreeMap::new(), None, - )?; + ) + } + + fn spawn_api(&self) -> Result { + let program = self.paths.bin("strata-next"); + self.spawn("api", &program, &self.api_args(), &BTreeMap::new(), None) + } + + async fn start_children(&mut self) -> Result { + self.set_phase(Phase::StartingGateway, "starting the gateway"); + let mut gateway = self.spawn_gateway()?; self.pids[1] = gateway.id(); let mut engine = match self.start_engine(&mut gateway).await { Ok(engine) => engine, @@ -158,34 +149,7 @@ impl Supervisor { return Err(flow); } }; - - // 3. public API - self.set_phase(Phase::StartingApi, "starting the API"); - let api_args = vec![ - "serve".to_owned(), - "--config".to_owned(), - self.paths.strata_config().display().to_string(), - ]; - let mut api = match self.spawn( - "api", - &self.paths.bin("strata-next"), - &api_args, - &BTreeMap::new(), - None, - ) { - Ok(child) => child, - Err(flow) => { - self.kill_children(&mut [Some(&mut engine), Some(&mut gateway)]) - .await; - return Err(flow); - } - }; - self.pids[2] = api.id(); - if let Err(flow) = self.wait_api_ready(&mut api).await { - self.kill_children(&mut [Some(&mut api), Some(&mut engine), Some(&mut gateway)]) - .await; - return Err(flow); - } + let api = self.start_api(&mut engine, &mut gateway).await?; self.set_phase(Phase::Ready, "ready"); self.log.line(&format!( "ready: http://{} model {} (profile {}, logs {})", @@ -194,152 +158,193 @@ impl Supervisor { self.config.profile.name, self.paths.logs().display() )); - let mut ready_since = Instant::now(); - // Gateway and API restarts in a row; like the engine's they are forgotten after a stable period, so that a service that - // runs for weeks is not ended by the sixth API crash of the month. - let (mut gateway_restarts, mut api_restarts) = (0u32, 0u32); - let (mut gateway_since, mut api_since) = (Instant::now(), Instant::now()); - let stable = Duration::from_secs(self.config.restart.stable_after_s); - // `leleka reconfigure` leaves a request file; look for it once a second. - let mut requests = tokio::time::interval(Duration::from_secs(1)); - requests.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); - let mut logs_tick = tokio::time::interval(Duration::from_secs(10)); - logs_tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); - let health = self.config.health.clone(); - let mut health_tick = tokio::time::interval(Duration::from_secs(health.interval_s.max(1))); - health_tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); - let mut watchdog = watchdog::Watchdog::new(watchdog::Limits { - fail: Duration::from_secs(health.fail_s), - max_request: Duration::from_secs(health.max_request_s), - }); + Ok(Running::new(&self.config, engine, gateway, api)) + } - // 4. supervise - let result: Result<(), Flow> = loop { - tokio::select! { - _ = self.shutdown.changed() => break Ok(()), - _ = requests.tick() => { - let Some(taken) = reconfigure::take_request(&self.paths) else { continue }; - match taken { - Err(message) => { - self.log.line(&format!("reconfigure: {message}")); - self.answer("", reconfigure::State::Refused, message, false); - } - Ok(request) => match self.reconfigure(request, &mut engine, &mut gateway, &mut api).await { - Ok(()) => { - ready_since = Instant::now(); - watchdog.reset(); - } - Err(Flow::Stopped) => break Ok(()), - Err(flow) => break Err(flow), - }, - } - } - status = engine.wait() => { - let text = status.map_or_else(|e| e.to_string(), |s| s.to_string()); - self.log.event( - leleka_obs::Level::Warn, - "engine_exit", - &[("status", text.as_str().into()), ("restarts_total", self.restarts_total.into()), ("msg", "the API reports not-ready until the engine is back".into())], - ); - match self.recover_engine(&mut engine, &mut gateway, &mut ready_since, format!("the engine process exited ({text})")).await { - Ok(()) => watchdog.reset(), - Err(Flow::Stopped) => break Ok(()), - Err(flow) => break Err(flow), - } - } - _ = logs_tick.tick() => { - self.enforce_logs(); - self.beats += 1; - if self.beats.is_multiple_of(3) { - self.heartbeat(); - } - } - _ = health_tick.tick(), if self.config.health.enabled => { - let sample = self.sample_health().await; - match watchdog.observe(Instant::now(), &sample) { - watchdog::Verdict::Healthy => self.note_health("healthy"), - watchdog::Verdict::Suspect(why) => { - if self.health_note != why { - self.log.event(leleka_obs::Level::Warn, "health", &[("finding", why.as_str().into())]); - } - self.note_health(&why); - } - watchdog::Verdict::RestartApi(why) => { - self.log.event(leleka_obs::Level::Warn, "restart", &[("target", "api".into()), ("reason", why.as_str().into())]); - self.restarts_total += 1; - self.last_restart = Some((unix_now(), why)); - api_since = Instant::now(); - match self.restart_api(&mut api).await { - Ok(()) => watchdog.reset(), - Err(Flow::Stopped) => break Ok(()), - Err(flow) => break Err(flow), - } - } - watchdog::Verdict::RestartEngine(why) => { - self.log.event(leleka_obs::Level::Warn, "restart", &[("target", "engine".into()), ("reason", why.as_str().into())]); - if let Err(flow) = self.hard_kill(&mut engine).await { - break Err(flow); - } - match self.recover_engine(&mut engine, &mut gateway, &mut ready_since, why).await { - Ok(()) => watchdog.reset(), - Err(Flow::Stopped) => break Ok(()), - Err(flow) => break Err(flow), - } - } - } - } - status = gateway.wait() => { - let text = status.map_or_else(|e| e.to_string(), |s| s.to_string()); - if gateway_since.elapsed() >= stable { - gateway_restarts = 0; - } - gateway_restarts += 1; - self.log.event( - leleka_obs::Level::Warn, - "gateway_exit", - &[("status", text.as_str().into()), ("restart", gateway_restarts.into()), ("of", 3u32.into())], - ); - if gateway_restarts > 3 { - break fail(1, "the gateway keeps dying"); - } - if !self.pause(Duration::from_secs(2)).await { - break Ok(()); - } - gateway = self.spawn("gateway", &self.paths.bin("leleka-daemon"), &daemon_args, &BTreeMap::new(), None)?; - self.pids[1] = gateway.id(); - gateway_since = Instant::now(); - } - status = api.wait() => { - let text = status.map_or_else(|e| e.to_string(), |s| s.to_string()); - if api_since.elapsed() >= stable { - api_restarts = 0; - } - api_restarts += 1; - self.log.event( - leleka_obs::Level::Warn, - "api_exit", - &[("status", text.as_str().into()), ("restart", api_restarts.into()), ("of", 5u32.into())], - ); - if api_restarts > 5 { - break fail(1, "the API keeps dying"); - } - if !self.pause(Duration::from_secs(2)).await { - break Ok(()); - } - api = self.spawn("api", &self.paths.bin("strata-next"), &api_args, &BTreeMap::new(), None)?; - self.pids[2] = api.id(); - api_since = Instant::now(); - } + /// The public API; the engine and the gateway are stopped when it does not come up. + async fn start_api(&mut self, engine: &mut Child, gateway: &mut Child) -> Result { + self.set_phase(Phase::StartingApi, "starting the API"); + let mut api = match self.spawn_api() { + Ok(child) => child, + Err(flow) => { + self.kill_children(&mut [Some(engine), Some(gateway)]).await; + return Err(flow); } }; + self.pids[2] = api.id(); + if let Err(flow) = self.wait_api_ready(&mut api).await { + self.kill_children(&mut [Some(&mut api), Some(engine), Some(gateway)]) + .await; + return Err(flow); + } + Ok(api) + } - // 5. drain: API first so streams end with a terminal event, then the gateway and the engine. - self.set_phase(Phase::Draining, "draining"); - self.log.line("stopping: API, gateway, engine"); - self.kill_children(&mut [Some(&mut api), Some(&mut gateway), Some(&mut engine)]) + /// The loop proper. `Err` leaves without the drain (a child that cannot be respawned); `Ok(result)` is drained + /// first. + async fn supervise(&mut self, r: &mut Running) -> Result, Flow> { + loop { + if let Step::End(result) = self.next_step(r).await? { + return Ok(result); + } + } + } + + /// Wait for the next thing that happens to the service and deal with it. + async fn next_step(&mut self, r: &mut Running) -> Result { + tokio::select! { + _ = self.shutdown.changed() => Ok(Step::End(Ok(()))), + _ = r.requests.tick() => Ok(self.on_request(r).await), + status = r.engine.wait() => Ok(self.on_engine_exit(r, describe_exit(status)).await), + _ = r.logs_tick.tick() => Ok(self.on_logs_tick()), + _ = r.health_tick.tick(), if self.config.health.enabled => Ok(self.on_health_tick(r).await), + status = r.gateway.wait() => self.on_gateway_exit(r, describe_exit(status)).await, + status = r.api.wait() => self.on_api_exit(r, describe_exit(status)).await, + } + } + + async fn on_request(&mut self, r: &mut Running) -> Step { + let request = match reconfigure::take_request(&self.paths) { + None => return Step::Go, + Some(Ok(request)) => request, + Some(Err(message)) => { + self.log.line(&format!("reconfigure: {message}")); + self.answer("", reconfigure::State::Refused, message, false); + return Step::Go; + } + }; + match self + .reconfigure(request, &mut r.engine, &mut r.gateway, &mut r.api) + .await + { + Ok(()) => { + r.ready_since = Instant::now(); + r.watchdog.reset(); + Step::Go + } + Err(flow) => end_of(flow), + } + } + + async fn on_engine_exit(&mut self, r: &mut Running, text: String) -> Step { + self.log.event( + leleka_obs::Level::Warn, + "engine_exit", + &[ + ("status", text.as_str().into()), + ("restarts_total", self.restarts_total.into()), + ( + "msg", + "the API reports not-ready until the engine is back".into(), + ), + ], + ); + let why = format!("the engine process exited ({text})"); + let result = self + .recover_engine(&mut r.engine, &mut r.gateway, &mut r.ready_since, why) .await; - self.pids = [None; 3]; - result + r.recovered(result) + } + + fn on_logs_tick(&mut self) -> Step { + self.enforce_logs(); + self.beats += 1; + if self.beats.is_multiple_of(3) { + self.heartbeat(); + } + Step::Go + } + + async fn on_health_tick(&mut self, r: &mut Running) -> Step { + let sample = self.sample_health().await; + match r.watchdog.observe(Instant::now(), &sample) { + watchdog::Verdict::Healthy => { + self.note_health("healthy"); + Step::Go + } + watchdog::Verdict::Suspect(why) => { + if self.health_note != why { + self.log.event( + leleka_obs::Level::Warn, + "health", + &[("finding", why.as_str().into())], + ); + } + self.note_health(&why); + Step::Go + } + watchdog::Verdict::RestartApi(why) => self.restart_api_for(r, why).await, + watchdog::Verdict::RestartEngine(why) => self.restart_engine_for(r, why).await, + } + } + + async fn restart_api_for(&mut self, r: &mut Running, why: String) -> Step { + let fields = [("target", "api".into()), ("reason", why.as_str().into())]; + self.log.event(leleka_obs::Level::Warn, "restart", &fields); + self.restarts_total += 1; + self.last_restart = Some((unix_now(), why)); + r.api_since = Instant::now(); + let result = self.restart_api(&mut r.api).await; + r.recovered(result) + } + + async fn restart_engine_for(&mut self, r: &mut Running, why: String) -> Step { + let fields = [("target", "engine".into()), ("reason", why.as_str().into())]; + self.log.event(leleka_obs::Level::Warn, "restart", &fields); + if let Err(flow) = self.hard_kill(&mut r.engine).await { + return Step::End(Err(flow)); + } + let result = self + .recover_engine(&mut r.engine, &mut r.gateway, &mut r.ready_since, why) + .await; + r.recovered(result) + } + + async fn on_gateway_exit(&mut self, r: &mut Running, text: String) -> Result { + if r.gateway_since.elapsed() >= r.stable { + r.gateway_restarts = 0; + } + r.gateway_restarts += 1; + let fields = [ + ("status", text.as_str().into()), + ("restart", r.gateway_restarts.into()), + ("of", 3u32.into()), + ]; + self.log + .event(leleka_obs::Level::Warn, "gateway_exit", &fields); + if r.gateway_restarts > 3 { + return Ok(Step::End(fail(1, "the gateway keeps dying"))); + } + if !self.pause(Duration::from_secs(2)).await { + return Ok(Step::End(Ok(()))); + } + r.gateway = self.spawn_gateway()?; + self.pids[1] = r.gateway.id(); + r.gateway_since = Instant::now(); + Ok(Step::Go) + } + + async fn on_api_exit(&mut self, r: &mut Running, text: String) -> Result { + if r.api_since.elapsed() >= r.stable { + r.api_restarts = 0; + } + r.api_restarts += 1; + let fields = [ + ("status", text.as_str().into()), + ("restart", r.api_restarts.into()), + ("of", 5u32.into()), + ]; + self.log.event(leleka_obs::Level::Warn, "api_exit", &fields); + if r.api_restarts > 5 { + return Ok(Step::End(fail(1, "the API keeps dying"))); + } + if !self.pause(Duration::from_secs(2)).await { + return Ok(Step::End(Ok(()))); + } + r.api = self.spawn_api()?; + self.pids[2] = r.api.id(); + r.api_since = Instant::now(); + Ok(Step::Go) } /// One look at `GET /metrics` (the control plane's own view of the worker and the active request) for the hang detector. diff --git a/crates/deploy/src/units.rs b/crates/deploy/src/units.rs index a801e022..a1d3b68d 100644 --- a/crates/deploy/src/units.rs +++ b/crates/deploy/src/units.rs @@ -42,6 +42,18 @@ pub fn render( let state_q = quote(state)?; let prefix_q = quote(prefix)?; let lab_q = quote(&state.join("lab-mode"))?; + let mut unit = unit_section(&state_q, &prefix_q, &lab_q); + unit.push_str(&service_section(scope, user, &env_file, &bin, &config)?); + unit.push_str("[Install]\n"); + unit.push_str(match scope { + UnitScope::System => "WantedBy=multi-user.target\n", + UnitScope::User => "WantedBy=default.target\n", + }); + Ok(unit) +} + +/// The header and the `[Unit]` section. +fn unit_section(state_q: &str, prefix_q: &str, lab_q: &str) -> String { let mut unit = String::new(); unit.push_str("# Generated by `leleka up`; edit the run configuration, not this file.\n"); unit.push_str("[Unit]\n"); @@ -55,21 +67,53 @@ pub fn render( // Never give up for good: an unattended host must come back by itself. The delay between starts grows (30 s up to 10 min) so // that a persistent failure does not re-read 55 GB in a tight loop. unit.push_str("StartLimitIntervalSec=0\n\n"); + unit +} + +/// The `[Service]` section. +fn service_section( + scope: UnitScope, + user: Option<&str>, + env_file: &str, + bin: &str, + config: &str, +) -> Result { + let mut unit = String::new(); unit.push_str("[Service]\n"); unit.push_str("Type=exec\n"); - if scope == UnitScope::System { - let user = user.ok_or("a system unit needs a service user")?; - if user.is_empty() - || !user - .bytes() - .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-' | b'.')) - { - return Err("service user must be [A-Za-z0-9_.-]+".into()); - } - unit.push_str(&format!("User={user}\n")); - } + unit.push_str(&service_user_line(scope, user)?); unit.push_str(&format!("EnvironmentFile={env_file}\n")); unit.push_str("UMask=0077\nNoNewPrivileges=yes\n"); + unit.push_str(&limits_and_logging(scope)); + unit.push_str(&format!("ExecStart={bin} run --config {config}\n")); + // A failed start must be looked at: the first start copies 55 GB. Exit 2 is a configuration error. + unit.push_str(concat!( + "Restart=on-failure\nRestartSec=30\nRestartSteps=6\n", + "RestartMaxDelaySec=600\nRestartPreventExitStatus=2\n" + )); + // The supervisor turns SIGTERM into a graceful stop of the API (drain), the gateway and the engine. + unit.push_str("KillSignal=SIGTERM\nTimeoutStopSec=180\nKillMode=mixed\n\n"); + Ok(unit) +} + +/// `User=` for a system unit (the name is checked); nothing for a user unit. +fn service_user_line(scope: UnitScope, user: Option<&str>) -> Result { + if scope != UnitScope::System { + return Ok(String::new()); + } + let user = user.ok_or("a system unit needs a service user")?; + if user.is_empty() + || !user + .bytes() + .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-' | b'.')) + { + return Err("service user must be [A-Za-z0-9_.-]+".into()); + } + Ok(format!("User={user}\n")) +} + +fn limits_and_logging(scope: UnitScope) -> String { + let mut unit = String::new(); // Pinned host memory (cudaHostAlloc/Register) is counted against RLIMIT_MEMLOCK on some drivers. unit.push_str("LimitMEMLOCK=infinity\n"); // No core dump: the engine holds 100+ GB of RAM, and writing that to the root disk after a crash would stall the host. @@ -80,17 +124,7 @@ pub fn render( } // Bounded journal traffic; the service keeps its own rotated logs in the state directory. unit.push_str("LogRateLimitIntervalSec=30s\nLogRateLimitBurst=1000\n"); - unit.push_str(&format!("ExecStart={bin} run --config {config}\n")); - // A failed start must be looked at: the first start copies 55 GB. Exit 2 is a configuration error. - unit.push_str("Restart=on-failure\nRestartSec=30\nRestartSteps=6\nRestartMaxDelaySec=600\nRestartPreventExitStatus=2\n"); - // The supervisor turns SIGTERM into a graceful stop of the API (drain), the gateway and the engine. - unit.push_str("KillSignal=SIGTERM\nTimeoutStopSec=180\nKillMode=mixed\n\n"); - unit.push_str("[Install]\n"); - unit.push_str(match scope { - UnitScope::System => "WantedBy=multi-user.target\n", - UnitScope::User => "WantedBy=default.target\n", - }); - Ok(unit) + unit } pub fn unit_path( @@ -163,42 +197,13 @@ mod tests { #[cfg(unix)] #[test] fn dangerous_paths_and_users_are_refused() { - assert!( - render( - UnitScope::System, - Path::new("/opt/le%leka"), - Path::new("/s"), - Some("u") - ) - .is_err() - ); - assert!( - render( - UnitScope::System, - Path::new("/opt/leleka"), - Path::new("relative"), - Some("u") - ) - .is_err() - ); - assert!( - render( - UnitScope::System, - Path::new("/opt/leleka"), - Path::new("/s"), - Some("a b") - ) - .is_err() - ); - assert!( - render( - UnitScope::System, - Path::new("/opt/leleka"), - Path::new("/s"), - None - ) - .is_err() - ); + let refused = |prefix: &str, state: &str, user: Option<&str>| { + render(UnitScope::System, Path::new(prefix), Path::new(state), user).is_err() + }; + assert!(refused("/opt/le%leka", "/s", Some("u"))); + assert!(refused("/opt/leleka", "relative", Some("u"))); + assert!(refused("/opt/leleka", "/s", Some("a b"))); + assert!(refused("/opt/leleka", "/s", None)); let spaced = render( UnitScope::User, Path::new("/opt/my leleka"), diff --git a/crates/deploy/src/watchdog.rs b/crates/deploy/src/watchdog.rs index aa089dbe..620337f4 100644 --- a/crates/deploy/src/watchdog.rs +++ b/crates/deploy/src/watchdog.rs @@ -103,45 +103,62 @@ impl Watchdog { pub fn observe(&mut self, now: Instant, sample: &Sample) -> Verdict { match sample { - Sample::Unreachable(why) => { - self.not_ready_since = None; - let since = *self.unreachable_since.get_or_insert(now); - let down = now.saturating_duration_since(since); - let why = format!("the API does not answer: {why}"); - if down >= self.limits.fail { - Verdict::RestartApi(format!("{why} (for {} s)", down.as_secs())) - } else { - Verdict::Suspect(why) - } - } + Sample::Unreachable(why) => self.observe_unreachable(now, why), Sample::Metrics { worker_ready, active_s, - } => { - self.unreachable_since = None; - if !worker_ready { - let since = *self.not_ready_since.get_or_insert(now); - let down = now.saturating_duration_since(since); - let why = "the API has lost the engine (worker not ready)".to_owned(); - return if down >= self.limits.fail { - Verdict::RestartEngine(format!("{why} for {} s", down.as_secs())) - } else { - Verdict::Suspect(why) - }; - } - self.not_ready_since = None; - match active_s { - Some(seconds) if *seconds >= self.limits.max_request.as_secs_f64() => { - Verdict::RestartEngine(format!( - "a request has been active for {seconds:.0} s, beyond the longest allowed ({} s): the engine makes no progress", - self.limits.max_request.as_secs() - )) - } - _ => Verdict::Healthy, - } - } + } => self.observe_metrics(now, *worker_ready, *active_s), } } + + fn observe_unreachable(&mut self, now: Instant, why: &str) -> Verdict { + self.not_ready_since = None; + let since = *self.unreachable_since.get_or_insert(now); + let down = now.saturating_duration_since(since); + let why = format!("the API does not answer: {why}"); + if down >= self.limits.fail { + Verdict::RestartApi(format!("{why} (for {} s)", down.as_secs())) + } else { + Verdict::Suspect(why) + } + } + + fn observe_metrics( + &mut self, + now: Instant, + worker_ready: bool, + active_s: Option, + ) -> Verdict { + self.unreachable_since = None; + if !worker_ready { + let since = *self.not_ready_since.get_or_insert(now); + let down = now.saturating_duration_since(since); + let why = "the API has lost the engine (worker not ready)".to_owned(); + return if down >= self.limits.fail { + Verdict::RestartEngine(format!("{why} for {} s", down.as_secs())) + } else { + Verdict::Suspect(why) + }; + } + self.not_ready_since = None; + match active_s { + Some(seconds) if seconds >= self.limits.max_request.as_secs_f64() => { + Verdict::RestartEngine(self.stall_reason(seconds)) + } + _ => Verdict::Healthy, + } + } + + fn stall_reason(&self, seconds: f64) -> String { + format!( + concat!( + "a request has been active for {seconds:.0} s, beyond the longest allowed ({} s): ", + "the engine makes no progress" + ), + self.limits.max_request.as_secs(), + seconds = seconds + ) + } } #[cfg(test)] diff --git a/crates/deploy/src/winfront/commands.rs b/crates/deploy/src/winfront/commands.rs index 981e3014..46324d28 100644 --- a/crates/deploy/src/winfront/commands.rs +++ b/crates/deploy/src/winfront/commands.rs @@ -5,44 +5,71 @@ use super::*; pub(super) async fn status(args: &[String]) -> i32 { let session = match open_session(args, false) { Ok(session) => session, - Err(message) => { - // Not an error of the tool: nothing is running. Same shape as a native "not ready". - let json = args.iter().any(|a| a == "--json"); - if json { - println!( - "{{\"ready\": false, \"reason\": {}}}", - Value::String(message) - ); - } else { - println!("ready: false\n{message}"); - } - return 1; - } + Err(message) => return print_not_running(args, message), }; let json = session.forwarded.args.iter().any(|a| a == "--json"); let state_dir = session.state_dir(); let api = session.api(&state_dir); - let supervisor: Option = session - .bridge - .read_file(&format!("{state_dir}/run/status.json")) - .and_then(|text| serde_json::from_str(&text).ok()); + let supervisor = supervisor_status(&session.bridge, &state_dir); let key = session.bridge.read_file(&format!("{state_dir}/api-key")); - let ready = match &key { - Some(key) => probe_ready_with_key(key, &api).await, - None => false, - }; - let gateway = match (&key, ready) { - (Some(key), true) => fetch_status_with_key(key, &api).await, - _ => None, - }; + let (ready, gateway) = probe_gateway(key.as_deref(), &api).await; if !json && key.is_none() { note(&format!( "no API key in {state_dir}/api-key of {} (has `leleka up` run? other state? pass --state-dir)", session.bridge.distro )); } - // The table lives in the distribution: the digest is taken there (`sha256sum`), the report is the same as on a Linux host. - let expert_tier = session + let expert_tier = expert_tier_of(&session, &state_dir); + print_status( + json, + ready, + None, + supervisor, + gateway.as_ref(), + expert_tier.as_ref(), + &linux_to_unc(&session.bridge.distro, &format!("{state_dir}/run")), + None, + ) +} + +/// Is the API ready, and what does the gateway say (only asked when it is)? +async fn probe_gateway(key: Option<&str>, api: &str) -> (bool, Option) { + let ready = match key { + Some(key) => probe_ready_with_key(key, api).await, + None => false, + }; + let gateway = match (key, ready) { + (Some(key), true) => fetch_status_with_key(key, api).await, + _ => None, + }; + (ready, gateway) +} + +/// Not an error of the tool: nothing is running. Same shape as a native "not ready". +fn print_not_running(args: &[String], message: String) -> i32 { + let json = args.iter().any(|a| a == "--json"); + if json { + println!( + "{{\"ready\": false, \"reason\": {}}}", + Value::String(message) + ); + } else { + println!("ready: false\n{message}"); + } + 1 +} + +/// `run/status.json` of the supervisor inside the distribution. +fn supervisor_status(bridge: &Bridge, state_dir: &str) -> Option { + bridge + .read_file(&format!("{state_dir}/run/status.json")) + .and_then(|text| serde_json::from_str(&text).ok()) +} + +/// The table lives in the distribution: the digest is taken there (`sha256sum`), the report is the same as on a Linux +/// host. +fn expert_tier_of(session: &Session, state_dir: &str) -> Option { + session .bridge .read_file(&format!("{state_dir}/leleka.json")) .and_then(|text| serde_json::from_str::(&text).ok()) @@ -62,17 +89,7 @@ pub(super) async fn status(args: &[String]) -> i32 { .and_then(|out| out.split_whitespace().next().map(str::to_owned)); crate::expert_profile::FileState::from_digest(observed.as_deref(), &expected) }) - }); - print_status( - json, - ready, - None, - supervisor, - gateway.as_ref(), - expert_tier.as_ref(), - &linux_to_unc(&session.bridge.distro, &format!("{state_dir}/run")), - None, - ) + }) } pub(super) async fn reconfigure(args: &[String]) -> i32 { @@ -95,6 +112,16 @@ pub(super) async fn reconfigure(args: &[String]) -> i32 { return 1; } }; + let (key, address) = match reachable_api(&session) { + Ok(found) => found, + Err(code) => return code, + }; + let json = session.forwarded.args.iter().any(|a| a == "--json"); + send_reconfigure(address, key.trim_end(), &document, json, None).await +} + +/// The API key of the service in the distribution and the loopback address of its API. +fn reachable_api(session: &Session) -> Result<(String, std::net::SocketAddr), i32> { let state_dir = session.state_dir(); let api = session.api(&state_dir); let Some(key) = session.bridge.read_file(&format!("{state_dir}/api-key")) else { @@ -102,14 +129,13 @@ pub(super) async fn reconfigure(args: &[String]) -> i32 { "no API key in {state_dir}/api-key of {} (is the service prepared?)", session.bridge.distro )); - return 1; + return Err(1); }; let Some(address) = crate::config::probe_address(&api) else { note(&format!("cannot reach the API address {api}")); - return 1; + return Err(1); }; - let json = session.forwarded.args.iter().any(|a| a == "--json"); - send_reconfigure(address, key.trim_end(), &document, json, None).await + Ok((key, address)) } pub(super) async fn down(args: &[String]) -> i32 { @@ -122,34 +148,10 @@ pub(super) async fn down(args: &[String]) -> i32 { }; let state_dir = session.state_dir(); let bridge = &session.bridge; - // A systemd user unit inside the distribution? - let unit = bridge - .capture("systemctl", &["--user", "is-active", "leleka.service"]) - .unwrap_or_default(); - if unit.trim() == "active" || unit.trim() == "activating" { - return match bridge.capture("systemctl", &["--user", "stop", "leleka.service"]) { - Ok(_) => { - note("stopped leleka.service (user unit in WSL)"); - 0 - } - Err(message) => { - note(&message); - 1 - } - }; + if let Some(code) = stop_user_unit(bridge) { + return code; } - let supervisor: Option = bridge - .read_file(&format!("{state_dir}/run/status.json")) - .and_then(|text| serde_json::from_str(&text).ok()); - let pid = supervisor - .as_ref() - .and_then(|s| s["supervisor_pid"].as_u64()); - let phase = supervisor - .as_ref() - .and_then(|s| s["phase"].as_str()) - .unwrap_or("") - .to_owned(); - let Some(pid) = pid.filter(|_| !matches!(phase.as_str(), "stopped" | "failed")) else { + let Some(pid) = running_supervisor(bridge, &state_dir) else { note("no running supervisor was found in this state directory"); return 0; }; @@ -160,17 +162,64 @@ pub(super) async fn down(args: &[String]) -> i32 { )); return 0; } + interrupt_and_wait(bridge, pid, &pid_text).await +} + +/// SIGINT to the supervisor, then wait for it to drain. +async fn interrupt_and_wait(bridge: &Bridge, pid: u64, pid_text: &str) -> i32 { note(&format!( "stopping the supervisor (pid {pid}) with SIGINT: the API drains first, then the gateway and the engine" )); - if let Err(message) = bridge.capture("kill", &["-INT", &pid_text]) { + if let Err(message) = bridge.capture("kill", &["-INT", pid_text]) { note(&message); return 1; } + wait_until_gone(bridge, pid_text).await +} + +/// A systemd user unit inside the distribution? Stop it: the exit code of `down`, or `None` when there is no active +/// unit. +fn stop_user_unit(bridge: &Bridge) -> Option { + let unit = bridge + .capture("systemctl", &["--user", "is-active", "leleka.service"]) + .unwrap_or_default(); + if unit.trim() != "active" && unit.trim() != "activating" { + return None; + } + Some( + match bridge.capture("systemctl", &["--user", "stop", "leleka.service"]) { + Ok(_) => { + note("stopped leleka.service (user unit in WSL)"); + 0 + } + Err(message) => { + note(&message); + 1 + } + }, + ) +} + +/// The pid of the supervisor that is neither stopped nor failed, from its status file. +fn running_supervisor(bridge: &Bridge, state_dir: &str) -> Option { + let supervisor = supervisor_status(bridge, state_dir); + let pid = supervisor + .as_ref() + .and_then(|s| s["supervisor_pid"].as_u64()); + let phase = supervisor + .as_ref() + .and_then(|s| s["phase"].as_str()) + .unwrap_or("") + .to_owned(); + pid.filter(|_| !matches!(phase.as_str(), "stopped" | "failed")) +} + +/// Wait up to two minutes for the supervisor to exit after the SIGINT. +async fn wait_until_gone(bridge: &Bridge, pid_text: &str) -> i32 { let started = std::time::Instant::now(); while started.elapsed() < Duration::from_secs(120) { tokio::time::sleep(Duration::from_secs(2)).await; - if bridge.capture("kill", &["-0", &pid_text]).is_err() { + if bridge.capture("kill", &["-0", pid_text]).is_err() { note("stopped"); return 0; } diff --git a/crates/deploy/src/winfront/doctor_command.rs b/crates/deploy/src/winfront/doctor_command.rs index faf66d9b..f71b959b 100644 --- a/crates/deploy/src/winfront/doctor_command.rs +++ b/crates/deploy/src/winfront/doctor_command.rs @@ -1,13 +1,54 @@ //! `leleka doctor` on Windows. use super::*; +use crate::{facts::Facts, layout::Paths, wsl::Distro}; +use std::path::Path; + +fn gib(bytes: u64) -> String { + format!("{:.1} GiB", bytes as f64 / (1u64 << 30) as f64) +} /// `leleka doctor [--assets DIR]`: everything this machine tells about the two routes, then what is missing and the one command /// that fixes the first missing thing. pub(super) async fn doctor(args: &[String]) -> i32 { - let var = |name: &str| std::env::var(name).ok().filter(|v| !v.is_empty()); let home = std::env::var_os("USERPROFILE").map(PathBuf::from); - let mut dirs = crate::layout::Dirs::defaults(false, home.as_deref(), &var); + let paths = doctor_dirs(home.as_deref(), args).paths(); + let exe_dir = std::env::current_exe() + .ok() + .and_then(|exe| exe.parent().map(PathBuf::from)); + let facts = probe(&ProbeRequest { + binary_dir: exe_dir.clone(), + ..ProbeRequest::default() + }); + print_windows_facts(&facts); + let (wsl_found, linux_leleka_found) = print_wsl_route(home.as_deref(), &facts); + println!("native route:"); + let native_missing = print_native_programs(exe_dir.as_deref()); + let cublas_missing = print_libraries(&facts); + let volume_missing = print_volume(&paths); + let inputs = crate::doctor::Inputs { + repo: find_repo(), + gpu_found: !facts.gpus.is_empty(), + native_binaries_missing: native_missing, + cublas_missing, + volume_missing, + assets: paths.dirs.assets.clone(), + wsl_found, + linux_leleka_found, + }; + print_verdict(&inputs); + print_next_command(&inputs, &paths) +} + +/// The default directories with the `--assets` of the command line. +fn doctor_dirs(home: Option<&Path>, args: &[String]) -> crate::layout::Dirs { + let var = |name: &str| std::env::var(name).ok().filter(|v| !v.is_empty()); + let mut dirs = crate::layout::Dirs::defaults(false, home, &var); + apply_assets_flag(&mut dirs, args); + dirs +} + +fn apply_assets_flag(dirs: &mut crate::layout::Dirs, args: &[String]) { let mut iter = args.iter(); while let Some(arg) = iter.next() { if let Some(value) = arg.strip_prefix("--assets=") { @@ -18,15 +59,9 @@ pub(super) async fn doctor(args: &[String]) -> i32 { dirs.assets = PathBuf::from(value); } } - let paths = dirs.paths(); - let exe_dir = std::env::current_exe() - .ok() - .and_then(|exe| exe.parent().map(PathBuf::from)); - let facts = probe(&ProbeRequest { - binary_dir: exe_dir.clone(), - ..ProbeRequest::default() - }); - let gib = |bytes: u64| format!("{:.1} GiB", bytes as f64 / (1u64 << 30) as f64); +} + +fn print_windows_facts(facts: &Facts) { println!("windows facts:"); println!(" os/arch {}/{}", facts.os, facts.arch); println!(" cpu {} logical cores", facts.cpu_cores); @@ -55,11 +90,39 @@ pub(super) async fn doctor(args: &[String]) -> i32 { gpu.driver ); } - let wslconfig = home.as_ref().map(|home| home.join(".wslconfig")); +} + +/// The WSL2 route: `.wslconfig`, the distributions and the Linux `leleka`. Returns whether `wsl.exe` was found and +/// what the +/// look for the Linux binary found (`None` when it was not looked for). +fn print_wsl_route(home: Option<&Path>, facts: &Facts) -> (bool, Option) { + println!("wsl2 (route A):"); + print_wslconfig(home, facts); + let mut linux_leleka_found = None; + let wsl = wsl_exe(); + match &wsl { + None => println!( + " wsl.exe not found (WSL is not installed: use --native, or `wsl --install -d Ubuntu`)" + ), + Some(wsl) => { + println!(" wsl.exe {}", wsl.display()); + linux_leleka_found = print_distros(wsl); + } + } + if let Some(saved) = BridgeState::read(&local_app_data()) { + println!( + " last up distro {} state {} api {}", + saved.distro, saved.state_dir, saved.api + ); + } + (wsl.is_some(), linux_leleka_found) +} + +fn print_wslconfig(home: Option<&Path>, facts: &Facts) { + let wslconfig = home.map(|home| home.join(".wslconfig")); let text = wslconfig .as_ref() .and_then(|path| std::fs::read_to_string(path).ok()); - println!("wsl2 (route A):"); match &text { Some(text) => { let config = parse_wslconfig(text); @@ -81,67 +144,69 @@ pub(super) async fn doctor(args: &[String]) -> i32 { Some(advice) => println!(" advice {advice}"), None => println!(" advice none: memory and swap are enough for the laptop profile"), } - let mut linux_leleka_found = None; - let wsl = wsl_exe(); - match &wsl { - None => println!( - " wsl.exe not found (WSL is not installed: use --native, or `wsl --install -d Ubuntu`)" - ), - Some(wsl) => { - println!(" wsl.exe {}", wsl.display()); - match list_distros(wsl) { - Err(message) => println!(" distros {message}"), - Ok(list) => { - for d in &list { - println!( - " distro {}{} {} (WSL{})", - if d.default { "* " } else { "" }, - d.name, - d.state, - d.version - ); - } - match pick_distro(&list, std::env::var("LELEKA_WSL_DISTRO").ok().as_deref()) { - Err(message) => println!(" chosen {message}"), - Ok(distro) => { - println!(" chosen {distro}"); - let bridge = Bridge { - wsl: wsl.clone(), - distro, - }; - if list.iter().any(|d| { - d.name == bridge.distro && d.state.eq_ignore_ascii_case("running") - }) { - match bridge.find_leleka(None) { - Ok(path) => { - println!(" linux leleka {path}"); - linux_leleka_found = Some(true); - } - Err(message) => { - println!(" linux leleka {message}"); - linux_leleka_found = Some(false); - } - } - } else { - println!( - " linux leleka (the distribution is stopped; not started just to look)" - ); - } - } - } - } - } +} + +/// The distributions and the one chosen; whether the Linux `leleka` was found in it when it is running. +fn print_distros(wsl: &Path) -> Option { + let list = match list_distros(wsl) { + Err(message) => { + println!(" distros {message}"); + return None; + } + Ok(list) => list, + }; + print_distro_list(&list); + match pick_distro(&list, std::env::var("LELEKA_WSL_DISTRO").ok().as_deref()) { + Err(message) => { + println!(" chosen {message}"); + None + } + Ok(distro) => { + println!(" chosen {distro}"); + let bridge = Bridge { + wsl: wsl.to_path_buf(), + distro, + }; + find_linux_leleka(&bridge, &list) } } - if let Some(saved) = BridgeState::read(&local_app_data()) { +} + +fn print_distro_list(list: &[Distro]) { + for d in list { println!( - " last up distro {} state {} api {}", - saved.distro, saved.state_dir, saved.api + " distro {}{} {} (WSL{})", + if d.default { "* " } else { "" }, + d.name, + d.state, + d.version ); } - println!("native route:"); +} + +fn find_linux_leleka(bridge: &Bridge, list: &[Distro]) -> Option { + if !list + .iter() + .any(|d| d.name == bridge.distro && d.state.eq_ignore_ascii_case("running")) + { + println!(" linux leleka (the distribution is stopped; not started just to look)"); + return None; + } + match bridge.find_leleka(None) { + Ok(path) => { + println!(" linux leleka {path}"); + Some(true) + } + Err(message) => { + println!(" linux leleka {message}"); + Some(false) + } + } +} + +/// The programs next to `leleka.exe`; the missing ones. +fn print_native_programs(exe_dir: Option<&Path>) -> Vec { let native_missing: Vec = exe_dir - .as_ref() .map(|dir| { crate::layout::BINARIES .iter() @@ -163,6 +228,11 @@ pub(super) async fn doctor(args: &[String]) -> i32 { format!("missing next to leleka.exe: {}", native_missing.join(", ")) } ); + native_missing +} + +/// The CUDA libraries the engine loads; the cuBLAS DLLs that were not found. +fn print_libraries(facts: &Facts) -> Vec<&'static str> { let mut cublas_missing = Vec::new(); for (soname, dll) in crate::facts::WINDOWS_LIBRARIES { let found = facts.lib(soname); @@ -174,7 +244,12 @@ pub(super) async fn doctor(args: &[String]) -> i32 { cublas_missing.push(dll); } } - let volume_missing = crate::doctor::volume_missing(&paths); + cublas_missing +} + +/// The asset volume; what is missing in it. +fn print_volume(paths: &Paths) -> Vec { + let volume_missing = crate::doctor::volume_missing(paths); println!(" volume {}", paths.dirs.assets.display()); for line in &volume_missing { println!(" {line}"); @@ -182,25 +257,19 @@ pub(super) async fn doctor(args: &[String]) -> i32 { if volume_missing.is_empty() { println!( " complete{}", - if crate::doctor::expert_profile_present(&paths) { + if crate::doctor::expert_profile_present(paths) { "" } else { " (data\\expert-profile.bin is absent or not the pinned table: `leleka up` installs it, or pass --expert-profile-file; without it the VRAM expert tier is OFF)" } ); } - let inputs = crate::doctor::Inputs { - repo: find_repo(), - gpu_found: !facts.gpus.is_empty(), - native_binaries_missing: native_missing, - cublas_missing, - volume_missing, - assets: paths.dirs.assets.clone(), - wsl_found: wsl.is_some(), - linux_leleka_found, - }; + volume_missing +} + +fn print_verdict(inputs: &crate::doctor::Inputs) { println!("verdict:"); - for finding in &crate::doctor::advise(&inputs) { + for finding in &crate::doctor::advise(inputs) { if finding.ok() { println!(" ok {}", finding.what); } else { @@ -210,7 +279,11 @@ pub(super) async fn doctor(args: &[String]) -> i32 { } } } - match crate::doctor::next_command(&inputs) { +} + +/// The exit code: 1 when something is missing, with the command that fixes the first missing thing. +fn print_next_command(inputs: &crate::doctor::Inputs, paths: &Paths) -> i32 { + match crate::doctor::next_command(inputs) { Some(command) => { println!("next (native route): {command}"); 1 diff --git a/crates/deploy/src/winfront/routing.rs b/crates/deploy/src/winfront/routing.rs index 59309cf7..06b0fcc7 100644 --- a/crates/deploy/src/winfront/routing.rs +++ b/crates/deploy/src/winfront/routing.rs @@ -56,46 +56,72 @@ pub async fn dispatch(args: &[String]) -> Option { } }; let command = args.first()?.clone(); - match command.as_str() { - "doctor" => return Some(doctor(&args[1..]).await), - "up" | "preflight" | "verify" | "status" | "reconfigure" | "down" | "service" | "logs" - | "report" => {} - _ => return None, + if command == "doctor" { + return Some(doctor(&args[1..]).await); + } + if !is_routed_command(&command) { + return None; } let have_wsl = wsl_exe().is_some(); let route = match explicit { Some(route) => route, - None if !have_wsl => Route::Native, - // A service is installed for the route that was prepared: the WSL bridge state, unless a native configuration exists. - None if command == "service" => { - if BridgeState::read(&local_app_data()).is_some() && !native_prepared() { - Route::Wsl - } else { - Route::Native - } - } - None if matches!( - command.as_str(), - "status" | "reconfigure" | "down" | "logs" | "report" - ) && native_service_alive() => - { - Route::Native - } - None => Route::Wsl, + None => default_route(&command, have_wsl), }; if route == Route::Native { // The ordinary command code, with the route flags removed. - let rest: Vec = args.clone(); - return Some(crate::app::main_native(rest).await); + return Some(crate::app::main_native(args).await); } + Some(run_through_wsl(&command, &args[1..], have_wsl).await) +} + +/// The command in the WSL2 distribution; `rest` are its arguments. +async fn run_through_wsl(command: &str, rest: &[String], have_wsl: bool) -> i32 { if !have_wsl { note("wsl.exe was not found; install WSL2 (`wsl --install -d Ubuntu`) or use --native"); - return Some(1); + return 1; } if command == "service" { - return Some(service_wsl(&args[1..]).await); + return service_wsl(rest).await; } - Some(wsl_route(&command, &args[1..]).await) + wsl_route(command, rest).await +} + +fn is_routed_command(command: &str) -> bool { + matches!( + command, + "up" | "preflight" + | "verify" + | "status" + | "reconfigure" + | "down" + | "service" + | "logs" + | "report" + ) +} + +/// The route when no flag names one. +fn default_route(command: &str, have_wsl: bool) -> Route { + if !have_wsl { + return Route::Native; + } + // A service is installed for the route that was prepared: the WSL bridge state, unless a native configuration + // exists. + if command == "service" { + return if BridgeState::read(&local_app_data()).is_some() && !native_prepared() { + Route::Wsl + } else { + Route::Native + }; + } + if matches!( + command, + "status" | "reconfigure" | "down" | "logs" | "report" + ) && native_service_alive() + { + return Route::Native; + } + Route::Wsl } /// Has `leleka up --native` written a run configuration in the default state directory? @@ -110,17 +136,9 @@ pub(super) fn native_prepared() -> bool { pub(super) async fn service_wsl(args: &[String]) -> i32 { use crate::cli::ServiceAction; - let action = match args.first().map(String::as_str) { - Some("install") => ServiceAction::Install, - Some("uninstall") => ServiceAction::Uninstall, - Some("status") => ServiceAction::Status, - Some("start") => ServiceAction::Start, - Some("stop") => ServiceAction::Stop, - Some("hold") => ServiceAction::Hold, - _ => { - note("usage: leleka service install|uninstall|status|start|stop [--wsl-distro NAME]"); - return 2; - } + let Some(action) = service_action(args) else { + note("usage: leleka service install|uninstall|status|start|stop [--wsl-distro NAME]"); + return 2; }; let hidden = args.iter().any(|a| a == "--hidden"); let rest: Vec = args[1..] @@ -129,18 +147,7 @@ pub(super) async fn service_wsl(args: &[String]) -> i32 { .cloned() .collect(); if action == ServiceAction::Install && args.iter().any(|a| a == "--dry-run") { - let exe = std::env::current_exe() - .map(|p| p.display().to_string()) - .unwrap_or_else(|_| "leleka.exe".into()); - let spec = - crate::service::wsl_task(&exe, "", &crate::winservice::current_user()); - println!( - "--dry-run: nothing is changed. In the distribution: `systemctl --user enable {}`; on Windows: `schtasks /Create /TN {} /XML /F` with this task definition: -{}", - crate::service::WSL_UNIT, - spec.name, - crate::service::task_xml(&spec) - ); + print_service_dry_run(); return 0; } let begin = matches!( @@ -149,36 +156,63 @@ pub(super) async fn service_wsl(args: &[String]) -> i32 { ); match open_session(&rest, begin) { Ok(session) => crate::winservice::run_wsl(action, &session.bridge, hidden).await, - Err(message) => match action { - ServiceAction::Status => { - println!("unit {}: {message}", crate::service::WSL_UNIT); - crate::winservice::print_task_state(crate::service::WSL_TASK); - 1 - } - ServiceAction::Uninstall => { - match crate::winservice::schtasks(&[ - "/Delete", - "/TN", - crate::service::WSL_TASK, - "/F", - ]) { - Ok(_) => println!("removed the task {}", crate::service::WSL_TASK), - Err(why) => note(&format!("task not removed: {why}")), - } - 0 - } - _ => { - note(&message); - 1 - } - }, + Err(message) => service_without_session(action, &message), } } -/// Choose the distribution, translate the arguments. `start` is false for read-only commands: they must not boot a stopped VM. -pub(super) fn open_session(args: &[String], start: bool) -> Result { - let wsl = wsl_exe().ok_or("wsl.exe was not found")?; - let saved = BridgeState::read(&local_app_data()); +fn service_action(args: &[String]) -> Option { + use crate::cli::ServiceAction; + Some(match args.first().map(String::as_str)? { + "install" => ServiceAction::Install, + "uninstall" => ServiceAction::Uninstall, + "status" => ServiceAction::Status, + "start" => ServiceAction::Start, + "stop" => ServiceAction::Stop, + "hold" => ServiceAction::Hold, + _ => return None, + }) +} + +fn print_service_dry_run() { + let exe = std::env::current_exe() + .map(|p| p.display().to_string()) + .unwrap_or_else(|_| "leleka.exe".into()); + let spec = crate::service::wsl_task(&exe, "", &crate::winservice::current_user()); + println!( + "--dry-run: nothing is changed. In the distribution: `systemctl --user enable {}`; on Windows: `schtasks /Create /TN {} /XML /F` with this task definition: +{}", + crate::service::WSL_UNIT, + spec.name, + crate::service::task_xml(&spec) + ); +} + +/// What a service command does when the distribution cannot be reached: the task side of `status` and `uninstall` +/// still works. +fn service_without_session(action: crate::cli::ServiceAction, message: &str) -> i32 { + use crate::cli::ServiceAction; + match action { + ServiceAction::Status => { + println!("unit {}: {message}", crate::service::WSL_UNIT); + crate::winservice::print_task_state(crate::service::WSL_TASK); + 1 + } + ServiceAction::Uninstall => { + match crate::winservice::schtasks(&["/Delete", "/TN", crate::service::WSL_TASK, "/F"]) { + Ok(_) => println!("removed the task {}", crate::service::WSL_TASK), + Err(why) => note(&format!("task not removed: {why}")), + } + 0 + } + _ => { + note(message); + 1 + } + } +} + +/// The distribution named by the flags or the environment, else the one of the last `up`. +fn requested_distro(args: &[String], saved: Option<&BridgeState>) -> Option { // The distribution can be named before the other flags are translated (UNC paths name it too). let mut requested = std::env::var("LELEKA_WSL_DISTRO") .ok() @@ -195,8 +229,17 @@ pub(super) fn open_session(args: &[String], start: bool) -> Result Result { + let wsl = wsl_exe().ok_or("wsl.exe was not found")?; + let saved = BridgeState::read(&local_app_data()); + let requested = requested_distro(args, saved.as_ref()); let list = list_distros(&wsl)?; let distro = pick_distro(&list, requested.as_deref())?; let running = list diff --git a/crates/deploy/src/winfront/session.rs b/crates/deploy/src/winfront/session.rs index a1c2fd9c..f76b6cc5 100644 --- a/crates/deploy/src/winfront/session.rs +++ b/crates/deploy/src/winfront/session.rs @@ -58,96 +58,181 @@ pub(super) async fn forward(command: &str, args: &[String]) -> i32 { } }; let json = session.forwarded.args.iter().any(|a| a == "--json"); - if let Some(assets) = &session.forwarded.assets - && is_drvfs(assets) - { - note(&format!( - "--assets {assets} is a Windows drive seen from WSL (9p): mapped and direct reads of the 140 GB model are far too slow there. Put the model volume on the WSL disk, e.g. --assets {}/leleka-assets (copy the files with `wsl -d {} cp` or from \\\\wsl.localhost\\{}\\...)", - session.home, session.bridge.distro, session.bridge.distro - )); - return 2; + if let Some(code) = refuse_drvfs_assets(&session) { + return code; } if !json && matches!(command, "up" | "preflight") { - match wslconfig_note(32) { - Some(advice) => note(&format!("note: {advice}")), - None => { - let have = std::env::var_os("USERPROFILE") - .map(|home| PathBuf::from(home).join(".wslconfig")) - .and_then(|path| std::fs::read_to_string(path).ok()) - .map(|text| { - effective_wsl_memory( - &parse_wslconfig(&text), - probe(&ProbeRequest::default()).memory.total, - ) - }); - if let Some(have) = have { - note(&format!( - "WSL2 memory is {:.0} GiB (.wslconfig); fine for the laptop profile", - have as f64 / (1u64 << 30) as f64 - )); - } - } - } + note_wsl_memory(); } - let binary = match session.bridge.find_leleka( - session - .forwarded - .wsl_bin - .as_deref() - .or(session.saved.as_ref().map(|s| s.leleka_bin.as_str())), - ) { + let binary = match find_linux_leleka(&session) { Ok(binary) => binary, Err(message) => { note(&message); return 1; } }; + run_in_wsl(&session, command, args, &binary).await +} + +/// `--assets` on a Windows drive seen from WSL (9p) is refused: the exit code, or `None` when the path is fine. +fn refuse_drvfs_assets(session: &Session) -> Option { + let assets = session.forwarded.assets.as_ref()?; + if !is_drvfs(assets) { + return None; + } + note(&format!( + concat!( + "--assets {assets} is a Windows drive seen from WSL (9p): mapped and direct reads of the 140 GB ", + "model are far too slow there. Put the model volume on the WSL disk, e.g. --assets ", + "{}/leleka-assets (copy the files with `wsl -d {} cp` or from \\\\wsl.localhost\\{}\\...)" + ), + session.home, + session.bridge.distro, + session.bridge.distro, + assets = assets + )); + Some(2) +} + +/// The advice about the memory of the WSL2 VM, or the figure when it is fine. +fn note_wsl_memory() { + if let Some(advice) = wslconfig_note(32) { + note(&format!("note: {advice}")); + return; + } + let have = std::env::var_os("USERPROFILE") + .map(|home| PathBuf::from(home).join(".wslconfig")) + .and_then(|path| std::fs::read_to_string(path).ok()) + .map(|text| { + effective_wsl_memory( + &parse_wslconfig(&text), + probe(&ProbeRequest::default()).memory.total, + ) + }); + if let Some(have) = have { + note(&format!( + "WSL2 memory is {:.0} GiB (.wslconfig); fine for the laptop profile", + have as f64 / (1u64 << 30) as f64 + )); + } +} + +fn find_linux_leleka(session: &Session) -> Result { + session.bridge.find_leleka( + session + .forwarded + .wsl_bin + .as_deref() + .or(session.saved.as_ref().map(|s| s.leleka_bin.as_str())), + ) +} + +/// Run the Linux `leleka COMMAND` in the distribution, pass Ctrl-C on, and say how to reach a service that `up` +/// started. +async fn run_in_wsl(session: &Session, command: &str, args: &[String], binary: &str) -> i32 { + let json = session.forwarded.args.iter().any(|a| a == "--json"); + let ran = Ran::of(command, args, json); + let dry_run = ran.dry_run; let state_dir = session.state_dir(); let api = format!("127.0.0.1:{}", session.forwarded.api_port.unwrap_or(8081)); - if command == "up" && !args.iter().any(|a| a == "--dry-run") { - let state = BridgeState { - distro: session.bridge.distro.clone(), - leleka_bin: binary.clone(), - state_dir: state_dir.clone(), - api: api.clone(), - }; - if let Err(message) = state.write(&local_app_data()) { - note(&format!("cannot remember the WSL settings: {message}")); - } + if command == "up" && !dry_run { + remember_bridge(session, binary, &state_dir, &api); } if !json { - note(&format!( - "running `{binary} {command}` in WSL2 ({}); the engine's output follows", - session.bridge.distro - )); - if command == "up" { - note(&format!( - "API endpoint will be http://{api} (WSL2 forwards loopback to Windows)" - )); - note(&format!( - "API key will be in {} (WSL path {state_dir}/api-key)", - session.key_unc(&state_dir) - )); - } + announce_run(session, command, binary, &state_dir, &api); } + let mut child = match spawn_linux(session, command, binary) { + Ok(child) => child, + Err(error) => { + note(&format!("cannot start wsl.exe: {error}")); + return 1; + } + }; + let announce = + (command == "up" && !json && !dry_run).then(|| spawn_announcer(session, &state_dir, &api)); + let status = wait_with_interrupts(&mut child).await; + if let Some(task) = announce { + task.abort(); + } + report_exit(status, &ran, session, (&state_dir, &api)) +} + +fn spawn_linux( + session: &Session, + command: &str, + binary: &str, +) -> std::io::Result { let mut linux_args = vec![command.to_owned()]; linux_args.extend(session.forwarded.args.clone()); - let mut child = - match tokio::process::Command::from(session.bridge.command(&binary, &linux_args)).spawn() { - Ok(child) => child, - Err(error) => { - note(&format!("cannot start wsl.exe: {error}")); - return 1; - } - }; - let announce = - (command == "up" && !json && !args.iter().any(|a| a == "--dry-run")).then(|| { - let bridge = session.bridge.clone(); - let (state_dir, api) = (state_dir.clone(), api.clone()); - tokio::spawn(async move { announce_when_ready(bridge, state_dir, api).await }) - }); + tokio::process::Command::from(session.bridge.command(binary, &linux_args)).spawn() +} + +/// The task that prints the Windows view once the service answers. +fn spawn_announcer(session: &Session, state_dir: &str, api: &str) -> tokio::task::JoinHandle<()> { + let bridge = session.bridge.clone(); + let (state_dir, api) = (state_dir.to_owned(), api.to_owned()); + tokio::spawn(async move { announce_when_ready(bridge, state_dir, api).await }) +} + +/// `--mode none` prepares everything and starts nothing. +fn prepares_only(args: &[String]) -> bool { + args.windows(2).any(|w| w[0] == "--mode" && w[1] == "none") + || args.iter().any(|a| a == "--mode=none") +} + +/// What was run, for the closing summary. +struct Ran<'a> { + command: &'a str, + json: bool, + dry_run: bool, + prepare_only: bool, +} + +impl<'a> Ran<'a> { + fn of(command: &'a str, args: &[String], json: bool) -> Self { + Ran { + command, + json, + dry_run: args.iter().any(|a| a == "--dry-run"), + prepare_only: prepares_only(args), + } + } +} + +fn remember_bridge(session: &Session, binary: &str, state_dir: &str, api: &str) { + let state = BridgeState { + distro: session.bridge.distro.clone(), + leleka_bin: binary.to_owned(), + state_dir: state_dir.to_owned(), + api: api.to_owned(), + }; + if let Err(message) = state.write(&local_app_data()) { + note(&format!("cannot remember the WSL settings: {message}")); + } +} + +fn announce_run(session: &Session, command: &str, binary: &str, state_dir: &str, api: &str) { + note(&format!( + "running `{binary} {command}` in WSL2 ({}); the engine's output follows", + session.bridge.distro + )); + if command == "up" { + note(&format!( + "API endpoint will be http://{api} (WSL2 forwards loopback to Windows)" + )); + note(&format!( + "API key will be in {} (WSL path {state_dir}/api-key)", + session.key_unc(state_dir) + )); + } +} + +/// Wait for the child; the first Ctrl-C lets the service drain, the second kills it. +async fn wait_with_interrupts( + child: &mut tokio::process::Child, +) -> std::io::Result { let mut interrupts = 0; - let status = loop { + loop { tokio::select! { status = child.wait() => break status, _ = tokio::signal::ctrl_c() => { @@ -159,22 +244,25 @@ pub(super) async fn forward(command: &str, args: &[String]) -> i32 { } } } - }; - if let Some(task) = announce { - task.abort(); } +} + +fn report_exit( + status: std::io::Result, + ran: &Ran, + session: &Session, + (state_dir, api): (&str, &str), +) -> i32 { match status { Ok(status) => { - let prepare_only = args.windows(2).any(|w| w[0] == "--mode" && w[1] == "none") - || args.iter().any(|a| a == "--mode=none"); - if command == "up" + if ran.command == "up" && status.success() - && !json - && !prepare_only - && !args.iter().any(|a| a == "--dry-run") + && !ran.json + && !ran.prepare_only + && !ran.dry_run { // A service started under systemd keeps running after `up` returns: say how to reach it. - print_windows_summary(&session.bridge.distro, &state_dir, &api); + print_windows_summary(&session.bridge.distro, state_dir, api); } status.code().unwrap_or(1) } diff --git a/crates/deploy/src/winservice.rs b/crates/deploy/src/winservice.rs index b4009edc..d983e003 100644 --- a/crates/deploy/src/winservice.rs +++ b/crates/deploy/src/winservice.rs @@ -2,13 +2,13 @@ //! The generated text is in `service.rs` (unit-tested); this file only runs programs and prints. use crate::{ cli::{ServiceAction, UpOptions}, - service::{ - NATIVE_TASK, TaskSpec, WSL_TASK, WSL_UNIT, native_task, parse_schtasks_query, task_xml, - utf16le_with_bom, wsl_task, - }, + service::{TaskSpec, parse_schtasks_query, task_xml, utf16le_with_bom}, wsl::Bridge, }; -use std::{path::Path, process::Command, time::Duration}; +use std::{path::Path, process::Command}; + +mod native_actions; +mod wsl_actions; fn note(message: &str) { eprintln!("leleka: {message}"); @@ -96,99 +96,11 @@ pub async fn run_native(action: ServiceAction, opts: UpOptions) -> i32 { note("`service hold` belongs to the WSL route (--wsl)"); 2 } - ServiceAction::Install => { - if crate::config::RunConfig::read(&paths.run_config()).is_err() { - note(&format!( - "{} is missing or invalid: prepare the service first, e.g. `leleka up --native --mode none --assets DIR`", - paths.run_config().display() - )); - return 1; - } - let exe = paths.bin("leleka"); - if !exe.is_file() { - note(&format!( - "{} is missing; `leleka up --native` installs the programs there", - exe.display() - )); - return 1; - } - let spec = native_task( - &exe.display().to_string(), - &paths.run_config().display().to_string(), - ¤t_user(), - ); - if opts.dry_run { - println!("--dry-run: nothing is registered. `schtasks /Create /TN {} /XML /F` with this task definition: -{}", spec.name, task_xml(&spec)); - return 0; - } - match register(&spec, &opts.dirs.state) { - Ok(()) => { - println!( - "installed the scheduled task {NATIVE_TASK}: `leleka.exe run --config {}` at logon of {}, restarted up to 3 times when it fails, no window", - paths.run_config().display(), - spec.user - ); - println!( - "start it now with `leleka service start`; stop it with `leleka service stop`; remove it with `leleka service uninstall`" - ); - 0 - } - Err(message) => { - note(&format!("cannot register the task: {message}")); - 1 - } - } - } - ServiceAction::Uninstall => { - #[cfg(windows)] - if crate::plan::service_running(&paths) { - crate::app::stop_foreground(&paths).await; - } - match schtasks(&["/Delete", "/TN", NATIVE_TASK, "/F"]) { - Ok(_) => { - println!("removed the scheduled task {NATIVE_TASK}"); - 0 - } - Err(message) => { - note(&format!("nothing removed: {message}")); - 1 - } - } - } - ServiceAction::Start => match schtasks(&["/Run", "/TN", NATIVE_TASK]) { - Ok(_) => { - println!( - "started the task {NATIVE_TASK}; `leleka status` shows the load (the model takes minutes)" - ); - 0 - } - Err(message) => { - note(&format!( - "cannot start the task (is it installed? `leleka service install`): {message}" - )); - 1 - } - }, - ServiceAction::Stop => { - #[cfg(windows)] - { - crate::app::stop_foreground(&paths).await - } - #[cfg(not(windows))] - { - 0 - } - } - ServiceAction::Status => { - let installed = print_task_state(NATIVE_TASK); - let running = crate::plan::service_running(&paths); - println!( - "supervisor: {}", - if running { "running" } else { "not running" } - ); - i32::from(!installed) - } + ServiceAction::Install => native_actions::install(&paths, &opts), + ServiceAction::Uninstall => native_actions::uninstall(&paths).await, + ServiceAction::Start => native_actions::start(), + ServiceAction::Stop => native_actions::stop(&paths).await, + ServiceAction::Status => native_actions::status(&paths), } } @@ -197,134 +109,12 @@ pub async fn run_native(action: ServiceAction, opts: UpOptions) -> i32 { /// `leleka service ...` for the WSL route. `hidden` is the logon task's own invocation of `hold`. pub async fn run_wsl(action: ServiceAction, bridge: &Bridge, hidden: bool) -> i32 { - let exe = std::env::current_exe() - .map(|p| p.display().to_string()) - .unwrap_or_else(|_| "leleka.exe".into()); - let xml_dir = std::env::var_os("LOCALAPPDATA") - .map(|d| std::path::PathBuf::from(d).join("leleka")) - .unwrap_or_else(|| std::path::PathBuf::from(".")); - let unit_state = || { - bridge - .capture("systemctl", &["--user", "is-active", WSL_UNIT]) - .unwrap_or_default() - .trim() - .to_owned() - }; match action { - ServiceAction::Install => { - if bridge - .capture( - "sh", - &[ - "-c", - "test -f \"$HOME/.config/systemd/user/leleka.service\" && echo yes", - ], - ) - .unwrap_or_default() - .trim() - != "yes" - { - note(&format!( - "the user unit leleka.service does not exist in {} yet: run `leleka up` once (with systemd enabled in the distribution) so that it installs the unit", - bridge.distro - )); - return 1; - } - if let Err(message) = bridge.capture("systemctl", &["--user", "enable", WSL_UNIT]) { - note(&message); - return 1; - } - let spec = wsl_task(&exe, &bridge.distro, ¤t_user()); - match register(&spec, &xml_dir) { - Ok(()) => { - println!( - "enabled {WSL_UNIT} in {} and installed the scheduled task {WSL_TASK}: at logon of {} it starts the unit and keeps the WSL2 VM alive (no window)", - bridge.distro, spec.user - ); - println!( - "start now: `leleka service start`; remove: `leleka service uninstall`" - ); - 0 - } - Err(message) => { - note(&format!( - "the unit is enabled, but the task could not be registered: {message}" - )); - 1 - } - } - } - ServiceAction::Uninstall => { - let _ = bridge.capture("systemctl", &["--user", "disable", "--now", WSL_UNIT]); - match schtasks(&["/Delete", "/TN", WSL_TASK, "/F"]) { - Ok(_) => println!( - "disabled {WSL_UNIT} in {} and removed the task {WSL_TASK}", - bridge.distro - ), - Err(message) => note(&format!("unit disabled; task not removed: {message}")), - } - 0 - } - ServiceAction::Start => match bridge.capture("systemctl", &["--user", "start", WSL_UNIT]) { - Ok(_) => { - println!( - "started {WSL_UNIT} in {}; `leleka status` shows the load", - bridge.distro - ); - 0 - } - Err(message) => { - note(&message); - 1 - } - }, - ServiceAction::Stop => match bridge.capture("systemctl", &["--user", "stop", WSL_UNIT]) { - Ok(_) => { - println!("stopped {WSL_UNIT} in {}", bridge.distro); - 0 - } - Err(message) => { - note(&message); - 1 - } - }, - ServiceAction::Status => { - println!( - "unit {WSL_UNIT} in {}: {} ({})", - bridge.distro, - unit_state(), - bridge - .capture("systemctl", &["--user", "is-enabled", WSL_UNIT]) - .unwrap_or_else(|_| "not installed".into()) - .trim() - ); - let installed = print_task_state(WSL_TASK); - i32::from(!installed) - } - ServiceAction::Hold => { - if hidden { - #[cfg(windows)] - crate::winsys::hide_console(); - } - let _ = bridge.capture("systemctl", &["--user", "start", WSL_UNIT]); - // A wsl.exe process that never ends keeps the VM (and with it the unit) alive; it ends when the task is stopped. - let mut command = bridge.command("sleep", &["infinity".to_owned()]); - #[cfg(windows)] - { - use std::os::windows::process::CommandExt; - command.creation_flags(0x0800_0000); - } - match command.spawn() { - Ok(mut child) => { - let _ = child.wait(); - 0 - } - Err(error) => { - note(&format!("cannot start wsl.exe: {error}")); - tokio::time::sleep(Duration::from_secs(1)).await; - 1 - } - } - } + ServiceAction::Install => wsl_actions::install(bridge), + ServiceAction::Uninstall => wsl_actions::uninstall(bridge), + ServiceAction::Start => wsl_actions::start(bridge), + ServiceAction::Stop => wsl_actions::stop(bridge), + ServiceAction::Status => wsl_actions::status(bridge), + ServiceAction::Hold => wsl_actions::hold(bridge, hidden).await, } } diff --git a/crates/deploy/src/winservice/native_actions.rs b/crates/deploy/src/winservice/native_actions.rs new file mode 100644 index 00000000..9d7dd6eb --- /dev/null +++ b/crates/deploy/src/winservice/native_actions.rs @@ -0,0 +1,129 @@ +//! The actions of `leleka service ...` on the native Windows route: the scheduled task that runs the supervisor. + +use super::{current_user, note, print_task_state, register, schtasks}; +use crate::{ + cli::UpOptions, + layout::Paths, + service::{NATIVE_TASK, native_task, task_xml}, +}; + +/// The programs and the configuration the task needs; the exit code of the refusal when they are not there. +fn installed_executable(paths: &Paths) -> Result { + if crate::config::RunConfig::read(&paths.run_config()).is_err() { + note(&format!( + "{} is missing or invalid: prepare the service first, e.g. `leleka up --native --mode none --assets DIR`", + paths.run_config().display() + )); + return Err(1); + } + let exe = paths.bin("leleka"); + if !exe.is_file() { + note(&format!( + "{} is missing; `leleka up --native` installs the programs there", + exe.display() + )); + return Err(1); + } + Ok(exe) +} + +pub(super) fn install(paths: &Paths, opts: &UpOptions) -> i32 { + let exe = match installed_executable(paths) { + Ok(exe) => exe, + Err(code) => return code, + }; + let spec = native_task( + &exe.display().to_string(), + &paths.run_config().display().to_string(), + ¤t_user(), + ); + if opts.dry_run { + println!("--dry-run: nothing is registered. `schtasks /Create /TN {} /XML /F` with this task definition: +{}", spec.name, task_xml(&spec)); + return 0; + } + match register(&spec, &opts.dirs.state) { + Ok(()) => { + say_installed(paths, &spec.user); + 0 + } + Err(message) => { + note(&format!("cannot register the task: {message}")); + 1 + } + } +} + +fn say_installed(paths: &Paths, user: &str) { + println!( + concat!( + "installed the scheduled task {}: `leleka.exe run --config {}` at logon of {}, ", + "restarted up to 3 times when it fails, no window" + ), + NATIVE_TASK, + paths.run_config().display(), + user + ); + println!(concat!( + "start it now with `leleka service start`; stop it with `leleka service stop`; ", + "remove it with `leleka service uninstall`" + )); +} + +pub(super) async fn uninstall(paths: &Paths) -> i32 { + #[cfg(windows)] + if crate::plan::service_running(paths) { + crate::app::stop_foreground(paths).await; + } + #[cfg(not(windows))] + let _ = paths; + match schtasks(&["/Delete", "/TN", NATIVE_TASK, "/F"]) { + Ok(_) => { + println!("removed the scheduled task {NATIVE_TASK}"); + 0 + } + Err(message) => { + note(&format!("nothing removed: {message}")); + 1 + } + } +} + +pub(super) fn start() -> i32 { + match schtasks(&["/Run", "/TN", NATIVE_TASK]) { + Ok(_) => { + println!( + "started the task {NATIVE_TASK}; `leleka status` shows the load (the model takes minutes)" + ); + 0 + } + Err(message) => { + note(&format!( + "cannot start the task (is it installed? `leleka service install`): {message}" + )); + 1 + } + } +} + +pub(super) async fn stop(paths: &Paths) -> i32 { + #[cfg(windows)] + { + crate::app::stop_foreground(paths).await + } + #[cfg(not(windows))] + { + let _ = paths; + 0 + } +} + +pub(super) fn status(paths: &Paths) -> i32 { + let installed = print_task_state(NATIVE_TASK); + let running = crate::plan::service_running(paths); + println!( + "supervisor: {}", + if running { "running" } else { "not running" } + ); + i32::from(!installed) +} diff --git a/crates/deploy/src/winservice/wsl_actions.rs b/crates/deploy/src/winservice/wsl_actions.rs new file mode 100644 index 00000000..684a654b --- /dev/null +++ b/crates/deploy/src/winservice/wsl_actions.rs @@ -0,0 +1,167 @@ +//! The actions of `leleka service ...` on the WSL route: the user unit inside the distribution and the logon task. + +use super::{current_user, note, print_task_state, register, schtasks}; +use crate::{ + service::{WSL_TASK, WSL_UNIT, wsl_task}, + wsl::Bridge, +}; +use std::time::Duration; + +/// Does the distribution have the user unit that `leleka up` installs? +fn unit_exists(bridge: &Bridge) -> bool { + bridge + .capture( + "sh", + &[ + "-c", + "test -f \"$HOME/.config/systemd/user/leleka.service\" && echo yes", + ], + ) + .unwrap_or_default() + .trim() + == "yes" +} + +fn note_missing_unit(distro: &str) { + note(&format!( + concat!( + "the user unit leleka.service does not exist in {} yet: run `leleka ", + "up` once (with systemd enabled in the distribution) so that it ", + "installs the unit" + ), + distro + )); +} + +/// Where the task definition is written before `schtasks` reads it. +fn task_xml_dir() -> std::path::PathBuf { + std::env::var_os("LOCALAPPDATA") + .map(|d| std::path::PathBuf::from(d).join("leleka")) + .unwrap_or_else(|| std::path::PathBuf::from(".")) +} + +pub(super) fn install(bridge: &Bridge) -> i32 { + let exe = std::env::current_exe() + .map(|p| p.display().to_string()) + .unwrap_or_else(|_| "leleka.exe".into()); + let xml_dir = task_xml_dir(); + if !unit_exists(bridge) { + note_missing_unit(&bridge.distro); + return 1; + } + if let Err(message) = bridge.capture("systemctl", &["--user", "enable", WSL_UNIT]) { + note(&message); + return 1; + } + let spec = wsl_task(&exe, &bridge.distro, ¤t_user()); + match register(&spec, &xml_dir) { + Ok(()) => { + say_installed(&bridge.distro, &spec.user); + 0 + } + Err(message) => { + note(&format!( + "the unit is enabled, but the task could not be registered: {message}" + )); + 1 + } + } +} + +fn say_installed(distro: &str, user: &str) { + println!( + concat!( + "enabled {} in {} and installed the scheduled task {}: at logon of {} it starts the unit ", + "and keeps the WSL2 VM alive (no window)" + ), + WSL_UNIT, distro, WSL_TASK, user + ); + println!("start now: `leleka service start`; remove: `leleka service uninstall`"); +} + +pub(super) fn uninstall(bridge: &Bridge) -> i32 { + let _ = bridge.capture("systemctl", &["--user", "disable", "--now", WSL_UNIT]); + match schtasks(&["/Delete", "/TN", WSL_TASK, "/F"]) { + Ok(_) => println!( + "disabled {WSL_UNIT} in {} and removed the task {WSL_TASK}", + bridge.distro + ), + Err(message) => note(&format!("unit disabled; task not removed: {message}")), + } + 0 +} + +pub(super) fn start(bridge: &Bridge) -> i32 { + match bridge.capture("systemctl", &["--user", "start", WSL_UNIT]) { + Ok(_) => { + println!( + "started {WSL_UNIT} in {}; `leleka status` shows the load", + bridge.distro + ); + 0 + } + Err(message) => { + note(&message); + 1 + } + } +} + +pub(super) fn stop(bridge: &Bridge) -> i32 { + match bridge.capture("systemctl", &["--user", "stop", WSL_UNIT]) { + Ok(_) => { + println!("stopped {WSL_UNIT} in {}", bridge.distro); + 0 + } + Err(message) => { + note(&message); + 1 + } + } +} + +pub(super) fn status(bridge: &Bridge) -> i32 { + let unit_state = bridge + .capture("systemctl", &["--user", "is-active", WSL_UNIT]) + .unwrap_or_default() + .trim() + .to_owned(); + println!( + "unit {WSL_UNIT} in {}: {} ({})", + bridge.distro, + unit_state, + bridge + .capture("systemctl", &["--user", "is-enabled", WSL_UNIT]) + .unwrap_or_else(|_| "not installed".into()) + .trim() + ); + let installed = print_task_state(WSL_TASK); + i32::from(!installed) +} + +/// The logon task: start the unit, then hold the VM up with a `wsl.exe` that never ends. +pub(super) async fn hold(bridge: &Bridge, hidden: bool) -> i32 { + if hidden { + #[cfg(windows)] + crate::winsys::hide_console(); + } + let _ = bridge.capture("systemctl", &["--user", "start", WSL_UNIT]); + // A wsl.exe process that never ends keeps the VM (and with it the unit) alive; it ends when the task is stopped. + let mut command = bridge.command("sleep", &["infinity".to_owned()]); + #[cfg(windows)] + { + use std::os::windows::process::CommandExt; + command.creation_flags(0x0800_0000); + } + match command.spawn() { + Ok(mut child) => { + let _ = child.wait(); + 0 + } + Err(error) => { + note(&format!("cannot start wsl.exe: {error}")); + tokio::time::sleep(Duration::from_secs(1)).await; + 1 + } + } +} diff --git a/crates/deploy/src/wsl/distros_and_paths.rs b/crates/deploy/src/wsl/distros_and_paths.rs index ea342323..b7c8f6ea 100644 --- a/crates/deploy/src/wsl/distros_and_paths.rs +++ b/crates/deploy/src/wsl/distros_and_paths.rs @@ -52,19 +52,7 @@ pub fn parse_distro_list(text: &str) -> Vec { /// The distribution to use: the requested one, else the default WSL2 distribution that can host the engine, else the first. pub fn pick_distro(list: &[Distro], requested: Option<&str>) -> Result { if let Some(name) = requested { - return list - .iter() - .find(|d| d.name.eq_ignore_ascii_case(name)) - .map(|d| d.name.clone()) - .ok_or_else(|| { - format!( - "no WSL distribution named {name:?}; installed: {}", - list.iter() - .map(|d| d.name.as_str()) - .collect::>() - .join(", ") - ) - }); + return named_distro(list, name); } let usable: Vec<&Distro> = list .iter() @@ -82,6 +70,21 @@ pub fn pick_distro(list: &[Distro], requested: Option<&str>) -> Result Result { + list.iter() + .find(|d| d.name.eq_ignore_ascii_case(name)) + .map(|d| d.name.clone()) + .ok_or_else(|| { + format!( + "no WSL distribution named {name:?}; installed: {}", + list.iter() + .map(|d| d.name.as_str()) + .collect::>() + .join(", ") + ) + }) +} + // --------------------------------------------------------------------------------------------------------------- // paths @@ -93,33 +96,10 @@ pub fn pick_distro(list: &[Distro], requested: Option<&str>) -> Result) -> Result { let normalized = path.replace('\\', "/"); if let Some(rest) = normalized.strip_prefix("//") { - let mut parts = rest.splitn(3, '/'); - let (host, share, tail) = ( - parts.next().unwrap_or(""), - parts.next().unwrap_or(""), - parts.next().unwrap_or(""), - ); - if host.eq_ignore_ascii_case("wsl$") || host.eq_ignore_ascii_case("wsl.localhost") { - if !share.eq_ignore_ascii_case(distro) { - return Err(format!( - "{path} is in the WSL distribution {share:?}, but {distro:?} is the one in use" - )); - } - return Ok(format!("/{}", tail.trim_end_matches('/'))); - } - return Err(format!( - "{path} is a network share; put the model volume on the WSL disk" - )); + return unc_to_wsl(path, rest, distro); } - let bytes = normalized.as_bytes(); - if bytes.len() >= 3 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':' && bytes[2] == b'/' { - let drive = (bytes[0] as char).to_ascii_lowercase(); - let tail = normalized[3..].trim_end_matches('/'); - return Ok(if tail.is_empty() { - format!("/mnt/{drive}") - } else { - format!("/mnt/{drive}/{tail}") - }); + if let Some(mounted) = drive_to_wsl(&normalized) { + return Ok(mounted); } if normalized == "~" || normalized.starts_with("~/") { let home = home.ok_or("cannot expand ~ without the home directory of the WSL user")?; @@ -137,6 +117,43 @@ pub fn to_wsl_path(path: &str, distro: &str, home: Option<&str>) -> Result Result { + let mut parts = rest.splitn(3, '/'); + let (host, share, tail) = ( + parts.next().unwrap_or(""), + parts.next().unwrap_or(""), + parts.next().unwrap_or(""), + ); + if host.eq_ignore_ascii_case("wsl$") || host.eq_ignore_ascii_case("wsl.localhost") { + if !share.eq_ignore_ascii_case(distro) { + return Err(format!( + "{path} is in the WSL distribution {share:?}, but {distro:?} is the one in use" + )); + } + return Ok(format!("/{}", tail.trim_end_matches('/'))); + } + Err(format!( + "{path} is a network share; put the model volume on the WSL disk" + )) +} + +/// `C:/Users/me/x` as `/mnt/c/Users/me/x`; `None` for a path that does not start with a drive letter. +fn drive_to_wsl(normalized: &str) -> Option { + let bytes = normalized.as_bytes(); + if bytes.len() < 3 || !bytes[0].is_ascii_alphabetic() || bytes[1] != b':' || bytes[2] != b'/' { + return None; + } + let drive = (bytes[0] as char).to_ascii_lowercase(); + let tail = normalized[3..].trim_end_matches('/'); + Some(if tail.is_empty() { + format!("/mnt/{drive}") + } else { + format!("/mnt/{drive}/{tail}") + }) +} + /// A Windows drive or share seen from WSL (`/mnt/c/...`): 9p, far too slow for mapped and direct reads of the model. pub fn is_drvfs(linux_path: &str) -> bool { let mut parts = linux_path.split('/').filter(|p| !p.is_empty()); @@ -163,18 +180,8 @@ pub fn translate_args( let mut index = 0; while index < args.len() { let arg = &args[index]; - let (name, inline) = match arg.split_once('=') { - Some((name, value)) if name.starts_with("--") => { - (name.to_owned(), Some(value.to_owned())) - } - _ => (arg.clone(), None), - }; - let takes_value = PATH_FLAGS.contains(&name.as_str()) - || matches!( - name.as_str(), - "--profile" | "--wsl-distro" | "--distro" | "--wsl-bin" | "--api-port" - ); - if !takes_value { + let (name, inline) = split_flag(arg); + if !takes_value(&name) { out.args.push(arg.clone()); index += 1; continue; @@ -189,38 +196,84 @@ pub fn translate_args( } }; index += 1; - match name.as_str() { - "--wsl-distro" | "--distro" => out.distro = Some(value), - "--wsl-bin" => out.wsl_bin = Some(value), - "--profile" => { - let looks_like_path = - value.contains('/') || value.contains('\\') || value.ends_with(".json"); - let value = if looks_like_path { - to_wsl_path(&value, distro, home)? - } else { - value - }; - out.args.extend(["--profile".into(), value]); - } - "--api-port" => { - out.api_port = value.parse().ok(); - out.args.extend(["--api-port".into(), value]); - } - flag => { - let translated = - to_wsl_path(&value, distro, home).map_err(|e| format!("{flag}: {e}"))?; - match flag { - "--assets" => out.assets = Some(translated.clone()), - "--state-dir" => out.state_dir = Some(translated.clone()), - _ => {} - } - out.args.extend([flag.to_owned(), translated]); - } - } + forward_flag(&mut out, &name, value, distro, home)?; } Ok(out) } +/// `--name=value` as the name and the inline value; any other argument is a name. +fn split_flag(arg: &str) -> (String, Option) { + match arg.split_once('=') { + Some((name, value)) if name.starts_with("--") => (name.to_owned(), Some(value.to_owned())), + _ => (arg.to_owned(), None), + } +} + +/// The flags whose value is a path or is read here. +fn takes_value(name: &str) -> bool { + PATH_FLAGS.contains(&name) + || matches!( + name, + "--profile" | "--wsl-distro" | "--distro" | "--wsl-bin" | "--api-port" + ) +} + +/// One flag with its value: kept for this side, or translated and passed on to the Linux command. +fn forward_flag( + out: &mut Forwarded, + name: &str, + value: String, + distro: &str, + home: Option<&str>, +) -> Result<(), String> { + match name { + "--wsl-distro" | "--distro" => out.distro = Some(value), + "--wsl-bin" => out.wsl_bin = Some(value), + "--profile" => forward_profile(out, value, distro, home)?, + "--api-port" => { + out.api_port = value.parse().ok(); + out.args.extend(["--api-port".into(), value]); + } + flag => forward_path_flag(out, flag, value, distro, home)?, + } + Ok(()) +} + +/// `--profile`: a path to a profile file is translated, a built-in name goes through. +fn forward_profile( + out: &mut Forwarded, + value: String, + distro: &str, + home: Option<&str>, +) -> Result<(), String> { + let looks_like_path = value.contains('/') || value.contains('\\') || value.ends_with(".json"); + let value = if looks_like_path { + to_wsl_path(&value, distro, home)? + } else { + value + }; + out.args.extend(["--profile".into(), value]); + Ok(()) +} + +/// Any other path flag: translated, and remembered when it names the assets or the state directory. +fn forward_path_flag( + out: &mut Forwarded, + flag: &str, + value: String, + distro: &str, + home: Option<&str>, +) -> Result<(), String> { + let translated = to_wsl_path(&value, distro, home).map_err(|e| format!("{flag}: {e}"))?; + match flag { + "--assets" => out.assets = Some(translated.clone()), + "--state-dir" => out.state_dir = Some(translated.clone()), + _ => {} + } + out.args.extend([flag.to_owned(), translated]); + Ok(()) +} + /// `40GB`, `40G`, `49152MB`, `40 GB`, plain bytes. pub fn parse_size(text: &str) -> Option { let text = text.trim().trim_matches('"').to_ascii_lowercase(); diff --git a/crates/deploy/src/wsl/tests.rs b/crates/deploy/src/wsl/tests.rs index 5a6643ea..58b01231 100644 --- a/crates/deploy/src/wsl/tests.rs +++ b/crates/deploy/src/wsl/tests.rs @@ -68,6 +68,11 @@ fn windows_paths_become_wsl_paths() { .unwrap_err() .contains("network share") ); + check_linux_and_relative_paths(); +} + +fn check_linux_and_relative_paths() { + let to = |p: &str| to_wsl_path(p, "Ubuntu", Some("/home/para")); assert_eq!(to("/home/para/laptop").unwrap(), "/home/para/laptop"); assert_eq!(to("~/laptop").unwrap(), "/home/para/laptop"); assert!(to("relative\\dir").unwrap_err().contains("absolute")); @@ -84,27 +89,30 @@ fn windows_paths_become_wsl_paths() { ); } +/// A command line with path flags, flags for this side and flags that go through. +const FORWARDED_COMMAND_LINE: [&str; 14] = [ + "--assets", + "\\\\wsl.localhost\\Ubuntu\\home\\para\\laptop", + "--state-dir=~/state", + "--gpu", + "0", + "--foreground", + "--wsl-distro", + "Ubuntu", + "--profile", + "rtx3080-16g", + "--api-port", + "9000", + "--cublas-dir", + "C:\\cuda\\bin", +]; + #[test] fn forwarded_arguments_translate_only_the_path_flags() { - let args: Vec = [ - "--assets", - "\\\\wsl.localhost\\Ubuntu\\home\\para\\laptop", - "--state-dir=~/state", - "--gpu", - "0", - "--foreground", - "--wsl-distro", - "Ubuntu", - "--profile", - "rtx3080-16g", - "--api-port", - "9000", - "--cublas-dir", - "C:\\cuda\\bin", - ] - .iter() - .map(|s| s.to_string()) - .collect(); + let args: Vec = FORWARDED_COMMAND_LINE + .iter() + .map(|s| s.to_string()) + .collect(); let f = translate_args(&args, "Ubuntu", Some("/home/para")).unwrap(); assert_eq!(f.distro.as_deref(), Some("Ubuntu")); assert_eq!(f.assets.as_deref(), Some("/home/para/laptop")); @@ -128,6 +136,10 @@ fn forwarded_arguments_translate_only_the_path_flags() { "/mnt/c/cuda/bin" ] ); + check_profile_path_and_missing_values(); +} + +fn check_profile_path_and_missing_values() { let profile = translate_args(&["--profile".into(), "C:\\p\\mine.json".into()], "U", None).unwrap(); assert_eq!(profile.args, ["--profile", "/mnt/c/p/mine.json"]); @@ -160,8 +172,12 @@ fn wslconfig_is_parsed_and_judged() { processors: Some(12) } ); + check_wslconfig_advice(&config); +} + +fn check_wslconfig_advice(config: &WslConfig) { // This laptop: 48 GB, memory=40GB swap=8GB -> fine. - assert_eq!(wslconfig_advice(&config, 48 * GIB, 32), None); + assert_eq!(wslconfig_advice(config, 48 * GIB, 32), None); // No file at all: half of 48 GB, no swap. let advice = wslconfig_advice(&WslConfig::default(), 48 * GIB, 32).unwrap(); assert!( diff --git a/crates/deploy/tests/e2e/dry_run_and_usage.rs b/crates/deploy/tests/e2e/dry_run_and_usage.rs index 76432cb8..bb66561d 100644 --- a/crates/deploy/tests/e2e/dry_run_and_usage.rs +++ b/crates/deploy/tests/e2e/dry_run_and_usage.rs @@ -7,15 +7,12 @@ use std::process::Command as Process; // ----------------------------------------------------------------------------------------------------------- // the command line -#[test] -fn dry_run_prints_the_plan_and_changes_nothing() { - let fixture = Fixture::new("dry"); - let bin = fixture.root.join("bin"); - fixture.install_fake_binaries(&bin); - let output = Process::new(LELEKA) +/// `leleka up --dry-run [extra] --profile rtx5090-32g --mode foreground` on the fixture's directories. +fn dry_run(fixture: &Fixture, bin: &std::path::Path, extra: &[&str]) -> std::process::Output { + Process::new(LELEKA) + .args(["up", "--dry-run"]) + .args(extra) .args([ - "up", - "--dry-run", "--profile", "rtx5090-32g", "--mode", @@ -28,9 +25,17 @@ fn dry_run_prints_the_plan_and_changes_nothing() { .arg("--prefix") .arg(&fixture.dirs.prefix) .arg("--bin-src") - .arg(&bin) + .arg(bin) .output() - .unwrap(); + .unwrap() +} + +#[test] +fn dry_run_prints_the_plan_and_changes_nothing() { + let fixture = Fixture::new("dry"); + let bin = fixture.root.join("bin"); + fixture.install_fake_binaries(&bin); + let output = dry_run(&fixture, &bin, &[]); let stdout = String::from_utf8_lossy(&output.stdout); let stderr = String::from_utf8_lossy(&output.stderr); assert!( @@ -54,26 +59,7 @@ fn dry_run_prints_the_plan_and_changes_nothing() { assert!(!path.exists(), "--dry-run created {}", path.display()); } // --json is one parseable document with the steps. - let output = Process::new(LELEKA) - .args([ - "up", - "--dry-run", - "--json", - "--profile", - "rtx5090-32g", - "--mode", - "foreground", - "--assets", - ]) - .arg(&fixture.dirs.assets) - .arg("--state-dir") - .arg(&fixture.dirs.state) - .arg("--prefix") - .arg(&fixture.dirs.prefix) - .arg("--bin-src") - .arg(&bin) - .output() - .unwrap(); + let output = dry_run(&fixture, &bin, &["--json"]); let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap(); assert_eq!(json["profile"], "rtx5090-32g"); assert!( diff --git a/crates/deploy/tests/e2e/engine_supervision.rs b/crates/deploy/tests/e2e/engine_supervision.rs index 8bbf2452..3dccb1dc 100644 --- a/crates/deploy/tests/e2e/engine_supervision.rs +++ b/crates/deploy/tests/e2e/engine_supervision.rs @@ -7,15 +7,32 @@ use std::{ time::{Duration, Instant}, }; -#[test] -fn a_hung_engine_is_killed_and_restarted_by_the_health_check() { - // `max_request_s` is 3 here; the fake API reports a request that has been active for 600 s. - let fixture = Fixture::new("hang"); +/// A fixture with the fakes, the file-backed profile written as state and an archive stand-in; with the path of the +/// config. +fn file_service(name: &str) -> (Fixture, std::path::PathBuf) { + let fixture = Fixture::new(name); fixture.install_fake_binaries(&fixture.dirs.prefix.join("bin")); fs::create_dir_all(fixture.fake_dir()).unwrap(); let config = fixture.write_state(file_profile()); fs::create_dir_all(&fixture.dirs.assets).unwrap(); fs::write(fixture.dirs.paths().kar(), b"archive").unwrap(); + (fixture, config) +} + +/// SIGTERM, and the supervisor exits with success. +fn stop_cleanly(supervisor: &mut std::process::Child) { + signal(u64::from(supervisor.id()), "TERM"); + assert!( + wait_exit(supervisor, Duration::from_secs(60)) + .unwrap() + .success() + ); +} + +#[test] +fn a_hung_engine_is_killed_and_restarted_by_the_health_check() { + // `max_request_s` is 3 here; the fake API reports a request that has been active for 600 s. + let (fixture, config) = file_service("hang"); tune(&config, |c| { c["health"] = serde_json::json!({"enabled": true, "interval_s": 1, "fail_s": 30, "max_request_s": 3}); @@ -46,22 +63,12 @@ fn a_hung_engine_is_killed_and_restarted_by_the_health_check() { healthy["restarts_total"], 1, "no second restart without a second stall" ); - signal(u64::from(supervisor.id()), "TERM"); - assert!( - wait_exit(&mut supervisor, Duration::from_secs(60)) - .unwrap() - .success() - ); + stop_cleanly(&mut supervisor); } #[test] fn engine_restarts_back_off_survive_failed_attempts_and_give_up_in_the_end() { - let fixture = Fixture::new("backoff"); - fixture.install_fake_binaries(&fixture.dirs.prefix.join("bin")); - fs::create_dir_all(fixture.fake_dir()).unwrap(); - let config = fixture.write_state(file_profile()); - fs::create_dir_all(&fixture.dirs.assets).unwrap(); - fs::write(fixture.dirs.paths().kar(), b"archive").unwrap(); + let (fixture, config) = file_service("backoff"); tune(&config, |c| { c["health"]["enabled"] = serde_json::json!(false); c["restart"] = serde_json::json!({"max_engine_restarts": 3, "stable_after_s": 600, "backoff_initial_s": 1, "backoff_max_s": 2}); @@ -86,12 +93,7 @@ fn engine_restarts_back_off_survive_failed_attempts_and_give_up_in_the_end() { ); // A restart that fails once and then works is just a slower restart. - let fixture = Fixture::new("backoff2"); - fixture.install_fake_binaries(&fixture.dirs.prefix.join("bin")); - fs::create_dir_all(fixture.fake_dir()).unwrap(); - let config = fixture.write_state(file_profile()); - fs::create_dir_all(&fixture.dirs.assets).unwrap(); - fs::write(fixture.dirs.paths().kar(), b"archive").unwrap(); + let (fixture, config) = file_service("backoff2"); tune(&config, |c| { c["health"]["enabled"] = serde_json::json!(false); c["restart"] = serde_json::json!({"max_engine_restarts": 5, "stable_after_s": 600, "backoff_initial_s": 1, "backoff_max_s": 2}); @@ -109,22 +111,12 @@ fn engine_restarts_back_off_survive_failed_attempts_and_give_up_in_the_end() { s["phase"] == "ready" && s["restarts_total"] == 1 }); assert!(again["engine_restarts"].as_u64().unwrap() >= 2, "{again}"); - signal(u64::from(supervisor.id()), "TERM"); - assert!( - wait_exit(&mut supervisor, Duration::from_secs(60)) - .unwrap() - .success() - ); + stop_cleanly(&mut supervisor); } #[test] fn logs_past_their_limit_are_rotated_while_the_service_runs() { - let fixture = Fixture::new("logs"); - fixture.install_fake_binaries(&fixture.dirs.prefix.join("bin")); - fs::create_dir_all(fixture.fake_dir()).unwrap(); - let config = fixture.write_state(file_profile()); - fs::create_dir_all(&fixture.dirs.assets).unwrap(); - fs::write(fixture.dirs.paths().kar(), b"archive").unwrap(); + let (fixture, config) = file_service("logs"); tune(&config, |c| { c["logs"] = serde_json::json!({"limit_mib": 1, "keep": 2}) }); @@ -149,22 +141,12 @@ fn logs_past_their_limit_are_rotated_while_the_service_runs() { assert!(fs::metadata(&big).unwrap().len() < 1 << 20); let doc = fixture.status().unwrap(); assert!(doc["log_bytes"].as_u64().unwrap() > 0); - signal(u64::from(supervisor.id()), "TERM"); - assert!( - wait_exit(&mut supervisor, Duration::from_secs(60)) - .unwrap() - .success() - ); + stop_cleanly(&mut supervisor); } #[test] fn a_killed_api_or_gateway_is_restarted_in_place_and_the_engine_is_left_alone() { - let fixture = Fixture::new("sidecars"); - fixture.install_fake_binaries(&fixture.dirs.prefix.join("bin")); - fs::create_dir_all(fixture.fake_dir()).unwrap(); - let config = fixture.write_state(file_profile()); - fs::create_dir_all(&fixture.dirs.assets).unwrap(); - fs::write(fixture.dirs.paths().kar(), b"archive").unwrap(); + let (fixture, config) = file_service("sidecars"); tune(&config, |c| { c["health"]["enabled"] = serde_json::json!(false) }); @@ -194,12 +176,7 @@ fn a_killed_api_or_gateway_is_restarted_in_place_and_the_engine_is_left_alone() std::thread::sleep(Duration::from_millis(200)); } assert_eq!(fixture.http_status("/ready"), 200); - signal(u64::from(supervisor.id()), "TERM"); - assert!( - wait_exit(&mut supervisor, Duration::from_secs(60)) - .unwrap() - .success() - ); + stop_cleanly(&mut supervisor); } #[test] diff --git a/crates/deploy/tests/e2e/expert_profile_install.rs b/crates/deploy/tests/e2e/expert_profile_install.rs index df1fc84b..9bb1235d 100644 --- a/crates/deploy/tests/e2e/expert_profile_install.rs +++ b/crates/deploy/tests/e2e/expert_profile_install.rs @@ -4,7 +4,7 @@ use crate::harness::*; use leleka_deploy::{ app::run_up, config::RunConfig, - plan::{FsState, plan_steps}, + plan::{Context, FsState, Step, plan_steps}, profile::Profile, steps::gather_fs, }; @@ -12,147 +12,159 @@ use std::fs; #[tokio::test] async fn up_installs_the_expert_profile_offline_and_reports_it() { - use leleka_deploy::expert_profile::{ - FileState, PROFILE_ENV, file_state, sha256_hex, tier_report, - }; - let fixture = Fixture::new("expert"); - let bin_src = fixture.root.join("release/bin"); - fixture.install_fake_binaries(&bin_src); - let (cublas, mtp) = (fixture.root.join("cublas"), fixture.root.join("mtp-src")); - fake_libraries(&cublas); - mtp_source(&mtp); - // A profile that pins the digest of a small fixture, so that the flow runs without the real 192 KiB table. - let table = b"STRP-fixture: a stand-in for the ranked expert table".to_vec(); - let digest = sha256_hex(&table); - let mut profile = Profile::builtin("rtx3080-16g").unwrap(); - profile.expert_profile_sha256 = Some(digest.clone()); - let profile_file = fixture.root.join("profile.json"); - fs::write(&profile_file, serde_json::to_string(&profile).unwrap()).unwrap(); - let local = fixture.root.join("table.bin"); - fs::write(&local, &table).unwrap(); - let paths = fixture.dirs.paths(); - let table_path = fixture.dirs.assets.join("data/expert-profile.bin"); - let flags = [ - profile_file.display().to_string(), - local.display().to_string(), - ]; + let scene = Scene::new(); + scene.no_table_blocks_with_both_ways_out().await; + scene.local_copy_is_installed_and_reported_on().await; + scene.second_run_rewrites_nothing().await; + scene.a_changed_file_turns_the_report_off().await; + scene.the_opt_out_is_recorded_and_reported().await; +} - // No table, offline, no override: the plan blocks with both ways out, before anything is downloaded. - let opts = up_options_with( - &fixture, - &bin_src, - &cublas, - &mtp, - &flags[0], - &["--no-fetch"], - ); - let ctx = healthy_context(&opts); - let steps = plan_steps(&ctx, &gather_fs(&ctx).await); - let step = steps.iter().find(|s| s.id == "expert-profile").unwrap(); - assert_eq!(step.state.tag(), "BLOCKED", "{step:?}"); - assert!( - step.state.why().contains("--expert-profile-file") - && step.state.why().contains("--no-expert-tier") - ); +/// The offline scenario: a profile that pins the digest of a small fixture, so that the flow runs without the real +/// table. +struct Scene { + fixture: Fixture, + bin_src: std::path::PathBuf, + cublas: std::path::PathBuf, + mtp: std::path::PathBuf, + profile_file: String, + local: String, + digest: String, + table_path: std::path::PathBuf, +} - // With the local copy: installed, verified, configured, reported ON. - let opts = up_options_with( - &fixture, - &bin_src, - &cublas, - &mtp, - &flags[0], - &["--expert-profile-file", &flags[1]], - ); - let ctx = healthy_context(&opts); - let steps = plan_steps(&ctx, &gather_fs(&ctx).await); - assert_eq!( - steps - .iter() - .find(|s| s.id == "expert-profile") - .unwrap() - .state - .tag(), - "todo" - ); - assert_eq!(run_up(&ctx, &steps).await.unwrap(), 0); - assert_eq!(file_state(&table_path, &digest), FileState::Valid); - let config = RunConfig::read(&paths.run_config()).unwrap(); - assert_eq!( - config.engine_env.get(PROFILE_ENV), - Some(&table_path.display().to_string()) - ); - let report = tier_report(&config, &fixture.dirs.assets); - assert!( - report.on && report.line().starts_with("expert tier ON"), - "{}", - report.line() - ); +impl Scene { + fn new() -> Scene { + use leleka_deploy::expert_profile::sha256_hex; + let fixture = Fixture::new("expert"); + let bin_src = fixture.root.join("release/bin"); + fixture.install_fake_binaries(&bin_src); + let (cublas, mtp) = (fixture.root.join("cublas"), fixture.root.join("mtp-src")); + fake_libraries(&cublas); + mtp_source(&mtp); + let table = b"STRP-fixture: a stand-in for the ranked expert table".to_vec(); + let digest = sha256_hex(&table); + let mut profile = Profile::builtin("rtx3080-16g").unwrap(); + profile.expert_profile_sha256 = Some(digest.clone()); + let profile_file = fixture.root.join("profile.json"); + fs::write(&profile_file, serde_json::to_string(&profile).unwrap()).unwrap(); + let local = fixture.root.join("table.bin"); + fs::write(&local, &table).unwrap(); + let table_path = fixture.dirs.assets.join("data/expert-profile.bin"); + Scene { + profile_file: profile_file.display().to_string(), + local: local.display().to_string(), + fixture, + bin_src, + cublas, + mtp, + digest, + table_path, + } + } - // Second run: done, nothing rewritten. - let ctx = healthy_context(&opts); - let steps = plan_steps(&ctx, &gather_fs(&ctx).await); - assert_eq!( - steps - .iter() - .find(|s| s.id == "expert-profile") - .unwrap() - .state - .tag(), - "done" - ); - assert_eq!(run_up(&ctx, &steps).await.unwrap(), 0); + /// The plan of an `up` with these extra flags. + async fn plan(&self, extra: &[&str]) -> (Context, Vec) { + let opts = up_options_with( + &self.fixture, + &self.bin_src, + &self.cublas, + &self.mtp, + &self.profile_file, + extra, + ); + let ctx = healthy_context(&opts); + let steps = plan_steps(&ctx, &gather_fs(&ctx).await); + (ctx, steps) + } - // The file changes behind the service's back: the report turns OFF and the start drops the switches. - fs::write(&table_path, b"corrupted").unwrap(); - let report = tier_report(&config, &fixture.dirs.assets); - assert!( - !report.on && report.line().starts_with("WARNING expert tier OFF"), - "{}", - report.line() - ); - let (env, _) = leleka_deploy::expert_profile::start_environment(&config, &fixture.dirs.assets); - assert!(!env.contains_key(PROFILE_ENV)); - // `up` without an override refuses to guess: the wrong file blocks the plan (it is never silently ignored). - let opts = up_options_with(&fixture, &bin_src, &cublas, &mtp, &flags[0], &[]); - let ctx = healthy_context(&opts); - let steps = plan_steps(&ctx, &gather_fs(&ctx).await); - assert_eq!( - steps - .iter() - .find(|s| s.id == "expert-profile") - .unwrap() - .state - .tag(), - "BLOCKED" - ); - assert!( - run_up(&ctx, &steps) - .await - .unwrap_err() - .contains("expert-profile") - ); + /// No table, offline, no override: the plan blocks with both ways out, before anything is downloaded. + async fn no_table_blocks_with_both_ways_out(&self) { + let (_, steps) = self.plan(&["--no-fetch"]).await; + let step = steps.iter().find(|s| s.id == "expert-profile").unwrap(); + assert_eq!(step.state.tag(), "BLOCKED", "{step:?}"); + assert!( + step.state.why().contains("--expert-profile-file") + && step.state.why().contains("--no-expert-tier") + ); + } - // The explicit opt-out is recorded and reported as such. - let opts = up_options_with( - &fixture, - &bin_src, - &cublas, - &mtp, - &flags[0], - &["--no-expert-tier"], - ); - let ctx = healthy_context(&opts); - let steps = plan_steps(&ctx, &gather_fs(&ctx).await); - assert_eq!(run_up(&ctx, &steps).await.unwrap(), 0); - let config = RunConfig::read(&paths.run_config()).unwrap(); - assert!(!config.expert_tier && !config.engine_env.contains_key(PROFILE_ENV)); - let report = tier_report(&config, &fixture.dirs.assets); - assert!( - !report.on && report.opted_out && report.line().contains("explicit opt-out"), - "{}", - report.line() - ); + /// With the local copy: installed, verified, configured, reported ON. + async fn local_copy_is_installed_and_reported_on(&self) { + use leleka_deploy::expert_profile::{FileState, PROFILE_ENV, file_state, tier_report}; + let (ctx, steps) = self.plan(&["--expert-profile-file", &self.local]).await; + assert_eq!(expert_step_tag(&steps), "todo"); + assert_eq!(run_up(&ctx, &steps).await.unwrap(), 0); + assert_eq!(file_state(&self.table_path, &self.digest), FileState::Valid); + let config = RunConfig::read(&self.fixture.dirs.paths().run_config()).unwrap(); + assert_eq!( + config.engine_env.get(PROFILE_ENV), + Some(&self.table_path.display().to_string()) + ); + let report = tier_report(&config, &self.fixture.dirs.assets); + assert!( + report.on && report.line().starts_with("expert tier ON"), + "{}", + report.line() + ); + } + + /// Second run: done, nothing rewritten. + async fn second_run_rewrites_nothing(&self) { + let (ctx, steps) = self.plan(&["--expert-profile-file", &self.local]).await; + assert_eq!(expert_step_tag(&steps), "done"); + assert_eq!(run_up(&ctx, &steps).await.unwrap(), 0); + } + + /// The file changes behind the service's back: the report turns OFF and the start drops the switches. + async fn a_changed_file_turns_the_report_off(&self) { + use leleka_deploy::expert_profile::{PROFILE_ENV, start_environment, tier_report}; + let assets = &self.fixture.dirs.assets; + let config = RunConfig::read(&self.fixture.dirs.paths().run_config()).unwrap(); + fs::write(&self.table_path, b"corrupted").unwrap(); + let report = tier_report(&config, assets); + assert!( + !report.on && report.line().starts_with("WARNING expert tier OFF"), + "{}", + report.line() + ); + let (env, _) = start_environment(&config, assets); + assert!(!env.contains_key(PROFILE_ENV)); + // `up` without an override refuses to guess: the wrong file blocks the plan (it is never silently ignored). + let (ctx, steps) = self.plan(&[]).await; + assert_eq!(expert_step_tag(&steps), "BLOCKED"); + assert!( + run_up(&ctx, &steps) + .await + .unwrap_err() + .contains("expert-profile") + ); + } + + /// The explicit opt-out is recorded and reported as such. + async fn the_opt_out_is_recorded_and_reported(&self) { + use leleka_deploy::expert_profile::{PROFILE_ENV, tier_report}; + let (ctx, steps) = self.plan(&["--no-expert-tier"]).await; + assert_eq!(run_up(&ctx, &steps).await.unwrap(), 0); + let config = RunConfig::read(&self.fixture.dirs.paths().run_config()).unwrap(); + assert!(!config.expert_tier && !config.engine_env.contains_key(PROFILE_ENV)); + let report = tier_report(&config, &self.fixture.dirs.assets); + assert!( + !report.on && report.opted_out && report.line().contains("explicit opt-out"), + "{}", + report.line() + ); + } +} + +/// The state tag of the `expert-profile` step. +fn expert_step_tag(steps: &[Step]) -> &str { + steps + .iter() + .find(|s| s.id == "expert-profile") + .unwrap() + .state + .tag() } #[tokio::test] diff --git a/crates/deploy/tests/e2e/harness.rs b/crates/deploy/tests/e2e/harness.rs index 3324edea..7b975ed8 100644 --- a/crates/deploy/tests/e2e/harness.rs +++ b/crates/deploy/tests/e2e/harness.rs @@ -257,35 +257,8 @@ pub(super) fn up_options_with( extra: &[&str], ) -> UpOptions { let var = |_: &str| None; - let args: Vec = [ - "up", - "--assets", - &fixture.dirs.assets.display().to_string(), - "--state-dir", - &fixture.dirs.state.display().to_string(), - "--prefix", - &fixture.dirs.prefix.display().to_string(), - "--bin-src", - &bin_src.display().to_string(), - "--cublas-dir", - &cublas.display().to_string(), - "--mtp-pack", - &mtp.display().to_string(), - "--api-port", - fixture.ports.api.rsplit(':').next().unwrap(), - "--engine-port", - fixture.ports.engine.rsplit(':').next().unwrap(), - "--daemon-port", - fixture.ports.daemon.rsplit(':').next().unwrap(), - "--profile", - profile, - "--mode", - "none", - ] - .iter() - .map(|s| s.to_string()) - .chain(extra.iter().map(|s| s.to_string())) - .collect(); + let mut args = up_arguments(fixture, [bin_src, cublas, mtp], profile); + args.extend(extra.iter().map(|s| s.to_string())); match parse( &args, &Environment { @@ -301,6 +274,39 @@ pub(super) fn up_options_with( } } +/// The command line of an `up` that locates the fixture's directories, ports and sources. `sources`: the binaries, +/// the cuBLAS directory and the MTP pack. +fn up_arguments(fixture: &Fixture, sources: [&Path; 3], profile: &str) -> Vec { + let [bin_src, cublas, mtp] = sources; + let port = |address: &str| address.rsplit(':').next().unwrap().to_owned(); + [ + "up".to_owned(), + "--assets".to_owned(), + fixture.dirs.assets.display().to_string(), + "--state-dir".to_owned(), + fixture.dirs.state.display().to_string(), + "--prefix".to_owned(), + fixture.dirs.prefix.display().to_string(), + "--bin-src".to_owned(), + bin_src.display().to_string(), + "--cublas-dir".to_owned(), + cublas.display().to_string(), + "--mtp-pack".to_owned(), + mtp.display().to_string(), + "--api-port".to_owned(), + port(&fixture.ports.api), + "--engine-port".to_owned(), + port(&fixture.ports.engine), + "--daemon-port".to_owned(), + port(&fixture.ports.daemon), + "--profile".to_owned(), + profile.to_owned(), + "--mode".to_owned(), + "none".to_owned(), + ] + .to_vec() +} + /// A host that passes the preflight, whatever machine runs the test. pub(super) fn healthy_context(opts: &UpOptions) -> Context { let mut ctx = gather(opts, &|_| None); @@ -312,6 +318,19 @@ pub(super) fn healthy_context(opts: &UpOptions) -> Context { vram_free_mib: 15500, sm: Some(86), }; + set_healthy_facts(&mut ctx, gpu); + ctx.needs.binary_has_sm86 = Some(true); + let profile = ctx.profile.as_ref().unwrap().clone(); + ctx.report = Some(evaluate(&ctx.facts, &profile, &ctx.needs)); + assert!( + !ctx.report.as_ref().unwrap().failed(), + "{}", + ctx.report.as_ref().unwrap().render() + ); + ctx +} + +fn set_healthy_facts(ctx: &mut Context, gpu: Gpu) { ctx.facts.os = "linux".into(); ctx.facts.arch = "x86_64".into(); ctx.facts.gpus = vec![gpu]; @@ -337,15 +356,6 @@ pub(super) fn healthy_context(opts: &UpOptions) -> Context { }, ); } - ctx.needs.binary_has_sm86 = Some(true); - let profile = ctx.profile.as_ref().unwrap().clone(); - ctx.report = Some(evaluate(&ctx.facts, &profile, &ctx.needs)); - assert!( - !ctx.report.as_ref().unwrap().failed(), - "{}", - ctx.report.as_ref().unwrap().render() - ); - ctx } pub(super) fn fake_libraries(dir: &Path) { diff --git a/crates/deploy/tests/e2e/reconfigure_flow.rs b/crates/deploy/tests/e2e/reconfigure_flow.rs index 47666b3b..1363b5e5 100644 --- a/crates/deploy/tests/e2e/reconfigure_flow.rs +++ b/crates/deploy/tests/e2e/reconfigure_flow.rs @@ -1,6 +1,7 @@ //! Reconfigure flows against the fake runtime: planning, persisting, restart and rollback. use crate::harness::*; +use leleka_deploy::config::RunConfig; use leleka_deploy::profile::{KarSource, Profile}; use leleka_deploy::reconfigure::{Outcome, Request, State, read_outcome, write_request}; use leleka_deploy::resources::Preset; @@ -37,68 +38,9 @@ fn a_new_budget_restarts_only_the_engine_with_the_same_sealed_archive() { ); assert!(!outcome.persisted); assert_eq!(outcome.effective.as_ref().unwrap()["gpu_budget_gib"], 2.0); - let after = fixture.wait_for("ready again", Duration::from_secs(60), |s| { - s["phase"] == "ready" - }); - assert_ne!( - after["engine_pid"].as_u64().unwrap(), - engine, - "the engine process is new" - ); - assert!(!pid_alive(engine), "the old engine is gone"); - assert_eq!( - after["gateway_pid"].as_u64().unwrap(), - gateway, - "the gateway keeps its process" - ); - assert_eq!( - after["api_pid"].as_u64().unwrap(), - api, - "the API keeps its process" - ); - assert_eq!( - after["engine_restarts"], 0, - "a planned restart is not a crash" - ); - assert_eq!(fixture.http_status("/ready"), 200); - let starts = service.starts(); - assert_eq!(starts.len(), 2, "{starts:?}"); - assert!( - starts[0].contains(&format!("--gpu-budget {}", 15 * GIB)), - "{}", - starts[0] - ); - assert!( - starts[1].contains(&format!("--gpu-budget {}", 2 * GIB)), - "{}", - starts[1] - ); - // the sealed descriptor of the first engine was handed on, and it is the one already verified - assert!( - starts[1].contains("--kar-archive-fd") && starts[1].contains("--kar-attested-by-stamp"), - "{}", - starts[1] - ); - let engine_log = fs::read_to_string(fixture.dirs.paths().logs().join("engine.log")).unwrap(); - assert_eq!(engine_log.matches("kar fd ").count(), 2, "{engine_log}"); - // not persisted: the file still has the old budget - assert_eq!( - fs::read_to_string(fixture.dirs.paths().run_config()).unwrap(), - before - ); - // asking for what is in force is answered at once, without another restart - let same = ask( - fixture, - &request("same", Some(2), None, json!({}), false), - Duration::from_secs(20), - ); - assert_eq!( - (same.state, same.message.contains("already")), - (State::Done, true), - "{}", - same.message - ); - assert_eq!(service.starts().len(), 2); + check_only_the_engine_was_replaced(fixture, (engine, gateway, api)); + check_new_engine_arguments(&service); + check_not_persisted_and_same_budget_is_a_noop(&service, &before); service.stop(); } @@ -132,41 +74,7 @@ fn persist_writes_the_files_and_a_crash_restart_keeps_the_new_numbers() { assert_eq!(config.profile.gpu_budget_bytes, 3 * GIB); assert_eq!(config.profile.context_tokens, 4096); assert_eq!(config.preset, Preset::Workstation); - assert!( - config.base_profile.is_some(), - "the unmodified profile is kept to undo the preset" - ); - assert_eq!( - config - .engine_environment() - .get("LELEKA_ORIGINAL_SERVE_CPU_WORKERS") - .map(String::as_str), - Some("3") - ); - // the API advertises the new context: its process was restarted on the same port, the gateway was not - let strata: serde_json::Value = - serde_json::from_str(&fs::read_to_string(fixture.dirs.paths().strata_config()).unwrap()) - .unwrap(); - assert_eq!(strata["runtime"]["max_context"], 4096); - let after = fixture.wait_for("ready again", Duration::from_secs(60), |s| { - s["phase"] == "ready" - }); - assert_ne!(after["api_pid"].as_u64().unwrap(), api); - assert_eq!(after["gateway_pid"].as_u64().unwrap(), gateway); - assert_eq!(fixture.http_status("/ready"), 200); - // a crash of the new engine restarts it with the new numbers, not the old ones - signal(after["engine_pid"].as_u64().unwrap(), "KILL"); - let again = fixture.wait_for("crash restart", Duration::from_secs(60), |s| { - s["phase"] == "ready" && s["engine_restarts"] == 1 - }); - assert_ne!(again["engine_pid"], after["engine_pid"]); - let starts = service.starts(); - let last = starts.last().unwrap(); - assert!( - last.contains(&format!("--gpu-budget {}", 3 * GIB)) - && last.contains("--context-tokens 4096"), - "{last}" - ); + check_persisted_numbers_survive(&service, gateway, api, &config); service.stop(); } @@ -205,23 +113,7 @@ fn settings_alone_are_recorded_and_persisted_without_a_restart() { "no restart" ); assert_eq!(service.starts().len(), 1); - // not persisted: in force for this supervisor only - let quiet = ask( - fixture, - &request("quiet", None, None, json!({"context_tokens": 2048}), false), - Duration::from_secs(30), - ); - assert_eq!((quiet.state, quiet.persisted), (State::Done, false)); - let file = leleka_deploy::config::RunConfig::read(&fixture.dirs.paths().run_config()).unwrap(); - assert_ne!(file.profile.context_tokens, 2048); - // an invalid document is refused and changes nothing - let bad = ask( - fixture, - &request("bad", None, None, json!({"cpu_workers": 99}), true), - Duration::from_secs(30), - ); - assert_eq!(bad.state, State::Refused); - assert!(bad.message.contains("cpu_workers"), "{}", bad.message); + check_unpersisted_and_invalid_documents(&service); service.stop(); } @@ -254,45 +146,7 @@ fn what_the_planner_refuses_changes_nothing_and_a_failing_new_engine_restores_th "the engine was not stopped" ); assert!(pid_alive(engine)); - // a budget the new engine cannot start with: the previous engine is started again with the previous numbers - fs::write( - fixture.fake_dir().join("fail-engine-budget"), - (4 * GIB).to_string(), - ) - .unwrap(); - let outcome = ask( - fixture, - &request("fails", Some(4), None, json!({}), true), - Duration::from_secs(180), - ); - assert_eq!( - outcome.state, - State::Refused, - "{}\n{}", - outcome.message, - fixture.logs() - ); - assert!( - outcome.message.contains("previous settings are back"), - "{}", - outcome.message - ); - let restored = fixture.wait_for("restored", Duration::from_secs(60), |s| { - s["phase"] == "ready" - }); - assert_ne!(restored["engine_pid"].as_u64().unwrap(), engine); - assert_eq!(fixture.http_status("/ready"), 200); - let starts = service.starts(); - assert_eq!(starts.len(), 3, "{starts:?}"); - assert!( - starts[1].contains(&format!("--gpu-budget {}", 4 * GIB)) - && starts[2].contains(&format!("--gpu-budget {}", 15 * GIB)), - "{starts:?}" - ); - // nothing was persisted from the failed attempt - let config = - leleka_deploy::config::RunConfig::read(&fixture.dirs.paths().run_config()).unwrap(); - assert_eq!(config.profile.gpu_budget_bytes, 15 * GIB); + check_failed_new_engine_restores_the_old_one(&service, engine); service.stop(); } @@ -375,5 +229,11 @@ fn when_not_even_the_previous_engine_comes_back_the_service_fails_with_an_answer assert_eq!(fixture.status().unwrap()["phase"], "failed"); } +mod checks; mod service; -use service::{ask, request, start}; +use checks::{ + check_failed_new_engine_restores_the_old_one, check_new_engine_arguments, + check_not_persisted_and_same_budget_is_a_noop, check_only_the_engine_was_replaced, + check_persisted_numbers_survive, check_unpersisted_and_invalid_documents, +}; +use service::{Service, ask, request, start}; diff --git a/crates/deploy/tests/e2e/reconfigure_flow/checks.rs b/crates/deploy/tests/e2e/reconfigure_flow/checks.rs new file mode 100644 index 00000000..7191e2e2 --- /dev/null +++ b/crates/deploy/tests/e2e/reconfigure_flow/checks.rs @@ -0,0 +1,205 @@ +//! Checks of the reconfigure scenarios: what the new, the restored and the unchanged engine must show. + +use super::*; + +pub(super) fn check_only_the_engine_was_replaced( + fixture: &Fixture, + (engine, gateway, api): (u64, u64, u64), +) { + let after = fixture.wait_for("ready again", Duration::from_secs(60), |s| { + s["phase"] == "ready" + }); + assert_ne!( + after["engine_pid"].as_u64().unwrap(), + engine, + "the engine process is new" + ); + assert!(!pid_alive(engine), "the old engine is gone"); + assert_eq!( + after["gateway_pid"].as_u64().unwrap(), + gateway, + "the gateway keeps its process" + ); + assert_eq!( + after["api_pid"].as_u64().unwrap(), + api, + "the API keeps its process" + ); + assert_eq!( + after["engine_restarts"], 0, + "a planned restart is not a crash" + ); + assert_eq!(fixture.http_status("/ready"), 200); +} + +/// The second engine has the new budget and is handed the first one's verified sealed descriptor. +pub(super) fn check_new_engine_arguments(service: &Service) { + let fixture = &service.fixture; + let starts = service.starts(); + assert_eq!(starts.len(), 2, "{starts:?}"); + assert!( + starts[0].contains(&format!("--gpu-budget {}", 15 * GIB)), + "{}", + starts[0] + ); + assert!( + starts[1].contains(&format!("--gpu-budget {}", 2 * GIB)), + "{}", + starts[1] + ); + // the sealed descriptor of the first engine was handed on, and it is the one already verified + assert!( + starts[1].contains("--kar-archive-fd") && starts[1].contains("--kar-attested-by-stamp"), + "{}", + starts[1] + ); + let engine_log = fs::read_to_string(fixture.dirs.paths().logs().join("engine.log")).unwrap(); + assert_eq!(engine_log.matches("kar fd ").count(), 2, "{engine_log}"); +} + +pub(super) fn check_not_persisted_and_same_budget_is_a_noop(service: &Service, before: &str) { + let fixture = &service.fixture; + // not persisted: the file still has the old budget + assert_eq!( + fs::read_to_string(fixture.dirs.paths().run_config()).unwrap(), + before + ); + // asking for what is in force is answered at once, without another restart + let same = ask( + fixture, + &request("same", Some(2), None, json!({}), false), + Duration::from_secs(20), + ); + assert_eq!( + (same.state, same.message.contains("already")), + (State::Done, true), + "{}", + same.message + ); + assert_eq!(service.starts().len(), 2); +} + +pub(super) fn check_persisted_numbers_survive( + service: &Service, + gateway: u64, + api: u64, + config: &RunConfig, +) { + let fixture = &service.fixture; + check_base_profile_and_workers(config); + // the API advertises the new context: its process was restarted on the same port, the gateway was not + let strata: serde_json::Value = + serde_json::from_str(&fs::read_to_string(fixture.dirs.paths().strata_config()).unwrap()) + .unwrap(); + assert_eq!(strata["runtime"]["max_context"], 4096); + let after = fixture.wait_for("ready again", Duration::from_secs(60), |s| { + s["phase"] == "ready" + }); + assert_ne!(after["api_pid"].as_u64().unwrap(), api); + assert_eq!(after["gateway_pid"].as_u64().unwrap(), gateway); + assert_eq!(fixture.http_status("/ready"), 200); + check_crash_restart_keeps_the_new_numbers(service, &after); +} + +fn check_base_profile_and_workers(config: &RunConfig) { + assert!( + config.base_profile.is_some(), + "the unmodified profile is kept to undo the preset" + ); + assert_eq!( + config + .engine_environment() + .get("LELEKA_ORIGINAL_SERVE_CPU_WORKERS") + .map(String::as_str), + Some("3") + ); +} + +pub(super) fn check_crash_restart_keeps_the_new_numbers( + service: &Service, + after: &serde_json::Value, +) { + let fixture = &service.fixture; + // a crash of the new engine restarts it with the new numbers, not the old ones + signal(after["engine_pid"].as_u64().unwrap(), "KILL"); + let again = fixture.wait_for("crash restart", Duration::from_secs(60), |s| { + s["phase"] == "ready" && s["engine_restarts"] == 1 + }); + assert_ne!(again["engine_pid"], after["engine_pid"]); + let starts = service.starts(); + let last = starts.last().unwrap(); + assert!( + last.contains(&format!("--gpu-budget {}", 3 * GIB)) + && last.contains("--context-tokens 4096"), + "{last}" + ); +} + +pub(super) fn check_unpersisted_and_invalid_documents(service: &Service) { + let fixture = &service.fixture; + // not persisted: in force for this supervisor only + let quiet = ask( + fixture, + &request("quiet", None, None, json!({"context_tokens": 2048}), false), + Duration::from_secs(30), + ); + assert_eq!((quiet.state, quiet.persisted), (State::Done, false)); + let file = leleka_deploy::config::RunConfig::read(&fixture.dirs.paths().run_config()).unwrap(); + assert_ne!(file.profile.context_tokens, 2048); + // an invalid document is refused and changes nothing + let bad = ask( + fixture, + &request("bad", None, None, json!({"cpu_workers": 99}), true), + Duration::from_secs(30), + ); + assert_eq!(bad.state, State::Refused); + assert!(bad.message.contains("cpu_workers"), "{}", bad.message); +} + +pub(super) fn check_failed_new_engine_restores_the_old_one(service: &Service, engine: u64) { + let fixture = &service.fixture; + // a budget the new engine cannot start with: the previous engine is started again with the previous numbers + fs::write( + fixture.fake_dir().join("fail-engine-budget"), + (4 * GIB).to_string(), + ) + .unwrap(); + let outcome = ask( + fixture, + &request("fails", Some(4), None, json!({}), true), + Duration::from_secs(180), + ); + assert_eq!( + outcome.state, + State::Refused, + "{}\n{}", + outcome.message, + fixture.logs() + ); + assert!( + outcome.message.contains("previous settings are back"), + "{}", + outcome.message + ); + check_restored_engine(service, engine); +} + +pub(super) fn check_restored_engine(service: &Service, engine: u64) { + let fixture = &service.fixture; + let restored = fixture.wait_for("restored", Duration::from_secs(60), |s| { + s["phase"] == "ready" + }); + assert_ne!(restored["engine_pid"].as_u64().unwrap(), engine); + assert_eq!(fixture.http_status("/ready"), 200); + let starts = service.starts(); + assert_eq!(starts.len(), 3, "{starts:?}"); + assert!( + starts[1].contains(&format!("--gpu-budget {}", 4 * GIB)) + && starts[2].contains(&format!("--gpu-budget {}", 15 * GIB)), + "{starts:?}" + ); + // nothing was persisted from the failed attempt + let config = + leleka_deploy::config::RunConfig::read(&fixture.dirs.paths().run_config()).unwrap(); + assert_eq!(config.profile.gpu_budget_bytes, 15 * GIB); +} diff --git a/crates/deploy/tests/e2e/sealed_archive.rs b/crates/deploy/tests/e2e/sealed_archive.rs index 4ffe1ab2..7972a9f6 100644 --- a/crates/deploy/tests/e2e/sealed_archive.rs +++ b/crates/deploy/tests/e2e/sealed_archive.rs @@ -20,7 +20,6 @@ fn a_sparse_memfd_profile_tells_every_engine_the_extents_digest_and_never_claims let fixture = Fixture::new("sparse"); fixture.install_fake_binaries(&fixture.dirs.prefix.join("bin")); let config = fixture.write_state(sparse_profile()); - let paths = fixture.dirs.paths(); let memfd = inheritable_sealed_memfd(&vec![7u8; 100_000]); let pin = "ab".repeat(32); let compiled = leleka_model_format::kar::PLE_EXTENTS_SHA256; @@ -41,6 +40,17 @@ fn a_sparse_memfd_profile_tells_every_engine_the_extents_digest_and_never_claims fixture.wait_for("engine restart", Duration::from_secs(60), |s| { s["phase"] == "ready" && s["engine_restarts"] == 1 }); + check_both_engines_got_the_digest(&fixture, &expected); + check_no_archive_stamp_and_digest_logged(&fixture, &expected); + signal(u64::from(supervisor.id()), "TERM"); + assert!( + wait_exit(&mut supervisor, Duration::from_secs(60)).is_some_and(|s| s.success()), + "{}", + fixture.logs() + ); +} + +fn check_both_engines_got_the_digest(fixture: &Fixture, expected: &str) { let calls = fs::read_to_string(fixture.fake_dir().join("calls.log")).unwrap(); let starts: Vec<&str> = calls .lines() @@ -59,6 +69,10 @@ fn a_sparse_memfd_profile_tells_every_engine_the_extents_digest_and_never_claims "engine {i}: {line}" ); } +} + +fn check_no_archive_stamp_and_digest_logged(fixture: &Fixture, expected: &str) { + let paths = fixture.dirs.paths(); // and no stamp of the archive was recorded from it let stamps: Vec = fs::read_dir(paths.stamps()) .map(|d| { @@ -74,13 +88,7 @@ fn a_sparse_memfd_profile_tells_every_engine_the_extents_digest_and_never_claims let log = fs::read_to_string(fixture.root.join("supervisor.out")).unwrap_or_default() + &fixture.logs(); // (the sparse memfd was EXPERIMENTAL until it became the rtx5090-32g form; the digest line is the contract) - assert!(log.contains(&expected), "{log}"); - signal(u64::from(supervisor.id()), "TERM"); - assert!( - wait_exit(&mut supervisor, Duration::from_secs(60)).is_some_and(|s| s.success()), - "{}", - fixture.logs() - ); + assert!(log.contains(expected), "{log}"); } #[test] @@ -131,14 +139,7 @@ fn seal_exec_hands_the_command_a_sealed_memfd_of_the_file_and_refuses_what_it_ca let file = dir.join("archive.bin"); let bytes: Vec = (0..300_000u32).map(|n| (n % 251) as u8).collect(); fs::write(&file, &bytes).unwrap(); - let run = |extra: &[&str]| { - Process::new(LELEKA) - .args(["seal-exec", "--file"]) - .arg(&file) - .args(extra) - .output() - .unwrap() - }; + let run = |extra: &[&str]| seal_exec_output(&file, extra); let ok = run(&[ "--expect-bytes", "300000", @@ -166,6 +167,21 @@ fn seal_exec_hands_the_command_a_sealed_memfd_of_the_file_and_refuses_what_it_ca out.contains(String::from_utf8_lossy(&want.stdout).trim()), "the descriptor holds the file byte for byte: {out}" ); + check_seal_exec_refusals(&file); + fs::remove_dir_all(&dir).unwrap(); +} + +fn seal_exec_output(file: &std::path::Path, extra: &[&str]) -> std::process::Output { + Process::new(LELEKA) + .args(["seal-exec", "--file"]) + .arg(file) + .args(extra) + .output() + .unwrap() +} + +fn check_seal_exec_refusals(file: &std::path::Path) { + let run = |extra: &[&str]| seal_exec_output(file, extra); // a wrong length, a missing command and the sparse form without its length are refused (exit 2), nothing is run for extra in [ vec!["--expect-bytes", "1", "--", "true"], @@ -188,5 +204,4 @@ fn seal_exec_hands_the_command_a_sealed_memfd_of_the_file_and_refuses_what_it_ca "{}", String::from_utf8_lossy(&sparse.stderr) ); - fs::remove_dir_all(&dir).unwrap(); } diff --git a/crates/deploy/tests/e2e/supervisor_lifecycle.rs b/crates/deploy/tests/e2e/supervisor_lifecycle.rs index 2c1b0061..861abadf 100644 --- a/crates/deploy/tests/e2e/supervisor_lifecycle.rs +++ b/crates/deploy/tests/e2e/supervisor_lifecycle.rs @@ -24,13 +24,20 @@ pub(super) fn lifecycle(source: KarSource) { let mut supervisor = start_supervisor(&fixture, &config, fd); let ready = fixture.wait_for("ready", Duration::from_secs(120), |s| s["phase"] == "ready"); + let pids = check_ready(&fixture, &ready, source); + let again = check_engine_restart(&fixture, pids); + check_restart_calls(&fixture, source); + // The sealed descriptor was reused, not copied again (one process held it the whole time). + assert!(!supervisor.try_wait().unwrap().is_some()); + check_clean_stop(&fixture, &mut supervisor, &again, pids); +} + +/// The ready status: no restarts, the API answers, the archive form is in the engine log, the status file is private. +/// Returns the pids of the engine, the gateway and the API. +fn check_ready(fixture: &Fixture, ready: &serde_json::Value, source: KarSource) -> (u64, u64, u64) { + let paths = fixture.dirs.paths(); assert_eq!(ready["engine_restarts"], 0); assert_eq!(fixture.http_status("/ready"), 200); - let (engine_pid, gateway_pid, api_pid) = ( - ready["engine_pid"].as_u64().unwrap(), - ready["gateway_pid"].as_u64().unwrap(), - ready["api_pid"].as_u64().unwrap(), - ); let engine_log = fs::read_to_string(paths.logs().join("engine.log")).unwrap(); match source { KarSource::Memfd => assert!(engine_log.contains("kar fd "), "{engine_log}"), @@ -49,8 +56,18 @@ pub(super) fn lifecycle(source: KarSource) { .unwrap() .contains(KEY) ); + ( + ready["engine_pid"].as_u64().unwrap(), + ready["gateway_pid"].as_u64().unwrap(), + ready["api_pid"].as_u64().unwrap(), + ) +} - // Kill the engine: the API reports not ready, the supervisor restarts it and loads again. +/// Kill the engine: the API reports not ready, the supervisor restarts it and loads again. +fn check_engine_restart( + fixture: &Fixture, + (engine_pid, gateway_pid, api_pid): (u64, u64, u64), +) -> serde_json::Value { signal(engine_pid, "KILL"); let again = fixture.wait_for("engine restart", Duration::from_secs(60), |s| { s["phase"] == "ready" && s["engine_restarts"] == 1 @@ -67,6 +84,10 @@ pub(super) fn lifecycle(source: KarSource) { "the API must survive an engine restart" ); assert_eq!(fixture.http_status("/ready"), 200); + again +} + +fn check_restart_calls(fixture: &Fixture, source: KarSource) { let calls = fs::read_to_string(fixture.fake_dir().join("calls.log")).unwrap(); assert_eq!(calls.matches("leleka-inference ").count(), 2, "{calls}"); assert_eq!(calls.matches("load-mtp").count(), 2, "{calls}"); @@ -91,13 +112,19 @@ pub(super) fn lifecycle(source: KarSource) { "{}", starts[1] ); - // The sealed descriptor was reused, not copied again (one process held it the whole time). - assert!(!supervisor.try_wait().unwrap().is_some()); +} - // SIGTERM drains and stops everything with status 0. +/// SIGTERM drains and stops everything with status 0. +fn check_clean_stop( + fixture: &Fixture, + supervisor: &mut std::process::Child, + again: &serde_json::Value, + (_, gateway_pid, api_pid): (u64, u64, u64), +) { + let paths = fixture.dirs.paths(); let new_engine = again["engine_pid"].as_u64().unwrap(); signal(u64::from(supervisor.id()), "TERM"); - let status = wait_exit(&mut supervisor, Duration::from_secs(60)) + let status = wait_exit(supervisor, Duration::from_secs(60)) .expect("the supervisor must exit after SIGTERM"); assert!(status.success(), "exit {status:?}\n{}", fixture.logs()); assert_eq!(fixture.status().unwrap()["phase"], "stopped"); diff --git a/crates/deploy/tests/e2e/up_flow.rs b/crates/deploy/tests/e2e/up_flow.rs index 829186b2..232a5253 100644 --- a/crates/deploy/tests/e2e/up_flow.rs +++ b/crates/deploy/tests/e2e/up_flow.rs @@ -11,18 +11,50 @@ use std::{fs, os::unix::fs::PermissionsExt}; #[tokio::test] async fn up_is_idempotent_resumable_and_never_rotates_secrets() { - let fixture = Fixture::new("up"); - let bin_src = fixture.root.join("release/bin"); - fixture.install_fake_binaries(&bin_src); - // The fakes find their shared state through the *installed* bin directory. - let (cublas, mtp) = (fixture.root.join("cublas"), fixture.root.join("mtp-src")); - fake_libraries(&cublas); - mtp_source(&mtp); - let opts = up_options(&fixture, &bin_src, &cublas, &mtp, &[]); - let paths = fixture.dirs.paths(); + let scene = Scene::new("up"); + let opts = scene.options(&[]); + let env_first = first_run_builds_everything(&scene, &opts).await; + second_run_does_nothing(&scene, &opts, &env_first).await; + a_lost_archive_is_rebuilt(&scene, &opts).await; + reverify_forces_the_verification(&scene).await; +} - // First run: everything is a todo, then everything exists. - let ctx = healthy_context(&opts); +type Options = leleka_deploy::cli::UpOptions; + +/// The directories and fakes of one `up` scenario. +struct Scene { + fixture: Fixture, + bin_src: std::path::PathBuf, + cublas: std::path::PathBuf, + mtp: std::path::PathBuf, +} + +impl Scene { + fn new(label: &str) -> Scene { + let fixture = Fixture::new(label); + let bin_src = fixture.root.join("release/bin"); + fixture.install_fake_binaries(&bin_src); + // The fakes find their shared state through the *installed* bin directory. + let (cublas, mtp) = (fixture.root.join("cublas"), fixture.root.join("mtp-src")); + fake_libraries(&cublas); + mtp_source(&mtp); + Scene { + fixture, + bin_src, + cublas, + mtp, + } + } + + fn options(&self, extra: &[&str]) -> Options { + up_options(&self.fixture, &self.bin_src, &self.cublas, &self.mtp, extra) + } +} + +/// First run: everything is a todo, then everything exists. Returns the environment file it wrote. +async fn first_run_builds_everything(scene: &Scene, opts: &Options) -> String { + let paths = scene.fixture.dirs.paths(); + let ctx = healthy_context(opts); let fs0 = gather_fs(&ctx).await; let steps = plan_steps(&ctx, &fs0); assert!( @@ -46,6 +78,13 @@ async fn up_is_idempotent_resumable_and_never_rotates_secrets() { ] { assert!(file.exists(), "{what}: {} missing", file.display()); } + check_modes_config_and_calls(scene) +} + +/// Private environment file, read-only archive, the profile of the run and the tools called once. +/// Returns the environment file. +fn check_modes_config_and_calls(scene: &Scene) -> String { + let (fixture, paths) = (&scene.fixture, scene.fixture.dirs.paths()); assert_eq!( fs::metadata(paths.env_file()).unwrap().permissions().mode() & 0o777, 0o600 @@ -59,21 +98,25 @@ async fn up_is_idempotent_resumable_and_never_rotates_secrets() { assert_eq!(config.profile.name, "rtx3080-16g"); let env_first = fs::read_to_string(paths.env_file()).unwrap(); assert!( - env_first.contains(&format!("LD_LIBRARY_PATH={}", cublas.display())), + env_first.contains(&format!("LD_LIBRARY_PATH={}", scene.cublas.display())), "{env_first}" ); assert_eq!( ( - count_calls(&fixture, "model fetch"), - count_calls(&fixture, "ensure-sharded-streamed"), - count_calls(&fixture, "api-key init") + count_calls(fixture, "model fetch"), + count_calls(fixture, "ensure-sharded-streamed"), + count_calls(fixture, "api-key init") ), (0, 1, 1), "the archive step fetches and verifies the shards itself" ); + env_first +} - // Second run: the plan has nothing to do and no tool is invoked again. - let ctx = healthy_context(&opts); +/// Second run: the plan has nothing to do and no tool is invoked again. +async fn second_run_does_nothing(scene: &Scene, opts: &Options, env_first: &str) { + let (fixture, paths) = (&scene.fixture, scene.fixture.dirs.paths()); + let ctx = healthy_context(opts); let fs1 = gather_fs(&ctx).await; let steps = plan_steps(&ctx, &fs1); for step in &steps { @@ -87,10 +130,10 @@ async fn up_is_idempotent_resumable_and_never_rotates_secrets() { assert_eq!(run_up(&ctx, &steps).await.unwrap(), 0); assert_eq!( ( - count_calls(&fixture, "model fetch"), - count_calls(&fixture, "model verify"), - count_calls(&fixture, "ensure-sharded-streamed"), - count_calls(&fixture, "extract-tokenizer") + count_calls(fixture, "model fetch"), + count_calls(fixture, "model verify"), + count_calls(fixture, "ensure-sharded-streamed"), + count_calls(fixture, "extract-tokenizer") ), (0, 0, 1, 1) ); @@ -99,11 +142,14 @@ async fn up_is_idempotent_resumable_and_never_rotates_secrets() { env_first, "tokens must never rotate" ); +} - // Resumable: a lost archive is rebuilt, everything else is left alone. +/// Resumable: a lost archive is rebuilt, everything else is left alone. +async fn a_lost_archive_is_rebuilt(scene: &Scene, opts: &leleka_deploy::cli::UpOptions) { + let (fixture, paths) = (&scene.fixture, scene.fixture.dirs.paths()); fs::set_permissions(paths.kar(), fs::Permissions::from_mode(0o600)).unwrap(); fs::remove_file(paths.kar()).unwrap(); - let ctx = healthy_context(&opts); + let ctx = healthy_context(opts); let steps = plan_steps(&ctx, &gather_fs(&ctx).await); assert_eq!( steps.iter().find(|s| s.id == "kar").unwrap().state.tag(), @@ -116,14 +162,16 @@ async fn up_is_idempotent_resumable_and_never_rotates_secrets() { assert_eq!(run_up(&ctx, &steps).await.unwrap(), 0); assert_eq!( ( - count_calls(&fixture, "model fetch"), - count_calls(&fixture, "ensure-sharded-streamed") + count_calls(fixture, "model fetch"), + count_calls(fixture, "ensure-sharded-streamed") ), (0, 2) ); +} - // --reverify forces the verification again. - let reverify = up_options(&fixture, &bin_src, &cublas, &mtp, &["--reverify"]); +/// `--reverify` forces the verification again. +async fn reverify_forces_the_verification(scene: &Scene) { + let reverify = scene.options(&["--reverify"]); let ctx = healthy_context(&reverify); let steps = plan_steps(&ctx, &gather_fs(&ctx).await); assert_eq!( @@ -135,13 +183,9 @@ async fn up_is_idempotent_resumable_and_never_rotates_secrets() { #[tokio::test] async fn trust_archive_skips_the_strict_rederivation_but_still_fetches_and_verifies_the_shards() { - let fixture = Fixture::new("trust"); - let bin_src = fixture.root.join("release/bin"); - fixture.install_fake_binaries(&bin_src); - let (cublas, mtp) = (fixture.root.join("cublas"), fixture.root.join("mtp-src")); - fake_libraries(&cublas); - mtp_source(&mtp); - let opts = up_options(&fixture, &bin_src, &cublas, &mtp, &["--trust-archive"]); + let scene = Scene::new("trust"); + let fixture = &scene.fixture; + let opts = scene.options(&["--trust-archive"]); let paths = fixture.dirs.paths(); // An archive of the pinned length with its provenance sidecar, as left by an earlier build. fs::create_dir_all(&fixture.dirs.assets).unwrap(); @@ -162,21 +206,19 @@ async fn trust_archive_skips_the_strict_rederivation_but_still_fetches_and_verif assert_eq!(run_up(&ctx, &steps).await.unwrap(), 0); assert_eq!( ( - count_calls(&fixture, "model fetch"), - count_calls(&fixture, "model verify"), - count_calls(&fixture, "ensure-sharded-streamed") + count_calls(fixture, "model fetch"), + count_calls(fixture, "model verify"), + count_calls(fixture, "ensure-sharded-streamed") ), (1, 1, 0) ); assert!(paths.stamps().join("kar.json").exists() && paths.stamps().join("model.json").exists()); - // Without the flag the same archive would be re-verified by the real tool. - let strict = healthy_context(&up_options( - &fixture, - &bin_src, - &cublas, - &mtp, - &["--reverify"], - )); + check_strict_plan_reverifies(&scene).await; +} + +/// Without the flag the same archive would be re-verified by the real tool. +async fn check_strict_plan_reverifies(scene: &Scene) { + let strict = healthy_context(&scene.options(&["--reverify"])); let steps = plan_steps(&strict, &gather_fs(&strict).await); assert!( !steps @@ -191,13 +233,9 @@ async fn trust_archive_skips_the_strict_rederivation_but_still_fetches_and_verif #[tokio::test] async fn a_wrong_size_archive_is_refused_before_the_engine_could_reject_it() { - let fixture = Fixture::new("wrongkar"); - let bin_src = fixture.root.join("release/bin"); - fixture.install_fake_binaries(&bin_src); - let (cublas, mtp) = (fixture.root.join("cublas"), fixture.root.join("mtp-src")); - fake_libraries(&cublas); - mtp_source(&mtp); - let opts = up_options(&fixture, &bin_src, &cublas, &mtp, &[]); + let scene = Scene::new("wrongkar"); + let fixture = &scene.fixture; + let opts = scene.options(&[]); // A pre-existing archive of the wrong length: the fake `ensure` reuses it, the size gate must object. fs::create_dir_all(&fixture.dirs.assets).unwrap(); fs::write(fixture.dirs.paths().kar(), b"short").unwrap(); diff --git a/crates/deploy/tests/e2e/verify_commands.rs b/crates/deploy/tests/e2e/verify_commands.rs index b9c8b408..2d6fb021 100644 --- a/crates/deploy/tests/e2e/verify_commands.rs +++ b/crates/deploy/tests/e2e/verify_commands.rs @@ -13,29 +13,8 @@ fn verify_quick_reports_the_health_of_the_installation_without_reading_the_model fixture.install_fake_binaries(&fixture.dirs.prefix.join("bin")); fs::create_dir_all(fixture.fake_dir()).unwrap(); let config = fixture.write_state(file_profile()); - let paths = fixture.dirs.paths(); - fs::create_dir_all(paths.shard(0).parent().unwrap()).unwrap(); - for (index, size) in [(0usize, 54_817_524_224u64), (1, 28_800_138_432)] { - fs::File::create(paths.shard(index)) - .unwrap() - .set_len(size) - .unwrap(); - } - fs::File::create(paths.kar()) - .unwrap() - .set_len(55_295_529_472) - .unwrap(); - let quick = || { - Process::new(LELEKA) - .args(["verify", "--quick", "--state-dir"]) - .arg(&fixture.dirs.state) - .arg("--prefix") - .arg(&fixture.dirs.prefix) - .arg("--assets") - .arg(&fixture.dirs.assets) - .output() - .unwrap() - }; + create_unstamped_model_files(&fixture); + let quick = || quick_verify(&fixture); // Not running: the files are there (unstamped, a note), the service is not (a problem). let before = quick(); let text = String::from_utf8_lossy(&before.stdout).into_owned(); @@ -58,7 +37,45 @@ fn verify_quick_reports_the_health_of_the_installation_without_reading_the_model && text.contains("engine restarts 0 in total"), "{text}" ); - // `leleka status` shows the same supervisor facts. + check_status_shows_the_same_facts(&fixture); + signal(u64::from(supervisor.id()), "TERM"); + assert!( + wait_exit(&mut supervisor, Duration::from_secs(60)) + .unwrap() + .success() + ); +} + +/// Sparse stand-ins for the two shards and the archive, of the pinned lengths and without stamps. +fn create_unstamped_model_files(fixture: &Fixture) { + let paths = fixture.dirs.paths(); + fs::create_dir_all(paths.shard(0).parent().unwrap()).unwrap(); + for (index, size) in [(0usize, 54_817_524_224u64), (1, 28_800_138_432)] { + fs::File::create(paths.shard(index)) + .unwrap() + .set_len(size) + .unwrap(); + } + fs::File::create(paths.kar()) + .unwrap() + .set_len(55_295_529_472) + .unwrap(); +} + +fn quick_verify(fixture: &Fixture) -> std::process::Output { + Process::new(LELEKA) + .args(["verify", "--quick", "--state-dir"]) + .arg(&fixture.dirs.state) + .arg("--prefix") + .arg(&fixture.dirs.prefix) + .arg("--assets") + .arg(&fixture.dirs.assets) + .output() + .unwrap() +} + +/// `leleka status` shows the same supervisor facts. +fn check_status_shows_the_same_facts(fixture: &Fixture) { let status = Process::new(LELEKA) .args(["status", "--state-dir"]) .arg(&fixture.dirs.state) @@ -73,12 +90,6 @@ fn verify_quick_reports_the_health_of_the_installation_without_reading_the_model text.contains("supervisor: phase ready") && text.contains("health: "), "{text}" ); - signal(u64::from(supervisor.id()), "TERM"); - assert!( - wait_exit(&mut supervisor, Duration::from_secs(60)) - .unwrap() - .success() - ); } #[test]