Files
leleka/crates/deploy/src/sealed/exec_arguments.rs
T

74 lines
2.8 KiB
Rust

//! The portable parts of `leleka seal-exec`: the sparse serve extents, the argument parser and the descriptor substitution.
use super::*;
/// The page-aligned ranges of the archive file at `kar` that the serve path reads, from its header and directory (about a megabyte of
/// reads, none of the payload). Refuses a file that is not a valid KAR archive of `expect_bytes`.
pub fn archive_serve_extents(
kar: &std::path::Path,
expect_bytes: u64,
) -> Result<Vec<leleka_model_format::kar::Extent>, String> {
use leleka_model_format::kar::{KarInspection, PLE_PART_NAMES};
let file =
std::fs::File::open(kar).map_err(|e| format!("cannot open {}: {e}", kar.display()))?;
let inspection = KarInspection::inspect(file)
.map_err(|e| format!("{} is not a valid KAR archive: {e}", kar.display()))?;
if inspection.summary().archive_bytes != expect_bytes {
return Err(format!(
"{} has {} bytes, expected {expect_bytes}",
kar.display(),
inspection.summary().archive_bytes
));
}
inspection
.serve_reads(&PLE_PART_NAMES)
.map(|reads| reads.extents)
.map_err(|e| format!("cannot derive the sparse extents of {}: {e}", kar.display()))
}
/// `--file PATH [--expect-bytes N] [--sparse-ple] -- COMMAND ARG...`
pub fn parse_seal_exec(args: &[String]) -> Result<SealExecPlan, String> {
let usage = "usage: leleka seal-exec --file PATH [--expect-bytes N] [--sparse-ple] -- COMMAND ARG... ({FD} marks the sealed descriptor)";
let (mut file, mut expect_bytes, mut sparse_ple) = (None, None, false);
let mut i = 0;
while i < args.len() {
match args[i].as_str() {
"--" => break,
"--file" => {
i += 1;
file = Some(std::path::PathBuf::from(
args.get(i).filter(|v| !v.is_empty()).ok_or(usage)?,
));
}
"--expect-bytes" => {
i += 1;
expect_bytes = Some(
args.get(i)
.and_then(|v| v.parse::<u64>().ok())
.ok_or(usage)?,
);
}
"--sparse-ple" => sparse_ple = true,
_ => return Err(usage.into()),
}
i += 1;
}
let command: Vec<String> = args.get(i + 1..).unwrap_or_default().to_vec();
if args.get(i).map(String::as_str) != Some("--") || command.is_empty() {
return Err(usage.into());
}
Ok(SealExecPlan {
file: file.ok_or(usage)?,
expect_bytes,
sparse_ple,
command,
})
}
/// Replace every `{FD}` in `args`.
pub fn substitute(args: &[String], number: i32) -> Vec<String> {
args.iter()
.map(|arg| arg.replace(PLACEHOLDER, &number.to_string()))
.collect()
}