Files
leleka/crates/deploy/src/steps.rs
T

1176 lines
40 KiB
Rust

//! Execution of the plan. Every step is idempotent and can be repeated after a crash: downloads resume
//! (`.part` files), verified assets carry a stamp (path, size, mtime) so a re-run does not hash 140 GB again,
//! generated files are rewritten only when their content changes, and secrets are never rotated.
use crate::{
config::{
ENV_HEADER, GATEWAY_TOKEN_ENV, RUNTIME_TOKEN_ENV, RunConfig, merge_env, new_token,
to_file_text,
},
facts::parse_env_file,
http,
layout::{BINARIES, MANIFEST, MTP_FILES, Paths},
plan::{
CUBLAS_SHA256, CUBLAS_URL, CUBLAS_VERSION, Context, FsState, Mode, Step, StepState,
UnitScopeTag, plan_steps,
},
profile::ARCHIVE_BYTES,
supervisor::{valid_token, write_private},
units,
};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::{
io::Read,
path::{Path, PathBuf},
process::Stdio,
time::{Duration, Instant, SystemTime, UNIX_EPOCH},
};
use tokio::{io::AsyncReadExt, io::AsyncWriteExt, process::Command};
pub fn say(message: &str) {
eprintln!("leleka: {message}");
}
// ---------------------------------------------------------------------------------------------------------------
// stamps
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct FileStamp {
pub path: String,
pub size: u64,
pub mtime_ns: u128,
}
#[derive(Debug, Serialize, Deserialize)]
struct StampFile {
leleka_version: String,
what: String,
files: Vec<FileStamp>,
verified_unix: u64,
}
pub fn file_stamp(path: &Path) -> Option<FileStamp> {
let meta = std::fs::metadata(path).ok().filter(|m| m.is_file())?;
let mtime = meta
.modified()
.ok()?
.duration_since(UNIX_EPOCH)
.ok()?
.as_nanos();
Some(FileStamp {
path: path.display().to_string(),
size: meta.len(),
mtime_ns: mtime,
})
}
pub fn stamp_path(paths: &Paths, name: &str) -> PathBuf {
paths.stamps().join(format!("{name}.json"))
}
/// True when `stamp` exists and every listed file still has the stamped size and mtime.
pub fn stamp_current(stamp: &Path, files: &[PathBuf]) -> bool {
let Ok(text) = std::fs::read_to_string(stamp) else {
return false;
};
let Ok(stored) = serde_json::from_str::<StampFile>(&text) else {
return false;
};
let now: Option<Vec<FileStamp>> = files.iter().map(|p| file_stamp(p)).collect();
now.is_some_and(|now| now == stored.files)
}
fn write_stamp(stamp: &Path, what: &str, files: &[PathBuf]) -> Result<(), String> {
let stamps: Option<Vec<FileStamp>> = files.iter().map(|p| file_stamp(p)).collect();
let files = stamps.ok_or("a verified file disappeared before it could be stamped")?;
let doc = StampFile {
leleka_version: env!("CARGO_PKG_VERSION").to_owned(),
what: what.to_owned(),
files,
verified_unix: SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |d| d.as_secs()),
};
write_private(stamp, &to_file_text(&doc))
.map_err(|e| format!("cannot write {}: {e}", stamp.display()))
}
// ---------------------------------------------------------------------------------------------------------------
// facts about the file system, for the plan
pub fn sha256_file(path: &Path) -> std::io::Result<String> {
let mut file = std::fs::File::open(path)?;
let mut hasher = Sha256::new();
let mut buffer = vec![0u8; 1 << 20];
loop {
let count = file.read(&mut buffer)?;
if count == 0 {
break;
}
hasher.update(&buffer[..count]);
}
Ok(hex::encode(hasher.finalize()))
}
fn mtp_complete(paths: &Paths) -> bool {
MTP_FILES.iter().all(|name| {
std::fs::metadata(paths.mtp_pack().join(name)).is_ok_and(|m| m.is_file() && m.len() > 0)
})
}
fn binary_digest(
manifest: Option<&crate::manifest::Manifest>,
src: &Path,
name: &str,
) -> Option<String> {
manifest
.and_then(|m| m.binaries.get(name).cloned())
.or_else(|| sha256_file(&src.join(name)).ok())
}
pub fn binaries_state(ctx: &Context) -> (bool, bool) {
let installed = ctx.paths.bin_dir();
let manifest = ctx.manifest.as_ref().and_then(|m| m.as_ref().ok());
let src_has_all = BINARIES.iter().all(|b| ctx.bin_src.join(b).is_file());
let installed_has_all = BINARIES.iter().all(|b| installed.join(b).is_file());
if !src_has_all && !installed_has_all {
return (false, false);
}
if !src_has_all {
return (true, true);
}
let current = BINARIES.iter().all(|name| {
let (src, dst) = (ctx.bin_src.join(name), installed.join(name));
if !dst.is_file() {
return false;
}
match (
binary_digest(manifest, &ctx.bin_src, name),
sha256_file(&dst).ok(),
) {
(Some(a), Some(b)) => a == b,
_ => src == dst,
}
});
(true, current)
}
pub fn render_configs(ctx: &Context) -> Vec<(PathBuf, String)> {
let Some(config) = &ctx.config else {
return Vec::new();
};
vec![
(ctx.paths.run_config(), to_file_text(config)),
(
ctx.paths.daemon_config(),
to_file_text(&config.daemon_json()),
),
(
ctx.paths.strata_config(),
to_file_text(&config.strata_json()),
),
(ctx.paths.profile_file(), to_file_text(&config.profile)),
]
}
/// The file that stands for a cuBLAS soname on this OS.
fn cublas_file(soname: &str) -> &str {
match (cfg!(windows), soname) {
(true, "libcublas.so.12") => "cublas64_12.dll",
(true, "libcublasLt.so.12") => "cublasLt64_12.dll",
_ => soname,
}
}
pub fn cublas_lib_dirs(ctx: &Context) -> Vec<PathBuf> {
let mut dirs: Vec<PathBuf> = Vec::new();
for soname in ["libcublas.so.12", "libcublasLt.so.12"] {
let file = cublas_file(soname);
let candidates = [
ctx.opts.cublas_dir.clone().map(|d| d.join(file)),
Some(ctx.paths.cublas_dir().join(file)),
ctx.facts.lib(soname).cloned(),
];
if let Some(found) = candidates.into_iter().flatten().find(|p| p.exists())
&& let Some(parent) = found.parent()
&& !dirs.iter().any(|d| d == parent)
{
dirs.push(parent.to_path_buf());
}
}
dirs
}
pub fn desired_ld_library_path(ctx: &Context) -> String {
cublas_lib_dirs(ctx)
.iter()
.map(|d| d.display().to_string())
.collect::<Vec<_>>()
.join(if cfg!(windows) { ";" } else { ":" })
}
fn secrets_ok(paths: &Paths) -> bool {
let env = std::fs::read_to_string(paths.env_file())
.map(|t| parse_env_file(&t))
.unwrap_or_default();
let good = |key: &str| env.get(key).is_some_and(|v| valid_token(v));
good(RUNTIME_TOKEN_ENV) && good(GATEWAY_TOKEN_ENV) && paths.api_key().is_file()
}
pub async fn gather_fs(ctx: &Context) -> FsState {
let paths = &ctx.paths;
let (binaries_source_ok, binaries_current) = binaries_state(ctx);
let model_files: Vec<PathBuf> = vec![paths.shard(0), paths.shard(1)];
let kar_files: Vec<PathBuf> = vec![paths.kar(), paths.kar_provenance()];
let kar_size_ok = std::fs::metadata(paths.kar()).is_ok_and(|m| m.len() == ARCHIVE_BYTES);
let configs = render_configs(ctx);
let configs_current = !configs.is_empty()
&& configs
.iter()
.all(|(path, text)| std::fs::read_to_string(path).is_ok_and(|t| &t == text))
&& std::fs::read_to_string(paths.env_file())
.ok()
.map(|t| parse_env_file(&t))
.is_some_and(|env| {
env.get("LD_LIBRARY_PATH").map(String::as_str).unwrap_or("")
== desired_ld_library_path(ctx)
});
let unit_current = match ctx.mode {
Mode::Systemd(scope) => unit_text(ctx, scope)
.ok()
.is_some_and(|(path, text)| std::fs::read_to_string(path).is_ok_and(|t| t == text)),
_ => false,
};
let service_ready = probe_ready(ctx).await;
FsState {
dirs_exist: [
paths.dirs.state.clone(),
paths.logs(),
paths.stamps(),
paths.bin_dir(),
paths.dirs.assets.clone(),
]
.iter()
.all(|d| d.is_dir()),
binaries_current,
binaries_source_ok,
cublas_ready: ctx.facts.lib("libcublas.so.12").is_some()
&& ctx.facts.lib("libcublasLt.so.12").is_some(),
secrets_present: secrets_ok(paths),
shards_stamp_ok: stamp_current(&stamp_path(paths, "model"), &model_files),
kar_present: kar_size_ok && paths.kar_provenance().is_file(),
kar_stamp_ok: kar_size_ok && stamp_current(&stamp_path(paths, "kar"), &kar_files),
mtp_present: mtp_complete(paths),
tokenizer_present: paths.tokenizer_dir().is_dir(),
configs_current,
unit_current,
service_ready,
}
}
pub async fn probe_ready(ctx: &Context) -> bool {
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;
};
probe_ready_with_key(&key, api).await
}
/// `GET /ready` with an API key read elsewhere (the WSL bridge reads it through `wsl.exe`).
pub async fn probe_ready_with_key(key: &str, api: &str) -> bool {
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)
}
/// `GET /v1/status` with the key of `paths`: the gateway's status document (`machine` carries the engine telemetry).
pub async fn fetch_status(paths: &Paths, api: &str) -> Option<serde_json::Value> {
let key = std::fs::read_to_string(paths.api_key()).ok()?;
fetch_status_with_key(&key, api).await
}
/// `GET /v1/status` with an API key read elsewhere.
pub async fn fetch_status_with_key(key: &str, api: &str) -> Option<serde_json::Value> {
let address = crate::config::probe_address(api)?;
let response = http::get(address, "/v1/status", Some(key.trim_end()), Duration::from_secs(3)).await.ok()?;
if response.status != 200 {
return None;
}
serde_json::from_str(&response.body).ok()
}
pub fn unit_text(ctx: &Context, scope: UnitScopeTag) -> Result<(PathBuf, String), String> {
let home = std::env::var_os("HOME").map(PathBuf::from);
let text = units::render(
scope.scope(),
&ctx.opts.dirs.prefix,
&ctx.opts.dirs.state,
Some(&ctx.service_user),
)?;
let path = units::unit_path(scope.scope(), home.as_deref(), ctx.paths.unit_name())?;
Ok((path, text))
}
// ---------------------------------------------------------------------------------------------------------------
// running tools
/// Run `program` with its output forwarded to stderr and appended to `log`. The environment is inherited (so
/// `HF_TOKEN` reaches `model fetch`); the command line printed here never contains a secret.
pub async fn run_tool(
label: &str,
program: &Path,
args: &[String],
log: &Path,
) -> Result<(), String> {
say(&format!("$ {} {}", program.display(), args.join(" ")));
let mut log_file = tokio::fs::OpenOptions::new()
.create(true)
.append(true)
.open(log)
.await
.map_err(|e| format!("cannot open {}: {e}", log.display()))?;
let mut child = Command::new(program)
.args(args)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.kill_on_drop(true)
.spawn()
.map_err(|e| format!("cannot start {}: {e}", program.display()))?;
let mut stdout = child.stdout.take().expect("piped");
let mut stderr = child.stderr.take().expect("piped");
let (mut out_buf, mut err_buf) = (vec![0u8; 8192], vec![0u8; 8192]);
let (mut out_open, mut err_open) = (true, true);
while out_open || err_open {
tokio::select! {
read = stdout.read(&mut out_buf), if out_open => match read {
Ok(0) | Err(_) => out_open = false,
Ok(n) => { forward(&mut log_file, &out_buf[..n]).await; }
},
read = stderr.read(&mut err_buf), if err_open => match read {
Ok(0) | Err(_) => err_open = false,
Ok(n) => { forward(&mut log_file, &err_buf[..n]).await; }
},
}
}
let status = child
.wait()
.await
.map_err(|e| format!("{label}: wait failed: {e}"))?;
if status.success() {
Ok(())
} else {
Err(format!("{label} failed ({status}); see {}", log.display()))
}
}
async fn forward(log: &mut tokio::fs::File, bytes: &[u8]) {
use std::io::Write;
let _ = std::io::stderr().write_all(bytes);
let _ = log.write_all(bytes).await;
}
// ---------------------------------------------------------------------------------------------------------------
// the steps
pub fn make_dirs(ctx: &Context) -> Result<(), String> {
let paths = &ctx.paths;
let private = [
paths.dirs.state.clone(),
paths.logs(),
paths.run_dir(),
paths.stamps(),
paths.engine_stamps(),
paths.mtp_staging(),
];
for dir in private.iter().chain(
[
paths.bin_dir(),
paths.dirs.assets.clone(),
paths.model_dir(),
paths.dirs.assets.join("data"),
]
.iter(),
) {
std::fs::create_dir_all(dir)
.map_err(|e| format!("cannot create {}: {e}", dir.display()))?;
}
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
for dir in &private {
std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))
.map_err(|e| format!("cannot restrict {}: {e}", dir.display()))?;
}
}
Ok(())
}
pub fn install_binaries(ctx: &Context) -> Result<usize, String> {
let (src_dir, dst_dir) = (&ctx.bin_src, ctx.paths.bin_dir());
let manifest = ctx.manifest.as_ref().and_then(|m| m.as_ref().ok());
let mut installed = 0;
for name in BINARIES {
let (src, dst) = (src_dir.join(name), dst_dir.join(name));
if !src.is_file() {
if dst.is_file() {
continue;
}
return Err(format!(
"{} is missing (looked in {} and {})",
name,
src_dir.display(),
dst_dir.display()
));
}
let digest =
sha256_file(&src).map_err(|e| format!("cannot read {}: {e}", src.display()))?;
if let Some(expected) = manifest.and_then(|m| m.binaries.get(name))
&& *expected != digest
{
return Err(format!(
"{} does not match MANIFEST.json (corrupt download?)",
src.display()
));
}
if dst.is_file() && sha256_file(&dst).ok().as_deref() == Some(digest.as_str()) {
continue;
}
let tmp = dst_dir.join(format!(".{name}.new"));
std::fs::copy(&src, &tmp).map_err(|e| format!("cannot copy {name}: {e}"))?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(0o755))
.map_err(|e| e.to_string())?;
}
// rename over a running binary is safe (a new inode); a plain overwrite would fail with ETXTBSY.
std::fs::rename(&tmp, &dst).map_err(|e| format!("cannot install {name}: {e}"))?;
installed += 1;
}
Ok(installed)
}
pub async fn install_cublas(ctx: &Context) -> Result<(), String> {
let paths = &ctx.paths;
let lib_dir = paths.dirs.prefix.join("lib");
std::fs::create_dir_all(&lib_dir).map_err(|e| e.to_string())?;
let tar_path = lib_dir.join(format!("libcublas-{CUBLAS_VERSION}.tar.xz"));
let part = lib_dir.join(format!("libcublas-{CUBLAS_VERSION}.tar.xz.part"));
let log = paths.logs().join("install.log");
let have = sha256_file(&tar_path)
.ok()
.is_some_and(|d| d == CUBLAS_SHA256);
if !have {
let downloader = if ctx.facts.tool("curl") {
"curl"
} else {
"wget"
};
let args: Vec<String> = if downloader == "curl" {
["-fL", "--retry", "5", "--retry-delay", "3", "-C", "-", "-o"]
.iter()
.map(|s| s.to_string())
.chain([part.display().to_string(), CUBLAS_URL.to_owned()])
.collect()
} else {
["-c", "-O"]
.iter()
.map(|s| s.to_string())
.chain([part.display().to_string(), CUBLAS_URL.to_owned()])
.collect()
};
run_tool("cuBLAS download", Path::new(downloader), &args, &log).await?;
let digest = sha256_file(&part).map_err(|e| format!("cannot hash the download: {e}"))?;
if digest != CUBLAS_SHA256 {
let _ = std::fs::remove_file(&part);
return Err(format!(
"the cuBLAS download has SHA-256 {digest}, expected {CUBLAS_SHA256}; it was deleted, rerun to download again"
));
}
std::fs::rename(&part, &tar_path).map_err(|e| e.to_string())?;
}
let staging = lib_dir.join(".cublas-extract");
let _ = std::fs::remove_dir_all(&staging);
std::fs::create_dir_all(&staging).map_err(|e| e.to_string())?;
let args: Vec<String> = [
"-xJf",
&tar_path.display().to_string(),
"-C",
&staging.display().to_string(),
"--strip-components=1",
"--wildcards",
"*/lib/libcublas.so.12*",
"*/lib/libcublasLt.so.12*",
"*/LICENSE",
]
.iter()
.map(|s| s.to_string())
.collect();
run_tool("cuBLAS unpack", Path::new("tar"), &args, &log).await?;
let target = paths.cublas_dir();
let _ = std::fs::remove_dir_all(&target);
std::fs::rename(staging.join("lib"), &target)
.map_err(|e| format!("cannot move the unpacked libraries: {e}"))?;
if staging.join("LICENSE").is_file() {
let _ = std::fs::rename(staging.join("LICENSE"), target.join("LICENSE-cublas.txt"));
}
let _ = std::fs::remove_dir_all(&staging);
let _ = std::fs::remove_file(&tar_path);
for soname in ["libcublas.so.12", "libcublasLt.so.12"] {
if !target.join(soname).exists() {
return Err(format!(
"{soname} is missing after unpacking the cuBLAS archive"
));
}
}
Ok(())
}
pub fn write_secrets_and_env(ctx: &Context) -> Result<(), String> {
let path = ctx.paths.env_file();
let existing = std::fs::read_to_string(&path).unwrap_or_default();
let parsed = parse_env_file(&existing);
let mut updates: Vec<(&str, String)> = Vec::new();
let mut seen: Vec<String> = Vec::new();
for key in [RUNTIME_TOKEN_ENV, GATEWAY_TOKEN_ENV] {
match parsed.get(key) {
Some(value) if valid_token(value) && !seen.contains(value) => seen.push(value.clone()),
_ => {
// Missing or malformed: create a fresh one. A valid existing token is never rotated.
let token = new_token()?;
seen.push(token.clone());
updates.push((key, token));
}
}
}
updates.push(("LD_LIBRARY_PATH", desired_ld_library_path(ctx)));
let base = if existing.is_empty() {
format!("{ENV_HEADER}\n")
} else {
existing
};
let text = merge_env(&base, &updates);
if text != std::fs::read_to_string(&path).unwrap_or_default() {
write_private(&path, &text).map_err(|e| format!("cannot write {}: {e}", path.display()))?;
}
Ok(())
}
pub async fn init_api_key(ctx: &Context) -> Result<(), String> {
let args = vec![
"api-key".to_owned(),
"init".to_owned(),
"--file".to_owned(),
ctx.paths.api_key().display().to_string(),
];
run_tool(
"api-key init",
&ctx.paths.bin("strata-next"),
&args,
&ctx.paths.logs().join("install.log"),
)
.await
}
pub async fn fetch_and_verify_model(ctx: &Context) -> Result<(), String> {
let strata = ctx.paths.bin("strata-next");
let log = ctx.paths.logs().join("install.log");
let model_dir = ctx.paths.model_dir().display().to_string();
if ctx.opts.fetch {
run_tool(
"model fetch",
&strata,
&[
"model".into(),
"fetch".into(),
MANIFEST.into(),
"--output".into(),
model_dir.clone(),
],
&log,
)
.await?;
}
run_tool(
"model verify",
&strata,
&[
"model".into(),
"verify".into(),
MANIFEST.into(),
"--output".into(),
model_dir,
],
&log,
)
.await?;
write_stamp(
&stamp_path(&ctx.paths, "model"),
"gguf shards verified by `model verify`",
&[ctx.paths.shard(0), ctx.paths.shard(1)],
)
}
pub async fn ensure_kar(ctx: &Context) -> Result<(), String> {
let strata = ctx.paths.bin("strata-next");
let log = ctx.paths.logs().join("install.log");
let present = std::fs::metadata(ctx.paths.kar()).is_ok_and(|m| m.len() == ARCHIVE_BYTES)
&& ctx.paths.kar_provenance().is_file();
if ctx.opts.trust_archive && present {
say("--trust-archive: the existing archive is accepted without the strict re-derivation");
} else {
let args: Vec<String> = [
"model",
"ensure-sharded-streamed",
MANIFEST,
"--source-dir",
&ctx.paths.model_dir().display().to_string(),
"--output",
&ctx.paths.kar().display().to_string(),
"--levels",
"2",
]
.iter()
.map(|s| s.to_string())
.collect();
run_tool("KAR archive", &strata, &args, &log).await?;
// The tool fetched and verified the shards before it touched the archive.
write_stamp(
&stamp_path(&ctx.paths, "model"),
"gguf shards verified by `ensure-sharded-streamed`",
&[ctx.paths.shard(0), ctx.paths.shard(1)],
)?;
}
let size = std::fs::metadata(ctx.paths.kar())
.map_err(|e| format!("the archive is missing after the build: {e}"))?
.len();
if size != ARCHIVE_BYTES {
return Err(format!(
"{} has {size} bytes but the engine only admits the pinned {ARCHIVE_BYTES}-byte level-2 archive; the engine would refuse it (do not use another --levels or an overlay here)",
ctx.paths.kar().display()
));
}
if !ctx.paths.kar_provenance().is_file() {
return Err(format!(
"{} is missing next to the archive",
ctx.paths.kar_provenance().display()
));
}
#[cfg(unix)]
if ctx
.config
.as_ref()
.is_some_and(|c| c.profile.kar_source == crate::profile::KarSource::File)
{
use std::os::unix::fs::PermissionsExt;
// `--kar-archive-file` admits only a regular, single-link file without write bits that this user owns.
std::fs::set_permissions(ctx.paths.kar(), std::fs::Permissions::from_mode(0o400))
.map_err(|e| format!("cannot make the archive read-only: {e}"))?;
}
write_stamp(
&stamp_path(&ctx.paths, "kar"),
"level-2 KAR archive verified by `ensure-sharded-streamed`",
&[ctx.paths.kar(), ctx.paths.kar_provenance()],
)
}
pub async fn import_mtp_pack(ctx: &Context) -> Result<(), String> {
let source = ctx.opts.mtp_pack.clone().ok_or("no --mtp-pack given")?;
let target = ctx.paths.mtp_pack();
let staging = ctx.paths.dirs.assets.join("data/.mtp-import");
let _ = std::fs::remove_dir_all(&staging);
std::fs::create_dir_all(&staging).map_err(|e| e.to_string())?;
let name = source
.file_name()
.and_then(|n| n.to_str())
.unwrap_or("")
.to_owned();
if source.is_dir() {
copy_dir(&source, &staging)?;
} else if name.ends_with(".tar")
|| name.ends_with(".tar.gz")
|| name.ends_with(".tgz")
|| name.ends_with(".tar.xz")
{
let flag = if name.ends_with(".tar") {
"-xf"
} else if name.ends_with(".tar.xz") {
"-xJf"
} else {
"-xzf"
};
run_tool(
"unpack the MTP pack",
Path::new("tar"),
&[
flag.into(),
source.display().to_string(),
"-C".into(),
staging.display().to_string(),
],
&ctx.paths.logs().join("install.log"),
)
.await?;
} else {
return Err(format!(
"--mtp-pack {} must be a directory or a .tar/.tar.gz/.tgz/.tar.xz archive",
source.display()
));
}
// The pack may sit in a sub-directory (data/mtp-rt/ inside the tarball).
let root = find_pack_root(&staging).ok_or_else(|| {
format!(
"none of the unpacked directories contains {}",
MTP_FILES.join(", ")
)
})?;
let _ = std::fs::remove_dir_all(&target);
std::fs::rename(&root, &target).map_err(|e| format!("cannot move the pack into place: {e}"))?;
let _ = std::fs::remove_dir_all(&staging);
if !mtp_complete(&ctx.paths) {
return Err("the imported MTP pack is incomplete".into());
}
Ok(())
}
fn find_pack_root(dir: &Path) -> Option<PathBuf> {
if MTP_FILES.iter().all(|f| dir.join(f).is_file()) {
return Some(dir.to_path_buf());
}
for entry in std::fs::read_dir(dir).ok()?.flatten() {
if entry.path().is_dir()
&& let Some(found) = find_pack_root(&entry.path())
{
return Some(found);
}
}
None
}
fn copy_dir(from: &Path, to: &Path) -> Result<(), String> {
for entry in std::fs::read_dir(from)
.map_err(|e| format!("cannot read {}: {e}", from.display()))?
.flatten()
{
let (src, dst) = (entry.path(), to.join(entry.file_name()));
if src.is_dir() {
std::fs::create_dir_all(&dst).map_err(|e| e.to_string())?;
copy_dir(&src, &dst)?;
} else if src.is_file() {
std::fs::copy(&src, &dst).map_err(|e| format!("cannot copy {}: {e}", src.display()))?;
}
}
Ok(())
}
pub async fn extract_tokenizer(ctx: &Context) -> Result<(), String> {
let args: Vec<String> = [
"model",
"extract-tokenizer",
&ctx.paths.shard(0).display().to_string(),
"--output",
&ctx.paths.tokenizer_root().display().to_string(),
]
.iter()
.map(|s| s.to_string())
.collect();
run_tool(
"tokenizer extraction",
&ctx.paths.bin("strata-next"),
&args,
&ctx.paths.logs().join("install.log"),
)
.await
}
pub fn write_configs(ctx: &Context) -> Result<usize, String> {
let mut written = 0;
for (path, text) in render_configs(ctx) {
if std::fs::read_to_string(&path).ok().as_deref() != Some(text.as_str()) {
write_private(&path, &text)
.map_err(|e| format!("cannot write {}: {e}", path.display()))?;
written += 1;
}
}
write_secrets_and_env(ctx)?;
Ok(written)
}
// ---------------------------------------------------------------------------------------------------------------
// system user and ownership (system unit only)
#[cfg(unix)]
pub fn lookup_user(name: &str) -> Option<(u32, u32)> {
let passwd = std::fs::read_to_string("/etc/passwd").ok()?;
passwd.lines().find_map(|line| {
let fields: Vec<&str> = line.split(':').collect();
(fields.first() == Some(&name))
.then(|| Some((fields.get(2)?.parse().ok()?, fields.get(3)?.parse().ok()?)))?
})
}
#[cfg(unix)]
pub async fn ensure_service_user(ctx: &Context) -> Result<(), String> {
let name = &ctx.service_user;
if name == "root" || lookup_user(name).is_some() {
return Ok(());
}
say(&format!(
"creating the system account {name} (no login shell, home {})",
ctx.opts.dirs.state.display()
));
let args: Vec<String> = [
"--system",
"--no-create-home",
"--home-dir",
&ctx.opts.dirs.state.display().to_string(),
"--shell",
"/usr/sbin/nologin",
name,
]
.iter()
.map(|s| s.to_string())
.collect();
run_tool(
"useradd",
Path::new("useradd"),
&args,
&ctx.paths.logs().join("install.log"),
)
.await
}
#[cfg(unix)]
pub fn chown_tree(root: &Path, uid: u32, gid: u32) -> Result<(), String> {
use std::os::unix::fs::chown;
if let Ok(meta) = std::fs::symlink_metadata(root) {
if meta.file_type().is_symlink() {
return Ok(());
}
chown(root, Some(uid), Some(gid)).map_err(|e| format!("chown {}: {e}", root.display()))?;
if meta.is_dir() {
for entry in std::fs::read_dir(root)
.map_err(|e| e.to_string())?
.flatten()
{
chown_tree(&entry.path(), uid, gid)?;
}
}
}
Ok(())
}
#[cfg(unix)]
pub fn hand_over_to_service_user(ctx: &Context) -> Result<(), String> {
if !matches!(ctx.mode, Mode::Systemd(UnitScopeTag::System)) || ctx.service_user == "root" {
return Ok(());
}
let (uid, gid) = lookup_user(&ctx.service_user)
.ok_or_else(|| format!("service user {} does not exist", ctx.service_user))?;
chown_tree(&ctx.paths.dirs.state, uid, gid)?;
chown_tree(&ctx.paths.dirs.assets, uid, gid)
}
// ---------------------------------------------------------------------------------------------------------------
// systemd
async fn systemctl(scope: UnitScopeTag, args: &[&str], log: &Path) -> Result<(), String> {
let mut all: Vec<String> = Vec::new();
if scope == UnitScopeTag::User {
all.push("--user".into());
}
all.extend(args.iter().map(|s| s.to_string()));
run_tool("systemctl", Path::new("systemctl"), &all, log).await
}
async fn systemctl_query(scope: UnitScopeTag, args: &[&str]) -> String {
let mut command = Command::new("systemctl");
if scope == UnitScopeTag::User {
command.arg("--user");
}
match command
.args(args)
.stdin(Stdio::null())
.stderr(Stdio::null())
.output()
.await
{
Ok(output) => String::from_utf8_lossy(&output.stdout).trim().to_owned(),
Err(_) => String::new(),
}
}
pub async fn install_unit(ctx: &Context, scope: UnitScopeTag) -> Result<bool, String> {
let (path, text) = unit_text(ctx, scope)?;
let changed = std::fs::read_to_string(&path).ok().as_deref() != Some(text.as_str());
if changed {
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)
.map_err(|e| format!("cannot create {}: {e}", parent.display()))?;
}
std::fs::write(&path, &text)
.map_err(|e| format!("cannot write {}: {e}", path.display()))?;
}
let log = ctx.paths.logs().join("install.log");
if changed {
systemctl(scope, &["daemon-reload"], &log).await?;
}
systemctl(scope, &["enable", ctx.paths.unit_name()], &log).await?;
Ok(changed)
}
pub async fn start_unit(
ctx: &Context,
scope: UnitScopeTag,
unit_changed: bool,
) -> Result<(), String> {
let log = ctx.paths.logs().join("install.log");
let active = systemctl_query(scope, &["is-active", ctx.paths.unit_name()]).await;
if active == "active" && unit_changed {
say("the unit changed while the service runs: restarting it");
systemctl(scope, &["restart", ctx.paths.unit_name()], &log).await
} else if active == "active" || active == "activating" {
say("the service is already running; waiting for it to become ready");
Ok(())
} else {
systemctl(scope, &["start", ctx.paths.unit_name()], &log).await
}
}
/// Poll `/ready`, printing the supervisor's phase every 15 s. Fails fast when the unit or supervisor failed.
pub async fn wait_ready(ctx: &Context, scope: Option<UnitScopeTag>) -> Result<(), String> {
let started = Instant::now();
let limit = Duration::from_secs(ctx.opts.timeout_s);
let mut last_phase = String::new();
let mut last_print = Instant::now() - Duration::from_secs(60);
loop {
if probe_ready(ctx).await {
return Ok(());
}
let status: Option<serde_json::Value> = std::fs::read_to_string(ctx.paths.status_file())
.ok()
.and_then(|t| serde_json::from_str(&t).ok());
let phase = status
.as_ref()
.and_then(|s| s.get("phase"))
.and_then(|v| v.as_str())
.unwrap_or("not started")
.to_owned();
if phase == "failed" {
let message = status
.as_ref()
.and_then(|s| s.get("message"))
.and_then(|v| v.as_str())
.unwrap_or("");
return Err(format!("the service failed: {message}\n{}", log_tail(ctx)));
}
if let Some(scope) = scope {
let active = systemctl_query(scope, &["is-active", ctx.paths.unit_name()]).await;
if active == "failed" {
return Err(format!(
"{} failed\n{}",
ctx.paths.unit_name(),
log_tail(ctx)
));
}
}
if phase != last_phase || last_print.elapsed() >= Duration::from_secs(30) {
say(&format!(
"waiting for ready: {phase} ({:.0}s)",
started.elapsed().as_secs_f32()
));
last_phase = phase;
last_print = Instant::now();
}
if started.elapsed() > limit {
return Err(format!(
"not ready after {} s (phase {last_phase}); the service keeps running; logs in {}",
limit.as_secs(),
ctx.paths.logs().display()
));
}
tokio::time::sleep(Duration::from_secs(3)).await;
}
}
fn log_tail(ctx: &Context) -> String {
let mut out = String::new();
for name in ["leleka.log", "engine.log"] {
if let Ok(text) = std::fs::read_to_string(ctx.paths.logs().join(name)) {
let lines: Vec<&str> = text.lines().collect();
let tail = &lines[lines.len().saturating_sub(12)..];
out.push_str(&format!(
"--- last lines of {} ---\n{}\n",
ctx.paths.logs().join(name).display(),
tail.join("\n")
));
}
}
out
}
// ---------------------------------------------------------------------------------------------------------------
// the whole plan
/// Will the `kar` step run `ensure-sharded-streamed`? That tool fetches and verifies the shards itself.
fn kar_runs_tool(ctx: &Context, steps: &[Step]) -> bool {
let kar_todo = steps
.iter()
.any(|s| s.id == "kar" && matches!(s.state, StepState::Todo(_)));
let present = std::fs::metadata(ctx.paths.kar()).is_ok_and(|m| m.len() == ARCHIVE_BYTES)
&& ctx.paths.kar_provenance().is_file();
kar_todo && !(ctx.opts.trust_archive && present)
}
/// Run every `Todo` step of the plan up to (not including) the start of the service. Returns the steps as
/// re-planned after the work, which the caller prints in `--json` mode.
/// What the preparation changed that a running service does not see until it restarts.
#[derive(Debug, Default, PartialEq, Eq)]
pub struct Changes {
pub binaries: usize,
pub configs: usize,
}
impl Changes {
pub fn needs_restart(&self) -> bool {
self.binaries > 0 || self.configs > 0
}
}
pub async fn prepare(ctx: &Context, steps: &[Step]) -> Result<Changes, String> {
let mut changes = Changes::default();
let total = steps.len();
for (index, step) in steps.iter().enumerate() {
match &step.state {
StepState::Blocked(why) => {
return Err(format!(
"step {} ({}) is blocked: {why}",
step.id, step.title
));
}
StepState::Done(_) | StepState::Skip(_) => continue,
StepState::Todo(_) => {}
}
if matches!(step.id, "preflight" | "service" | "start" | "ready") {
continue;
}
if step.id == "model" && kar_runs_tool(ctx, steps) {
say("the shards are fetched and verified by the archive step below");
continue;
}
say(&format!("[{}/{}] {}", index + 1, total, step.title));
let started = Instant::now();
let result: Result<(), String> = match step.id {
"layout" => make_dirs(ctx),
"binaries" => install_binaries(ctx).map(|n| {
changes.binaries += n;
say(&format!(
"installed {n} binaries into {}",
ctx.paths.bin_dir().display()
))
}),
"cublas" => install_cublas(ctx).await,
"secrets" => {
write_secrets_and_env(ctx)?;
init_api_key(ctx).await
}
"model" => fetch_and_verify_model(ctx).await,
"kar" => ensure_kar(ctx).await,
"mtp-pack" => import_mtp_pack(ctx).await,
"tokenizer" => extract_tokenizer(ctx).await,
"config" => write_configs(ctx).map(|n| {
changes.configs += n;
say(&format!(
"wrote {n} configuration file(s) in {}",
ctx.paths.dirs.state.display()
))
}),
other => Err(format!("internal error: no executor for step {other}")),
};
result.map_err(|e| format!("step {} failed: {e}", step.id))?;
say(&format!(
"[{}/{}] done in {:.1}s",
index + 1,
total,
started.elapsed().as_secs_f32()
));
}
Ok(changes)
}
/// Re-plan with the current state of the disk (after `prepare`), used to decide what `start` has to do.
pub async fn replan(ctx: &Context) -> Vec<Step> {
let fs = gather_fs(ctx).await;
plan_steps(ctx, &fs)
}
pub fn config_of(ctx: &Context) -> Result<&RunConfig, String> {
ctx.config
.as_ref()
.ok_or_else(|| "no profile could be selected".to_owned())
}
#[cfg(test)]
mod tests {
use super::*;
fn temp(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("leleka-steps-{}-{name}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
dir
}
#[test]
fn stamps_track_size_and_mtime() {
let dir = temp("stamp");
let (a, b) = (dir.join("a.gguf"), dir.join("b.gguf"));
std::fs::write(&a, b"aaaa").unwrap();
std::fs::write(&b, b"bb").unwrap();
let stamp = dir.join("model.json");
assert!(!stamp_current(&stamp, &[a.clone(), b.clone()]));
write_stamp(&stamp, "test", &[a.clone(), b.clone()]).unwrap();
assert!(stamp_current(&stamp, &[a.clone(), b.clone()]));
std::fs::write(&b, b"bbb").unwrap();
assert!(
!stamp_current(&stamp, &[a.clone(), b.clone()]),
"a changed size must invalidate the stamp"
);
assert!(!stamp_current(&stamp, std::slice::from_ref(&a)));
std::fs::remove_file(&a).unwrap();
assert!(!stamp_current(&stamp, &[a, b]));
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn mtp_pack_root_is_found_in_a_subdirectory() {
let dir = temp("mtp");
let nested = dir.join("data/mtp-rt");
std::fs::create_dir_all(&nested).unwrap();
assert_eq!(find_pack_root(&dir), None);
for name in MTP_FILES {
std::fs::write(nested.join(name), b"x").unwrap();
}
assert_eq!(find_pack_root(&dir), Some(nested));
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn sha256_of_a_file() {
let dir = temp("sha");
let file = dir.join("f");
std::fs::write(&file, b"abc").unwrap();
assert_eq!(
sha256_file(&file).unwrap(),
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
);
std::fs::remove_dir_all(dir).unwrap();
}
}