diff --git a/leaf-ffi/src/lib.rs b/leaf-ffi/src/lib.rs index 77927e0..b650c8f 100644 --- a/leaf-ffi/src/lib.rs +++ b/leaf-ffi/src/lib.rs @@ -382,3 +382,33 @@ pub unsafe extern "C" fn leaf_get_since_last_active( Err(e) => to_errno(e), } } + +/// Reports per-outbound traffic since start. +/// +/// The callback is invoked once per outbound tag with the cumulative number of +/// bytes sent (upload) and received (download), including live sessions. +/// +/// @param rt_id The ID of the leaf instance. +/// @param context User-provided context pointer passed back to the callback. +/// @param callback Arguments: tag, bytes_sent, bytes_recvd, context. +/// @return Returns ERR_OK on success. +#[no_mangle] +pub unsafe extern "C" fn leaf_get_outbound_traffic( + rt_id: u16, + context: *mut std::ffi::c_void, + callback: extern "C" fn(*const c_char, u64, u64, *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); + }; + // Called from a non-async thread (e.g. the tunnel provider), so take the + // lock synchronously instead of spinning up a tokio runtime per call. + let stats = m.stat_manager().blocking_read().outbound_traffic(); + for (tag, sent, recvd) in stats { + if let Ok(tag) = std::ffi::CString::new(tag) { + callback(tag.as_ptr(), sent, recvd, context); + } + } + ERR_OK +} diff --git a/leaf/src/app/stat_manager.rs b/leaf/src/app/stat_manager.rs index 672dead..e75f859 100644 --- a/leaf/src/app/stat_manager.rs +++ b/leaf/src/app/stat_manager.rs @@ -16,6 +16,9 @@ use crate::{option, proxy::*, session::*}; pub type SyncStatManager = Arc>; +/// Cumulative (sent, recvd) bytes of finished sessions, keyed by outbound tag. +pub type OutboundTotals = Arc>>; + pub struct Stream { pub inner: AnyStream, pub bytes_recvd: Arc, @@ -187,6 +190,7 @@ pub struct Counter { pub send_completed: Arc, pub last_peer_active: Arc, pub logged: Arc, + pub totals: OutboundTotals, } impl Counter { @@ -216,6 +220,16 @@ impl Counter { pub fn log_session_end(&self) { if !self.logged.swap(true, Ordering::Relaxed) { + let (sent, recvd) = (self.bytes_sent(), self.bytes_recvd()); + if let Ok(mut totals) = self.totals.lock() { + // Only allocate the key the first time an outbound tag is seen. + if let Some(e) = totals.get_mut(&self.sess.outbound_tag) { + e.0 += sent; + e.1 += recvd; + } else { + totals.insert(self.sess.outbound_tag.clone(), (sent, recvd)); + } + } let _g = self.sess.span.enter(); debug!( "session end out={} dst={} tx={} rx={}", @@ -248,6 +262,7 @@ pub struct StatManager { pub next_id: u64, pub tx: mpsc::UnboundedSender, pub rx: Option>, + pub outbound_totals: OutboundTotals, } impl Default for StatManager { @@ -260,6 +275,7 @@ impl Default for StatManager { next_id: 1, tx, rx: Some(rx), + outbound_totals: Arc::new(std::sync::Mutex::new(HashMap::new())), } } } @@ -368,6 +384,7 @@ impl StatManager { send_completed: send_completed.clone(), last_peer_active: last_peer_active.clone(), logged, + totals: self.outbound_totals.clone(), }, ); Box::new(Stream { @@ -404,6 +421,7 @@ impl StatManager { send_completed: send_completed.clone(), last_peer_active: last_peer_active.clone(), logged, + totals: self.outbound_totals.clone(), }, ); Box::new(Stream { @@ -444,6 +462,7 @@ impl StatManager { send_completed: send_completed.clone(), last_peer_active: last_peer_active.clone(), logged, + totals: self.outbound_totals.clone(), }, ); Box::new(Datagram { @@ -466,6 +485,27 @@ impl StatManager { .max() } + /// Per-outbound traffic since start: (tag, bytes_sent, bytes_recvd), + /// including finished sessions and the current bytes of live ones. + pub fn outbound_traffic(&self) -> Vec<(String, u64, u64)> { + let mut map: HashMap = self + .outbound_totals + .lock() + .map(|t| t.clone()) + .unwrap_or_default(); + for c in self.counters.values() { + if c.logged.load(Ordering::Relaxed) { + continue; + } + let e = map.entry(c.sess.outbound_tag.clone()).or_insert((0, 0)); + e.0 += c.bytes_sent(); + e.1 += c.bytes_recvd(); + } + let mut v: Vec<_> = map.into_iter().map(|(k, (s, r))| (k, s, r)).collect(); + v.sort_by(|a, b| a.0.cmp(&b.0)); + v + } + pub fn since_last_peer_active(&self, outbound_tag: &str) -> Option { self.get_last_peer_active(outbound_tag) .map(|ts| get_unix_timestamp().saturating_sub(ts)) @@ -649,4 +689,28 @@ mod tests { .expect("unsplit datagram drop should enqueue cleanup"); assert_eq!(id, 1); } + + #[test] + fn outbound_traffic_counts_closed_and_live_sessions() { + let mut sm = StatManager::new(); + let mk = |tag: &str| Session { + outbound_tag: tag.to_string(), + ..Default::default() + }; + let d1 = sm.stat_outbound_datagram(Box::new(MockOutboundDatagram), mk("Direct")); + let d2 = sm.stat_outbound_datagram(Box::new(MockOutboundDatagram), mk("Proxy")); + for (i, c) in sm.counters.values().enumerate() { + c.bytes_sent.store(10 * (i as u64 + 1), Ordering::Relaxed); + c.bytes_recvd.store(100 * (i as u64 + 1), Ordering::Relaxed); + } + let before = sm.outbound_traffic(); + // Close one session; its bytes must move into the totals exactly once. + let id = *sm.counters.keys().next().unwrap(); + let closed = sm.counters.remove(&id).unwrap(); + closed.log_session_end(); + closed.log_session_end(); + drop(closed); + assert_eq!(sm.outbound_traffic(), before); + drop((d1, d2)); + } } diff --git a/leaf/src/lib.rs b/leaf/src/lib.rs index 154c55e..4aa9e5d 100644 --- a/leaf/src/lib.rs +++ b/leaf/src/lib.rs @@ -202,6 +202,11 @@ impl RuntimeManager { Err(Error::Config(anyhow!("selector {} not found", outbound))) } + /// Per-outbound traffic since start: (tag, bytes_sent, bytes_recvd). + pub async fn get_outbound_traffic(&self) -> Vec<(String, u64, u64)> { + self.stat_manager.read().await.outbound_traffic() + } + /// Get the last peer active time (in seconds) for an outbound pub async fn get_outbound_last_peer_active( &self,