tessera-command 0.6.0

The tesserax command: opens a recipe, then serves, fetches or runs tasks
Documentation
//! Inspect or compact host memory.

use tessera_engine::{CompactOptions, HostStats, compact_memory};
use tessera_frontend::tasks::Error;
use tessera_frontend::tasks::task::{Run, Sink, Task};

/// Compact Linux host memory or inspect fragmentation stats.
#[derive(Task)]
#[task(name = "compact-memory")]
pub(crate) struct CompactMemory {
    /// Report planned changes without touching kernel settings.
    pub dry_run: bool,
    /// Print memory and fragmentation stats without compacting.
    pub report_only: bool,
    /// Target free headroom in MiB.
    #[arg(value = "<n>")]
    pub headroom_mib: Option<u64>,
    /// Compact even when fragmentation is below threshold.
    pub force: bool,
    /// Print the report as JSON.
    pub json: bool,
}

impl CompactMemory {
    pub(crate) fn to_options(&self) -> CompactOptions {
        let mut opts = CompactOptions {
            dry_run: self.dry_run,
            report_only: self.report_only,
            force: self.force,
            ..CompactOptions::default()
        };
        if let Some(mib) = self.headroom_mib {
            opts.headroom_mib = mib;
        }
        opts
    }
}

fn summary(label: &str, s: &HostStats) -> String {
    let show = |v: Option<u64>| v.map_or_else(|| "unknown".into(), |v| v.to_string());
    let frag = s.fragmentation.as_ref().map_or_else(
        || "unknown".into(),
        |f| format!("{:?} ({:.1}% below target)", f.level, 100.0 * f.unusable),
    );
    format!(
        "{label}: MemFree={} KiB, MemAvailable={} KiB, SecPageTables={} KiB, HardwareCorrupted={} KiB, {} KiB blocks={}, fragmentation={frag}\n",
        s.free_kib,
        s.available_kib,
        show(s.sec_page_tables_kib),
        show(s.hardware_corrupted_kib),
        s.block_kib,
        show(s.target_blocks)
    )
}

impl Run<()> for CompactMemory {
    fn run(self, _: (), sink: &mut dyn Sink) -> Result<(), Error> {
        let opts = self.to_options();
        let report = compact_memory(&opts)?;
        if !sink.passthrough() {
            sink.record(serde_json::to_value(&report)?);
            return Ok(());
        }
        if self.json {
            sink.text(&format!("{}\n", serde_json::to_string_pretty(&report)?));
        } else {
            sink.text(&summary("Before", &report.before));
            for pass in report.sweeps {
                sink.text(&format!(
                    "{} KiB sweep: allocated {} of {} additional pages\n",
                    pass.page_kib, pass.allocated, pass.requested
                ));
            }
            if let Some(after) = report.after {
                sink.text(&summary("After", &after));
            }
            if opts.dry_run {
                sink.text("Dry run: kernel settings remain unchanged.\n");
            }
        }
        Ok(())
    }
}

crate::task::register!(CompactMemory, crate::task::OnMachine, "", false);