diff --git a/src/main.rs b/src/main.rs index 2a5fc86..779ec7b 100644 --- a/src/main.rs +++ b/src/main.rs @@ -136,10 +136,191 @@ fn dispatch() { match std::env::args().nth(1).as_deref() { Some("read") => noteguard::readpolicy::run(), + Some("dump-buckets") => dump_buckets(), _ => noteguard(), } } +/// `noteguard dump-buckets [--json] [--capacity BYTES] [PATH]` — a read-only +/// operator peek into the shared per-IP read-bandwidth byte-bucket table (see +/// [`noteguard::readfilters::dump`]). Prints one row per OCCUPIED slot — the key +/// (client IP), bytes remaining, and how long ago the slot last refilled — +/// sorted most-throttled first. With `--capacity` it also shows each bucket +/// refilled to now and how full that leaves it. Never mutates the file. +fn dump_buckets() { + use std::io::Write; + + // One minute in nanoseconds — the refill window, mirrored from the shm + // module so `--capacity` can project a bucket's balance to now. + const MINUTE_NS: f64 = 60.0 * 1_000_000_000.0; + + // Parse: an optional `--json`, an optional `--capacity BYTES`, and an + // optional trailing PATH (defaults to the tmpfs file the read filter uses). + let mut json = false; + let mut capacity: Option = None; + let mut path: Option = None; + let mut args = std::env::args().skip(2); + while let Some(arg) = args.next() { + match arg.as_str() { + "--json" => json = true, + "--capacity" => { + capacity = match args.next().and_then(|v| v.parse::().ok()) { + Some(c) if c > 0.0 => Some(c), + _ => { + eprintln!("dump-buckets: --capacity needs a positive number of bytes"); + std::process::exit(2); + } + }; + } + "-h" | "--help" => { + println!("usage: noteguard dump-buckets [--json] [--capacity BYTES] [PATH]"); + println!( + " inspect the shared read-bandwidth byte buckets (default {})", + noteguard::readfilters::DEFAULT_PATH + ); + return; + } + other if other.starts_with('-') => { + eprintln!("dump-buckets: unknown flag {other}"); + std::process::exit(2); + } + other => { + if path.replace(other.to_string()).is_some() { + eprintln!("dump-buckets: only one PATH may be given"); + std::process::exit(2); + } + } + } + } + let path = path.unwrap_or_else(|| noteguard::readfilters::DEFAULT_PATH.to_string()); + + let dump = match noteguard::readfilters::dump(&path) { + Ok(d) => d, + Err(e) => { + eprintln!("dump-buckets: cannot read {path}: {e}"); + std::process::exit(1); + } + }; + + // Age in nanoseconds against the clock `dump` captured; negative means a + // last_refill in the future (stale across a reboot — the monotonic clock + // reset), which the read filter treats as fully stale (a full bucket). + let age_ns = + |e: ¬eguard::readfilters::BucketEntry| dump.now_ns as i128 - e.last_refill_ns as i128; + + // Project a bucket's balance to now (same shape as the filter's refill: + // elapsed/60 of a minute's capacity, clamped to a minute and capped; a + // future timestamp resets to full). Only meaningful with a known capacity. + let refilled = |e: ¬eguard::readfilters::BucketEntry, cap: f64| -> f64 { + let age = age_ns(e); + if age < 0 { + return cap; + } + let elapsed = (age as f64).min(MINUTE_NS); + (e.tokens + (elapsed / MINUTE_NS) * cap).min(cap) + }; + + // Sort most-throttled first (fewest bytes remaining), the default an + // operator hunting for a hammered IP wants at the top. + let mut entries = dump.entries; + entries.sort_by(|a, b| { + a.tokens + .partial_cmp(&b.tokens) + .unwrap_or(std::cmp::Ordering::Equal) + }); + + if json { + // Hand-roll the JSON so we don't need a Serialize impl on the shm types. + let mut items = Vec::with_capacity(entries.len()); + for e in &entries { + let mut obj = serde_json::json!({ + "key": e.key, + "tokens": e.tokens, + "last_refill_ns": e.last_refill_ns, + "age_seconds": age_ns(e) as f64 / 1e9, + }); + if let Some(cap) = capacity { + let r = refilled(e, cap); + obj["refilled_tokens"] = serde_json::json!(r); + obj["percent_full"] = serde_json::json!(r / cap * 100.0); + } + items.push(obj); + } + let out = serde_json::json!({ + "path": path, + "slot_count": dump.slot_count, + "occupied": entries.len(), + "now_ns": dump.now_ns, + "capacity": capacity, + "buckets": items, + }); + println!( + "{}", + serde_json::to_string_pretty(&out).expect("dump JSON serializes") + ); + return; + } + + // Text output. Buffer to stdout so a huge table isn't line-flushed. + let stdout = io::stdout(); + let mut out = io::BufWriter::new(stdout.lock()); + let _ = writeln!( + out, + "{}: slot_count={} occupied={}", + path, + dump.slot_count, + entries.len() + ); + if let Some(cap) = capacity { + let _ = writeln!( + out, + "{:<46} {:>16} {:>10} {:>16} {:>7}", + "KEY", "BYTES_REMAINING", "AGE", "REFILLED_NOW", "%FULL" + ); + for e in &entries { + let r = refilled(e, cap); + let _ = writeln!( + out, + "{:<46} {:>16.0} {:>10} {:>16.0} {:>6.1}%", + e.key, + e.tokens, + fmt_age(age_ns(e)), + r, + r / cap * 100.0, + ); + } + } else { + let _ = writeln!( + out, + "{:<46} {:>16} {:>10}", + "KEY", "BYTES_REMAINING", "AGE" + ); + for e in &entries { + let _ = writeln!( + out, + "{:<46} {:>16.0} {:>10}", + e.key, + e.tokens, + fmt_age(age_ns(e)), + ); + } + } +} + +/// Render a bucket age (nanoseconds; may be negative if stale across a reboot) +/// as a short human string like `4.2s` or `stale`. +fn fmt_age(age_ns: i128) -> String { + if age_ns < 0 { + return "stale".to_string(); + } + let secs = age_ns as f64 / 1e9; + if secs < 60.0 { + format!("{secs:.1}s") + } else { + format!("{:.1}m", secs / 60.0) + } +} + fn serialize_output_message(msg: &OutputMessage) -> String { serde_json::to_string(msg).expect("OutputMessage should always serialize correctly") } diff --git a/src/readfilters/mod.rs b/src/readfilters/mod.rs index 706ddd9..2efecab 100644 --- a/src/readfilters/mod.rs +++ b/src/readfilters/mod.rs @@ -11,6 +11,7 @@ mod nscript; pub use bandwidth::ReadBandwidth; pub use max_events::MaxEventsPerConn; +pub use shm::{dump, BucketEntry, Dump, DEFAULT_PATH}; #[cfg(feature = "nscript")] pub use nscript::NScriptRead; diff --git a/src/readfilters/shm.rs b/src/readfilters/shm.rs index 4705701..3c62694 100644 --- a/src/readfilters/shm.rs +++ b/src/readfilters/shm.rs @@ -67,6 +67,11 @@ const MAGIC: u64 = u64::from_le_bytes(*b"NGRDBW\x00\x01"); /// (→ fail open), rather than misinterpreting its bytes. const VERSION: u32 = 1; +/// The conventional shared-memory path for the read-bandwidth buckets, on +/// `tmpfs`. The default the `read_bandwidth` filter documents and the +/// [`dump`] operator tool falls back to when given no explicit path. +pub const DEFAULT_PATH: &str = "/dev/shm/noteguard-read-bandwidth"; + /// Fixed key capacity: an IPv6 textual address is at most 45 bytes /// (`INET6_ADDRSTRLEN`-ish), and the `conn:` fallback is at most ~25, so 48 /// covers every key. A longer key fails open. @@ -330,12 +335,8 @@ impl SharedByteBuckets { let state = unsafe { &*addr_of!((*hdr).init_state) }; let mut spins = 0u64; loop { - match state.compare_exchange( - UNINIT, - INITIALIZING, - Ordering::Acquire, - Ordering::Acquire, - ) { + match state.compare_exchange(UNINIT, INITIALIZING, Ordering::Acquire, Ordering::Acquire) + { Ok(_) => { unsafe { addr_of_mut!((*hdr).magic).write(MAGIC); @@ -440,6 +441,126 @@ impl SharedByteBuckets { } } +/// One OCCUPIED bucket, as read by [`dump`]. A read-only, best-effort snapshot +/// of a slot's body — see [`dump`] for the lock-free-read caveat. +#[derive(Debug, Clone)] +pub struct BucketEntry { + /// The slot's key: the client IP text, or a `conn:` fallback. Rendered + /// lossily (keys are ASCII in practice, but a corrupt/foreign file might not + /// be, and a diagnostic tool must never panic on the bytes it finds). + pub key: String, + /// Bucket balance in bytes at the instant of the snapshot, exactly as last + /// written by a metering process — NOT refilled to now (the caller can do + /// that against [`Dump::now_ns`] if it knows the capacity). + pub tokens: f64, + /// This slot's last refill, in `CLOCK_MONOTONIC` nanoseconds — comparable to + /// [`Dump::now_ns`] (both read the same host-wide clock). + pub last_refill_ns: u64, +} + +/// The result of a [`dump`]: the table's configured `slot_count`, a monotonic +/// clock reading captured at dump time (so each entry can be aged against the +/// same clock the buckets use), and every OCCUPIED slot. +#[derive(Debug, Clone)] +pub struct Dump { + /// Total slot capacity of the table (from the header) — power of two. + pub slot_count: u32, + /// `CLOCK_MONOTONIC` nanoseconds captured just before scanning the slots. + /// Subtract an entry's `last_refill_ns` for its age; the difference can be + /// negative for an entry carried across a reboot (the clock reset), which a + /// caller should treat as stale. + pub now_ns: u64, + /// Every OCCUPIED slot, in slot order (unsorted). + pub entries: Vec, +} + +/// Read-only, best-effort snapshot of the shared byte-bucket table at `path`, +/// for operator inspection (the `noteguard dump-buckets` CLI). Opens the file +/// **read-only** and maps it **read-only**: it never writes, so it cannot perturb +/// live metering or leave a slot lock wedged. Validates the header's magic and +/// version (a mismatch or an under-sized file is a clear `InvalidData` error) +/// before trusting any offset. +/// +/// **Lock-free by design.** Unlike the metering paths, `dump` does *not* take +/// each slot's spinlock: acquiring the lock writes to the mapping, which a +/// read-only tool must not do (a tool that died mid-hold would wedge a live +/// slot). Instead it reads each field directly. This is sound as a diagnostic: +/// a slot's `key`/`key_len` are written once under lock at claim time and are +/// immutable thereafter (entries are never evicted), so an OCCUPIED slot's key +/// never tears; `tokens`/`last_refill` are naturally-aligned 8-byte words whose +/// reads don't tear on the single-host, coherent-cache architectures this table +/// targets, though either may read an instant stale versus a concurrent refill. +/// Good enough to peek at; never authoritative. +pub fn dump(path: &str) -> io::Result { + let file = OpenOptions::new().read(true).open(path)?; + let len = file.metadata()?.len() as usize; + if len < HEADER_SIZE { + return Err(invalid("shared byte-bucket file smaller than its header")); + } + // SAFETY: read-only mapping of a file at least `HEADER_SIZE` long; nothing + // else holds a `&mut` to these bytes in this process. + let mmap = unsafe { MmapOptions::new().len(len).map(&file)? }; + let base = mmap.as_ptr(); + + // Validate the header before trusting the slot_count it claims. + let hdr = base as *const Header; + let (magic, version, slot_count) = unsafe { + ( + addr_of!((*hdr).magic).read(), + addr_of!((*hdr).version).read(), + addr_of!((*hdr).slot_count).read(), + ) + }; + if magic != MAGIC { + return Err(invalid("shared byte-bucket file has wrong magic")); + } + if version != VERSION { + return Err(invalid("shared byte-bucket file version mismatch")); + } + + // The file must be large enough to hold the slot table the header claims, + // or a slot read would run off the mapping. + let slot_count = slot_count as usize; + let need = HEADER_SIZE + slot_count * SLOT_SIZE; + if len < need { + return Err(invalid( + "shared byte-bucket file truncated (smaller than its slot table)", + )); + } + + let now_ns = monotonic_ns(); + let mut entries = Vec::new(); + for i in 0..slot_count { + // SAFETY: `i < slot_count` and the file is >= HEADER_SIZE + slot_count*SLOT_SIZE. + let slot = unsafe { (base.add(HEADER_SIZE) as *const Slot).add(i) }; + if unsafe { addr_of!((*slot).state).read() } != OCCUPIED { + continue; + } + let key_len = unsafe { addr_of!((*slot).key_len).read() } as usize; + // Defensive: never trust an out-of-range key_len from a corrupt file. + if key_len > KEY_LEN { + continue; + } + let key = unsafe { + let p = addr_of!((*slot).key) as *const u8; + String::from_utf8_lossy(std::slice::from_raw_parts(p, key_len)).into_owned() + }; + let tokens = f64::from_bits(unsafe { addr_of!((*slot).tokens).read() }); + let last_refill_ns = unsafe { addr_of!((*slot).last_refill).read() }; + entries.push(BucketEntry { + key, + tokens, + last_refill_ns, + }); + } + + Ok(Dump { + slot_count: slot_count as u32, + now_ns, + entries, + }) +} + #[cfg(test)] mod tests { use super::*; @@ -500,7 +621,10 @@ mod tests { m.tokens_after_refill(b"9.9.9.9", cap); m.spend(b"9.9.9.9", cap, 250.0); let t = m.tokens_after_refill(b"9.9.9.9", cap).unwrap(); - assert!(t < 0.0, "overspend should leave a negative balance, got {t}"); + assert!( + t < 0.0, + "overspend should leave a negative balance, got {t}" + ); } #[test] @@ -636,4 +760,46 @@ mod tests { // shard against a different-sized table. assert!(SharedByteBuckets::open(&tf.0, 128).is_err()); } + + #[test] + fn dump_reports_occupied_buckets() { + // The operator peek: write two known buckets through the metering paths, + // drop the map, then read them back read-only via `dump`. + let tf = TmpFile::new("dump"); + let cap = 1000.0; + { + let m = SharedByteBuckets::open(&tf.0, 64).unwrap(); + m.tokens_after_refill(b"1.2.3.4", cap); // full + m.spend(b"1.2.3.4", cap, 600.0); // ~400 left + m.tokens_after_refill(b"5.6.7.8", cap); // full + } + let d = dump(&tf.0).unwrap(); + assert_eq!(d.slot_count, 64); + assert_eq!(d.entries.len(), 2, "exactly the two OCCUPIED slots"); + + let by_key = |k: &str| { + d.entries + .iter() + .find(|e| e.key == k) + .unwrap_or_else(|| panic!("missing bucket for {k}")) + }; + assert!((by_key("1.2.3.4").tokens - 400.0).abs() < 1.0); + assert!((by_key("5.6.7.8").tokens - 1000.0).abs() < 1.0); + + // Both slots were just refilled, so their ages are small & non-negative + // against the same monotonic clock `dump` captured. + for e in &d.entries { + let age = d.now_ns as i128 - e.last_refill_ns as i128; + assert!(age >= 0, "fresh dump should not see a future last_refill"); + } + } + + #[test] + fn dump_rejects_a_non_bucket_file() { + // A file that isn't a bucket table (wrong magic) is a clear error, not a + // pile of garbage rows. + let tf = TmpFile::new("dump-bad"); + std::fs::write(&tf.0, b"this is definitely not a noteguard bucket file..").unwrap(); + assert!(dump(&tf.0).is_err()); + } }