use std::collections::{HashSet, VecDeque};
use std::net::IpAddr;
use std::time::{Duration, Instant};
use crate::journal::settle::Settled;
use crate::model::capture::CaptureCounts;
use crate::report::{ScannerKind, StopReason};
use crate::scanner::audit::ProbeAudit;
use crate::scanner::pacing::deadline::AdaptiveDeadline;
use crate::scanner::pacing::retry::{Due, ProbeLedger};
use crate::scanner::session::ScanContext;
pub struct HostSweep<T> {
pub ledger: ProbeLedger<IpAddr, T>,
pub due: Vec<Due<IpAddr>>,
pub retries: VecDeque<IpAddr>,
pub responded: HashSet<IpAddr>,
pub audit: ProbeAudit,
}
impl<T: Copy + PartialEq> HostSweep<T> {
pub fn new(ledger: ProbeLedger<IpAddr, T>) -> Self {
Self {
ledger,
due: Vec::new(),
retries: VecDeque::new(),
responded: HashSet::new(),
audit: ProbeAudit::new(),
}
}
pub fn service_retries(&mut self, ctx: &ScanContext, now: Instant) {
self.drain_into_retries(ctx, now, true);
}
pub fn service_retries_without_settling(&mut self, ctx: &ScanContext, now: Instant) {
self.drain_into_retries(ctx, now, false);
}
fn drain_into_retries(&mut self, ctx: &ScanContext, now: Instant, settles: bool) {
let mut due = std::mem::take(&mut self.due);
self.ledger.drain_due(now, &mut due);
self.absorb_due(ctx, &mut due, settles);
self.due = due;
}
pub fn service_second_ledger<U: Copy + PartialEq>(
&mut self,
ctx: &ScanContext,
other: &mut ProbeLedger<IpAddr, U>,
now: Instant,
) {
let settles = true;
let mut due = std::mem::take(&mut self.due);
other.drain_due(now, &mut due);
self.absorb_due(ctx, &mut due, settles);
self.due = due;
}
fn absorb_due(&mut self, ctx: &ScanContext, due: &mut Vec<Due<IpAddr>>, settles: bool) {
for event in due.drain(..) {
match event {
Due::Retry { key, .. } => self.retries.push_back(key),
Due::Exhausted { key, .. } => {
if settles {
ctx.settle_address(key, Settled::Exhausted);
}
}
}
}
}
pub fn idle_delay(&self, deadline: &AdaptiveDeadline, now: Instant) -> Duration {
let until_deadline_tick = deadline.time_until_next_tick();
match self.ledger.next_due() {
Some(due) => until_deadline_tick.min(due.saturating_duration_since(now)),
None => until_deadline_tick,
}
}
pub fn all_responded(&self, target_count: u128) -> bool {
self.responded.len() as u128 >= target_count
}
pub fn note_answered(&mut self, target: IpAddr) -> bool {
self.responded.insert(target)
}
pub fn report(
&mut self,
ctx: &ScanContext,
label: &str,
kind: ScannerKind,
targets: u128,
reason: StopReason,
capture: Option<CaptureCounts>,
) {
self.audit.report(label, targets, reason, capture, None);
ctx.record_probe_stats(self.audit.stats(kind, targets, reason, capture, None));
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::journal::settle::Outcome;
use crate::model::ip::set::IpSet;
use crate::scanner::pacing::retry::RetryPolicy;
use crate::scanner::session::ScanSession;
use std::str::FromStr;
const ONE_SHOT: RetryPolicy = RetryPolicy::new(
1,
Duration::from_millis(10),
Duration::from_millis(1),
Duration::from_millis(20),
1.0,
0.0,
None,
);
fn counting(written: &str) -> (crate::scanner::session::ScanContext, IpAddr) {
let plan = IpSet::from_str(written).expect("a range");
let first = plan.iter().next().expect("at least one address");
let (_session, ctx) = ScanSession::builder().counting(plan.positions()).build();
(ctx, first)
}
#[test]
fn an_exhausted_probe_settles_the_address_when_the_sweep_settles() {
let (ctx, host) = counting("127.0.0.1");
let mut sweep: HostSweep<()> = HostSweep::new(ProbeLedger::new(ONE_SHOT, 4));
let now = Instant::now();
sweep.ledger.arm(host, host, (), (), now);
sweep.service_retries(&ctx, now + Duration::from_millis(50));
assert_eq!(
ctx.settlements().count(Outcome::Answered { position: 0 }),
0
);
assert_eq!(
ctx.settlements().checkpoint().watermark,
1,
"the one position in the plan, earned by a spent budget"
);
}
#[test]
fn an_exhausted_probe_settles_nothing_when_the_sweep_does_not() {
let (ctx, host) = counting("127.0.0.1");
let mut sweep: HostSweep<()> = HostSweep::new(ProbeLedger::new(ONE_SHOT, 4));
let now = Instant::now();
sweep.ledger.arm(host, host, (), (), now);
sweep.service_retries_without_settling(&ctx, now + Duration::from_millis(50));
assert_eq!(
ctx.settlements().checkpoint().watermark,
0,
"nothing was earned, so nothing is skipped on a resume"
);
assert_eq!(ctx.settlements().settled_count(), 0);
}
#[test]
fn a_probe_with_budget_left_is_queued_rather_than_settled() {
let (ctx, host) = counting("127.0.0.1");
let policy = RetryPolicy::new(
3,
Duration::from_millis(10),
Duration::from_millis(1),
Duration::from_millis(20),
1.0,
0.0,
None,
);
let mut sweep: HostSweep<()> = HostSweep::new(ProbeLedger::new(policy, 4));
let now = Instant::now();
sweep.ledger.arm(host, host, (), (), now);
sweep.service_retries(&ctx, now + Duration::from_millis(50));
assert_eq!(sweep.retries.front(), Some(&host), "owed another attempt");
assert_eq!(ctx.settlements().settled_count(), 0);
}
#[test]
fn a_second_ledger_queues_and_settles_through_the_same_path() {
let (ctx, host) = counting("127.0.0.1");
let mut sweep: HostSweep<()> = HostSweep::new(ProbeLedger::new(ONE_SHOT, 4));
let mut other: ProbeLedger<IpAddr, ()> = ProbeLedger::new(ONE_SHOT, 4);
let now = Instant::now();
other.arm(host, host, (), (), now);
sweep.service_second_ledger(&ctx, &mut other, now + Duration::from_millis(50));
assert_eq!(
ctx.settlements().checkpoint().watermark,
1,
"the second schedule settles exactly as the first does"
);
}
#[test]
fn a_sweep_knows_when_every_target_has_answered() {
let mut sweep: HostSweep<()> = HostSweep::new(ProbeLedger::new(ONE_SHOT, 4));
let one: IpAddr = "192.0.2.1".parse().expect("literal");
let two: IpAddr = "192.0.2.2".parse().expect("literal");
assert!(sweep.note_answered(one), "the first sighting is news");
assert!(!sweep.note_answered(one), "the second is not");
assert!(!sweep.all_responded(2));
sweep.note_answered(two);
assert!(sweep.all_responded(2));
}
}