STRA-338 size-fn: leleka-deploy: further helpers for the functions still above 30 lines

This commit is contained in:
Pavlo Ratushnyi
2026-11-06 17:35:39 +01:00
parent 28cd67752c
commit cdf963ea4a
31 changed files with 767 additions and 467 deletions
+19 -5
View File
@@ -18,9 +18,7 @@ pub async fn up(opts: UpOptions) -> i32 {
}
let fs = gather_fs(&ctx).await;
let steps = plan_steps(&ctx, &fs);
let blocked = steps
.iter()
.any(|s| matches!(s.state, StepState::Blocked(_)) && s.id != "preflight");
let blocked = has_blocked_step(&steps);
if opts.dry_run {
print_dry_run(&ctx, &steps);
return i32::from(report.failed() || blocked);
@@ -32,7 +30,18 @@ pub async fn up(opts: UpOptions) -> i32 {
return 1;
}
eprint!("{}", render_plan(&ctx, &steps));
match run_up(&ctx, &steps).await {
finish_up(run_up(&ctx, &steps).await)
}
/// A step other than the preflight that cannot run.
fn has_blocked_step(steps: &[Step]) -> bool {
steps
.iter()
.any(|s| matches!(s.state, StepState::Blocked(_)) && s.id != "preflight")
}
fn finish_up(result: Result<i32, String>) -> i32 {
match result {
Ok(code) => code,
Err(message) => {
eprintln!("leleka: {message}");
@@ -109,6 +118,11 @@ async fn run_foreground(ctx: &Context, config: &crate::config::RunConfig) -> Res
ctx.opts.dirs.state.display()
));
}
Ok(serve_until_exit(ctx, config).await)
}
/// The supervisor runs here; its exit code ends the call, and the summary is printed once the service answers.
async fn serve_until_exit(ctx: &Context, config: &crate::config::RunConfig) -> i32 {
let options = supervisor::Options {
config: ctx.paths.run_config(),
kar_fd: ctx.opts.kar_fd,
@@ -118,7 +132,7 @@ async fn run_foreground(ctx: &Context, config: &crate::config::RunConfig) -> Res
let mut printed = false;
loop {
tokio::select! {
code = &mut run => return Ok(code),
code = &mut run => return code,
ready = steps::wait_ready(ctx, None), if !printed => {
printed = true;
match ready {
+38 -22
View File
@@ -47,14 +47,7 @@ pub async fn send_reconfigure(
eprintln!(
"leleka: reconfiguring {settings}; the engine reopens its serve stack (tens of seconds, requests wait meanwhile)"
);
let response = crate::http::post_json(
address,
"/v1/reconfigure",
Some(key),
settings,
std::time::Duration::from_secs(1900),
)
.await;
let response = post_settings(address, key, settings).await;
match response {
Ok(response) => {
let persisted = match &persist {
@@ -73,6 +66,21 @@ pub async fn send_reconfigure(
}
}
async fn post_settings(
address: std::net::SocketAddr,
key: &str,
settings: &str,
) -> Result<crate::http::Response, String> {
crate::http::post_json(
address,
"/v1/reconfigure",
Some(key),
settings,
std::time::Duration::from_secs(1900),
)
.await
}
/// The answer of the gateway: the JSON document with `persisted` added, or the settings in force, or why it was refused.
fn print_reconfigure_answer(
response: &crate::http::Response,
@@ -92,13 +100,7 @@ fn print_reconfigure_answer(
} else if response.status == 200 {
println!("reconfigured; the engine runs with:");
print!("{}", render_settings(&document["settings"]));
match persisted {
Some(Ok(note)) => println!("persisted: {note}"),
Some(Err(why)) => eprintln!(
"leleka: the engine runs with the new settings, but they were not persisted: {why}"
),
None => {}
}
print_persisted(persisted);
} else {
let message = document["error"]["message"]
.as_str()
@@ -110,6 +112,16 @@ fn print_reconfigure_answer(
}
}
fn print_persisted(persisted: Option<&Result<String, String>>) {
match persisted {
Some(Ok(note)) => println!("persisted: {note}"),
Some(Err(why)) => eprintln!(
"leleka: the engine runs with the new settings, but they were not persisted: {why}"
),
None => {}
}
}
/// `--persist` after a runtime change: the supervisor records it in the configuration it holds (so that a restart of the engine
/// keeps it) and writes the file; with no supervisor the file is edited directly.
pub(super) async fn persist_settings(
@@ -191,13 +203,7 @@ pub(super) async fn reconfigure_by_restart(
}
let load_timeout = crate::config::RunConfig::read(&paths.run_config())
.map_or(1800, |config| config.load_timeout_s);
let request = crate::reconfigure::Request {
id: crate::reconfigure::new_request_id(),
gpu_budget_gib: args.gpu_budget_gib,
preset: args.preset,
settings: args.settings.clone(),
persist: args.persist,
};
let request = restart_request(args);
eprintln!(
"leleka: asking the supervisor to restart the engine with the new settings (the model loads again; the gateway and the API keep their ports)"
);
@@ -212,6 +218,16 @@ pub(super) async fn reconfigure_by_restart(
}
}
fn restart_request(args: &ReconfigureArgs) -> crate::reconfigure::Request {
crate::reconfigure::Request {
id: crate::reconfigure::new_request_id(),
gpu_budget_gib: args.gpu_budget_gib,
preset: args.preset,
settings: args.settings.clone(),
persist: args.persist,
}
}
fn print_restart_outcome(outcome: &crate::reconfigure::Outcome, json: bool) -> i32 {
let done = outcome.state == crate::reconfigure::State::Done;
if json {
+22 -15
View File
@@ -72,19 +72,14 @@ pub fn print_status(
run_dir: &str,
requests: Option<&str>,
) -> i32 {
let machine = gateway
.map(|g| g["machine"].clone())
.filter(Value::is_object);
let machine = machine_of(gateway);
if json {
let unit_state = unit.as_ref().map(|(_, state)| state);
let prefix_cache = gateway.map(|g| g["prefix_cache"].clone());
let document = json!({"ready": ready, "unit": unit.as_ref().map(|(_, state)| state),
"supervisor": supervisor, "machine": machine, "prefix_cache": gateway.map(|g| g["prefix_cache"].clone()),
"expert_tier": expert_tier, "requests": requests});
println!(
"{}",
serde_json::to_string_pretty(
&json!({"ready": ready, "unit": unit_state, "supervisor": supervisor, "machine": machine,
"prefix_cache": prefix_cache, "expert_tier": expert_tier, "requests": requests})
)
.expect("serializable")
serde_json::to_string_pretty(&document).expect("serializable")
);
} else {
println!("ready: {ready}");
@@ -92,15 +87,27 @@ pub fn print_status(
println!("systemd unit {name}: {state}");
}
print_status_text(supervisor, expert_tier, run_dir, requests);
if let Some(machine) = &machine {
print!("{}", render_machine(machine));
} else if ready {
println!("engine load: the engine reports no telemetry yet");
}
print_machine(machine.as_ref(), ready);
}
i32::from(!ready)
}
/// The engine telemetry block of the gateway status, when it has one.
fn machine_of(gateway: Option<&Value>) -> Option<Value> {
gateway
.map(|g| g["machine"].clone())
.filter(Value::is_object)
}
/// The telemetry of the engine, or why there is none.
fn print_machine(machine: Option<&Value>, ready: bool) {
if let Some(machine) = machine {
print!("{}", render_machine(machine));
} else if ready {
println!("engine load: the engine reports no telemetry yet");
}
}
/// The supervisor document, the expert tier and the request line of the text form.
fn print_status_text(
supervisor: Option<Value>,
+27 -18
View File
@@ -37,26 +37,16 @@ pub(super) async fn verify(opts: UpOptions) -> i32 {
return verify_quick(&opts).await;
}
let paths = opts.dirs.paths();
let config = match read_run_config(&paths) {
Ok(config) => config,
let (config, stamp_dir, token) = match verify_inputs(&paths) {
Ok(inputs) => inputs,
Err(code) => return code,
};
let stamp_dir = match prepare_stamp_dir(&paths) {
Ok(dir) => dir,
Err(code) => return code,
};
let token = match runtime_token(&paths) {
Ok(token) => token,
Err(code) => return code,
};
// The expert tier's table is 192 KiB: checked first, loudly, because losing it is a silent large slowdown.
let tier = crate::expert_profile::tier_report(&config, &paths.dirs.assets);
say(&tier.line());
let tier_failed = !tier.on && !tier.opted_out && config.profile.expert_profile.is_some();
let tier_failed = tier_has_failed(&config, &paths);
let started = std::time::Instant::now();
say(
"hashing both shards (and the archive, when it is a file) in full, in parallel; this renews the stamps",
);
say(concat!(
"hashing both shards (and the archive, when it is a file) in full, in parallel; ",
"this renews the stamps"
));
let engine = run_engine_verification(&paths, &config, token);
let archive = hash_archive_file(&paths, &config, stamp_dir);
let (engine, archive) = tokio::join!(engine, archive);
@@ -67,12 +57,31 @@ pub(super) async fn verify(opts: UpOptions) -> i32 {
);
code = 1;
}
say_verdict(code, started);
code
}
fn say_verdict(code: i32, started: std::time::Instant) {
say(&format!(
"verification {} in {:.1}s",
if code == 0 { "passed" } else { "FAILED" },
started.elapsed().as_secs_f32()
));
code
}
/// The configuration, the stamp directory and the token the verification needs, or the exit code of the refusal.
fn verify_inputs(paths: &Paths) -> Result<(RunConfig, PathBuf, String), i32> {
let config = read_run_config(paths)?;
let stamp_dir = prepare_stamp_dir(paths)?;
let token = runtime_token(paths)?;
Ok((config, stamp_dir, token))
}
/// The expert tier's table is 192 KiB: checked first, loudly, because losing it is a silent large slowdown.
fn tier_has_failed(config: &RunConfig, paths: &Paths) -> bool {
let tier = crate::expert_profile::tier_report(config, &paths.dirs.assets);
say(&tier.line());
!tier.on && !tier.opted_out && config.profile.expert_profile.is_some()
}
fn prepare_stamp_dir(paths: &Paths) -> Result<PathBuf, i32> {
@@ -24,12 +24,7 @@ pub(super) fn engine(fake: &Path, args: &[String]) {
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()
);
announce_listening(fake, &listen);
if fake.join("fail-load").exists() {
// The real engine reports a failed load on its own stderr and stays up.
eprintln!("leleka-load phase=OriginalStack class=BackendUnavailable");
@@ -40,6 +35,15 @@ pub(super) fn engine(fake: &Path, args: &[String]) {
}
}
fn announce_listening(fake: &Path, listen: &str) {
let _ = fs::remove_file(fake.join("loaded"));
let _ = fs::write(fake.join("engine.pid"), std::process::id().to_string());
eprintln!(
"fake engine: listening on {listen} pid {}",
std::process::id()
);
}
/// `--verify-only`: the load-time source verification, no listener, no model.
fn verify_only(fake: &Path) {
if fake.join("fail-verify").exists() {
@@ -6,10 +6,7 @@ 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] => init_api_key(file),
["model", "fetch", _, "--output", dir] => {
fetch_shards(dir);
println!("fetched");
}
["model", "fetch", _, "--output", dir] => fetch_and_say(dir),
["model", "verify", _, "--output", _] => println!("verified"),
[
"model",
@@ -22,11 +19,7 @@ pub(super) fn strata(fake: &Path, args: &[String]) {
"--levels",
"2",
] => 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"), "{}")
.expect("tokenizer file");
}
["model", "extract-tokenizer", _, "--output", dir] => extract_tokenizer(dir),
["serve", "--config", config] => api(fake, config),
other => {
eprintln!("fake strata-next: unsupported {other:?}");
@@ -35,6 +28,16 @@ pub(super) fn strata(fake: &Path, args: &[String]) {
}
}
fn fetch_and_say(dir: &str) {
fetch_shards(dir);
println!("fetched");
}
fn extract_tokenizer(dir: &str) {
fs::create_dir_all(Path::new(dir).join("tokenizer")).expect("tokenizer dir");
fs::write(Path::new(dir).join("tokenizer/tokenizer.json"), "{}").expect("tokenizer file");
}
fn init_api_key(file: &str) {
if !Path::new(file).exists() {
let key = "fake-api-key-0123456789abcdef0123456789abcdef";
@@ -151,29 +154,44 @@ fn answer(request: &str, path: &str, fake: &Path, state: (bool, bool)) -> (&'sta
"401 Unauthorized",
"{\"error\":\"unauthorized\"}".to_owned(),
),
"/ready" if ready => (
"200 OK",
"{\"service\":\"strata-control\",\"ready\":true}".to_owned(),
),
"/ready" => (
"503 Service Unavailable",
"{\"service\":\"strata-control\",\"ready\":false}".to_owned(),
),
"/ready" => ready_answer(ready),
"/metrics" => metrics_answer(fake, ready),
"/v1/status" if ready => (
"200 OK",
"{\"loaded\":true,\"machine\":{\"phase\":\"idle\",\"gpu\":null,\"cpu\":null,\"ram\":null,\"throughput\":{},\"cache\":{},\"context\":{\"live_tokens\":0,\"max_tokens\":8192}},\"prefix_cache\":null}".to_owned(),
),
// `POST /v1/reconfigure`: accept and echo the settings the way the real gateway answers.
"/v1/reconfigure" if request.starts_with("POST") && ready => {
let body = request.split("\r\n\r\n").nth(1).unwrap_or("{}");
let settings: serde_json::Value = serde_json::from_str(body).unwrap_or_default();
("200 OK", serde_json::json!({"settings": settings}).to_string())
}
"/v1/reconfigure" => reconfigure_answer(request, ready),
_ => ("404 Not Found", "{}".to_owned()),
}
}
fn ready_answer(ready: bool) -> (&'static str, String) {
if ready {
(
"200 OK",
"{\"service\":\"strata-control\",\"ready\":true}".to_owned(),
)
} else {
(
"503 Service Unavailable",
"{\"service\":\"strata-control\",\"ready\":false}".to_owned(),
)
}
}
/// `POST /v1/reconfigure`: accept and echo the settings the way the real gateway answers.
fn reconfigure_answer(request: &str, ready: bool) -> (&'static str, String) {
if !(request.starts_with("POST") && ready) {
return ("404 Not Found", "{}".to_owned());
}
let body = request.split("\r\n\r\n").nth(1).unwrap_or("{}");
let settings: serde_json::Value = serde_json::from_str(body).unwrap_or_default();
(
"200 OK",
serde_json::json!({"settings": settings}).to_string(),
)
}
/// The control plane's own view: the worker state and the request that is active (a switch file makes one stay active).
/// One-shot: the next answer after it is a healthy one (the restarted engine is not hung).
fn metrics_answer(fake: &Path, ready: bool) -> (&'static str, String) {
+13 -8
View File
@@ -23,14 +23,7 @@ fn main() {
.trim_end_matches(".exe")
.to_owned();
let args: Vec<String> = args.collect();
let bin_dir = Path::new(&invoked)
.parent()
.map(Path::to_path_buf)
.unwrap_or_default();
let fake = bin_dir
.parent()
.map(|p| p.join("fake"))
.unwrap_or_else(|| PathBuf::from("fake"));
let fake = fake_dir(&invoked);
let _ = fs::create_dir_all(&fake);
log_call(&fake, &name, &args);
match name.as_str() {
@@ -45,6 +38,18 @@ fn main() {
}
}
/// `PREFIX/fake`, found from the invocation path `PREFIX/bin/NAME`.
fn fake_dir(invoked: &str) -> PathBuf {
let bin_dir = Path::new(invoked)
.parent()
.map(Path::to_path_buf)
.unwrap_or_default();
bin_dir
.parent()
.map(|p| p.join("fake"))
.unwrap_or_else(|| PathBuf::from("fake"))
}
fn log_call(fake: &Path, name: &str, args: &[String]) {
// Tokens never appear on a command line; the log is for call counting.
if let Ok(mut file) = fs::OpenOptions::new()
+16 -10
View File
@@ -136,16 +136,7 @@ pub(super) fn up_options(args: &[String], env: &Environment) -> Result<UpOptions
let kar_fd = up_kar_fd(&flags, mode)?;
check_mode_for_host(mode, env)?;
let ports = up_ports(&flags)?;
let cublas_dir = text(&flags, "--cublas-dir").map(PathBuf::from);
if let Some(dir) = &cublas_dir
&& !is_absolute(dir)
{
return Err("--cublas-dir must be an absolute path".into());
}
let expert_profile_file = text(&flags, "--expert-profile-file").map(PathBuf::from);
if expert_profile_file.is_some() && flags.contains_key("--no-expert-tier") {
return Err("--expert-profile-file and --no-expert-tier contradict each other".into());
}
let (cublas_dir, expert_profile_file) = up_files(&flags)?;
let numbers = UpNumbers::read(&flags, env)?;
let chosen = Chosen {
dirs,
@@ -158,6 +149,21 @@ pub(super) fn up_options(args: &[String], env: &Environment) -> Result<UpOptions
Ok(assemble_up_options(&flags, chosen, numbers))
}
/// `--cublas-dir` (absolute) and `--expert-profile-file` (not together with `--no-expert-tier`).
fn up_files(flags: &Flags) -> Result<(Option<PathBuf>, Option<PathBuf>), String> {
let cublas_dir = text(flags, "--cublas-dir").map(PathBuf::from);
if let Some(dir) = &cublas_dir
&& !is_absolute(dir)
{
return Err("--cublas-dir must be an absolute path".into());
}
let expert_profile_file = text(flags, "--expert-profile-file").map(PathBuf::from);
if expert_profile_file.is_some() && flags.contains_key("--no-expert-tier") {
return Err("--expert-profile-file and --no-expert-tier contradict each other".into());
}
Ok((cublas_dir, expert_profile_file))
}
/// The options of `up` that are checked against the host or each other.
struct Chosen {
dirs: Dirs,
+2 -8
View File
@@ -177,16 +177,10 @@ pub enum KarArg {
}
/// The environment variables the engine is started with.
type EngineEnv = BTreeMap<String, String>;
type Env = BTreeMap<String, String>;
impl RunConfig {
pub fn new(
dirs: &Dirs,
ports: Ports,
gpu: u32,
profile: Profile,
engine_env: EngineEnv,
) -> Self {
pub fn new(dirs: &Dirs, ports: Ports, gpu: u32, profile: Profile, engine_env: Env) -> Self {
RunConfig {
schema_version: SCHEMA_VERSION,
leleka_version: env!("CARGO_PKG_VERSION").to_owned(),
+24 -14
View File
@@ -49,22 +49,11 @@ pub(super) fn print_entries(entries: &[Entry], raw: bool) {
}
pub fn run_logs(opts: &UpOptions, args: &LogsArgs) -> i32 {
let dir = opts.dirs.paths().logs();
let now = now_ms();
let filter = match filter_from(args, now) {
Ok(filter) => filter,
Err(message) => {
eprintln!("leleka: {message}");
return 2;
}
let (dir, filter) = match log_directory_and_filter(opts, args, now) {
Ok(found) => found,
Err(code) => return code,
};
if !dir.is_dir() {
eprintln!(
"leleka: no log directory {} (the service has not run with this --state-dir)",
dir.display()
);
return 1;
}
let entries = collect(&dir, &filter);
if args.request.is_some() {
return show_request(&entries, opts.json);
@@ -84,6 +73,27 @@ pub fn run_logs(opts: &UpOptions, args: &LogsArgs) -> i32 {
0
}
/// The log directory (it must exist) and the filter of the flags, or the exit code of the refusal.
fn log_directory_and_filter(
opts: &UpOptions,
args: &LogsArgs,
now: u64,
) -> Result<(PathBuf, Filter), i32> {
let dir = opts.dirs.paths().logs();
let filter = filter_from(args, now).map_err(|message| {
eprintln!("leleka: {message}");
2
})?;
if !dir.is_dir() {
eprintln!(
"leleka: no log directory {} (the service has not run with this --state-dir)",
dir.display()
);
return Err(1);
}
Ok((dir, filter))
}
/// The lines that mention a request, and the request as one record (the API and the engine figures joined).
fn show_request(entries: &[Entry], json: bool) -> i32 {
let joined = join_requests(entries);
+47 -26
View File
@@ -63,27 +63,15 @@ pub fn gather_report(opts: &UpOptions, last: usize) -> (ReportInputs, Option<Str
register_local_secrets(&paths);
let now = now_ms();
let config = crate::config::RunConfig::read(&paths.run_config()).ok();
let expert_tier = config.as_ref().map(|c| {
serde_json::to_value(crate::expert_profile::tier_report(c, &c.dirs().assets))
.unwrap_or(Value::Null)
});
let expert_tier = config.as_ref().map(expert_tier_value);
let service = std::fs::read_to_string(paths.status_file())
.ok()
.and_then(|t| serde_json::from_str::<Value>(&t).ok())
.map(|s| service_summary(&s, now / 1000));
let logs_dir = paths.logs();
let warnings = collect(
&logs_dir,
&Filter {
min_level: Level::Warn,
tail: 50,
..Filter::default()
},
);
let warnings = recent_warnings(&logs_dir);
let log_files = list_log_files(&logs_dir);
let home = std::env::var("HOME")
.or_else(|_| std::env::var("USERPROFILE"))
.ok();
let home = home_directory();
(
ReportInputs {
now_ms: now,
@@ -100,6 +88,30 @@ pub fn gather_report(opts: &UpOptions, last: usize) -> (ReportInputs, Option<Str
)
}
fn expert_tier_value(c: &crate::config::RunConfig) -> Value {
serde_json::to_value(crate::expert_profile::tier_report(c, &c.dirs().assets))
.unwrap_or(Value::Null)
}
/// The home directory, which the report replaces by `~`.
fn home_directory() -> Option<String> {
std::env::var("HOME")
.or_else(|_| std::env::var("USERPROFILE"))
.ok()
}
/// The newest 50 warning and error entries of the logs.
fn recent_warnings(logs_dir: &Path) -> Vec<Entry> {
collect(
logs_dir,
&Filter {
min_level: Level::Warn,
tail: 50,
..Filter::default()
},
)
}
/// The names and sizes of the files in the log directory, sorted.
fn list_log_files(logs_dir: &Path) -> Vec<(String, u64)> {
let mut log_files = Vec::new();
@@ -125,17 +137,7 @@ pub fn run_report(opts: &UpOptions, args: &ReportArgs) -> i32 {
.replace([':', '.'], "")
.replace("T", "-")
.replace('Z', "");
let destination = match args.out.as_deref() {
Some("-") => None,
Some(path) => Some(PathBuf::from(path)),
None => Some(
paths
.dirs
.state
.join("reports")
.join(format!("leleka-report-{stamp}.json")),
),
};
let destination = report_destination(args, &paths, &stamp);
if !args.yes {
print_preview(args, &inputs, &text, destination.as_deref());
return 3;
@@ -149,6 +151,25 @@ pub fn run_report(opts: &UpOptions, args: &ReportArgs) -> i32 {
}
}
/// Where the report goes: `-` is standard output, a path is a file, and the default is a stamped file in the state directory.
fn report_destination(
args: &ReportArgs,
paths: &crate::layout::Paths,
stamp: &str,
) -> Option<PathBuf> {
match args.out.as_deref() {
Some("-") => None,
Some(path) => Some(PathBuf::from(path)),
None => Some(
paths
.dirs
.state
.join("reports")
.join(format!("leleka-report-{stamp}.json")),
),
}
}
/// What a report would contain, without writing anything (the answer to a `leleka report` without `--yes`).
fn print_preview(args: &ReportArgs, inputs: &ReportInputs, text: &str, destination: Option<&Path>) {
println!("leleka report: nothing has been written or sent. A report would contain:");
+89 -39
View File
@@ -57,31 +57,17 @@ pub fn gather(opts: &UpOptions, var: &dyn Fn(&str) -> Option<String>) -> Context
let paths = opts.dirs.paths();
let bin_src = opts.bin_src.clone().unwrap_or_else(current_bin_dir);
let installed = paths.bin_dir();
// Probe the source of the binaries, or the installed copy when the source has none (re-run after install).
let binary_dir = if BINARIES.iter().all(|b| bin_src.join(b).is_file()) {
bin_src.clone()
} else {
installed.clone()
};
let binary_dir = probed_binary_dir(&bin_src, &installed);
let facts = probe(&probe_request(opts, &paths, &binary_dir));
let manifest = Manifest::find(&binary_dir);
let gpu = facts.gpus.iter().find(|g| g.index == opts.gpu);
let mut profile = tuned_profile(opts, gpu);
let mode = resolve_mode(chosen_mode(opts), &facts, user_session_available(var));
let service_user = service_user_of(opts, &mode, var);
let has_sm86 = manifest
.as_ref()
.and_then(|m| m.as_ref().ok())
.map(Manifest::has_sm86);
let has_sm86 = sm86_of(&manifest);
let installs = !same_dir(&bin_src, &installed);
let mut needs = base_needs(opts, &paths, &facts, &mode, (installs, has_sm86));
let (config, report) = match &mut profile {
Ok(p) => {
let (config, report) = configure_engine(opts, &facts, gpu, p, &mut needs);
(Some(config), Some(report))
}
Err(_) => (None, None),
};
let (config, report) = configured(opts, &facts, gpu, &mut profile, &mut needs);
Context {
opts: opts.clone(),
facts,
@@ -97,6 +83,40 @@ pub fn gather(opts: &UpOptions, var: &dyn Fn(&str) -> Option<String>) -> Context
}
}
/// Probe the source of the binaries, or the installed copy when the source has none (re-run after install).
fn probed_binary_dir(bin_src: &Path, installed: &Path) -> PathBuf {
if BINARIES.iter().all(|b| bin_src.join(b).is_file()) {
bin_src.to_path_buf()
} else {
installed.to_path_buf()
}
}
/// Does the build carry sm_86 kernels, when a manifest says?
fn sm86_of(manifest: &Option<Result<Manifest, String>>) -> Option<bool> {
manifest
.as_ref()
.and_then(|m| m.as_ref().ok())
.map(Manifest::has_sm86)
}
/// The configuration and the preflight report, when the profile is usable.
fn configured(
opts: &UpOptions,
facts: &Facts,
gpu: Option<&crate::facts::Gpu>,
profile: &mut Result<Profile, String>,
needs: &mut Needs,
) -> (Option<RunConfig>, Option<Report>) {
match profile {
Ok(p) => {
let (config, report) = configure_engine(opts, facts, gpu, p, needs);
(Some(config), Some(report))
}
Err(_) => (None, None),
}
}
fn probe_request(opts: &UpOptions, paths: &Paths, binary_dir: &Path) -> ProbeRequest {
let mut extra_library_dirs: Vec<PathBuf> = Vec::new();
if let Some(dir) = &opts.cublas_dir {
@@ -169,26 +189,24 @@ fn base_needs(
binaries: (bool, Option<bool>),
) -> Needs {
let (shards, kar) = missing_asset_bytes(paths);
// Windows never fetches or builds: the model volume is copied in (the plan blocks with the reason when it is not).
let fetches = opts.fetch && facts.os != "windows";
Needs {
gpu_index: opts.gpu,
assets_dir: opts.dirs.assets.clone(),
state_dir: opts.dirs.state.clone(),
prefix_dir: opts.dirs.prefix.clone(),
shard_bytes_missing: if fetches { shards } else { 0 },
kar_bytes_missing: if fetches { kar } else { 0 },
shard_bytes_missing: if fetches_assets(opts, facts) {
shards
} else {
0
},
kar_bytes_missing: if fetches_assets(opts, facts) { kar } else { 0 },
install_binaries: binaries.0,
may_install_cublas: opts.install_cublas
&& opts.cublas_dir.is_none()
&& facts.os != "windows",
cublas_download_bytes: CUBLAS_BYTES,
wants_systemd: matches!(mode, Mode::Systemd(_)),
service_ports: vec![
("api".into(), port_of(&opts.ports.api)),
("engine".into(), port_of(&opts.ports.engine)),
("gateway".into(), port_of(&opts.ports.daemon)),
],
service_ports: service_ports(opts),
require_binaries: true,
binary_has_sm86: binaries.1,
service_running: service_running(paths),
@@ -200,6 +218,19 @@ fn base_needs(
}
}
/// Windows never fetches or builds: the model volume is copied in (the plan blocks with the reason when it is not).
fn fetches_assets(opts: &UpOptions, facts: &Facts) -> bool {
opts.fetch && facts.os != "windows"
}
fn service_ports(opts: &UpOptions) -> Vec<(String, u16)> {
vec![
("api".into(), port_of(&opts.ports.api)),
("engine".into(), port_of(&opts.ports.engine)),
("gateway".into(), port_of(&opts.ports.daemon)),
]
}
/// With a usable profile: the resources the host leaves it, the engine environment, the configuration and the preflight report.
fn configure_engine(
opts: &UpOptions,
@@ -212,19 +243,10 @@ fn configure_engine(
if p.kar_source == KarSource::None {
needs.kar_bytes_missing = 0;
}
needs.expert_profile = if opts.no_expert_tier && p.expert_profile.is_some() {
Some(ExpertProfileState::OptedOut)
} else {
expert_profile_state(p, &opts.dirs.assets)
};
needs.expert_profile = expert_tier_need(opts, p);
let mut engine_env = BTreeMap::new();
let base_profile = p.clone();
// An inherited sealed archive is already resident: it is not part of what the engine still needs from the host.
let planned_host = if opts.kar_fd.is_some() {
crate::resources::with_resident_bytes(facts, p.memfd_bytes())
} else {
facts.clone()
};
let planned_host = host_for_planning(opts, facts, p);
let resources = crate::resources::compute(&planned_host, gpu, p, opts.preset);
crate::resources::apply(
&resources,
@@ -234,6 +256,35 @@ fn configure_engine(
);
needs.resources = Some(resources);
add_expert_tier_environment(opts, p, needs, &mut engine_env);
let config = run_config(opts, p, engine_env, base_profile);
let report = evaluate(facts, p, needs);
(config, report)
}
/// The state of the expert table, unless the operator opted out of the tier.
fn expert_tier_need(opts: &UpOptions, p: &Profile) -> Option<ExpertProfileState> {
if opts.no_expert_tier && p.expert_profile.is_some() {
Some(ExpertProfileState::OptedOut)
} else {
expert_profile_state(p, &opts.dirs.assets)
}
}
/// An inherited sealed archive is already resident: it is not part of what the engine still needs from the host.
fn host_for_planning(opts: &UpOptions, facts: &Facts, p: &Profile) -> Facts {
if opts.kar_fd.is_some() {
crate::resources::with_resident_bytes(facts, p.memfd_bytes())
} else {
facts.clone()
}
}
fn run_config(
opts: &UpOptions,
p: &Profile,
engine_env: BTreeMap<String, String>,
base_profile: Profile,
) -> RunConfig {
let mut config = RunConfig::new(
&opts.dirs,
opts.ports.clone(),
@@ -244,8 +295,7 @@ fn configure_engine(
config.preset = opts.preset;
config.expert_tier = !opts.no_expert_tier;
config.base_profile = Some(base_profile);
let report = evaluate(facts, p, needs);
(config, report)
config
}
/// The tier is configured whenever it is intended (any state but the explicit opt-out): a missing or wrong table is
+14 -14
View File
@@ -2,6 +2,11 @@
use super::*;
const SHARE_ENV: &str = "LELEKA_MEMORY_CACHE_SHARE_PERCENT";
const RETENTION_ENV: &str = "LELEKA_PREFIX_RETENTION_S";
const HEAL_ENV: &str = "LELEKA_MEMORY_HEAL";
const RESIDENT_ENV: &str = "LELEKA_ORIGINAL_SERVE_RESIDENT_BUDGET_GIB";
impl MemoryBudget {
pub fn validate(&self) -> Result<(), String> {
self.validate_prefix_cache()?;
@@ -92,26 +97,21 @@ impl MemoryBudget {
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",
text(self.cache_share_percent),
);
put(SHARE_ENV, text(self.cache_share_percent));
put("LELEKA_MEMORY_LOCK", self.lock.clone());
if self.prefix_cache_on() {
put(
"LELEKA_PREFIX_RETENTION_S",
self.prefix_retention_min
.map(|minutes| minutes.saturating_mul(60).to_string()),
);
put(RETENTION_ENV, self.retention_seconds());
}
put(
"LELEKA_MEMORY_HEAL",
HEAL_ENV,
self.heal.map(|v| if v { "1" } else { "0" }.to_owned()),
);
put(
"LELEKA_ORIGINAL_SERVE_RESIDENT_BUDGET_GIB",
text(self.resident_budget_gib),
);
put(RESIDENT_ENV, text(self.resident_budget_gib));
env
}
fn retention_seconds(&self) -> Option<String> {
self.prefix_retention_min
.map(|minutes| minutes.saturating_mul(60).to_string())
}
}
@@ -17,12 +17,7 @@ pub fn plan(
let preset = request.preset.unwrap_or(config.preset);
let base = requested_base(config, request, preset)?;
let mut profile = base.clone();
let seen = if archive_resident {
resources::with_resident_bytes(facts, profile.memfd_bytes())
} else {
facts.clone()
};
let seen = seen_host(facts, &profile, archive_resident);
let gpu = gpu_of(&seen, config.gpu).cloned();
let resources = resources::compute(&seen, gpu.as_ref(), &profile, preset);
check_resources(&resources, request, preset, archive_resident)?;
@@ -38,6 +33,29 @@ pub fn plan(
if let Some(gpu) = &gpu {
check_gpu_fits(&profile, gpu)?;
}
Ok(planned(config, (profile, base, env, preset), resources))
}
/// The host as the planner sees it: the archive memfd the supervisor holds already counts against the available RAM.
fn seen_host(facts: &Facts, profile: &Profile, archive_resident: bool) -> Facts {
if archive_resident {
resources::with_resident_bytes(facts, profile.memfd_bytes())
} else {
facts.clone()
}
}
/// The new configuration, and whether it differs from the one in force.
fn planned(
config: &RunConfig,
(profile, base, env, preset): (
Profile,
Profile,
std::collections::BTreeMap<String, String>,
Preset,
),
resources: ResourcePlan,
) -> Planned {
let mut next = config.clone();
next.profile = profile;
next.base_profile = Some(base);
@@ -46,11 +64,11 @@ pub fn plan(
let unchanged = next.profile == config.profile
&& next.preset == config.preset
&& next.engine_env == config.engine_env;
Ok(Planned {
Planned {
config: next,
resources,
unchanged,
})
}
}
/// The profile the request starts from: the recorded base (or the profile in force), with the settings and the budget applied.
+7 -5
View File
@@ -64,17 +64,19 @@ fn apply_setting(next: &mut Profile, name: &str, value: &Value) -> Result<(), St
"prefix_cache_mib" => set_prefix_cache_mib(next, value),
"prefix_cache_tail" => set_prefix_cache_tail(next, value),
"prefix_cache_block" => set_prefix_cache_block(next, value, name),
"prefix_retention_min" => {
next.memory.prefix_retention_min = Some(whole(value, name)?);
enable_prefix_cache(next);
Ok(())
}
"prefix_retention_min" => set_prefix_retention_min(next, value, name),
"cpu_workers" => set_cpu_workers(next, value, name),
"spec_min_p" => set_spec_min_p(next, value),
_ => unreachable!("checked above"),
}
}
fn set_prefix_retention_min(next: &mut Profile, value: &Value, name: &str) -> Result<(), String> {
next.memory.prefix_retention_min = Some(whole(value, name)?);
enable_prefix_cache(next);
Ok(())
}
fn set_context_tokens(next: &mut Profile, value: &Value, name: &str) -> Result<(), String> {
let tokens = whole(value, name)?;
if !(1..=262_144).contains(&tokens) {
+19 -14
View File
@@ -36,20 +36,8 @@ pub fn parse_seal_exec(args: &[String]) -> Result<SealExecPlan, String> {
while i < args.len() {
match args[i].as_str() {
"--" => break,
"--file" => {
i += 1;
file = Some(std::path::PathBuf::from(
args.get(i).filter(|v| !v.is_empty()).ok_or(usage)?,
));
}
"--expect-bytes" => {
i += 1;
expect_bytes = Some(
args.get(i)
.and_then(|v| v.parse::<u64>().ok())
.ok_or(usage)?,
);
}
"--file" => file = Some(path_value(args, &mut i)?),
"--expect-bytes" => expect_bytes = Some(bytes_value(args, &mut i)?),
"--sparse-ple" => sparse_ple = true,
_ => return Err(usage.into()),
}
@@ -64,6 +52,23 @@ pub fn parse_seal_exec(args: &[String]) -> Result<SealExecPlan, String> {
})
}
/// The value of `--file`: the next argument, which must not be empty.
fn path_value(args: &[String], i: &mut usize) -> Result<std::path::PathBuf, String> {
*i += 1;
args.get(*i)
.filter(|v| !v.is_empty())
.map(std::path::PathBuf::from)
.ok_or_else(|| SEAL_EXEC_USAGE.to_owned())
}
/// The value of `--expect-bytes`: the next argument, a number of bytes.
fn bytes_value(args: &[String], i: &mut usize) -> Result<u64, String> {
*i += 1;
args.get(*i)
.and_then(|v| v.parse::<u64>().ok())
.ok_or_else(|| SEAL_EXEC_USAGE.to_owned())
}
/// The command after the `--` at `args[i]`, which must be there and not empty.
fn seal_command(args: &[String], i: usize) -> Result<Vec<String>, String> {
let command: Vec<String> = args.get(i + 1..).unwrap_or_default().to_vec();
+10 -7
View File
@@ -116,19 +116,22 @@ fn check_extents(extents: &[Extent], total: u64) -> Result<(), String> {
Ok(())
}
fn seal_ranges(
path: &Path,
expect_bytes: Option<u64>,
extents: Option<&[Extent]>,
progress: &mut dyn FnMut(u64, u64),
) -> Result<
/// A sealed memfd, the identity of the file it was copied from and how the copy was read.
type SealedArchive = Result<
(
File,
Option<FileIdentity>,
leleka_model_format::bulk_read::Report,
),
String,
> {
>;
fn seal_ranges(
path: &Path,
expect_bytes: Option<u64>,
extents: Option<&[Extent]>,
progress: &mut dyn FnMut(u64, u64),
) -> SealedArchive {
let (source, metadata) = open_archive(path, expect_bytes)?;
let identity_before = FileIdentity::of(&metadata);
let total = metadata.len();
+32 -23
View File
@@ -83,11 +83,7 @@ pub fn provision_expert_profile(ctx: &Context) -> Result<(), String> {
.ok_or("the profile has no expert profile")?;
let dest = ctx.opts.dirs.assets.join(relative);
let expected = expected_digest(profile);
let tool = if cfg!(windows) || ctx.facts.tool("curl") {
"curl"
} else {
"wget"
};
let tool = small_download_tool(ctx);
let log = ctx.paths.logs().join("install.log");
let sources: &[&str] = if expected == crate::expert_profile::PINNED_SHA256 {
&SOURCES
@@ -109,6 +105,14 @@ pub fn provision_expert_profile(ctx: &Context) -> Result<(), String> {
Ok(())
}
fn small_download_tool(ctx: &Context) -> &'static str {
if cfg!(windows) || ctx.facts.tool("curl") {
"curl"
} else {
"wget"
}
}
fn report_provisioned(outcome: crate::expert_profile::Outcome, dest: &Path, expected: &str) {
use crate::expert_profile::Outcome;
match outcome {
@@ -151,15 +155,19 @@ pub async fn install_cublas(ctx: &Context) -> Result<(), String> {
let _ = std::fs::remove_dir_all(&staging);
std::fs::create_dir_all(&staging).map_err(|e| e.to_string())?;
unpack_cublas(&tar_path, &staging, &log).await?;
let target = paths.cublas_dir();
let _ = std::fs::remove_dir_all(&target);
std::fs::rename(staging.join("lib"), &target)
move_unpacked_cublas(&paths.cublas_dir(), &staging, &tar_path)
}
/// Replace the installed libraries by the unpacked ones and check that both are there.
fn move_unpacked_cublas(target: &Path, staging: &Path, tar_path: &Path) -> Result<(), String> {
let _ = std::fs::remove_dir_all(target);
std::fs::rename(staging.join("lib"), target)
.map_err(|e| format!("cannot move the unpacked libraries: {e}"))?;
if staging.join("LICENSE").is_file() {
let _ = std::fs::rename(staging.join("LICENSE"), target.join("LICENSE-cublas.txt"));
}
let _ = std::fs::remove_dir_all(&staging);
let _ = std::fs::remove_file(&tar_path);
let _ = std::fs::remove_dir_all(staging);
let _ = std::fs::remove_file(tar_path);
for soname in ["libcublas.so.12", "libcublasLt.so.12"] {
if !target.join(soname).exists() {
return Err(format!(
@@ -183,19 +191,7 @@ async fn download_cublas(
} else {
"wget"
};
let args: Vec<String> = if downloader == "curl" {
["-fL", "--retry", "5", "--retry-delay", "3", "-C", "-", "-o"]
.iter()
.map(|s| s.to_string())
.chain([part.display().to_string(), CUBLAS_URL.to_owned()])
.collect()
} else {
["-c", "-O"]
.iter()
.map(|s| s.to_string())
.chain([part.display().to_string(), CUBLAS_URL.to_owned()])
.collect()
};
let args = cublas_download_args(downloader, &part);
run_tool("cuBLAS download", Path::new(downloader), &args, log).await?;
let digest = sha256_file(&part).map_err(|e| format!("cannot hash the download: {e}"))?;
if digest != CUBLAS_SHA256 {
@@ -207,6 +203,19 @@ async fn download_cublas(
std::fs::rename(&part, tar_path).map_err(|e| e.to_string())
}
fn cublas_download_args(downloader: &str, part: &Path) -> Vec<String> {
let options: &[&str] = if downloader == "curl" {
&["-fL", "--retry", "5", "--retry-delay", "3", "-C", "-", "-o"]
} else {
&["-c", "-O"]
};
options
.iter()
.map(|s| s.to_string())
.chain([part.display().to_string(), CUBLAS_URL.to_owned()])
.collect()
}
/// Unpack the two libraries and the license of the archive into `staging`.
async fn unpack_cublas(tar_path: &Path, staging: &Path, log: &Path) -> Result<(), String> {
let args: Vec<String> = [
+13 -14
View File
@@ -10,13 +10,7 @@ pub async fn fetch_and_verify_model(ctx: &Context) -> Result<(), String> {
run_tool(
"model fetch",
&strata,
&[
"model".into(),
"fetch".into(),
MANIFEST.into(),
"--output".into(),
model_dir.clone(),
],
&model_args("fetch", &model_dir),
&log,
)
.await?;
@@ -24,13 +18,7 @@ pub async fn fetch_and_verify_model(ctx: &Context) -> Result<(), String> {
run_tool(
"model verify",
&strata,
&[
"model".into(),
"verify".into(),
MANIFEST.into(),
"--output".into(),
model_dir,
],
&model_args("verify", &model_dir),
&log,
)
.await?;
@@ -41,6 +29,17 @@ pub async fn fetch_and_verify_model(ctx: &Context) -> Result<(), String> {
)
}
/// `strata-next model VERB MANIFEST --output DIR`.
fn model_args(verb: &str, model_dir: &str) -> Vec<String> {
vec![
"model".into(),
verb.into(),
MANIFEST.into(),
"--output".into(),
model_dir.to_owned(),
]
}
pub async fn ensure_kar(ctx: &Context) -> Result<(), String> {
let present = std::fs::metadata(ctx.paths.kar()).is_ok_and(|m| m.len() == ARCHIVE_BYTES)
&& ctx.paths.kar_provenance().is_file();
+28 -15
View File
@@ -65,12 +65,7 @@ pub async fn run_tool(
log: &Path,
) -> Result<(), String> {
say(&format!("$ {} {}", program.display(), args.join(" ")));
let mut log_file = tokio::fs::OpenOptions::new()
.create(true)
.append(true)
.open(log)
.await
.map_err(|e| format!("cannot open {}: {e}", log.display()))?;
let mut log_file = open_install_log(log).await?;
let mut child = Command::new(program)
.args(args)
.stdin(Stdio::null())
@@ -93,6 +88,15 @@ pub async fn run_tool(
}
}
async fn open_install_log(log: &Path) -> Result<tokio::fs::File, String> {
tokio::fs::OpenOptions::new()
.create(true)
.append(true)
.open(log)
.await
.map_err(|e| format!("cannot open {}: {e}", log.display()))
}
/// Copy what the tool prints on both streams to standard error and the log, until both are closed.
async fn forward_both(
mut stdout: tokio::process::ChildStdout,
@@ -179,12 +183,7 @@ fn install_binary(
if dst.is_file() {
return Ok(false);
}
return Err(format!(
"{} is missing (looked in {} and {})",
name,
src_dir.display(),
dst_dir.display()
));
return Err(missing_binary(name, src_dir, dst_dir));
}
let digest = sha256_file(&src).map_err(|e| format!("cannot read {}: {e}", src.display()))?;
if let Some(expected) = manifest.and_then(|m| m.binaries.get(name))
@@ -198,8 +197,23 @@ fn install_binary(
if dst.is_file() && sha256_file(&dst).ok().as_deref() == Some(digest.as_str()) {
return Ok(false);
}
copy_into_place(name, &src, &dst, dst_dir)?;
Ok(true)
}
fn missing_binary(name: &str, src_dir: &Path, dst_dir: &Path) -> String {
format!(
"{} is missing (looked in {} and {})",
name,
src_dir.display(),
dst_dir.display()
)
}
/// Copy `src` to a temporary name next to `dst`, make it executable and rename it over `dst`.
fn copy_into_place(name: &str, src: &Path, dst: &Path, dst_dir: &Path) -> Result<(), String> {
let tmp = dst_dir.join(format!(".{name}.new"));
std::fs::copy(&src, &tmp).map_err(|e| format!("cannot copy {name}: {e}"))?;
std::fs::copy(src, &tmp).map_err(|e| format!("cannot copy {name}: {e}"))?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
@@ -207,6 +221,5 @@ fn install_binary(
.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)
std::fs::rename(&tmp, dst).map_err(|e| format!("cannot install {name}: {e}"))
}
+15 -9
View File
@@ -144,15 +144,7 @@ pub async fn wait_ready(ctx: &Context, scope: Option<UnitScopeTag>) -> Result<()
if probe_ready(ctx).await {
return Ok(());
}
let status: Option<serde_json::Value> = std::fs::read_to_string(ctx.paths.status_file())
.ok()
.and_then(|t| serde_json::from_str(&t).ok());
let phase = status
.as_ref()
.and_then(|s| s.get("phase"))
.and_then(|v| v.as_str())
.unwrap_or("not started")
.to_owned();
let (status, phase) = supervisor_phase(ctx);
check_not_failed(ctx, status.as_ref(), &phase)?;
if let Some(scope) = scope {
check_unit_not_failed(ctx, scope).await?;
@@ -173,6 +165,20 @@ pub async fn wait_ready(ctx: &Context, scope: Option<UnitScopeTag>) -> Result<()
}
}
/// The status document of the supervisor and its phase (`not started` without one).
fn supervisor_phase(ctx: &Context) -> (Option<serde_json::Value>, String) {
let status: Option<serde_json::Value> = std::fs::read_to_string(ctx.paths.status_file())
.ok()
.and_then(|t| serde_json::from_str(&t).ok());
let phase = status
.as_ref()
.and_then(|s| s.get("phase"))
.and_then(|v| v.as_str())
.unwrap_or("not started")
.to_owned();
(status, phase)
}
/// The supervisor says it failed: end the wait with its message and the log tail.
fn check_not_failed(
ctx: &Context,
+1 -4
View File
@@ -85,10 +85,7 @@ impl Supervisor {
.stdout(Stdio::from(out))
.stderr(Stdio::from(err))
.kill_on_drop(true);
command.stdin(match stdin {
Some(file) => Stdio::from(file),
None => Stdio::null(),
});
command.stdin(stdin.map_or_else(Stdio::null, Stdio::from));
self.child_env(&mut command, extra);
match command.spawn() {
Ok(child) => Ok(child),
+31 -20
View File
@@ -190,12 +190,7 @@ impl Supervisor {
ready_since: &mut Instant,
reason: String,
) -> Result<(), Flow> {
self.pids[0] = None;
self.restarts_total += 1;
self.last_restart = Some((unix_now(), reason.clone()));
if ready_since.elapsed() >= Duration::from_secs(self.config.restart.stable_after_s) {
self.engine_restarts = 0;
}
self.begin_recovery(ready_since, &reason);
loop {
self.check_restart_budget(&reason)?;
self.engine_restarts += 1;
@@ -204,20 +199,36 @@ impl Supervisor {
if !self.pause(wait).await {
return Err(Flow::Stopped);
}
match self.start_engine(gateway).await {
Ok(child) => {
*engine = child;
self.set_phase(Phase::Ready, "ready (engine restarted)");
*ready_since = Instant::now();
return Ok(());
}
Err(Flow::Stopped) => return Err(Flow::Stopped),
Err(Flow::Fatal(failure)) => {
self.log.line(&format!(
"the engine did not come back: {}",
failure.message
));
}
if let Some(child) = self.try_start_engine(gateway).await? {
*engine = child;
self.set_phase(Phase::Ready, "ready (engine restarted)");
*ready_since = Instant::now();
return Ok(());
}
}
}
/// The engine is gone: count the restart, and forget the attempts in a row when the service was stable.
fn begin_recovery(&mut self, ready_since: &Instant, reason: &str) {
self.pids[0] = None;
self.restarts_total += 1;
self.last_restart = Some((unix_now(), reason.to_owned()));
if ready_since.elapsed() >= Duration::from_secs(self.config.restart.stable_after_s) {
self.engine_restarts = 0;
}
}
/// One start: the engine, or `None` after a failure that is logged (the next attempt follows); a stop ends it.
async fn try_start_engine(&mut self, gateway: &mut Child) -> Result<Option<Child>, Flow> {
match self.start_engine(gateway).await {
Ok(child) => Ok(Some(child)),
Err(Flow::Stopped) => Err(Flow::Stopped),
Err(Flow::Fatal(failure)) => {
self.log.line(&format!(
"the engine did not come back: {}",
failure.message
));
Ok(None)
}
}
}
@@ -18,16 +18,7 @@ impl Supervisor {
gateway: &mut Child,
api: &mut Child,
) -> Result<(), Flow> {
let id = request.id.clone();
self.log.line(&format!(
"reconfigure {id}: budget {:?} GiB, preset {:?}, settings {}, persist {}",
request.gpu_budget_gib,
request.preset.map(|p| p.as_str()),
serde_json::Value::Object(request.settings.clone()),
request.persist
));
if !request.needs_restart() {
self.record_settings_only(&request);
if self.settings_only(&request) {
return Ok(());
}
let resident = self.archive.is_some();
@@ -37,22 +28,41 @@ impl Supervisor {
self.stop_engine_for(&request, engine).await;
let verdict = self.plan_on_stopped_host(&request, resident).await?;
let previous = self.config.clone();
let refusal = match verdict {
let failure = match verdict {
Ok(planned) => {
let started = self
.start_reconfigured(planned.config, &request, &previous, (engine, gateway, api))
.await?;
match started {
None => return Ok(()),
Some(failed) => failed,
}
self.start_reconfigured(planned.config, &request, &previous, (engine, gateway, api))
.await?
}
Err(why) => why,
Err(why) => Some(why),
};
let Some(refusal) = failure else {
return Ok(());
};
self.restore_previous(previous, &request, refusal, engine, gateway)
.await
}
/// Log the request; a request without a budget or preset change is recorded and done. True when it was.
fn settings_only(&mut self, request: &reconfigure::Request) -> bool {
self.log_request(request);
if request.needs_restart() {
return false;
}
self.record_settings_only(request);
true
}
fn log_request(&self, request: &reconfigure::Request) {
self.log.line(&format!(
"reconfigure {}: budget {:?} GiB, preset {:?}, settings {}, persist {}",
request.id,
request.gpu_budget_gib,
request.preset.map(|p| p.as_str()),
serde_json::Value::Object(request.settings.clone()),
request.persist
));
}
/// Settings alone: only the configuration in force changes (and the file, when asked).
fn record_settings_only(&mut self, request: &reconfigure::Request) {
let id = &request.id;
@@ -86,13 +96,7 @@ impl Supervisor {
/// The first planning, without disturbing the service. True when the request was answered (refused or already in force).
fn refused_before_stopping(&mut self, request: &reconfigure::Request, resident: bool) -> bool {
let id = &request.id;
let facts = self.host_facts();
match reconfigure::plan(
&self.config,
request,
&reconfigure::optimistic(&facts),
resident,
) {
match self.plan_on_optimistic_host(request, resident) {
Err(why) => {
self.log.line(&format!(
"reconfigure {id} refused before any change: {why}"
@@ -118,6 +122,21 @@ impl Supervisor {
}
}
/// The plan against what the host would offer once the engine is stopped.
fn plan_on_optimistic_host(
&self,
request: &reconfigure::Request,
resident: bool,
) -> Result<reconfigure::Planned, String> {
let facts = self.host_facts();
reconfigure::plan(
&self.config,
request,
&reconfigure::optimistic(&facts),
resident,
)
}
async fn stop_engine_for(&mut self, request: &reconfigure::Request, engine: &mut Child) {
self.answer(
&request.id,
@@ -172,21 +191,7 @@ impl Supervisor {
match self.start_engine(gateway).await {
Ok(child) => {
*engine = child;
let (persisted, note) = self.persist_note(request.persist);
// the API advertises the context of strata.json: follow it
if persisted
&& self.config.profile.context_tokens != previous.profile.context_tokens
{
self.restart_api(api).await?;
}
self.set_phase(Phase::Ready, "ready (engine reconfigured)");
self.log.line("reconfigure: done");
self.answer(
&request.id,
reconfigure::State::Done,
format!("the engine runs with the new settings; {note}"),
persisted,
);
self.announce_reconfigured(request, previous, api).await?;
Ok(None)
}
Err(Flow::Stopped) => Err(Flow::Stopped),
@@ -194,6 +199,36 @@ impl Supervisor {
}
}
/// The new engine runs: write the configuration when asked, follow a new context in the API, and answer.
async fn announce_reconfigured(
&mut self,
request: &reconfigure::Request,
previous: &RunConfig,
api: &mut Child,
) -> Result<(), Flow> {
let (persisted, note) = self.persist_note(request.persist);
// the API advertises the context of strata.json: follow it
if persisted && self.config.profile.context_tokens != previous.profile.context_tokens {
self.restart_api(api).await?;
}
self.set_phase(Phase::Ready, "ready (engine reconfigured)");
self.log.line("reconfigure: done");
self.answer(
&request.id,
reconfigure::State::Done,
format!("the engine runs with the new settings; {note}"),
persisted,
);
Ok(())
}
/// Not even the previous engine starts: answer `failed` and give the flow back to end the service.
fn restore_failed(&self, id: &str, refusal: &str, flow: Flow) -> Flow {
let why = format!("{refusal}; the previous settings could not be restored either");
self.answer(id, reconfigure::State::Failed, why, false);
flow
}
/// Refused on the stopped host, or the new engine did not come up: put the previous engine back.
async fn restore_previous(
&mut self,
@@ -203,23 +238,19 @@ impl Supervisor {
engine: &mut Child,
gateway: &mut Child,
) -> Result<(), Flow> {
let id = &request.id;
self.config = previous;
self.log.line(&format!(
"reconfigure {id}: {refusal}; restoring the previous settings"
"reconfigure {}: {refusal}; restoring the previous settings",
request.id
));
let child = match self.start_engine(gateway).await {
Ok(child) => child,
Err(flow) => {
let why = format!("{refusal}; the previous settings could not be restored either");
self.answer(id, reconfigure::State::Failed, why, false);
return Err(flow);
}
Err(flow) => return Err(self.restore_failed(&request.id, &refusal, flow)),
};
*engine = child;
self.set_phase(Phase::Ready, "ready (previous settings restored)");
self.answer(
id,
&request.id,
reconfigure::State::Refused,
format!("{refusal}; the previous settings are back"),
false,
+12 -9
View File
@@ -25,11 +25,7 @@ pub(super) async fn run_inner(options: Options) -> Result<(), Failure> {
let api_key = read_api_key(&paths)?;
check_binaries(&paths)?;
let addresses = parse_addresses(&config)?;
// No log line of this process or of its children may ever contain the key or a token.
leleka_obs::register_secret(&api_key);
for value in env.values() {
leleka_obs::register_secret(value);
}
register_secrets(&api_key, &env);
let log_file = open_log(&paths.logs().join("leleka.log"))
.map_err(|e| setup_failure(format!("cannot open the log: {e}")))?;
@@ -51,6 +47,14 @@ pub(super) async fn run_inner(options: Options) -> Result<(), Failure> {
supervisor.conclude(outcome)
}
/// No log line of this process or of its children may ever contain the key or a token.
fn register_secrets(api_key: &str, env: &BTreeMap<String, String>) {
leleka_obs::register_secret(api_key);
for value in env.values() {
leleka_obs::register_secret(value);
}
}
fn create_directories(paths: &Paths) -> Result<(), Failure> {
let stamps_dir = paths.engine_stamps();
for dir in [
@@ -141,7 +145,6 @@ struct Assembly {
impl Supervisor {
fn assemble(parts: Assembly, addresses: (SocketAddr, SocketAddr, SocketAddr)) -> Self {
let (api_addr, engine_addr, daemon_addr) = addresses;
Supervisor {
status_path: parts.paths.status_file(),
stamps: VerifyStamps::new(parts.paths.engine_stamps(), false),
@@ -157,9 +160,9 @@ impl Supervisor {
source_identity: None,
archive_attested: false,
archive_sparse_pin: None,
api_addr,
engine_addr,
daemon_addr,
api_addr: addresses.0,
engine_addr: addresses.1,
daemon_addr: addresses.2,
engine_restarts: 0,
pids: [None; 3],
phase: Phase::Starting,
+14 -10
View File
@@ -182,21 +182,25 @@ impl Supervisor {
/// The loop proper. `Err` leaves without the drain (a child that cannot be respawned); `Ok(result)` is drained first.
async fn supervise(&mut self, r: &mut Running) -> Result<Result<(), Flow>, Flow> {
loop {
let step = tokio::select! {
_ = self.shutdown.changed() => Step::End(Ok(())),
_ = r.requests.tick() => self.on_request(r).await,
status = r.engine.wait() => self.on_engine_exit(r, describe_exit(status)).await,
_ = r.logs_tick.tick() => self.on_logs_tick(),
_ = r.health_tick.tick(), if self.config.health.enabled => self.on_health_tick(r).await,
status = r.gateway.wait() => self.on_gateway_exit(r, describe_exit(status)).await?,
status = r.api.wait() => self.on_api_exit(r, describe_exit(status)).await?,
};
if let Step::End(result) = step {
if let Step::End(result) = self.next_step(r).await? {
return Ok(result);
}
}
}
/// Wait for the next thing that happens to the service and deal with it.
async fn next_step(&mut self, r: &mut Running) -> Result<Step, Flow> {
Ok(tokio::select! {
_ = self.shutdown.changed() => Step::End(Ok(())),
_ = r.requests.tick() => self.on_request(r).await,
status = r.engine.wait() => self.on_engine_exit(r, describe_exit(status)).await,
_ = r.logs_tick.tick() => self.on_logs_tick(),
_ = r.health_tick.tick(), if self.config.health.enabled => self.on_health_tick(r).await,
status = r.gateway.wait() => self.on_gateway_exit(r, describe_exit(status)).await?,
status = r.api.wait() => self.on_api_exit(r, describe_exit(status)).await?,
})
}
async fn on_request(&mut self, r: &mut Running) -> Step {
let request = match reconfigure::take_request(&self.paths) {
None => return Step::Go,
+21 -10
View File
@@ -12,14 +12,7 @@ pub(super) async fn status(args: &[String]) -> i32 {
let api = session.api(&state_dir);
let supervisor = supervisor_status(&session.bridge, &state_dir);
let key = session.bridge.read_file(&format!("{state_dir}/api-key"));
let ready = match &key {
Some(key) => probe_ready_with_key(key, &api).await,
None => false,
};
let gateway = match (&key, ready) {
(Some(key), true) => fetch_status_with_key(key, &api).await,
_ => None,
};
let (ready, gateway) = probe_gateway(key.as_deref(), &api).await;
if !json && key.is_none() {
note(&format!(
"no API key in {state_dir}/api-key of {} (has `leleka up` run? other state? pass --state-dir)",
@@ -39,6 +32,19 @@ pub(super) async fn status(args: &[String]) -> i32 {
)
}
/// Is the API ready, and what does the gateway say (only asked when it is)?
async fn probe_gateway(key: Option<&str>, api: &str) -> (bool, Option<Value>) {
let ready = match key {
Some(key) => probe_ready_with_key(key, api).await,
None => false,
};
let gateway = match (key, ready) {
(Some(key), true) => fetch_status_with_key(key, api).await,
_ => None,
};
(ready, gateway)
}
/// Not an error of the tool: nothing is running. Same shape as a native "not ready".
fn print_not_running(args: &[String], message: String) -> i32 {
let json = args.iter().any(|a| a == "--json");
@@ -155,14 +161,19 @@ pub(super) async fn down(args: &[String]) -> i32 {
));
return 0;
}
interrupt_and_wait(bridge, pid, &pid_text).await
}
/// SIGINT to the supervisor, then wait for it to drain.
async fn interrupt_and_wait(bridge: &Bridge, pid: u64, pid_text: &str) -> i32 {
note(&format!(
"stopping the supervisor (pid {pid}) with SIGINT: the API drains first, then the gateway and the engine"
));
if let Err(message) = bridge.capture("kill", &["-INT", &pid_text]) {
if let Err(message) = bridge.capture("kill", &["-INT", pid_text]) {
note(&message);
return 1;
}
wait_until_gone(bridge, &pid_text).await
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.
+22 -13
View File
@@ -11,11 +11,8 @@ fn gib(bytes: u64) -> String {
/// `leleka doctor [--assets DIR]`: everything this machine tells about the two routes, then what is missing and the one command
/// that fixes the first missing thing.
pub(super) async fn doctor(args: &[String]) -> i32 {
let var = |name: &str| std::env::var(name).ok().filter(|v| !v.is_empty());
let home = std::env::var_os("USERPROFILE").map(PathBuf::from);
let mut dirs = crate::layout::Dirs::defaults(false, home.as_deref(), &var);
apply_assets_flag(&mut dirs, args);
let paths = dirs.paths();
let paths = doctor_dirs(home.as_deref(), args).paths();
let exe_dir = std::env::current_exe()
.ok()
.and_then(|exe| exe.parent().map(PathBuf::from));
@@ -43,6 +40,14 @@ pub(super) async fn doctor(args: &[String]) -> i32 {
print_next_command(&inputs, &paths)
}
/// The default directories with the `--assets` of the command line.
fn doctor_dirs(home: Option<&Path>, args: &[String]) -> crate::layout::Dirs {
let var = |name: &str| std::env::var(name).ok().filter(|v| !v.is_empty());
let mut dirs = crate::layout::Dirs::defaults(false, home, &var);
apply_assets_flag(&mut dirs, args);
dirs
}
fn apply_assets_flag(dirs: &mut crate::layout::Dirs, args: &[String]) {
let mut iter = args.iter();
while let Some(arg) = iter.next() {
@@ -149,15 +154,7 @@ fn print_distros(wsl: &Path) -> Option<bool> {
}
Ok(list) => list,
};
for d in &list {
println!(
" distro {}{} {} (WSL{})",
if d.default { "* " } else { "" },
d.name,
d.state,
d.version
);
}
print_distro_list(&list);
match pick_distro(&list, std::env::var("LELEKA_WSL_DISTRO").ok().as_deref()) {
Err(message) => {
println!(" chosen {message}");
@@ -174,6 +171,18 @@ fn print_distros(wsl: &Path) -> Option<bool> {
}
}
fn print_distro_list(list: &[Distro]) {
for d in list {
println!(
" distro {}{} {} (WSL{})",
if d.default { "* " } else { "" },
d.name,
d.state,
d.version
);
}
}
fn find_linux_leleka(bridge: &Bridge, list: &[Distro]) -> Option<bool> {
if !list
.iter()
+25 -16
View File
@@ -69,17 +69,21 @@ pub async fn dispatch(args: &[String]) -> Option<i32> {
};
if route == Route::Native {
// The ordinary command code, with the route flags removed.
let rest: Vec<String> = args.clone();
return Some(crate::app::main_native(rest).await);
return Some(crate::app::main_native(args).await);
}
Some(run_through_wsl(&command, &args[1..], have_wsl).await)
}
/// The command in the WSL2 distribution; `rest` are its arguments.
async fn run_through_wsl(command: &str, rest: &[String], have_wsl: bool) -> i32 {
if !have_wsl {
note("wsl.exe was not found; install WSL2 (`wsl --install -d Ubuntu`) or use --native");
return Some(1);
return 1;
}
if command == "service" {
return Some(service_wsl(&args[1..]).await);
return service_wsl(rest).await;
}
Some(wsl_route(&command, &args[1..]).await)
wsl_route(command, rest).await
}
fn is_routed_command(command: &str) -> bool {
@@ -131,17 +135,9 @@ pub(super) fn native_prepared() -> bool {
pub(super) async fn service_wsl(args: &[String]) -> i32 {
use crate::cli::ServiceAction;
let action = match args.first().map(String::as_str) {
Some("install") => ServiceAction::Install,
Some("uninstall") => ServiceAction::Uninstall,
Some("status") => ServiceAction::Status,
Some("start") => ServiceAction::Start,
Some("stop") => ServiceAction::Stop,
Some("hold") => ServiceAction::Hold,
_ => {
note("usage: leleka service install|uninstall|status|start|stop [--wsl-distro NAME]");
return 2;
}
let Some(action) = service_action(args) else {
note("usage: leleka service install|uninstall|status|start|stop [--wsl-distro NAME]");
return 2;
};
let hidden = args.iter().any(|a| a == "--hidden");
let rest: Vec<String> = args[1..]
@@ -163,6 +159,19 @@ pub(super) async fn service_wsl(args: &[String]) -> i32 {
}
}
fn service_action(args: &[String]) -> Option<crate::cli::ServiceAction> {
use crate::cli::ServiceAction;
Some(match args.first().map(String::as_str)? {
"install" => ServiceAction::Install,
"uninstall" => ServiceAction::Uninstall,
"status" => ServiceAction::Status,
"start" => ServiceAction::Start,
"stop" => ServiceAction::Stop,
"hold" => ServiceAction::Hold,
_ => return None,
})
}
fn print_service_dry_run() {
let exe = std::env::current_exe()
.map(|p| p.display().to_string())
+3 -7
View File
@@ -123,7 +123,8 @@ fn find_linux_leleka(session: &Session) -> Result<String, String> {
/// 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 ran = Ran::of(command, args, json);
let dry_run = ran.dry_run;
let state_dir = session.state_dir();
let api = format!("127.0.0.1:{}", session.forwarded.api_port.unwrap_or(8081));
if command == "up" && !dry_run {
@@ -145,12 +146,7 @@ async fn run_in_wsl(session: &Session, command: &str, args: &[String], binary: &
if let Some(task) = announce {
task.abort();
}
report_exit(
status,
&Ran::of(command, args, json),
session,
(&state_dir, &api),
)
report_exit(status, &ran, session, (&state_dir, &api))
}
fn spawn_linux(
+46 -26
View File
@@ -179,12 +179,7 @@ pub fn translate_args(
let mut index = 0;
while index < args.len() {
let arg = &args[index];
let (name, inline) = match arg.split_once('=') {
Some((name, value)) if name.starts_with("--") => {
(name.to_owned(), Some(value.to_owned()))
}
_ => (arg.clone(), None),
};
let (name, inline) = split_flag(arg);
if !takes_value(&name) {
out.args.push(arg.clone());
index += 1;
@@ -205,6 +200,14 @@ pub fn translate_args(
Ok(out)
}
/// `--name=value` as the name and the inline value; any other argument is a name.
fn split_flag(arg: &str) -> (String, Option<String>) {
match arg.split_once('=') {
Some((name, value)) if name.starts_with("--") => (name.to_owned(), Some(value.to_owned())),
_ => (arg.to_owned(), None),
}
}
/// The flags whose value is a path or is read here.
fn takes_value(name: &str) -> bool {
PATH_FLAGS.contains(&name)
@@ -225,34 +228,51 @@ fn forward_flag(
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]);
}
"--profile" => forward_profile(out, value, distro, home)?,
"--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]);
}
flag => forward_path_flag(out, flag, value, distro, home)?,
}
Ok(())
}
/// `--profile`: a path to a profile file is translated, a built-in name goes through.
fn forward_profile(
out: &mut Forwarded,
value: String,
distro: &str,
home: Option<&str>,
) -> Result<(), String> {
let looks_like_path = value.contains('/') || value.contains('\\') || value.ends_with(".json");
let value = if looks_like_path {
to_wsl_path(&value, distro, home)?
} else {
value
};
out.args.extend(["--profile".into(), value]);
Ok(())
}
/// Any other path flag: translated, and remembered when it names the assets or the state directory.
fn forward_path_flag(
out: &mut Forwarded,
flag: &str,
value: String,
distro: &str,
home: Option<&str>,
) -> Result<(), String> {
let translated = to_wsl_path(&value, distro, home).map_err(|e| format!("{flag}: {e}"))?;
match flag {
"--assets" => out.assets = Some(translated.clone()),
"--state-dir" => out.state_dir = Some(translated.clone()),
_ => {}
}
out.args.extend([flag.to_owned(), translated]);
Ok(())
}
/// `40GB`, `40G`, `49152MB`, `40 GB`, plain bytes.
pub fn parse_size(text: &str) -> Option<u64> {
let text = text.trim().trim_matches('"').to_ascii_lowercase();