feat(stats): per-host stats and session events behind HOST_STATS

StatManager aggregates activity per host, so clients can see which hosts
are used, through which outbound, and which ones fail and need a rule.
The host is the requested domain, else a sniffed domain (TLS, HTTP, DNS),
else the destination IP. Recording happens only when HOST_STATS is true
(off by default), so servers skip the extra locks and allocations.

Per host (at most 2000 hosts; when full, the least recently seen tenth is
evicted in one pass):
- sessions, bytes of finished sessions, the outbound most recently chosen
- failed sessions (outbound connect/handshake failed, TCP and UDP), not
  included in the session count, so hosts that only ever fail show up
- the most recent destination IPs and ports (up to 8 each)

Each session start (sequence number, time in ms, host, outbound) also goes
into a ring of the most recent 20000 events, so clients can correlate
hosts that are accessed together, e.g. the hosts behind one web page.

"handled ... dst=<ip>:<port>" log lines append " sniffed=<domain>" when
the route was picked for a sniffed domain, so UDP flows (e.g. QUIC) to an
IP can be matched to the host they are counted under.

- RuntimeManager::get_host_stats() / get_host_events_since(seq)
- leaf_get_host_stats(rt_id, ctx, cb): sessions, failed, bytes, outbound,
  ips and ports as comma-separated strings
- leaf_reset_host_stats(rt_id)
- leaf_get_host_events(rt_id, since_seq, latest_seq, ctx, cb)
- tests: per-host counts, live + finished bytes, reset; event sequencing,
  bound, incremental reads; IPs under the sniffed domain; ports; failed
  sessions
This commit is contained in:
eric committed 2026-12-03 19:27:21 +08:00
1 parent 263cff16b7
commit 3e126eb063
5 files changed
+581 -3

No files matched your search

