Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
776 lines
33 KiB
Rust
776 lines
33 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 reconfigure [OPTIONS] change the inference settings of the running engine without reloading the model
|
|
leleka down [OPTIONS] stop the systemd service
|
|
leleka service install|uninstall|status|start|stop [OPTIONS]
|
|
keep the service running without a terminal: a Task Scheduler task at logon on Windows (native route),
|
|
the user unit in the distribution (+ a task that keeps the VM alive) on the WSL route
|
|
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)
|
|
|
|
RECONFIGURE OPTIONS (any of them; the call waits for the request in flight, the engine reopens its serve stack in a few seconds, the weights stay
|
|
loaded; a refused change keeps the previous settings; --kv-resident is fixed per process and needs `leleka up`)
|
|
--context-tokens N tokens of context (1..262144)
|
|
--prefill-capacity N prefill chunk: 256 512 1024 2048 3072 4096 6144 8192
|
|
--kv-resident N only the value in force is accepted (the K/V window is fixed per process; restart to change it)
|
|
--prefix-cache-mib auto|off|N host-RAM budget of the cross-session prefix cache
|
|
--prefix-cache-tail off|prompt|reply request-end checkpoints
|
|
--prefix-cache-block N tokens per prefix block (multiple of 256; 0 = the prefill chunk)
|
|
--prefix-retention-min N minutes an idle cached session is kept (0 = no limit)
|
|
--cpu-workers N CPU expert workers (1..15)
|
|
--spec-min-p P draft-probability floor (0..1)
|
|
--gpu-budget-gib N VRAM budget of the engine (1..1024). Fixed when the CUDA context is created: the supervisor restarts
|
|
the engine process (the model loads again, minutes), the gateway and the API keep their ports
|
|
--preset dedicated|workstation resource preset (same restart); refused when the host cannot hold it
|
|
--persist keep the change across restarts of the service (writes leleka.json)
|
|
--assets/--state-dir/--prefix/--api-port/--json as for `up`; `leleka status` prints the settings in force
|
|
|
|
WINDOWS
|
|
leleka.exe runs the engine in one of two ways (docs/windows.md):
|
|
--wsl / --native route for up, preflight, verify, status, reconfigure, down: `--wsl` (the default for `up`) runs the Linux
|
|
`leleka` inside WSL2 through wsl.exe and talks to it over loopback HTTP; `--native` runs engine, gateway
|
|
and API as Windows processes (the model volume must already be on a Windows disk)
|
|
--wsl-distro NAME WSL2 distribution to use (default: the default one that is not Docker's) [$LELEKA_WSL_DISTRO]
|
|
--wsl-bin PATH the Linux `leleka` inside the distribution (default: searched in the usual places)
|
|
leleka doctor what this Windows machine offers: GPU, RAM, .wslconfig advice, WSL distributions, the Linux leleka
|
|
Paths for the WSL route may be Linux paths (/home/me/leleka), \\\\wsl.localhost\\Ubuntu\\... paths or Windows paths (C:\\...; they become
|
|
/mnt/c/..., which is far too slow for the model, so --assets is refused there). Native defaults live in %LOCALAPPDATA%\\leleka.
|
|
|
|
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>,
|
|
}
|
|
|
|
/// What `leleka reconfigure` was asked to change.
|
|
#[derive(Clone, Debug, Default, PartialEq)]
|
|
pub struct ReconfigureArgs {
|
|
/// Runtime settings (the members of `POST /v1/reconfigure`): the engine reopens its serve stack.
|
|
pub settings: serde_json::Map<String, serde_json::Value>,
|
|
/// New VRAM budget: needs a new engine process.
|
|
pub gpu_budget_gib: Option<u64>,
|
|
/// New resource preset: needs a new engine process.
|
|
pub preset: Option<crate::resources::Preset>,
|
|
/// Keep the change across restarts of the service (`leleka.json`).
|
|
pub persist: bool,
|
|
}
|
|
|
|
impl ReconfigureArgs {
|
|
/// The budget and the preset are fixed when the CUDA context is created.
|
|
pub fn needs_restart(&self) -> bool {
|
|
self.gpu_budget_gib.is_some() || self.preset.is_some()
|
|
}
|
|
}
|
|
|
|
/// `leleka service ACTION`: keep the service running without a terminal (`service.rs`).
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
pub enum ServiceAction {
|
|
Install,
|
|
Uninstall,
|
|
Status,
|
|
Start,
|
|
Stop,
|
|
/// WSL route only: the logon task runs this to start the unit and keep the WSL2 VM alive.
|
|
Hold,
|
|
}
|
|
|
|
#[derive(Debug)]
|
|
pub enum Command {
|
|
Service(ServiceAction, UpOptions),
|
|
Up(UpOptions),
|
|
Preflight(UpOptions),
|
|
Run {
|
|
config: PathBuf,
|
|
kar_fd: Option<u32>,
|
|
},
|
|
ExecInherit(Vec<String>),
|
|
Status(UpOptions),
|
|
Down(UpOptions),
|
|
/// The options locate the running service; the arguments are what to change.
|
|
Reconfigure(UpOptions, ReconfigureArgs),
|
|
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>,
|
|
}
|
|
|
|
/// An absolute path; on Windows also a rooted one without a drive (`\data` or `/data`, relative to the current drive).
|
|
fn is_absolute(path: &std::path::Path) -> bool {
|
|
path.is_absolute() || (cfg!(windows) && path.has_root())
|
|
}
|
|
|
|
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 !is_absolute(&path) {
|
|
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 cfg!(windows) && matches!(mode, ModeChoice::System | ModeChoice::User) {
|
|
return Err("--mode system/user need systemd; on Windows use --foreground (or --mode none to only prepare)".into());
|
|
}
|
|
if mode == ModeChoice::System && !env.root {
|
|
return Err("--mode system needs root (use sudo), or --mode user / --foreground".into());
|
|
}
|
|
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
|
|
&& !is_absolute(dir)
|
|
{
|
|
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
|
|
},
|
|
})
|
|
}
|
|
|
|
/// The settings flags of `leleka reconfigure` (member of the settings document, takes a value).
|
|
const RECONFIGURE_FLAGS: &[(&str, &str)] = &[
|
|
("--context-tokens", "context_tokens"),
|
|
("--prefill-capacity", "prefill_capacity"),
|
|
("--kv-resident", "kv_resident"),
|
|
("--prefix-cache-mib", "prefix_cache_mib"),
|
|
("--prefix-cache-tail", "prefix_cache_tail"),
|
|
("--prefix-cache-block", "prefix_cache_block"),
|
|
("--prefix-retention-min", "prefix_retention_min"),
|
|
("--cpu-workers", "cpu_workers"),
|
|
("--spec-min-p", "spec_min_p"),
|
|
];
|
|
|
|
/// The settings flags of a `reconfigure` command line: returns the other arguments (they locate the service) and the JSON
|
|
/// document the engine validates. Numbers stay numbers; the two cache members stay text.
|
|
pub fn split_reconfigure(args: &[String]) -> Result<(Vec<String>, ReconfigureArgs), String> {
|
|
let mut rest: Vec<String> = Vec::new();
|
|
let mut document = serde_json::Map::new();
|
|
let mut extra = ReconfigureArgs::default();
|
|
let mut index = 0;
|
|
while index < args.len() {
|
|
let arg = &args[index];
|
|
let (name, inline) = match arg.split_once('=') {
|
|
Some((name, value)) if name.starts_with("--") => (name, Some(value.to_owned())),
|
|
_ => (arg.as_str(), None),
|
|
};
|
|
if name == "--persist" {
|
|
if inline.is_some() {
|
|
return Err("--persist takes no value".into());
|
|
}
|
|
extra.persist = true;
|
|
index += 1;
|
|
continue;
|
|
}
|
|
if name == "--gpu-budget-gib" || name == "--preset" {
|
|
let value = match inline {
|
|
Some(value) => value,
|
|
None => {
|
|
index += 1;
|
|
args.get(index).ok_or_else(|| format!("{name} needs a value"))?.clone()
|
|
}
|
|
};
|
|
if name == "--preset" {
|
|
if extra.preset.replace(crate::resources::Preset::parse(&value)?).is_some() {
|
|
return Err(format!("{name} given twice"));
|
|
}
|
|
} else {
|
|
let gib: u64 = value.parse().map_err(|_| format!("{name} needs a whole number of GiB"))?;
|
|
if !(1..=1024).contains(&gib) {
|
|
return Err(format!("{name} must be 1..1024"));
|
|
}
|
|
if extra.gpu_budget_gib.replace(gib).is_some() {
|
|
return Err(format!("{name} given twice"));
|
|
}
|
|
}
|
|
index += 1;
|
|
continue;
|
|
}
|
|
if let Some((_, member)) = RECONFIGURE_FLAGS.iter().find(|(flag, _)| *flag == name) {
|
|
let value = match inline {
|
|
Some(value) => value,
|
|
None => {
|
|
index += 1;
|
|
args.get(index).ok_or_else(|| format!("{name} needs a value"))?.clone()
|
|
}
|
|
};
|
|
let json = match *member {
|
|
"prefix_cache_mib" | "prefix_cache_tail" => serde_json::Value::String(value),
|
|
"spec_min_p" => serde_json::Value::from(value.parse::<f64>().map_err(|_| format!("{name} needs a number"))?),
|
|
_ => serde_json::Value::from(value.parse::<i64>().map_err(|_| format!("{name} needs a whole number"))?),
|
|
};
|
|
if document.insert((*member).to_owned(), json).is_some() {
|
|
return Err(format!("{name} given twice"));
|
|
}
|
|
} else {
|
|
rest.push(arg.clone());
|
|
}
|
|
index += 1;
|
|
}
|
|
if document.is_empty() && !extra.needs_restart() {
|
|
return Err("leleka reconfigure needs at least one setting; see `leleka --help`".into());
|
|
}
|
|
extra.settings = document;
|
|
Ok((rest, extra))
|
|
}
|
|
|
|
/// `leleka reconfigure`: pull the settings flags out, let `up_options` read the rest (where the service lives).
|
|
fn reconfigure_command(args: &[String], env: &Environment) -> Result<Command, String> {
|
|
let (rest, extra) = split_reconfigure(args)?;
|
|
let options = up_options(&rest, env)?;
|
|
Ok(Command::Reconfigure(options, extra))
|
|
}
|
|
|
|
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),
|
|
"reconfigure" => reconfigure_command(rest, env),
|
|
"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()?,
|
|
})
|
|
}
|
|
"service" => {
|
|
let Some((action, rest)) = rest.split_first() else {
|
|
return Err("usage: leleka service install|uninstall|status|start|stop".into());
|
|
};
|
|
let action = match action.as_str() {
|
|
"install" => ServiceAction::Install,
|
|
"uninstall" => ServiceAction::Uninstall,
|
|
"status" => ServiceAction::Status,
|
|
"start" => ServiceAction::Start,
|
|
"stop" => ServiceAction::Stop,
|
|
"hold" => ServiceAction::Hold,
|
|
other => return Err(format!("unknown service action {other:?}; use install, uninstall, status, start or stop")),
|
|
};
|
|
up_options(rest, env).map(|options| Command::Service(action, options))
|
|
}
|
|
"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,
|
|
},
|
|
)
|
|
}
|
|
|
|
#[cfg(unix)]
|
|
#[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 reconfigure_collects_the_settings_and_locates_the_service_with_the_up_flags() {
|
|
let Ok(Command::Reconfigure(options, args)) = parse_as(
|
|
false,
|
|
&["reconfigure", "--context-tokens", "65536", "--prefix-cache-tail=reply", "--prefix-cache-mib", "20480", "--spec-min-p", "0.5", "--state-dir", "/var/lib/leleka/state"],
|
|
) else {
|
|
panic!("reconfigure did not parse");
|
|
};
|
|
assert_eq!(options.dirs.state, std::path::PathBuf::from("/var/lib/leleka/state"));
|
|
assert!(!args.needs_restart() && !args.persist);
|
|
let value = serde_json::Value::Object(args.settings);
|
|
assert_eq!(value["context_tokens"], 65536);
|
|
assert_eq!(value["prefix_cache_tail"], "reply");
|
|
assert_eq!(value["prefix_cache_mib"], "20480");
|
|
assert_eq!(value["spec_min_p"], 0.5);
|
|
assert!(parse_as(false, &["reconfigure"]).unwrap_err().contains("at least one setting"));
|
|
assert!(parse_as(false, &["reconfigure", "--cpu-workers", "many"]).unwrap_err().contains("whole number"));
|
|
assert!(parse_as(false, &["reconfigure", "--cpu-workers", "4", "--cpu-workers", "5"]).unwrap_err().contains("twice"));
|
|
}
|
|
|
|
#[test]
|
|
fn reconfigure_takes_the_budget_the_preset_and_persist_out_of_the_up_flags() {
|
|
let Ok(Command::Reconfigure(options, args)) = parse_as(
|
|
false,
|
|
&["reconfigure", "--gpu-budget-gib", "24", "--preset=workstation", "--persist", "--context-tokens", "65536", "--state-dir", "/s"],
|
|
) else {
|
|
panic!("reconfigure did not parse");
|
|
};
|
|
assert!(args.needs_restart() && args.persist);
|
|
assert_eq!(args.gpu_budget_gib, Some(24));
|
|
assert_eq!(args.preset, Some(crate::resources::Preset::Workstation));
|
|
assert_eq!(args.settings["context_tokens"], 65536);
|
|
// they are the restart request, not `up` options: the service is located by the remaining flags only
|
|
assert_eq!(options.dirs.state, std::path::PathBuf::from("/s"));
|
|
assert_eq!(options.gpu_budget_gib, None);
|
|
assert_eq!(options.preset, crate::resources::Preset::Dedicated);
|
|
// the budget or the preset alone is a request; nothing at all is not
|
|
assert!(matches!(parse_as(false, &["reconfigure", "--preset", "dedicated"]), Ok(Command::Reconfigure(..))));
|
|
assert!(matches!(parse_as(false, &["reconfigure", "--gpu-budget-gib", "20"]), Ok(Command::Reconfigure(..))));
|
|
assert!(parse_as(false, &["reconfigure", "--persist"]).unwrap_err().contains("at least one setting"));
|
|
assert!(parse_as(false, &["reconfigure", "--gpu-budget-gib", "0"]).unwrap_err().contains("1..1024"));
|
|
assert!(parse_as(false, &["reconfigure", "--gpu-budget-gib", "many"]).unwrap_err().contains("whole number"));
|
|
assert!(parse_as(false, &["reconfigure", "--preset", "shared"]).unwrap_err().contains("unknown preset"));
|
|
assert!(parse_as(false, &["reconfigure", "--persist=yes", "--cpu-workers", "2"]).unwrap_err().contains("no value"));
|
|
assert!(parse_as(false, &["reconfigure", "--gpu-budget-gib", "20", "--gpu-budget-gib", "21"]).unwrap_err().contains("twice"));
|
|
}
|
|
|
|
#[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());
|
|
}
|
|
|
|
#[cfg(windows)]
|
|
#[test]
|
|
fn windows_has_no_systemd_modes_and_defaults_to_the_profile() {
|
|
assert!(parse_as(false, &["up", "--mode", "system"]).unwrap_err().contains("--foreground"));
|
|
assert!(parse_as(false, &["up", "--mode=user"]).is_err());
|
|
let Command::Up(options) = parse_as(false, &["up"]).unwrap() else {
|
|
panic!()
|
|
};
|
|
assert!(options.dirs.state.ends_with("leleka/state"), "{:?}", options.dirs);
|
|
assert_eq!(options.mode, ModeChoice::Auto);
|
|
assert!(parse_as(false, &["up", "--assets", "D:\\models"]).is_ok());
|
|
assert!(parse_as(false, &["up", "--assets", "models"]).is_err());
|
|
}
|
|
|
|
#[cfg(unix)]
|
|
#[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(_)
|
|
));
|
|
}
|
|
}
|