Files
leleka/crates/model-format/examples/kar_census.rs
T

160 lines
5.8 KiB
Rust

//! Read-only census of a KAR archive: every record with its kind, size and offset, which of them the serve path reads,
//! and the totals per kind. Reads the 256-byte header, the names and the directory (about a megabyte) and nothing
//! of the payload, so it is safe to run against the 55 GB archive on a host whose disk is struggling.
//!
//! kar_census ARCHIVE full table + totals
//! kar_census ARCHIVE --summary totals and the PLE partitions only
//! kar_census ARCHIVE --extents also list the page-aligned extents of a sparse copy
//! kar_census ARCHIVE --hash-extents [--throttle-mib-s N]
//! ALSO read the extents (about 16 GB) and print their pinned SHA-256
//! (default throttle 200 MiB/s). Heavy I/O: only when the host is steady,
//! and only for an archive that has matched its full pinned SHA-256.
//!
//! Nothing is written, nothing needs a GPU.
use leleka_model_format::kar::{KarCensus, KarInspection, PLE_PART_NAMES, digest_extents};
use std::{
fs::File,
process::ExitCode,
time::{Duration, Instant},
};
/// What the command line asks for.
struct Options {
path: String,
summary: bool,
list_extents: bool,
hash: bool,
throttle_mib_s: u64,
}
fn parse_throttle(args: &mut impl Iterator<Item = String>) -> Result<u64, ExitCode> {
match args.next().and_then(|v| v.parse().ok()).filter(|v| *v > 0) {
Some(v) => Ok(v),
None => Err(usage("--throttle-mib-s needs a positive number")),
}
}
fn take_path(path: &mut Option<String>, arg: &str) -> Result<(), ExitCode> {
if arg.starts_with('-') {
return Err(usage(&format!("unknown option {arg}")));
}
if path.replace(arg.to_owned()).is_some() {
return Err(usage("one archive path only"));
}
Ok(())
}
fn parse_options() -> Result<Options, ExitCode> {
let mut path = None;
let (mut summary, mut list_extents, mut hash) = (false, false, false);
let mut throttle_mib_s = 200u64;
let mut args = std::env::args().skip(1);
while let Some(arg) = args.next() {
match arg.as_str() {
"--summary" => summary = true,
"--extents" => list_extents = true,
"--hash-extents" => hash = true,
"--throttle-mib-s" => throttle_mib_s = parse_throttle(&mut args)?,
"-h" | "--help" => return Err(usage("")),
other => take_path(&mut path, other)?,
}
}
let Some(path) = path else { return Err(usage("an archive path is required")) };
Ok(Options { path, summary, list_extents, hash, throttle_mib_s })
}
fn load_census(path: &str) -> Result<KarCensus, ExitCode> {
let file = match File::open(path) {
Ok(file) => file,
Err(error) => {
eprintln!("cannot open {path}: {error}");
return Err(ExitCode::FAILURE);
}
};
let inspection = match KarInspection::inspect(file) {
Ok(inspection) => inspection,
Err(error) => {
eprintln!("not a valid KAR archive: {error}");
return Err(ExitCode::FAILURE);
}
};
match inspection.census(&PLE_PART_NAMES) {
Ok(census) => Ok(census),
Err(error) => {
eprintln!("census failed: {error}");
Err(ExitCode::FAILURE)
}
}
}
fn print_hash(digest: Result<[u8; 32], impl std::fmt::Display>, done: u64, started: Instant) -> Result<(), ExitCode> {
match digest {
Ok(digest) => {
let hex: String = digest.iter().map(|b| format!("{b:02x}")).collect();
println!("\nple_extents_sha256={hex}");
println!("extent_bytes_hashed={done} in {:.1}s", started.elapsed().as_secs_f64());
println!("const_line: pub const PLE_EXTENTS_SHA256: [u8; 32] = {digest:?};");
Ok(())
}
Err(error) => {
eprintln!("hashing failed: {error}");
Err(ExitCode::FAILURE)
}
}
}
fn hash_extents(options: &Options, census: &KarCensus) -> Result<(), ExitCode> {
let (path, throttle_mib_s) = (&options.path, options.throttle_mib_s);
let file = match File::open(path) {
Ok(file) => file,
Err(error) => {
eprintln!("cannot reopen {path}: {error}");
return Err(ExitCode::FAILURE);
}
};
let total = census.serve.extent_bytes();
eprintln!("hashing {} MiB of extents at <= {throttle_mib_s} MiB/s", total >> 20);
let started = Instant::now();
let mut done = 0u64;
let digest = digest_extents(&file, &census.serve.extents, |n| {
done += n;
let due = Duration::from_secs_f64(done as f64 / (throttle_mib_s as f64 * 1_048_576.0));
if let Some(wait) = due.checked_sub(started.elapsed()) {
std::thread::sleep(wait);
}
});
print_hash(digest, done, started)
}
fn main() -> ExitCode {
let options = match parse_options() {
Ok(options) => options,
Err(code) => return code,
};
let census = match load_census(&options.path) {
Ok(census) => census,
Err(code) => return code,
};
print!("{}", census.render(!options.summary));
if options.list_extents {
println!("\n# extents of a sparse copy (page-aligned, offset len)");
for e in &census.serve.extents {
println!("extent {} {}", e.offset, e.len);
}
}
if options.hash {
if let Err(code) = hash_extents(&options, &census) {
return code;
}
}
ExitCode::SUCCESS
}
fn usage(problem: &str) -> ExitCode {
if !problem.is_empty() {
eprintln!("{problem}");
}
eprintln!("usage: kar_census ARCHIVE [--summary] [--extents] [--hash-extents [--throttle-mib-s N]]");
if problem.is_empty() { ExitCode::SUCCESS } else { ExitCode::from(2) }
}