From e35f688d28ad8675bac5bacc8c6d88636f7047e9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Robert=20Chac=C3=B3n?= Date: Tue, 24 Jun 2025 19:48:26 -0600 Subject: [PATCH 01/16] Update integrations.md --- docs/v2.0/integrations.md | 48 +++++++++++++++++++-------------------- 1 file changed, 23 insertions(+), 25 deletions(-) diff --git a/docs/v2.0/integrations.md b/docs/v2.0/integrations.md index 62b47249..c9b82b4d 100644 --- a/docs/v2.0/integrations.md +++ b/docs/v2.0/integrations.md @@ -18,31 +18,29 @@ First, set the relevant parameters for Splynx (splynx_api_key, splynx_api_secret The Splynx Integration uses Basic authentication. For using this type of authentication, please make sure you enable [Unsecure access](https://splynx.docs.apiary.io/#introduction/authentication) in your Splynx API key settings. Also the Splynx API key should be granted access to the necessary permissions. -* Tariff Plans -> Internet -> view -* Tariff Plans -> Bundle -> view -* Tariff Plans -> One time -> view -* Tariff Plans -> Recurring -> view -* FUP -> Counter -> view -* FUP -> Compiler -> view -* FUP -> Policies -> view -* FUP -> Capped Data -> view -* FUP -> CAP Tariff -> view -* FUP -> FUP Limits -> view -* FUP -> Traffic Usage -> view -* Customers -> customer -> view -* Customers -> customer information -> view -* Customers -> Customers online -> view -* Customers -> customer bundle services -> view -* Customers -> customer internet services -> view -* Customers -> traffic counter -> view -* Customers -> customer recurring services -> view -* Customers -> bonus traffic counter -> view -* Customers -> CAP history -> view -* Networking -> routers -> view -* Networking -> network sites >view -* Networking -> router contention -> view -* Networking -> IPv4 networks -> view -* Networking -> IPv4 networks IP -> view +| Category | Name | Permission | +|----------------|------------------------------|------------| +| Tariff Plans | Internet | View | +| FUP | Compiler | View | +| FUP | Policies | View | +| FUP | Capped Data | View | +| FUP | CAP Tariff | View | +| FUP | FUP Limits | View | +| Customers | Customer | View | +| Customers | Customers Online | View | +| Customers | Customer Internet services | View | +| Networking | Routers | View | +| Networking | Router contention | View | +| Networking | MikroTik | View | +| Networking | Monitoring | View | +| Networking | Network Sites | View | +| Networking | IPv4 Networks | View | +| Networking | IPv4 Networks IP | View | +| Networking | CPE | View | +| Networking | CPE AP | View | +| Networking | IPv6 Networks | View | +| Networking | IPv6 Networks IP (Addresses) | View | +| Administration | Locations | View | To test the Splynx Integration, use -- knotmirror 0.0.1 From d3cc7bce57a4eff38a110f7b7776a80b298ed617 Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Wed, 25 Jun 2025 08:34:40 -0500 Subject: [PATCH 02/16] Fix: Clear prior settings before recreating the MQ devices --- src/rust/lqos_bakery/src/commands.rs | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/src/rust/lqos_bakery/src/commands.rs b/src/rust/lqos_bakery/src/commands.rs index 8844755b..30877fba 100644 --- a/src/rust/lqos_bakery/src/commands.rs +++ b/src/rust/lqos_bakery/src/commands.rs @@ -108,9 +108,27 @@ impl BakeryCommands { queues_available: usize, stick_offset: usize, ) -> Option>> { + let mut result = Vec::new(); + warn!("Clearing prior settings"); + if config.on_a_stick_mode() { + // Clear just the MQ on the ISP-facing interface + result.push(vec![ + "qdisc".to_string(), "del".to_string(), "dev".to_string(), + config.isp_interface(), "root".to_string() + ]); + } else { + result.push(vec![ + "qdisc".to_string(), "del".to_string(), "dev".to_string(), + config.isp_interface(), "root".to_string() + ]); + result.push(vec![ + "qdisc".to_string(), "del".to_string(), "dev".to_string(), + config.internet_interface(), "root".to_string() + ]); + } + info!("Setting up MQ with {} queues and stick offset {}", queues_available, stick_offset); // command = 'qdisc replace dev ' + thisInterface + ' root handle 7FFF: mq' - let mut result = Vec::new(); let sqm_strings = sqm_as_vec(config); let r2q = r2q(u64::max(config.queues.uplink_bandwidth_mbps, config.queues.downlink_bandwidth_mbps)); -- knotmirror 0.0.1 From 26283c6b666db08eea2919cfed7e69689c3cb3d4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Robert=20Chac=C3=B3n?= Date: Wed, 25 Jun 2025 14:16:00 -0600 Subject: [PATCH 03/16] Revert "fix duration underflow panic" --- src/rust/lqos_utils/src/unix_time.rs | 15 +------ src/rust/lqosd/src/anonymous_usage/mod.rs | 12 +---- .../node_manager/local_api/flow_explorer.rs | 15 ++----- .../lqosd/src/shaped_devices_tracker/mod.rs | 16 ++----- .../src/shaped_devices_tracker/netjson.rs | 14 ++---- .../flow_data/flow_analysis/finished_flows.rs | 44 ++----------------- src/rust/lqosd/src/throughput_tracker/mod.rs | 13 ------ 7 files changed, 15 insertions(+), 114 deletions(-) diff --git a/src/rust/lqos_utils/src/unix_time.rs b/src/rust/lqos_utils/src/unix_time.rs index a3e54573..5cd57b71 100644 --- a/src/rust/lqos_utils/src/unix_time.rs +++ b/src/rust/lqos_utils/src/unix_time.rs @@ -36,19 +36,8 @@ pub fn time_since_boot() -> Result { pub fn boot_time_nanos_to_unix_now(start_time_nanos_since_boot: u64) -> Result { let time_since_boot = time_since_boot()?; let since_boot = Duration::from(time_since_boot); - let current_unix_time = unix_now()?; - - // Use saturating_sub to prevent underflow panic - let boot_time = current_unix_time.saturating_sub(since_boot.as_secs()); - - // Add additional validation to prevent overflow - let start_time_secs = Duration::from_nanos(start_time_nanos_since_boot).as_secs(); - let result = boot_time.saturating_add(start_time_secs); - - tracing::debug!("Time conversion - current_unix: {}, since_boot: {}, boot_time: {}, start_time_secs: {}, result: {}", - current_unix_time, since_boot.as_secs(), boot_time, start_time_secs, result); - - Ok(result) + let boot_time = unix_now().unwrap() - since_boot.as_secs(); + Ok(boot_time + Duration::from_nanos(start_time_nanos_since_boot).as_secs()) } /// Error type for time functions. diff --git a/src/rust/lqosd/src/anonymous_usage/mod.rs b/src/rust/lqosd/src/anonymous_usage/mod.rs index 1badb5c5..f68f7600 100644 --- a/src/rust/lqosd/src/anonymous_usage/mod.rs +++ b/src/rust/lqosd/src/anonymous_usage/mod.rs @@ -77,17 +77,7 @@ fn anonymous_usage_dump() -> anyhow::Result<()> { data.git_hash = env!("GIT_HASH").to_string(); data.shaped_device_count = SHAPED_DEVICES.load().devices.len(); - - // Add error handling for mutex poisoning - match NETWORK_JSON.read() { - Ok(nj) => { - data.net_json_len = nj.get_nodes_when_ready().len(); - }, - Err(e) => { - tracing::error!("Failed to acquire NETWORK_JSON read lock in anonymous usage (possibly poisoned): {:?}", e); - data.net_json_len = 0; // Use default value - } - } + data.net_json_len = NETWORK_JSON.read().unwrap().get_nodes_when_ready().len(); data.high_watermark_bps = (HIGH_WATERMARK.get_down(), HIGH_WATERMARK.get_up()); diff --git a/src/rust/lqosd/src/node_manager/local_api/flow_explorer.rs b/src/rust/lqosd/src/node_manager/local_api/flow_explorer.rs index b8685ca4..eff2f7e4 100644 --- a/src/rust/lqosd/src/node_manager/local_api/flow_explorer.rs +++ b/src/rust/lqosd/src/node_manager/local_api/flow_explorer.rs @@ -43,10 +43,7 @@ pub struct FlowTimeline { pub async fn flow_timeline(Path(asn_id): Path) -> Json> { let time_since_boot = time_since_boot().unwrap(); let since_boot = Duration::from(time_since_boot); - let current_unix_time = unix_now().unwrap(); - - // Use saturating_sub to prevent underflow panic - let boot_time = current_unix_time.saturating_sub(since_boot.as_secs()); + let boot_time = unix_now().unwrap() - since_boot.as_secs(); let all_flows_for_asn = RECENT_FLOWS.all_flows_for_asn(asn_id); @@ -107,10 +104,7 @@ fn all_flows_to_transport( pub async fn country_timeline(Path(iso_code): Path) -> Json> { let time_since_boot = time_since_boot().unwrap(); let since_boot = Duration::from(time_since_boot); - let current_unix_time = unix_now().unwrap(); - - // Use saturating_sub to prevent underflow panic - let boot_time = current_unix_time.saturating_sub(since_boot.as_secs()); + let boot_time = unix_now().unwrap() - since_boot.as_secs(); let all_flows_for_asn = RECENT_FLOWS.all_flows_for_country(&iso_code); @@ -123,10 +117,7 @@ pub async fn protocol_timeline(Path(protocol_name): Path) -> Json { - crate::throughput_tracker::THROUGHPUT_TRACKER.refresh_circuit_ids(&nj); - STATS_NEEDS_NEW_SHAPED_DEVICES.store(true, std::sync::atomic::Ordering::Relaxed); - }, - Err(e) => { - error!("Failed to acquire NETWORK_JSON read lock (possibly poisoned): {:?}", e); - // Continue operation without refreshing circuit IDs - STATS_NEEDS_NEW_SHAPED_DEVICES.store(true, std::sync::atomic::Ordering::Relaxed); - } - } + let nj = NETWORK_JSON.read().unwrap(); + crate::throughput_tracker::THROUGHPUT_TRACKER.refresh_circuit_ids(&nj); + STATS_NEEDS_NEW_SHAPED_DEVICES.store(true, std::sync::atomic::Ordering::Relaxed); } else { warn!( "ShapedDevices.csv failed to load, see previous error messages. Reverting to empty set." diff --git a/src/rust/lqosd/src/shaped_devices_tracker/netjson.rs b/src/rust/lqosd/src/shaped_devices_tracker/netjson.rs index 69f5c3e6..8df7e314 100644 --- a/src/rust/lqosd/src/shaped_devices_tracker/netjson.rs +++ b/src/rust/lqosd/src/shaped_devices_tracker/netjson.rs @@ -43,17 +43,9 @@ fn watch_for_network_json_changing() -> Result<()> { fn load_network_json() { let njs = NetworkJson::load(); if let Ok(njs) = njs { - // Add error handling for mutex poisoning - match NETWORK_JSON.write() { - Ok(mut nj) => { - *nj = njs; - crate::throughput_tracker::THROUGHPUT_TRACKER.refresh_circuit_ids(&nj); - }, - Err(e) => { - error!("Failed to acquire NETWORK_JSON write lock (possibly poisoned): {:?}", e); - warn!("Skipping network.json update due to lock poisoning"); - } - } + let mut nj = NETWORK_JSON.write().unwrap(); + *nj = njs; + crate::throughput_tracker::THROUGHPUT_TRACKER.refresh_circuit_ids(&nj); } else { warn!("Unable to load network.json"); } diff --git a/src/rust/lqosd/src/throughput_tracker/flow_data/flow_analysis/finished_flows.rs b/src/rust/lqosd/src/throughput_tracker/flow_data/flow_analysis/finished_flows.rs index 0664a2a6..dcbf6a8f 100644 --- a/src/rust/lqosd/src/throughput_tracker/flow_data/flow_analysis/finished_flows.rs +++ b/src/rust/lqosd/src/throughput_tracker/flow_data/flow_analysis/finished_flows.rs @@ -269,22 +269,7 @@ impl TimeBuffer { buffer .iter() - .filter_map(|f| { - // Add bounds checking to prevent duration overflow - let start_time = f.data.1.start_time; - let last_seen = f.data.1.last_seen; - - if last_seen >= start_time { - let duration_nanos = last_seen - start_time; - tracing::debug!("Flow duration calculation - start: {}, end: {}, duration: {}", - start_time, last_seen, duration_nanos); - Some(Duration::from_nanos(duration_nanos)) - } else { - tracing::warn!("Invalid flow timing - last_seen ({}) < start_time ({}), skipping", - last_seen, start_time); - None - } - }) + .map(|f| Duration::from_nanos(f.data.1.last_seen - f.data.1.start_time)) // Duration in nanoseconds .map(|nanos| nanos.as_secs()) .sorted() .dedup_with_count() // Now we're (count, duration in seconds) @@ -468,31 +453,8 @@ impl FinishedFlowAnalysis { fn enqueue(key: FlowbeeKey, data: FlowbeeLocalData, analysis: FlowAnalysis) { debug!("Finished flow analysis"); - - // Add diagnostic logging for time conversion issues - tracing::debug!("Flow timing - start_time: {}, last_seen: {}", data.start_time, data.last_seen); - - let start_time = match boot_time_nanos_to_unix_now(data.start_time) { - Ok(time) => { - tracing::debug!("Converted start_time to unix: {}", time); - time - }, - Err(e) => { - tracing::error!("Failed to convert start_time {} to unix time: {:?}", data.start_time, e); - 0 - } - }; - - let last_seen = match boot_time_nanos_to_unix_now(data.last_seen) { - Ok(time) => { - tracing::debug!("Converted last_seen to unix: {}", time); - time - }, - Err(e) => { - tracing::error!("Failed to convert last_seen {} to unix time: {:?}", data.last_seen, e); - 0 - } - }; + let start_time = boot_time_nanos_to_unix_now(data.start_time).unwrap_or(0); + let last_seen = boot_time_nanos_to_unix_now(data.last_seen).unwrap_or(0); let one_way = data.bytes_sent.down == 0 || data.bytes_sent.up == 0; let sd = SHAPED_DEVICES.load(); diff --git a/src/rust/lqosd/src/throughput_tracker/mod.rs b/src/rust/lqosd/src/throughput_tracker/mod.rs index a3980922..0e4a523a 100644 --- a/src/rust/lqosd/src/throughput_tracker/mod.rs +++ b/src/rust/lqosd/src/throughput_tracker/mod.rs @@ -108,19 +108,6 @@ fn throughput_task( system_usage_actor: crossbeam_channel::Sender>, bakery_sender: crossbeam_channel::Sender, ) { - // Add diagnostic logging for time-related issues - tracing::info!("Throughput Monitor starting - checking system time"); - if let Ok(now) = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH) { - tracing::info!("System time since UNIX epoch: {:?}", now); - } else { - tracing::error!("System time is before UNIX epoch - this will cause duration overflow issues"); - } - - if let Ok(boot_time) = lqos_utils::unix_time::time_since_boot() { - tracing::info!("Time since boot: {:?}", boot_time); - } else { - tracing::error!("Unable to get time since boot - this may cause timing issues"); - } // Obtain the flow timeout from the config, default to 30 seconds let timeout_seconds = if let Ok(config) = lqos_config::load_config() { if let Some(flow_config) = &config.flows { -- knotmirror 0.0.1 From 78fe1270df316a9a753baa3b08a17f228235b0b9 Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Tue, 1 Jul 2025 10:47:22 -0500 Subject: [PATCH 04/16] Feat: update allocative flamegraph system. --- src/rust/Cargo.lock | 8 +++++ src/rust/Cargo.toml | 4 +++ src/rust/lqos_bakery/Cargo.toml | 2 ++ src/rust/lqos_bakery/src/commands.rs | 5 +-- src/rust/lqos_bus/Cargo.toml | 4 +-- src/rust/lqos_bus/src/anonymous/mod.rs | 3 +- src/rust/lqos_bus/src/anonymous/v1.rs | 5 +-- src/rust/lqos_bus/src/bus/queue_data.rs | 9 +++--- src/rust/lqos_bus/src/bus/reply.rs | 3 +- src/rust/lqos_bus/src/bus/request.rs | 9 +++--- src/rust/lqos_bus/src/bus/response.rs | 5 +-- src/rust/lqos_bus/src/bus/session.rs | 3 +- src/rust/lqos_bus/src/ip_stats.rs | 15 ++++----- src/rust/lqos_config/Cargo.toml | 4 +-- src/rust/lqos_config/src/authentication.rs | 7 +++-- .../src/etc/v15/anonymous_stats.rs | 3 +- src/rust/lqos_config/src/etc/v15/bridge.rs | 5 +-- src/rust/lqos_config/src/etc/v15/flows.rs | 3 +- src/rust/lqos_config/src/etc/v15/influxdb.rs | 3 +- .../src/etc/v15/integration_common.rs | 3 +- src/rust/lqos_config/src/etc/v15/ip_ranges.rs | 3 +- .../src/etc/v15/long_term_stats.rs | 3 +- .../src/etc/v15/powercode_integration.rs | 3 +- src/rust/lqos_config/src/etc/v15/queues.rs | 5 +-- .../src/etc/v15/sonar_integration.rs | 3 +- .../src/etc/v15/spylnx_integration.rs | 3 +- .../lqos_config/src/etc/v15/stormguard.rs | 3 +- .../lqos_config/src/etc/v15/top_config.rs | 3 +- src/rust/lqos_config/src/etc/v15/tuning.rs | 3 +- .../src/etc/v15/uisp_integration.rs | 5 +-- src/rust/lqos_config/src/etc/v15/wispgate.rs | 3 +- .../network_json/network_json_transport.rs | 3 +- .../src/shaped_devices/serializable.rs | 3 +- .../src/shaped_devices/shaped_device.rs | 3 +- src/rust/lqos_stormguard/Cargo.toml | 6 +++- src/rust/lqos_stormguard/src/config.rs | 4 +++ src/rust/lqos_stormguard/src/datalog.rs | 2 ++ .../src/site_state/analysis.rs | 8 +++-- .../src/site_state/recommendation.rs | 8 +++-- .../src/site_state/ring_buffer.rs | 3 ++ .../lqos_stormguard/src/site_state/site.rs | 2 ++ .../src/site_state/stormguard_state.rs | 4 ++- src/rust/lqos_sys/Cargo.toml | 4 +-- src/rust/lqos_utils/Cargo.toml | 4 +-- src/rust/lqosd/Cargo.toml | 6 ++-- src/rust/lqosd/src/anonymous_usage/lshw.rs | 3 +- src/rust/lqosd/src/main.rs | 4 +++ src/rust/lts_client/Cargo.toml | 4 +++ .../src/collector/collation/session_buffer.rs | 4 ++- .../lts_client/src/collector/network_tree.rs | 3 +- .../src/collector/stats_availability.rs | 3 +- .../src/collector/throughput_summary.rs | 6 ++-- .../src/transport_data/submissions.rs | 19 ++++++------ src/rust/uisp/Cargo.toml | 3 ++ src/rust/uisp/src/data_link.rs | 13 ++++---- src/rust/uisp/src/device.rs | 31 ++++++++++--------- src/rust/uisp/src/site.rs | 21 +++++++------ 57 files changed, 200 insertions(+), 114 deletions(-) diff --git a/src/rust/Cargo.lock b/src/rust/Cargo.lock index bdebea69..b244b618 100644 --- a/src/rust/Cargo.lock +++ b/src/rust/Cargo.lock @@ -1889,6 +1889,8 @@ dependencies = [ name = "lqos_bakery" version = "0.1.0" dependencies = [ + "allocative", + "allocative_derive", "anyhow", "crossbeam-channel", "lqos_bus", @@ -2015,6 +2017,8 @@ dependencies = [ name = "lqos_stormguard" version = "0.1.0" dependencies = [ + "allocative", + "allocative_derive", "anyhow", "crossbeam-channel", "lqos_bakery", @@ -2185,6 +2189,8 @@ dependencies = [ name = "lts_client" version = "0.1.0" dependencies = [ + "allocative", + "allocative_derive", "bincode", "dashmap", "dryoc 0.5.4", @@ -4065,6 +4071,8 @@ checksum = "1dccffe3ce07af9386bfd29e80c0ab1a8205a2fc34e4bcd40364df902cfa8f3f" name = "uisp" version = "0.1.0" dependencies = [ + "allocative", + "allocative_derive", "anyhow", "lqos_config", "reqwest", diff --git a/src/rust/Cargo.toml b/src/rust/Cargo.toml index bdc7c1d1..b5f60345 100644 --- a/src/rust/Cargo.toml +++ b/src/rust/Cargo.toml @@ -79,3 +79,7 @@ arc-swap = "1.7.1" # May have to change this one for ARM? #jemallocator = "0.5" mimalloc = "0.1.43" + +# For memory debugging +allocative = { version = "0.3.3", features = [ "dashmap" ] } +allocative_derive = "0.3.3" \ No newline at end of file diff --git a/src/rust/lqos_bakery/Cargo.toml b/src/rust/lqos_bakery/Cargo.toml index c63305e7..83220f66 100644 --- a/src/rust/lqos_bakery/Cargo.toml +++ b/src/rust/lqos_bakery/Cargo.toml @@ -10,3 +10,5 @@ anyhow.workspace = true tracing.workspace = true crossbeam-channel.workspace = true once_cell.workspace = true +allocative.workspace = true +allocative_derive.workspace = true diff --git a/src/rust/lqos_bakery/src/commands.rs b/src/rust/lqos_bakery/src/commands.rs index 30877fba..4717cd0e 100644 --- a/src/rust/lqos_bakery/src/commands.rs +++ b/src/rust/lqos_bakery/src/commands.rs @@ -5,9 +5,10 @@ use lqos_bus::TcHandle; use lqos_config::LazyQueueMode; use crate::MQ_CREATED; use crate::queue_math::{format_rate_for_tc, format_rate_for_tc_f32, quantum, r2q, sqm_as_vec, sqm_rate_fixup}; +use allocative::Allocative; /// Execution Mode -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Allocative)] pub enum ExecutionMode { /// We're constructing the tree Builder, @@ -16,7 +17,7 @@ pub enum ExecutionMode { } /// List of commands that the Bakery system can handle. -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Allocative)] pub enum BakeryCommands { OnCircuitActivity { circuit_ids: HashSet }, Tick, diff --git a/src/rust/lqos_bus/Cargo.toml b/src/rust/lqos_bus/Cargo.toml index 8f5859ce..8e89e604 100644 --- a/src/rust/lqos_bus/Cargo.toml +++ b/src/rust/lqos_bus/Cargo.toml @@ -21,5 +21,5 @@ nix = { workspace = true } serde_cbor = { workspace = true } # For memory debugging -allocative = { version = "0.3.3", features = [ "dashmap" ] } -allocative_derive = "0.3.3" +allocative.workspace = true +allocative_derive.workspace = true diff --git a/src/rust/lqos_bus/src/anonymous/mod.rs b/src/rust/lqos_bus/src/anonymous/mod.rs index 69ee502e..d7801c36 100644 --- a/src/rust/lqos_bus/src/anonymous/mod.rs +++ b/src/rust/lqos_bus/src/anonymous/mod.rs @@ -1,10 +1,11 @@ mod v1; +use allocative::Allocative; use serde::{Deserialize, Serialize}; use thiserror::Error; use tracing::warn; pub use v1::*; -#[derive(Debug, Clone, Serialize, Deserialize)] +#[derive(Debug, Clone, Serialize, Deserialize, Allocative)] /// Header for stats submission pub struct StatsHeader { /// The version to use (should be 1) diff --git a/src/rust/lqos_bus/src/anonymous/v1.rs b/src/rust/lqos_bus/src/anonymous/v1.rs index 48f9edf0..23ad9c77 100644 --- a/src/rust/lqos_bus/src/anonymous/v1.rs +++ b/src/rust/lqos_bus/src/anonymous/v1.rs @@ -1,5 +1,6 @@ +use allocative::Allocative; use serde::{Deserialize, Serialize}; -#[derive(Default, Debug, Serialize, Deserialize)] +#[derive(Default, Debug, Serialize, Deserialize, Allocative)] /// Defines data to be submitted if anonymous usage submission is /// enabled. This is protocol version 1. @@ -67,7 +68,7 @@ pub struct AnonymousUsageV1 { } /// Description of installed NIC (version 1 data) -#[derive(Default, Debug, Serialize, Deserialize)] +#[derive(Default, Debug, Serialize, Deserialize, Allocative)] pub struct NicV1 { /// Description, usually "Ethernet" pub description: String, diff --git a/src/rust/lqos_bus/src/bus/queue_data.rs b/src/rust/lqos_bus/src/bus/queue_data.rs index 25a40da4..b8885fbf 100644 --- a/src/rust/lqos_bus/src/bus/queue_data.rs +++ b/src/rust/lqos_bus/src/bus/queue_data.rs @@ -1,9 +1,10 @@ +use allocative::Allocative; use serde::{Deserialize, Serialize}; /// Type used for *displaying* the queue store data. It deliberately /// doesn't include data that we aren't going to display in a GUI. #[allow(missing_docs)] -#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)] +#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default, Allocative)] pub struct QueueStoreTransit { pub history: Vec<(CakeDiffTransit, CakeDiffTransit)>, pub history_head: usize, @@ -13,7 +14,7 @@ pub struct QueueStoreTransit { pub current_upload: CakeTransit, } -#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)] +#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default, Allocative)] #[allow(missing_docs)] pub struct CakeDiffTransit { pub bytes: u64, @@ -22,7 +23,7 @@ pub struct CakeDiffTransit { pub tins: Vec, } -#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)] +#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default, Allocative)] #[allow(missing_docs)] pub struct CakeDiffTinTransit { pub sent_bytes: u64, @@ -32,7 +33,7 @@ pub struct CakeDiffTinTransit { pub base_delay_us: u32, } -#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)] +#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default, Allocative)] #[allow(missing_docs)] pub struct CakeTransit { //pub handle: TcHandle, diff --git a/src/rust/lqos_bus/src/bus/reply.rs b/src/rust/lqos_bus/src/bus/reply.rs index 17d4635f..26efcff5 100644 --- a/src/rust/lqos_bus/src/bus/reply.rs +++ b/src/rust/lqos_bus/src/bus/reply.rs @@ -1,4 +1,5 @@ use crate::BusResponse; +use allocative::Allocative; use serde::{Deserialize, Serialize}; /// A single reply, always generated in response to a `BusSession` request. @@ -8,7 +9,7 @@ use serde::{Deserialize, Serialize}; /// /// No ordering guarantee is present. Responses may be out-of-order with /// respect to the order of the requests. -#[derive(Serialize, Deserialize, Clone, Debug)] +#[derive(Serialize, Deserialize, Clone, Debug, Allocative)] pub struct BusReply { /// A list of `BusResponse` objects generated in response to the /// requests that started the session. diff --git a/src/rust/lqos_bus/src/bus/request.rs b/src/rust/lqos_bus/src/bus/request.rs index 7b41e781..bca3666e 100644 --- a/src/rust/lqos_bus/src/bus/request.rs +++ b/src/rust/lqos_bus/src/bus/request.rs @@ -1,11 +1,12 @@ use crate::TcHandle; +use allocative::Allocative; use lqos_config::Tunables; use serde::{Deserialize, Serialize}; /// One or more `BusRequest` objects must be included in a `BusSession` /// request. Each `BusRequest` represents a single request for action /// or data. -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Allocative)] pub enum BusRequest { /// A generic "is it alive?" test. Returns an `Ack`. Ping, @@ -294,7 +295,7 @@ pub enum BusRequest { } /// Defines the parts of the blackboard -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Copy)] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Copy, Allocative)] pub enum BlackboardSystem { /// The system as a whole System, @@ -307,7 +308,7 @@ pub enum BlackboardSystem { } /// Defines the type of "top" flow being requested -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Copy)] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Copy, Allocative)] pub enum TopFlowType { /// Top flows by current estimated bandwidth use RateEstimate, @@ -322,7 +323,7 @@ pub enum TopFlowType { } /// Specific requests from the long-term stats system -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Allocative)] pub enum StatsRequest { /// Retrieve the current totals for all hosts CurrentTotals, diff --git a/src/rust/lqos_bus/src/bus/response.rs b/src/rust/lqos_bus/src/bus/response.rs index 5adf3c6d..2b395f07 100644 --- a/src/rust/lqos_bus/src/bus/response.rs +++ b/src/rust/lqos_bus/src/bus/response.rs @@ -3,13 +3,14 @@ use crate::{ Circuit, IpMapping, IpStats, XdpPpingResult, ip_stats::{FlowbeeSummaryData, PacketHeader}, }; +use allocative::Allocative; use lqos_utils::units::DownUpOrder; use lts_client::transport_data::{StatsHost, StatsTotals, StatsTreeNode}; use serde::{Deserialize, Serialize}; use std::net::IpAddr; /// Serializable snapshot of BakeryStats for bus transmission -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Allocative)] pub struct BakeryStatsSnapshot { /// The number of active circuits in the bakery pub active_circuits: u64, @@ -18,7 +19,7 @@ pub struct BakeryStatsSnapshot { /// A `BusResponse` object represents a single /// reply generated from a `BusRequest`, and batched /// inside a `BusReply`. -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Allocative)] pub enum BusResponse { /// Yes, we're alive Ack, diff --git a/src/rust/lqos_bus/src/bus/session.rs b/src/rust/lqos_bus/src/bus/session.rs index 31131d72..d6b823c7 100644 --- a/src/rust/lqos_bus/src/bus/session.rs +++ b/src/rust/lqos_bus/src/bus/session.rs @@ -1,10 +1,11 @@ use crate::BusRequest; +use allocative::Allocative; use serde::{Deserialize, Serialize}; /// `BusSession` represents a complete session with `lqosd`. It must /// contain a cookie value (defined in the `cookie_value()` function), /// which serves as a sanity check that the connection is valid. -#[derive(Serialize, Deserialize, Clone, Debug)] +#[derive(Serialize, Deserialize, Clone, Debug, Allocative)] pub struct BusSession { /// A list of requests to include in this session. pub requests: Vec, diff --git a/src/rust/lqos_bus/src/ip_stats.rs b/src/rust/lqos_bus/src/ip_stats.rs index fc35492f..56c1e40e 100644 --- a/src/rust/lqos_bus/src/ip_stats.rs +++ b/src/rust/lqos_bus/src/ip_stats.rs @@ -1,11 +1,12 @@ use crate::TcHandle; +use allocative::Allocative; use lqos_utils::units::DownUpOrder; use serde::{Deserialize, Serialize}; use std::net::IpAddr; /// Transmission representation of IP statistics associated /// with a host. -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Allocative)] pub struct IpStats { /// The host's IP address, as detected by the XDP program. pub ip_address: String, @@ -31,7 +32,7 @@ pub struct IpStats { } /// Represents an IP Mapping in the XDP IP to TC/CPU mapping system. -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Allocative)] pub struct IpMapping { /// The mapped IP address. May be IPv4, or IPv6. pub ip_address: String, @@ -49,7 +50,7 @@ pub struct IpMapping { /// Provided for backwards compatibility with `xdp_pping`, with the intent /// to retire it eventually. -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Allocative)] pub struct XdpPpingResult { /// The TC handle in text format. e.g. "1:12" pub tc: String, @@ -84,7 +85,7 @@ pub fn tos_parser(tos: u8) -> (u8, u8) { } /// Packet header dump -#[derive(Deserialize, Serialize, Debug, Clone, PartialEq)] +#[derive(Deserialize, Serialize, Debug, Clone, PartialEq, Allocative)] pub struct PacketHeader { /// Timestamp (ns since boot) pub timestamp: u64, @@ -115,7 +116,7 @@ pub struct PacketHeader { } /// Flowbee protocol enumeration -#[derive(Deserialize, Serialize, Debug, Clone, PartialEq)] +#[derive(Deserialize, Serialize, Debug, Clone, PartialEq, Allocative)] pub enum FlowbeeProtocol { /// TCP (type 6) TCP, @@ -136,7 +137,7 @@ impl From for FlowbeeProtocol { } /// Flowbee: a complete flow data, combining key and data. -#[derive(Deserialize, Serialize, Debug, Clone, PartialEq)] +#[derive(Deserialize, Serialize, Debug, Clone, PartialEq, Allocative)] pub struct FlowbeeSummaryData { /// Mapped `XdpIpAddress` source for the flow. pub remote_ip: String, @@ -185,7 +186,7 @@ pub struct FlowbeeSummaryData { } /// Circuit statistics for transmit -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Allocative)] pub struct Circuit { /// The IP address of the host. pub ip: IpAddr, diff --git a/src/rust/lqos_config/Cargo.toml b/src/rust/lqos_config/Cargo.toml index 121eae66..b14dc7f5 100644 --- a/src/rust/lqos_config/Cargo.toml +++ b/src/rust/lqos_config/Cargo.toml @@ -21,5 +21,5 @@ arc-swap = { workspace = true } once_cell = { workspace = true } # For memory debugging -allocative = { version = "0.3.3", features = [ "dashmap" ] } -allocative_derive = "0.3.3" \ No newline at end of file +allocative.workspace = true +allocative_derive.workspace = true \ No newline at end of file diff --git a/src/rust/lqos_config/src/authentication.rs b/src/rust/lqos_config/src/authentication.rs index 62b336aa..efdedae0 100644 --- a/src/rust/lqos_config/src/authentication.rs +++ b/src/rust/lqos_config/src/authentication.rs @@ -1,6 +1,7 @@ //! The `authentication` module provides authorization for use of the //! local web UI on LibreQoS boxes. It maps to `//lqusers.toml` +use allocative::Allocative; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; use std::{ @@ -14,7 +15,7 @@ use tracing::{error, warn}; use uuid::Uuid; /// Access rights of a user -#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq, Allocative)] pub enum UserRole { /// The user may view data but not change it. ReadOnly, @@ -54,7 +55,7 @@ impl Display for UserRole { } /// A user of the web UI. -#[derive(Clone, Debug, Deserialize, Serialize)] +#[derive(Clone, Debug, Deserialize, Serialize, Allocative)] pub struct WebUser { /// The user's username. pub username: String, @@ -67,7 +68,7 @@ pub struct WebUser { } /// Container holding the authorized web users. -#[derive(Clone, Debug, Deserialize, Serialize, Default)] +#[derive(Clone, Debug, Deserialize, Serialize, Default, Allocative)] pub struct WebUsers { allow_unauthenticated_to_view: bool, users: Vec, diff --git a/src/rust/lqos_config/src/etc/v15/anonymous_stats.rs b/src/rust/lqos_config/src/etc/v15/anonymous_stats.rs index 2bd4a5b7..30e829dc 100644 --- a/src/rust/lqos_config/src/etc/v15/anonymous_stats.rs +++ b/src/rust/lqos_config/src/etc/v15/anonymous_stats.rs @@ -1,9 +1,10 @@ //! Anonymous statistics section of the configuration //! file. +use allocative::Allocative; use serde::{Deserialize, Serialize}; -#[derive(Clone, Serialize, Deserialize, Debug, PartialEq)] +#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Allocative)] pub struct UsageStats { /// Are we allowed to send stats at all? pub send_anonymous: bool, diff --git a/src/rust/lqos_config/src/etc/v15/bridge.rs b/src/rust/lqos_config/src/etc/v15/bridge.rs index 39cf3aae..2951ccf8 100644 --- a/src/rust/lqos_config/src/etc/v15/bridge.rs +++ b/src/rust/lqos_config/src/etc/v15/bridge.rs @@ -2,10 +2,11 @@ //! A config file must contain EITHER this, or a `single_interface` //! section, but not both. +use allocative::Allocative; use serde::{Deserialize, Serialize}; /// Represents a two-interface bridge configuration. -#[derive(Clone, Serialize, Deserialize, Debug, PartialEq)] +#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Allocative)] pub struct BridgeConfig { /// Use the XDP-accelerated bridge? pub use_xdp_bridge: bool, @@ -27,7 +28,7 @@ impl Default for BridgeConfig { } } -#[derive(Clone, Serialize, Deserialize, Debug, PartialEq)] +#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Allocative)] pub struct SingleInterfaceConfig { /// The name of the interface pub interface: String, diff --git a/src/rust/lqos_config/src/etc/v15/flows.rs b/src/rust/lqos_config/src/etc/v15/flows.rs index 38a657c5..351ce7ec 100644 --- a/src/rust/lqos_config/src/etc/v15/flows.rs +++ b/src/rust/lqos_config/src/etc/v15/flows.rs @@ -2,9 +2,10 @@ //! //! You can enable them by adding a `[flows]` section to your configuration file. +use allocative::Allocative; use serde::{Deserialize, Serialize}; -#[derive(Clone, Serialize, Deserialize, Debug, PartialEq)] +#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Allocative)] pub struct FlowConfig { pub flow_timeout_seconds: u64, pub netflow_enabled: bool, diff --git a/src/rust/lqos_config/src/etc/v15/influxdb.rs b/src/rust/lqos_config/src/etc/v15/influxdb.rs index 5947c48a..afcb73ce 100644 --- a/src/rust/lqos_config/src/etc/v15/influxdb.rs +++ b/src/rust/lqos_config/src/etc/v15/influxdb.rs @@ -1,6 +1,7 @@ +use allocative::Allocative; use serde::{Deserialize, Serialize}; -#[derive(Clone, Serialize, Deserialize, Debug, PartialEq)] +#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Allocative)] pub struct InfluxDbConfig { pub enable_influxdb: bool, pub url: String, diff --git a/src/rust/lqos_config/src/etc/v15/integration_common.rs b/src/rust/lqos_config/src/etc/v15/integration_common.rs index c2803233..f8872fbe 100644 --- a/src/rust/lqos_config/src/etc/v15/integration_common.rs +++ b/src/rust/lqos_config/src/etc/v15/integration_common.rs @@ -1,8 +1,9 @@ //! Common integration variables, shared between integrations +use allocative::Allocative; use serde::{Deserialize, Serialize}; -#[derive(Clone, Serialize, Deserialize, Debug, PartialEq)] +#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Allocative)] pub struct IntegrationConfig { /// Replace names with addresses? pub circuit_name_as_address: bool, diff --git a/src/rust/lqos_config/src/etc/v15/ip_ranges.rs b/src/rust/lqos_config/src/etc/v15/ip_ranges.rs index 140c257e..bb0653af 100644 --- a/src/rust/lqos_config/src/etc/v15/ip_ranges.rs +++ b/src/rust/lqos_config/src/etc/v15/ip_ranges.rs @@ -1,9 +1,10 @@ +use allocative::Allocative; use ip_network::IpNetwork; use ip_network_table::IpNetworkTable; use serde::{Deserialize, Serialize}; use std::net::{Ipv4Addr, Ipv6Addr}; -#[derive(Clone, Serialize, Deserialize, Debug, PartialEq)] +#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Allocative)] pub struct IpRanges { pub ignore_subnets: Vec, pub allow_subnets: Vec, diff --git a/src/rust/lqos_config/src/etc/v15/long_term_stats.rs b/src/rust/lqos_config/src/etc/v15/long_term_stats.rs index 9b0621e0..8f469360 100644 --- a/src/rust/lqos_config/src/etc/v15/long_term_stats.rs +++ b/src/rust/lqos_config/src/etc/v15/long_term_stats.rs @@ -1,8 +1,9 @@ //! Defines configuration for the LTS project +use allocative::Allocative; use serde::{Deserialize, Serialize}; -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Allocative)] pub struct LongTermStats { /// Should we store long-term stats at all? pub gather_stats: bool, diff --git a/src/rust/lqos_config/src/etc/v15/powercode_integration.rs b/src/rust/lqos_config/src/etc/v15/powercode_integration.rs index 64d557ea..6db3f8e2 100644 --- a/src/rust/lqos_config/src/etc/v15/powercode_integration.rs +++ b/src/rust/lqos_config/src/etc/v15/powercode_integration.rs @@ -1,6 +1,7 @@ +use allocative::Allocative; use serde::{Deserialize, Serialize}; -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Allocative)] pub struct PowercodeIntegration { pub enable_powercode: bool, pub powercode_api_key: String, diff --git a/src/rust/lqos_config/src/etc/v15/queues.rs b/src/rust/lqos_config/src/etc/v15/queues.rs index 01a8eea1..da5dae48 100644 --- a/src/rust/lqos_config/src/etc/v15/queues.rs +++ b/src/rust/lqos_config/src/etc/v15/queues.rs @@ -1,8 +1,9 @@ //! Queue Generation definitions (originally from ispConfig.py) +use allocative::Allocative; use serde::{Deserialize, Serialize}; -#[derive(Clone, Serialize, Deserialize, Debug, PartialEq)] +#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Allocative)] pub struct QueueConfig { /// Which SQM to use by default pub default_sqm: String, @@ -43,7 +44,7 @@ pub struct QueueConfig { } /// Lazy queue creation modes -#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Default)] +#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Default, Allocative)] pub enum LazyQueueMode { /// No lazy queue creation #[default] diff --git a/src/rust/lqos_config/src/etc/v15/sonar_integration.rs b/src/rust/lqos_config/src/etc/v15/sonar_integration.rs index 14bd332b..9dafe114 100644 --- a/src/rust/lqos_config/src/etc/v15/sonar_integration.rs +++ b/src/rust/lqos_config/src/etc/v15/sonar_integration.rs @@ -1,6 +1,7 @@ +use allocative::Allocative; use serde::{Deserialize, Serialize}; -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Allocative)] pub struct SonarIntegration { pub enable_sonar: bool, pub sonar_api_url: String, diff --git a/src/rust/lqos_config/src/etc/v15/spylnx_integration.rs b/src/rust/lqos_config/src/etc/v15/spylnx_integration.rs index abce8e7a..8fc31632 100644 --- a/src/rust/lqos_config/src/etc/v15/spylnx_integration.rs +++ b/src/rust/lqos_config/src/etc/v15/spylnx_integration.rs @@ -1,6 +1,7 @@ +use allocative::Allocative; use serde::{Deserialize, Serialize}; -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Allocative)] pub struct SplynxIntegration { pub enable_spylnx: bool, pub api_key: String, diff --git a/src/rust/lqos_config/src/etc/v15/stormguard.rs b/src/rust/lqos_config/src/etc/v15/stormguard.rs index 8148f6fc..af6eb674 100644 --- a/src/rust/lqos_config/src/etc/v15/stormguard.rs +++ b/src/rust/lqos_config/src/etc/v15/stormguard.rs @@ -1,9 +1,10 @@ //! StormGuard definitions (originally from ispConfig.py) +use allocative::Allocative; use serde::{Deserialize, Serialize}; /// Configuration for the Tornado module (auto-rate) -#[derive(Clone, Serialize, Deserialize, Debug, PartialEq)] +#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Allocative)] pub struct StormguardConfig { /// Whether Tornado is enabled or not pub enabled: bool, diff --git a/src/rust/lqos_config/src/etc/v15/top_config.rs b/src/rust/lqos_config/src/etc/v15/top_config.rs index 8149a3de..cdc51a49 100644 --- a/src/rust/lqos_config/src/etc/v15/top_config.rs +++ b/src/rust/lqos_config/src/etc/v15/top_config.rs @@ -2,6 +2,7 @@ use super::anonymous_stats::UsageStats; use super::tuning::Tunables; +use allocative::Allocative; use serde::{Deserialize, Serialize}; use sha2::Digest; use sha2::digest::Update; @@ -9,7 +10,7 @@ use uuid::Uuid; use crate::etc::v15::stormguard; /// Top-level configuration file for LibreQoS. -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Allocative)] pub struct Config { /// Version number for the configuration file. /// This will be set to "1.5". Versioning will make diff --git a/src/rust/lqos_config/src/etc/v15/tuning.rs b/src/rust/lqos_config/src/etc/v15/tuning.rs index b2e18756..d3a0ecd3 100644 --- a/src/rust/lqos_config/src/etc/v15/tuning.rs +++ b/src/rust/lqos_config/src/etc/v15/tuning.rs @@ -1,10 +1,11 @@ //! Interface tuning instructions +use allocative::Allocative; use serde::{Deserialize, Serialize}; /// Represents a set of `sysctl` and `ethtool` tweaks that may be /// applied (in place of the previous version's offload service) -#[derive(Clone, Serialize, Deserialize, Debug, PartialEq)] +#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Allocative)] pub struct Tunables { /// Should the `irq_balance` system service be stopped? pub stop_irq_balance: bool, diff --git a/src/rust/lqos_config/src/etc/v15/uisp_integration.rs b/src/rust/lqos_config/src/etc/v15/uisp_integration.rs index 99f7b326..729f312c 100644 --- a/src/rust/lqos_config/src/etc/v15/uisp_integration.rs +++ b/src/rust/lqos_config/src/etc/v15/uisp_integration.rs @@ -1,6 +1,7 @@ +use allocative::Allocative; use serde::{Deserialize, Serialize}; -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Allocative)] pub struct UispIntegration { pub enable_uisp: bool, pub token: String, @@ -25,7 +26,7 @@ fn default_ignore_calculated_capacity() -> bool { false } -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Allocative)] pub struct ExceptionCpe { pub cpe: String, pub parent: String, diff --git a/src/rust/lqos_config/src/etc/v15/wispgate.rs b/src/rust/lqos_config/src/etc/v15/wispgate.rs index 8e023d38..3052ed0d 100644 --- a/src/rust/lqos_config/src/etc/v15/wispgate.rs +++ b/src/rust/lqos_config/src/etc/v15/wispgate.rs @@ -1,6 +1,7 @@ +use allocative::Allocative; use serde::{Deserialize, Serialize}; -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Default)] +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Default, Allocative)] pub struct WispGateIntegration { pub enable_wispgate: bool, pub wispgate_api_token: String, diff --git a/src/rust/lqos_config/src/network_json/network_json_transport.rs b/src/rust/lqos_config/src/network_json/network_json_transport.rs index 0b265806..df793120 100644 --- a/src/rust/lqos_config/src/network_json/network_json_transport.rs +++ b/src/rust/lqos_config/src/network_json/network_json_transport.rs @@ -1,9 +1,10 @@ +use allocative::Allocative; use serde::{Deserialize, Serialize}; /// A "transport-friendly" version of `NetworkJsonNode`. Designed /// to be quickly cloned from original nodes and efficiently /// transmitted/received. -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Allocative)] pub struct NetworkJsonTransport { /// Display name pub name: String, diff --git a/src/rust/lqos_config/src/shaped_devices/serializable.rs b/src/rust/lqos_config/src/shaped_devices/serializable.rs index b853e6a1..447189f2 100644 --- a/src/rust/lqos_config/src/shaped_devices/serializable.rs +++ b/src/rust/lqos_config/src/shaped_devices/serializable.rs @@ -1,9 +1,10 @@ use crate::ShapedDevice; +use allocative::Allocative; use serde::Serialize; use std::net::{Ipv4Addr, Ipv6Addr}; // Example: StringRecord(["1", "968 Circle St., Gurnee, IL 60031", "1", "Device 1", "", "", "192.168.101.2", "", "25", "5", "10000", "10000", ""]) -#[derive(Serialize, Debug)] +#[derive(Serialize, Debug, Allocative)] pub(crate) struct SerializableShapedDevice { pub circuit_id: String, pub circuit_name: String, diff --git a/src/rust/lqos_config/src/shaped_devices/shaped_device.rs b/src/rust/lqos_config/src/shaped_devices/shaped_device.rs index 14458ef7..7dff1bdc 100644 --- a/src/rust/lqos_config/src/shaped_devices/shaped_device.rs +++ b/src/rust/lqos_config/src/shaped_devices/shaped_device.rs @@ -1,4 +1,5 @@ use super::ShapedDevicesError; +use allocative::Allocative; use csv::StringRecord; use lqos_utils::hash_to_i64; use serde::{Deserialize, Serialize}; @@ -6,7 +7,7 @@ use std::net::{Ipv4Addr, Ipv6Addr}; use tracing::error; /// Represents a row in the `ShapedDevices.csv` file. -#[derive(Clone, Debug, Serialize, Deserialize, Default)] +#[derive(Clone, Debug, Serialize, Deserialize, Default, PartialEq, Allocative)] pub struct ShapedDevice { // Circuit ID,Circuit Name,Device ID,Device Name,Parent Node,MAC,IPv4,IPv6,Download Min Mbps,Upload Min Mbps,Download Max Mbps,Upload Max Mbps,Comment /// The ID of the circuit to which the device belongs. Circuits are 1:many, diff --git a/src/rust/lqos_stormguard/Cargo.toml b/src/rust/lqos_stormguard/Cargo.toml index 1fcac90d..315841c5 100644 --- a/src/rust/lqos_stormguard/Cargo.toml +++ b/src/rust/lqos_stormguard/Cargo.toml @@ -14,4 +14,8 @@ tokio.workspace = true lqos_queue_tracker = { path = "../lqos_queue_tracker" } lqos_utils = { path = "../lqos_utils" } lqos_bakery = { path = "../lqos_bakery" } -crossbeam-channel.workspace = true \ No newline at end of file +crossbeam-channel.workspace = true + +# For memory debugging +allocative.workspace = true +allocative_derive.workspace = true \ No newline at end of file diff --git a/src/rust/lqos_stormguard/src/config.rs b/src/rust/lqos_stormguard/src/config.rs index b52507ea..728e6d5c 100644 --- a/src/rust/lqos_stormguard/src/config.rs +++ b/src/rust/lqos_stormguard/src/config.rs @@ -1,9 +1,11 @@ use std::collections::HashMap; +use allocative::Allocative; use tracing::{debug, error}; use lqos_bus::TcHandle; use crate::queue_structure::{find_queue_bandwidth, find_queue_dependents}; use crate::STORMGUARD_STATS; +#[derive(Allocative)] pub struct WatchingSite { pub name: String, pub max_download_mbps: u64, @@ -13,6 +15,7 @@ pub struct WatchingSite { pub dependent_nodes: Vec, } +#[derive(Allocative)] pub struct WatchingSiteDependency { pub name: String, pub class_id: TcHandle, @@ -20,6 +23,7 @@ pub struct WatchingSiteDependency { pub original_max_upload_mbps: u64, } +#[derive(Allocative)] pub struct StormguardConfig { pub sites: HashMap, pub download_interface: String, diff --git a/src/rust/lqos_stormguard/src/datalog.rs b/src/rust/lqos_stormguard/src/datalog.rs index b0bb38d2..4fde99ff 100644 --- a/src/rust/lqos_stormguard/src/datalog.rs +++ b/src/rust/lqos_stormguard/src/datalog.rs @@ -1,8 +1,10 @@ use crate::config::StormguardConfig; use std::io::Write; +use allocative::Allocative; use tracing::debug; use lqos_utils::unix_time::unix_now; +#[derive(Allocative)] pub enum LogCommand { SpeedChange { site: String, diff --git a/src/rust/lqos_stormguard/src/site_state/analysis.rs b/src/rust/lqos_stormguard/src/site_state/analysis.rs index a2dff226..938c27ca 100644 --- a/src/rust/lqos_stormguard/src/site_state/analysis.rs +++ b/src/rust/lqos_stormguard/src/site_state/analysis.rs @@ -1,7 +1,9 @@ use std::fmt::Display; +use allocative::Allocative; + use crate::site_state::ring_buffer::RingBuffer; -#[derive(PartialEq)] +#[derive(PartialEq, Allocative)] pub enum SaturationLevel { Low, Medium, @@ -30,7 +32,7 @@ impl SaturationLevel { } } -#[derive(PartialEq)] +#[derive(PartialEq, Allocative)] pub enum RetransmitState { RisingFast, Rising, @@ -75,7 +77,7 @@ impl RetransmitState { } } -#[derive(PartialEq)] +#[derive(PartialEq, Allocative)] pub enum RttState { Rising{magnitude: f32}, Flat, diff --git a/src/rust/lqos_stormguard/src/site_state/recommendation.rs b/src/rust/lqos_stormguard/src/site_state/recommendation.rs index 7b259b8d..bbdce83a 100644 --- a/src/rust/lqos_stormguard/src/site_state/recommendation.rs +++ b/src/rust/lqos_stormguard/src/site_state/recommendation.rs @@ -1,6 +1,8 @@ use std::fmt::Display; -#[derive(Debug)] +use allocative::Allocative; + +#[derive(Debug, Allocative)] pub struct Recommendation { pub site: String, pub direction: RecommendationDirection, @@ -8,7 +10,7 @@ pub struct Recommendation { } -#[derive(Debug, Copy, Clone)] +#[derive(Debug, Copy, Clone, Allocative)] pub enum RecommendationDirection { Download, Upload, @@ -23,7 +25,7 @@ impl Display for RecommendationDirection { } } -#[derive(Debug)] +#[derive(Debug, Allocative)] pub enum RecommendationAction { IncreaseFast, Increase, diff --git a/src/rust/lqos_stormguard/src/site_state/ring_buffer.rs b/src/rust/lqos_stormguard/src/site_state/ring_buffer.rs index 43accad3..54cc2dba 100644 --- a/src/rust/lqos_stormguard/src/site_state/ring_buffer.rs +++ b/src/rust/lqos_stormguard/src/site_state/ring_buffer.rs @@ -1,3 +1,6 @@ +use allocative::Allocative; + +#[derive(Allocative)] pub struct RingBuffer { data: Vec>, index: usize, diff --git a/src/rust/lqos_stormguard/src/site_state/site.rs b/src/rust/lqos_stormguard/src/site_state/site.rs index 2ee10db5..6c0c78d5 100644 --- a/src/rust/lqos_stormguard/src/site_state/site.rs +++ b/src/rust/lqos_stormguard/src/site_state/site.rs @@ -1,3 +1,4 @@ +use allocative::Allocative; use tracing::{debug, info}; use crate::config::WatchingSite; use crate::site_state::analysis::{RetransmitState, RttState, SaturationLevel}; @@ -34,6 +35,7 @@ pub struct SiteState<'a> { pub ticks_since_last_probe_upload: u32, } +#[derive(Allocative)] struct RecommendationParams { direction: RecommendationDirection, can_increase: bool, diff --git a/src/rust/lqos_stormguard/src/site_state/stormguard_state.rs b/src/rust/lqos_stormguard/src/site_state/stormguard_state.rs index cc434ff1..c0cfda77 100644 --- a/src/rust/lqos_stormguard/src/site_state/stormguard_state.rs +++ b/src/rust/lqos_stormguard/src/site_state/stormguard_state.rs @@ -1,6 +1,8 @@ use std::time::Instant; -#[derive(PartialEq, Debug)] +use allocative::Allocative; + +#[derive(PartialEq, Debug, Allocative)] pub enum StormguardState { Warmup, Running, diff --git a/src/rust/lqos_sys/Cargo.toml b/src/rust/lqos_sys/Cargo.toml index b4278ac6..dfd39c91 100644 --- a/src/rust/lqos_sys/Cargo.toml +++ b/src/rust/lqos_sys/Cargo.toml @@ -17,8 +17,8 @@ thiserror = { workspace = true } zerocopy = { workspace = true } # For memory debugging -allocative = { version = "0.3.3", features = [ "dashmap" ] } -allocative_derive = "0.3.3" +allocative.workspace = true +allocative_derive.workspace = true [build-dependencies] bindgen = "0.71.1" diff --git a/src/rust/lqos_utils/Cargo.toml b/src/rust/lqos_utils/Cargo.toml index 132ea108..828a9fd5 100644 --- a/src/rust/lqos_utils/Cargo.toml +++ b/src/rust/lqos_utils/Cargo.toml @@ -16,5 +16,5 @@ num-traits = { workspace = true } crossbeam-channel = { workspace = true } # For memory debugging -allocative = { version = "0.3.3", features = [ "dashmap" ] } -allocative_derive = "0.3.3" \ No newline at end of file +allocative.workspace = true +allocative_derive.workspace = true \ No newline at end of file diff --git a/src/rust/lqosd/Cargo.toml b/src/rust/lqosd/Cargo.toml index 24dda468..23b3b5c5 100644 --- a/src/rust/lqosd/Cargo.toml +++ b/src/rust/lqosd/Cargo.toml @@ -5,7 +5,7 @@ edition = "2024" license = "GPL-2.0-only" [features] -default = ["equinix_tests"] +default = ["equinix_tests", "flamegraphs"] equinix_tests = [] flamegraphs = [] @@ -61,8 +61,8 @@ ureq = { version = "2.12.1", features = ["json", "native-tls"] } csv = { workspace = true } # For memory debugging -allocative = { version = "0.3.3", features = [ "dashmap" ] } -allocative_derive = "0.3.3" +allocative.workspace = true +allocative_derive.workspace = true # Support JemAlloc on supported platforms #[target.'cfg(any(target_arch = "x86", target_arch = "x86_64"))'.dependencies] diff --git a/src/rust/lqosd/src/anonymous_usage/lshw.rs b/src/rust/lqosd/src/anonymous_usage/lshw.rs index d78ef839..b51037e9 100644 --- a/src/rust/lqosd/src/anonymous_usage/lshw.rs +++ b/src/rust/lqosd/src/anonymous_usage/lshw.rs @@ -1,8 +1,9 @@ use std::process::Command; +use allocative::Allocative; use lqos_bus::anonymous::NicV1; -#[derive(Default)] +#[derive(Default, Allocative)] pub(crate) struct Nic { pub(crate) description: String, pub(crate) product: String, diff --git a/src/rust/lqosd/src/main.rs b/src/rust/lqosd/src/main.rs index 590aebaa..60e517f5 100644 --- a/src/rust/lqosd/src/main.rs +++ b/src/rust/lqosd/src/main.rs @@ -268,6 +268,10 @@ fn main() -> Result<()> { #[cfg(feature = "flamegraphs")] fn memory_debug() { + // To use this, install "inferno" with `cargo install inferno`. + // When you want to make the flamegraph, run: + // inferno-flamegraph /tmp/lqosd-mem.svg > output.svg + // You can then view output.svg in a web browser. std::thread::spawn(|| { loop { std::thread::sleep(std::time::Duration::from_secs(60)); diff --git a/src/rust/lts_client/Cargo.toml b/src/rust/lts_client/Cargo.toml index 0286270a..f3abc8fd 100644 --- a/src/rust/lts_client/Cargo.toml +++ b/src/rust/lts_client/Cargo.toml @@ -21,3 +21,7 @@ sysinfo = { workspace = true } num-traits = { workspace = true } miniz_oxide = { workspace = true } dashmap = { workspace = true } + +# For memory debugging +allocative.workspace = true +allocative_derive.workspace = true \ No newline at end of file diff --git a/src/rust/lts_client/src/collector/collation/session_buffer.rs b/src/rust/lts_client/src/collector/collation/session_buffer.rs index 40a25d50..d5ee8936 100644 --- a/src/rust/lts_client/src/collector/collation/session_buffer.rs +++ b/src/rust/lts_client/src/collector/collation/session_buffer.rs @@ -1,10 +1,12 @@ use crate::collector::{ThroughputSummary, network_tree::NetworkTreeEntry}; +use allocative::Allocative; use once_cell::sync::Lazy; use tokio::sync::Mutex; pub(crate) static SESSION_BUFFER: Lazy>> = Lazy::new(|| Mutex::new(Vec::new())); - + +#[derive(Allocative)] pub(crate) struct StatsSession { pub(crate) throughput: ThroughputSummary, pub(crate) network_tree: Vec<(usize, NetworkTreeEntry)>, diff --git a/src/rust/lts_client/src/collector/network_tree.rs b/src/rust/lts_client/src/collector/network_tree.rs index 96474199..c4782858 100644 --- a/src/rust/lts_client/src/collector/network_tree.rs +++ b/src/rust/lts_client/src/collector/network_tree.rs @@ -1,6 +1,7 @@ +use allocative::Allocative; use lqos_config::NetworkJsonNode; -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Allocative)] pub struct NetworkTreeEntry { pub name: String, pub max_throughput: (u32, u32), diff --git a/src/rust/lts_client/src/collector/stats_availability.rs b/src/rust/lts_client/src/collector/stats_availability.rs index bb76f524..fd44e845 100644 --- a/src/rust/lts_client/src/collector/stats_availability.rs +++ b/src/rust/lts_client/src/collector/stats_availability.rs @@ -1,11 +1,12 @@ //! Message type to be sent to the long-term stats thread when //! data is available. +use allocative::Allocative; use lqos_config::ShapedDevice; use super::{ThroughputSummary, network_tree::NetworkTreeEntry}; -#[derive(Debug)] +#[derive(Debug, Allocative)] /// Messages to/from the stats collection thread pub enum StatsUpdateMessage { /// Fresh throughput stats have been collected diff --git a/src/rust/lts_client/src/collector/throughput_summary.rs b/src/rust/lts_client/src/collector/throughput_summary.rs index 8d22bb1a..de3a7038 100644 --- a/src/rust/lts_client/src/collector/throughput_summary.rs +++ b/src/rust/lts_client/src/collector/throughput_summary.rs @@ -6,7 +6,9 @@ use std::net::IpAddr; -#[derive(Debug)] +use allocative::Allocative; + +#[derive(Debug, Allocative)] pub struct ThroughputSummary { pub bits_per_second: (u64, u64), pub shaped_bits_per_second: (u64, u64), @@ -14,7 +16,7 @@ pub struct ThroughputSummary { pub hosts: Vec, } -#[derive(Debug)] +#[derive(Debug, Allocative)] pub struct HostSummary { pub ip: IpAddr, pub circuit_id: Option, diff --git a/src/rust/lts_client/src/transport_data/submissions.rs b/src/rust/lts_client/src/transport_data/submissions.rs index d6dc124e..b2513a80 100644 --- a/src/rust/lts_client/src/transport_data/submissions.rs +++ b/src/rust/lts_client/src/transport_data/submissions.rs @@ -4,10 +4,11 @@ use lqos_config::ShapedDevice; use serde::{Deserialize, Serialize}; use uisp::Device; +use allocative::Allocative; /// Type that provides a minimum, maximum and average value /// for a given statistic within the associated time period. -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Allocative)] pub struct StatsSummary { /// Minimum value pub min: (u64, u64), @@ -19,7 +20,7 @@ pub struct StatsSummary { /// Type that provides a minimum, maximum and average value /// for a given RTT value within the associated time period. -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Allocative)] pub struct StatsRttSummary { /// Minimum value pub min: u32, @@ -30,7 +31,7 @@ pub struct StatsRttSummary { } /// Type that holds total traffic statistics for a given time period -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Allocative)] pub struct StatsTotals { /// Total number of packets pub packets: StatsSummary, @@ -42,7 +43,7 @@ pub struct StatsTotals { /// Type that holds per-host statistics for a given stats collation /// period. -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Allocative)] pub struct StatsHost { /// Host circuit_id as it appears in ShapedDevices.csv pub circuit_id: Option, @@ -55,7 +56,7 @@ pub struct StatsHost { } /// Node inside a traffic summary tree -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Allocative)] pub struct StatsTreeNode { /// Index in the tree vector pub index: usize, @@ -76,7 +77,7 @@ pub struct StatsTreeNode { } /// Collation of all stats for a given time period -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Allocative)] pub struct StatsSubmission { /// Timestamp of the collation (UNIX time) pub timestamp: u64, @@ -95,14 +96,14 @@ pub struct StatsSubmission { } /// Submission to the `lts_node` process -#[derive(Serialize, Deserialize, Clone, Debug)] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Allocative)] pub enum LtsCommand { Submit(Box), Devices(Vec), } /// Extended data provided from UISP -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Allocative)] pub struct UispExtDevice { pub device_id: String, pub name: String, @@ -120,7 +121,7 @@ pub struct UispExtDevice { pub interfaces: Vec, } -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Allocative)] pub struct UispExtDeviceInterface { pub name: String, pub mac: String, diff --git a/src/rust/uisp/Cargo.toml b/src/rust/uisp/Cargo.toml index f94abf3d..2ed02496 100644 --- a/src/rust/uisp/Cargo.toml +++ b/src/rust/uisp/Cargo.toml @@ -8,3 +8,6 @@ lqos_config = { path = "../lqos_config" } serde = { workspace = true } reqwest = { workspace = true } anyhow = { workspace = true } +# For memory debugging +allocative.workspace = true +allocative_derive.workspace = true \ No newline at end of file diff --git a/src/rust/uisp/src/data_link.rs b/src/rust/uisp/src/data_link.rs index 17ec0c3d..903be62f 100644 --- a/src/rust/uisp/src/data_link.rs +++ b/src/rust/uisp/src/data_link.rs @@ -1,7 +1,8 @@ +use allocative::Allocative; use serde::{Deserialize, Serialize}; #[allow(non_snake_case)] -#[derive(Serialize, Deserialize, Debug)] +#[derive(Serialize, Deserialize, Debug, Allocative)] pub struct DataLink { pub id: String, pub from: DataLinkFrom, @@ -11,34 +12,34 @@ pub struct DataLink { } #[allow(non_snake_case)] -#[derive(Serialize, Deserialize, Debug)] +#[derive(Serialize, Deserialize, Debug, Allocative)] pub struct DataLinkFrom { pub device: Option, pub site: Option, } #[allow(non_snake_case)] -#[derive(Serialize, Deserialize, Debug)] +#[derive(Serialize, Deserialize, Debug, Allocative)] pub struct DataLinkDevice { pub identification: DataLinkDeviceIdentification, } #[allow(non_snake_case)] -#[derive(Serialize, Deserialize, Debug)] +#[derive(Serialize, Deserialize, Debug, Allocative)] pub struct DataLinkDeviceIdentification { pub id: String, pub name: String, } #[allow(non_snake_case)] -#[derive(Serialize, Deserialize, Debug)] +#[derive(Serialize, Deserialize, Debug, Allocative)] pub struct DataLinkTo { pub device: Option, pub site: Option, } #[allow(non_snake_case)] -#[derive(Serialize, Deserialize, Debug)] +#[derive(Serialize, Deserialize, Debug, Allocative)] pub struct DataLinkSite { pub identification: DataLinkDeviceIdentification, } diff --git a/src/rust/uisp/src/device.rs b/src/rust/uisp/src/device.rs index 43fbdd64..66a50c30 100644 --- a/src/rust/uisp/src/device.rs +++ b/src/rust/uisp/src/device.rs @@ -1,8 +1,9 @@ +use allocative::Allocative; use serde::{Deserialize, Serialize}; use std::collections::HashSet; #[allow(non_snake_case)] -#[derive(Serialize, Deserialize, Debug)] +#[derive(Serialize, Deserialize, Debug, Allocative)] pub struct Device { pub identification: DeviceIdentification, pub ipAddress: Option, @@ -112,7 +113,7 @@ impl Device { } #[allow(non_snake_case)] -#[derive(Serialize, Deserialize, Debug)] +#[derive(Serialize, Deserialize, Debug, Allocative)] pub struct DeviceIdentification { pub id: String, pub hostname: Option, @@ -127,35 +128,35 @@ pub struct DeviceIdentification { } #[allow(non_snake_case)] -#[derive(Serialize, Deserialize, Debug)] +#[derive(Serialize, Deserialize, Debug, Allocative)] pub struct DeviceSite { pub id: String, pub parent: Option, } #[allow(non_snake_case)] -#[derive(Serialize, Deserialize, Debug)] +#[derive(Serialize, Deserialize, Debug, Allocative)] pub struct DeviceParent { pub id: String, pub name: String, } #[allow(non_snake_case)] -#[derive(Serialize, Deserialize, Debug)] +#[derive(Serialize, Deserialize, Debug, Allocative)] pub struct DeviceAttributes { pub ssid: Option, pub apDevice: Option, } #[allow(non_snake_case)] -#[derive(Serialize, Deserialize, Debug)] +#[derive(Serialize, Deserialize, Debug, Allocative)] pub struct DeviceAccessPoint { pub id: Option, pub name: Option, } #[allow(non_snake_case)] -#[derive(Serialize, Deserialize, Debug)] +#[derive(Serialize, Deserialize, Debug, Allocative)] pub struct DeviceInterface { pub identification: Option, pub addresses: Option>, @@ -165,27 +166,27 @@ pub struct DeviceInterface { } #[allow(non_snake_case)] -#[derive(Serialize, Deserialize, Debug)] +#[derive(Serialize, Deserialize, Debug, Allocative)] pub struct InterfaceIdentification { pub name: Option, pub mac: Option, } #[allow(non_snake_case)] -#[derive(Serialize, Deserialize, Debug)] +#[derive(Serialize, Deserialize, Debug, Allocative)] pub struct DeviceAddress { pub cidr: Option, } #[allow(non_snake_case)] -#[derive(Serialize, Deserialize, Debug)] +#[derive(Serialize, Deserialize, Debug, Allocative)] pub struct InterfaceStatus { pub status: Option, pub speed: Option, } #[allow(non_snake_case)] -#[derive(Serialize, Deserialize, Debug)] +#[derive(Serialize, Deserialize, Debug, Allocative)] pub struct DeviceOverview { pub status: Option, pub frequency: Option, @@ -211,7 +212,7 @@ pub struct DeviceOverview { } #[allow(non_snake_case)] -#[derive(Serialize, Deserialize, Debug)] +#[derive(Serialize, Deserialize, Debug, Allocative)] pub struct DeviceLinkScore { pub score: Option, pub scoreMax: Option, @@ -223,7 +224,7 @@ pub struct DeviceLinkScore { } #[allow(non_snake_case)] -#[derive(Serialize, Deserialize, Debug)] +#[derive(Serialize, Deserialize, Debug, Allocative)] pub struct DeviceAntenna { pub id: Option, pub gain: Option, @@ -233,13 +234,13 @@ pub struct DeviceAntenna { } #[allow(non_snake_case)] -#[derive(Serialize, Deserialize, Debug)] +#[derive(Serialize, Deserialize, Debug, Allocative)] pub struct DeviceWireless { pub noiseFloor: Option, } #[allow(non_snake_case)] -#[derive(Serialize, Deserialize, Debug)] +#[derive(Serialize, Deserialize, Debug, Allocative)] pub struct DeviceStation { connected: Option, connectedTime: Option, diff --git a/src/rust/uisp/src/site.rs b/src/rust/uisp/src/site.rs index 080636f3..dd9b6c00 100644 --- a/src/rust/uisp/src/site.rs +++ b/src/rust/uisp/src/site.rs @@ -1,7 +1,8 @@ +use allocative::Allocative; use serde::{Deserialize, Serialize}; #[allow(non_snake_case)] -#[derive(Serialize, Deserialize, Debug)] +#[derive(Serialize, Deserialize, Debug, Allocative)] pub struct Site { pub id: String, pub identification: Option, @@ -102,13 +103,13 @@ impl Site { } #[allow(non_snake_case)] -#[derive(Serialize, Deserialize, Debug)] +#[derive(Serialize, Deserialize, Debug, Allocative)] pub struct SiteParent { pub id: Option, } #[allow(non_snake_case)] -#[derive(Serialize, Deserialize, Debug)] +#[derive(Serialize, Deserialize, Debug, Allocative)] pub struct SiteId { pub name: Option, #[serde(rename = "type")] @@ -119,7 +120,7 @@ pub struct SiteId { } #[allow(non_snake_case)] -#[derive(Serialize, Deserialize, Debug, Clone)] +#[derive(Serialize, Deserialize, Debug, Clone, Allocative)] pub struct Endpoint { pub id: Option, pub name: Option, @@ -127,7 +128,7 @@ pub struct Endpoint { } #[allow(non_snake_case)] -#[derive(Serialize, Deserialize, Debug)] +#[derive(Serialize, Deserialize, Debug, Allocative)] pub struct Description { pub address: Option, pub location: Option, @@ -136,14 +137,14 @@ pub struct Description { } #[allow(non_snake_case)] -#[derive(Serialize, Deserialize, Debug)] +#[derive(Serialize, Deserialize, Debug, Allocative)] pub struct Location { pub longitude: f64, pub latitude: f64, } #[allow(non_snake_case)] -#[derive(Serialize, Deserialize, Debug)] +#[derive(Serialize, Deserialize, Debug, Allocative)] pub struct Qos { pub enabled: bool, pub downloadSpeed: Option, @@ -151,21 +152,21 @@ pub struct Qos { } #[allow(non_snake_case)] -#[derive(Serialize, Deserialize, Debug)] +#[derive(Serialize, Deserialize, Debug, Allocative)] pub struct Ucrm { pub client: Option, pub service: Option, } #[allow(non_snake_case)] -#[derive(Serialize, Deserialize, Debug)] +#[derive(Serialize, Deserialize, Debug, Allocative)] pub struct UcrmClient { pub id: String, pub name: String, } #[allow(non_snake_case)] -#[derive(Serialize, Deserialize, Debug)] +#[derive(Serialize, Deserialize, Debug, Allocative)] pub struct UcrmService { pub id: String, pub name: String, -- knotmirror 0.0.1 From f4e41233120f66a3a8585b5466057bab45dff7e8 Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Tue, 1 Jul 2025 13:06:56 -0500 Subject: [PATCH 05/16] Cap the number of locally held tcp retransmit timestemps per flow. --- .../src/throughput_tracker/flow_data/flow_tracker.rs | 12 ++++++++---- .../lqosd/src/throughput_tracker/flow_data/mod.rs | 2 +- .../lqosd/src/throughput_tracker/tracking_data.rs | 11 +++++++++-- 3 files changed, 18 insertions(+), 7 deletions(-) diff --git a/src/rust/lqosd/src/throughput_tracker/flow_data/flow_tracker.rs b/src/rust/lqosd/src/throughput_tracker/flow_data/flow_tracker.rs index 7cd30985..19c9d596 100644 --- a/src/rust/lqosd/src/throughput_tracker/flow_data/flow_tracker.rs +++ b/src/rust/lqosd/src/throughput_tracker/flow_data/flow_tracker.rs @@ -9,6 +9,10 @@ use lqos_utils::units::DownUpOrder; use once_cell::sync::Lazy; use serde::Serialize; use std::sync::Mutex; +use std::collections::VecDeque; + +/// Maximum number of retry timestamps to keep per direction +pub const MAX_RETRY_TIMESTAMPS: usize = 20; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Allocative)] pub struct AsnId(pub u32); @@ -49,9 +53,9 @@ pub struct FlowbeeLocalData { /// Throughput Buffer //pub throughput_buffer: Vec>, /// When did the retries happen? In nanoseconds since kernel boot - pub retry_times_down: Vec, + pub retry_times_down: VecDeque, /// When did the retries happen? In nanoseconds since kernel boot - pub retry_times_up: Vec, + pub retry_times_up: VecDeque, } impl From<&FlowbeeData> for FlowbeeLocalData { @@ -68,8 +72,8 @@ impl From<&FlowbeeData> for FlowbeeLocalData { flags: data.flags, rtt: [RttData::from_nanos(0); 2], //throughput_buffer: vec![ data.bytes_sent ], - retry_times_down: Vec::new(), - retry_times_up: Vec::new(), + retry_times_down: VecDeque::with_capacity(MAX_RETRY_TIMESTAMPS), + retry_times_up: VecDeque::with_capacity(MAX_RETRY_TIMESTAMPS), } } } diff --git a/src/rust/lqosd/src/throughput_tracker/flow_data/mod.rs b/src/rust/lqosd/src/throughput_tracker/flow_data/mod.rs index e525b2e8..bcdc8d89 100644 --- a/src/rust/lqosd/src/throughput_tracker/flow_data/mod.rs +++ b/src/rust/lqosd/src/throughput_tracker/flow_data/mod.rs @@ -17,7 +17,7 @@ pub(crate) use flow_analysis::{ flowbee_rtt_map, get_asn_name_and_country, get_flowbee_event_count_and_reset, get_rtt_events_per_second, setup_flow_analysis, }; -pub(crate) use flow_tracker::{ALL_FLOWS, AsnId, FlowbeeLocalData}; +pub(crate) use flow_tracker::{ALL_FLOWS, AsnId, FlowbeeLocalData, MAX_RETRY_TIMESTAMPS}; use lqos_sys::flowbee_data::FlowbeeKey; use tracing::{debug, error, info}; diff --git a/src/rust/lqosd/src/throughput_tracker/tracking_data.rs b/src/rust/lqosd/src/throughput_tracker/tracking_data.rs index 4bdc2333..898ec047 100644 --- a/src/rust/lqosd/src/throughput_tracker/tracking_data.rs +++ b/src/rust/lqosd/src/throughput_tracker/tracking_data.rs @@ -2,6 +2,7 @@ use super::{ RETIRE_AFTER_SECONDS, flow_data::{ ALL_FLOWS, FlowAnalysis, FlowbeeLocalData, RttData, get_flowbee_event_count_and_reset, + MAX_RETRY_TIMESTAMPS, }, throughput_entry::ThroughputEntry, }; @@ -343,10 +344,16 @@ impl ThroughputTracker { if let Some(this_flow) = all_flows_lock.flow_data.get_mut(&key) { // If retransmits have changed, add the time to the retry list if data.tcp_retransmits.down != this_flow.0.tcp_retransmits.down { - this_flow.0.retry_times_down.push(data.last_seen); + if this_flow.0.retry_times_down.len() >= MAX_RETRY_TIMESTAMPS { + this_flow.0.retry_times_down.pop_front(); + } + this_flow.0.retry_times_down.push_back(data.last_seen); } if data.tcp_retransmits.up != this_flow.0.tcp_retransmits.up { - this_flow.0.retry_times_up.push(data.last_seen); + if this_flow.0.retry_times_up.len() >= MAX_RETRY_TIMESTAMPS { + this_flow.0.retry_times_up.pop_front(); + } + this_flow.0.retry_times_up.push_back(data.last_seen); } //let change_since_last_time = data.bytes_sent.checked_sub_or_zero(this_flow.0.bytes_sent); -- knotmirror 0.0.1 From 5813d7051aec52cb29af63bb6e621a9ad97c7b34 Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Tue, 1 Jul 2025 13:54:02 -0500 Subject: [PATCH 06/16] Experiment with using reference counting on flows to reduce duplication, and better handling of excessive burts. --- .../single_user_channels/flows_by_circuit.rs | 4 +- .../flow_data/flow_analysis/finished_flows.rs | 89 ++++++++++---- .../flow_data/flow_tracker.rs | 3 +- .../src/throughput_tracker/flow_data/mod.rs | 21 +++- .../flow_data/netflow5/mod.rs | 22 ++-- .../flow_data/netflow9/mod.rs | 22 ++-- src/rust/lqosd/src/throughput_tracker/mod.rs | 115 ++++++++++-------- .../src/throughput_tracker/tracking_data.rs | 53 ++++---- 8 files changed, 210 insertions(+), 119 deletions(-) diff --git a/src/rust/lqosd/src/node_manager/ws/single_user_channels/flows_by_circuit.rs b/src/rust/lqosd/src/node_manager/ws/single_user_channels/flows_by_circuit.rs index c101d8ad..6b549789 100644 --- a/src/rust/lqosd/src/node_manager/ws/single_user_channels/flows_by_circuit.rs +++ b/src/rust/lqosd/src/node_manager/ws/single_user_channels/flows_by_circuit.rs @@ -23,7 +23,9 @@ fn recent_flows_by_circuit( let result: Vec<(FlowbeeKeyTransit, FlowbeeLocalData, FlowAnalysis)> = all_flows .flow_data .iter() - .filter_map(|(key, (local, analysis))| { + .filter_map(|(key, flow_arc)| { + let flow_lock = flow_arc.lock().unwrap(); + let (local, analysis) = &*flow_lock; // Don't show older flows if local.last_seen < five_minutes_ago { return None; diff --git a/src/rust/lqosd/src/throughput_tracker/flow_data/flow_analysis/finished_flows.rs b/src/rust/lqosd/src/throughput_tracker/flow_data/flow_analysis/finished_flows.rs index dcbf6a8f..cd34f824 100644 --- a/src/rust/lqosd/src/throughput_tracker/flow_data/flow_analysis/finished_flows.rs +++ b/src/rust/lqosd/src/throughput_tracker/flow_data/flow_analysis/finished_flows.rs @@ -1,6 +1,6 @@ use super::{FlowAnalysis, get_asn_lat_lon, get_asn_name_and_country, get_asn_name_by_id}; use crate::shaped_devices_tracker::SHAPED_DEVICES; -use crate::throughput_tracker::flow_data::FlowbeeLocalData; +use crate::throughput_tracker::flow_data::{FlowbeeLocalData, FLOW_CHANNEL_CAPACITY}; use allocative_derive::Allocative; use crossbeam_channel::Sender; use fxhash::FxHashMap; @@ -15,6 +15,7 @@ use serde::Serialize; use std::sync::Mutex; use std::time::Duration; use tracing::debug; +use std::sync::Arc; #[derive(Allocative)] pub struct TimeBuffer { @@ -24,7 +25,7 @@ pub struct TimeBuffer { #[derive(Clone, Debug, Allocative)] struct TimeEntry { time: u64, - data: (FlowbeeKey, FlowbeeLocalData, FlowAnalysis), + data: (FlowbeeKey, Arc>), } #[derive(Debug, Serialize)] @@ -79,7 +80,9 @@ impl TimeBuffer { let mut my_buffer = buffer .iter() .map(|v| { - let (key, data, _analysis) = &v.data; + let (key, flow_arc) = &v.data; + let flow_ref = flow_arc.lock().unwrap(); + let (data, _analysis) = &*flow_ref; let (lat, lon) = get_asn_lat_lon(key.remote_ip.as_ip()); let geo = get_asn_name_and_country(key.remote_ip.as_ip()); ( @@ -107,7 +110,9 @@ impl TimeBuffer { let mut my_buffer = buffer .iter() .map(|v| { - let (key, data, _analysis) = &v.data; + let (key, flow_arc) = &v.data; + let flow_ref = flow_arc.lock().unwrap(); + let (data, _analysis) = &*flow_ref; let geo = get_asn_name_and_country(key.remote_ip.as_ip()); let rtt = [data.rtt[0].as_nanos() as f32, data.rtt[1].as_nanos() as f32]; (geo.country, data.bytes_sent, rtt, geo.flag) @@ -206,7 +211,9 @@ impl TimeBuffer { let mut v6_rtt = [Vec::new(), Vec::new()]; buffer.iter().for_each(|v| { - let (key, data, _analysis) = &v.data; + let (key, flow_arc) = &v.data; + let flow_ref = flow_arc.lock().unwrap(); + let (data, _analysis) = &*flow_ref; if key.local_ip.is_v4() { // It's V4 v4_bytes_sent.checked_add(data.bytes_sent); @@ -249,7 +256,9 @@ impl TimeBuffer { let mut results = FxHashMap::default(); buffer.iter().for_each(|v| { - let (_key, data, analysis) = &v.data; + let (_key, flow_arc) = &v.data; + let flow_ref = flow_arc.lock().unwrap(); + let (data, analysis) = &*flow_ref; let proto = analysis.protocol_analysis.to_string(); let entry = results.entry(proto).or_insert(DownUpOrder::zeroed()); entry.checked_add(data.bytes_sent); @@ -269,7 +278,10 @@ impl TimeBuffer { buffer .iter() - .map(|f| Duration::from_nanos(f.data.1.last_seen - f.data.1.start_time)) // Duration in nanoseconds + .map(|f| { + let flow_ref = f.data.1.lock().unwrap(); + Duration::from_nanos(flow_ref.0.last_seen - flow_ref.0.start_time) + }) // Duration in nanoseconds .map(|nanos| nanos.as_secs()) .sorted() .dedup_with_count() // Now we're (count, duration in seconds) @@ -281,8 +293,15 @@ impl TimeBuffer { let buffer = self.buffer.lock().unwrap(); buffer .iter() - .filter(|flow| flow.data.2.asn_id.0 == id) - .map(|flow| flow.data.clone()) + .filter(|flow| { + let flow_ref = flow.data.1.lock().unwrap(); + flow_ref.1.asn_id.0 == id + }) + .map(|flow| { + let (key, arc) = flow.data.clone(); + let flow_ref = arc.lock().unwrap(); + (key, flow_ref.0.clone(), flow_ref.1.clone()) + }) .collect() } @@ -297,7 +316,11 @@ impl TimeBuffer { let country = get_asn_name_and_country(flow.data.0.remote_ip.as_ip()); country.flag == iso_code }) - .map(|flow| flow.data.clone()) + .map(|flow| { + let (key, arc) = flow.data.clone(); + let flow_ref = arc.lock().unwrap(); + (key, flow_ref.0.clone(), flow_ref.1.clone()) + }) .collect() } @@ -308,8 +331,15 @@ impl TimeBuffer { let buffer = self.buffer.lock().unwrap(); buffer .iter() - .filter(|flow| flow.data.2.protocol_analysis.to_string() == protocol_name) - .map(|flow| flow.data.clone()) + .filter(|flow| { + let flow_ref = flow.data.1.lock().unwrap(); + flow_ref.1.protocol_analysis.to_string() == protocol_name + }) + .map(|flow| { + let (key, arc) = flow.data.clone(); + let flow_ref = arc.lock().unwrap(); + (key, flow_ref.0.clone(), flow_ref.1.clone()) + }) .collect() } @@ -326,9 +356,13 @@ impl TimeBuffer { .into_iter() .filter(|flow| { // Total flow time > 3 seconds - flow.data.1.last_seen - flow.data.1.start_time > 3_000_000_000 + let flow_ref = flow.data.1.lock().unwrap(); + flow_ref.0.last_seen - flow_ref.0.start_time > 3_000_000_000 + }) + .map(|flow| { + let flow_ref = flow.data.1.lock().unwrap(); + flow_ref.1.asn_id.0 }) - .map(|flow| flow.data.2.asn_id.0) .collect(); // Sort the buffer @@ -360,7 +394,8 @@ impl TimeBuffer { .into_iter() .filter(|flow| { // Total flow time > 3 seconds - flow.data.1.last_seen - flow.data.1.start_time > 3_000_000_000 + let flow_ref = flow.data.1.lock().unwrap(); + flow_ref.0.last_seen - flow_ref.0.start_time > 3_000_000_000 }) .map(|flow| { let country = get_asn_name_and_country(flow.data.0.remote_ip.as_ip()); @@ -397,9 +432,13 @@ impl TimeBuffer { .into_iter() .filter(|flow| { // Total flow time > 3 seconds - flow.data.1.last_seen - flow.data.1.start_time > 3_000_000_000 + let flow_ref = flow.data.1.lock().unwrap(); + flow_ref.0.last_seen - flow_ref.0.start_time > 3_000_000_000 + }) + .map(|flow| { + let flow_ref = flow.data.1.lock().unwrap(); + flow_ref.1.protocol_analysis.to_string() }) - .map(|flow| flow.data.2.protocol_analysis.to_string()) .collect(); // Sort the buffer @@ -425,10 +464,10 @@ pub static RECENT_FLOWS: Lazy = Lazy::new(|| TimeBuffer::new()); pub struct FinishedFlowAnalysis {} impl FinishedFlowAnalysis { - pub fn new() -> Sender<(FlowbeeKey, (FlowbeeLocalData, FlowAnalysis))> { + pub fn new() -> Sender<(FlowbeeKey, Arc>)> { debug!("Created Flow Analysis Endpoint"); let (tx, rx) = - crossbeam_channel::bounded::<(FlowbeeKey, (FlowbeeLocalData, FlowAnalysis))>(65535); + crossbeam_channel::bounded::<(FlowbeeKey, Arc>)>(FLOW_CHANNEL_CAPACITY); let _ = std::thread::Builder::new() .name("Flow Expiration".to_string()) @@ -441,8 +480,8 @@ impl FinishedFlowAnalysis { let _ = std::thread::Builder::new() .name("Flow Analysis".to_string()) .spawn(move || { - while let Ok((key, (data, analysis))) = rx.recv() { - enqueue(key, data, analysis); + while let Ok((key, flow_arc)) = rx.recv() { + enqueue(key, flow_arc); } tracing::error!("Flow Analysis thread died"); }); @@ -451,8 +490,12 @@ impl FinishedFlowAnalysis { } } -fn enqueue(key: FlowbeeKey, data: FlowbeeLocalData, analysis: FlowAnalysis) { +fn enqueue(key: FlowbeeKey, flow_arc: Arc>) { debug!("Finished flow analysis"); + let (data, analysis) = { + let flow_ref = flow_arc.lock().unwrap(); + (flow_ref.0.clone(), flow_ref.1.clone()) + }; let start_time = boot_time_nanos_to_unix_now(data.start_time).unwrap_or(0); let last_seen = boot_time_nanos_to_unix_now(data.last_seen).unwrap_or(0); @@ -495,7 +538,7 @@ fn enqueue(key: FlowbeeKey, data: FlowbeeLocalData, analysis: FlowAnalysis) { .duration_since(std::time::UNIX_EPOCH) .unwrap() .as_secs(), - data: (key, data, analysis), + data: (key, flow_arc), }); } else { // We have a one-way flow! diff --git a/src/rust/lqosd/src/throughput_tracker/flow_data/flow_tracker.rs b/src/rust/lqosd/src/throughput_tracker/flow_data/flow_tracker.rs index 19c9d596..e1138c29 100644 --- a/src/rust/lqosd/src/throughput_tracker/flow_data/flow_tracker.rs +++ b/src/rust/lqosd/src/throughput_tracker/flow_data/flow_tracker.rs @@ -10,6 +10,7 @@ use once_cell::sync::Lazy; use serde::Serialize; use std::sync::Mutex; use std::collections::VecDeque; +use std::sync::Arc; /// Maximum number of retry timestamps to keep per direction pub const MAX_RETRY_TIMESTAMPS: usize = 20; @@ -21,7 +22,7 @@ pub static ALL_FLOWS: Lazy> = Lazy::new(|| Mutex::new(FlowTra #[derive(Default, Allocative)] pub struct FlowTracker { - pub flow_data: FxHashMap, + pub flow_data: FxHashMap>>, } /// Condensed representation of the FlowbeeData type. This contains diff --git a/src/rust/lqosd/src/throughput_tracker/flow_data/mod.rs b/src/rust/lqosd/src/throughput_tracker/flow_data/mod.rs index bcdc8d89..148a689f 100644 --- a/src/rust/lqosd/src/throughput_tracker/flow_data/mod.rs +++ b/src/rust/lqosd/src/throughput_tracker/flow_data/mod.rs @@ -20,11 +20,19 @@ pub(crate) use flow_analysis::{ pub(crate) use flow_tracker::{ALL_FLOWS, AsnId, FlowbeeLocalData, MAX_RETRY_TIMESTAMPS}; use lqos_sys::flowbee_data::FlowbeeKey; use tracing::{debug, error, info}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Mutex}; + +/// Maximum capacity for flow data channels +pub const FLOW_CHANNEL_CAPACITY: usize = 65535; + +/// Counter for flows discarded due to full netflow channel +static DISCARDED_NETFLOW_FLOWS: AtomicU64 = AtomicU64::new(0); // Creates the netflow tracker and returns the sender -pub fn setup_netflow_tracker() -> Result> { +pub fn setup_netflow_tracker() -> Result>)>> { let (tx, rx) = - crossbeam_channel::bounded::<(FlowbeeKey, (FlowbeeLocalData, FlowAnalysis))>(65535); + crossbeam_channel::bounded::<(FlowbeeKey, Arc>)>(FLOW_CHANNEL_CAPACITY); let config = lqos_config::load_config().inspect_err(|e| error!("Failed to load configuration: {e}"))?; @@ -34,7 +42,7 @@ pub fn setup_netflow_tracker() -> Result> = + let mut endpoints: Vec>)>> = Vec::new(); endpoints.push(FinishedFlowAnalysis::new()); @@ -64,11 +72,12 @@ pub fn setup_netflow_tracker() -> Result anyhow::Result> { + ) -> anyhow::Result>)>> { let (tx, rx) = - crossbeam_channel::bounded::<(FlowbeeKey, (FlowbeeLocalData, FlowAnalysis))>(65535); + crossbeam_channel::bounded::<(FlowbeeKey, Arc>)>(FLOW_CHANNEL_CAPACITY); std::thread::Builder::new() .name("Netflow5".to_string()) @@ -31,13 +33,15 @@ impl Netflow5 { let sequence = AtomicU32::new(0); let mut accumulator = Vec::with_capacity(15); let mut last_sent = std::time::Instant::now(); - while let Ok((key, (data, analysis))) = rx.recv() { + while let Ok((key, flow_arc)) = rx.recv() { // Exclude one-way flows - if (data.bytes_sent.sum()) == 0 { + let flow_ref = flow_arc.lock().unwrap(); + if (flow_ref.0.bytes_sent.sum()) == 0 { continue; } + drop(flow_ref); // Release borrow before storing - accumulator.push((key, (data, analysis))); + accumulator.push((key, flow_arc)); // Send if there is more than 15 records AND it has been more than 1 second since the last send if accumulator.len() >= 15 && last_sent.elapsed().as_secs() > 1 { @@ -61,7 +65,7 @@ impl Netflow5 { } fn queue_handler( - accumulator: &[(FlowbeeKey, (FlowbeeLocalData, FlowAnalysis))], + accumulator: &[(FlowbeeKey, Arc>)], socket: &UdpSocket, target: &str, sequence: &AtomicU32, @@ -81,7 +85,9 @@ impl Netflow5 { ); buffer.extend_from_slice(header_bytes); - for (key, (data, _)) in accumulator { + for (key, flow_arc) in accumulator { + let flow_ref = flow_arc.lock().unwrap(); + let (data, _) = &*flow_ref; if let Ok((packet1, packet2)) = to_netflow_5(key, data) { let packet1_bytes = unsafe { std::slice::from_raw_parts( diff --git a/src/rust/lqosd/src/throughput_tracker/flow_data/netflow9/mod.rs b/src/rust/lqosd/src/throughput_tracker/flow_data/netflow9/mod.rs index aa0d9491..c4ad664c 100644 --- a/src/rust/lqosd/src/throughput_tracker/flow_data/netflow9/mod.rs +++ b/src/rust/lqosd/src/throughput_tracker/flow_data/netflow9/mod.rs @@ -1,11 +1,13 @@ use self::protocol::to_netflow_9; -use super::{FlowAnalysis, FlowbeeLocalData}; +use super::{FlowAnalysis, FlowbeeLocalData, FLOW_CHANNEL_CAPACITY}; use crate::throughput_tracker::flow_data::netflow9::protocol::{ header::Netflow9Header, template_ipv4::template_data_ipv4, template_ipv6::template_data_ipv6, }; use crossbeam_channel::Sender; use lqos_sys::flowbee_data::FlowbeeKey; use std::{net::UdpSocket, sync::atomic::AtomicU32}; +use std::sync::Arc; +use std::sync::Mutex; mod protocol; pub(crate) struct Netflow9 {} @@ -13,9 +15,9 @@ pub(crate) struct Netflow9 {} impl Netflow9 { pub(crate) fn new( target: String, - ) -> anyhow::Result> { + ) -> anyhow::Result>)>> { let (tx, rx) = - crossbeam_channel::bounded::<(FlowbeeKey, (FlowbeeLocalData, FlowAnalysis))>(65535); + crossbeam_channel::bounded::<(FlowbeeKey, Arc>)>(FLOW_CHANNEL_CAPACITY); let socket = UdpSocket::bind("0.0.0.0:0")?; std::thread::Builder::new() @@ -24,13 +26,15 @@ impl Netflow9 { let mut accumulator = Vec::with_capacity(14); let sequence = AtomicU32::new(0); let mut last_sent = std::time::Instant::now(); - while let Ok((key, (data, analysis))) = rx.recv() { + while let Ok((key, flow_arc)) = rx.recv() { // Exclude one-way flows - if (data.bytes_sent.sum()) == 0 { + let flow_ref = flow_arc.lock().unwrap(); + if (flow_ref.0.bytes_sent.sum()) == 0 { continue; } + drop(flow_ref); // Release borrow before storing - accumulator.push((key, (data, analysis))); + accumulator.push((key, flow_arc)); // Send if there is more than 15 records AND it has been more than 1 second since the last send if accumulator.len() >= 14 && last_sent.elapsed().as_secs() > 1 { @@ -54,7 +58,7 @@ impl Netflow9 { } fn queue_handler( - accumulator: &[(FlowbeeKey, (FlowbeeLocalData, FlowAnalysis))], + accumulator: &[(FlowbeeKey, Arc>)], socket: &UdpSocket, target: &str, sequence: &AtomicU32, @@ -77,7 +81,9 @@ impl Netflow9 { buffer.extend_from_slice(&template1); buffer.extend_from_slice(&template2); - for (key, (data, _)) in accumulator { + for (key, flow_arc) in accumulator { + let flow_ref = flow_arc.lock().unwrap(); + let (data, _) = &*flow_ref; if let Ok((packet1, packet2)) = to_netflow_9(key, data) { buffer.extend_from_slice(&packet1); buffer.extend_from_slice(&packet2); diff --git a/src/rust/lqosd/src/throughput_tracker/mod.rs b/src/rust/lqosd/src/throughput_tracker/mod.rs index 0e4a523a..07e6efad 100644 --- a/src/rust/lqosd/src/throughput_tracker/mod.rs +++ b/src/rust/lqosd/src/throughput_tracker/mod.rs @@ -4,6 +4,7 @@ mod throughput_entry; mod tracking_data; use self::flow_data::{ALL_FLOWS, FlowAnalysis, FlowbeeLocalData, get_asn_name_and_country}; +use std::sync::{Arc, Mutex}; use crate::system_stats::SystemStats; use crate::throughput_tracker::flow_data::RttData; use crate::{ @@ -41,7 +42,7 @@ pub static THROUGHPUT_TRACKER: Lazy = Lazy::new(ThroughputTra /// collection thread that there is fresh data. pub fn spawn_throughput_monitor( long_term_stats_tx: Sender, - netflow_sender: crossbeam_channel::Sender<(FlowbeeKey, (FlowbeeLocalData, FlowAnalysis))>, + netflow_sender: crossbeam_channel::Sender<(FlowbeeKey, Arc>)>, system_usage_actor: crossbeam_channel::Sender>, bakery_sender: crossbeam_channel::Sender, ) -> anyhow::Result<()> { @@ -104,7 +105,7 @@ impl ThroughputTaskTimeMetrics { fn throughput_task( long_term_stats_tx: Sender, - netflow_sender: crossbeam_channel::Sender<(FlowbeeKey, (FlowbeeLocalData, FlowAnalysis))>, + netflow_sender: crossbeam_channel::Sender<(FlowbeeKey, Arc>)>, system_usage_actor: crossbeam_channel::Sender>, bakery_sender: crossbeam_channel::Sender, ) { @@ -730,6 +731,8 @@ pub fn dump_active_flows() -> BusResponse { .flow_data .iter() .map(|(key, row)| { + let flow_data = row.lock().unwrap(); + let (local_data, analysis) = &*flow_data; let geo = get_asn_name_and_country(key.remote_ip.as_ip()); let (circuit_id, circuit_name) = (String::new(), String::new()); @@ -740,20 +743,20 @@ pub fn dump_active_flows() -> BusResponse { src_port: key.src_port, dst_port: key.dst_port, ip_protocol: FlowbeeProtocol::from(key.ip_protocol), - bytes_sent: row.0.bytes_sent, - packets_sent: row.0.packets_sent, - rate_estimate_bps: row.0.rate_estimate_bps, - tcp_retransmits: row.0.tcp_retransmits, - end_status: row.0.end_status, - tos: row.0.tos, - flags: row.0.flags, - remote_asn: row.1.asn_id.0, + bytes_sent: local_data.bytes_sent, + packets_sent: local_data.packets_sent, + rate_estimate_bps: local_data.rate_estimate_bps, + tcp_retransmits: local_data.tcp_retransmits, + end_status: local_data.end_status, + tos: local_data.tos, + flags: local_data.flags, + remote_asn: analysis.asn_id.0, remote_asn_name: geo.name, remote_asn_country: geo.country, - analysis: row.1.protocol_analysis.to_string(), - last_seen: row.0.last_seen, - start_time: row.0.start_time, - rtt_nanos: DownUpOrder::new(row.0.rtt[0].as_nanos(), row.0.rtt[1].as_nanos()), + analysis: analysis.protocol_analysis.to_string(), + last_seen: local_data.last_seen, + start_time: local_data.start_time, + rtt_nanos: DownUpOrder::new(local_data.rtt[0].as_nanos(), local_data.rtt[1].as_nanos()), circuit_id, circuit_name, } @@ -772,7 +775,7 @@ pub fn count_active_flows() -> BusResponse { /// Top Flows Report pub fn top_flows(n: u32, flow_type: TopFlowType) -> BusResponse { let lock = ALL_FLOWS.lock().unwrap(); - let mut table: Vec<(FlowbeeKey, (FlowbeeLocalData, FlowAnalysis))> = lock + let mut table: Vec<(FlowbeeKey, Arc>)> = lock .flow_data .iter() .map(|(key, value)| (key.clone(), value.clone())) @@ -782,36 +785,46 @@ pub fn top_flows(n: u32, flow_type: TopFlowType) -> BusResponse { match flow_type { TopFlowType::RateEstimate => { table.sort_by(|a, b| { - let a_total = a.1.0.rate_estimate_bps.sum(); - let b_total = b.1.0.rate_estimate_bps.sum(); + let a_lock = a.1.lock().unwrap(); + let b_lock = b.1.lock().unwrap(); + let a_total = a_lock.0.rate_estimate_bps.sum(); + let b_total = b_lock.0.rate_estimate_bps.sum(); b_total.cmp(&a_total) }); } TopFlowType::Bytes => { table.sort_by(|a, b| { - let a_total = a.1.0.bytes_sent.sum(); - let b_total = b.1.0.bytes_sent.sum(); + let a_lock = a.1.lock().unwrap(); + let b_lock = b.1.lock().unwrap(); + let a_total = a_lock.0.bytes_sent.sum(); + let b_total = b_lock.0.bytes_sent.sum(); b_total.cmp(&a_total) }); } TopFlowType::Packets => { table.sort_by(|a, b| { - let a_total = a.1.0.packets_sent.sum(); - let b_total = b.1.0.packets_sent.sum(); + let a_lock = a.1.lock().unwrap(); + let b_lock = b.1.lock().unwrap(); + let a_total = a_lock.0.packets_sent.sum(); + let b_total = b_lock.0.packets_sent.sum(); b_total.cmp(&a_total) }); } TopFlowType::Drops => { table.sort_by(|a, b| { - let a_total = a.1.0.tcp_retransmits.sum(); - let b_total = b.1.0.tcp_retransmits.sum(); + let a_lock = a.1.lock().unwrap(); + let b_lock = b.1.lock().unwrap(); + let a_total = a_lock.0.tcp_retransmits.sum(); + let b_total = b_lock.0.tcp_retransmits.sum(); b_total.cmp(&a_total) }); } TopFlowType::RoundTripTime => { table.sort_by(|a, b| { - let a_total = a.1.0.rtt; - let b_total = b.1.0.rtt; + let a_lock = a.1.lock().unwrap(); + let b_lock = b.1.lock().unwrap(); + let a_total = a_lock.0.rtt; + let b_total = b_lock.0.rtt; a_total.cmp(&b_total) }); } @@ -823,6 +836,8 @@ pub fn top_flows(n: u32, flow_type: TopFlowType) -> BusResponse { .iter() .take(n as usize) .map(|(ip, flow)| { + let flow_data = flow.lock().unwrap(); + let (local_data, analysis) = &*flow_data; let geo = get_asn_name_and_country(ip.remote_ip.as_ip()); let (circuit_id, circuit_name) = sd @@ -835,20 +850,20 @@ pub fn top_flows(n: u32, flow_type: TopFlowType) -> BusResponse { src_port: ip.src_port, dst_port: ip.dst_port, ip_protocol: FlowbeeProtocol::from(ip.ip_protocol), - bytes_sent: flow.0.bytes_sent, - packets_sent: flow.0.packets_sent, - rate_estimate_bps: flow.0.rate_estimate_bps, - tcp_retransmits: flow.0.tcp_retransmits, - end_status: flow.0.end_status, - tos: flow.0.tos, - flags: flow.0.flags, - remote_asn: flow.1.asn_id.0, + bytes_sent: local_data.bytes_sent, + packets_sent: local_data.packets_sent, + rate_estimate_bps: local_data.rate_estimate_bps, + tcp_retransmits: local_data.tcp_retransmits, + end_status: local_data.end_status, + tos: local_data.tos, + flags: local_data.flags, + remote_asn: analysis.asn_id.0, remote_asn_name: geo.name, remote_asn_country: geo.country, - analysis: flow.1.protocol_analysis.to_string(), - last_seen: flow.0.last_seen, - start_time: flow.0.start_time, - rtt_nanos: DownUpOrder::new(flow.0.rtt[0].as_nanos(), flow.0.rtt[1].as_nanos()), + analysis: analysis.protocol_analysis.to_string(), + last_seen: local_data.last_seen, + start_time: local_data.start_time, + rtt_nanos: DownUpOrder::new(local_data.rtt[0].as_nanos(), local_data.rtt[1].as_nanos()), circuit_id, circuit_name, } @@ -869,6 +884,8 @@ pub fn flows_by_ip(ip: &str) -> BusResponse { .iter() .filter(|(key, _)| key.local_ip == ip) .map(|(key, row)| { + let flow_data = row.lock().unwrap(); + let (local_data, analysis) = &*flow_data; let geo = get_asn_name_and_country(key.remote_ip.as_ip()); let (circuit_id, circuit_name) = sd @@ -881,20 +898,20 @@ pub fn flows_by_ip(ip: &str) -> BusResponse { src_port: key.src_port, dst_port: key.dst_port, ip_protocol: FlowbeeProtocol::from(key.ip_protocol), - bytes_sent: row.0.bytes_sent, - packets_sent: row.0.packets_sent, - rate_estimate_bps: row.0.rate_estimate_bps, - tcp_retransmits: row.0.tcp_retransmits, - end_status: row.0.end_status, - tos: row.0.tos, - flags: row.0.flags, - remote_asn: row.1.asn_id.0, + bytes_sent: local_data.bytes_sent, + packets_sent: local_data.packets_sent, + rate_estimate_bps: local_data.rate_estimate_bps, + tcp_retransmits: local_data.tcp_retransmits, + end_status: local_data.end_status, + tos: local_data.tos, + flags: local_data.flags, + remote_asn: analysis.asn_id.0, remote_asn_name: geo.name, remote_asn_country: geo.country, - analysis: row.1.protocol_analysis.to_string(), - last_seen: row.0.last_seen, - start_time: row.0.start_time, - rtt_nanos: DownUpOrder::new(row.0.rtt[0].as_nanos(), row.0.rtt[1].as_nanos()), + analysis: analysis.protocol_analysis.to_string(), + last_seen: local_data.last_seen, + start_time: local_data.start_time, + rtt_nanos: DownUpOrder::new(local_data.rtt[0].as_nanos(), local_data.rtt[1].as_nanos()), circuit_id, circuit_name, } diff --git a/src/rust/lqosd/src/throughput_tracker/tracking_data.rs b/src/rust/lqosd/src/throughput_tracker/tracking_data.rs index 898ec047..a19448a9 100644 --- a/src/rust/lqosd/src/throughput_tracker/tracking_data.rs +++ b/src/rust/lqosd/src/throughput_tracker/tracking_data.rs @@ -21,14 +21,18 @@ use lqos_sys::{flowbee_data::FlowbeeKey, iterate_flows, throughput_for_each}; use lqos_utils::units::{AtomicDownUp, DownUpOrder}; use lqos_utils::{XdpIpAddress, unix_time::time_since_boot}; use std::collections::{HashMap, HashSet}; -use std::sync::Mutex; +use std::sync::{Mutex, Arc}; use std::{sync::atomic::AtomicU64, time::Duration}; use tracing::{debug, info, warn}; +use std::sync::atomic::Ordering; // Maximum number of flows to track simultaneously // TODO: This should be made configurable via the config file const MAX_FLOWS: usize = 1_000_000; +/// Counter for flows discarded due to full expired flow channel +static DISCARDED_EXPIRED_FLOWS: AtomicU64 = AtomicU64::new(0); + #[derive(Allocative)] pub struct ThroughputTracker { pub(crate) cycle: AtomicU64, @@ -313,7 +317,7 @@ impl ThroughputTracker { &self, timeout_seconds: u64, _netflow_enabled: bool, - sender: crossbeam_channel::Sender<(FlowbeeKey, (FlowbeeLocalData, FlowAnalysis))>, + sender: crossbeam_channel::Sender<(FlowbeeKey, Arc>)>, net_json_calc: &mut NetworkJson, rtt_circuit_tracker: &mut FxHashMap; 2]>, tcp_retries: &mut FxHashMap>, @@ -343,38 +347,39 @@ impl ThroughputTracker { // We have a valid flow, so it needs to be tracked if let Some(this_flow) = all_flows_lock.flow_data.get_mut(&key) { // If retransmits have changed, add the time to the retry list - if data.tcp_retransmits.down != this_flow.0.tcp_retransmits.down { - if this_flow.0.retry_times_down.len() >= MAX_RETRY_TIMESTAMPS { - this_flow.0.retry_times_down.pop_front(); + let mut flow_data = this_flow.lock().unwrap(); + if data.tcp_retransmits.down != flow_data.0.tcp_retransmits.down { + if flow_data.0.retry_times_down.len() >= MAX_RETRY_TIMESTAMPS { + flow_data.0.retry_times_down.pop_front(); } - this_flow.0.retry_times_down.push_back(data.last_seen); + flow_data.0.retry_times_down.push_back(data.last_seen); } - if data.tcp_retransmits.up != this_flow.0.tcp_retransmits.up { - if this_flow.0.retry_times_up.len() >= MAX_RETRY_TIMESTAMPS { - this_flow.0.retry_times_up.pop_front(); + if data.tcp_retransmits.up != flow_data.0.tcp_retransmits.up { + if flow_data.0.retry_times_up.len() >= MAX_RETRY_TIMESTAMPS { + flow_data.0.retry_times_up.pop_front(); } - this_flow.0.retry_times_up.push_back(data.last_seen); + flow_data.0.retry_times_up.push_back(data.last_seen); } //let change_since_last_time = data.bytes_sent.checked_sub_or_zero(this_flow.0.bytes_sent); //this_flow.0.throughput_buffer.push(change_since_last_time); //println!("{change_since_last_time:?}"); - this_flow.0.last_seen = data.last_seen; - this_flow.0.bytes_sent = data.bytes_sent; - this_flow.0.packets_sent = data.packets_sent; - this_flow.0.rate_estimate_bps = data.rate_estimate_bps; - this_flow.0.tcp_retransmits = data.tcp_retransmits; - this_flow.0.end_status = data.end_status; - this_flow.0.tos = data.tos; - this_flow.0.flags = data.flags; + flow_data.0.last_seen = data.last_seen; + flow_data.0.bytes_sent = data.bytes_sent; + flow_data.0.packets_sent = data.packets_sent; + flow_data.0.rate_estimate_bps = data.rate_estimate_bps; + flow_data.0.tcp_retransmits = data.tcp_retransmits; + flow_data.0.end_status = data.end_status; + flow_data.0.tos = data.tos; + flow_data.0.flags = data.flags; if let Some([up, down]) = rtt_samples.get(&key) { if up.as_nanos() != 0 { - this_flow.0.rtt[0] = *up; + flow_data.0.rtt[0] = *up; } if down.as_nanos() != 0 { - this_flow.0.rtt[1] = *down; + flow_data.0.rtt[1] = *down; } } } else { @@ -396,7 +401,7 @@ impl ThroughputTracker { let flow_analysis = FlowAnalysis::new(&key); all_flows_lock .flow_data - .insert(key.clone(), (data.into(), flow_analysis)); + .insert(key.clone(), Arc::new(Mutex::new((data.into(), flow_analysis)))); } } @@ -498,7 +503,9 @@ impl ThroughputTracker { for key in expired_keys.iter() { // Send it off to netperf for analysis if we are supporting doing so. if let Some(d) = all_flows_lock.flow_data.remove(&key) { - let _ = sender.send((key.clone(), (d.0.clone(), d.1.clone()))); + if sender.try_send((key.clone(), d)).is_err() { + DISCARDED_EXPIRED_FLOWS.fetch_add(1, Ordering::Relaxed); + } } } @@ -511,7 +518,7 @@ impl ThroughputTracker { // Cleaning run all_flows_lock .flow_data - .retain(|_k, v| v.0.last_seen >= expire); + .retain(|_k, v| v.lock().unwrap().0.last_seen >= expire); all_flows_lock.flow_data.shrink_to_fit(); expire_rtt_flows(); } -- knotmirror 0.0.1 From 10a8a33f60e7ccfce024f905f714e9122ba4c116 Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Tue, 1 Jul 2025 14:05:52 -0500 Subject: [PATCH 07/16] Revert "Experiment with using reference counting on flows to reduce duplication, and better handling of excessive burts." This reverts commit 5813d7051aec52cb29af63bb6e621a9ad97c7b34. --- .../single_user_channels/flows_by_circuit.rs | 4 +- .../flow_data/flow_analysis/finished_flows.rs | 89 ++++---------- .../flow_data/flow_tracker.rs | 3 +- .../src/throughput_tracker/flow_data/mod.rs | 21 +--- .../flow_data/netflow5/mod.rs | 22 ++-- .../flow_data/netflow9/mod.rs | 22 ++-- src/rust/lqosd/src/throughput_tracker/mod.rs | 115 ++++++++---------- .../src/throughput_tracker/tracking_data.rs | 53 ++++---- 8 files changed, 119 insertions(+), 210 deletions(-) diff --git a/src/rust/lqosd/src/node_manager/ws/single_user_channels/flows_by_circuit.rs b/src/rust/lqosd/src/node_manager/ws/single_user_channels/flows_by_circuit.rs index 6b549789..c101d8ad 100644 --- a/src/rust/lqosd/src/node_manager/ws/single_user_channels/flows_by_circuit.rs +++ b/src/rust/lqosd/src/node_manager/ws/single_user_channels/flows_by_circuit.rs @@ -23,9 +23,7 @@ fn recent_flows_by_circuit( let result: Vec<(FlowbeeKeyTransit, FlowbeeLocalData, FlowAnalysis)> = all_flows .flow_data .iter() - .filter_map(|(key, flow_arc)| { - let flow_lock = flow_arc.lock().unwrap(); - let (local, analysis) = &*flow_lock; + .filter_map(|(key, (local, analysis))| { // Don't show older flows if local.last_seen < five_minutes_ago { return None; diff --git a/src/rust/lqosd/src/throughput_tracker/flow_data/flow_analysis/finished_flows.rs b/src/rust/lqosd/src/throughput_tracker/flow_data/flow_analysis/finished_flows.rs index cd34f824..dcbf6a8f 100644 --- a/src/rust/lqosd/src/throughput_tracker/flow_data/flow_analysis/finished_flows.rs +++ b/src/rust/lqosd/src/throughput_tracker/flow_data/flow_analysis/finished_flows.rs @@ -1,6 +1,6 @@ use super::{FlowAnalysis, get_asn_lat_lon, get_asn_name_and_country, get_asn_name_by_id}; use crate::shaped_devices_tracker::SHAPED_DEVICES; -use crate::throughput_tracker::flow_data::{FlowbeeLocalData, FLOW_CHANNEL_CAPACITY}; +use crate::throughput_tracker::flow_data::FlowbeeLocalData; use allocative_derive::Allocative; use crossbeam_channel::Sender; use fxhash::FxHashMap; @@ -15,7 +15,6 @@ use serde::Serialize; use std::sync::Mutex; use std::time::Duration; use tracing::debug; -use std::sync::Arc; #[derive(Allocative)] pub struct TimeBuffer { @@ -25,7 +24,7 @@ pub struct TimeBuffer { #[derive(Clone, Debug, Allocative)] struct TimeEntry { time: u64, - data: (FlowbeeKey, Arc>), + data: (FlowbeeKey, FlowbeeLocalData, FlowAnalysis), } #[derive(Debug, Serialize)] @@ -80,9 +79,7 @@ impl TimeBuffer { let mut my_buffer = buffer .iter() .map(|v| { - let (key, flow_arc) = &v.data; - let flow_ref = flow_arc.lock().unwrap(); - let (data, _analysis) = &*flow_ref; + let (key, data, _analysis) = &v.data; let (lat, lon) = get_asn_lat_lon(key.remote_ip.as_ip()); let geo = get_asn_name_and_country(key.remote_ip.as_ip()); ( @@ -110,9 +107,7 @@ impl TimeBuffer { let mut my_buffer = buffer .iter() .map(|v| { - let (key, flow_arc) = &v.data; - let flow_ref = flow_arc.lock().unwrap(); - let (data, _analysis) = &*flow_ref; + let (key, data, _analysis) = &v.data; let geo = get_asn_name_and_country(key.remote_ip.as_ip()); let rtt = [data.rtt[0].as_nanos() as f32, data.rtt[1].as_nanos() as f32]; (geo.country, data.bytes_sent, rtt, geo.flag) @@ -211,9 +206,7 @@ impl TimeBuffer { let mut v6_rtt = [Vec::new(), Vec::new()]; buffer.iter().for_each(|v| { - let (key, flow_arc) = &v.data; - let flow_ref = flow_arc.lock().unwrap(); - let (data, _analysis) = &*flow_ref; + let (key, data, _analysis) = &v.data; if key.local_ip.is_v4() { // It's V4 v4_bytes_sent.checked_add(data.bytes_sent); @@ -256,9 +249,7 @@ impl TimeBuffer { let mut results = FxHashMap::default(); buffer.iter().for_each(|v| { - let (_key, flow_arc) = &v.data; - let flow_ref = flow_arc.lock().unwrap(); - let (data, analysis) = &*flow_ref; + let (_key, data, analysis) = &v.data; let proto = analysis.protocol_analysis.to_string(); let entry = results.entry(proto).or_insert(DownUpOrder::zeroed()); entry.checked_add(data.bytes_sent); @@ -278,10 +269,7 @@ impl TimeBuffer { buffer .iter() - .map(|f| { - let flow_ref = f.data.1.lock().unwrap(); - Duration::from_nanos(flow_ref.0.last_seen - flow_ref.0.start_time) - }) // Duration in nanoseconds + .map(|f| Duration::from_nanos(f.data.1.last_seen - f.data.1.start_time)) // Duration in nanoseconds .map(|nanos| nanos.as_secs()) .sorted() .dedup_with_count() // Now we're (count, duration in seconds) @@ -293,15 +281,8 @@ impl TimeBuffer { let buffer = self.buffer.lock().unwrap(); buffer .iter() - .filter(|flow| { - let flow_ref = flow.data.1.lock().unwrap(); - flow_ref.1.asn_id.0 == id - }) - .map(|flow| { - let (key, arc) = flow.data.clone(); - let flow_ref = arc.lock().unwrap(); - (key, flow_ref.0.clone(), flow_ref.1.clone()) - }) + .filter(|flow| flow.data.2.asn_id.0 == id) + .map(|flow| flow.data.clone()) .collect() } @@ -316,11 +297,7 @@ impl TimeBuffer { let country = get_asn_name_and_country(flow.data.0.remote_ip.as_ip()); country.flag == iso_code }) - .map(|flow| { - let (key, arc) = flow.data.clone(); - let flow_ref = arc.lock().unwrap(); - (key, flow_ref.0.clone(), flow_ref.1.clone()) - }) + .map(|flow| flow.data.clone()) .collect() } @@ -331,15 +308,8 @@ impl TimeBuffer { let buffer = self.buffer.lock().unwrap(); buffer .iter() - .filter(|flow| { - let flow_ref = flow.data.1.lock().unwrap(); - flow_ref.1.protocol_analysis.to_string() == protocol_name - }) - .map(|flow| { - let (key, arc) = flow.data.clone(); - let flow_ref = arc.lock().unwrap(); - (key, flow_ref.0.clone(), flow_ref.1.clone()) - }) + .filter(|flow| flow.data.2.protocol_analysis.to_string() == protocol_name) + .map(|flow| flow.data.clone()) .collect() } @@ -356,13 +326,9 @@ impl TimeBuffer { .into_iter() .filter(|flow| { // Total flow time > 3 seconds - let flow_ref = flow.data.1.lock().unwrap(); - flow_ref.0.last_seen - flow_ref.0.start_time > 3_000_000_000 - }) - .map(|flow| { - let flow_ref = flow.data.1.lock().unwrap(); - flow_ref.1.asn_id.0 + flow.data.1.last_seen - flow.data.1.start_time > 3_000_000_000 }) + .map(|flow| flow.data.2.asn_id.0) .collect(); // Sort the buffer @@ -394,8 +360,7 @@ impl TimeBuffer { .into_iter() .filter(|flow| { // Total flow time > 3 seconds - let flow_ref = flow.data.1.lock().unwrap(); - flow_ref.0.last_seen - flow_ref.0.start_time > 3_000_000_000 + flow.data.1.last_seen - flow.data.1.start_time > 3_000_000_000 }) .map(|flow| { let country = get_asn_name_and_country(flow.data.0.remote_ip.as_ip()); @@ -432,13 +397,9 @@ impl TimeBuffer { .into_iter() .filter(|flow| { // Total flow time > 3 seconds - let flow_ref = flow.data.1.lock().unwrap(); - flow_ref.0.last_seen - flow_ref.0.start_time > 3_000_000_000 - }) - .map(|flow| { - let flow_ref = flow.data.1.lock().unwrap(); - flow_ref.1.protocol_analysis.to_string() + flow.data.1.last_seen - flow.data.1.start_time > 3_000_000_000 }) + .map(|flow| flow.data.2.protocol_analysis.to_string()) .collect(); // Sort the buffer @@ -464,10 +425,10 @@ pub static RECENT_FLOWS: Lazy = Lazy::new(|| TimeBuffer::new()); pub struct FinishedFlowAnalysis {} impl FinishedFlowAnalysis { - pub fn new() -> Sender<(FlowbeeKey, Arc>)> { + pub fn new() -> Sender<(FlowbeeKey, (FlowbeeLocalData, FlowAnalysis))> { debug!("Created Flow Analysis Endpoint"); let (tx, rx) = - crossbeam_channel::bounded::<(FlowbeeKey, Arc>)>(FLOW_CHANNEL_CAPACITY); + crossbeam_channel::bounded::<(FlowbeeKey, (FlowbeeLocalData, FlowAnalysis))>(65535); let _ = std::thread::Builder::new() .name("Flow Expiration".to_string()) @@ -480,8 +441,8 @@ impl FinishedFlowAnalysis { let _ = std::thread::Builder::new() .name("Flow Analysis".to_string()) .spawn(move || { - while let Ok((key, flow_arc)) = rx.recv() { - enqueue(key, flow_arc); + while let Ok((key, (data, analysis))) = rx.recv() { + enqueue(key, data, analysis); } tracing::error!("Flow Analysis thread died"); }); @@ -490,12 +451,8 @@ impl FinishedFlowAnalysis { } } -fn enqueue(key: FlowbeeKey, flow_arc: Arc>) { +fn enqueue(key: FlowbeeKey, data: FlowbeeLocalData, analysis: FlowAnalysis) { debug!("Finished flow analysis"); - let (data, analysis) = { - let flow_ref = flow_arc.lock().unwrap(); - (flow_ref.0.clone(), flow_ref.1.clone()) - }; let start_time = boot_time_nanos_to_unix_now(data.start_time).unwrap_or(0); let last_seen = boot_time_nanos_to_unix_now(data.last_seen).unwrap_or(0); @@ -538,7 +495,7 @@ fn enqueue(key: FlowbeeKey, flow_arc: Arc> = Lazy::new(|| Mutex::new(FlowTra #[derive(Default, Allocative)] pub struct FlowTracker { - pub flow_data: FxHashMap>>, + pub flow_data: FxHashMap, } /// Condensed representation of the FlowbeeData type. This contains diff --git a/src/rust/lqosd/src/throughput_tracker/flow_data/mod.rs b/src/rust/lqosd/src/throughput_tracker/flow_data/mod.rs index 148a689f..bcdc8d89 100644 --- a/src/rust/lqosd/src/throughput_tracker/flow_data/mod.rs +++ b/src/rust/lqosd/src/throughput_tracker/flow_data/mod.rs @@ -20,19 +20,11 @@ pub(crate) use flow_analysis::{ pub(crate) use flow_tracker::{ALL_FLOWS, AsnId, FlowbeeLocalData, MAX_RETRY_TIMESTAMPS}; use lqos_sys::flowbee_data::FlowbeeKey; use tracing::{debug, error, info}; -use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::{Arc, Mutex}; - -/// Maximum capacity for flow data channels -pub const FLOW_CHANNEL_CAPACITY: usize = 65535; - -/// Counter for flows discarded due to full netflow channel -static DISCARDED_NETFLOW_FLOWS: AtomicU64 = AtomicU64::new(0); // Creates the netflow tracker and returns the sender -pub fn setup_netflow_tracker() -> Result>)>> { +pub fn setup_netflow_tracker() -> Result> { let (tx, rx) = - crossbeam_channel::bounded::<(FlowbeeKey, Arc>)>(FLOW_CHANNEL_CAPACITY); + crossbeam_channel::bounded::<(FlowbeeKey, (FlowbeeLocalData, FlowAnalysis))>(65535); let config = lqos_config::load_config().inspect_err(|e| error!("Failed to load configuration: {e}"))?; @@ -42,7 +34,7 @@ pub fn setup_netflow_tracker() -> Result>)>> = + let mut endpoints: Vec> = Vec::new(); endpoints.push(FinishedFlowAnalysis::new()); @@ -72,12 +64,11 @@ pub fn setup_netflow_tracker() -> Result anyhow::Result>)>> { + ) -> anyhow::Result> { let (tx, rx) = - crossbeam_channel::bounded::<(FlowbeeKey, Arc>)>(FLOW_CHANNEL_CAPACITY); + crossbeam_channel::bounded::<(FlowbeeKey, (FlowbeeLocalData, FlowAnalysis))>(65535); std::thread::Builder::new() .name("Netflow5".to_string()) @@ -33,15 +31,13 @@ impl Netflow5 { let sequence = AtomicU32::new(0); let mut accumulator = Vec::with_capacity(15); let mut last_sent = std::time::Instant::now(); - while let Ok((key, flow_arc)) = rx.recv() { + while let Ok((key, (data, analysis))) = rx.recv() { // Exclude one-way flows - let flow_ref = flow_arc.lock().unwrap(); - if (flow_ref.0.bytes_sent.sum()) == 0 { + if (data.bytes_sent.sum()) == 0 { continue; } - drop(flow_ref); // Release borrow before storing - accumulator.push((key, flow_arc)); + accumulator.push((key, (data, analysis))); // Send if there is more than 15 records AND it has been more than 1 second since the last send if accumulator.len() >= 15 && last_sent.elapsed().as_secs() > 1 { @@ -65,7 +61,7 @@ impl Netflow5 { } fn queue_handler( - accumulator: &[(FlowbeeKey, Arc>)], + accumulator: &[(FlowbeeKey, (FlowbeeLocalData, FlowAnalysis))], socket: &UdpSocket, target: &str, sequence: &AtomicU32, @@ -85,9 +81,7 @@ impl Netflow5 { ); buffer.extend_from_slice(header_bytes); - for (key, flow_arc) in accumulator { - let flow_ref = flow_arc.lock().unwrap(); - let (data, _) = &*flow_ref; + for (key, (data, _)) in accumulator { if let Ok((packet1, packet2)) = to_netflow_5(key, data) { let packet1_bytes = unsafe { std::slice::from_raw_parts( diff --git a/src/rust/lqosd/src/throughput_tracker/flow_data/netflow9/mod.rs b/src/rust/lqosd/src/throughput_tracker/flow_data/netflow9/mod.rs index c4ad664c..aa0d9491 100644 --- a/src/rust/lqosd/src/throughput_tracker/flow_data/netflow9/mod.rs +++ b/src/rust/lqosd/src/throughput_tracker/flow_data/netflow9/mod.rs @@ -1,13 +1,11 @@ use self::protocol::to_netflow_9; -use super::{FlowAnalysis, FlowbeeLocalData, FLOW_CHANNEL_CAPACITY}; +use super::{FlowAnalysis, FlowbeeLocalData}; use crate::throughput_tracker::flow_data::netflow9::protocol::{ header::Netflow9Header, template_ipv4::template_data_ipv4, template_ipv6::template_data_ipv6, }; use crossbeam_channel::Sender; use lqos_sys::flowbee_data::FlowbeeKey; use std::{net::UdpSocket, sync::atomic::AtomicU32}; -use std::sync::Arc; -use std::sync::Mutex; mod protocol; pub(crate) struct Netflow9 {} @@ -15,9 +13,9 @@ pub(crate) struct Netflow9 {} impl Netflow9 { pub(crate) fn new( target: String, - ) -> anyhow::Result>)>> { + ) -> anyhow::Result> { let (tx, rx) = - crossbeam_channel::bounded::<(FlowbeeKey, Arc>)>(FLOW_CHANNEL_CAPACITY); + crossbeam_channel::bounded::<(FlowbeeKey, (FlowbeeLocalData, FlowAnalysis))>(65535); let socket = UdpSocket::bind("0.0.0.0:0")?; std::thread::Builder::new() @@ -26,15 +24,13 @@ impl Netflow9 { let mut accumulator = Vec::with_capacity(14); let sequence = AtomicU32::new(0); let mut last_sent = std::time::Instant::now(); - while let Ok((key, flow_arc)) = rx.recv() { + while let Ok((key, (data, analysis))) = rx.recv() { // Exclude one-way flows - let flow_ref = flow_arc.lock().unwrap(); - if (flow_ref.0.bytes_sent.sum()) == 0 { + if (data.bytes_sent.sum()) == 0 { continue; } - drop(flow_ref); // Release borrow before storing - accumulator.push((key, flow_arc)); + accumulator.push((key, (data, analysis))); // Send if there is more than 15 records AND it has been more than 1 second since the last send if accumulator.len() >= 14 && last_sent.elapsed().as_secs() > 1 { @@ -58,7 +54,7 @@ impl Netflow9 { } fn queue_handler( - accumulator: &[(FlowbeeKey, Arc>)], + accumulator: &[(FlowbeeKey, (FlowbeeLocalData, FlowAnalysis))], socket: &UdpSocket, target: &str, sequence: &AtomicU32, @@ -81,9 +77,7 @@ impl Netflow9 { buffer.extend_from_slice(&template1); buffer.extend_from_slice(&template2); - for (key, flow_arc) in accumulator { - let flow_ref = flow_arc.lock().unwrap(); - let (data, _) = &*flow_ref; + for (key, (data, _)) in accumulator { if let Ok((packet1, packet2)) = to_netflow_9(key, data) { buffer.extend_from_slice(&packet1); buffer.extend_from_slice(&packet2); diff --git a/src/rust/lqosd/src/throughput_tracker/mod.rs b/src/rust/lqosd/src/throughput_tracker/mod.rs index 07e6efad..0e4a523a 100644 --- a/src/rust/lqosd/src/throughput_tracker/mod.rs +++ b/src/rust/lqosd/src/throughput_tracker/mod.rs @@ -4,7 +4,6 @@ mod throughput_entry; mod tracking_data; use self::flow_data::{ALL_FLOWS, FlowAnalysis, FlowbeeLocalData, get_asn_name_and_country}; -use std::sync::{Arc, Mutex}; use crate::system_stats::SystemStats; use crate::throughput_tracker::flow_data::RttData; use crate::{ @@ -42,7 +41,7 @@ pub static THROUGHPUT_TRACKER: Lazy = Lazy::new(ThroughputTra /// collection thread that there is fresh data. pub fn spawn_throughput_monitor( long_term_stats_tx: Sender, - netflow_sender: crossbeam_channel::Sender<(FlowbeeKey, Arc>)>, + netflow_sender: crossbeam_channel::Sender<(FlowbeeKey, (FlowbeeLocalData, FlowAnalysis))>, system_usage_actor: crossbeam_channel::Sender>, bakery_sender: crossbeam_channel::Sender, ) -> anyhow::Result<()> { @@ -105,7 +104,7 @@ impl ThroughputTaskTimeMetrics { fn throughput_task( long_term_stats_tx: Sender, - netflow_sender: crossbeam_channel::Sender<(FlowbeeKey, Arc>)>, + netflow_sender: crossbeam_channel::Sender<(FlowbeeKey, (FlowbeeLocalData, FlowAnalysis))>, system_usage_actor: crossbeam_channel::Sender>, bakery_sender: crossbeam_channel::Sender, ) { @@ -731,8 +730,6 @@ pub fn dump_active_flows() -> BusResponse { .flow_data .iter() .map(|(key, row)| { - let flow_data = row.lock().unwrap(); - let (local_data, analysis) = &*flow_data; let geo = get_asn_name_and_country(key.remote_ip.as_ip()); let (circuit_id, circuit_name) = (String::new(), String::new()); @@ -743,20 +740,20 @@ pub fn dump_active_flows() -> BusResponse { src_port: key.src_port, dst_port: key.dst_port, ip_protocol: FlowbeeProtocol::from(key.ip_protocol), - bytes_sent: local_data.bytes_sent, - packets_sent: local_data.packets_sent, - rate_estimate_bps: local_data.rate_estimate_bps, - tcp_retransmits: local_data.tcp_retransmits, - end_status: local_data.end_status, - tos: local_data.tos, - flags: local_data.flags, - remote_asn: analysis.asn_id.0, + bytes_sent: row.0.bytes_sent, + packets_sent: row.0.packets_sent, + rate_estimate_bps: row.0.rate_estimate_bps, + tcp_retransmits: row.0.tcp_retransmits, + end_status: row.0.end_status, + tos: row.0.tos, + flags: row.0.flags, + remote_asn: row.1.asn_id.0, remote_asn_name: geo.name, remote_asn_country: geo.country, - analysis: analysis.protocol_analysis.to_string(), - last_seen: local_data.last_seen, - start_time: local_data.start_time, - rtt_nanos: DownUpOrder::new(local_data.rtt[0].as_nanos(), local_data.rtt[1].as_nanos()), + analysis: row.1.protocol_analysis.to_string(), + last_seen: row.0.last_seen, + start_time: row.0.start_time, + rtt_nanos: DownUpOrder::new(row.0.rtt[0].as_nanos(), row.0.rtt[1].as_nanos()), circuit_id, circuit_name, } @@ -775,7 +772,7 @@ pub fn count_active_flows() -> BusResponse { /// Top Flows Report pub fn top_flows(n: u32, flow_type: TopFlowType) -> BusResponse { let lock = ALL_FLOWS.lock().unwrap(); - let mut table: Vec<(FlowbeeKey, Arc>)> = lock + let mut table: Vec<(FlowbeeKey, (FlowbeeLocalData, FlowAnalysis))> = lock .flow_data .iter() .map(|(key, value)| (key.clone(), value.clone())) @@ -785,46 +782,36 @@ pub fn top_flows(n: u32, flow_type: TopFlowType) -> BusResponse { match flow_type { TopFlowType::RateEstimate => { table.sort_by(|a, b| { - let a_lock = a.1.lock().unwrap(); - let b_lock = b.1.lock().unwrap(); - let a_total = a_lock.0.rate_estimate_bps.sum(); - let b_total = b_lock.0.rate_estimate_bps.sum(); + let a_total = a.1.0.rate_estimate_bps.sum(); + let b_total = b.1.0.rate_estimate_bps.sum(); b_total.cmp(&a_total) }); } TopFlowType::Bytes => { table.sort_by(|a, b| { - let a_lock = a.1.lock().unwrap(); - let b_lock = b.1.lock().unwrap(); - let a_total = a_lock.0.bytes_sent.sum(); - let b_total = b_lock.0.bytes_sent.sum(); + let a_total = a.1.0.bytes_sent.sum(); + let b_total = b.1.0.bytes_sent.sum(); b_total.cmp(&a_total) }); } TopFlowType::Packets => { table.sort_by(|a, b| { - let a_lock = a.1.lock().unwrap(); - let b_lock = b.1.lock().unwrap(); - let a_total = a_lock.0.packets_sent.sum(); - let b_total = b_lock.0.packets_sent.sum(); + let a_total = a.1.0.packets_sent.sum(); + let b_total = b.1.0.packets_sent.sum(); b_total.cmp(&a_total) }); } TopFlowType::Drops => { table.sort_by(|a, b| { - let a_lock = a.1.lock().unwrap(); - let b_lock = b.1.lock().unwrap(); - let a_total = a_lock.0.tcp_retransmits.sum(); - let b_total = b_lock.0.tcp_retransmits.sum(); + let a_total = a.1.0.tcp_retransmits.sum(); + let b_total = b.1.0.tcp_retransmits.sum(); b_total.cmp(&a_total) }); } TopFlowType::RoundTripTime => { table.sort_by(|a, b| { - let a_lock = a.1.lock().unwrap(); - let b_lock = b.1.lock().unwrap(); - let a_total = a_lock.0.rtt; - let b_total = b_lock.0.rtt; + let a_total = a.1.0.rtt; + let b_total = b.1.0.rtt; a_total.cmp(&b_total) }); } @@ -836,8 +823,6 @@ pub fn top_flows(n: u32, flow_type: TopFlowType) -> BusResponse { .iter() .take(n as usize) .map(|(ip, flow)| { - let flow_data = flow.lock().unwrap(); - let (local_data, analysis) = &*flow_data; let geo = get_asn_name_and_country(ip.remote_ip.as_ip()); let (circuit_id, circuit_name) = sd @@ -850,20 +835,20 @@ pub fn top_flows(n: u32, flow_type: TopFlowType) -> BusResponse { src_port: ip.src_port, dst_port: ip.dst_port, ip_protocol: FlowbeeProtocol::from(ip.ip_protocol), - bytes_sent: local_data.bytes_sent, - packets_sent: local_data.packets_sent, - rate_estimate_bps: local_data.rate_estimate_bps, - tcp_retransmits: local_data.tcp_retransmits, - end_status: local_data.end_status, - tos: local_data.tos, - flags: local_data.flags, - remote_asn: analysis.asn_id.0, + bytes_sent: flow.0.bytes_sent, + packets_sent: flow.0.packets_sent, + rate_estimate_bps: flow.0.rate_estimate_bps, + tcp_retransmits: flow.0.tcp_retransmits, + end_status: flow.0.end_status, + tos: flow.0.tos, + flags: flow.0.flags, + remote_asn: flow.1.asn_id.0, remote_asn_name: geo.name, remote_asn_country: geo.country, - analysis: analysis.protocol_analysis.to_string(), - last_seen: local_data.last_seen, - start_time: local_data.start_time, - rtt_nanos: DownUpOrder::new(local_data.rtt[0].as_nanos(), local_data.rtt[1].as_nanos()), + analysis: flow.1.protocol_analysis.to_string(), + last_seen: flow.0.last_seen, + start_time: flow.0.start_time, + rtt_nanos: DownUpOrder::new(flow.0.rtt[0].as_nanos(), flow.0.rtt[1].as_nanos()), circuit_id, circuit_name, } @@ -884,8 +869,6 @@ pub fn flows_by_ip(ip: &str) -> BusResponse { .iter() .filter(|(key, _)| key.local_ip == ip) .map(|(key, row)| { - let flow_data = row.lock().unwrap(); - let (local_data, analysis) = &*flow_data; let geo = get_asn_name_and_country(key.remote_ip.as_ip()); let (circuit_id, circuit_name) = sd @@ -898,20 +881,20 @@ pub fn flows_by_ip(ip: &str) -> BusResponse { src_port: key.src_port, dst_port: key.dst_port, ip_protocol: FlowbeeProtocol::from(key.ip_protocol), - bytes_sent: local_data.bytes_sent, - packets_sent: local_data.packets_sent, - rate_estimate_bps: local_data.rate_estimate_bps, - tcp_retransmits: local_data.tcp_retransmits, - end_status: local_data.end_status, - tos: local_data.tos, - flags: local_data.flags, - remote_asn: analysis.asn_id.0, + bytes_sent: row.0.bytes_sent, + packets_sent: row.0.packets_sent, + rate_estimate_bps: row.0.rate_estimate_bps, + tcp_retransmits: row.0.tcp_retransmits, + end_status: row.0.end_status, + tos: row.0.tos, + flags: row.0.flags, + remote_asn: row.1.asn_id.0, remote_asn_name: geo.name, remote_asn_country: geo.country, - analysis: analysis.protocol_analysis.to_string(), - last_seen: local_data.last_seen, - start_time: local_data.start_time, - rtt_nanos: DownUpOrder::new(local_data.rtt[0].as_nanos(), local_data.rtt[1].as_nanos()), + analysis: row.1.protocol_analysis.to_string(), + last_seen: row.0.last_seen, + start_time: row.0.start_time, + rtt_nanos: DownUpOrder::new(row.0.rtt[0].as_nanos(), row.0.rtt[1].as_nanos()), circuit_id, circuit_name, } diff --git a/src/rust/lqosd/src/throughput_tracker/tracking_data.rs b/src/rust/lqosd/src/throughput_tracker/tracking_data.rs index a19448a9..898ec047 100644 --- a/src/rust/lqosd/src/throughput_tracker/tracking_data.rs +++ b/src/rust/lqosd/src/throughput_tracker/tracking_data.rs @@ -21,18 +21,14 @@ use lqos_sys::{flowbee_data::FlowbeeKey, iterate_flows, throughput_for_each}; use lqos_utils::units::{AtomicDownUp, DownUpOrder}; use lqos_utils::{XdpIpAddress, unix_time::time_since_boot}; use std::collections::{HashMap, HashSet}; -use std::sync::{Mutex, Arc}; +use std::sync::Mutex; use std::{sync::atomic::AtomicU64, time::Duration}; use tracing::{debug, info, warn}; -use std::sync::atomic::Ordering; // Maximum number of flows to track simultaneously // TODO: This should be made configurable via the config file const MAX_FLOWS: usize = 1_000_000; -/// Counter for flows discarded due to full expired flow channel -static DISCARDED_EXPIRED_FLOWS: AtomicU64 = AtomicU64::new(0); - #[derive(Allocative)] pub struct ThroughputTracker { pub(crate) cycle: AtomicU64, @@ -317,7 +313,7 @@ impl ThroughputTracker { &self, timeout_seconds: u64, _netflow_enabled: bool, - sender: crossbeam_channel::Sender<(FlowbeeKey, Arc>)>, + sender: crossbeam_channel::Sender<(FlowbeeKey, (FlowbeeLocalData, FlowAnalysis))>, net_json_calc: &mut NetworkJson, rtt_circuit_tracker: &mut FxHashMap; 2]>, tcp_retries: &mut FxHashMap>, @@ -347,39 +343,38 @@ impl ThroughputTracker { // We have a valid flow, so it needs to be tracked if let Some(this_flow) = all_flows_lock.flow_data.get_mut(&key) { // If retransmits have changed, add the time to the retry list - let mut flow_data = this_flow.lock().unwrap(); - if data.tcp_retransmits.down != flow_data.0.tcp_retransmits.down { - if flow_data.0.retry_times_down.len() >= MAX_RETRY_TIMESTAMPS { - flow_data.0.retry_times_down.pop_front(); + if data.tcp_retransmits.down != this_flow.0.tcp_retransmits.down { + if this_flow.0.retry_times_down.len() >= MAX_RETRY_TIMESTAMPS { + this_flow.0.retry_times_down.pop_front(); } - flow_data.0.retry_times_down.push_back(data.last_seen); + this_flow.0.retry_times_down.push_back(data.last_seen); } - if data.tcp_retransmits.up != flow_data.0.tcp_retransmits.up { - if flow_data.0.retry_times_up.len() >= MAX_RETRY_TIMESTAMPS { - flow_data.0.retry_times_up.pop_front(); + if data.tcp_retransmits.up != this_flow.0.tcp_retransmits.up { + if this_flow.0.retry_times_up.len() >= MAX_RETRY_TIMESTAMPS { + this_flow.0.retry_times_up.pop_front(); } - flow_data.0.retry_times_up.push_back(data.last_seen); + this_flow.0.retry_times_up.push_back(data.last_seen); } //let change_since_last_time = data.bytes_sent.checked_sub_or_zero(this_flow.0.bytes_sent); //this_flow.0.throughput_buffer.push(change_since_last_time); //println!("{change_since_last_time:?}"); - flow_data.0.last_seen = data.last_seen; - flow_data.0.bytes_sent = data.bytes_sent; - flow_data.0.packets_sent = data.packets_sent; - flow_data.0.rate_estimate_bps = data.rate_estimate_bps; - flow_data.0.tcp_retransmits = data.tcp_retransmits; - flow_data.0.end_status = data.end_status; - flow_data.0.tos = data.tos; - flow_data.0.flags = data.flags; + this_flow.0.last_seen = data.last_seen; + this_flow.0.bytes_sent = data.bytes_sent; + this_flow.0.packets_sent = data.packets_sent; + this_flow.0.rate_estimate_bps = data.rate_estimate_bps; + this_flow.0.tcp_retransmits = data.tcp_retransmits; + this_flow.0.end_status = data.end_status; + this_flow.0.tos = data.tos; + this_flow.0.flags = data.flags; if let Some([up, down]) = rtt_samples.get(&key) { if up.as_nanos() != 0 { - flow_data.0.rtt[0] = *up; + this_flow.0.rtt[0] = *up; } if down.as_nanos() != 0 { - flow_data.0.rtt[1] = *down; + this_flow.0.rtt[1] = *down; } } } else { @@ -401,7 +396,7 @@ impl ThroughputTracker { let flow_analysis = FlowAnalysis::new(&key); all_flows_lock .flow_data - .insert(key.clone(), Arc::new(Mutex::new((data.into(), flow_analysis)))); + .insert(key.clone(), (data.into(), flow_analysis)); } } @@ -503,9 +498,7 @@ impl ThroughputTracker { for key in expired_keys.iter() { // Send it off to netperf for analysis if we are supporting doing so. if let Some(d) = all_flows_lock.flow_data.remove(&key) { - if sender.try_send((key.clone(), d)).is_err() { - DISCARDED_EXPIRED_FLOWS.fetch_add(1, Ordering::Relaxed); - } + let _ = sender.send((key.clone(), (d.0.clone(), d.1.clone()))); } } @@ -518,7 +511,7 @@ impl ThroughputTracker { // Cleaning run all_flows_lock .flow_data - .retain(|_k, v| v.lock().unwrap().0.last_seen >= expire); + .retain(|_k, v| v.0.last_seen >= expire); all_flows_lock.flow_data.shrink_to_fit(); expire_rtt_flows(); } -- knotmirror 0.0.1 From 88a282bafe1b289d3dbfa7f5a51b0c2a23ce540d Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Tue, 1 Jul 2025 14:05:52 -0500 Subject: [PATCH 08/16] Revert "Cap the number of locally held tcp retransmit timestemps per flow." This reverts commit f4e41233120f66a3a8585b5466057bab45dff7e8. --- .../src/throughput_tracker/flow_data/flow_tracker.rs | 12 ++++-------- .../lqosd/src/throughput_tracker/flow_data/mod.rs | 2 +- .../lqosd/src/throughput_tracker/tracking_data.rs | 11 ++--------- 3 files changed, 7 insertions(+), 18 deletions(-) diff --git a/src/rust/lqosd/src/throughput_tracker/flow_data/flow_tracker.rs b/src/rust/lqosd/src/throughput_tracker/flow_data/flow_tracker.rs index 19c9d596..7cd30985 100644 --- a/src/rust/lqosd/src/throughput_tracker/flow_data/flow_tracker.rs +++ b/src/rust/lqosd/src/throughput_tracker/flow_data/flow_tracker.rs @@ -9,10 +9,6 @@ use lqos_utils::units::DownUpOrder; use once_cell::sync::Lazy; use serde::Serialize; use std::sync::Mutex; -use std::collections::VecDeque; - -/// Maximum number of retry timestamps to keep per direction -pub const MAX_RETRY_TIMESTAMPS: usize = 20; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Allocative)] pub struct AsnId(pub u32); @@ -53,9 +49,9 @@ pub struct FlowbeeLocalData { /// Throughput Buffer //pub throughput_buffer: Vec>, /// When did the retries happen? In nanoseconds since kernel boot - pub retry_times_down: VecDeque, + pub retry_times_down: Vec, /// When did the retries happen? In nanoseconds since kernel boot - pub retry_times_up: VecDeque, + pub retry_times_up: Vec, } impl From<&FlowbeeData> for FlowbeeLocalData { @@ -72,8 +68,8 @@ impl From<&FlowbeeData> for FlowbeeLocalData { flags: data.flags, rtt: [RttData::from_nanos(0); 2], //throughput_buffer: vec![ data.bytes_sent ], - retry_times_down: VecDeque::with_capacity(MAX_RETRY_TIMESTAMPS), - retry_times_up: VecDeque::with_capacity(MAX_RETRY_TIMESTAMPS), + retry_times_down: Vec::new(), + retry_times_up: Vec::new(), } } } diff --git a/src/rust/lqosd/src/throughput_tracker/flow_data/mod.rs b/src/rust/lqosd/src/throughput_tracker/flow_data/mod.rs index bcdc8d89..e525b2e8 100644 --- a/src/rust/lqosd/src/throughput_tracker/flow_data/mod.rs +++ b/src/rust/lqosd/src/throughput_tracker/flow_data/mod.rs @@ -17,7 +17,7 @@ pub(crate) use flow_analysis::{ flowbee_rtt_map, get_asn_name_and_country, get_flowbee_event_count_and_reset, get_rtt_events_per_second, setup_flow_analysis, }; -pub(crate) use flow_tracker::{ALL_FLOWS, AsnId, FlowbeeLocalData, MAX_RETRY_TIMESTAMPS}; +pub(crate) use flow_tracker::{ALL_FLOWS, AsnId, FlowbeeLocalData}; use lqos_sys::flowbee_data::FlowbeeKey; use tracing::{debug, error, info}; diff --git a/src/rust/lqosd/src/throughput_tracker/tracking_data.rs b/src/rust/lqosd/src/throughput_tracker/tracking_data.rs index 898ec047..4bdc2333 100644 --- a/src/rust/lqosd/src/throughput_tracker/tracking_data.rs +++ b/src/rust/lqosd/src/throughput_tracker/tracking_data.rs @@ -2,7 +2,6 @@ use super::{ RETIRE_AFTER_SECONDS, flow_data::{ ALL_FLOWS, FlowAnalysis, FlowbeeLocalData, RttData, get_flowbee_event_count_and_reset, - MAX_RETRY_TIMESTAMPS, }, throughput_entry::ThroughputEntry, }; @@ -344,16 +343,10 @@ impl ThroughputTracker { if let Some(this_flow) = all_flows_lock.flow_data.get_mut(&key) { // If retransmits have changed, add the time to the retry list if data.tcp_retransmits.down != this_flow.0.tcp_retransmits.down { - if this_flow.0.retry_times_down.len() >= MAX_RETRY_TIMESTAMPS { - this_flow.0.retry_times_down.pop_front(); - } - this_flow.0.retry_times_down.push_back(data.last_seen); + this_flow.0.retry_times_down.push(data.last_seen); } if data.tcp_retransmits.up != this_flow.0.tcp_retransmits.up { - if this_flow.0.retry_times_up.len() >= MAX_RETRY_TIMESTAMPS { - this_flow.0.retry_times_up.pop_front(); - } - this_flow.0.retry_times_up.push_back(data.last_seen); + this_flow.0.retry_times_up.push(data.last_seen); } //let change_since_last_time = data.bytes_sent.checked_sub_or_zero(this_flow.0.bytes_sent); -- knotmirror 0.0.1 From acd9bde953c093ee82ce36dc5c81b38fbedc2978 Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Tue, 1 Jul 2025 14:57:44 -0500 Subject: [PATCH 09/16] Chore: flows only allocate retry time buffer if they have retries, and the buffer size is capped --- .../node_manager/local_api/flow_explorer.rs | 29 +++++++++++-------- .../flow_data/flow_analysis/finished_flows.rs | 26 ++++++++++++----- .../flow_data/flow_tracker.rs | 8 ++--- .../src/throughput_tracker/tracking_data.rs | 22 ++++++++++++-- 4 files changed, 59 insertions(+), 26 deletions(-) diff --git a/src/rust/lqosd/src/node_manager/local_api/flow_explorer.rs b/src/rust/lqosd/src/node_manager/local_api/flow_explorer.rs index eff2f7e4..d22fe939 100644 --- a/src/rust/lqosd/src/node_manager/local_api/flow_explorer.rs +++ b/src/rust/lqosd/src/node_manager/local_api/flow_explorer.rs @@ -72,6 +72,21 @@ fn all_flows_to_transport( circuit_name = flow.0.local_ip.as_ip().to_string(); } + let retransmit_times_down = if let Some(v) = &flow.1.retry_times_down { + v.iter() + .map(|t| boot_time + Duration::from_nanos(*t).as_secs()) + .collect() + } else { + Vec::new() + }; + let retransmit_times_up = if let Some(v) = &flow.1.retry_times_up { + v.iter() + .map(|t| boot_time + Duration::from_nanos(*t).as_secs()) + .collect() + } else { + Vec::new() + }; + FlowTimeline { start: boot_time + Duration::from_nanos(flow.1.start_time).as_secs(), end: boot_time + Duration::from_nanos(flow.1.last_seen).as_secs(), @@ -79,18 +94,8 @@ fn all_flows_to_transport( tcp_retransmits: flow.1.tcp_retransmits.clone(), throughput: vec![], rtt: flow.1.rtt.clone(), - retransmit_times_down: flow - .1 - .retry_times_down - .iter() - .map(|t| boot_time + Duration::from_nanos(*t).as_secs()) - .collect(), - retransmit_times_up: flow - .1 - .retry_times_up - .iter() - .map(|t| boot_time + Duration::from_nanos(*t).as_secs()) - .collect(), + retransmit_times_down, + retransmit_times_up, total_bytes: flow.1.bytes_sent.clone(), protocol: flow.2.protocol_analysis.to_string(), circuit_id, diff --git a/src/rust/lqosd/src/throughput_tracker/flow_data/flow_analysis/finished_flows.rs b/src/rust/lqosd/src/throughput_tracker/flow_data/flow_analysis/finished_flows.rs index dcbf6a8f..0f843a50 100644 --- a/src/rust/lqosd/src/throughput_tracker/flow_data/flow_analysis/finished_flows.rs +++ b/src/rust/lqosd/src/throughput_tracker/flow_data/flow_analysis/finished_flows.rs @@ -464,6 +464,22 @@ fn enqueue(key: FlowbeeKey, data: FlowbeeLocalData, analysis: FlowAnalysis) { //data.trim(); // Remove the trailing 30 seconds of zeroes //let tp_buf_dn = data.throughput_buffer.iter().map(|v| v.down).collect(); //let tp_buf_up = data.throughput_buffer.iter().map(|v| v.up).collect(); + + let retransmit_times_down = if let Some(v) = &data.retry_times_down { + v.iter() + .map(|t| boot_time_nanos_to_unix_now(*t).unwrap_or(0) as i64) + .collect() + } else { + Vec::new() + }; + let retransmit_times_up = if let Some(v) = &data.retry_times_up { + v.iter() + .map(|t| boot_time_nanos_to_unix_now(*t).unwrap_or(0) as i64) + .collect() + } else { + Vec::new() + }; + if let Err(e) = crate::lts2_sys::two_way_flow( start_time, last_seen, @@ -476,14 +492,8 @@ fn enqueue(key: FlowbeeKey, data: FlowbeeLocalData, analysis: FlowAnalysis) { data.bytes_sent.up, data.packets_sent.down as i64, data.packets_sent.up as i64, - data.retry_times_down - .iter() - .map(|t| boot_time_nanos_to_unix_now(*t).unwrap_or(0) as i64) - .collect(), - data.retry_times_up - .iter() - .map(|t| boot_time_nanos_to_unix_now(*t).unwrap_or(0) as i64) - .collect(), + retransmit_times_down, + retransmit_times_up, data.rtt[0].as_micros() as f32, data.rtt[1].as_micros() as f32, circuit_hash, diff --git a/src/rust/lqosd/src/throughput_tracker/flow_data/flow_tracker.rs b/src/rust/lqosd/src/throughput_tracker/flow_data/flow_tracker.rs index 7cd30985..d8118b6f 100644 --- a/src/rust/lqosd/src/throughput_tracker/flow_data/flow_tracker.rs +++ b/src/rust/lqosd/src/throughput_tracker/flow_data/flow_tracker.rs @@ -49,9 +49,9 @@ pub struct FlowbeeLocalData { /// Throughput Buffer //pub throughput_buffer: Vec>, /// When did the retries happen? In nanoseconds since kernel boot - pub retry_times_down: Vec, + pub retry_times_down: Option>, /// When did the retries happen? In nanoseconds since kernel boot - pub retry_times_up: Vec, + pub retry_times_up: Option>, } impl From<&FlowbeeData> for FlowbeeLocalData { @@ -68,8 +68,8 @@ impl From<&FlowbeeData> for FlowbeeLocalData { flags: data.flags, rtt: [RttData::from_nanos(0); 2], //throughput_buffer: vec![ data.bytes_sent ], - retry_times_down: Vec::new(), - retry_times_up: Vec::new(), + retry_times_down: None, + retry_times_up: None, } } } diff --git a/src/rust/lqosd/src/throughput_tracker/tracking_data.rs b/src/rust/lqosd/src/throughput_tracker/tracking_data.rs index 4bdc2333..e3bdbf1a 100644 --- a/src/rust/lqosd/src/throughput_tracker/tracking_data.rs +++ b/src/rust/lqosd/src/throughput_tracker/tracking_data.rs @@ -28,6 +28,8 @@ use tracing::{debug, info, warn}; // TODO: This should be made configurable via the config file const MAX_FLOWS: usize = 1_000_000; +const MAX_RETRY_TIMES: usize = 32; + #[derive(Allocative)] pub struct ThroughputTracker { pub(crate) cycle: AtomicU64, @@ -343,10 +345,26 @@ impl ThroughputTracker { if let Some(this_flow) = all_flows_lock.flow_data.get_mut(&key) { // If retransmits have changed, add the time to the retry list if data.tcp_retransmits.down != this_flow.0.tcp_retransmits.down { - this_flow.0.retry_times_down.push(data.last_seen); + if this_flow.0.retry_times_down.is_none() { + this_flow.0.retry_times_down = Some(Vec::with_capacity(MAX_RETRY_TIMES)); + } + if let Some(retry_times) = &mut this_flow.0.retry_times_down { + if retry_times.len() >= MAX_RETRY_TIMES { + retry_times.remove(0); + } + retry_times.push(data.last_seen); + } } if data.tcp_retransmits.up != this_flow.0.tcp_retransmits.up { - this_flow.0.retry_times_up.push(data.last_seen); + if this_flow.0.retry_times_up.is_none() { + this_flow.0.retry_times_up = Some(Vec::with_capacity(MAX_RETRY_TIMES)); + } + if let Some(retry_times) = &mut this_flow.0.retry_times_up { + if retry_times.len() >= MAX_RETRY_TIMES { + retry_times.remove(0); + } + retry_times.push(data.last_seen); + } } //let change_since_last_time = data.bytes_sent.checked_sub_or_zero(this_flow.0.bytes_sent); -- knotmirror 0.0.1 From 7910f9062a7533a730a07f47cf8c0f2fb95bbd4e Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Tue, 1 Jul 2025 14:58:43 -0500 Subject: [PATCH 10/16] Chore: Use try_send when submitting flow data because its better to lose some data than stall. --- src/rust/lqosd/src/throughput_tracker/flow_data/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/rust/lqosd/src/throughput_tracker/flow_data/mod.rs b/src/rust/lqosd/src/throughput_tracker/flow_data/mod.rs index e525b2e8..31084af1 100644 --- a/src/rust/lqosd/src/throughput_tracker/flow_data/mod.rs +++ b/src/rust/lqosd/src/throughput_tracker/flow_data/mod.rs @@ -67,7 +67,7 @@ pub fn setup_netflow_tracker() -> Result Date: Thu, 3 Jul 2025 11:52:47 -0500 Subject: [PATCH 11/16] The flow analysis is now pointer-free and copy (for simpler management), flow expiration is a little more aggressive to reduce burstiness. --- .../node_manager/local_api/flow_explorer.rs | 6 ++++-- .../flow_data/flow_analysis/finished_flows.rs | 10 ++++++---- .../flow_data/flow_analysis/mod.rs | 2 +- .../flow_data/flow_tracker.rs | 8 +++++--- .../src/throughput_tracker/tracking_data.rs | 20 +++++++++---------- 5 files changed, 25 insertions(+), 21 deletions(-) diff --git a/src/rust/lqosd/src/node_manager/local_api/flow_explorer.rs b/src/rust/lqosd/src/node_manager/local_api/flow_explorer.rs index d22fe939..967c7aac 100644 --- a/src/rust/lqosd/src/node_manager/local_api/flow_explorer.rs +++ b/src/rust/lqosd/src/node_manager/local_api/flow_explorer.rs @@ -73,14 +73,16 @@ fn all_flows_to_transport( } let retransmit_times_down = if let Some(v) = &flow.1.retry_times_down { - v.iter() + v.1.iter() + .filter(|n| **n > 0) .map(|t| boot_time + Duration::from_nanos(*t).as_secs()) .collect() } else { Vec::new() }; let retransmit_times_up = if let Some(v) = &flow.1.retry_times_up { - v.iter() + v.1.iter() + .filter(|n| **n > 0) .map(|t| boot_time + Duration::from_nanos(*t).as_secs()) .collect() } else { diff --git a/src/rust/lqosd/src/throughput_tracker/flow_data/flow_analysis/finished_flows.rs b/src/rust/lqosd/src/throughput_tracker/flow_data/flow_analysis/finished_flows.rs index 0f843a50..bec334ab 100644 --- a/src/rust/lqosd/src/throughput_tracker/flow_data/flow_analysis/finished_flows.rs +++ b/src/rust/lqosd/src/throughput_tracker/flow_data/flow_analysis/finished_flows.rs @@ -21,7 +21,7 @@ pub struct TimeBuffer { buffer: Mutex>, } -#[derive(Clone, Debug, Allocative)] +#[derive(Clone, Copy, Debug, Allocative)] struct TimeEntry { time: u64, data: (FlowbeeKey, FlowbeeLocalData, FlowAnalysis), @@ -435,7 +435,7 @@ impl FinishedFlowAnalysis { .spawn(|| { loop { RECENT_FLOWS.expire_over_one_minutes(); - std::thread::sleep(std::time::Duration::from_secs(60)); + std::thread::sleep(std::time::Duration::from_secs(10)); } }); let _ = std::thread::Builder::new() @@ -466,14 +466,16 @@ fn enqueue(key: FlowbeeKey, data: FlowbeeLocalData, analysis: FlowAnalysis) { //let tp_buf_up = data.throughput_buffer.iter().map(|v| v.up).collect(); let retransmit_times_down = if let Some(v) = &data.retry_times_down { - v.iter() + v.1.iter() + .filter(|n| **n > 0) .map(|t| boot_time_nanos_to_unix_now(*t).unwrap_or(0) as i64) .collect() } else { Vec::new() }; let retransmit_times_up = if let Some(v) = &data.retry_times_up { - v.iter() + v.1.iter() + .filter(|n| **n > 0) .map(|t| boot_time_nanos_to_unix_now(*t).unwrap_or(0) as i64) .collect() } else { diff --git a/src/rust/lqosd/src/throughput_tracker/flow_data/flow_analysis/mod.rs b/src/rust/lqosd/src/throughput_tracker/flow_data/flow_analysis/mod.rs index 996409ac..cf4fee31 100644 --- a/src/rust/lqosd/src/throughput_tracker/flow_data/flow_analysis/mod.rs +++ b/src/rust/lqosd/src/throughput_tracker/flow_data/flow_analysis/mod.rs @@ -73,7 +73,7 @@ pub fn setup_flow_analysis() -> anyhow::Result<()> { Ok(()) } -#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Allocative)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Allocative)] pub struct FlowAnalysis { pub asn_id: AsnId, pub protocol_analysis: FlowProtocol, diff --git a/src/rust/lqosd/src/throughput_tracker/flow_data/flow_tracker.rs b/src/rust/lqosd/src/throughput_tracker/flow_data/flow_tracker.rs index d8118b6f..d3eaeaec 100644 --- a/src/rust/lqosd/src/throughput_tracker/flow_data/flow_tracker.rs +++ b/src/rust/lqosd/src/throughput_tracker/flow_data/flow_tracker.rs @@ -1,6 +1,8 @@ //! Provides a globally accessible vector of all flows. This is used to store //! all flows for the purpose of tracking and data-services. +use crate::throughput_tracker::tracking_data::MAX_RETRY_TIMES; + use super::{RttData, flow_analysis::FlowAnalysis}; use allocative_derive::Allocative; use fxhash::FxHashMap; @@ -23,7 +25,7 @@ pub struct FlowTracker { /// Condensed representation of the FlowbeeData type. This contains /// only the information we want to keep locally for analysis purposes, /// adds RTT data, and uses Rust-friendly typing. -#[derive(Debug, Clone, Serialize, Allocative)] +#[derive(Debug, Clone, Copy, Serialize, Allocative)] pub struct FlowbeeLocalData { /// Time (nanos) when the connection was established pub start_time: u64, @@ -49,9 +51,9 @@ pub struct FlowbeeLocalData { /// Throughput Buffer //pub throughput_buffer: Vec>, /// When did the retries happen? In nanoseconds since kernel boot - pub retry_times_down: Option>, + pub retry_times_down: Option<(usize, [u64; MAX_RETRY_TIMES])>, /// When did the retries happen? In nanoseconds since kernel boot - pub retry_times_up: Option>, + pub retry_times_up: Option<(usize, [u64; MAX_RETRY_TIMES])>, } impl From<&FlowbeeData> for FlowbeeLocalData { diff --git a/src/rust/lqosd/src/throughput_tracker/tracking_data.rs b/src/rust/lqosd/src/throughput_tracker/tracking_data.rs index e3bdbf1a..a1f4a9ae 100644 --- a/src/rust/lqosd/src/throughput_tracker/tracking_data.rs +++ b/src/rust/lqosd/src/throughput_tracker/tracking_data.rs @@ -28,7 +28,7 @@ use tracing::{debug, info, warn}; // TODO: This should be made configurable via the config file const MAX_FLOWS: usize = 1_000_000; -const MAX_RETRY_TIMES: usize = 32; +pub const MAX_RETRY_TIMES: usize = 32; #[derive(Allocative)] pub struct ThroughputTracker { @@ -346,24 +346,22 @@ impl ThroughputTracker { // If retransmits have changed, add the time to the retry list if data.tcp_retransmits.down != this_flow.0.tcp_retransmits.down { if this_flow.0.retry_times_down.is_none() { - this_flow.0.retry_times_down = Some(Vec::with_capacity(MAX_RETRY_TIMES)); + this_flow.0.retry_times_down = Some((0, [0; MAX_RETRY_TIMES])); } if let Some(retry_times) = &mut this_flow.0.retry_times_down { - if retry_times.len() >= MAX_RETRY_TIMES { - retry_times.remove(0); - } - retry_times.push(data.last_seen); + retry_times.1[retry_times.0] = data.last_seen; + retry_times.0 += 1; + retry_times.0 %= MAX_RETRY_TIMES; } } if data.tcp_retransmits.up != this_flow.0.tcp_retransmits.up { if this_flow.0.retry_times_up.is_none() { - this_flow.0.retry_times_up = Some(Vec::with_capacity(MAX_RETRY_TIMES)); + this_flow.0.retry_times_up = Some((0, [0; MAX_RETRY_TIMES])); } if let Some(retry_times) = &mut this_flow.0.retry_times_up { - if retry_times.len() >= MAX_RETRY_TIMES { - retry_times.remove(0); - } - retry_times.push(data.last_seen); + retry_times.1[retry_times.0] = data.last_seen; + retry_times.0 += 1; + retry_times.0 %= MAX_RETRY_TIMES; } } -- knotmirror 0.0.1 From 27af94eaea48848e742e0940f49bd36d9045cc1d Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Thu, 3 Jul 2025 14:33:10 -0500 Subject: [PATCH 12/16] Test: no mimalloc, and the bus is much more strict about memory usage. --- .../lqos_bus/src/bus/unix_socket_server.rs | 20 ++++++++++++++++--- src/rust/lqosd/src/main.rs | 10 +++++----- 2 files changed, 22 insertions(+), 8 deletions(-) diff --git a/src/rust/lqos_bus/src/bus/unix_socket_server.rs b/src/rust/lqos_bus/src/bus/unix_socket_server.rs index f98e7257..d219503b 100644 --- a/src/rust/lqos_bus/src/bus/unix_socket_server.rs +++ b/src/rust/lqos_bus/src/bus/unix_socket_server.rs @@ -16,6 +16,9 @@ use super::BUS_SOCKET_DIRECTORY; /// Requests are handled and then forwarded to the handler. pub struct UnixSocketServer {} +static RECEIVE_BUFFER: tokio::sync::OnceCell>> = tokio::sync::OnceCell::const_new(); +const RECEIVE_BUFFER_SIZE: usize = 1024 * 1024 * 512; // 512 MiB + impl UnixSocketServer { /// Creates a new `UnixSocketServer`. Will delete any pre-existing /// socket file. @@ -88,6 +91,10 @@ impl UnixSocketServer { BusRequest, )>, ) -> Result<(), UnixSocketServerError> { + RECEIVE_BUFFER + .set(tokio::sync::Mutex::new(vec![0; RECEIVE_BUFFER_SIZE])) // 512 MiB + .map_err(|_| UnixSocketServerError::MkDirFail)?; + // Set up the listener and grant permissions to it let listener = UnixListener::bind(BUS_SOCKET_PATH); if listener.is_err() { @@ -155,10 +162,16 @@ impl UnixSocketServer { let request_id = u64::from_le_bytes(id_buf[0..8].try_into().unwrap()); let request_size = u64::from_le_bytes(id_buf[8..16].try_into().unwrap()); debug!("Received request ID: {request_id}, Size: {request_size}"); + if request_size > RECEIVE_BUFFER_SIZE as u64 { + warn!("Received request size ({request_size}) exceeds buffer size ({RECEIVE_BUFFER_SIZE})."); + break; // Escape out of the thread + } // Read the request data - let mut buf = vec![0; request_size as usize]; - let bytes_read = socket.read_exact(&mut buf).await; + //let mut buf = vec![0; request_size as usize]; + let mut buf = RECEIVE_BUFFER.get().unwrap().lock().await; + + let bytes_read = socket.read_exact(&mut buf[0 .. request_size as usize]).await; if bytes_read.is_err() { debug!("Unable to read request data from client socket. Server remains alive."); debug!("This is probably harmless."); @@ -167,11 +180,12 @@ impl UnixSocketServer { } // Decode the request - let Ok(request) = bincode::deserialize::(&buf) else { + let Ok(request) = bincode::deserialize::(&buf[0..request_size as usize]) else { warn!("Invalid data on local socket"); break; }; debug!("Received request: {:?}", request); + drop(buf); // Release the lock on the buffer // Handle the request and build the response let mut response = BusReply { responses: Vec::with_capacity(8) }; diff --git a/src/rust/lqosd/src/main.rs b/src/rust/lqosd/src/main.rs index 60e517f5..02e45c13 100644 --- a/src/rust/lqosd/src/main.rs +++ b/src/rust/lqosd/src/main.rs @@ -48,8 +48,8 @@ use throughput_tracker::flow_data::get_rtt_events_per_second; use tracing::{error, info, warn}; // Use MiMalloc only on supported platforms -#[cfg(any(target_arch = "x86", target_arch = "x86_64"))] -use mimalloc::MiMalloc; +//#[cfg(any(target_arch = "x86", target_arch = "x86_64"))] +//use mimalloc::MiMalloc; use crate::blackboard::{BLACKBOARD_SENDER, BlackboardCommand}; @@ -64,9 +64,9 @@ use tracing::level_filters::LevelFilter; use lqos_stormguard::STORMGUARD_STATS; // Use MiMalloc only on supported platforms -#[cfg(any(target_arch = "x86", target_arch = "x86_64"))] -#[global_allocator] -static GLOBAL: MiMalloc = MiMalloc; +// #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] +// #[global_allocator] +// static GLOBAL: MiMalloc = MiMalloc; /// Configure a highly detailed logging system. pub fn set_console_logging() -> anyhow::Result<()> { -- knotmirror 0.0.1 From a1ede4c8dd053b14c23c1aa8688033f9a1bddc72 Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Thu, 3 Jul 2025 14:51:32 -0500 Subject: [PATCH 13/16] Test: more allocative tracking --- .../src/node_manager/ws/publish_subscribe/publisher_channel.rs | 2 ++ .../lqosd/src/node_manager/ws/publish_subscribe/subscriber.rs | 3 +++ src/rust/lqosd/src/node_manager/ws/published_channels.rs | 3 ++- .../flow_data/flow_analysis/kernel_ringbuffer.rs | 2 ++ 4 files changed, 9 insertions(+), 1 deletion(-) diff --git a/src/rust/lqosd/src/node_manager/ws/publish_subscribe/publisher_channel.rs b/src/rust/lqosd/src/node_manager/ws/publish_subscribe/publisher_channel.rs index 382a32f6..95ea35d0 100644 --- a/src/rust/lqosd/src/node_manager/ws/publish_subscribe/publisher_channel.rs +++ b/src/rust/lqosd/src/node_manager/ws/publish_subscribe/publisher_channel.rs @@ -1,9 +1,11 @@ use crate::node_manager::ws::publish_subscribe::subscriber::Subscriber; use crate::node_manager::ws::published_channels::PublishedChannels; +use allocative::Allocative; use serde_json::json; use std::sync::Arc; use tokio::sync::mpsc::Sender; +#[derive(Allocative)] pub(super) struct PublisherChannel { pub(super) channel_type: PublishedChannels, subscribers: Vec, diff --git a/src/rust/lqosd/src/node_manager/ws/publish_subscribe/subscriber.rs b/src/rust/lqosd/src/node_manager/ws/publish_subscribe/subscriber.rs index 044189f4..6aabb09b 100644 --- a/src/rust/lqosd/src/node_manager/ws/publish_subscribe/subscriber.rs +++ b/src/rust/lqosd/src/node_manager/ws/publish_subscribe/subscriber.rs @@ -1,7 +1,10 @@ use std::sync::Arc; +use allocative::Allocative; use tokio::sync::mpsc::Sender; +#[derive(Allocative)] pub(super) struct Subscriber { pub(super) is_alive: bool, + #[allocative(skip)] pub(super) sender: Sender>, } diff --git a/src/rust/lqosd/src/node_manager/ws/published_channels.rs b/src/rust/lqosd/src/node_manager/ws/published_channels.rs index a7fc3dc2..15e03d6a 100644 --- a/src/rust/lqosd/src/node_manager/ws/published_channels.rs +++ b/src/rust/lqosd/src/node_manager/ws/published_channels.rs @@ -1,6 +1,7 @@ +use allocative::Allocative; use strum::{Display, EnumIter, EnumString}; -#[derive(PartialEq, Clone, Copy, Debug, EnumIter, Display, EnumString, Hash, Eq)] +#[derive(PartialEq, Clone, Copy, Debug, EnumIter, Display, EnumString, Hash, Eq, Allocative)] pub enum PublishedChannels { /// Provides a 1-second tick notification to the client Cadence, diff --git a/src/rust/lqosd/src/throughput_tracker/flow_data/flow_analysis/kernel_ringbuffer.rs b/src/rust/lqosd/src/throughput_tracker/flow_data/flow_analysis/kernel_ringbuffer.rs index 06585f15..a7d5ef29 100644 --- a/src/rust/lqosd/src/throughput_tracker/flow_data/flow_analysis/kernel_ringbuffer.rs +++ b/src/rust/lqosd/src/throughput_tracker/flow_data/flow_analysis/kernel_ringbuffer.rs @@ -1,5 +1,6 @@ //! Connects to the "flowbee_events" ring buffer and processes the events. use crate::throughput_tracker::flow_data::flow_analysis::rtt_types::RttData; +use allocative::Allocative; use fxhash::FxHashMap; use lqos_sys::flowbee_data::FlowbeeKey; use lqos_utils::unix_time::time_since_boot; @@ -20,6 +21,7 @@ static EVENTS_PER_SECOND: AtomicU64 = AtomicU64::new(0); const BUFFER_SIZE: usize = 1024; +#[derive(Allocative)] struct RttBuffer { index: usize, buffer: [[RttData; BUFFER_SIZE]; 2], -- knotmirror 0.0.1 From 993a6d0cbabb1aec8dcb029bd58d7692565dc72e Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Thu, 3 Jul 2025 15:16:32 -0500 Subject: [PATCH 14/16] Experiment: config in an arcswap to further reduce churn. --- src/rust/lqos_config/src/etc/mod.rs | 50 +++++++++++++++-------------- 1 file changed, 26 insertions(+), 24 deletions(-) diff --git a/src/rust/lqos_config/src/etc/mod.rs b/src/rust/lqos_config/src/etc/mod.rs index fd9804f9..750fee5e 100644 --- a/src/rust/lqos_config/src/etc/mod.rs +++ b/src/rust/lqos_config/src/etc/mod.rs @@ -8,8 +8,8 @@ use arc_swap::ArcSwap; pub use etclqos_migration::*; use once_cell::sync::Lazy; use std::path::Path; -use std::sync::atomic::AtomicBool; -use std::sync::{Arc, Mutex}; +use std::sync::Once; +use std::sync::Arc; use thiserror::Error; use tracing::{debug, error, info}; @@ -20,30 +20,32 @@ pub mod test_data; mod v15; pub use v15::{BridgeConfig, Tunables, LazyQueueMode}; -static CONFIG_LOADED: AtomicBool = AtomicBool::new(false); -static CONFIG: Lazy> = Lazy::new(|| match load_config() { - Ok(config) => { - CONFIG_LOADED.store(true, std::sync::atomic::Ordering::SeqCst); - ArcSwap::new(config) - } - Err(e) => { - error!("Unable to load configuration: {:?}", e); - ArcSwap::new(Arc::new(Config::default())) - } -}); - -static LOADER_MUTEX: Mutex = Mutex::new(false); +static CONFIG: Lazy>>> = Lazy::new(|| ArcSwap::from_pointee(None)); +static INIT_ONCE: Once = Once::new(); /// Load the configuration from `/etc/lqos.conf`. pub fn load_config() -> Result, LibreQoSConfigError> { - // If we have a cached version, return it - let mut lock = LOADER_MUTEX.lock().unwrap(); - *lock = !(*lock); // Not actually useful, prevents it from being optimized away - if CONFIG_LOADED.load(std::sync::atomic::Ordering::SeqCst) { - let clone = CONFIG.load().clone(); - return Ok(clone); - } + // Ensure first load happens only once + INIT_ONCE.call_once(|| { + match actually_load_from_disk() { + Ok(config) => { + CONFIG.store(Some(config).into()); + } + Err(e) => { + error!("Initial config load failed: {:?}", e); + } + } + }); + + // Fast path - just load the Arc + CONFIG.load() + .as_ref() + .as_ref() + .cloned() + .ok_or(LibreQoSConfigError::FileNotFoud) +} +fn actually_load_from_disk() -> Result, LibreQoSConfigError> { let config_location = if let Ok(lqos_config) = std::env::var("LQOS_CONFIG") { info!("Overriding lqos.conf location from environment variable."); lqos_config @@ -111,7 +113,7 @@ pub fn enable_long_term_stats(license_key: String) -> Result<(), LibreQoSConfigE /// Update the configuration on disk pub fn update_config(new_config: &Config) -> Result<(), LibreQoSConfigError> { debug!("Updating stored configuration"); - CONFIG.store(Arc::new(new_config.clone())); + CONFIG.store(Some(Arc::new(new_config.clone())).into()); // Does the configuration exist? let config_path = Path::new("/etc/lqos.conf"); @@ -149,7 +151,7 @@ pub fn disable_xdp_bridge() -> Result<(), LibreQoSConfigError> { } // Write the lock - CONFIG.store(Arc::new(config)); + CONFIG.store(Some(Arc::new(config)).into()); Ok(()) } -- knotmirror 0.0.1 From 1073279a7f025f2afd998cffdedf7ef96d70be99 Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Thu, 3 Jul 2025 15:29:22 -0500 Subject: [PATCH 15/16] Chore: Fix spelling mistake --- src/rust/lqos_config/src/etc/mod.rs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/rust/lqos_config/src/etc/mod.rs b/src/rust/lqos_config/src/etc/mod.rs index 750fee5e..f0564ab5 100644 --- a/src/rust/lqos_config/src/etc/mod.rs +++ b/src/rust/lqos_config/src/etc/mod.rs @@ -42,7 +42,7 @@ pub fn load_config() -> Result, LibreQoSConfigError> { .as_ref() .as_ref() .cloned() - .ok_or(LibreQoSConfigError::FileNotFoud) + .ok_or(LibreQoSConfigError::FileNotFound) } fn actually_load_from_disk() -> Result, LibreQoSConfigError> { @@ -56,13 +56,13 @@ fn actually_load_from_disk() -> Result, LibreQoSConfigError> { debug!("Loading configuration file {config_location}"); migrate_if_needed(&config_location).map_err(|e| { error!("Unable to migrate configuration: {:?}", e); - LibreQoSConfigError::FileNotFoud + LibreQoSConfigError::FileNotFound })?; let file_result = std::fs::read_to_string(&config_location); if file_result.is_err() { error!("Unable to open {config_location}"); - return Err(LibreQoSConfigError::FileNotFoud); + return Err(LibreQoSConfigError::FileNotFound); } let raw = file_result.unwrap(); @@ -83,7 +83,7 @@ fn actually_load_from_disk() -> Result, LibreQoSConfigError> { } debug!("Set cached version of config file"); - let new_config = Arc::new(final_config.clone()); + let new_config = Arc::new(final_config); Ok(new_config) } @@ -163,7 +163,7 @@ pub enum LibreQoSConfigError { #[error( "Unable to locate (path to LibreQoS)/ispConfig.py. Check your path and that you have configured it." )] - FileNotFoud, + FileNotFound, #[error("Unable to read the contents of ispConfig.py. Check file permissions.")] CannotReadFile, #[error("Unable to parse ispConfig.py")] -- knotmirror 0.0.1 From 28d2813134b6ac80a2267d2fccf568c6531f25bf Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Tue, 8 Jul 2025 11:14:41 -0500 Subject: [PATCH 16/16] Chore: reset to normal mode rather than flamegraph tracking. --- src/rust/lqosd/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/rust/lqosd/Cargo.toml b/src/rust/lqosd/Cargo.toml index 23b3b5c5..aa4d170d 100644 --- a/src/rust/lqosd/Cargo.toml +++ b/src/rust/lqosd/Cargo.toml @@ -5,7 +5,7 @@ edition = "2024" license = "GPL-2.0-only" [features] -default = ["equinix_tests", "flamegraphs"] +default = ["equinix_tests"] equinix_tests = [] flamegraphs = [] -- knotmirror 0.0.1