feat(deploy): API bind, --kar-fd, release packaging, install.sh and OCI recipe

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Pavlo Ratushnyi
2026-10-17 14:42:17 +02:00
co-authored by Claude Sonnet 5.5
parent d84e1a12c9
commit 5bc008122b
12 changed files with 589 additions and 51 deletions
+38 -27
View File
@@ -2,7 +2,7 @@
use crate::{
cli::{Command, Environment, USAGE, UpOptions, parse},
plan::{Context, Mode, Step, StepState, UnitScopeTag, gather, plan_steps, render_plan},
preflight::{Level, Report},
preflight::Report,
profile::{BUILTIN, Profile},
steps::{self, gather_fs, say},
supervisor,
@@ -197,6 +197,9 @@ pub async fn run_up(ctx: &Context, steps: &[Step]) -> Result<i32, String> {
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);
@@ -210,7 +213,7 @@ pub async fn run_up(ctx: &Context, steps: &[Step]) -> Result<i32, String> {
}
let options = supervisor::Options {
config: ctx.paths.run_config(),
kar_fd: None,
kar_fd: ctx.opts.kar_fd,
};
let run = supervisor::run(options);
tokio::pin!(run);
@@ -316,31 +319,41 @@ pub fn summary(ctx: &Context, config: &crate::config::RunConfig) {
eprintln!("{text}");
}
/// 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 ctx = gather(&opts, &env_var);
let status: Option<Value> = std::fs::read_to_string(ctx.paths.status_file())
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(&ctx).await;
let unit = match ctx.mode {
Mode::Systemd(_) => {
let scope = if let Mode::Systemd(scope) = ctx.mode {
scope
} else {
UnitScopeTag::User
};
let ready = steps::probe_ready_at(&paths, &api).await;
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", ctx.paths.unit_name()]);
command.args(["is-active", paths.unit_name()]);
command
.output()
.await
.ok()
.map(|o| String::from_utf8_lossy(&o.stdout).trim().to_owned())
}
_ => None,
None => None,
};
if opts.json {
println!(
@@ -353,11 +366,12 @@ async fn status(opts: UpOptions) -> i32 {
} else {
println!("ready: {ready}");
if let Some(unit) = unit {
println!("systemd unit {}: {unit}", ctx.paths.unit_name());
println!("systemd unit {}: {unit}", paths.unit_name());
}
match status {
Some(s) => println!(
"supervisor: phase {} (pid {}), engine restarts {}, updated {}\n {}",
"supervisor: phase {} (pid {}), engine restarts {}, updated {}
{}",
s["phase"].as_str().unwrap_or("?"),
s["supervisor_pid"],
s["engine_restarts"],
@@ -369,7 +383,7 @@ async fn status(opts: UpOptions) -> i32 {
),
None => println!(
"supervisor: no status file in {} (never started?)",
ctx.paths.run_dir().display()
paths.run_dir().display()
),
}
}
@@ -377,16 +391,16 @@ async fn status(opts: UpOptions) -> i32 {
}
async fn down(opts: UpOptions) -> i32 {
let ctx = gather(&opts, &env_var);
match ctx.mode {
Mode::Systemd(scope) => {
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", ctx.paths.unit_name()]).status().await {
match command.args(["stop", paths.unit_name()]).status().await {
Ok(status) if status.success() => {
eprintln!("leleka: stopped {}", ctx.paths.unit_name());
eprintln!("leleka: stopped {}", paths.unit_name());
0
}
Ok(status) => {
@@ -399,14 +413,11 @@ async fn down(opts: UpOptions) -> i32 {
}
}
}
_ => {
None => {
eprintln!(
"leleka: foreground mode: stop it with Ctrl-C (SIGINT/SIGTERM drain the API, then stop the gateway and the engine)"
"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
}
}
}
#[allow(dead_code)]
fn unused(_: Level) {}
+55 -2
View File
@@ -25,7 +25,9 @@ UP / PREFLIGHT OPTIONS
--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 on 127.0.0.1 (default 8081)
--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)
--gpu-budget-gib N override the profile's GPU memory budget
@@ -36,6 +38,8 @@ UP / PREFLIGHT OPTIONS
--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
@@ -71,6 +75,8 @@ pub struct UpOptions {
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)]
@@ -103,6 +109,7 @@ const UP_FLAGS: &[(&str, bool)] = &[
("--mode", true),
("--foreground", false),
("--api-port", true),
("--api-bind", true),
("--engine-port", true),
("--daemon-port", true),
("--gpu-budget-gib", true),
@@ -114,6 +121,7 @@ const UP_FLAGS: &[(&str, bool)] = &[
("--no-install-cublas", false),
("--timeout-s", true),
("--service-user", true),
("--kar-fd", true),
];
fn parse_flags(args: &[String], table: &[(&str, bool)]) -> Result<Flags, String> {
@@ -164,6 +172,19 @@ fn number<T: std::str::FromStr>(flags: &Flags, name: &str, default: T) -> Result
}
}
/// `--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,
@@ -235,11 +256,30 @@ fn up_options(args: &[String], env: &Environment) -> Result<UpOptions, String> {
}
}
};
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!("127.0.0.1:{}", port(&flags, "--api-port", 8081)?),
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)?),
};
@@ -265,6 +305,7 @@ fn up_options(args: &[String], env: &Environment) -> Result<UpOptions, String> {
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"),
mtp_pack: text(&flags, "--mtp-pack").map(PathBuf::from),
@@ -396,6 +437,18 @@ mod tests {
}
}
#[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!(
+31 -6
View File
@@ -110,15 +110,16 @@ impl RunConfig {
));
}
self.profile.validate()?;
for (name, address) in [
("api", &self.ports.api),
("engine", &self.ports.engine),
("daemon", &self.ports.daemon),
for (name, address, must_be_loopback) in [
("api", &self.ports.api, false),
("engine", &self.ports.engine, true),
("daemon", &self.ports.daemon, true),
] {
let parsed: std::net::SocketAddr = address
.parse()
.map_err(|_| format!("ports.{name} must be a literal ip:port"))?;
if !parsed.ip().is_loopback() {
// Only the API may leave the loopback interface (containers); the engine and the gateway never.
if must_be_loopback && !parsed.ip().is_loopback() {
return Err(format!(
"ports.{name} must be a loopback address (use an SSH tunnel for remote access)"
));
@@ -246,6 +247,17 @@ impl RunConfig {
}
}
/// The address to probe for an `ip:port` the service binds: an unspecified address (0.0.0.0, ::) is probed on
/// the loopback interface.
pub fn probe_address(bind: &str) -> Option<std::net::SocketAddr> {
let address: std::net::SocketAddr = bind.parse().ok()?;
Some(if address.ip().is_unspecified() {
std::net::SocketAddr::from(([127, 0, 0, 1], address.port()))
} else {
address
})
}
/// Pretty JSON with a trailing newline, the byte form that is written and compared.
pub fn to_file_text(value: &impl Serialize) -> String {
let mut text = serde_json::to_string_pretty(value).expect("serializable");
@@ -370,8 +382,21 @@ mod tests {
#[test]
fn validation_rejects_non_loopback_and_future_schemas() {
// Only the API may be bound beyond loopback (container use); the others never.
let mut open_api = config("rtx5090-32g");
open_api.ports.api = "0.0.0.0:8081".into();
assert!(open_api.validate().is_ok());
assert_eq!(
probe_address("0.0.0.0:8081"),
Some("127.0.0.1:8081".parse().unwrap())
);
assert_eq!(
probe_address("127.0.0.1:1"),
Some("127.0.0.1:1".parse().unwrap())
);
assert_eq!(probe_address("nonsense"), None);
let mut bad = config("rtx5090-32g");
bad.ports.api = "0.0.0.0:8081".into();
bad.ports.engine = "0.0.0.0:18766".into();
assert!(bad.validate().unwrap_err().contains("loopback"));
let mut bad = config("rtx5090-32g");
bad.schema_version = 9;
+2 -8
View File
@@ -92,10 +92,7 @@ pub fn parse_response(raw: &[u8]) -> Result<Response, String> {
fn dechunk(body: &str) -> String {
let mut out = String::new();
let mut rest = body;
while let Some((size_line, after)) = rest.split_once(
"
",
) {
while let Some((size_line, after)) = rest.split_once("\r\n") {
let Ok(size) = usize::from_str_radix(size_line.split(';').next().unwrap_or("").trim(), 16)
else {
break;
@@ -104,10 +101,7 @@ fn dechunk(body: &str) -> String {
break;
}
out.push_str(&after[..size]);
rest = after[size..].trim_start_matches(
"
",
);
rest = after[size..].trim_start_matches("\r\n");
}
out
}
+9 -1
View File
@@ -198,7 +198,12 @@ pub fn gather(opts: &UpOptions, var: &dyn Fn(&str) -> Option<String>) -> Context
profile = Err(message);
}
}
let mode = resolve_mode(opts.mode, &facts, user_session_available(var));
let choice = if opts.kar_fd.is_some() && opts.mode == ModeChoice::Auto {
ModeChoice::Foreground
} else {
opts.mode
};
let mode = resolve_mode(choice, &facts, user_session_available(var));
let service_user = if matches!(mode, Mode::Systemd(UnitScopeTag::System)) {
opts.service_user
.clone()
@@ -232,6 +237,9 @@ pub fn gather(opts: &UpOptions, var: &dyn Fn(&str) -> Option<String>) -> Context
.and_then(|m| m.as_ref().ok())
.map(Manifest::has_sm86),
service_running: service_running(&paths),
kar_fd_inherited: opts.kar_fd.is_some(),
api_bind_open: crate::config::probe_address(&opts.ports.api)
.is_some_and(|a| !a.ip().is_loopback()),
expert_profile: None,
};
let (config, report) = match &profile {
+27 -4
View File
@@ -89,6 +89,10 @@ pub struct Needs {
pub binary_has_sm86: Option<bool>,
/// Ports already owned by this deployment's own running service are not conflicts.
pub service_running: bool,
/// The public API is bound beyond the loopback interface (`--api-bind`).
pub api_bind_open: bool,
/// The sealed archive comes from the parent process (`--kar-fd`): the service does not copy it.
pub kar_fd_inherited: bool,
/// Expert profile present, and its digest is the pinned one (only meaningful for profiles that name one).
pub expert_profile: Option<ExpertProfileState>,
}
@@ -311,6 +315,15 @@ pub fn evaluate(facts: &Facts, profile: &Profile, needs: &Needs) -> Report {
// 3. RAM
let ram = &facts.memory;
// An inherited sealed archive is already counted in the parent's memory: only the engine's own need remains.
let min_available = if needs.kar_fd_inherited {
profile
.min_ram_available_bytes
.saturating_sub(ARCHIVE_BYTES)
.max(4 * GIB)
} else {
profile.min_ram_available_bytes
};
if ram.available == 0 && ram.total == 0 {
checks.push(check(
"ram",
@@ -330,23 +343,23 @@ pub fn evaluate(facts: &Facts, profile: &Profile, needs: &Needs) -> Report {
gib(profile.min_ram_total_bytes)
));
}
if ram.available < profile.min_ram_available_bytes {
if ram.available < min_available {
level = Level::Fail;
problems.push(format!(
"{} available is below the {} needed to start (kar_source={})",
gib(ram.available),
gib(profile.min_ram_available_bytes),
gib(min_available),
profile.kar_source.as_str()
));
}
if let Some(limit) = facts.cgroup_memory_max
&& limit < profile.min_ram_available_bytes
&& limit < min_available
{
level = Level::Fail;
problems.push(format!(
"the cgroup memory limit {} is below the {} needed",
gib(limit),
gib(profile.min_ram_available_bytes)
gib(min_available)
));
}
let fix = if level == Level::Fail {
@@ -609,6 +622,16 @@ pub fn evaluate(facts: &Facts, profile: &Profile, needs: &Needs) -> Report {
));
}
if needs.api_bind_open {
checks.push(check(
"api-bind",
Level::Warn,
"API listen address",
"the API is bound beyond the loopback interface; the bearer key is its only protection and there is no TLS".into(),
Some("publish the port to 127.0.0.1 only (docker run -p 127.0.0.1:8081:8081) or put a TLS proxy / SSH tunnel in front".into()),
));
}
// 10. binaries
if needs.require_binaries {
let missing: Vec<&String> = facts
+31
View File
@@ -18,6 +18,11 @@ pub fn seal_file(
Err("sealed memfd archives require Linux".into())
}
#[cfg(not(target_os = "linux"))]
pub fn check_inherited_archive(_fd: u32, _expect_bytes: u64) -> Result<(), String> {
Err("inherited descriptors require Linux".into())
}
#[cfg(not(target_os = "linux"))]
pub fn open_inherited(_fd: u32) -> Result<std::fs::File, String> {
Err("inherited descriptors require Linux".into())
@@ -133,6 +138,32 @@ mod linux {
.map_err(|e| format!("descriptor {fd} is not open in this process: {e}"))
}
/// The descriptor the parent passed with `--kar-fd` must be what the engine will accept: a regular, unlinked
/// file of the pinned length with every seal. Checked here so that the mistake surfaces before an engine start.
pub fn check_inherited_archive(fd: u32, expect_bytes: u64) -> Result<(), String> {
use std::os::unix::fs::MetadataExt;
let file = open_inherited(fd)?;
let meta = file
.metadata()
.map_err(|e| format!("cannot inspect descriptor {fd}: {e}"))?;
if !meta.is_file() || meta.nlink() != 0 || meta.len() != expect_bytes {
return Err(format!(
"descriptor {fd} is not an unlinked regular file of {expect_bytes} bytes (it has {} bytes, {} links)",
meta.len(),
meta.nlink()
));
}
if !fcntl_get_seals(&file)
.map_err(|e| format!("cannot read the seals of descriptor {fd}: {e}"))?
.contains(SEALS)
{
return Err(format!(
"descriptor {fd} lacks the WRITE, GROW, SHRINK and SEAL seals"
));
}
Ok(())
}
/// `leleka exec-inherit -- COMMAND ARG...`: standard input is the sealed archive. Move it to a descriptor
/// number >= 3 (inheritable), give the command `/dev/null` as standard input, replace `{FD}` and `exec`.
pub fn exec_inherit(args: &[String]) -> Result<Infallible, String> {
+7 -2
View File
@@ -258,10 +258,15 @@ pub async fn gather_fs(ctx: &Context) -> FsState {
}
pub async fn probe_ready(ctx: &Context) -> bool {
let Ok(key) = std::fs::read_to_string(ctx.paths.api_key()) else {
probe_ready_at(&ctx.paths, &ctx.opts.ports.api).await
}
/// `GET /ready` with the key of `paths`. False on any failure (no key, nothing listening, 503).
pub async fn probe_ready_at(paths: &Paths, api: &str) -> bool {
let Ok(key) = std::fs::read_to_string(paths.api_key()) else {
return false;
};
let Ok(address) = ctx.opts.ports.api.parse() else {
let Some(address) = crate::config::probe_address(api) else {
return false;
};
matches!(http::get(address, "/ready", Some(key.trim_end()), Duration::from_secs(3)).await, Ok(r) if r.status == 200)
+4 -1
View File
@@ -303,7 +303,10 @@ async fn run_inner(options: Options) -> Result<(), Failure> {
})
};
let (api_addr, engine_addr, daemon_addr) = (
parse("api", &config.ports.api)?,
crate::config::probe_address(&config.ports.api).ok_or(Failure {
code: 2,
message: "ports.api is not an ip:port".into(),
})?,
parse("engine", &config.ports.engine)?,
parse("daemon", &config.ports.daemon)?,
);
+66
View File
@@ -0,0 +1,66 @@
# OCI image of the Rust runtime (engine + gateway + API + `leleka`): binaries and CUDA 12 cuBLAS only.
#
# NOT in the image, by design:
# * the model (shards, KAR archive, MTP pack, tokenizer) - mount a volume at /models; never baked, never in Git;
# * the NVIDIA driver and libcuda.so.1 - injected by the NVIDIA Container Toolkit (docker run --gpus all);
# * secrets - the tokens and the API key are generated into the /state volume on the first start;
# * the sealed PTX is embedded in the binaries (sm_120, and the sm_86 companions when built with `sm86`).
#
# Build context = an unpacked release tarball (it holds bin/ and MANIFEST.json), see docs/deploy.md:
# tar -xJf leleka-VERSION-linux-x86_64.tar.xz && cd leleka-VERSION-linux-x86_64
# docker build -f /path/to/deploy/Containerfile.rust-runtime -t leleka-runtime:VERSION .
#
# Base: Ubuntu 24.04 (glibc 2.39), the oldest glibc the release is built against. Pin the digest for a release:
# docker buildx imagetools inspect ubuntu:24.04 -> --build-arg BASE=ubuntu:24.04@sha256:...
ARG BASE=ubuntu:24.04
# --- stage 1: the pinned NVIDIA cuBLAS 12.9.1.4 redistributable, checksum-verified by BuildKit ---------------
FROM ${BASE} AS cublas
ARG CUBLAS_URL=https://developer.download.nvidia.com/compute/cuda/redist/libcublas/linux-x86_64/libcublas-linux-x86_64-12.9.1.4-archive.tar.xz
ARG CUBLAS_SHA256=546addc4a9d82b8f23aa9ba9274b6bc0429a63008a31c759884ac24880796057
ADD --checksum=sha256:${CUBLAS_SHA256} ${CUBLAS_URL} /cublas.tar.xz
RUN mkdir /out \
&& tar -xJf /cublas.tar.xz -C /out --strip-components=1 --wildcards '*/lib/libcublas.so.12*' '*/lib/libcublasLt.so.12*' '*/LICENSE' \
&& mv /out/LICENSE /out/lib/LICENSE-cublas.txt
# --- stage 2: the runtime ---------------------------------------------------------------------------------------
FROM ${BASE}
ARG VERSION=dev
LABEL org.opencontainers.image.title="leleka-runtime" \
org.opencontainers.image.description="Leleka runtime: Rust CUDA engine, gateway and API. Model volume mounted externally." \
org.opencontainers.image.version="${VERSION}"
RUN groupadd --gid 10001 leleka \
&& useradd --uid 10001 --gid 10001 --no-create-home --home-dir /state --shell /usr/sbin/nologin leleka \
&& install -d -m 0755 /opt/leleka/bin /opt/leleka/lib/cublas /usr/share/leleka \
&& install -d -m 0700 -o leleka -g leleka /state \
&& install -d -m 0755 -o leleka -g leleka /models
COPY --chmod=0755 bin/ /opt/leleka/bin/
COPY --from=cublas --chmod=0644 /out/lib/ /opt/leleka/lib/cublas/
COPY --chmod=0644 MANIFEST.json PROVENANCE.json SHA256SUMS /usr/share/leleka/
COPY --chmod=0755 install.sh /usr/share/leleka/install.sh
# `leleka up` finds libcublas.so.12 in PREFIX/lib/cublas on its own and records it in the service environment.
# The paths below are the defaults of `leleka` (--prefix / --state-dir / --assets).
ENV LELEKA_PREFIX=/opt/leleka \
LELEKA_STATE=/state \
LELEKA_ASSETS=/models \
HOME=/state \
NVIDIA_VISIBLE_DEVICES=all \
NVIDIA_DRIVER_CAPABILITIES=compute,utility
USER 10001:10001
WORKDIR /state
VOLUME ["/models", "/state"]
EXPOSE 8081
# Ready = the API answers /ready with the key kept in /state. The first start downloads, verifies and converts
# the model (hours), so the start period is long; a restart with a populated volume is minutes.
HEALTHCHECK --interval=30s --timeout=10s --start-period=4h --retries=3 \
CMD ["/opt/leleka/bin/leleka", "status"]
# SIGTERM -> `leleka` drains the API, then stops the gateway and the engine.
STOPSIGNAL SIGTERM
ENTRYPOINT ["/opt/leleka/bin/leleka"]
CMD ["up", "--foreground", "--no-install-cublas", "--api-bind", "0.0.0.0", "--timeout-s", "86400"]
+34
View File
@@ -0,0 +1,34 @@
#!/bin/sh
# One command on a fresh Linux CUDA machine (or WSL2): verify this release, then hand over to `leleka up`.
#
# tar -xJf leleka-VERSION-linux-x86_64.tar.xz && cd leleka-VERSION-linux-x86_64
# sudo ./install.sh --assets /data/leleka # systemd service, starts at boot
# ./install.sh --assets ~/leleka --foreground # WSL2 without systemd, or a terminal
# ./install.sh --dry-run # print the plan, change nothing
#
# Every option is passed to `leleka up` (see `./bin/leleka --help`). Nothing here needs Python.
set -eu
here=$(cd "$(dirname "$0")" && pwd)
cd "$here"
case "$(uname -s)/$(uname -m)" in
Linux/x86_64) ;;
*) echo "install.sh: this release is for Linux x86_64 (WSL2 included), not $(uname -s)/$(uname -m)" >&2; exit 1 ;;
esac
[ -x ./bin/leleka ] || { echo "install.sh: ./bin/leleka is missing; run this script from the unpacked release directory" >&2; exit 1; }
if [ -f SHA256SUMS ]; then
if command -v sha256sum >/dev/null 2>&1; then
echo "install.sh: verifying the release files against SHA256SUMS ..." >&2
sha256sum --quiet -c SHA256SUMS || {
echo "install.sh: a file does not match SHA256SUMS; download the release again" >&2
exit 1
}
else
echo "install.sh: sha256sum not found, skipping the integrity check" >&2
fi
fi
exec ./bin/leleka up "$@"
+285
View File
@@ -0,0 +1,285 @@
#!/usr/bin/env python3
"""Assemble the Leleka release tarball (offline build tooling; production serving has no Python dependency).
Inputs: a release build of the seven binaries (`cargo build --release --locked ...`, see docs/deploy.md), the
repository tree (for templates, sealed PTX and docs) and a provenance record. Output, in --out:
leleka-VERSION-COMMIT12-linux-x86_64.tar.xz bin/ share/ MANIFEST.json PROVENANCE.json SHA256SUMS install.sh
leleka-VERSION-COMMIT12-linux-x86_64.tar.xz.sha256
The provenance record names the git commit, whether the tree was clean, and the local changes to the imported
Strata source relative to the upstream commit in docs/upstream.md. Builds happen in WSL/Linux from an exported tree
(no .git there), so the record is produced where git exists:
python3 scripts/package-release.py provenance --repo . --out provenance.json
python3 scripts/package-release.py package --repo . --target-dir ~/target --provenance provenance.json --out dist
`package` alone also works inside a git checkout (it computes the provenance itself). Nothing here downloads
anything; cuBLAS is not bundled (the NVIDIA redistributable is fetched by `leleka up`, or add --with-cublas DIR).
"""
import argparse
import datetime
import hashlib
import io
import json
import os
from pathlib import Path
import re
import shutil
import subprocess
import sys
import tarfile
RUNTIME_BINARIES = ['leleka', 'strata-next', 'leleka-inference', 'leleka-daemon', 'leleka-cli', 'leleka-seal-exec']
TEMPLATES = [
'deploy/rust-runtime/leleka-daemon.service',
'deploy/rust-runtime/leleka-inference.service',
'deploy/rust-runtime/runtime.env.example',
]
UPSTREAM_DOC = 'docs/upstream.md'
SUBTREE = 'engine/strata'
def run(args, cwd=None, check=True):
result = subprocess.run([str(a) for a in args], cwd=cwd, capture_output=True, text=True)
if check and result.returncode != 0:
raise RuntimeError(f'{" ".join(map(str, args))} failed: {result.stderr.strip()}')
return result.stdout.strip()
def sha256(path):
digest = hashlib.sha256()
with open(path, 'rb') as source:
for chunk in iter(lambda: source.read(1 << 20), b''):
digest.update(chunk)
return digest.hexdigest()
def upstream_record(repo):
text = (repo / UPSTREAM_DOC).read_text(encoding='utf-8')
url = re.search(r'Upstream repository URL \| (\S+)', text)
sha = re.search(r'Upstream commit SHA \| `([0-9a-f]{40})`', text)
if not url or not sha:
raise RuntimeError(f'{UPSTREAM_DOC} does not name the upstream repository and commit')
return url.group(1), sha.group(1)
def provenance(repo, allow_dirty=False):
"""Git commit, cleanliness, and the local changes to engine/strata relative to the recorded upstream commit."""
url, upstream_sha = upstream_record(repo)
commit = run(['git', '-C', repo, 'rev-parse', 'HEAD'])
status = run(['git', '-C', repo, 'status', '--porcelain', '--untracked-files=normal'])
dirty_files = [line for line in status.splitlines() if line]
# Windows checkouts report CRLF-only differences as modified; hash what git would actually record.
diff_digest = hashlib.sha256(run(['git', '-C', repo, 'diff', 'HEAD', '--binary'], check=False).encode()).hexdigest() if dirty_files else None
if dirty_files and not allow_dirty:
raise RuntimeError(f'the tree has {len(dirty_files)} uncommitted change(s); commit them or pass --allow-dirty (the release is then marked dirty)')
# Import commit(s): the first commit that touched the subtree.
history = run(['git', '-C', repo, 'log', '--format=%H %s', '--reverse', '--', SUBTREE]).splitlines()
import_commit = history[0].split(' ', 1)[0] if history else None
subtree_tree = run(['git', '-C', repo, 'rev-parse', f'HEAD:{SUBTREE}'])
record = {
'schema_version': 1,
'git_commit': commit,
'git_describe': run(['git', '-C', repo, 'describe', '--always', '--dirty', '--abbrev=12'], check=False),
'git_branch': run(['git', '-C', repo, 'rev-parse', '--abbrev-ref', 'HEAD'], check=False),
'dirty': bool(dirty_files),
'dirty_file_count': len(dirty_files),
'dirty_diff_sha256': diff_digest,
'cargo_lock_sha256': sha256(repo / 'Cargo.lock'),
'strata': {
'upstream_url': url,
'upstream_commit': upstream_sha,
'subtree_path': SUBTREE,
'subtree_tree_at_head': subtree_tree,
'import_commit': import_commit,
'commits_touching_subtree': len(history),
'local_patch_commits': [line.split(' ', 1) for line in history[1:]][:200],
},
}
# Local changes since the import (the committed ones), and against the upstream tree when it is present.
if import_commit:
stat = run(['git', '-C', repo, 'diff', '--shortstat', f'{import_commit}', 'HEAD', '--', SUBTREE], check=False)
diff = run(['git', '-C', repo, 'diff', '--binary', f'{import_commit}', 'HEAD', '--', SUBTREE], check=False)
record['strata']['diff_since_import'] = {
'shortstat': stat or 'no change',
'diff_sha256': hashlib.sha256(diff.encode()).hexdigest(),
}
have_upstream = subprocess.run(['git', '-C', str(repo), 'cat-file', '-e', f'{upstream_sha}^{{commit}}'], capture_output=True).returncode == 0
if have_upstream:
upstream_tree = run(['git', '-C', repo, 'rev-parse', f'{upstream_sha}^{{tree}}'])
record['strata']['diff_vs_upstream'] = {
'upstream_tree': upstream_tree,
'shortstat': run(['git', '-C', repo, 'diff', '--shortstat', upstream_tree, f'HEAD:{SUBTREE}'], check=False) or 'identical',
}
else:
record['strata']['diff_vs_upstream'] = {
'available': False,
'why': f'the upstream commit {upstream_sha} is not in this repository (fetch the strata-upstream remote to compare)',
}
return record
def version_of(repo):
text = (repo / 'crates/deploy/Cargo.toml').read_text(encoding='utf-8')
return re.search(r'^version = "([^"]+)"', text, re.M).group(1)
def tool_version(*args):
return run(args, check=False).splitlines()[0] if run(args, check=False) else None
def add_tree(tar, source_dir, arc_prefix, epoch):
for path in sorted(source_dir.rglob('*')):
if path.is_file():
add_file(tar, path, f'{arc_prefix}/{path.relative_to(source_dir).as_posix()}', epoch, executable=os.access(path, os.X_OK))
def add_file(tar, path, name, epoch, executable=False, data=None):
info = tarfile.TarInfo(name)
payload = data if data is not None else path.read_bytes()
info.size = len(payload)
info.mtime = epoch
info.mode = 0o755 if executable else 0o644
info.uid = info.gid = 0
info.uname = info.gname = 'root'
tar.addfile(info, io.BytesIO(payload))
def package(args):
repo = Path(args.repo).resolve()
target = Path(args.target_dir).expanduser().resolve() / 'release'
out = Path(args.out).resolve()
out.mkdir(parents=True, exist_ok=True)
if args.provenance:
record = json.loads(Path(args.provenance).read_text(encoding='utf-8'))
else:
record = provenance(repo, args.allow_dirty)
if record.get('dirty') and not args.allow_dirty:
raise RuntimeError('the provenance record says the tree was dirty; pass --allow-dirty to package it anyway (the manifest keeps the mark)')
commit = record['git_commit']
version = args.version or version_of(repo)
features = sorted(set(args.feature or ['sm86']))
name = f'leleka-{version}-{commit[:12]}-linux-x86_64'
epoch = int(os.environ.get('SOURCE_DATE_EPOCH', datetime.datetime.now(datetime.timezone.utc).timestamp()))
members = {} # archive path -> (bytes, executable)
binaries = {}
for binary in RUNTIME_BINARIES:
path = target / binary
if not path.is_file():
raise RuntimeError(f'{path} is missing; build it first (docs/deploy.md, "Build a release")')
data = path.read_bytes()
members[f'bin/{binary}'] = (data, True)
binaries[binary] = hashlib.sha256(data).hexdigest()
for template in TEMPLATES:
members[f'share/leleka/templates/{Path(template).name}'] = ((repo / template).read_bytes(), False)
for profile in sorted((repo / 'deploy/rust-runtime/profiles').glob('*.json')):
members[f'share/leleka/profiles/{profile.name}'] = (profile.read_bytes(), False)
for doc in ['docs/deploy.md', 'docs/upstream.md', 'docs/rust-runtime-run.md', 'docs/laptop-profile.md', 'docs/sm86-assets.md']:
if (repo / doc).is_file():
members[f'share/leleka/docs/{Path(doc).name}'] = ((repo / doc).read_bytes(), False)
members['install.sh'] = ((repo / 'deploy/rust-runtime/install.sh').read_bytes(), True)
ptx_lines = []
if not args.no_ptx:
sets = {'sm_120': [p for p in (repo / 'crates/cuda-driver').rglob('*.ptx') if 'ptx-sm86' not in p.parts],
'sm_86': sorted((repo / 'crates/cuda-driver/ptx-sm86').glob('*.ptx'))}
for arch, files in sets.items():
for path in sorted(files):
data = path.read_bytes()
members[f'share/leleka/ptx/{arch}/{path.name}'] = (data, False)
ptx_lines.append(f'{hashlib.sha256(data).hexdigest()} {arch}/{path.name}')
if (repo / 'crates/cuda-driver/ptx-sm86/MANIFEST.json').is_file():
members['share/leleka/ptx/sm_86-MANIFEST.json'] = ((repo / 'crates/cuda-driver/ptx-sm86/MANIFEST.json').read_bytes(), False)
members['share/leleka/ptx/SHA256SUMS'] = (('\n'.join(ptx_lines) + '\n').encode(), False)
if args.with_cublas:
for path in sorted(Path(args.with_cublas).glob('libcublas*.so*')):
members[f'lib/cublas/{path.name}'] = (path.read_bytes(), False)
manifest = {
'schema_version': 1,
'name': 'leleka',
'version': version,
'git_commit': commit,
'dirty': bool(record.get('dirty')),
'features': features,
'binaries': binaries,
'built_with': {
'rustc': tool_version('rustc', '--version'),
'cargo': tool_version('cargo', '--version'),
'host': tool_version('uname', '-sr'),
'glibc': tool_version('ldd', '--version'),
},
'runtime_requirements': {
'os': 'linux x86_64, glibc',
'nvidia_driver_min': 595,
'cublas': 'libcublas.so.12 and libcublasLt.so.12 (CUDA 12; pinned redistributable 12.9.1.4 is fetched by `leleka up`)' if not args.with_cublas else 'bundled in lib/cublas (CUDA 12.9.1.4 redistributable, NVIDIA license applies)',
'gpu_architectures': ['sm_120'] + (['sm_86..sm_119 (companion PTX, feature sm86)'] if 'sm86' in features else []),
},
'ptx_included': not args.no_ptx,
'created_utc': datetime.datetime.fromtimestamp(epoch, datetime.timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ'),
}
members['MANIFEST.json'] = ((json.dumps(manifest, indent=2, sort_keys=True) + '\n').encode(), False)
members['PROVENANCE.json'] = ((json.dumps(record, indent=2, sort_keys=True) + '\n').encode(), False)
sums = ''.join(f'{hashlib.sha256(data).hexdigest()} {path}\n' for path, (data, _) in sorted(members.items()))
members['SHA256SUMS'] = (sums.encode(), False)
tarball = out / f'{name}.tar'
with tarfile.open(tarball, 'w', format=tarfile.PAX_FORMAT) as tar:
for path, (data, executable) in sorted(members.items()):
add_file(tar, None, f'{name}/{path}', epoch, executable, data)
compressed = out / f'{name}.tar.xz'
import lzma
with open(tarball, 'rb') as source, lzma.open(compressed, 'wb', preset=6) as target_file:
shutil.copyfileobj(source, target_file)
tarball.unlink()
digest = sha256(compressed)
(out / f'{name}.tar.xz.sha256').write_text(f'{digest} {compressed.name}\n', encoding='ascii')
# Verify what was written: the member list matches SHA256SUMS byte for byte.
with tarfile.open(compressed, 'r:xz') as tar:
names = {m.name for m in tar.getmembers() if m.isfile()}
sums_member = tar.extractfile(f'{name}/SHA256SUMS').read().decode()
for line in sums_member.splitlines():
expected, rel = line.split(' ', 1)
actual = hashlib.sha256(tar.extractfile(f'{name}/{rel}').read()).hexdigest()
if actual != expected:
raise RuntimeError(f'verification failed for {rel}')
assert names == {f'{name}/{p}' for p in members}
print(json.dumps({'tarball': str(compressed), 'sha256': digest, 'bytes': compressed.stat().st_size, 'files': len(members), 'git_commit': commit, 'dirty': manifest['dirty'], 'features': features}, indent=2))
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
sub = parser.add_subparsers(dest='command', required=True)
prov = sub.add_parser('provenance', help='write the provenance record of a git checkout')
prov.add_argument('--repo', default='.')
prov.add_argument('--out', required=True)
prov.add_argument('--allow-dirty', action='store_true')
pack = sub.add_parser('package', help='assemble the tarball')
pack.add_argument('--repo', default='.')
pack.add_argument('--target-dir', required=True, help='cargo target dir that holds release/<binaries>')
pack.add_argument('--out', default='dist')
pack.add_argument('--provenance', help='record made by the `provenance` command (needed when the tree has no .git)')
pack.add_argument('--version')
pack.add_argument('--feature', action='append', help='Cargo feature the runtime binaries were built with (repeatable; default: sm86)')
pack.add_argument('--allow-dirty', action='store_true')
pack.add_argument('--no-ptx', action='store_true', help='omit the sealed PTX files (they are embedded in the binaries anyway)')
pack.add_argument('--with-cublas', help='directory with libcublas.so.12* / libcublasLt.so.12* to bundle')
args = parser.parse_args()
try:
if args.command == 'provenance':
record = provenance(Path(args.repo).resolve(), args.allow_dirty)
Path(args.out).write_text(json.dumps(record, indent=2, sort_keys=True) + '\n', encoding='utf-8')
print(f'wrote {args.out}: {record["git_commit"]} dirty={record["dirty"]}')
else:
package(args)
except (RuntimeError, OSError) as error:
print(f'package-release: {error}', file=sys.stderr)
sys.exit(1)
if __name__ == '__main__':
main()