leleka up --preset dedicated|workstation (env LELEKA_PRESET): CPU expert workers, host RAM floors and VRAM budget are computed from cores, MemTotal/MemAvailable and free VRAM, printed, preflighted and baked into leleka.json. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
529 lines
20 KiB
Rust
529 lines
20 KiB
Rust
//! Command-line parsing for `leleka`. No framework: a flag table per command, `--flag value` or `--flag=value`.
|
|
use crate::{config::Ports, layout::Dirs};
|
|
use std::{collections::BTreeMap, path::PathBuf};
|
|
|
|
pub const USAGE: &str = "\
|
|
leleka - one-command deployment of the Leleka runtime
|
|
|
|
USAGE
|
|
leleka up [OPTIONS] preflight, fetch+verify the model, build the KAR archive, install, start, wait for ready
|
|
leleka preflight [OPTIONS] only the host checks (exit 1 when one fails)
|
|
leleka run --config FILE the foreground supervisor that systemd starts (engine + gateway + API)
|
|
leleka status [OPTIONS] service state and readiness
|
|
leleka down [OPTIONS] stop the systemd service
|
|
leleka verify [OPTIONS] hash both shards and the archive in full (in parallel), check the pinned digests, renew the
|
|
verification stamps that let a restart skip the hashing (needs a prepared state)
|
|
leleka profiles [show NAME] list the memory profiles, or print one as JSON
|
|
leleka version
|
|
|
|
UP / PREFLIGHT OPTIONS
|
|
--dry-run print the plan and the preflight, change nothing
|
|
--json machine-readable plan / summary on stdout
|
|
--profile auto|NAME|FILE memory profile (default auto: chosen from the GPU)
|
|
--gpu N CUDA device ordinal (default 0)
|
|
--assets DIR model volume: shards, KAR archive, MTP pack, tokenizer [$LELEKA_ASSETS]
|
|
--state-dir DIR configs, tokens, logs, status [$LELEKA_STATE]
|
|
--prefix DIR install prefix (bin/, lib/cublas/) [$LELEKA_PREFIX]
|
|
--bin-src DIR where to take the six binaries from (default: the directory of this binary)
|
|
--mode auto|system|user|foreground|none
|
|
--foreground same as --mode foreground (WSL without systemd, containers, terminals)
|
|
--api-port N API port (default 8081)
|
|
--api-bind IP API listen address (default 127.0.0.1; 0.0.0.0 only inside a container whose port
|
|
is published to 127.0.0.1 or tunnelled; the key is the only protection, no TLS)
|
|
--engine-port N engine gRPC port (default 18766)
|
|
--daemon-port N gateway port (default 18080)
|
|
--preset dedicated|workstation dedicated (default) takes the whole host; workstation leaves cores, RAM and VRAM
|
|
for Docker, agents and the IDE (env LELEKA_PRESET)
|
|
--gpu-budget-gib N override the profile's GPU memory budget
|
|
--context-tokens N override the profile's context ceiling
|
|
--no-fetch never download or build; require the model files to exist
|
|
--reverify ignore the verification stamps and hash everything again
|
|
--trust-archive accept an existing archive of the pinned length + its provenance file without the
|
|
strict re-derivation (hours-scale); the engine still checks its SHA-256 and every
|
|
CRC against the pinned digest at each load
|
|
--mtp-pack PATH import the MTP pack (directory or .tar/.tar.gz of data/mtp-rt) into the assets
|
|
--cublas-dir DIR use this CUDA 12 cuBLAS directory instead of searching / downloading
|
|
--no-install-cublas fail instead of downloading cuBLAS 12.9.1.4
|
|
--timeout-s N wait this long for readiness (default 3600)
|
|
--kar-fd N an already sealed KAR memfd inherited from the parent process: not copied again,
|
|
its RAM is not required (foreground / --mode none only)
|
|
--service-user NAME system unit only: account the service runs as (default leleka, created if missing)
|
|
|
|
ENVIRONMENT
|
|
HF_TOKEN optional Hugging Face token for the model download (sent only to huggingface.co)
|
|
";
|
|
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
pub enum ModeChoice {
|
|
Auto,
|
|
System,
|
|
User,
|
|
Foreground,
|
|
None,
|
|
}
|
|
|
|
#[derive(Clone, Debug)]
|
|
pub struct UpOptions {
|
|
pub dry_run: bool,
|
|
pub json: bool,
|
|
pub profile: Option<String>,
|
|
pub gpu: u32,
|
|
pub dirs: Dirs,
|
|
pub bin_src: Option<PathBuf>,
|
|
pub mode: ModeChoice,
|
|
/// Resource preset (`--preset`, `LELEKA_PRESET`): how much of the host the engine may take.
|
|
pub preset: crate::resources::Preset,
|
|
pub ports: Ports,
|
|
pub gpu_budget_gib: Option<u64>,
|
|
pub context_tokens: Option<u32>,
|
|
pub fetch: bool,
|
|
pub reverify: bool,
|
|
/// Accept an existing archive of the pinned length without the strict F32 re-derivation.
|
|
pub trust_archive: bool,
|
|
pub mtp_pack: Option<PathBuf>,
|
|
pub cublas_dir: Option<PathBuf>,
|
|
pub install_cublas: bool,
|
|
pub timeout_s: u64,
|
|
/// System unit only: the account the service runs as (created when missing). Default `leleka`.
|
|
pub service_user: Option<String>,
|
|
/// An already sealed archive descriptor inherited from the parent (foreground / prepare-only runs).
|
|
pub kar_fd: Option<u32>,
|
|
}
|
|
|
|
#[derive(Debug)]
|
|
pub enum Command {
|
|
Up(UpOptions),
|
|
Preflight(UpOptions),
|
|
Run {
|
|
config: PathBuf,
|
|
kar_fd: Option<u32>,
|
|
},
|
|
ExecInherit(Vec<String>),
|
|
Status(UpOptions),
|
|
Down(UpOptions),
|
|
Verify(UpOptions),
|
|
Profiles(Option<String>),
|
|
Version,
|
|
Help,
|
|
}
|
|
|
|
type Flags = BTreeMap<String, Option<String>>;
|
|
|
|
const UP_FLAGS: &[(&str, bool)] = &[
|
|
("--dry-run", false),
|
|
("--json", false),
|
|
("--profile", true),
|
|
("--gpu", true),
|
|
("--assets", true),
|
|
("--state-dir", true),
|
|
("--prefix", true),
|
|
("--bin-src", true),
|
|
("--mode", true),
|
|
("--preset", true),
|
|
("--foreground", false),
|
|
("--api-port", true),
|
|
("--api-bind", true),
|
|
("--engine-port", true),
|
|
("--daemon-port", true),
|
|
("--gpu-budget-gib", true),
|
|
("--context-tokens", true),
|
|
("--no-fetch", false),
|
|
("--reverify", false),
|
|
("--trust-archive", false),
|
|
("--mtp-pack", true),
|
|
("--cublas-dir", true),
|
|
("--no-install-cublas", false),
|
|
("--timeout-s", true),
|
|
("--service-user", true),
|
|
("--kar-fd", true),
|
|
];
|
|
|
|
fn parse_flags(args: &[String], table: &[(&str, bool)]) -> Result<Flags, String> {
|
|
let mut flags = Flags::new();
|
|
let mut index = 0;
|
|
while index < args.len() {
|
|
let arg = &args[index];
|
|
let (name, inline) = match arg.split_once('=') {
|
|
Some((name, value)) if name.starts_with("--") => (name, Some(value.to_owned())),
|
|
_ => (arg.as_str(), None),
|
|
};
|
|
let Some((_, takes_value)) = table.iter().find(|(flag, _)| *flag == name) else {
|
|
return Err(format!("unknown option {name:?}; see `leleka --help`"));
|
|
};
|
|
let value = if *takes_value {
|
|
match inline {
|
|
Some(value) => Some(value),
|
|
None => {
|
|
index += 1;
|
|
Some(
|
|
args.get(index)
|
|
.ok_or_else(|| format!("{name} needs a value"))?
|
|
.clone(),
|
|
)
|
|
}
|
|
}
|
|
} else if inline.is_some() {
|
|
return Err(format!("{name} takes no value"));
|
|
} else {
|
|
None
|
|
};
|
|
if flags.insert(name.to_owned(), value).is_some() {
|
|
return Err(format!("{name} given twice"));
|
|
}
|
|
index += 1;
|
|
}
|
|
Ok(flags)
|
|
}
|
|
|
|
fn number<T: std::str::FromStr>(flags: &Flags, name: &str, default: T) -> Result<T, String> {
|
|
match flags.get(name) {
|
|
None => Ok(default),
|
|
Some(value) => value
|
|
.as_deref()
|
|
.unwrap_or("")
|
|
.parse()
|
|
.map_err(|_| format!("{name} needs a number")),
|
|
}
|
|
}
|
|
|
|
/// `--api-bind IP`: where the public API listens. Loopback unless asked; the engine and the gateway always
|
|
/// stay on loopback. A non-loopback bind is for containers (publish the port to 127.0.0.1 on the host).
|
|
fn api_bind(flags: &Flags) -> Result<String, String> {
|
|
match text(flags, "--api-bind") {
|
|
None => Ok("127.0.0.1".into()),
|
|
Some(ip) => match ip.parse::<std::net::IpAddr>() {
|
|
Ok(std::net::IpAddr::V4(v4)) => Ok(v4.to_string()),
|
|
Ok(std::net::IpAddr::V6(_)) => Err("--api-bind takes an IPv4 address".into()),
|
|
Err(_) => Err(format!("--api-bind needs an IP address, not {ip:?}")),
|
|
},
|
|
}
|
|
}
|
|
|
|
fn ranged<T: std::str::FromStr + PartialOrd + std::fmt::Display + Copy>(
|
|
flags: &Flags,
|
|
name: &str,
|
|
range: std::ops::RangeInclusive<T>,
|
|
) -> Result<Option<T>, String> {
|
|
if !flags.contains_key(name) {
|
|
return Ok(None);
|
|
}
|
|
let value: T = number(flags, name, *range.start())?;
|
|
if !range.contains(&value) {
|
|
return Err(format!("{name} must be {}..{}", range.start(), range.end()));
|
|
}
|
|
Ok(Some(value))
|
|
}
|
|
|
|
fn text<'a>(flags: &'a Flags, name: &str) -> Option<&'a str> {
|
|
flags.get(name).and_then(|v| v.as_deref())
|
|
}
|
|
|
|
fn port(flags: &Flags, name: &str, default: u16) -> Result<u16, String> {
|
|
let value: u16 = number(flags, name, default)?;
|
|
if value < 1024 {
|
|
return Err(format!("{name} must be 1024..65535"));
|
|
}
|
|
Ok(value)
|
|
}
|
|
|
|
/// Environment access is injected so that parsing is testable.
|
|
pub struct Environment<'a> {
|
|
pub root: bool,
|
|
pub home: Option<PathBuf>,
|
|
pub var: &'a dyn Fn(&str) -> Option<String>,
|
|
}
|
|
|
|
fn up_options(args: &[String], env: &Environment) -> Result<UpOptions, String> {
|
|
let flags = parse_flags(args, UP_FLAGS)?;
|
|
let defaults = Dirs::defaults(env.root, env.home.as_deref(), env.var);
|
|
let abs = |name: &str, fallback: PathBuf| -> Result<PathBuf, String> {
|
|
let path = text(&flags, name).map(PathBuf::from).unwrap_or(fallback);
|
|
if !path.is_absolute() {
|
|
return Err(format!(
|
|
"{name} must be an absolute path (got {})",
|
|
path.display()
|
|
));
|
|
}
|
|
Ok(path)
|
|
};
|
|
let dirs = Dirs {
|
|
prefix: abs("--prefix", defaults.prefix)?,
|
|
state: abs("--state-dir", defaults.state)?,
|
|
assets: abs("--assets", defaults.assets)?,
|
|
};
|
|
let mode = if flags.contains_key("--foreground") {
|
|
if flags.contains_key("--mode") {
|
|
return Err("use either --foreground or --mode".into());
|
|
}
|
|
ModeChoice::Foreground
|
|
} else {
|
|
match text(&flags, "--mode").unwrap_or("auto") {
|
|
"auto" => ModeChoice::Auto,
|
|
"system" => ModeChoice::System,
|
|
"user" => ModeChoice::User,
|
|
"foreground" => ModeChoice::Foreground,
|
|
"none" => ModeChoice::None,
|
|
other => {
|
|
return Err(format!(
|
|
"--mode must be auto, system, user, foreground or none, not {other:?}"
|
|
));
|
|
}
|
|
}
|
|
};
|
|
let kar_fd = match flags.get("--kar-fd") {
|
|
None => None,
|
|
Some(_) => {
|
|
let fd: u32 = number(&flags, "--kar-fd", 0u32)?;
|
|
if !(3..=1_048_576).contains(&fd) {
|
|
return Err(
|
|
"--kar-fd must be an inherited descriptor number of 3 or higher".into(),
|
|
);
|
|
}
|
|
if matches!(mode, ModeChoice::System | ModeChoice::User) {
|
|
return Err("--kar-fd belongs to a process that holds the descriptor; use it with --foreground or --mode none, not with a systemd unit".into());
|
|
}
|
|
Some(fd)
|
|
}
|
|
};
|
|
if mode == ModeChoice::System && !env.root {
|
|
return Err("--mode system needs root (use sudo), or --mode user / --foreground".into());
|
|
}
|
|
let ports = Ports {
|
|
api: format!(
|
|
"{}:{}",
|
|
api_bind(&flags)?,
|
|
port(&flags, "--api-port", 8081)?
|
|
),
|
|
engine: format!("127.0.0.1:{}", port(&flags, "--engine-port", 18766)?),
|
|
daemon: format!("127.0.0.1:{}", port(&flags, "--daemon-port", 18080)?),
|
|
};
|
|
let distinct = [&ports.api, &ports.engine, &ports.daemon];
|
|
if distinct[0] == distinct[1] || distinct[0] == distinct[2] || distinct[1] == distinct[2] {
|
|
return Err("the API, engine and gateway ports must differ".into());
|
|
}
|
|
let cublas_dir = text(&flags, "--cublas-dir").map(PathBuf::from);
|
|
if let Some(dir) = &cublas_dir
|
|
&& !dir.is_absolute()
|
|
{
|
|
return Err("--cublas-dir must be an absolute path".into());
|
|
}
|
|
Ok(UpOptions {
|
|
dry_run: flags.contains_key("--dry-run"),
|
|
json: flags.contains_key("--json"),
|
|
profile: text(&flags, "--profile").map(str::to_owned),
|
|
gpu: number(&flags, "--gpu", 0u32)?,
|
|
dirs,
|
|
bin_src: text(&flags, "--bin-src").map(PathBuf::from),
|
|
mode,
|
|
preset: match text(&flags, "--preset") {
|
|
Some(value) => crate::resources::Preset::parse(value)?,
|
|
None => match (env.var)("LELEKA_PRESET") {
|
|
Some(value) if !value.is_empty() => crate::resources::Preset::parse(&value)?,
|
|
_ => crate::resources::Preset::Dedicated,
|
|
},
|
|
},
|
|
ports,
|
|
gpu_budget_gib: ranged(&flags, "--gpu-budget-gib", 1u64..=1024)?,
|
|
context_tokens: ranged(&flags, "--context-tokens", 1u32..=262_144)?,
|
|
service_user: text(&flags, "--service-user").map(str::to_owned),
|
|
kar_fd,
|
|
fetch: !flags.contains_key("--no-fetch"),
|
|
reverify: flags.contains_key("--reverify"),
|
|
trust_archive: flags.contains_key("--trust-archive"),
|
|
mtp_pack: text(&flags, "--mtp-pack").map(PathBuf::from),
|
|
cublas_dir,
|
|
install_cublas: !flags.contains_key("--no-install-cublas"),
|
|
timeout_s: {
|
|
let value: u64 = number(&flags, "--timeout-s", 3600)?;
|
|
if !(1..=86_400).contains(&value) {
|
|
return Err("--timeout-s must be 1..86400".into());
|
|
}
|
|
value
|
|
},
|
|
})
|
|
}
|
|
|
|
pub fn parse(args: &[String], env: &Environment) -> Result<Command, String> {
|
|
let Some((command, rest)) = args.split_first() else {
|
|
return Ok(Command::Help);
|
|
};
|
|
match command.as_str() {
|
|
"-h" | "--help" | "help" => Ok(Command::Help),
|
|
"version" | "--version" | "-V" => Ok(Command::Version),
|
|
"up" => up_options(rest, env).map(Command::Up),
|
|
"preflight" => up_options(rest, env).map(Command::Preflight),
|
|
"status" => up_options(rest, env).map(Command::Status),
|
|
"down" => up_options(rest, env).map(Command::Down),
|
|
"verify" => up_options(rest, env).map(Command::Verify),
|
|
"profiles" => match rest {
|
|
[] => Ok(Command::Profiles(None)),
|
|
[show, name] if show == "show" => Ok(Command::Profiles(Some(name.clone()))),
|
|
_ => Err("usage: leleka profiles [show NAME]".into()),
|
|
},
|
|
"run" => {
|
|
let flags = parse_flags(rest, &[("--config", true), ("--kar-fd", true)])?;
|
|
let config = text(&flags, "--config").ok_or("leleka run needs --config FILE")?;
|
|
Ok(Command::Run {
|
|
config: PathBuf::from(config),
|
|
kar_fd: flags
|
|
.get("--kar-fd")
|
|
.map(|_| number(&flags, "--kar-fd", 0u32))
|
|
.transpose()?,
|
|
})
|
|
}
|
|
"exec-inherit" => Ok(Command::ExecInherit(rest.to_vec())),
|
|
other => Err(format!("unknown command {other:?}; see `leleka --help`")),
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
fn strings(items: &[&str]) -> Vec<String> {
|
|
items.iter().map(|s| s.to_string()).collect()
|
|
}
|
|
|
|
fn parse_as(root: bool, args: &[&str]) -> Result<Command, String> {
|
|
let var = |_: &str| None;
|
|
parse(
|
|
&strings(args),
|
|
&Environment {
|
|
root,
|
|
home: Some("/home/para".into()),
|
|
var: &var,
|
|
},
|
|
)
|
|
}
|
|
|
|
#[test]
|
|
fn up_defaults_for_a_user() {
|
|
let Command::Up(options) = parse_as(false, &["up"]).unwrap() else {
|
|
panic!()
|
|
};
|
|
assert_eq!(
|
|
options.dirs.assets,
|
|
PathBuf::from("/home/para/.local/share/leleka/assets")
|
|
);
|
|
assert_eq!(options.ports.api, "127.0.0.1:8081");
|
|
assert!(options.fetch && options.install_cublas && !options.dry_run);
|
|
assert_eq!(options.mode, ModeChoice::Auto);
|
|
assert_eq!(options.timeout_s, 3600);
|
|
}
|
|
|
|
#[test]
|
|
fn flags_accept_both_forms_and_reject_mistakes() {
|
|
let Command::Up(options) = parse_as(
|
|
false,
|
|
&[
|
|
"up",
|
|
"--assets=/data/l",
|
|
"--gpu",
|
|
"1",
|
|
"--foreground",
|
|
"--dry-run",
|
|
"--json",
|
|
"--no-fetch",
|
|
"--api-port=9000",
|
|
],
|
|
)
|
|
.unwrap() else {
|
|
panic!()
|
|
};
|
|
assert_eq!(options.dirs.assets, PathBuf::from("/data/l"));
|
|
assert_eq!(
|
|
(
|
|
options.gpu,
|
|
options.mode,
|
|
options.dry_run,
|
|
options.json,
|
|
options.fetch
|
|
),
|
|
(1, ModeChoice::Foreground, true, true, false)
|
|
);
|
|
assert_eq!(options.ports.api, "127.0.0.1:9000");
|
|
for bad in [
|
|
&["up", "--nope"][..],
|
|
&["up", "--gpu"],
|
|
&["up", "--dry-run", "--dry-run"],
|
|
&["up", "--dry-run=1"],
|
|
&["up", "--assets", "relative/dir"],
|
|
&["up", "--api-port", "80"],
|
|
&["up", "--api-port", "9000", "--engine-port", "9000"],
|
|
&["up", "--mode", "weird"],
|
|
&["up", "--foreground", "--mode", "user"],
|
|
&["up", "--gpu-budget-gib", "0"],
|
|
&["up", "--context-tokens", "999999"],
|
|
&["up", "--timeout-s", "0"],
|
|
] {
|
|
assert!(parse_as(false, bad).is_err(), "{bad:?} should fail");
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn the_resource_preset_comes_from_the_flag_then_the_environment() {
|
|
use crate::resources::Preset;
|
|
let preset = |args: &[&str]| match parse_as(false, args) {
|
|
Ok(Command::Up(options)) => Ok(options.preset),
|
|
Ok(_) => unreachable!(),
|
|
Err(message) => Err(message),
|
|
};
|
|
assert_eq!(preset(&["up"]), Ok(Preset::Dedicated));
|
|
assert_eq!(preset(&["up", "--preset", "workstation"]), Ok(Preset::Workstation));
|
|
assert!(preset(&["up", "--preset", "shared"]).unwrap_err().contains("unknown preset"));
|
|
}
|
|
|
|
#[test]
|
|
fn api_bind_is_explicit_and_only_for_the_api() {
|
|
let Command::Up(options) = parse_as(false, &["up", "--api-bind", "0.0.0.0"]).unwrap()
|
|
else {
|
|
panic!()
|
|
};
|
|
assert_eq!(options.ports.api, "0.0.0.0:8081");
|
|
assert_eq!(options.ports.engine, "127.0.0.1:18766");
|
|
assert!(parse_as(false, &["up", "--api-bind", "localhost"]).is_err());
|
|
assert!(parse_as(false, &["up", "--api-bind", "::"]).is_err());
|
|
}
|
|
|
|
#[test]
|
|
fn system_mode_needs_root() {
|
|
assert!(
|
|
parse_as(false, &["up", "--mode", "system"])
|
|
.unwrap_err()
|
|
.contains("root")
|
|
);
|
|
assert!(parse_as(true, &["up", "--mode", "system"]).is_ok());
|
|
let Command::Up(options) = parse_as(true, &["up"]).unwrap() else {
|
|
panic!()
|
|
};
|
|
assert_eq!(options.dirs.prefix, PathBuf::from("/opt/leleka"));
|
|
}
|
|
|
|
#[test]
|
|
fn other_commands() {
|
|
assert!(matches!(parse_as(false, &[]).unwrap(), Command::Help));
|
|
assert!(matches!(
|
|
parse_as(false, &["profiles"]).unwrap(),
|
|
Command::Profiles(None)
|
|
));
|
|
assert!(matches!(
|
|
parse_as(false, &["profiles", "show", "rtx5090-32g"]).unwrap(),
|
|
Command::Profiles(Some(_))
|
|
));
|
|
let Command::Run { config, kar_fd } = parse_as(
|
|
false,
|
|
&["run", "--config", "/s/leleka.json", "--kar-fd", "3"],
|
|
)
|
|
.unwrap() else {
|
|
panic!()
|
|
};
|
|
assert_eq!((config, kar_fd), (PathBuf::from("/s/leleka.json"), Some(3)));
|
|
assert!(parse_as(false, &["run"]).is_err());
|
|
assert!(parse_as(false, &["frobnicate"]).is_err());
|
|
assert!(matches!(
|
|
parse_as(false, &["exec-inherit", "--", "x"]).unwrap(),
|
|
Command::ExecInherit(_)
|
|
));
|
|
}
|
|
}
|