STRA-338 size-fn: leleka-deploy: winfront, wsl paths, units, http, status, doctor, logs, steps, profile and fake runtime split into stage helpers (second batch)
This commit is contained in:
+33
-25
@@ -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",
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -69,13 +69,32 @@ pub async fn main_native(mut args: Vec<String>) -> 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<String>) -> 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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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))]
|
||||
|
||||
@@ -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<String> {
|
||||
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(
|
||||
@@ -75,11 +76,13 @@ pub fn print_status(
|
||||
.map(|g| g["machine"].clone())
|
||||
.filter(Value::is_object);
|
||||
if json {
|
||||
let unit_state = unit.as_ref().map(|(_, state)| state);
|
||||
let prefix_cache = gateway.map(|g| g["prefix_cache"].clone());
|
||||
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})
|
||||
&json!({"ready": ready, "unit": unit_state, "supervisor": supervisor, "machine": machine,
|
||||
"prefix_cache": prefix_cache, "expert_tier": expert_tier, "requests": requests})
|
||||
)
|
||||
.expect("serializable")
|
||||
);
|
||||
@@ -88,16 +91,7 @@ pub fn print_status(
|
||||
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}");
|
||||
}
|
||||
print_status_text(supervisor, expert_tier, run_dir, requests);
|
||||
if let Some(machine) = &machine {
|
||||
print!("{}", render_machine(machine));
|
||||
} else if ready {
|
||||
@@ -107,6 +101,25 @@ pub fn print_status(
|
||||
i32::from(!ready)
|
||||
}
|
||||
|
||||
/// The supervisor document, the expert tier and the request line of the text form.
|
||||
fn print_status_text(
|
||||
supervisor: Option<Value>,
|
||||
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 +161,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 +170,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
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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 [
|
||||
|
||||
@@ -10,18 +10,47 @@ 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);
|
||||
});
|
||||
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");
|
||||
}
|
||||
crash_once_if_asked(fake);
|
||||
for stream in listener.incoming() {
|
||||
drop(stream);
|
||||
}
|
||||
}
|
||||
|
||||
/// `--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 +70,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 +97,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 +108,4 @@ pub(super) fn engine(fake: &Path, args: &[String]) {
|
||||
std::process::exit(9);
|
||||
});
|
||||
}
|
||||
for stream in listener.incoming() {
|
||||
drop(stream);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,22 +5,7 @@ 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}}");
|
||||
}
|
||||
["api-key", "init", "--file", file] => init_api_key(file),
|
||||
["model", "fetch", _, "--output", dir] => {
|
||||
fetch_shards(dir);
|
||||
println!("fetched");
|
||||
@@ -36,17 +21,7 @@ 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}");
|
||||
}
|
||||
] => ensure_streamed_archive(source_dir, 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"), "{}")
|
||||
@@ -60,6 +35,35 @@ pub(super) fn strata(fake: &Path, args: &[String]) {
|
||||
}
|
||||
}
|
||||
|
||||
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()
|
||||
@@ -95,34 +99,53 @@ 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 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) = 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<u8> = 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::<usize>().ok())
|
||||
})
|
||||
.unwrap_or(0);
|
||||
body.len() >= wanted
|
||||
});
|
||||
if count == 0 || complete {
|
||||
if count == 0 || request_complete(&raw) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let request = String::from_utf8_lossy(&raw).into_owned();
|
||||
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() {
|
||||
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::<usize>().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",
|
||||
@@ -136,20 +159,7 @@ pub(super) fn respond(mut stream: TcpStream, fake: &Path, engine_address: &str,
|
||||
"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" }),
|
||||
),
|
||||
"/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(),
|
||||
@@ -161,10 +171,25 @@ pub(super) fn respond(mut stream: TcpStream, fake: &Path, engine_address: &str,
|
||||
("200 OK", serde_json::json!({"settings": settings}).to_string())
|
||||
}
|
||||
_ => ("404 Not Found", "{}".to_owned()),
|
||||
};
|
||||
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 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" }
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -9,49 +9,41 @@ pub fn parse(args: &[String], env: &Environment) -> Result<Command, String> {
|
||||
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<Command, String> {
|
||||
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<Command, String> {
|
||||
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<Command, String> {
|
||||
other => Err(format!("unknown command {other:?}; see `leleka --help`")),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_profiles(rest: &[String]) -> Result<Command, String> {
|
||||
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<Command, String> {
|
||||
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<Command, String> {
|
||||
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))
|
||||
}
|
||||
|
||||
@@ -176,13 +176,16 @@ pub enum KarArg {
|
||||
None,
|
||||
}
|
||||
|
||||
/// The environment variables the engine is started with.
|
||||
type EngineEnv = BTreeMap<String, String>;
|
||||
|
||||
impl RunConfig {
|
||||
pub fn new(
|
||||
dirs: &Dirs,
|
||||
ports: Ports,
|
||||
gpu: u32,
|
||||
profile: Profile,
|
||||
engine_env: BTreeMap<String, String>,
|
||||
engine_env: EngineEnv,
|
||||
) -> Self {
|
||||
RunConfig {
|
||||
schema_version: SCHEMA_VERSION,
|
||||
|
||||
@@ -7,8 +7,37 @@ impl RunConfig {
|
||||
/// operator-source tuples). `{FD}` stays literal for [`KarArg::Fd`].
|
||||
pub fn engine_args(&self, kar: KarArg) -> Vec<String> {
|
||||
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<String> {
|
||||
let profile = &self.profile;
|
||||
let mut args: Vec<String> = 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<String> {
|
||||
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<String> {
|
||||
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
|
||||
}
|
||||
|
||||
+66
-39
@@ -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<String> {
|
||||
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<String> {
|
||||
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<String> {
|
||||
missing
|
||||
}
|
||||
|
||||
/// The size of a regular file.
|
||||
fn file_size(path: &Path) -> Option<u64> {
|
||||
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<String> {
|
||||
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<PathBuf>, name: &str) -> String {
|
||||
}
|
||||
|
||||
pub fn advise(inputs: &Inputs) -> Vec<Finding> {
|
||||
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<Finding> {
|
||||
.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<Finding> {
|
||||
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<Finding> {
|
||||
),
|
||||
_ => None,
|
||||
},
|
||||
});
|
||||
findings
|
||||
}
|
||||
}
|
||||
|
||||
/// The one command to run next for the native route, or `None` when it is ready to start.
|
||||
|
||||
+45
-28
@@ -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<Vec<u8>, 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<Response, String> {
|
||||
let text = String::from_utf8_lossy(raw);
|
||||
let (head, body) = text
|
||||
|
||||
+31
-22
@@ -77,29 +77,9 @@ pub fn rotate_if_needed(path: &Path, policy: Policy) -> io::Result<bool> {
|
||||
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,35 @@ pub fn rotate_if_needed(path: &Path, policy: Policy) -> io::Result<bool> {
|
||||
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<bool>)> {
|
||||
let Ok(entries) = std::fs::read_dir(dir) else {
|
||||
|
||||
@@ -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::<Vec<_>>()
|
||||
.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::<Vec<_>>()
|
||||
.join(" ")
|
||||
));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
@@ -45,17 +45,7 @@ impl Profile {
|
||||
pub fn resolve(spec: Option<&str>, gpu: Option<&Gpu>) -> Result<Profile, String> {
|
||||
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<Profile, String>
|
||||
_ => 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<Profile, String> {
|
||||
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(", ")
|
||||
))
|
||||
}
|
||||
|
||||
@@ -4,6 +4,26 @@ use super::*;
|
||||
|
||||
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::<u64>().ok().is_none_or(|mib| mib > (1 << 30))
|
||||
@@ -20,21 +40,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,27 +80,21 @@ impl MemoryBudget {
|
||||
|
||||
/// The engine environment this section adds.
|
||||
pub fn env(&self) -> BTreeMap<String, String> {
|
||||
fn text<T: ToString>(value: Option<T>) -> Option<String> {
|
||||
value.map(|v| v.to_string())
|
||||
}
|
||||
let mut env = BTreeMap::new();
|
||||
let mut put = |key: &str, value: Option<String>| {
|
||||
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_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(
|
||||
"LELEKA_MEMORY_CACHE_SHARE_PERCENT",
|
||||
self.cache_share_percent.map(|v| v.to_string()),
|
||||
text(self.cache_share_percent),
|
||||
);
|
||||
put("LELEKA_MEMORY_LOCK", self.lock.clone());
|
||||
if self.prefix_cache_on() {
|
||||
@@ -111,7 +110,7 @@ impl MemoryBudget {
|
||||
);
|
||||
put(
|
||||
"LELEKA_ORIGINAL_SERVE_RESIDENT_BUDGET_GIB",
|
||||
self.resident_budget_gib.map(|v| v.to_string()),
|
||||
text(self.resident_budget_gib),
|
||||
);
|
||||
env
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -282,47 +282,58 @@ 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<String, String>,
|
||||
) {
|
||||
if let Some(gib) = plan.mapped_working_set_gib
|
||||
&& !profile.engine_env.contains_key(MAPPED_WORKING_SET_ENV)
|
||||
{
|
||||
@@ -334,3 +345,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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,9 +26,11 @@ pub fn archive_serve_extents(
|
||||
.map_err(|e| format!("cannot derive the sparse extents of {}: {e}", kar.display()))
|
||||
}
|
||||
|
||||
const SEAL_EXEC_USAGE: &str = "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<SealExecPlan, String> {
|
||||
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() {
|
||||
@@ -53,10 +55,7 @@ pub fn parse_seal_exec(args: &[String]) -> Result<SealExecPlan, String> {
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
let command: Vec<String> = 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 +64,15 @@ pub fn parse_seal_exec(args: &[String]) -> Result<SealExecPlan, String> {
|
||||
})
|
||||
}
|
||||
|
||||
/// The command after the `--` at `args[i]`, which must be there and not empty.
|
||||
fn seal_command(args: &[String], i: usize) -> Result<Vec<String>, String> {
|
||||
let command: Vec<String> = 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<String> {
|
||||
args.iter()
|
||||
|
||||
@@ -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#"<?xml version="1.0" encoding="UTF-16"?>
|
||||
<Task version="1.4" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
|
||||
<RegistrationInfo>
|
||||
@@ -122,7 +120,16 @@ pub fn task_xml(spec: &TaskSpec) -> String {
|
||||
</Exec>
|
||||
</Actions>
|
||||
</Task>
|
||||
"#,
|
||||
"#
|
||||
};
|
||||
}
|
||||
|
||||
/// 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),
|
||||
|
||||
@@ -79,22 +79,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 +93,28 @@ pub async fn run_tool(
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 +134,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 +160,53 @@ pub fn install_binaries(ctx: &Context) -> Result<usize, String> {
|
||||
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<bool, String> {
|
||||
let (src, dst) = (src_dir.join(name), dst_dir.join(name));
|
||||
if !src.is_file() {
|
||||
if dst.is_file() {
|
||||
return Ok(false);
|
||||
}
|
||||
return Err(format!(
|
||||
"{} is missing (looked in {} and {})",
|
||||
name,
|
||||
src_dir.display(),
|
||||
dst_dir.display()
|
||||
));
|
||||
}
|
||||
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);
|
||||
}
|
||||
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}"))?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
@@ -153,29 +153,12 @@ pub async fn wait_ready(ctx: &Context, scope: Option<UnitScopeTag>) -> Result<()
|
||||
.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)));
|
||||
}
|
||||
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 +173,41 @@ pub async fn wait_ready(ctx: &Context, scope: Option<UnitScopeTag>) -> Result<()
|
||||
}
|
||||
}
|
||||
|
||||
/// 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"] {
|
||||
|
||||
@@ -180,35 +180,11 @@ pub async fn gather_fs(ctx: &Context) -> FsState {
|
||||
let model_files: Vec<PathBuf> = vec![paths.shard(0), paths.shard(1)];
|
||||
let kar_files: Vec<PathBuf> = 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
|
||||
}
|
||||
|
||||
@@ -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<Result<(), Flow>> {
|
||||
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,
|
||||
|
||||
@@ -24,15 +24,13 @@ impl Supervisor {
|
||||
kar_fd: Option<u32>,
|
||||
) -> Result<Option<File>, Flow> {
|
||||
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
|
||||
),
|
||||
);
|
||||
}
|
||||
(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("kar_source none: no KAR archive; the PLE rows are read from the GGUF shard (qwen4exp-native-mtp-v1)");
|
||||
Ok(None)
|
||||
|
||||
@@ -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<String, String>,
|
||||
stdin: Option<File>,
|
||||
) -> Result<Child, Flow> {
|
||||
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),
|
||||
};
|
||||
@@ -95,6 +99,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.
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,33 +3,58 @@
|
||||
use super::*;
|
||||
|
||||
pub(super) fn spawn_signal_task(stop: watch::Sender<bool>, 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<bool>, 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<impl std::future::Future<Output = 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<bool>) {
|
||||
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<bool>, run_dir: PathBuf) {
|
||||
}
|
||||
let _ = stop.send(true);
|
||||
});
|
||||
#[cfg(not(any(unix, windows)))]
|
||||
drop(stop);
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
|
||||
@@ -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],
|
||||
|
||||
+53
-22
@@ -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,50 @@ 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<String, String> {
|
||||
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("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");
|
||||
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<String, String> {
|
||||
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 +121,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(
|
||||
|
||||
@@ -103,43 +103,52 @@ 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<f64>,
|
||||
) -> 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(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,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,27 +5,12 @@ 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<Value> = 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,
|
||||
@@ -41,8 +26,43 @@ pub(super) async fn status(args: &[String]) -> i32 {
|
||||
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,
|
||||
)
|
||||
}
|
||||
|
||||
/// 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<Value> {
|
||||
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<crate::expert_profile::TierReport> {
|
||||
session
|
||||
.bridge
|
||||
.read_file(&format!("{state_dir}/leleka.json"))
|
||||
.and_then(|text| serde_json::from_str::<crate::config::RunConfig>(&text).ok())
|
||||
@@ -62,17 +82,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 +105,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 +122,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 +141,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<Value> = 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;
|
||||
};
|
||||
@@ -167,10 +162,51 @@ pub(super) async fn down(args: &[String]) -> i32 {
|
||||
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<i32> {
|
||||
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<u64> {
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -56,32 +56,16 @@ pub async fn dispatch(args: &[String]) -> Option<i32> {
|
||||
}
|
||||
};
|
||||
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.
|
||||
@@ -98,6 +82,43 @@ pub async fn dispatch(args: &[String]) -> Option<i32> {
|
||||
Some(wsl_route(&command, &args[1..]).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?
|
||||
pub(super) fn native_prepared() -> bool {
|
||||
let var = |name: &str| std::env::var(name).ok().filter(|v| !v.is_empty());
|
||||
@@ -129,18 +150,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, "<distribution>", &crate::winservice::current_user());
|
||||
println!(
|
||||
"--dry-run: nothing is changed. In the distribution: `systemctl --user enable {}`; on Windows: `schtasks /Create /TN {} /XML <file> /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 +159,49 @@ 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<Session, String> {
|
||||
let wsl = wsl_exe().ok_or("wsl.exe was not found")?;
|
||||
let saved = BridgeState::read(&local_app_data());
|
||||
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, "<distribution>", &crate::winservice::current_user());
|
||||
println!(
|
||||
"--dry-run: nothing is changed. In the distribution: `systemctl --user enable {}`; on Windows: `schtasks /Create /TN {} /XML <file> /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<String> {
|
||||
// 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 +218,16 @@ pub(super) fn open_session(args: &[String], start: bool) -> Result<Session, Stri
|
||||
}
|
||||
}
|
||||
if requested.is_none() {
|
||||
requested = saved.as_ref().map(|s| s.distro.clone());
|
||||
requested = saved.map(|s| s.distro.clone());
|
||||
}
|
||||
requested
|
||||
}
|
||||
|
||||
/// 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<Session, String> {
|
||||
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
|
||||
|
||||
@@ -58,96 +58,177 @@ 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<i32> {
|
||||
let assets = session.forwarded.assets.as_ref()?;
|
||||
if !is_drvfs(assets) {
|
||||
return None;
|
||||
}
|
||||
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
|
||||
));
|
||||
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<String, String> {
|
||||
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 dry_run = args.iter().any(|a| a == "--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::of(command, args, json),
|
||||
session,
|
||||
(&state_dir, &api),
|
||||
)
|
||||
}
|
||||
|
||||
fn spawn_linux(
|
||||
session: &Session,
|
||||
command: &str,
|
||||
binary: &str,
|
||||
) -> std::io::Result<tokio::process::Child> {
|
||||
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<std::process::ExitStatus> {
|
||||
let mut interrupts = 0;
|
||||
let status = loop {
|
||||
loop {
|
||||
tokio::select! {
|
||||
status = child.wait() => break status,
|
||||
_ = tokio::signal::ctrl_c() => {
|
||||
@@ -159,22 +240,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<std::process::ExitStatus>,
|
||||
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)
|
||||
}
|
||||
|
||||
@@ -52,19 +52,7 @@ pub fn parse_distro_list(text: &str) -> Vec<Distro> {
|
||||
/// 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<String, String> {
|
||||
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::<Vec<_>>()
|
||||
.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<String, S
|
||||
})
|
||||
}
|
||||
|
||||
fn named_distro(list: &[Distro], name: &str) -> Result<String, String> {
|
||||
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::<Vec<_>>()
|
||||
.join(", ")
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------------------------
|
||||
// paths
|
||||
|
||||
@@ -93,33 +96,10 @@ pub fn pick_distro(list: &[Distro], requested: Option<&str>) -> Result<String, S
|
||||
pub fn to_wsl_path(path: &str, distro: &str, home: Option<&str>) -> Result<String, String> {
|
||||
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,42 @@ pub fn to_wsl_path(path: &str, distro: &str, home: Option<&str>) -> Result<Strin
|
||||
))
|
||||
}
|
||||
|
||||
/// `\\wsl.localhost\Ubuntu\home\me\x` (`rest` is what follows the two slashes) in the distribution in use; any other share is refused.
|
||||
fn unc_to_wsl(path: &str, rest: &str, distro: &str) -> Result<String, String> {
|
||||
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<String> {
|
||||
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());
|
||||
@@ -169,12 +185,7 @@ pub fn translate_args(
|
||||
}
|
||||
_ => (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 {
|
||||
if !takes_value(&name) {
|
||||
out.args.push(arg.clone());
|
||||
index += 1;
|
||||
continue;
|
||||
@@ -189,38 +200,59 @@ 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)
|
||||
}
|
||||
|
||||
/// 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" => {
|
||||
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]);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `40GB`, `40G`, `49152MB`, `40 GB`, plain bytes.
|
||||
pub fn parse_size(text: &str) -> Option<u64> {
|
||||
let text = text.trim().trim_matches('"').to_ascii_lowercase();
|
||||
|
||||
Reference in New Issue
Block a user