+125
View File
@@ -412,3 +412,128 @@ pub unsafe extern "C" fn leaf_get_outbound_traffic(
}
ERR_OK
}
/// Reports per-host activity since start (or the last reset).
///
/// The callback is invoked once per host. The host is the requested domain,
/// else a sniffed domain, else the destination IP; `outbound` is the outbound
/// most recently chosen for it. At most 2000 hosts are tracked.
///
/// Host stats are recorded only when the `HOST_STATS` environment variable is
/// set to true before leaf starts; otherwise nothing is reported.
///
/// @param rt_id The ID of the leaf instance.
/// @param context User-provided context pointer passed back to the callback.
/// @param callback Arguments: host, outbound, ips (comma-separated destination
/// IPs, most recent first), ports (comma-separated destination
/// ports, most recent first), sessions, failed sessions,
/// bytes_sent, bytes_recvd, last_seen (unix seconds), context.
/// @return Returns ERR_OK on success.
#[no_mangle]
pub unsafe extern "C" fn leaf_get_host_stats(
rt_id: u16,
context: *mut std::ffi::c_void,
callback: extern "C" fn(
*const c_char,
*const c_char,
*const c_char,
*const c_char,
u64,
u64,
u64,
u64,
u32,
*mut std::ffi::c_void,
),
) -> i32 {
let manager = leaf::RUNTIME_MANAGER.lock().unwrap().get(&rt_id).cloned();
let Some(m) = manager else {
return to_errno(leaf::Error::RuntimeManager);
};
let stats = m.stat_manager().blocking_read().host_stats();
for (host, h) in stats {
if let (Ok(host), Ok(outbound), Ok(ips), Ok(ports)) = (
std::ffi::CString::new(host),
std::ffi::CString::new(h.outbound),
std::ffi::CString::new(h.ips.join(",")),
std::ffi::CString::new(
h.ports
.iter()
.map(|p| p.to_string())
.collect::<Vec<_>>()
.join(","),
),
) {
callback(
host.as_ptr(),
outbound.as_ptr(),
ips.as_ptr(),
ports.as_ptr(),
h.count,
h.failed,
h.sent,
h.recvd,
h.last_seen,
context,
);
}
}
ERR_OK
}
/// Clears per-host activity.
///
/// @param rt_id The ID of the leaf instance.
/// @return Returns ERR_OK on success.
#[no_mangle]
pub extern "C" fn leaf_reset_host_stats(rt_id: u16) -> i32 {
let manager = leaf::RUNTIME_MANAGER.lock().unwrap().get(&rt_id).cloned();
let Some(m) = manager else {
return to_errno(leaf::Error::RuntimeManager);
};
m.stat_manager().blocking_read().reset_host_stats();
ERR_OK
}
/// Reports session-start events (host, outbound, time) newer than `since_seq`.
///
/// Events are kept in a ring of the most recent 20000 sessions; clients can use
/// them to correlate hosts accessed together. Sequence numbers start at 1 and
/// restart when leaf restarts.
/// Recorded only when `HOST_STATS` is enabled, as for `leaf_get_host_stats`.
///
/// @param rt_id The ID of the leaf instance.
/// @param since_seq Only events with a greater sequence number are reported.
/// @param latest_seq If not null, receives the latest sequence number issued.
/// @param context User-provided context pointer passed back to the callback.
/// @param callback Arguments: seq, unix time in ms, host, outbound, context.
/// @return Returns ERR_OK on success.
#[no_mangle]
pub unsafe extern "C" fn leaf_get_host_events(
rt_id: u16,
since_seq: u64,
latest_seq: *mut u64,
context: *mut std::ffi::c_void,
callback: extern "C" fn(u64, u64, *const c_char, *const c_char, *mut std::ffi::c_void),
) -> i32 {
let manager = leaf::RUNTIME_MANAGER.lock().unwrap().get(&rt_id).cloned();
let Some(m) = manager else {
return to_errno(leaf::Error::RuntimeManager);
};
let (events, latest) = m
.stat_manager()
.blocking_read()
.host_events_since(since_seq);
if !latest_seq.is_null() {
unsafe { *latest_seq = latest };
}
for e in events {
if let (Ok(host), Ok(outbound)) = (
std::ffi::CString::new(e.host),
std::ffi::CString::new(e.outbound),
) {
callback(e.seq, e.ts_ms, host.as_ptr(), outbound.as_ptr(), context);
}
}
ERR_OK
}
+25 -3
View File
@@ -89,6 +89,16 @@ impl OutboundDatagram for HealthcheckUdpDatagram {
fn log_request(sess: &Session, outbound_tag: &str, handshake_time: Option<u128>) {
let hs = handshake_time.map_or("failed".to_string(), |hs| format!("{}ms", hs));
let network = sess.network.to_string();
// When the destination is an IP, also show the domain the route was picked for (sniffed
// from TLS / HTTP / DNS), so IP-only log lines can be traced back to a host.
let sniffed = if sess.destination.is_domain() {
String::new()
} else {
match sess.destination_for_routing() {
Ok(d) if d.is_domain() => format!(" sniffed={}", d.host()),
_ => String::new(),
}
};
#[cfg(feature = "rule-process-name")]
{
@@ -103,7 +113,7 @@ fn log_request(sess: &Session, outbound_tag: &str, handshake_time: Option<u128>)
})
.unwrap_or("");
info!(
"handled process={} src={} proto={} in={} out={} connect={} dst={}",
"handled process={} src={} proto={} in={} out={} connect={} dst={}{}",
process_name,
sess.forwarded_source.unwrap_or_else(|| sess.source.ip()),
network,
@@ -111,19 +121,21 @@ fn log_request(sess: &Session, outbound_tag: &str, handshake_time: Option<u128>)
outbound_tag,
hs,
&sess.destination,
sniffed,
);
}
#[cfg(not(feature = "rule-process-name"))]
{
info!(
"handled src={} proto={} in={} out={} connect={} dst={}",
"handled src={} proto={} in={} out={} connect={} dst={}{}",
sess.forwarded_source.unwrap_or_else(|| sess.source.ip()),
network,
&sess.inbound_tag,
outbound_tag,
hs,
&sess.destination,
sniffed,
);
}
}
@@ -287,6 +299,7 @@ impl Dispatcher {
e
);
log_request(&sess, h.tag(), None);
self.stat_manager.read().await.record_failed_session(&sess);
return;
}
};
@@ -344,6 +357,7 @@ impl Dispatcher {
Err(e) => {
debug!("outbound handle err={}", e);
log_request(&sess, h.tag(), None);
self.stat_manager.read().await.record_failed_session(&sess);
}
}
}
@@ -448,7 +462,14 @@ impl Dispatcher {
debug!("connect datagram outbound={}", h.tag());
let transport =
crate::proxy::connect_datagram_outbound(&sess, self.dns_client.clone(), &h).await?;
match crate::proxy::connect_datagram_outbound(&sess, self.dns_client.clone(), &h).await
{
Ok(t) => t,
Err(e) => {
self.stat_manager.read().await.record_failed_session(&sess);
return Err(e);
}
};
match h.datagram()?.handle(&sess, transport).await {
Ok(mut d) => {
@@ -473,6 +494,7 @@ impl Dispatcher {
Err(e) => {
debug!("outbound handle err={}", e);
log_request(&sess, h.tag(), None);
self.stat_manager.read().await.record_failed_session(&sess);
Err(e)
}
}
+410
View File
@@ -19,6 +19,115 @@ pub type SyncStatManager = Arc<RwLock<StatManager>>;
/// Cumulative (sent, recvd) bytes of finished sessions, keyed by outbound tag.
pub type OutboundTotals = Arc<std::sync::Mutex<HashMap<String, (u64, u64)>>>;
/// Per-host activity: sessions seen, bytes of finished sessions and the
/// outbound most recently chosen for the host.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct HostStat {
pub count: u64,
pub sent: u64,
pub recvd: u64,
pub outbound: String,
pub last_seen: u32,
/// Destination IPs seen for this host, most recent first (at most `MAX_HOST_IPS`).
pub ips: Vec<String>,
/// Destination ports seen for this host, most recent first (at most `MAX_HOST_PORTS`).
pub ports: Vec<u16>,
/// Sessions whose outbound connection failed (not included in `count`).
pub failed: u64,
}
/// Number of destination ports remembered per host.
pub const MAX_HOST_PORTS: usize = 8;
fn remember_port(ports: &mut Vec<u16>, sess: &Session) {
let port = sess.destination.port();
if port == 0 {
return;
}
if let Some(pos) = ports.iter().position(|x| *x == port) {
ports.remove(pos);
}
ports.insert(0, port);
ports.truncate(MAX_HOST_PORTS);
}
/// Number of destination IPs remembered per host.
pub const MAX_HOST_IPS: usize = 8;
fn remember_ip(ips: &mut Vec<String>, sess: &Session) {
if let SocksAddr::Ip(addr) = &sess.destination {
let ip = addr.ip().to_string();
if let Some(pos) = ips.iter().position(|x| *x == ip) {
ips.remove(pos);
}
ips.insert(0, ip);
ips.truncate(MAX_HOST_IPS);
}
}
pub type HostStats = Arc<std::sync::Mutex<HashMap<String, HostStat>>>;
/// Upper bound on tracked hosts; when reached, the least recently seen
/// `HOST_STATS_EVICT_BATCH` hosts are evicted together.
pub const MAX_HOST_STATS: usize = 2000;
/// Hosts evicted at once when the table is full, so the O(n) pass to find the
/// least recently seen hosts runs once per batch rather than once per new host.
pub const HOST_STATS_EVICT_BATCH: usize = MAX_HOST_STATS / 10;
/// Drops the `n` least recently seen hosts.
fn evict_oldest_hosts(hosts: &mut HashMap<String, HostStat>, n: usize) {
if n == 0 || hosts.is_empty() {
return;
}
if n >= hosts.len() {
hosts.clear();
return;
}
let mut ages: Vec<(u32, &String)> = hosts.iter().map(|(k, h)| (h.last_seen, k)).collect();
ages.select_nth_unstable_by_key(n - 1, |(ts, _)| *ts);
let victims: Vec<String> = ages[..n].iter().map(|(_, k)| (*k).clone()).collect();
for k in victims {
hosts.remove(&k);
}
}
/// A session start, kept in a bounded ring so clients can correlate hosts by time.
#[derive(Clone, Debug, PartialEq)]
pub struct HostEvent {
/// Monotonic sequence number, starting at 1.
pub seq: u64,
/// Unix time in milliseconds.
pub ts_ms: u64,
pub host: String,
pub outbound: String,
}
#[derive(Debug, Default)]
pub struct HostEventLog {
pub events: VecDeque<HostEvent>,
pub next_seq: u64,
}
pub type HostEvents = Arc<std::sync::Mutex<HostEventLog>>;
/// Number of session-start events retained.
pub const MAX_HOST_EVENTS: usize = 20000;
/// The name a session is reported under: the requested domain, else a sniffed
/// domain (TLS, HTTP, DNS), else the destination IP.
pub fn host_key(sess: &Session) -> String {
if let SocksAddr::Domain(domain, _) = &sess.destination {
return domain.clone();
}
sess.tls_sniffed_domain
.as_ref()
.or(sess.http_sniffed_domain.as_ref())
.or(sess.dns_sniffed_domain.as_ref())
.cloned()
.unwrap_or_else(|| sess.destination.host())
}
pub struct Stream {
pub inner: AnyStream,
pub bytes_recvd: Arc<AtomicU64>,
@@ -191,6 +300,9 @@ pub struct Counter {
pub last_peer_active: Arc<AtomicU32>,
pub logged: Arc<AtomicBool>,
pub totals: OutboundTotals,
pub hosts: HostStats,
/// The host this session is counted under; `None` when host stats are off.
pub host: Option<String>,
}
impl Counter {
@@ -230,6 +342,14 @@ impl Counter {
totals.insert(self.sess.outbound_tag.clone(), (sent, recvd));
}
}
if let Some(host) = &self.host {
if let Ok(mut hosts) = self.hosts.lock() {
if let Some(h) = hosts.get_mut(host) {
h.sent += sent;
h.recvd += recvd;
}
}
}
let _g = self.sess.span.enter();
debug!(
"session end out={} dst={} tx={} rx={}",
@@ -263,6 +383,10 @@ pub struct StatManager {
pub tx: mpsc::UnboundedSender<u64>,
pub rx: Option<mpsc::UnboundedReceiver<u64>>,
pub outbound_totals: OutboundTotals,
pub host_stats: HostStats,
pub host_events: HostEvents,
/// Whether per-host stats and events are recorded (`HOST_STATS`).
pub host_stats_enabled: bool,
}
impl Default for StatManager {
@@ -276,6 +400,12 @@ impl Default for StatManager {
tx,
rx: Some(rx),
outbound_totals: Arc::new(std::sync::Mutex::new(HashMap::new())),
host_stats: Arc::new(std::sync::Mutex::new(HashMap::new())),
host_events: Arc::new(std::sync::Mutex::new(HostEventLog {
events: VecDeque::new(),
next_seq: 1,
})),
host_stats_enabled: *option::HOST_STATS,
}
}
}
@@ -372,6 +502,7 @@ impl StatManager {
let last_peer_active = Arc::new(AtomicU32::new(ts));
let id = self.next_id;
self.next_id += 1;
let host = self.record_host(&sess);
self.counters.insert(
id,
Counter {
@@ -385,6 +516,8 @@ impl StatManager {
last_peer_active: last_peer_active.clone(),
logged,
totals: self.outbound_totals.clone(),
hosts: self.host_stats.clone(),
host,
},
);
Box::new(Stream {
@@ -409,6 +542,7 @@ impl StatManager {
let last_peer_active = Arc::new(AtomicU32::new(ts));
let id = self.next_id;
self.next_id += 1;
let host = self.record_host(&sess);
self.counters.insert(
id,
Counter {
@@ -422,6 +556,8 @@ impl StatManager {
last_peer_active: last_peer_active.clone(),
logged,
totals: self.outbound_totals.clone(),
hosts: self.host_stats.clone(),
host,
},
);
Box::new(Stream {
@@ -450,6 +586,7 @@ impl StatManager {
let last_peer_active = Arc::new(AtomicU32::new(ts));
let id = self.next_id;
self.next_id += 1;
let host = self.record_host(&sess);
self.counters.insert(
id,
Counter {
@@ -463,6 +600,8 @@ impl StatManager {
last_peer_active: last_peer_active.clone(),
logged,
totals: self.outbound_totals.clone(),
hosts: self.host_stats.clone(),
host,
},
);
Box::new(Datagram {
@@ -506,6 +645,121 @@ impl StatManager {
v
}
/// Counts a session whose outbound connection failed, so hosts that never
/// connected (e.g. blocked direct destinations) still show up.
pub fn record_failed_session(&self, sess: &Session) {
self.record_host_inner(sess, true);
}
/// Counts a new session for its host and remembers the chosen outbound.
fn record_host(&self, sess: &Session) -> Option<String> {
self.record_host_inner(sess, false)
}
fn record_host_inner(&self, sess: &Session, failed: bool) -> Option<String> {
if !self.host_stats_enabled {
return None;
}
let host = host_key(sess);
if let Ok(mut log) = self.host_events.lock() {
let seq = log.next_seq;
log.next_seq += 1;
if log.events.len() >= MAX_HOST_EVENTS {
log.events.pop_front();
}
let ts_ms = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_millis() as u64)
.unwrap_or(0);
log.events.push_back(HostEvent {
seq,
ts_ms,
host: host.clone(),
outbound: sess.outbound_tag.clone(),
});
}
if let Ok(mut hosts) = self.host_stats.lock() {
let now = get_unix_timestamp();
if let Some(h) = hosts.get_mut(&host) {
if failed {
h.failed += 1;
} else {
h.count += 1;
}
h.last_seen = now;
if h.outbound != sess.outbound_tag {
h.outbound = sess.outbound_tag.clone();
}
remember_ip(&mut h.ips, sess);
remember_port(&mut h.ports, sess);
} else {
if hosts.len() >= MAX_HOST_STATS {
evict_oldest_hosts(&mut hosts, HOST_STATS_EVICT_BATCH);
}
let mut ips = Vec::new();
remember_ip(&mut ips, sess);
let mut ports = Vec::new();
remember_port(&mut ports, sess);
hosts.insert(
host.clone(),
HostStat {
count: if failed { 0 } else { 1 },
failed: if failed { 1 } else { 0 },
sent: 0,
recvd: 0,
outbound: sess.outbound_tag.clone(),
last_seen: now,
ips,
ports,
},
);
}
}
Some(host)
}
/// Per-host activity since start (or the last reset), including the
/// current bytes of live sessions.
pub fn host_stats(&self) -> Vec<(String, HostStat)> {
let mut map: HashMap<String, HostStat> = self
.host_stats
.lock()
.map(|h| h.clone())
.unwrap_or_default();
for c in self.counters.values() {
if c.logged.load(Ordering::Relaxed) {
continue;
}
let Some(host) = &c.host else { continue };
if let Some(h) = map.get_mut(host) {
h.sent += c.bytes_sent();
h.recvd += c.bytes_recvd();
}
}
map.into_iter().collect()
}
/// Session-start events with a sequence number greater than `since`, and the
/// latest sequence number issued (0 if none yet).
pub fn host_events_since(&self, since: u64) -> (Vec<HostEvent>, u64) {
let Ok(log) = self.host_events.lock() else {
return (Vec::new(), 0);
};
// Events are ordered by seq; skip the ones already seen.
let start = log.events.partition_point(|e| e.seq <= since);
(
log.events.iter().skip(start).cloned().collect(),
log.next_seq - 1,
)
}
/// Forgets all per-host activity.
pub fn reset_host_stats(&self) {
if let Ok(mut hosts) = self.host_stats.lock() {
hosts.clear();
}
}
pub fn since_last_peer_active(&self, outbound_tag: &str) -> Option<u32> {
self.get_last_peer_active(outbound_tag)
.map(|ts| get_unix_timestamp().saturating_sub(ts))
@@ -713,4 +967,160 @@ mod tests {
assert_eq!(sm.outbound_traffic(), before);
drop((d1, d2));
}
fn host_stats_manager() -> StatManager {
let mut sm = StatManager::new();
sm.host_stats_enabled = true;
sm
}
fn host_session(host: &str) -> Session {
Session {
outbound_tag: "Direct".to_string(),
destination: SocksAddr::try_from((host.to_string(), 443)).unwrap(),
..Default::default()
}
}
#[test]
fn host_stats_off_records_nothing() {
let mut sm = StatManager::new();
sm.host_stats_enabled = false;
let d = sm.stat_outbound_datagram(Box::new(MockOutboundDatagram), host_session("a.com"));
sm.record_failed_session(&host_session("b.com"));
assert!(sm.host_stats().is_empty());
assert_eq!(sm.host_events_since(0), (Vec::new(), 0));
assert!(sm.counters.values().all(|c| c.host.is_none()));
drop(d);
}
#[test]
fn host_stats_evict_least_recently_seen_in_a_batch() {
let sm = host_stats_manager();
for i in 0..MAX_HOST_STATS {
sm.record_failed_session(&host_session(&format!("h{}.com", i)));
}
// Make h0..h(BATCH-1) the oldest and everything else newer.
{
let mut hosts = sm.host_stats.lock().unwrap();
for (k, h) in hosts.iter_mut() {
let i: usize = k[1..k.len() - 4].parse().unwrap();
h.last_seen = if i < HOST_STATS_EVICT_BATCH {
1
} else {
1000 + i as u32
};
}
}
sm.record_failed_session(&host_session("new.com"));
let hosts = sm.host_stats.lock().unwrap();
assert_eq!(hosts.len(), MAX_HOST_STATS - HOST_STATS_EVICT_BATCH + 1);
assert!(hosts.contains_key("new.com"));
assert!((0..HOST_STATS_EVICT_BATCH).all(|i| !hosts.contains_key(&format!("h{}.com", i))));
assert!(hosts.contains_key(&format!("h{}.com", HOST_STATS_EVICT_BATCH)));
}
#[test]
fn host_stats_count_sessions_and_bytes_per_host() {
let mut sm = host_stats_manager();
let mk = |host: &str, out: &str| Session {
outbound_tag: out.to_string(),
destination: SocksAddr::try_from((host.to_string(), 443)).unwrap(),
..Default::default()
};
let a1 = sm.stat_outbound_datagram(Box::new(MockOutboundDatagram), mk("a.com", "Direct"));
let a2 = sm.stat_outbound_datagram(Box::new(MockOutboundDatagram), mk("a.com", "Proxy"));
let b = sm.stat_outbound_datagram(Box::new(MockOutboundDatagram), mk("1.2.3.4", "Proxy"));
for c in sm.counters.values() {
c.bytes_sent.store(1, Ordering::Relaxed);
c.bytes_recvd.store(10, Ordering::Relaxed);
}
let stats: HashMap<_, _> = sm.host_stats().into_iter().collect();
let a = &stats["a.com"];
assert_eq!(
(a.count, a.sent, a.recvd, a.outbound.as_str()),
(2, 2, 20, "Proxy")
);
assert_eq!(stats["1.2.3.4"].count, 1);
// Finished sessions keep their bytes, exactly once.
let ids: Vec<_> = sm.counters.keys().copied().collect();
for id in ids {
let c = sm.counters.remove(&id).unwrap();
c.log_session_end();
c.log_session_end();
}
let after: HashMap<_, _> = sm.host_stats().into_iter().collect();
assert_eq!(after, stats);
sm.reset_host_stats();
assert!(sm.host_stats().is_empty());
drop((a1, a2, b));
}
#[test]
fn host_events_are_sequenced_and_bounded() {
let mut sm = host_stats_manager();
let mut keep = Vec::new();
for i in 0..(MAX_HOST_EVENTS + 5) {
let sess = Session {
outbound_tag: "Direct".to_string(),
destination: SocksAddr::try_from((format!("h{}.com", i % 7), 443)).unwrap(),
..Default::default()
};
keep.push(sm.stat_outbound_datagram(Box::new(MockOutboundDatagram), sess));
}
let (all, latest) = sm.host_events_since(0);
assert_eq!(latest, (MAX_HOST_EVENTS + 5) as u64);
assert_eq!(all.len(), MAX_HOST_EVENTS);
assert_eq!(all.first().unwrap().seq, 6);
let (tail, _) = sm.host_events_since(latest - 3);
assert_eq!(
tail.iter().map(|e| e.seq).collect::<Vec<_>>(),
vec![latest - 2, latest - 1, latest]
);
assert!(sm.host_events_since(latest).0.is_empty());
drop(keep);
}
#[test]
fn host_stats_remember_destination_ips_under_sniffed_domain() {
let mut sm = host_stats_manager();
let mut keep = Vec::new();
for ip in ["18.136.169.56", "18.136.169.57", "18.136.169.56"] {
let sess = Session {
outbound_tag: "Direct".to_string(),
destination: SocksAddr::from(SocketAddr::new(ip.parse().unwrap(), 443)),
dns_sniffed_domain: Some("app.slack.com".to_string()),
..Default::default()
};
keep.push(sm.stat_outbound_datagram(Box::new(MockOutboundDatagram), sess));
}
let stats: HashMap<_, _> = sm.host_stats().into_iter().collect();
let h = &stats["app.slack.com"];
assert_eq!(h.count, 3);
assert_eq!(h.ips, vec!["18.136.169.56", "18.136.169.57"]);
assert_eq!(h.ports, vec![443]);
assert_eq!(h.failed, 0);
drop(keep);
}
#[test]
fn host_stats_count_failed_sessions() {
let sm = host_stats_manager();
let sess = Session {
outbound_tag: "Direct".to_string(),
destination: SocksAddr::try_from(("blocked.example".to_string(), 443)).unwrap(),
..Default::default()
};
sm.record_failed_session(&sess);
sm.record_failed_session(&sess);
let stats: HashMap<_, _> = sm.host_stats().into_iter().collect();
let h = &stats["blocked.example"];
assert_eq!((h.count, h.failed), (0, 2));
assert_eq!(h.outbound, "Direct");
assert_eq!(h.ports, vec![443]);
let keep: Vec<()> = Vec::new();
drop(keep);
}
}
+13
View File
@@ -207,6 +207,19 @@ impl RuntimeManager {
self.stat_manager.read().await.outbound_traffic()
}
/// Per-host activity since start (or the last reset).
pub async fn get_host_stats(&self) -> Vec<(String, app::stat_manager::HostStat)> {
self.stat_manager.read().await.host_stats()
}
/// Session-start events after `since`, plus the latest sequence number.
pub async fn get_host_events_since(
&self,
since: u64,
) -> (Vec<app::stat_manager::HostEvent>, u64) {
self.stat_manager.read().await.host_events_since(since)
}
/// Get the last peer active time (in seconds) for an outbound
pub async fn get_outbound_last_peer_active(
&self,
+8
View File
@@ -90,6 +90,14 @@ lazy_static! {
get_env_var_or("MAX_RECENT_CONNECTIONS", 0)
};
/// Track per-host activity (sessions, traffic, destination IPs and ports)
/// and a ring of recent session-start events, as reported by
/// `leaf_get_host_stats` / `leaf_get_host_events`. Meant for clients; off by
/// default so servers don't pay for it.
pub static ref HOST_STATS: bool = {
get_env_bool("HOST_STATS", false)
};
pub static ref HTTP_USER_AGENT: String = {
get_env_var_or_else(
"HTTP_USER_AGENT",