Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
957 lines
38 KiB
Rust
957 lines
38 KiB
Rust
//! Command implementations behind `main`: `up`, `preflight`, `status`, `down`, `profiles`.
|
|
use crate::{
|
|
cli::{Command, Environment, ReconfigureArgs, USAGE, UpOptions, parse},
|
|
plan::{Context, Mode, Step, StepState, UnitScopeTag, gather, plan_steps, render_plan},
|
|
preflight::Report,
|
|
profile::{BUILTIN, Profile},
|
|
steps::{self, gather_fs, say},
|
|
supervisor,
|
|
};
|
|
use serde_json::{Value, json};
|
|
use std::path::PathBuf;
|
|
|
|
pub fn env_var(name: &str) -> Option<String> {
|
|
std::env::var(name).ok().filter(|v| !v.is_empty())
|
|
}
|
|
|
|
fn is_root() -> bool {
|
|
#[cfg(target_os = "linux")]
|
|
{
|
|
rustix::process::geteuid().is_root()
|
|
}
|
|
#[cfg(not(target_os = "linux"))]
|
|
{
|
|
false
|
|
}
|
|
}
|
|
|
|
/// The command line of `leleka`. On Windows the WSL2 route (`winfront`) takes the deployment commands first.
|
|
pub async fn main_with(args: Vec<String>) -> i32 {
|
|
#[cfg(windows)]
|
|
if let Some(code) = crate::winfront::dispatch(&args).await {
|
|
return code;
|
|
}
|
|
main_native(args).await
|
|
}
|
|
|
|
fn home_dir() -> Option<PathBuf> {
|
|
#[cfg(windows)]
|
|
{
|
|
std::env::var_os("USERPROFILE").map(PathBuf::from)
|
|
}
|
|
#[cfg(not(windows))]
|
|
{
|
|
std::env::var_os("HOME").map(PathBuf::from)
|
|
}
|
|
}
|
|
|
|
/// The commands on this host itself: systemd or foreground on Linux, foreground on Windows (`--native`).
|
|
pub async fn main_native(mut args: Vec<String>) -> i32 {
|
|
// `--hidden` (the logon task): hide the console window (the console itself stays, children stop through it).
|
|
if let Some(index) = args.iter().position(|a| a == "--hidden") {
|
|
args.remove(index);
|
|
crate::supervisor::HIDDEN.store(true, std::sync::atomic::Ordering::Relaxed);
|
|
#[cfg(windows)]
|
|
crate::winsys::hide_console();
|
|
}
|
|
let var = env_var;
|
|
let environment = Environment {
|
|
root: is_root(),
|
|
home: home_dir(),
|
|
var: &var,
|
|
};
|
|
let command = match parse(&args, &environment) {
|
|
Ok(command) => command,
|
|
Err(message) => {
|
|
eprintln!("leleka: {message}");
|
|
return 2;
|
|
}
|
|
};
|
|
match command {
|
|
Command::Help => {
|
|
print!("{USAGE}");
|
|
0
|
|
}
|
|
Command::Version => {
|
|
println!("leleka {}", env!("CARGO_PKG_VERSION"));
|
|
0
|
|
}
|
|
Command::Profiles(None) => {
|
|
for (name, _) in BUILTIN {
|
|
let profile = Profile::builtin(name).expect("built-in");
|
|
println!("{name}\n {}", profile.description);
|
|
}
|
|
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::Service(action, opts) => crate::winservice::run_native(action, opts).await,
|
|
Command::Run { config, kar_fd } => {
|
|
supervisor::run(supervisor::Options { config, kar_fd }).await
|
|
}
|
|
Command::ExecInherit(rest) => match crate::sealed::exec_inherit(&rest) {
|
|
Ok(never) => match never {},
|
|
Err(message) => {
|
|
eprintln!("leleka exec-inherit: {message}");
|
|
2
|
|
}
|
|
},
|
|
}
|
|
}
|
|
|
|
fn print_report(report: &Report) {
|
|
eprint!("{}", report.render());
|
|
}
|
|
|
|
fn json_plan(ctx: &Context, steps: &[Step]) -> Value {
|
|
json!({
|
|
"mode": ctx.mode,
|
|
"profile": ctx.config.as_ref().map(|c| c.profile.name.clone()),
|
|
"preflight": ctx.report,
|
|
"steps": steps,
|
|
"engine_command": ctx.config.as_ref().map(|c| {
|
|
let mut args = vec![ctx.paths.bin("leleka-inference").display().to_string()];
|
|
args.extend(c.engine_args(c.kar_arg()));
|
|
args
|
|
}),
|
|
})
|
|
}
|
|
|
|
async fn preflight(opts: UpOptions) -> i32 {
|
|
let ctx = gather(&opts, &env_var);
|
|
match (&ctx.profile, &ctx.report) {
|
|
(Err(message), _) => {
|
|
eprintln!("leleka: {message}");
|
|
1
|
|
}
|
|
(Ok(_), Some(report)) => {
|
|
if opts.json {
|
|
println!(
|
|
"{}",
|
|
serde_json::to_string_pretty(report).expect("serializable")
|
|
);
|
|
} else {
|
|
print_report(report);
|
|
}
|
|
i32::from(report.failed())
|
|
}
|
|
_ => 1,
|
|
}
|
|
}
|
|
|
|
pub async fn up(opts: UpOptions) -> i32 {
|
|
let ctx = gather(&opts, &env_var);
|
|
if let Err(message) = &ctx.profile {
|
|
eprintln!("leleka: {message}");
|
|
return 1;
|
|
}
|
|
let report = ctx
|
|
.report
|
|
.as_ref()
|
|
.expect("report exists when the profile does");
|
|
print_report(report);
|
|
if let Some(resources) = &ctx.needs.resources {
|
|
eprint!("{}", resources.render(&ctx.facts));
|
|
}
|
|
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");
|
|
if opts.dry_run {
|
|
if opts.json {
|
|
println!(
|
|
"{}",
|
|
serde_json::to_string_pretty(&json_plan(&ctx, &steps)).expect("serializable")
|
|
);
|
|
} else {
|
|
print!("{}", render_plan(&ctx, &steps));
|
|
println!(
|
|
"mode: {}; nothing was changed (--dry-run)",
|
|
ctx.mode.label()
|
|
);
|
|
}
|
|
return i32::from(report.failed() || blocked);
|
|
}
|
|
if report.failed() {
|
|
eprintln!(
|
|
"leleka: preflight failed; nothing was changed. Fix the FAIL lines above and rerun the same command."
|
|
);
|
|
return 1;
|
|
}
|
|
eprint!("{}", render_plan(&ctx, &steps));
|
|
match run_up(&ctx, &steps).await {
|
|
Ok(code) => code,
|
|
Err(message) => {
|
|
eprintln!("leleka: {message}");
|
|
eprintln!(
|
|
"leleka: the run is resumable: fix the cause and rerun the same command (finished steps are skipped)."
|
|
);
|
|
1
|
|
}
|
|
}
|
|
}
|
|
|
|
pub async fn run_up(ctx: &Context, steps: &[Step]) -> Result<i32, String> {
|
|
let changes = steps::prepare(ctx, steps).await?;
|
|
let config = steps::config_of(ctx)?;
|
|
match ctx.mode {
|
|
Mode::None => {
|
|
say(&format!(
|
|
"prepared. Start it with: {} run --config {}",
|
|
ctx.paths.bin("leleka").display(),
|
|
ctx.paths.run_config().display()
|
|
));
|
|
Ok(0)
|
|
}
|
|
Mode::Systemd(scope) => {
|
|
#[cfg(unix)]
|
|
if scope == UnitScopeTag::System {
|
|
steps::ensure_service_user(ctx).await?;
|
|
steps::hand_over_to_service_user(ctx)?;
|
|
}
|
|
let changed = steps::install_unit(ctx, scope).await?;
|
|
steps::start_unit(ctx, scope, changed || changes.needs_restart()).await?;
|
|
steps::wait_ready(ctx, Some(scope)).await?;
|
|
summary(ctx, config);
|
|
Ok(0)
|
|
}
|
|
Mode::Foreground => {
|
|
if let Some(fd) = ctx.opts.kar_fd {
|
|
crate::sealed::check_inherited_archive(fd, crate::profile::ARCHIVE_BYTES)?;
|
|
}
|
|
if steps::probe_ready(ctx).await {
|
|
say("a supervisor for this state directory is already ready");
|
|
summary(ctx, config);
|
|
return Ok(0);
|
|
}
|
|
if crate::plan::service_running(&ctx.paths) {
|
|
return Err(format!(
|
|
"another supervisor is running for {} (not ready yet); wait for it or stop it first",
|
|
ctx.opts.dirs.state.display()
|
|
));
|
|
}
|
|
let options = supervisor::Options {
|
|
config: ctx.paths.run_config(),
|
|
kar_fd: ctx.opts.kar_fd,
|
|
};
|
|
let run = supervisor::run(options);
|
|
tokio::pin!(run);
|
|
let mut printed = false;
|
|
loop {
|
|
tokio::select! {
|
|
code = &mut run => return Ok(code),
|
|
ready = steps::wait_ready(ctx, None), if !printed => {
|
|
printed = true;
|
|
match ready {
|
|
Ok(()) => summary(ctx, config),
|
|
Err(message) => say(&message),
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
pub fn summary_json(ctx: &Context, config: &crate::config::RunConfig) -> Value {
|
|
let gpu = ctx.facts.gpus.iter().find(|g| g.index == ctx.opts.gpu);
|
|
json!({
|
|
"ready": true,
|
|
"endpoint": format!("http://{}", ctx.opts.ports.api),
|
|
"model": config.model_id,
|
|
"model_digest": config.model_digest,
|
|
"api_key_file": ctx.paths.api_key().display().to_string(),
|
|
"gpu": gpu.map(|g| json!({"index": g.index, "name": g.name, "sm": g.sm, "vram_total_mib": g.vram_total_mib, "driver": g.driver})),
|
|
"profile": config.profile.name,
|
|
"gpu_budget_bytes": config.profile.gpu_budget_bytes,
|
|
"context_tokens": config.profile.context_tokens,
|
|
"kar_source": config.profile.kar_source.as_str(),
|
|
"ram_total_bytes": ctx.facts.memory.total,
|
|
"ram_available_at_start_bytes": ctx.facts.memory.available,
|
|
"service": ctx.mode.label(),
|
|
"logs": ctx.paths.logs().display().to_string(),
|
|
"state": ctx.opts.dirs.state.display().to_string(),
|
|
"assets": ctx.opts.dirs.assets.display().to_string(),
|
|
})
|
|
}
|
|
|
|
pub fn summary(ctx: &Context, config: &crate::config::RunConfig) {
|
|
let gib = |bytes: u64| format!("{:.1} GiB", bytes as f64 / (1u64 << 30) as f64);
|
|
if ctx.opts.json {
|
|
println!(
|
|
"{}",
|
|
serde_json::to_string_pretty(&summary_json(ctx, config)).expect("serializable")
|
|
);
|
|
return;
|
|
}
|
|
let gpu = ctx.facts.gpus.iter().find(|g| g.index == ctx.opts.gpu);
|
|
let key_file = ctx.paths.api_key().display().to_string();
|
|
let mut text = String::from("\nLeleka is ready.\n");
|
|
text.push_str(&format!(
|
|
" endpoint http://{} (loopback only; reach it from elsewhere through an SSH tunnel)\n",
|
|
ctx.opts.ports.api
|
|
));
|
|
text.push_str(&format!(
|
|
" model {} {}\n",
|
|
config.model_id, config.model_digest
|
|
));
|
|
text.push_str(&format!(
|
|
" api key in {key_file} (send it as `Authorization: Bearer ...`)\n"
|
|
));
|
|
if let Some(gpu) = gpu {
|
|
text.push_str(&format!(
|
|
" gpu {} (GPU {}, sm_{}, {} MiB, driver {})\n",
|
|
gpu.name,
|
|
gpu.index,
|
|
gpu.sm.map_or("?".into(), |s| s.to_string()),
|
|
gpu.vram_total_mib,
|
|
gpu.driver
|
|
));
|
|
}
|
|
text.push_str(&format!(
|
|
" profile {}: VRAM budget {}, context {} tokens, KAR archive as {}\n",
|
|
config.profile.name,
|
|
gib(config.profile.gpu_budget_bytes),
|
|
config.profile.context_tokens,
|
|
match config.profile.kar_source {
|
|
crate::profile::KarSource::Memfd => format!(
|
|
"a sealed memfd ({} of RAM held for the life of the service)",
|
|
gib(crate::profile::ARCHIVE_BYTES)
|
|
),
|
|
crate::profile::KarSource::File => "a read-only file (page cache only)".to_owned(),
|
|
}
|
|
));
|
|
text.push_str(&format!(
|
|
" host RAM {} total, {} available before start\n",
|
|
gib(ctx.facts.memory.total),
|
|
gib(ctx.facts.memory.available)
|
|
));
|
|
text.push_str(&format!(" service {}\n", ctx.mode.label()));
|
|
if ctx.mode == Mode::Systemd(UnitScopeTag::User) {
|
|
text.push_str(" a user unit runs while you have a session; `loginctl enable-linger $USER` starts it at boot
|
|
");
|
|
}
|
|
text.push_str(&format!(
|
|
" logs {} (leleka.log, engine.log, gateway.log, api.log)\n",
|
|
ctx.paths.logs().display()
|
|
));
|
|
if ctx.facts.os == "windows" {
|
|
text.push_str(&format!(
|
|
" try {}
|
|
",
|
|
powershell_try(&key_file, &ctx.opts.ports.api, &config.model_id)
|
|
));
|
|
eprintln!("{text}");
|
|
return;
|
|
}
|
|
text.push_str(&format!(
|
|
" try curl -s -H \"Authorization: Bearer $(cat {key_file})\" -H 'content-type: application/json' \\\n -d '{{\"model\":\"{}\",\"input\":\"hello\",\"max_output_tokens\":32}}' http://{}/v1/responses\n",
|
|
config.model_id, ctx.opts.ports.api
|
|
));
|
|
eprintln!("{text}");
|
|
}
|
|
|
|
/// A PowerShell one-liner that sends one request to the API (the key file may be a UNC path into WSL).
|
|
pub fn powershell_try(key_file: &str, api: &str, model: &str) -> String {
|
|
format!(
|
|
"$k=(Get-Content -Raw '{key_file}').Trim(); Invoke-RestMethod -Method Post -Uri http://{api}/v1/responses -Headers @{{Authorization=\"Bearer $k\"}} -ContentType 'application/json' -Body '{{\"model\":\"{model}\",\"input\":\"hello\",\"max_output_tokens\":32}}'"
|
|
)
|
|
}
|
|
|
|
/// Which systemd unit of this deployment exists (system first), judged by the unit file.
|
|
fn installed_scope(paths: &crate::layout::Paths) -> Option<UnitScopeTag> {
|
|
let home = std::env::var_os("HOME").map(PathBuf::from);
|
|
[UnitScopeTag::System, UnitScopeTag::User]
|
|
.into_iter()
|
|
.find(|scope| {
|
|
crate::units::unit_path(scope.scope(), home.as_deref(), paths.unit_name())
|
|
.is_ok_and(|path| path.is_file())
|
|
})
|
|
}
|
|
|
|
/// Cheap by design (the container health check runs it every 30 s): no GPU probe, no hashing.
|
|
async fn status(opts: UpOptions) -> i32 {
|
|
let paths = opts.dirs.paths();
|
|
let api = crate::config::RunConfig::read(&paths.run_config())
|
|
.map(|config| config.ports.api)
|
|
.unwrap_or_else(|_| opts.ports.api.clone());
|
|
let status: Option<Value> = std::fs::read_to_string(paths.status_file())
|
|
.ok()
|
|
.and_then(|t| serde_json::from_str(&t).ok());
|
|
let ready = steps::probe_ready_at(&paths, &api).await;
|
|
let gateway = if ready { steps::fetch_status(&paths, &api).await } 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,
|
|
};
|
|
print_status(
|
|
opts.json,
|
|
ready,
|
|
unit.map(|state| (paths.unit_name().to_owned(), state)),
|
|
status,
|
|
gateway.as_ref(),
|
|
&paths.run_dir().display().to_string(),
|
|
)
|
|
}
|
|
|
|
/// The `leleka status` output from the pieces gathered on this host or through the WSL bridge. Exit code 1 when not ready.
|
|
pub fn print_status(
|
|
json: bool,
|
|
ready: bool,
|
|
unit: Option<(String, String)>,
|
|
supervisor: Option<Value>,
|
|
gateway: Option<&Value>,
|
|
run_dir: &str,
|
|
) -> i32 {
|
|
let machine = gateway.map(|g| g["machine"].clone()).filter(Value::is_object);
|
|
if json {
|
|
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())})
|
|
)
|
|
.expect("serializable")
|
|
);
|
|
} else {
|
|
println!("ready: {ready}");
|
|
if let Some((name, state)) = unit {
|
|
println!("systemd unit {name}: {state}");
|
|
}
|
|
match supervisor {
|
|
Some(s) => println!(
|
|
"supervisor: phase {} (pid {}), engine restarts {}, updated {}
|
|
{}",
|
|
s["phase"].as_str().unwrap_or("?"),
|
|
s["supervisor_pid"],
|
|
s["engine_restarts"],
|
|
s["updated_unix"]
|
|
.as_u64()
|
|
.map(supervisor::format_utc)
|
|
.unwrap_or_default(),
|
|
s["message"].as_str().unwrap_or("")
|
|
),
|
|
None => println!("supervisor: no status file in {run_dir} (never started?)"),
|
|
}
|
|
if let Some(machine) = &machine {
|
|
print!("{}", render_machine(machine));
|
|
} else if ready {
|
|
println!("engine load: the engine reports no telemetry yet");
|
|
}
|
|
}
|
|
i32::from(!ready)
|
|
}
|
|
|
|
/// `leleka reconfigure`.
|
|
///
|
|
/// Runtime settings go to the running engine through the gateway (`POST /v1/reconfigure`, same API key as every request). A
|
|
/// budget or preset change cannot be made that way: it is handed to the supervisor, which restarts only the engine process.
|
|
/// `--persist` then writes the result into `leleka.json` (through the supervisor when one runs, directly otherwise).
|
|
async fn reconfigure(opts: UpOptions, args: ReconfigureArgs) -> i32 {
|
|
let paths = opts.dirs.paths();
|
|
let supervised = crate::plan::service_running(&paths);
|
|
if args.needs_restart() {
|
|
return reconfigure_by_restart(&opts, &args, supervised).await;
|
|
}
|
|
let settings = serde_json::Value::Object(args.settings.clone()).to_string();
|
|
let api = crate::config::RunConfig::read(&paths.run_config())
|
|
.map(|config| config.ports.api)
|
|
.unwrap_or_else(|_| opts.ports.api.clone());
|
|
let Ok(key) = std::fs::read_to_string(paths.api_key()) else {
|
|
eprintln!("leleka: no API key in {} (is the service prepared?)", paths.api_key().display());
|
|
return 1;
|
|
};
|
|
let Some(address) = crate::config::probe_address(&api) else {
|
|
eprintln!("leleka: cannot reach the API address {api}");
|
|
return 1;
|
|
};
|
|
let persist = args.persist.then(|| PersistTarget { paths: &paths, settings: &args.settings, supervised });
|
|
send_reconfigure(address, key.trim_end(), &settings, opts.json, persist).await
|
|
}
|
|
|
|
/// Where `--persist` writes after a successful runtime change.
|
|
pub struct PersistTarget<'a> {
|
|
pub paths: &'a crate::layout::Paths,
|
|
pub settings: &'a serde_json::Map<String, Value>,
|
|
/// A supervisor runs: it records the change in the configuration it holds.
|
|
pub supervised: bool,
|
|
}
|
|
|
|
/// POST the settings document to the gateway at `address` (a loopback address) and print the answer. Shared with the WSL bridge.
|
|
pub async fn send_reconfigure(address: std::net::SocketAddr, key: &str, settings: &str, json: bool, persist: Option<PersistTarget<'_>>) -> i32 {
|
|
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;
|
|
match response {
|
|
Ok(response) => {
|
|
let document: Value = serde_json::from_str(&response.body).unwrap_or(Value::Null);
|
|
let mut persisted = None;
|
|
if response.status == 200
|
|
&& let Some(target) = &persist
|
|
{
|
|
persisted = Some(persist_settings(target.paths, target.settings, target.supervised).await);
|
|
}
|
|
if json {
|
|
let mut shown = document.clone();
|
|
if let (Some(object), Some(result)) = (shown.as_object_mut(), &persisted) {
|
|
object.insert("persisted".into(), json!(result.is_ok()));
|
|
}
|
|
println!("{}", serde_json::to_string_pretty(&shown).unwrap_or(response.body));
|
|
} else if response.status == 200 {
|
|
println!("reconfigured; the engine runs with:");
|
|
print!("{}", render_settings(&document["settings"]));
|
|
match &persisted {
|
|
Some(Ok(note)) => println!("persisted: {note}"),
|
|
Some(Err(why)) => eprintln!("leleka: the engine runs with the new settings, but they were not persisted: {why}"),
|
|
None => {}
|
|
}
|
|
} else {
|
|
let message = document["error"]["message"].as_str().unwrap_or(&response.body);
|
|
eprintln!("leleka: the change was refused (HTTP {}): {message}", response.status);
|
|
}
|
|
i32::from(response.status != 200 || persisted.is_some_and(|result| result.is_err()))
|
|
}
|
|
Err(message) => {
|
|
eprintln!("leleka: {message}");
|
|
1
|
|
}
|
|
}
|
|
}
|
|
|
|
/// `--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.
|
|
async fn persist_settings(paths: &crate::layout::Paths, settings: &serde_json::Map<String, Value>, supervised: bool) -> Result<String, String> {
|
|
if !supervised {
|
|
let changed = crate::reconfigure::persist_offline(paths, settings)?;
|
|
return Ok(format!("leleka.json updated ({} changed; no supervisor was running)", changed.len()));
|
|
}
|
|
let request = crate::reconfigure::Request {
|
|
id: crate::reconfigure::new_request_id(),
|
|
settings: settings.clone(),
|
|
persist: true,
|
|
..Default::default()
|
|
};
|
|
let outcome = ask_supervisor(paths, &request, std::time::Duration::from_secs(60), false).await?;
|
|
if outcome.state == crate::reconfigure::State::Done && outcome.persisted {
|
|
Ok(outcome.message)
|
|
} else {
|
|
Err(outcome.message)
|
|
}
|
|
}
|
|
|
|
/// Leave `request` for the supervisor and wait for its answer (`running` answers are progress, not the end).
|
|
async fn ask_supervisor(
|
|
paths: &crate::layout::Paths,
|
|
request: &crate::reconfigure::Request,
|
|
limit: std::time::Duration,
|
|
show_progress: bool,
|
|
) -> Result<crate::reconfigure::Outcome, String> {
|
|
use crate::reconfigure::{State, read_outcome, write_request};
|
|
write_request(paths, request)?;
|
|
let started = std::time::Instant::now();
|
|
let mut last = String::new();
|
|
loop {
|
|
tokio::time::sleep(std::time::Duration::from_millis(500)).await;
|
|
match read_outcome(paths, &request.id) {
|
|
Some(outcome) if outcome.state != State::Running => return Ok(outcome),
|
|
Some(outcome) if show_progress && outcome.message != last => {
|
|
eprintln!("leleka: {}", outcome.message);
|
|
last = outcome.message;
|
|
}
|
|
_ => {}
|
|
}
|
|
if !crate::plan::service_running(paths) {
|
|
return Err("the supervisor stopped before it answered; see the service log".into());
|
|
}
|
|
if started.elapsed() > limit {
|
|
let _ = std::fs::remove_file(paths.reconfigure_request());
|
|
return Err(format!("the supervisor did not answer within {} s", limit.as_secs()));
|
|
}
|
|
}
|
|
}
|
|
|
|
/// A budget or preset change: the supervisor restarts the engine process with the new numbers.
|
|
async fn reconfigure_by_restart(opts: &UpOptions, args: &ReconfigureArgs, supervised: bool) -> i32 {
|
|
let paths = opts.dirs.paths();
|
|
if !supervised {
|
|
eprintln!(
|
|
"leleka: --gpu-budget-gib and --preset restart the engine process under the supervisor, and no supervisor runs for {}; start the service first (`leleka up`), or change the budget there: `leleka up --gpu-budget-gib N --preset P`",
|
|
paths.dirs.state.display()
|
|
);
|
|
return 1;
|
|
}
|
|
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,
|
|
};
|
|
eprintln!("leleka: asking the supervisor to restart the engine with the new settings (the model loads again; the gateway and the API keep their ports)");
|
|
// two engine starts at worst (the new one fails, the previous one is restored), plus the stop and the host checks
|
|
let limit = std::time::Duration::from_secs(2 * load_timeout + 300);
|
|
let outcome = match ask_supervisor(&paths, &request, limit, !opts.json).await {
|
|
Ok(outcome) => outcome,
|
|
Err(why) => {
|
|
eprintln!("leleka: {why}");
|
|
return 1;
|
|
}
|
|
};
|
|
let done = outcome.state == crate::reconfigure::State::Done;
|
|
if opts.json {
|
|
println!("{}", serde_json::to_string_pretty(&outcome).unwrap_or_default());
|
|
} else if done {
|
|
println!("reconfigured: {}", outcome.message);
|
|
if let Some(effective) = &outcome.effective {
|
|
print!("{}", render_effective(effective));
|
|
}
|
|
} else {
|
|
eprintln!("leleka: the change was not made: {}", outcome.message);
|
|
}
|
|
i32::from(!done)
|
|
}
|
|
|
|
/// The numbers in force after a restart-in-place, one line each.
|
|
pub fn render_effective(effective: &Value) -> String {
|
|
let Some(object) = effective.as_object() else { return String::new() };
|
|
let mut out = String::new();
|
|
for (key, value) in object {
|
|
if !value.is_null() {
|
|
out.push_str(&format!(" {key:20} {value}\n"));
|
|
}
|
|
}
|
|
out
|
|
}
|
|
|
|
/// The settings block of the engine, one line per member.
|
|
pub fn render_settings(settings: &Value) -> String {
|
|
let Some(object) = settings.as_object() else { return String::new() };
|
|
let mut out = String::new();
|
|
for (key, value) in object {
|
|
if key == "prefix_cache" && value.is_object() {
|
|
out.push_str(&format!(
|
|
" prefix cache {} MiB requested {}, tail {}, block {} tokens, kept {} min\n",
|
|
value["budget_mib"].as_u64().map_or("?".to_owned(), |m| m.to_string()),
|
|
value["requested"],
|
|
value["tail"].as_str().unwrap_or("?"),
|
|
value["block_tokens"],
|
|
value["retention_min"]
|
|
));
|
|
} else if key == "prefix_cache" {
|
|
out.push_str(" prefix cache off\n");
|
|
} else {
|
|
out.push_str(&format!(" {key:13} {value}\n"));
|
|
}
|
|
}
|
|
out
|
|
}
|
|
|
|
/// The human view of the engine telemetry document (`machine` of `/v1/status`): GPU, CPU, RAM, throughput, cache, context.
|
|
pub fn render_machine(machine: &Value) -> String {
|
|
let gib = |mib: &Value| mib.as_f64().map_or("?".to_owned(), |m| format!("{:.1}", m / 1024.0));
|
|
let num = |value: &Value| value.as_f64().map_or("-".to_owned(), |v| format!("{v:.0}"));
|
|
let pct = |value: &Value| value.as_f64().map_or("-".to_owned(), |v| format!("{:.0}%", v * 100.0));
|
|
let mut out = format!("engine load ({}):\n", machine["phase"].as_str().unwrap_or("?"));
|
|
let gpu = &machine["gpu"];
|
|
if gpu.is_object() {
|
|
out.push_str(&format!(
|
|
" gpu {}% busy (memory bus {}%), VRAM {} of {} GiB{}{}{}\n",
|
|
gpu["util_pct"], gpu["mem_util_pct"], gib(&gpu["vram_used_mib"]), gib(&gpu["vram_total_mib"]),
|
|
gpu["power_w"].as_f64().map_or(String::new(), |w| format!(", {w:.0} W")),
|
|
gpu["sm_clock_mhz"].as_u64().map_or(String::new(), |m| format!(", {m} MHz")),
|
|
gpu["temp_c"].as_u64().map_or(String::new(), |t| format!(", {t} C")),
|
|
));
|
|
}
|
|
let cpu = &machine["cpu"];
|
|
if cpu.is_object() {
|
|
out.push_str(&format!(
|
|
" cpu {} of {} cores busy in the engine (whole system {}%)\n",
|
|
cpu["process_busy_cores"], cpu["cores"], cpu["system_busy_pct"]
|
|
));
|
|
}
|
|
let ram = &machine["ram"];
|
|
if ram.is_object() {
|
|
out.push_str(&format!(
|
|
" ram {} of {} GiB available, engine {} GiB resident ({} GiB pinned), swap in use {} GiB\n",
|
|
gib(&ram["available_mib"]), gib(&ram["total_mib"]), gib(&ram["process_rss_mib"]), gib(&ram["process_pinned_mib"]), gib(&ram["swap_used_mib"])
|
|
));
|
|
}
|
|
let rates = &machine["throughput"];
|
|
out.push_str(&format!(
|
|
" prefill {} tok/s last, {} average, {} lifetime\n",
|
|
num(&rates["prefill_tok_s_last"]), num(&rates["prefill_tok_s_avg"]), num(&rates["prefill_tok_s_lifetime"])
|
|
));
|
|
out.push_str(&format!(
|
|
" decode {} tok/s last, {} average, {} lifetime{}\n",
|
|
num(&rates["decode_tok_s_last"]), num(&rates["decode_tok_s_avg"]), num(&rates["decode_tok_s_lifetime"]),
|
|
rates["decode_tok_s_live"].as_f64().map_or(String::new(), |v| format!(", {v:.0} now"))
|
|
));
|
|
let cache = &machine["cache"];
|
|
out.push_str(&format!(
|
|
" cache {} of requests hit, {} of prompt tokens reused (last request {} of {})\n",
|
|
pct(&cache["hit_ratio"]), pct(&cache["token_hit_ratio"]), cache["last_reused_tokens"], cache["last_prompt_tokens"]
|
|
));
|
|
let context = &machine["context"];
|
|
out.push_str(&format!(
|
|
" context {} of {} tokens{}\n",
|
|
context["live_tokens"], context["max_tokens"],
|
|
context["used_pct"].as_f64().map_or(String::new(), |p| format!(" ({p:.1}%)"))
|
|
));
|
|
if machine["settings"].is_object() {
|
|
out.push_str("settings in force:\n");
|
|
out.push_str(&render_settings(&machine["settings"]));
|
|
}
|
|
out
|
|
}
|
|
|
|
/// `leleka verify`: full hashing of both shards and the archive, in parallel, against the pinned digests; renews the
|
|
/// stamps (`STATE/stamps/engine`) that let the next start skip the hashing. Nothing is loaded and no GPU is touched.
|
|
async fn verify(opts: UpOptions) -> i32 {
|
|
use crate::{config::RUNTIME_TOKEN_ENV, facts::parse_env_file, profile::KarSource};
|
|
use leleka_model_format::verify_stamp::{FileIdentity, VerifyStamps, sha256_of_file};
|
|
let paths = opts.dirs.paths();
|
|
let config = match crate::config::RunConfig::read(&paths.run_config()) {
|
|
Ok(config) => config,
|
|
Err(message) => {
|
|
eprintln!("leleka: {message}");
|
|
return 2;
|
|
}
|
|
};
|
|
let stamp_dir = paths.engine_stamps();
|
|
if let Err(error) = std::fs::create_dir_all(&stamp_dir) {
|
|
eprintln!("leleka: cannot create {}: {error}", stamp_dir.display());
|
|
return 1;
|
|
}
|
|
#[cfg(unix)]
|
|
{
|
|
use std::os::unix::fs::PermissionsExt;
|
|
let _ = std::fs::set_permissions(&stamp_dir, std::fs::Permissions::from_mode(0o700));
|
|
}
|
|
let env = std::fs::read_to_string(paths.env_file())
|
|
.map(|text| parse_env_file(&text))
|
|
.unwrap_or_default();
|
|
let Some(token) = env.get(RUNTIME_TOKEN_ENV).cloned() else {
|
|
eprintln!(
|
|
"leleka: {} has no {RUNTIME_TOKEN_ENV}; run `leleka up`",
|
|
paths.env_file().display()
|
|
);
|
|
return 2;
|
|
};
|
|
let started = std::time::Instant::now();
|
|
say(
|
|
"hashing both shards (and the archive, when it is a file) in full, in parallel; this renews the stamps",
|
|
);
|
|
let engine = tokio::process::Command::new(paths.bin("leleka-inference"))
|
|
.args(config.verify_args(true))
|
|
.env(RUNTIME_TOKEN_ENV, token)
|
|
.env_remove("HF_TOKEN")
|
|
.stdin(std::process::Stdio::null())
|
|
.status();
|
|
// A sealed-memfd profile cannot hand the engine the file (it must be read-only and owned); the archive file is
|
|
// hashed here instead, against the pinned digest, and stamped for the supervisor (kind `kar-source`).
|
|
let archive = tokio::task::spawn_blocking({
|
|
let kar = paths.kar();
|
|
let memfd = config.profile.kar_source == KarSource::Memfd;
|
|
let stamps = VerifyStamps::new(stamp_dir.clone(), true);
|
|
move || -> Result<Option<f64>, String> {
|
|
if !memfd {
|
|
return Ok(None);
|
|
}
|
|
let begun = std::time::Instant::now();
|
|
let file = std::fs::File::open(&kar)
|
|
.map_err(|e| format!("cannot open {}: {e}", kar.display()))?;
|
|
let before = file.metadata().ok().and_then(|m| FileIdentity::of(&m));
|
|
let digest =
|
|
sha256_of_file(&file).map_err(|e| format!("cannot read {}: {e}", kar.display()))?;
|
|
if digest != crate::profile::archive_sha256() {
|
|
return Err(format!(
|
|
"{} does not match the pinned archive digest",
|
|
kar.display()
|
|
));
|
|
}
|
|
let after = file.metadata().ok().and_then(|m| FileIdentity::of(&m));
|
|
if let (Some(before), true) = (before, before == after) {
|
|
stamps
|
|
.record("kar-source", &crate::profile::archive_sha256(), &before)
|
|
.map_err(|e| format!("cannot record the archive stamp: {e}"))?;
|
|
}
|
|
Ok(Some(begun.elapsed().as_secs_f64()))
|
|
}
|
|
});
|
|
let (engine, archive) = tokio::join!(engine, archive);
|
|
let mut code = 0;
|
|
match engine {
|
|
Ok(status) if status.success() => {}
|
|
Ok(status) => {
|
|
eprintln!(
|
|
"leleka: the engine's verification failed ({status}); a file does not match its pinned digest"
|
|
);
|
|
code = 1;
|
|
}
|
|
Err(error) => {
|
|
eprintln!(
|
|
"leleka: cannot run {}: {error}",
|
|
paths.bin("leleka-inference").display()
|
|
);
|
|
code = 1;
|
|
}
|
|
}
|
|
match archive {
|
|
Ok(Ok(Some(seconds))) => say(&format!(
|
|
"archive file matches the pinned SHA-256 ({seconds:.1}s); stamped"
|
|
)),
|
|
Ok(Ok(None)) => {}
|
|
Ok(Err(message)) => {
|
|
eprintln!("leleka: {message}");
|
|
code = 1;
|
|
}
|
|
Err(error) => {
|
|
eprintln!("leleka: archive verification failed to run: {error}");
|
|
code = 1;
|
|
}
|
|
}
|
|
say(&format!(
|
|
"verification {} in {:.1}s",
|
|
if code == 0 { "passed" } else { "FAILED" },
|
|
started.elapsed().as_secs_f32()
|
|
));
|
|
code
|
|
}
|
|
|
|
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
|
|
}
|
|
}
|
|
}
|
|
None => {
|
|
#[cfg(windows)]
|
|
{
|
|
return stop_foreground(&paths).await;
|
|
}
|
|
#[cfg(not(windows))]
|
|
{
|
|
eprintln!(
|
|
"leleka: no systemd unit is installed for this deployment; a foreground service stops with Ctrl-C (SIGINT/SIGTERM drain the API, then stop the gateway and the engine)"
|
|
);
|
|
0
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/// 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 {
|
|
if !crate::plan::service_running(paths) {
|
|
eprintln!("leleka: no running supervisor for {} (Ctrl-C stops one that runs in a terminal)", paths.dirs.state.display());
|
|
return 0;
|
|
}
|
|
let request = paths.run_dir().join(supervisor::STOP_REQUEST_FILE);
|
|
if let Err(error) = std::fs::write(&request, b"stop
|
|
") {
|
|
eprintln!("leleka: cannot write {}: {error}", request.display());
|
|
return 1;
|
|
}
|
|
eprintln!("leleka: stop requested: the API drains first, then the gateway and the engine");
|
|
let started = std::time::Instant::now();
|
|
while started.elapsed() < std::time::Duration::from_secs(120) {
|
|
tokio::time::sleep(std::time::Duration::from_secs(2)).await;
|
|
if !crate::plan::service_running(paths) {
|
|
eprintln!("leleka: stopped");
|
|
return 0;
|
|
}
|
|
}
|
|
eprintln!("leleka: the supervisor is still draining after 120 s; check `leleka status`");
|
|
1
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod machine_tests {
|
|
use super::render_machine;
|
|
use serde_json::json;
|
|
|
|
#[test]
|
|
fn the_machine_view_names_every_figure_the_operator_asked_for() {
|
|
let text = render_machine(&json!({
|
|
"phase": "decode",
|
|
"gpu": {"util_pct": 91, "mem_util_pct": 40, "vram_used_mib": 30000, "vram_total_mib": 32607, "power_w": 480.0, "sm_clock_mhz": 2900},
|
|
"cpu": {"cores": 32, "process_busy_cores": 7.4, "system_busy_pct": 31.0},
|
|
"ram": {"total_mib": 122880, "available_mib": 70000, "process_rss_mib": 55000, "process_pinned_mib": 3000, "swap_used_mib": 0},
|
|
"throughput": {"prefill_tok_s_last": 5050.0, "prefill_tok_s_avg": 5010.0, "prefill_tok_s_lifetime": 5030.0,
|
|
"decode_tok_s_last": 131.0, "decode_tok_s_avg": 129.0, "decode_tok_s_lifetime": 128.5, "decode_tok_s_live": 135.2},
|
|
"cache": {"hit_ratio": 0.87, "token_hit_ratio": 0.91, "last_reused_tokens": 175104, "last_prompt_tokens": 179968},
|
|
"context": {"live_tokens": 179968, "max_tokens": 262144, "used_pct": 68.65}
|
|
}));
|
|
for needle in ["engine load (decode)", "91% busy", "VRAM 29.3 of 31.8 GiB", "480 W", "7.4 of 32 cores", "prefill 5050 tok/s", "decode 131 tok/s", "135 now", "87% of requests", "91% of prompt", "179968 of 262144 tokens (68.7%)"] {
|
|
assert!(text.contains(needle), "{needle}\
|
|
{text}");
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn the_settings_block_lists_every_member_and_the_prefix_cache_on_one_line() {
|
|
let text = super::render_settings(&json!({
|
|
"context_tokens": 65536, "prefill_capacity": 8192, "cpu_workers": 8,
|
|
"prefix_cache": {"budget_mib": 20480, "requested": 20480, "tail": "reply", "block_tokens": 8192, "retention_min": 60}
|
|
}));
|
|
for needle in ["context_tokens", "65536", "prefill_capacity", "cpu_workers", "prefix cache 20480 MiB requested 20480, tail reply, block 8192 tokens, kept 60 min"] {
|
|
assert!(text.contains(needle), "{needle}
|
|
{text}");
|
|
}
|
|
assert!(super::render_settings(&json!({"prefix_cache": null})).contains("prefix cache off"));
|
|
}
|
|
|
|
#[test]
|
|
fn missing_blocks_are_left_out_not_invented() {
|
|
let text = render_machine(&json!({"phase": "idle", "gpu": null, "cpu": null, "ram": null,
|
|
"throughput": {}, "cache": {}, "context": {"live_tokens": 0, "max_tokens": 8192}}));
|
|
assert!(!text.contains(" gpu ") && !text.contains(" cpu ") && !text.contains(" ram "), "{text}");
|
|
assert!(text.contains("prefill - tok/s"));
|
|
}
|
|
}
|
|
|