diff --git a/src/LibreQoS.py b/src/LibreQoS.py index 87e09a40..fa16bb6f 100755 --- a/src/LibreQoS.py +++ b/src/LibreQoS.py @@ -157,8 +157,7 @@ def tearDown(interfaceA, interfaceB): # Full teardown of everything for exiting LibreQoS if enable_actual_shell_commands(): # Clear IP filters and remove xdp program from interfaces - #result = os.system('./bin/xdp_iphash_to_cpu_cmdline clear') - clear_ip_mappings() # Use the bus + # The bakery tracks and prunes mappings; avoid clearing everything here. clearPriorSettings(interfaceA, interfaceB) def findQueuesAvailable(interfaceName): @@ -1135,10 +1134,8 @@ def refreshShapers(): # Setup XDP and disable XPS regardless of whether it is first run or not (necessary to handle cases where systemctl stop was used) xdpStartTime = datetime.now() - if enable_actual_shell_commands(): - # Here we use os.system for the command, because otherwise it sometimes gltiches out with Popen in shell() - #result = os.system('./bin/xdp_iphash_to_cpu_cmdline clear') - clear_ip_mappings() # Use the bus + #if enable_actual_shell_commands(): + # The bakery will handle stale mapping cleanup; avoid clearing mappings here. # Set up XDP-CPUMAP-TC logging.info("# XDP Setup") # Commented out - the daemon does this diff --git a/src/rust/Cargo.lock b/src/rust/Cargo.lock index 86958614..d2a592a0 100644 --- a/src/rust/Cargo.lock +++ b/src/rust/Cargo.lock @@ -1896,6 +1896,7 @@ dependencies = [ "lqos_config", "once_cell", "parking_lot", + "tokio", "tracing", ] diff --git a/src/rust/lqos_bakery/Cargo.toml b/src/rust/lqos_bakery/Cargo.toml index 38adce64..fac885ae 100644 --- a/src/rust/lqos_bakery/Cargo.toml +++ b/src/rust/lqos_bakery/Cargo.toml @@ -13,3 +13,4 @@ once_cell.workspace = true allocative.workspace = true allocative_derive.workspace = true parking_lot.workspace = true +tokio.workspace = true diff --git a/src/rust/lqos_bakery/src/commands.rs b/src/rust/lqos_bakery/src/commands.rs index dc90098f..d6e670e3 100644 --- a/src/rust/lqos_bakery/src/commands.rs +++ b/src/rust/lqos_bakery/src/commands.rs @@ -47,6 +47,28 @@ pub enum ExecutionMode { /// List of commands that the Bakery system can handle. #[derive(Debug, Clone, Allocative)] pub enum BakeryCommands { + /// Add or update an IP mapping (mirrors `MapIpToFlow` from the bus) + MapIp { + /// The IP address to map (may include CIDR prefix) + ip_address: String, + /// Classifier handle (major:minor) + tc_handle: TcHandle, + /// CPU index + cpu: u32, + /// Upload map (on-a-stick second map) + upload: bool, + }, + /// Delete an IP mapping (mirrors `DelIpFlow` from the bus) + DelIp { + /// The IP address to unmap (may include CIDR prefix) + ip_address: String, + /// Upload map (on-a-stick second map) + upload: bool, + }, + /// Clear all IP mappings (mirrors `ClearIpFlow` from the bus) + ClearIpAll, + /// Commit the current set of staged IP mappings and perform stale cleanup. + CommitMappings, /// Send this when circuits are seen by the throughput tracker OnCircuitActivity { /// All active circuit IDs diff --git a/src/rust/lqos_bakery/src/lib.rs b/src/rust/lqos_bakery/src/lib.rs index 5464f681..91ec75cc 100644 --- a/src/rust/lqos_bakery/src/lib.rs +++ b/src/rust/lqos_bakery/src/lib.rs @@ -39,6 +39,7 @@ use crate::queue_math::format_rate_for_tc_f32; use crate::utils::{execute_in_memory, write_command_file}; pub use commands::BakeryCommands; use lqos_config::{Config, LazyQueueMode}; +use lqos_bus::{BusRequest, BusResponse, LibreqosBusClient, TcHandle}; /// Count of Bakery-Managed circuits that are currently active. pub static ACTIVE_CIRCUITS: AtomicUsize = AtomicUsize::new(0); @@ -70,6 +71,145 @@ fn bakery_main(rx: Receiver, tx: Sender) { let mut circuits: HashMap> = HashMap::new(); let mut live_circuits: HashMap = HashMap::new(); + // Mapping state + #[derive(Clone, Hash, PartialEq, Eq, Debug)] + struct MappingKey { + ip: String, + prefix: u32, + upload: bool, + } + #[derive(Clone, Debug)] + struct MappingVal { + handle: TcHandle, + cpu: u32, + } + // Current kernel view (authoritative state) as tracked by the bakery + let mut mapping_current: HashMap = HashMap::new(); + // Next desired set staged during a batch (Python batches or other tools) + let mut mapping_staged: Option> = None; + // Keys that exist in the kernel but we couldn't classify to a known circuit (never delete automatically) + let mut mapping_unknown: HashSet = HashSet::new(); + let mut mapping_seeded: bool = false; + + fn parse_ip_and_prefix(ip: &str) -> (String, u32) { + if let Some((addr, pfx)) = ip.split_once('/') { + if let Ok(n) = pfx.parse::() { + return (addr.to_string(), n); + } + } + // No prefix provided; infer by address family + // Simple heuristic: ':' suggests IPv6 + if ip.contains(':') { + (ip.to_string(), 128) + } else { + (ip.to_string(), 32) + } + } + + fn handle_map_ip( + ip_address: &str, + tc_handle: TcHandle, + cpu: u32, + upload: bool, + mapping_staged: &mut Option>, + ) { + let (ip, prefix) = parse_ip_and_prefix(ip_address); + let key = MappingKey { ip, prefix, upload }; + let val = MappingVal { handle: tc_handle, cpu }; + if mapping_staged.is_none() { + *mapping_staged = Some(HashMap::new()); + } + if let Some(stage) = mapping_staged.as_mut() { + stage.insert(key, val); + } + } + + fn handle_del_ip( + ip_address: &str, + upload: bool, + mapping_staged: &mut Option>, + mapping_current: &mut HashMap, + ) { + // Best-effort deletion: if exact prefix was provided, remove that, else try common host prefixes + let (ip, prefix) = parse_ip_and_prefix(ip_address); + let key = MappingKey { ip: ip.clone(), prefix, upload }; + if let Some(stage) = mapping_staged.as_mut() { + stage.remove(&key); + } + mapping_current.remove(&key); + } + + fn build_handle_sets( + circuits: &HashMap>, + ) -> (HashSet, HashSet) { + let mut down = HashSet::new(); + let mut up = HashSet::new(); + for (_k, v) in circuits.iter() { + if let BakeryCommands::AddCircuit { + class_minor, + class_major, + up_class_major, + .. + } = v.as_ref() + { + let down_tc = TcHandle::from_u32(((*class_major as u32) << 16) | (*class_minor as u32)); + let up_tc = TcHandle::from_u32(((*up_class_major as u32) << 16) | (*class_minor as u32)); + down.insert(down_tc); + up.insert(up_tc); + } + } + (down, up) + } + + fn attempt_seed_mappings( + circuits: &HashMap>, + mapping_current: &mut HashMap, + mapping_unknown: &mut HashSet, + ) -> anyhow::Result<()> { + // Build classification sets + let (down_set, up_set) = build_handle_sets(circuits); + + // Create a small runtime to make a one-shot bus request + let rt = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build()?; + rt.block_on(async { + let mut bus = LibreqosBusClient::new().await?; + let reply = bus.request(vec![BusRequest::ListIpFlow]).await?; + for r in reply.iter() { + if let BusResponse::MappedIps(list) = r { + for m in list.iter() { + // m.ip_address does not include prefix, prefix_length is provided + let key = MappingKey { + ip: m.ip_address.clone(), + prefix: m.prefix_length, + upload: if up_set.contains(&m.tc_handle) { + true + } else if down_set.contains(&m.tc_handle) { + false + } else { + // Unknown mapping (do not delete automatically) + let k = MappingKey { + ip: m.ip_address.clone(), + prefix: m.prefix_length, + upload: false, // default; upload is unknown + }; + mapping_unknown.insert(k.clone()); + mapping_current.insert( + k, + MappingVal { handle: m.tc_handle, cpu: m.cpu }, + ); + continue; + }, + }; + mapping_current.insert(key, MappingVal { handle: m.tc_handle, cpu: m.cpu }); + } + } + } + anyhow::Ok(()) + }) + } + { let Ok(config) = lqos_config::load_config() else { error!("Failed to load configuration, exiting Bakery thread."); @@ -86,6 +226,91 @@ fn bakery_main(rx: Receiver, tx: Sender) { debug!("Bakery received command: {:?}", command); match command { + // Mapping events (mirrored from lqosd bus handling) + BakeryCommands::MapIp { + ip_address, + tc_handle, + cpu, + upload, + } => { + handle_map_ip(&ip_address, tc_handle, cpu, upload, &mut mapping_staged); + } + BakeryCommands::DelIp { ip_address, upload } => { + handle_del_ip(&ip_address, upload, &mut mapping_staged, &mut mapping_current); + } + BakeryCommands::ClearIpAll => { + mapping_current.clear(); + mapping_unknown.clear(); + mapping_staged = None; + } + BakeryCommands::CommitMappings => { + // Ensure we are seeded before first commit to avoid assuming empty kernel state. + if !mapping_seeded { + match attempt_seed_mappings(&circuits, &mut mapping_current, &mut mapping_unknown) { + Ok(_) => { + info!("Bakery: Seeded IP mappings from kernel"); + mapping_seeded = true; + } + Err(e) => warn!("Bakery: Failed to seed IP mappings: {:?}", e), + } + } + + if let Some(staged) = mapping_staged.take() { + // Remove stale mappings: present in current, not in staged; never delete unknowns + let mut stale = Vec::new(); + for k in mapping_current.keys() { + if mapping_unknown.contains(k) { + continue; // don't touch unknowns + } + if !staged.contains_key(k) { + stale.push(k.clone()); + } + } + + if !stale.is_empty() { + // Batch deletions via the bus client + let rt = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build(); + if let Ok(rt) = rt { + let stale_to_delete = stale.clone(); + let _ = rt.block_on(async move { + if let Ok(mut bus) = LibreqosBusClient::new().await { + // chunk operations to keep request sizes reasonable + const CHUNK: usize = 512; + for chunk in stale_to_delete.chunks(CHUNK) { + let mut reqs = Vec::with_capacity(chunk.len()); + for k in chunk.iter() { + // Recompose an IP string with prefix if not host (/32 or /128) + let ip = if k.prefix == 32 || k.prefix == 128 { + k.ip.clone() + } else { + format!("{}/{}", k.ip, k.prefix) + }; + reqs.push(BusRequest::DelIpFlow { + ip_address: ip, + upload: k.upload, + }); + } + let _ = bus.request(reqs).await; + } + } + }); + } else { + warn!("Bakery: Unable to create runtime for stale IP deletions"); + } + + for k in stale.into_iter() { + mapping_current.remove(&k); + } + } + + // Merge staged into current (they are already applied in kernel by lqosd) + for (k, v) in staged.into_iter() { + mapping_current.insert(k, v); + } + } + } BakeryCommands::StartBatch => { batch = Some(Vec::new()); } diff --git a/src/rust/lqosd/src/main.rs b/src/rust/lqosd/src/main.rs index f3d4e5b4..a3919369 100644 --- a/src/rust/lqosd/src/main.rs +++ b/src/rust/lqosd/src/main.rs @@ -350,10 +350,42 @@ fn handle_bus_requests(requests: &[BusRequest], responses: &mut Vec tc_handle, cpu, upload, - } => map_ip_to_flow(ip_address, tc_handle, *cpu, *upload), - BusRequest::ClearHotCache => clear_hot_cache(), - BusRequest::DelIpFlow { ip_address, upload } => del_ip_flow(ip_address, *upload), - BusRequest::ClearIpFlow => clear_ip_flows(), + } => { + let resp = map_ip_to_flow(ip_address, tc_handle, *cpu, *upload); + if let Some(sender) = lqos_bakery::BAKERY_SENDER.get() { + let _ = sender.send(lqos_bakery::BakeryCommands::MapIp { + ip_address: ip_address.clone(), + tc_handle: *tc_handle, + cpu: *cpu, + upload: *upload, + }); + } + resp + } + BusRequest::ClearHotCache => { + // Let the bakery finalize staged mapping changes, then clear hot cache. + if let Some(sender) = lqos_bakery::BAKERY_SENDER.get() { + let _ = sender.send(lqos_bakery::BakeryCommands::CommitMappings); + } + clear_hot_cache() + } + BusRequest::DelIpFlow { ip_address, upload } => { + let resp = del_ip_flow(ip_address, *upload); + if let Some(sender) = lqos_bakery::BAKERY_SENDER.get() { + let _ = sender.send(lqos_bakery::BakeryCommands::DelIp { + ip_address: ip_address.clone(), + upload: *upload, + }); + } + resp + } + BusRequest::ClearIpFlow => { + let resp = clear_ip_flows(); + if let Some(sender) = lqos_bakery::BAKERY_SENDER.get() { + let _ = sender.send(lqos_bakery::BakeryCommands::ClearIpAll); + } + resp + } BusRequest::ListIpFlow => list_mapped_ips(), BusRequest::XdpPping => throughput_tracker::xdp_pping_compat(), BusRequest::RttHistogram => throughput_tracker::rtt_histogram::<50>(), -- knotmirror 0.0.1 From 956415e5717cdb6936d3d85afcb9607b5a137c6a Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Thu, 30 Oct 2025 13:40:13 -0500 Subject: [PATCH 02/11] Feat: Dynamic circuit changes Circuits can now be added, removed, change speed and IP without triggering a full reload. Changes happen in-place (circuits are removed and re-added, not ideal but works around TC bugs). --- src/rust/lqos_bakery/src/commands.rs | 2 + src/rust/lqos_bakery/src/diff/circuits.rs | 121 ++++++++------ src/rust/lqos_bakery/src/diff/mod.rs | 2 +- src/rust/lqos_bakery/src/lib.rs | 182 +++++++++++++--------- src/rust/lqosd/src/main.rs | 15 ++ 5 files changed, 202 insertions(+), 120 deletions(-) diff --git a/src/rust/lqos_bakery/src/commands.rs b/src/rust/lqos_bakery/src/commands.rs index d6e670e3..e66e62ff 100644 --- a/src/rust/lqos_bakery/src/commands.rs +++ b/src/rust/lqos_bakery/src/commands.rs @@ -47,6 +47,8 @@ pub enum ExecutionMode { /// List of commands that the Bakery system can handle. #[derive(Debug, Clone, Allocative)] pub enum BakeryCommands { + /// Notification that the bus socket is ready; bakery can seed mappings + BusReady, /// Add or update an IP mapping (mirrors `MapIpToFlow` from the bus) MapIp { /// The IP address to map (may include CIDR prefix) diff --git a/src/rust/lqos_bakery/src/diff/circuits.rs b/src/rust/lqos_bakery/src/diff/circuits.rs index cc9f21b1..8400cccf 100644 --- a/src/rust/lqos_bakery/src/diff/circuits.rs +++ b/src/rust/lqos_bakery/src/diff/circuits.rs @@ -3,13 +3,17 @@ use std::collections::HashMap; use std::sync::Arc; use tracing::warn; +pub(crate) struct CircuitDiffCategories<'a> { + pub newly_added: Vec<&'a Arc>, + pub removed_circuits: Vec, + pub speed_changed: Vec<&'a Arc>, + pub ip_changed: Vec<&'a Arc>, + pub structural_changed: Vec<&'a Arc>, +} + pub(crate) enum CircuitDiffResult<'a> { NoChange, - CircuitsChanged { - newly_added: Vec<&'a Arc>, - removed_circuits: Vec, // Just store the circuit hash for removal - updated_circuits: Vec<&'a Arc>, - }, + Categorized(CircuitDiffCategories<'a>), } pub(crate) fn diff_circuits<'a>( @@ -27,46 +31,67 @@ pub(crate) fn diff_circuits<'a>( }) .collect(); - // Find any circuits that have been added to `new_circuits` and not in `old_circuits` let mut newly_added = Vec::new(); + let mut removed_circuits = Vec::new(); + let mut speed_changed = Vec::new(); + let mut ip_changed = Vec::new(); + let mut structural_changed = Vec::new(); + for (circuit_hash, new_cmd) in &new_circuits { if !old_circuits.contains_key(circuit_hash) { newly_added.push(*new_cmd); } } - // Find any circuits that have been removed from `new_circuits`, but were in `old_circuits` - let mut removed_circuits = Vec::new(); for circuit_hash in old_circuits.keys() { if !new_circuits.contains_key(circuit_hash) { removed_circuits.push(*circuit_hash); } } - // Find any circuits that have changed in `new_circuits` compared to `old_circuits` - let mut updated_circuits = Vec::new(); for (circuit_hash, old_cmd) in old_circuits { - if let Some(new_cmd) = new_circuits.get(circuit_hash) - && has_circuit_changed(old_cmd.as_ref(), new_cmd.as_ref()) { - updated_circuits.push(*new_cmd); + if let Some(new_cmd) = new_circuits.get(circuit_hash) { + match classify_circuit_change(old_cmd.as_ref(), new_cmd.as_ref()) { + CircuitChange::None => {} + CircuitChange::Structural => structural_changed.push(*new_cmd), + CircuitChange::Speed => speed_changed.push(*new_cmd), + CircuitChange::Ip => ip_changed.push(*new_cmd), + CircuitChange::SpeedAndIp => { + speed_changed.push(*new_cmd); + ip_changed.push(*new_cmd); + } } + } } - // If there are any changes, return them - if !newly_added.is_empty() || !removed_circuits.is_empty() || !updated_circuits.is_empty() { - CircuitDiffResult::CircuitsChanged { + if !newly_added.is_empty() + || !removed_circuits.is_empty() + || !speed_changed.is_empty() + || !ip_changed.is_empty() + || !structural_changed.is_empty() + { + CircuitDiffResult::Categorized(CircuitDiffCategories { newly_added, removed_circuits, - updated_circuits, - } + speed_changed, + ip_changed, + structural_changed, + }) } else { CircuitDiffResult::NoChange } } -fn has_circuit_changed(circuit_a: &BakeryCommands, circuit_b: &BakeryCommands) -> bool { +enum CircuitChange { + None, + Structural, + Speed, + Ip, + SpeedAndIp, +} + +fn classify_circuit_change(a: &BakeryCommands, b: &BakeryCommands) -> CircuitChange { let BakeryCommands::AddCircuit { - circuit_hash, parent_class_id, up_parent_class_id, class_minor, @@ -77,16 +102,13 @@ fn has_circuit_changed(circuit_a: &BakeryCommands, circuit_b: &BakeryCommands) - class_major, up_class_major, ip_addresses, - } = circuit_a + .. + } = a else { - warn!( - "circuit_changed called on non-circuit command: {:?}", - circuit_a - ); - return false; // Not a circuit command + warn!("classify_circuit_change called on non-circuit command: {:?}", a); + return CircuitChange::None; }; let BakeryCommands::AddCircuit { - circuit_hash: other_circuit_hash, parent_class_id: other_parent_class_id, up_parent_class_id: other_up_parent_class_id, class_minor: other_class_minor, @@ -97,31 +119,34 @@ fn has_circuit_changed(circuit_a: &BakeryCommands, circuit_b: &BakeryCommands) - class_major: other_class_major, up_class_major: other_up_class_major, ip_addresses: other_ip_addresses, - } = circuit_b + .. + } = b else { - warn!( - "circuit_changed called on non-circuit command: {:?}", - circuit_b - ); - return false; // Not a circuit command + warn!("classify_circuit_change called on non-circuit command: {:?}", b); + return CircuitChange::None; }; - if circuit_hash != other_circuit_hash { - // This should never happen - warn!( - "Circuit hashes do not match: {} != {}", - circuit_hash, other_circuit_hash - ); - return false; // Different circuit hashes - } - - parent_class_id != other_parent_class_id + // Structural change? + let structural = parent_class_id != other_parent_class_id || up_parent_class_id != other_up_parent_class_id || class_minor != other_class_minor - || download_bandwidth_min != other_download_bandwidth_min + || class_major != other_class_major + || up_class_major != other_up_class_major; + + if structural { + return CircuitChange::Structural; + } + + let speed = download_bandwidth_min != other_download_bandwidth_min || upload_bandwidth_min != other_upload_bandwidth_min || download_bandwidth_max != other_download_bandwidth_max - || upload_bandwidth_max != other_upload_bandwidth_max - || class_major != other_class_major - || up_class_major != other_up_class_major - || ip_addresses != other_ip_addresses + || upload_bandwidth_max != other_upload_bandwidth_max; + + let ip = ip_addresses != other_ip_addresses; + + match (speed, ip) { + (false, false) => CircuitChange::None, + (true, false) => CircuitChange::Speed, + (false, true) => CircuitChange::Ip, + (true, true) => CircuitChange::SpeedAndIp, + } } diff --git a/src/rust/lqos_bakery/src/diff/mod.rs b/src/rust/lqos_bakery/src/diff/mod.rs index 020a029d..23120f73 100644 --- a/src/rust/lqos_bakery/src/diff/mod.rs +++ b/src/rust/lqos_bakery/src/diff/mod.rs @@ -1,5 +1,5 @@ mod circuits; mod sites; -pub(crate) use circuits::{CircuitDiffResult, diff_circuits}; +pub(crate) use circuits::{CircuitDiffCategories, CircuitDiffResult, diff_circuits}; pub(crate) use sites::{SiteDiffResult, diff_sites}; diff --git a/src/rust/lqos_bakery/src/lib.rs b/src/rust/lqos_bakery/src/lib.rs index 91ec75cc..3c9b7609 100644 --- a/src/rust/lqos_bakery/src/lib.rs +++ b/src/rust/lqos_bakery/src/lib.rs @@ -34,7 +34,7 @@ use tracing::{debug, error, info, warn}; use utils::current_timestamp; pub(crate) const CHANNEL_CAPACITY: usize = 65536; // 64k capacity for Bakery commands use crate::commands::ExecutionMode; -use crate::diff::{SiteDiffResult, diff_sites}; +use crate::diff::{CircuitDiffResult, SiteDiffResult, diff_circuits, diff_sites}; use crate::queue_math::format_rate_for_tc_f32; use crate::utils::{execute_in_memory, write_command_file}; pub use commands::BakeryCommands; @@ -235,6 +235,19 @@ fn bakery_main(rx: Receiver, tx: Sender) { } => { handle_map_ip(&ip_address, tc_handle, cpu, upload, &mut mapping_staged); } + BakeryCommands::BusReady => { + if !mapping_seeded { + match attempt_seed_mappings(&circuits, &mut mapping_current, &mut mapping_unknown) { + Ok(_) => { + let total = mapping_current.len(); + let unknown = mapping_unknown.len(); + info!("Bakery mappings seeded: total={}, unknown={}", total, unknown); + mapping_seeded = true; + } + Err(e) => warn!("Bakery: Failed to seed IP mappings at bus-ready: {:?}", e), + } + } + } BakeryCommands::DelIp { ip_address, upload } => { handle_del_ip(&ip_address, upload, &mut mapping_staged, &mut mapping_current); } @@ -248,7 +261,9 @@ fn bakery_main(rx: Receiver, tx: Sender) { if !mapping_seeded { match attempt_seed_mappings(&circuits, &mut mapping_current, &mut mapping_unknown) { Ok(_) => { - info!("Bakery: Seeded IP mappings from kernel"); + let total = mapping_current.len(); + let unknown = mapping_unknown.len(); + info!("Bakery mappings seeded: total={}, unknown={}", total, unknown); mapping_seeded = true; } Err(e) => warn!("Bakery: Failed to seed IP mappings: {:?}", e), @@ -444,37 +459,41 @@ fn handle_commit_batch( let site_change_mode = diff_sites(&new_batch, sites); if matches!(site_change_mode, SiteDiffResult::RebuildRequired) { // If the site structure has changed, we need to rebuild everything. - info!("Site structure has changed, performing full reload."); + info!("Bakery full reload: site_struct=1, circuit_struct=0"); full_reload(batch, sites, circuits, live_circuits, &config, new_batch); MQ_CREATED.store(true, std::sync::atomic::Ordering::Relaxed); return; } - let circuit_change_mode = diff::diff_circuits(&new_batch, circuits); + let circuit_change_mode = diff_circuits(&new_batch, circuits); // If neither has changed, there's nothing to do. if matches!(site_change_mode, SiteDiffResult::NoChange) - && matches!(circuit_change_mode, diff::CircuitDiffResult::NoChange) + && matches!(circuit_change_mode, CircuitDiffResult::NoChange) { // No changes detected, skip processing info!("No changes detected in batch, skipping processing."); return; } - // Check if we should do a full reload based on the number of circuit changes - if let diff::CircuitDiffResult::CircuitsChanged { - newly_added: _, - removed_circuits: _, - updated_circuits: _, - } = &circuit_change_mode - { - full_reload(batch, sites, circuits, live_circuits, &config, new_batch); - return; // Skip the rest of this CommitBatch processing + // If any structural changes occurred, do a full reload + if let CircuitDiffResult::Categorized(categories) = &circuit_change_mode { + if !categories.structural_changed.is_empty() { + info!( + "Bakery full reload: site_struct=0, circuit_struct={}", + categories.structural_changed.len() + ); + full_reload(batch, sites, circuits, live_circuits, &config, new_batch); + MQ_CREATED.store(true, std::sync::atomic::Ordering::Relaxed); + return; + } } // Declare any site speed changes that need to be applied. We're sending them // to ourselves as future commands via the BakeryCommands channel. + let mut site_speed_change_count = 0usize; if let SiteDiffResult::SpeedChanges { changes } = site_change_mode { + site_speed_change_count = changes.len(); for change in &changes { let BakeryCommands::AddSite { site_hash, @@ -499,6 +518,7 @@ fn handle_commit_batch( upload_bandwidth_max: *upload_bandwidth_max, }) { error!("Channel full, falling back to full rebuild: {}", e); + info!("Bakery full reload: site_struct=0, circuit_struct=0"); full_reload( batch, sites, @@ -512,89 +532,109 @@ fn handle_commit_batch( } } - // Now we can process circuit changes - if let diff::CircuitDiffResult::CircuitsChanged { - newly_added, - removed_circuits, - updated_circuits, - } = circuit_change_mode - { - // Process removed circuits (including those that are being updated) - let mut circuits_to_remove = removed_circuits; - if !updated_circuits.is_empty() { - // For updates, we need to remove the old version first - for cmd in &updated_circuits { - if let BakeryCommands::AddCircuit { circuit_hash, .. } = cmd.as_ref() { - circuits_to_remove.push(*circuit_hash); - } - } - } + // Now we can process circuit changes incrementally + if let CircuitDiffResult::Categorized(categories) = circuit_change_mode { + // One-line summary of changes (info!) + info!( + "Bakery changes: sites_speed={}, circuits_added={}, removed={}, speed={}, ip={}", + site_speed_change_count, + categories.newly_added.len(), + categories.removed_circuits.len(), + categories.speed_changed.len(), + categories.ip_changed.len() + ); - // Removing circuits. - if !circuits_to_remove.is_empty() { - for circuit_hash in circuits_to_remove { + // 1) Removals + if !categories.removed_circuits.is_empty() { + for circuit_hash in categories.removed_circuits { if let Some(circuit) = circuits.remove(&circuit_hash) { let was_activated = live_circuits.contains_key(&circuit_hash); - - // Only generate removal commands if appropriate for the mode let commands = match config.queues.lazy_queues.as_ref() { + None | Some(LazyQueueMode::No) => circuit.to_prune(&config, true), + Some(LazyQueueMode::Htb) => { + if was_activated { circuit.to_prune(&config, false) } else { None } + } + Some(LazyQueueMode::Full) => { + if was_activated { circuit.to_prune(&config, true) } else { None } + } + }; + if let Some(cmd) = commands { execute_in_memory(&cmd, "removing circuit"); } + live_circuits.remove(&circuit_hash); + } else { + warn!("RemoveCircuit received for unknown circuit: {}", circuit_hash); + } + } + } + + // 2) Speed changes (avoid linux TC deadlock by removing qdisc first) + if !categories.speed_changed.is_empty() { + let mut commands = Vec::new(); + for cmd in &categories.speed_changed { + if let BakeryCommands::AddCircuit { circuit_hash, .. } = cmd.as_ref() { + let was_activated = live_circuits.contains_key(circuit_hash); + match config.queues.lazy_queues.as_ref() { None | Some(LazyQueueMode::No) => { - // Non-lazy: everything was created, delete everything - circuit.to_prune(&config, true) + // Remove both HTB and CAKE; then re-add fully + if let Some(prune) = cmd.to_prune(&config, true) { commands.extend(prune); } + if let Some(add) = cmd.to_commands(&config, ExecutionMode::Builder) { commands.extend(add); } + circuits.insert(*circuit_hash, Arc::clone(cmd)); } Some(LazyQueueMode::Htb) => { - // HTB mode: only delete CAKE if it was created if was_activated { - circuit.to_prune(&config, false) // This will only delete CAKE, not HTB + // Remove CAKE only + if let Some(prune) = cmd.to_prune(&config, false) { commands.extend(prune); } + // Update HTB with Builder (HTB only in Htb mode) + if let Some(add_htb) = cmd.to_commands(&config, ExecutionMode::Builder) { commands.extend(add_htb); } + // Re-add CAKE via LiveUpdate to minimize unshaped window + if let Some(add_qdisc) = cmd.to_commands(&config, ExecutionMode::LiveUpdate) { commands.extend(add_qdisc); } } else { - None // CAKE was never created, nothing to delete + // Not active: just ensure HTB state reflects new rates + if let Some(add_htb) = cmd.to_commands(&config, ExecutionMode::Builder) { commands.extend(add_htb); } } + circuits.insert(*circuit_hash, Arc::clone(cmd)); } Some(LazyQueueMode::Full) => { - // Full lazy: only delete the circuit if activated if was_activated { - circuit.to_prune(&config, true) + // Remove both, re-add in LiveUpdate (HTB + CAKE) + if let Some(prune) = cmd.to_prune(&config, true) { commands.extend(prune); } + if let Some(add_all) = cmd.to_commands(&config, ExecutionMode::LiveUpdate) { commands.extend(add_all); } } else { - None // Nothing was created, nothing to delete + // Not active: no TC state to touch; just record new definition } + circuits.insert(*circuit_hash, Arc::clone(cmd)); } - }; - - if let Some(cmd) = commands { - execute_in_memory(&cmd, "removing circuit"); } - live_circuits.remove(&circuit_hash); - } else { - warn!( - "RemoveCircuit received for unknown circuit: {}", - circuit_hash - ); - continue; } } + if !commands.is_empty() { + execute_in_memory(&commands, "updating circuit speeds"); + } } - // Newly added is a little harder - if !newly_added.is_empty() { - // Collect both newly added and updated circuits - let mut all_new_circuits: Vec<&Arc> = newly_added; - all_new_circuits.extend(updated_circuits); - let commands: Vec> = all_new_circuits + // 3) Additions + if !categories.newly_added.is_empty() { + let commands: Vec> = categories + .newly_added .iter() .filter_map(|c| c.to_commands(&config, ExecutionMode::Builder)) .flatten() .collect(); - if commands.is_empty() { - debug!("No commands to execute for newly added circuits."); - } else { + if !commands.is_empty() { execute_in_memory(&commands, "adding new circuits"); - // Update the circuit map with the newly added circuits - for command in all_new_circuits { - if let BakeryCommands::AddCircuit { circuit_hash, .. } = command.as_ref() { - circuits.insert(*circuit_hash, Arc::clone(command)); - } else { - warn!("AddCircuit received a non-circuit command: {:?}", command); - } + } + for command in categories.newly_added { + if let BakeryCommands::AddCircuit { circuit_hash, .. } = command.as_ref() { + circuits.insert(*circuit_hash, Arc::clone(command)); + } + } + } + + // 4) IP-only changes require no TC commands; mappings already handled by mapping engine + // We still refresh the stored circuit snapshot for those entries + if !categories.ip_changed.is_empty() { + for command in categories.ip_changed { + if let BakeryCommands::AddCircuit { circuit_hash, .. } = command.as_ref() { + circuits.insert(*circuit_hash, Arc::clone(command)); } } } diff --git a/src/rust/lqosd/src/main.rs b/src/rust/lqosd/src/main.rs index a3919369..9f5ffbc9 100644 --- a/src/rust/lqosd/src/main.rs +++ b/src/rust/lqosd/src/main.rs @@ -250,6 +250,21 @@ fn main() -> Result<()> { return; }; tokio_runtime.block_on(async { + // Notify bakery when the bus socket becomes available + tokio::spawn(async move { + use tokio::time::{sleep, Duration}; + // Wait up to ~5 seconds for the socket to appear + for _ in 0..100u32 { + if tokio::fs::metadata(lqos_bus::BUS_SOCKET_PATH).await.is_ok() { + break; + } + sleep(Duration::from_millis(50)).await; + } + if let Some(sender) = lqos_bakery::BAKERY_SENDER.get() { + let _ = sender.send(lqos_bakery::BakeryCommands::BusReady); + } + }); + tokio::spawn(async move { match lts2_sys::control_channel::start_control_channel(control_channel) .await -- knotmirror 0.0.1 From c1249bf4992d6ef892f4cb1e11c25fcc8c3eca0f Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Thu, 30 Oct 2025 13:58:56 -0500 Subject: [PATCH 03/11] Feat: Transactional circuit speed changes. Changing speed on a circuit is a 3-step process: create a temporary circuit, switch mappings to it. Remove the old circuit after a delay, and add in a replacement and switch mappings. After a final delay, remove the temporary circuit. This ensures that circuits remain shaped throughout the change process, and should minimize packet loss. --- src/rust/Cargo.lock | 1 + src/rust/lqos_bakery/Cargo.toml | 1 + src/rust/lqos_bakery/src/lib.rs | 430 ++++++++++++++++++++++++++++++-- 3 files changed, 410 insertions(+), 22 deletions(-) diff --git a/src/rust/Cargo.lock b/src/rust/Cargo.lock index d2a592a0..61cf32fd 100644 --- a/src/rust/Cargo.lock +++ b/src/rust/Cargo.lock @@ -1894,6 +1894,7 @@ dependencies = [ "crossbeam-channel", "lqos_bus", "lqos_config", + "lqos_sys", "once_cell", "parking_lot", "tokio", diff --git a/src/rust/lqos_bakery/Cargo.toml b/src/rust/lqos_bakery/Cargo.toml index fac885ae..74fb8abc 100644 --- a/src/rust/lqos_bakery/Cargo.toml +++ b/src/rust/lqos_bakery/Cargo.toml @@ -6,6 +6,7 @@ edition = "2024" [dependencies] lqos_config = { path = "../lqos_config" } lqos_bus = { path = "../lqos_bus" } +lqos_sys = { path = "../lqos_sys" } anyhow.workspace = true tracing.workspace = true crossbeam-channel.workspace = true diff --git a/src/rust/lqos_bakery/src/lib.rs b/src/rust/lqos_bakery/src/lib.rs index 3c9b7609..a995c320 100644 --- a/src/rust/lqos_bakery/src/lib.rs +++ b/src/rust/lqos_bakery/src/lib.rs @@ -40,6 +40,152 @@ use crate::utils::{execute_in_memory, write_command_file}; pub use commands::BakeryCommands; use lqos_config::{Config, LazyQueueMode}; use lqos_bus::{BusRequest, BusResponse, LibreqosBusClient, TcHandle}; +use lqos_sys; // direct mapping control for live-move to avoid bus full-sync side-effects + +// ---------------------- Live-Move Types and Helpers (module scope) ---------------------- + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum MigrationStage { + PrepareShadow, + SwapToShadow, + BuildFinal, + SwapToFinal, + TeardownShadow, + Done, +} + +#[derive(Clone, Debug)] +struct Migration { + circuit_hash: i64, + // Parent handles and majors + parent_class_id: TcHandle, + up_parent_class_id: TcHandle, + class_major: u16, + up_class_major: u16, + // Old and new rates + old_down_min: f32, + old_down_max: f32, + old_up_min: f32, + old_up_max: f32, + new_down_min: f32, + new_down_max: f32, + new_up_min: f32, + new_up_max: f32, + // Minors + old_minor: u16, + shadow_minor: u16, + final_minor: u16, + // IP list for remapping + ips: Vec, + stage: MigrationStage, +} + +fn parse_ip_list(s: &str) -> Vec { + s.split(',') + .map(|x| x.trim().to_string()) + .filter(|x| !x.is_empty()) + .collect() +} + +fn parse_ip_and_prefix(ip: &str) -> (String, u32) { + if let Some((addr, pfx)) = ip.split_once('/') { + if let Ok(n) = pfx.parse::() { + return (addr.to_string(), n); + } + } + if ip.contains(':') { (ip.to_string(), 128) } else { (ip.to_string(), 32) } +} + +fn tc_handle_from_major_minor(major: u16, minor: u16) -> TcHandle { + TcHandle::from_u32(((major as u32) << 16) | (minor as u32)) +} + +fn used_minors_for_parent( + circuits: &HashMap>, + parent: &TcHandle, +) -> HashSet { + let mut set = HashSet::new(); + for (_k, v) in circuits.iter() { + if let BakeryCommands::AddCircuit { + parent_class_id, + class_minor, + .. + } = v.as_ref() + { + if parent_class_id == parent { + set.insert(*class_minor); + } + } + } + set +} + +fn find_free_minor( + circuits: &HashMap>, + down_parent: &TcHandle, + up_parent: &TcHandle, +) -> Option { + let used_down = used_minors_for_parent(circuits, down_parent); + let used_up = used_minors_for_parent(circuits, up_parent); + for start in [0x2000u16, 0x4000, 0x6000, 0x8000, 0xA000, 0xC000, 0xE000] { + let end = start.saturating_add(0x1FFF); + for m in start..=end.min(0xFFFE) { + if !used_down.contains(&m) && !used_up.contains(&m) { + return Some(m); + } + } + } + for m in 1..=0xFFFEu16 { + if !used_down.contains(&m) && !used_up.contains(&m) { + return Some(m); + } + } + None +} + +fn add_commands_for_circuit( + cmd: &BakeryCommands, + config: &Arc, + mode: ExecutionMode, +) -> Option>> { + cmd.to_commands(config, mode) +} + +fn build_temp_add_cmd( + base: &BakeryCommands, + minor: u16, + down_min: f32, + down_max: f32, + up_min: f32, + up_max: f32, +) -> Option { + if let BakeryCommands::AddCircuit { + circuit_hash, + parent_class_id, + up_parent_class_id, + class_major, + up_class_major, + ip_addresses, + .. + } = base + { + Some(BakeryCommands::AddCircuit { + circuit_hash: *circuit_hash, + parent_class_id: *parent_class_id, + up_parent_class_id: *up_parent_class_id, + class_minor: minor, + download_bandwidth_min: down_min, + upload_bandwidth_min: up_min, + download_bandwidth_max: down_max, + upload_bandwidth_max: up_max, + class_major: *class_major, + up_class_major: *up_class_major, + ip_addresses: ip_addresses.clone(), + }) + } else { + None + } +} /// Count of Bakery-Managed circuits that are currently active. pub static ACTIVE_CIRCUITS: AtomicUsize = AtomicUsize::new(0); @@ -91,6 +237,9 @@ fn bakery_main(rx: Receiver, tx: Sender) { let mut mapping_unknown: HashSet = HashSet::new(); let mut mapping_seeded: bool = false; + let mut migrations: HashMap = HashMap::new(); + const MIGRATIONS_PER_TICK: usize = 16; + fn parse_ip_and_prefix(ip: &str) -> (String, u32) { if let Some((addr, pfx)) = ip.split_once('/') { if let Ok(n) = pfx.parse::() { @@ -336,6 +485,7 @@ fn bakery_main(rx: Receiver, tx: Sender) { &mut circuits, &mut live_circuits, &tx, + &mut migrations, ); } BakeryCommands::MqSetup { .. } => { @@ -359,6 +509,194 @@ fn bakery_main(rx: Receiver, tx: Sender) { BakeryCommands::Tick => { // Reset per-cycle counters at the start of the tick handle_tick(&mut circuits, &mut live_circuits, &mut sites); + + // Advance live-move migrations + let Ok(config) = lqos_config::load_config() else { + error!("Failed to load configuration, exiting Bakery thread."); + continue; + }; + let mut advanced = 0usize; + let mut to_remove = Vec::new(); + for (_hash, mig) in migrations.iter_mut() { + if advanced >= MIGRATIONS_PER_TICK { + break; + } + match mig.stage { + MigrationStage::PrepareShadow => { + // Create shadow HTB+CAKE with OLD rates + if let Some(temp) = build_temp_add_cmd( + &BakeryCommands::AddCircuit { + circuit_hash: mig.circuit_hash, + parent_class_id: mig.parent_class_id, + up_parent_class_id: mig.up_parent_class_id, + class_minor: mig.shadow_minor, + download_bandwidth_min: mig.old_down_min, + upload_bandwidth_min: mig.old_up_min, + download_bandwidth_max: mig.old_down_max, + upload_bandwidth_max: mig.old_up_max, + class_major: mig.class_major, + up_class_major: mig.up_class_major, + ip_addresses: "".to_string(), + }, + mig.shadow_minor, + mig.old_down_min, + mig.old_down_max, + mig.old_up_min, + mig.old_up_max, + ) { + let mut cmds = Vec::new(); + match config.queues.lazy_queues.as_ref() { + None | Some(LazyQueueMode::No) => { + if let Some(c) = add_commands_for_circuit(&temp, &config, ExecutionMode::Builder) { cmds.extend(c); } + } + Some(LazyQueueMode::Htb) => { + if let Some(c) = add_commands_for_circuit(&temp, &config, ExecutionMode::Builder) { cmds.extend(c); } + if let Some(c) = add_commands_for_circuit(&temp, &config, ExecutionMode::LiveUpdate) { cmds.extend(c); } + } + Some(LazyQueueMode::Full) => { + if let Some(c) = add_commands_for_circuit(&temp, &config, ExecutionMode::LiveUpdate) { cmds.extend(c); } + } + } + if !cmds.is_empty() { execute_in_memory(&cmds, "live-move: create shadow"); } + mig.stage = MigrationStage::SwapToShadow; + advanced += 1; + } else { + warn!("live-move: failed to build shadow add cmd for {}", mig.circuit_hash); + mig.stage = MigrationStage::Done; + advanced += 1; + } + } + MigrationStage::SwapToShadow => { + // Remap all IPs to shadow handles using existing CPU + for ip in &mig.ips { + let (ip_s, prefix) = parse_ip_and_prefix(ip); + for &upload in &[false, true] { + let key = MappingKey { ip: ip_s.clone(), prefix, upload }; + let cpu = mapping_current.get(&key).map(|v| v.cpu).unwrap_or(0); + let handle = if upload { + tc_handle_from_major_minor(mig.up_class_major, mig.shadow_minor) + } else { + tc_handle_from_major_minor(mig.class_major, mig.shadow_minor) + }; + let _ = lqos_sys::add_ip_to_tc(&ip_s, handle, cpu, upload); + // Update local mapping view + mapping_current.insert(key.clone(), MappingVal { handle, cpu }); + } + } + // Clear the hot cache directly + let _ = lqos_sys::clear_hot_cache(); + mig.stage = MigrationStage::BuildFinal; + advanced += 1; + } + MigrationStage::BuildFinal => { + // Delete old classes/qdiscs and create final with NEW rates at original minor + if let Some(old_cmd) = build_temp_add_cmd( + &BakeryCommands::AddCircuit { + circuit_hash: mig.circuit_hash, + parent_class_id: mig.parent_class_id, + up_parent_class_id: mig.up_parent_class_id, + class_minor: mig.old_minor, + download_bandwidth_min: mig.old_down_min, + upload_bandwidth_min: mig.old_up_min, + download_bandwidth_max: mig.old_down_max, + upload_bandwidth_max: mig.old_up_max, + class_major: mig.class_major, + up_class_major: mig.up_class_major, + ip_addresses: "".to_string(), + }, + mig.old_minor, + mig.old_down_min, + mig.old_down_max, + mig.old_up_min, + mig.old_up_max, + ) { + let mut cmds = Vec::new(); + if let Some(prune) = old_cmd.to_prune(&config, true) { cmds.extend(prune); } + // Final add (new rates) at final_minor + if let Some(final_cmd) = build_temp_add_cmd( + &old_cmd, + mig.final_minor, + mig.new_down_min, + mig.new_down_max, + mig.new_up_min, + mig.new_up_max, + ) { + match config.queues.lazy_queues.as_ref() { + None | Some(LazyQueueMode::No) => { + if let Some(c) = add_commands_for_circuit(&final_cmd, &config, ExecutionMode::Builder) { cmds.extend(c); } + } + Some(LazyQueueMode::Htb) => { + if let Some(c) = add_commands_for_circuit(&final_cmd, &config, ExecutionMode::Builder) { cmds.extend(c); } + if let Some(c) = add_commands_for_circuit(&final_cmd, &config, ExecutionMode::LiveUpdate) { cmds.extend(c); } + } + Some(LazyQueueMode::Full) => { + if let Some(c) = add_commands_for_circuit(&final_cmd, &config, ExecutionMode::LiveUpdate) { cmds.extend(c); } + } + } + } + if !cmds.is_empty() { execute_in_memory(&cmds, "live-move: build final"); } + mig.stage = MigrationStage::SwapToFinal; + advanced += 1; + } else { + warn!("live-move: failed to build old prune cmd for {}", mig.circuit_hash); + mig.stage = MigrationStage::Done; + advanced += 1; + } + } + MigrationStage::SwapToFinal => { + for ip in &mig.ips { + let (ip_s, prefix) = parse_ip_and_prefix(ip); + for &upload in &[false, true] { + let key = MappingKey { ip: ip_s.clone(), prefix, upload }; + let cpu = mapping_current.get(&key).map(|v| v.cpu).unwrap_or(0); + let handle = if upload { + tc_handle_from_major_minor(mig.up_class_major, mig.final_minor) + } else { + tc_handle_from_major_minor(mig.class_major, mig.final_minor) + }; + let _ = lqos_sys::add_ip_to_tc(&ip_s, handle, cpu, upload); + mapping_current.insert(key.clone(), MappingVal { handle, cpu }); + } + } + let _ = lqos_sys::clear_hot_cache(); + mig.stage = MigrationStage::TeardownShadow; + advanced += 1; + } + MigrationStage::TeardownShadow => { + // Remove shadow classes + if let Some(shadow_cmd) = build_temp_add_cmd( + &BakeryCommands::AddCircuit { + circuit_hash: mig.circuit_hash, + parent_class_id: mig.parent_class_id, + up_parent_class_id: mig.up_parent_class_id, + class_minor: mig.shadow_minor, + download_bandwidth_min: mig.old_down_min, + upload_bandwidth_min: mig.old_up_min, + download_bandwidth_max: mig.old_down_max, + upload_bandwidth_max: mig.old_up_max, + class_major: mig.class_major, + up_class_major: mig.up_class_major, + ip_addresses: "".to_string(), + }, + mig.shadow_minor, + mig.old_down_min, + mig.old_down_max, + mig.old_up_min, + mig.old_up_max, + ) { + if let Some(prune) = shadow_cmd.to_prune(&config, true) { + execute_in_memory(&prune, "live-move: prune shadow"); + } + } + mig.stage = MigrationStage::Done; + advanced += 1; + } + MigrationStage::Done => { + to_remove.push(mig.circuit_hash); + } + } + } + for h in to_remove { migrations.remove(&h); } } BakeryCommands::ChangeSiteSpeedLive { site_hash, @@ -436,6 +774,7 @@ fn handle_commit_batch( circuits: &mut HashMap>, live_circuits: &mut HashMap, tx: &Sender, + migrations: &mut HashMap, ) { let Ok(config) = lqos_config::load_config() else { error!("Failed to load configuration, exiting Bakery thread."); @@ -568,46 +907,93 @@ fn handle_commit_batch( // 2) Speed changes (avoid linux TC deadlock by removing qdisc first) if !categories.speed_changed.is_empty() { - let mut commands = Vec::new(); + let mut immediate_commands = Vec::new(); for cmd in &categories.speed_changed { - if let BakeryCommands::AddCircuit { circuit_hash, .. } = cmd.as_ref() { + if let BakeryCommands::AddCircuit { + circuit_hash, + parent_class_id, + up_parent_class_id, + class_minor, + download_bandwidth_min, + upload_bandwidth_min, + download_bandwidth_max, + upload_bandwidth_max, + class_major, + up_class_major, + ip_addresses, + } = cmd.as_ref() + { let was_activated = live_circuits.contains_key(circuit_hash); + if was_activated { + // Attempt live-move + if let Some(shadow_minor) = find_free_minor(circuits, parent_class_id, up_parent_class_id) { + // Find old command for old rates + if let Some(old_cmd) = circuits.get(circuit_hash) { + if let BakeryCommands::AddCircuit { + download_bandwidth_min: old_down_min, + upload_bandwidth_min: old_up_min, + download_bandwidth_max: old_down_max, + upload_bandwidth_max: old_up_max, + .. + } = old_cmd.as_ref() + { + let mig = Migration { + circuit_hash: *circuit_hash, + parent_class_id: *parent_class_id, + up_parent_class_id: *up_parent_class_id, + class_major: *class_major, + up_class_major: *up_class_major, + old_down_min: *old_down_min, + old_down_max: *old_down_max, + old_up_min: *old_up_min, + old_up_max: *old_up_max, + new_down_min: *download_bandwidth_min, + new_down_max: *download_bandwidth_max, + new_up_min: *upload_bandwidth_min, + new_up_max: *upload_bandwidth_max, + old_minor: *class_minor, + shadow_minor, + final_minor: *class_minor, + ips: parse_ip_list(ip_addresses), + stage: MigrationStage::PrepareShadow, + }; + migrations.insert(*circuit_hash, mig); + // Update desired circuit definition now + circuits.insert(*circuit_hash, Arc::clone(cmd)); + continue; // skip immediate path + } + } + } + } + // Fallback: immediate safe update match config.queues.lazy_queues.as_ref() { None | Some(LazyQueueMode::No) => { - // Remove both HTB and CAKE; then re-add fully - if let Some(prune) = cmd.to_prune(&config, true) { commands.extend(prune); } - if let Some(add) = cmd.to_commands(&config, ExecutionMode::Builder) { commands.extend(add); } - circuits.insert(*circuit_hash, Arc::clone(cmd)); + if let Some(prune) = cmd.to_prune(&config, true) { immediate_commands.extend(prune); } + if let Some(add) = cmd.to_commands(&config, ExecutionMode::Builder) { immediate_commands.extend(add); } } Some(LazyQueueMode::Htb) => { if was_activated { - // Remove CAKE only - if let Some(prune) = cmd.to_prune(&config, false) { commands.extend(prune); } - // Update HTB with Builder (HTB only in Htb mode) - if let Some(add_htb) = cmd.to_commands(&config, ExecutionMode::Builder) { commands.extend(add_htb); } - // Re-add CAKE via LiveUpdate to minimize unshaped window - if let Some(add_qdisc) = cmd.to_commands(&config, ExecutionMode::LiveUpdate) { commands.extend(add_qdisc); } + if let Some(prune) = cmd.to_prune(&config, false) { immediate_commands.extend(prune); } + if let Some(add_htb) = cmd.to_commands(&config, ExecutionMode::Builder) { immediate_commands.extend(add_htb); } + if let Some(add_qdisc) = cmd.to_commands(&config, ExecutionMode::LiveUpdate) { immediate_commands.extend(add_qdisc); } } else { - // Not active: just ensure HTB state reflects new rates - if let Some(add_htb) = cmd.to_commands(&config, ExecutionMode::Builder) { commands.extend(add_htb); } + if let Some(add_htb) = cmd.to_commands(&config, ExecutionMode::Builder) { immediate_commands.extend(add_htb); } } - circuits.insert(*circuit_hash, Arc::clone(cmd)); } Some(LazyQueueMode::Full) => { if was_activated { - // Remove both, re-add in LiveUpdate (HTB + CAKE) - if let Some(prune) = cmd.to_prune(&config, true) { commands.extend(prune); } - if let Some(add_all) = cmd.to_commands(&config, ExecutionMode::LiveUpdate) { commands.extend(add_all); } + if let Some(prune) = cmd.to_prune(&config, true) { immediate_commands.extend(prune); } + if let Some(add_all) = cmd.to_commands(&config, ExecutionMode::LiveUpdate) { immediate_commands.extend(add_all); } } else { - // Not active: no TC state to touch; just record new definition + // No TC ops } - circuits.insert(*circuit_hash, Arc::clone(cmd)); } } + circuits.insert(*circuit_hash, Arc::clone(cmd)); } } - if !commands.is_empty() { - execute_in_memory(&commands, "updating circuit speeds"); + if !immediate_commands.is_empty() { + execute_in_memory(&immediate_commands, "updating circuit speeds (fallback)"); } } -- knotmirror 0.0.1 From 5acf54fd78f7aef84efa0ca6e22559caa9b69c28 Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Thu, 30 Oct 2025 14:09:24 -0500 Subject: [PATCH 04/11] Feat: Improve the sorting handling to try to minimize structural (HTB tree) changes on reload. --- src/LibreQoS.py | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/src/LibreQoS.py b/src/LibreQoS.py index fa16bb6f..86b36092 100755 --- a/src/LibreQoS.py +++ b/src/LibreQoS.py @@ -755,7 +755,16 @@ def refreshShapers(): # - After processing all circuits for a node, we add CIRCUIT_PADDING to the minor counter # - This creates gaps that allow adding new circuits without affecting other ClassIDs # - Children are also sorted before recursive processing to ensure deterministic traversal - for node in sorted(data.keys()): + # For top-level binpacked keys (CpueQueueN), enforce numeric ordering of N + keys = list(data.keys()) + if depth == 0 and len(keys) > 0 and all(k.startswith("CpueQueue") for k in keys): + try: + keys.sort(key=lambda k: int(k.replace("CpueQueue", ""))) + except Exception: + keys = sorted(keys) + else: + keys = sorted(keys) + for node in keys: #if data[node]['type'] == "virtual": # print(node + " is a virtual node. Skipping.") # if depth == 0: @@ -903,6 +912,11 @@ def refreshShapers(): print("BinPacking is enabled, so we're going to sort your network.") cpuBin = {} weights = get_tree_weights() + # Stable tie-breaking: sort by (-weight, name) so equal weights have deterministic order + try: + weights = sorted(weights, key=lambda w: (-int(w.weight), str(w.name))) + except Exception: + pass for w in weights: cpuBin[w.name] = w.weight bins = binpacking.to_constant_bin_number(cpuBin, queuesAvailable) @@ -917,7 +931,8 @@ def refreshShapers(): 'type': 'site', 'downloadBandwidthMbpsMin': generated_pn_download_mbps(), 'uploadBandwidthMbpsMin': generated_pn_upload_mbps(), - 'children': {} + 'children': {}, + 'name': cpuKey } for node in network: found = False @@ -1009,7 +1024,7 @@ def refreshShapers(): case _: return sqm for node in sorted(data.keys()): - site_name = data[node]['name'] if 'name' in data[node] else "root" + site_name = data[node]['name'] if 'name' in data[node] else node bakery.add_site( site_name, data[node]['parentClassID'], -- knotmirror 0.0.1 From 725519e9dd723daa52a088089903c88eb789cf9e Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Thu, 30 Oct 2025 15:18:08 -0500 Subject: [PATCH 05/11] Chore: minor warning cleanup --- src/rust/lqos_bakery/src/diff/mod.rs | 2 +- src/rust/lqos_bakery/src/lib.rs | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/src/rust/lqos_bakery/src/diff/mod.rs b/src/rust/lqos_bakery/src/diff/mod.rs index 23120f73..020a029d 100644 --- a/src/rust/lqos_bakery/src/diff/mod.rs +++ b/src/rust/lqos_bakery/src/diff/mod.rs @@ -1,5 +1,5 @@ mod circuits; mod sites; -pub(crate) use circuits::{CircuitDiffCategories, CircuitDiffResult, diff_circuits}; +pub(crate) use circuits::{CircuitDiffResult, diff_circuits}; pub(crate) use sites::{SiteDiffResult, diff_sites}; diff --git a/src/rust/lqos_bakery/src/lib.rs b/src/rust/lqos_bakery/src/lib.rs index a995c320..be1294c1 100644 --- a/src/rust/lqos_bakery/src/lib.rs +++ b/src/rust/lqos_bakery/src/lib.rs @@ -87,14 +87,14 @@ fn parse_ip_list(s: &str) -> Vec { .collect() } -fn parse_ip_and_prefix(ip: &str) -> (String, u32) { +/*fn parse_ip_and_prefix(ip: &str) -> (String, u32) { if let Some((addr, pfx)) = ip.split_once('/') { if let Ok(n) = pfx.parse::() { return (addr.to_string(), n); } } if ip.contains(':') { (ip.to_string(), 128) } else { (ip.to_string(), 32) } -} +}*/ fn tc_handle_from_major_minor(major: u16, minor: u16) -> TcHandle { TcHandle::from_u32(((major as u32) << 16) | (minor as u32)) @@ -226,6 +226,7 @@ fn bakery_main(rx: Receiver, tx: Sender) { } #[derive(Clone, Debug)] struct MappingVal { + #[allow(dead_code)] handle: TcHandle, cpu: u32, } -- knotmirror 0.0.1 From 773ff589963c319ffb8a9074d08ad0b81d255759 Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Thu, 30 Oct 2025 16:42:08 -0500 Subject: [PATCH 06/11] Feat: Support adding sqm ("fq_codel" or "cake") as an extra column to ShapedDevices.csv, and the qdisc is built as intended. --- src/LibreQoS.py | 2686 +++++++++-------- src/ShapedDevices.example.csv | 24 +- src/rust/lqos_bakery/src/commands.rs | 36 +- src/rust/lqos_bakery/src/diff/circuits.rs | 5 +- src/rust/lqos_bakery/src/lib.rs | 9 + src/rust/lqos_bakery/src/queue_math.rs | 44 + src/rust/lqos_bus/src/bus/request.rs | 2 + .../lqos_config/src/shaped_devices/mod.rs | 3 + .../src/shaped_devices/shaped_device.rs | 32 +- src/rust/lqos_python/src/lib.rs | 5 + src/rust/lqosd/src/main.rs | 13 + 11 files changed, 1512 insertions(+), 1347 deletions(-) diff --git a/src/LibreQoS.py b/src/LibreQoS.py index 86b36092..69b16f9d 100755 --- a/src/LibreQoS.py +++ b/src/LibreQoS.py @@ -22,12 +22,12 @@ import binpacking from deepdiff import DeepDiff from liblqos_python import is_lqosd_alive, clear_ip_mappings, delete_ip_mapping, validate_shaped_devices, \ - is_libre_already_running, create_lock_file, free_lock_file, add_ip_mapping, BatchedCommands, \ - check_config, sqm, upstream_bandwidth_capacity_download_mbps, upstream_bandwidth_capacity_upload_mbps, \ - interface_a, interface_b, enable_actual_shell_commands, use_bin_packing_to_balance_cpu, monitor_mode_only, \ - run_shell_commands_as_sudo, generated_pn_download_mbps, generated_pn_upload_mbps, queues_available_override, \ - on_a_stick, get_tree_weights, get_weights, is_network_flat, get_libreqos_directory, enable_insight_topology, \ - Bakery + is_libre_already_running, create_lock_file, free_lock_file, add_ip_mapping, BatchedCommands, \ + check_config, sqm, upstream_bandwidth_capacity_download_mbps, upstream_bandwidth_capacity_upload_mbps, \ + interface_a, interface_b, enable_actual_shell_commands, use_bin_packing_to_balance_cpu, monitor_mode_only, \ + run_shell_commands_as_sudo, generated_pn_download_mbps, generated_pn_upload_mbps, queues_available_override, \ + on_a_stick, get_tree_weights, get_weights, is_network_flat, get_libreqos_directory, enable_insight_topology, \ + Bakery R2Q = 10 #MAX_R2Q = 200_000 @@ -39,1358 +39,1392 @@ MIN_QUANTUM = 1522 # Setting to 0 disables padding (not recommended for production) # Higher values provide more room for growth but reduce total capacity try: - from ispConfig import CIRCUIT_PADDING + from ispConfig import CIRCUIT_PADDING except ImportError: - CIRCUIT_PADDING = 8 # Default value if not configured + CIRCUIT_PADDING = 8 # Default value if not configured def get_shaped_devices_path(): - base_dir = get_libreqos_directory() + base_dir = get_libreqos_directory() - if enable_insight_topology(): - insight_path = os.path.join(base_dir, "ShapedDevices.insight.csv") - if os.path.exists(insight_path): - return insight_path + if enable_insight_topology(): + insight_path = os.path.join(base_dir, "ShapedDevices.insight.csv") + if os.path.exists(insight_path): + return insight_path - # Either insight not enabled, or file doesn't exist - return os.path.join(base_dir, "ShapedDevices.csv") + # Either insight not enabled, or file doesn't exist + return os.path.join(base_dir, "ShapedDevices.csv") def get_network_json_path(): - base_dir = get_libreqos_directory() + base_dir = get_libreqos_directory() - if enable_insight_topology(): - insight_path = os.path.join(base_dir, "network.insight.json") - if os.path.exists(insight_path): - return insight_path + if enable_insight_topology(): + insight_path = os.path.join(base_dir, "network.insight.json") + if os.path.exists(insight_path): + return insight_path - # Either insight not enabled, or file doesn't exist - return os.path.join(base_dir, "network.json") + # Either insight not enabled, or file doesn't exist + return os.path.join(base_dir, "network.json") def calculateR2q(maxRateInMbps): - # So we've learned that r2q defaults to 10, and is used to calculate quantum. Quantum is rateInBytes/r2q by - # default. This default gives errors at high rates, and tc clamps the quantum to 200000. Setting a high quantum - # directly gives no errors. So we want to calculate r2q to default to 10, but not exceed 200000 for the highest - # specified rate (which will be the available bandwidth rate). - maxRateInBytesPerSecond = maxRateInMbps * 125000 - r2q = 10 - quantum = maxRateInBytesPerSecond / r2q - while quantum > MAX_R2Q: - r2q += 1 - quantum = maxRateInBytesPerSecond / r2q - global R2Q - R2Q = r2q + # So we've learned that r2q defaults to 10, and is used to calculate quantum. Quantum is rateInBytes/r2q by + # default. This default gives errors at high rates, and tc clamps the quantum to 200000. Setting a high quantum + # directly gives no errors. So we want to calculate r2q to default to 10, but not exceed 200000 for the highest + # specified rate (which will be the available bandwidth rate). + maxRateInBytesPerSecond = maxRateInMbps * 125000 + r2q = 10 + quantum = maxRateInBytesPerSecond / r2q + while quantum > MAX_R2Q: + r2q += 1 + quantum = maxRateInBytesPerSecond / r2q + global R2Q + R2Q = r2q def quantum(rateInMbps): - # Attempt to calculate an appropriate quantum for an HTB queue, given - # that `mq` does not appear to carry a valid `r2q` value to individual - # root nodes. - rateInBytesPerSecond = rateInMbps * 125000 - quantum = max(MIN_QUANTUM, int(rateInBytesPerSecond / R2Q)) - #print("R2Q=" + str(R2Q) + ", quantum: " + str(quantum)) - quantrumString = " quantum " + str(quantum) - return quantrumString + # Attempt to calculate an appropriate quantum for an HTB queue, given + # that `mq` does not appear to carry a valid `r2q` value to individual + # root nodes. + rateInBytesPerSecond = rateInMbps * 125000 + quantum = max(MIN_QUANTUM, int(rateInBytesPerSecond / R2Q)) + #print("R2Q=" + str(R2Q) + ", quantum: " + str(quantum)) + quantrumString = " quantum " + str(quantum) + return quantrumString def format_rate_for_tc(rate_mbps): - """ - Format a rate in Mbps for TC commands with smart unit selection. - - Rates >= 1000 Mbps use 'gbit' - - Rates >= 1 Mbps use 'mbit' - - Rates < 1 Mbps use 'kbit' - """ - if rate_mbps >= 1000: - return f"{rate_mbps/1000:.1f}gbit" - elif rate_mbps >= 1: - return f"{rate_mbps:.1f}mbit" - else: - return f"{rate_mbps*1000:.0f}kbit" + """ + Format a rate in Mbps for TC commands with smart unit selection. + - Rates >= 1000 Mbps use 'gbit' + - Rates >= 1 Mbps use 'mbit' + - Rates < 1 Mbps use 'kbit' + """ + if rate_mbps >= 1000: + return f"{rate_mbps/1000:.1f}gbit" + elif rate_mbps >= 1: + return f"{rate_mbps:.1f}mbit" + else: + return f"{rate_mbps*1000:.0f}kbit" def shell(command): - if enable_actual_shell_commands(): - if run_shell_commands_as_sudo(): - command = 'sudo ' + command - logging.info(command) - commands = command.split(' ') - proc = subprocess.Popen(commands, stdout=subprocess.PIPE) - for line in io.TextIOWrapper(proc.stdout, encoding="utf-8"): # or another encoding - if logging.DEBUG <= logging.root.level: - print(line) - if ("RTNETLINK answers" in line) or ("We have an error talking to the kernel" in line): - warnings.warn("Command: '" + command + "' resulted in " + line, stacklevel=2) - else: - logging.info(command) + if enable_actual_shell_commands(): + if run_shell_commands_as_sudo(): + command = 'sudo ' + command + logging.info(command) + commands = command.split(' ') + proc = subprocess.Popen(commands, stdout=subprocess.PIPE) + for line in io.TextIOWrapper(proc.stdout, encoding="utf-8"): # or another encoding + if logging.DEBUG <= logging.root.level: + print(line) + if ("RTNETLINK answers" in line) or ("We have an error talking to the kernel" in line): + warnings.warn("Command: '" + command + "' resulted in " + line, stacklevel=2) + else: + logging.info(command) def shellReturn(command): - returnableString = '' - if enable_actual_shell_commands(): - commands = command.split(' ') - proc = subprocess.Popen(commands, stdout=subprocess.PIPE) - for line in io.TextIOWrapper(proc.stdout, encoding="utf-8"): # or another encoding - returnableString = returnableString + line + '\n' - return returnableString + returnableString = '' + if enable_actual_shell_commands(): + commands = command.split(' ') + proc = subprocess.Popen(commands, stdout=subprocess.PIPE) + for line in io.TextIOWrapper(proc.stdout, encoding="utf-8"): # or another encoding + returnableString = returnableString + line + '\n' + return returnableString def checkIfFirstRunSinceBoot(): - if os.path.isfile("lastRun.txt"): - with open("lastRun.txt", 'r') as file: - lastRun = datetime.strptime(file.read(), "%d-%b-%Y (%H:%M:%S.%f)") - systemRunningSince = datetime.fromtimestamp(psutil.boot_time()) - if systemRunningSince > lastRun: - print("First time run since system boot.") - return True - else: - print("Not first time run since system boot.") - return False - else: - print("First time run since system boot.") - return True - + if os.path.isfile("lastRun.txt"): + with open("lastRun.txt", 'r') as file: + lastRun = datetime.strptime(file.read(), "%d-%b-%Y (%H:%M:%S.%f)") + systemRunningSince = datetime.fromtimestamp(psutil.boot_time()) + if systemRunningSince > lastRun: + print("First time run since system boot.") + return True + else: + print("Not first time run since system boot.") + return False + else: + print("First time run since system boot.") + return True + def clearPriorSettings(interfaceA, interfaceB): - if enable_actual_shell_commands(): - if 'mq' in shellReturn('tc qdisc show dev ' + interfaceA + ' root'): - print('MQ detected. Will delete and recreate mq qdisc.') - # Clear tc filter - if on_a_stick() == True: - shell('tc qdisc delete dev ' + interfaceA + ' root') - else: - shell('tc qdisc delete dev ' + interfaceA + ' root') - shell('tc qdisc delete dev ' + interfaceB + ' root') - + if enable_actual_shell_commands(): + if 'mq' in shellReturn('tc qdisc show dev ' + interfaceA + ' root'): + print('MQ detected. Will delete and recreate mq qdisc.') + # Clear tc filter + if on_a_stick() == True: + shell('tc qdisc delete dev ' + interfaceA + ' root') + else: + shell('tc qdisc delete dev ' + interfaceA + ' root') + shell('tc qdisc delete dev ' + interfaceB + ' root') + def tearDown(interfaceA, interfaceB): - # Full teardown of everything for exiting LibreQoS - if enable_actual_shell_commands(): - # Clear IP filters and remove xdp program from interfaces - # The bakery tracks and prunes mappings; avoid clearing everything here. - clearPriorSettings(interfaceA, interfaceB) + # Full teardown of everything for exiting LibreQoS + if enable_actual_shell_commands(): + # Clear IP filters and remove xdp program from interfaces + # The bakery tracks and prunes mappings; avoid clearing everything here. + clearPriorSettings(interfaceA, interfaceB) def findQueuesAvailable(interfaceName): - # Find queues and CPU cores available. Use min between those two as queuesAvailable - if enable_actual_shell_commands(): - if queues_available_override() == 0: - queuesAvailable = 0 - path = '/sys/class/net/' + interfaceName + '/queues/' - directory_contents = os.listdir(path) - for item in directory_contents: - if "tx-" in str(item): - queuesAvailable += 1 - print(f"Interface {interfaceName} NIC queues:\t\t\t" + str(queuesAvailable)) - else: - queuesAvailable = queues_available_override() - print(f"Interface {interfaceName} NIC queues (Override):\t\t\t" + str(queuesAvailable)) - cpuCount = multiprocessing.cpu_count() - print("CPU cores:\t\t\t" + str(cpuCount)) - if queuesAvailable < 2: - raise SystemError(f'Only 1 NIC rx/tx queue available for interface {interfaceName}. You will need to use a NIC with 2 or more rx/tx queues available.') - if cpuCount < 2: - raise SystemError('Only 1 CPU core available. You will need to use a CPU with 2 or more CPU cores.') - queuesAvailable = min(queuesAvailable,cpuCount) - print(f"queuesAvailable for interface {interfaceName} set to:\t" + str(queuesAvailable)) - else: - print("As enableActualShellCommands is False, CPU core / queue count has been set to 16") - logging.info(f"Interface {interfaceName} NIC queues:\t\t\t" + str(16)) - cpuCount = multiprocessing.cpu_count() - logging.info("CPU cores:\t\t\t" + str(16)) - logging.info(f"queuesAvailable for interface {interfaceName} set to:\t" + str(16)) - queuesAvailable = 16 - return queuesAvailable + # Find queues and CPU cores available. Use min between those two as queuesAvailable + if enable_actual_shell_commands(): + if queues_available_override() == 0: + queuesAvailable = 0 + path = '/sys/class/net/' + interfaceName + '/queues/' + directory_contents = os.listdir(path) + for item in directory_contents: + if "tx-" in str(item): + queuesAvailable += 1 + print(f"Interface {interfaceName} NIC queues:\t\t\t" + str(queuesAvailable)) + else: + queuesAvailable = queues_available_override() + print(f"Interface {interfaceName} NIC queues (Override):\t\t\t" + str(queuesAvailable)) + cpuCount = multiprocessing.cpu_count() + print("CPU cores:\t\t\t" + str(cpuCount)) + if queuesAvailable < 2: + raise SystemError(f'Only 1 NIC rx/tx queue available for interface {interfaceName}. You will need to use a NIC with 2 or more rx/tx queues available.') + if cpuCount < 2: + raise SystemError('Only 1 CPU core available. You will need to use a CPU with 2 or more CPU cores.') + queuesAvailable = min(queuesAvailable,cpuCount) + print(f"queuesAvailable for interface {interfaceName} set to:\t" + str(queuesAvailable)) + else: + print("As enableActualShellCommands is False, CPU core / queue count has been set to 16") + logging.info(f"Interface {interfaceName} NIC queues:\t\t\t" + str(16)) + cpuCount = multiprocessing.cpu_count() + logging.info("CPU cores:\t\t\t" + str(16)) + logging.info(f"queuesAvailable for interface {interfaceName} set to:\t" + str(16)) + queuesAvailable = 16 + return queuesAvailable def validateNetworkAndDevices(): - # Verify Network.json is valid json - networkValidatedOrNot = True - # Verify ShapedDevices.csv is valid - devicesValidatedOrNot = True # True by default, switches to false if ANY entry in ShapedDevices.csv fails validation - - # Verify that the Rust side of things can read the CSV file - rustValid = validate_shaped_devices() - if rustValid == "OK": - print("Rust validated ShapedDevices.csv") - else: - warnings.warn("Rust failed to validate ShapedDevices.csv", stacklevel=2) - warnings.warn(rustValid, stacklevel=2) - devicesValidatedOrNot = False - with open(get_network_json_path()) as file: - try: - data = json.load(file) # put JSON-data to a variable - if data != {}: - #Traverse - observedNodes = {} # Will not be used later - def traverseToVerifyValidity(data): - for elem in data: - if isinstance(elem, str): - if (isinstance(data[elem], dict)) and (elem != 'children'): - if elem not in observedNodes: - observedNodes[elem] = {'downloadBandwidthMbps': data[elem]['uploadBandwidthMbps'], 'downloadBandwidthMbps': data[elem]['uploadBandwidthMbps']} - if 'children' in data[elem]: - traverseToVerifyValidity(data[elem]['children']) - else: - warnings.warn("Non-unique Node name in network.json: " + elem, stacklevel=2) - networkValidatedOrNot = False - traverseToVerifyValidity(data) - if len(observedNodes) < 1: - warnings.warn("network.json had 0 valid nodes. Only {} is accepted for that scenario.", stacklevel=2) - networkValidatedOrNot = False - except json.decoder.JSONDecodeError: - warnings.warn("network.json is an invalid JSON file", stacklevel=2) # in case json is invalid - networkValidatedOrNot = False - rowNum = 2 - - # Handle non-utf8 encoding in ShapedDevices.csv - with open(get_shaped_devices_path(), 'rb') as f: - raw_bytes = f.read() - - # Handle BOM if present - if raw_bytes.startswith(b'\xef\xbb\xbf'): # UTF-8 BOM - raw_bytes = raw_bytes[3:] - text_content = raw_bytes.decode('utf-8') - elif raw_bytes.startswith(b'\xff\xfe'): # UTF-16 LE BOM - text_content = raw_bytes.decode('utf-16') - elif raw_bytes.startswith(b'\xfe\xff'): # UTF-16 BE BOM - text_content = raw_bytes.decode('utf-16') - else: - # Try UTF-8 first - try: - text_content = raw_bytes.decode('utf-8') - except UnicodeDecodeError: - # Detect encoding - detected = chardet.detect(raw_bytes) - encoding = detected['encoding'] or 'utf-8' - text_content = raw_bytes.decode(encoding, errors='replace') - - # Create a StringIO object to mimic a file - # And read from the sanitized byte stream - with io.StringIO(text_content) as csv_file: - csv_reader = csv.reader(csv_file, delimiter=',') - #Remove comments if any - commentsRemoved = [] - for row in csv_reader: - if not row[0].startswith('#'): - commentsRemoved.append(row) - #Remove header - commentsRemoved.pop(0) - seenTheseIPsAlready = [] - for row in commentsRemoved: - circuitID, circuitName, deviceID, deviceName, ParentNode, mac, ipv4_input, ipv6_input, downloadMin, uploadMin, downloadMax, uploadMax, comment = row - # Must have circuitID, it's a unique identifier required for stateful changes to queue structure - if circuitID == '': - warnings.warn("No Circuit ID provided in ShapedDevices.csv at row " + str(rowNum), stacklevel=2) - devicesValidatedOrNot = False - # Each entry in ShapedDevices.csv can have multiple IPv4s or IPv6s separated by commas. Split them up and parse each to ensure valid - ipv4_subnets_and_hosts = [] - ipv6_subnets_and_hosts = [] - if ipv4_input != "": - try: - ipv4_input = ipv4_input.replace(' ','') - if "," in ipv4_input: - ipv4_list = ipv4_input.split(',') - else: - ipv4_list = [ipv4_input] - for ipEntry in ipv4_list: - if ipEntry in seenTheseIPsAlready: - warnings.warn("Provided IPv4 '" + ipEntry + "' in ShapedDevices.csv at row " + str(rowNum) + " is duplicate.", stacklevel=2) - #devicesValidatedOrNot = False - seenTheseIPsAlready.append(ipEntry) - else: - if (type(ipaddress.ip_network(ipEntry)) is ipaddress.IPv4Network) or (type(ipaddress.ip_address(ipEntry)) is ipaddress.IPv4Address): - ipv4_subnets_and_hosts.extend(ipEntry) - else: - warnings.warn("Provided IPv4 '" + ipEntry + "' in ShapedDevices.csv at row " + str(rowNum) + " is not valid.", stacklevel=2) - devicesValidatedOrNot = False - seenTheseIPsAlready.append(ipEntry) - except: - warnings.warn("Provided IPv4 '" + ipv4_input + "' in ShapedDevices.csv at row " + str(rowNum) + " is not valid.", stacklevel=2) - devicesValidatedOrNot = False - if ipv6_input != "": - try: - ipv6_input = ipv6_input.replace(' ','') - if "," in ipv6_input: - ipv6_list = ipv6_input.split(',') - else: - ipv6_list = [ipv6_input] - for ipEntry in ipv6_list: - if ipEntry in seenTheseIPsAlready: - warnings.warn("Provided IPv6 '" + ipEntry + "' in ShapedDevices.csv at row " + str(rowNum) + " is duplicate.", stacklevel=2) - devicesValidatedOrNot = False - seenTheseIPsAlready.append(ipEntry) - else: - if (type(ipaddress.ip_network(ipEntry)) is ipaddress.IPv6Network) or (type(ipaddress.ip_address(ipEntry)) is ipaddress.IPv6Address): - ipv6_subnets_and_hosts.extend(ipEntry) - else: - warnings.warn("Provided IPv6 '" + ipEntry + "' in ShapedDevices.csv at row " + str(rowNum) + " is not valid.", stacklevel=2) - devicesValidatedOrNot = False - seenTheseIPsAlready.append(ipEntry) - except: - warnings.warn("Provided IPv6 '" + ipv6_input + "' in ShapedDevices.csv at row " + str(rowNum) + " is not valid.", stacklevel=2) - devicesValidatedOrNot = False - try: - a = float(downloadMin) - if a < 0.1: - warnings.warn("Provided downloadMin '" + downloadMin + "' in ShapedDevices.csv at row " + str(rowNum) + " is < 0.1 Mbps.", stacklevel=2) - devicesValidatedOrNot = False - except: - warnings.warn("Provided downloadMin '" + downloadMin + "' in ShapedDevices.csv at row " + str(rowNum) + " is not a valid number.", stacklevel=2) - devicesValidatedOrNot = False - try: - a = float(uploadMin) - if a < 0.1: - warnings.warn("Provided uploadMin '" + uploadMin + "' in ShapedDevices.csv at row " + str(rowNum) + " is < 0.1 Mbps.", stacklevel=2) - devicesValidatedOrNot = False - except: - warnings.warn("Provided uploadMin '" + uploadMin + "' in ShapedDevices.csv at row " + str(rowNum) + " is not a valid number.", stacklevel=2) - devicesValidatedOrNot = False - try: - a = float(downloadMax) - if a < 0.1: - warnings.warn("Provided downloadMax '" + downloadMax + "' in ShapedDevices.csv at row " + str(rowNum) + " is < 0.2 Mbps.", stacklevel=2) - devicesValidatedOrNot = False - except: - warnings.warn("Provided downloadMax '" + downloadMax + "' in ShapedDevices.csv at row " + str(rowNum) + " is not a valid number.", stacklevel=2) - devicesValidatedOrNot = False - try: - a = float(uploadMax) - if a < 0.1: - warnings.warn("Provided uploadMax '" + uploadMax + "' in ShapedDevices.csv at row " + str(rowNum) + " is < 0.2 Mbps.", stacklevel=2) - devicesValidatedOrNot = False - except: - warnings.warn("Provided uploadMax '" + uploadMax + "' in ShapedDevices.csv at row " + str(rowNum) + " is not a valid number.", stacklevel=2) - devicesValidatedOrNot = False - - try: - if float(downloadMin) > float(downloadMax): - warnings.warn("Provided downloadMin '" + downloadMin + "' in ShapedDevices.csv at row " + str(rowNum) + " is greater than downloadMax", stacklevel=2) - devicesValidatedOrNot = False - if float(uploadMin) > float(uploadMax): - warnings.warn("Provided uploadMin '" + uploadMin + "' in ShapedDevices.csv at row " + str(rowNum) + " is greater than uploadMax", stacklevel=2) - devicesValidatedOrNot = False - except: - devicesValidatedOrNot = False - - rowNum += 1 - if devicesValidatedOrNot == True: - print("ShapedDevices.csv passed validation") - else: - print("ShapedDevices.csv failed validation") - if networkValidatedOrNot == True: - print("network.json passed validation") - else: - print("network.json failed validation") - if (devicesValidatedOrNot == True) and (networkValidatedOrNot == True): - return True - else: - return False + # Verify Network.json is valid json + networkValidatedOrNot = True + # Verify ShapedDevices.csv is valid + devicesValidatedOrNot = True # True by default, switches to false if ANY entry in ShapedDevices.csv fails validation + + # Verify that the Rust side of things can read the CSV file + rustValid = validate_shaped_devices() + if rustValid == "OK": + print("Rust validated ShapedDevices.csv") + else: + warnings.warn("Rust failed to validate ShapedDevices.csv", stacklevel=2) + warnings.warn(rustValid, stacklevel=2) + devicesValidatedOrNot = False + with open(get_network_json_path()) as file: + try: + data = json.load(file) # put JSON-data to a variable + if data != {}: + #Traverse + observedNodes = {} # Will not be used later + def traverseToVerifyValidity(data): + for elem in data: + if isinstance(elem, str): + if (isinstance(data[elem], dict)) and (elem != 'children'): + if elem not in observedNodes: + observedNodes[elem] = {'downloadBandwidthMbps': data[elem]['uploadBandwidthMbps'], 'downloadBandwidthMbps': data[elem]['uploadBandwidthMbps']} + if 'children' in data[elem]: + traverseToVerifyValidity(data[elem]['children']) + else: + warnings.warn("Non-unique Node name in network.json: " + elem, stacklevel=2) + networkValidatedOrNot = False + traverseToVerifyValidity(data) + if len(observedNodes) < 1: + warnings.warn("network.json had 0 valid nodes. Only {} is accepted for that scenario.", stacklevel=2) + networkValidatedOrNot = False + except json.decoder.JSONDecodeError: + warnings.warn("network.json is an invalid JSON file", stacklevel=2) # in case json is invalid + networkValidatedOrNot = False + rowNum = 2 + + # Handle non-utf8 encoding in ShapedDevices.csv + with open(get_shaped_devices_path(), 'rb') as f: + raw_bytes = f.read() + + # Handle BOM if present + if raw_bytes.startswith(b'\xef\xbb\xbf'): # UTF-8 BOM + raw_bytes = raw_bytes[3:] + text_content = raw_bytes.decode('utf-8') + elif raw_bytes.startswith(b'\xff\xfe'): # UTF-16 LE BOM + text_content = raw_bytes.decode('utf-16') + elif raw_bytes.startswith(b'\xfe\xff'): # UTF-16 BE BOM + text_content = raw_bytes.decode('utf-16') + else: + # Try UTF-8 first + try: + text_content = raw_bytes.decode('utf-8') + except UnicodeDecodeError: + # Detect encoding + detected = chardet.detect(raw_bytes) + encoding = detected['encoding'] or 'utf-8' + text_content = raw_bytes.decode(encoding, errors='replace') + + # Create a StringIO object to mimic a file + # And read from the sanitized byte stream + with io.StringIO(text_content) as csv_file: + csv_reader = csv.reader(csv_file, delimiter=',') + #Remove comments if any + commentsRemoved = [] + for row in csv_reader: + if not row[0].startswith('#'): + commentsRemoved.append(row) + #Remove header + commentsRemoved.pop(0) + seenTheseIPsAlready = [] + for row in commentsRemoved: + # Accept optional 14th column 'sqm' but ignore here (validation focuses on core fields) + circuitID, circuitName, deviceID, deviceName, ParentNode, mac, ipv4_input, ipv6_input, downloadMin, uploadMin, downloadMax, uploadMax, comment = row[0:13] + # Must have circuitID, it's a unique identifier required for stateful changes to queue structure + if circuitID == '': + warnings.warn("No Circuit ID provided in ShapedDevices.csv at row " + str(rowNum), stacklevel=2) + devicesValidatedOrNot = False + # Each entry in ShapedDevices.csv can have multiple IPv4s or IPv6s separated by commas. Split them up and parse each to ensure valid + ipv4_subnets_and_hosts = [] + ipv6_subnets_and_hosts = [] + if ipv4_input != "": + try: + ipv4_input = ipv4_input.replace(' ','') + if "," in ipv4_input: + ipv4_list = ipv4_input.split(',') + else: + ipv4_list = [ipv4_input] + for ipEntry in ipv4_list: + if ipEntry in seenTheseIPsAlready: + warnings.warn("Provided IPv4 '" + ipEntry + "' in ShapedDevices.csv at row " + str(rowNum) + " is duplicate.", stacklevel=2) + #devicesValidatedOrNot = False + seenTheseIPsAlready.append(ipEntry) + else: + if (type(ipaddress.ip_network(ipEntry)) is ipaddress.IPv4Network) or (type(ipaddress.ip_address(ipEntry)) is ipaddress.IPv4Address): + ipv4_subnets_and_hosts.extend(ipEntry) + else: + warnings.warn("Provided IPv4 '" + ipEntry + "' in ShapedDevices.csv at row " + str(rowNum) + " is not valid.", stacklevel=2) + devicesValidatedOrNot = False + seenTheseIPsAlready.append(ipEntry) + except: + warnings.warn("Provided IPv4 '" + ipv4_input + "' in ShapedDevices.csv at row " + str(rowNum) + " is not valid.", stacklevel=2) + devicesValidatedOrNot = False + if ipv6_input != "": + try: + ipv6_input = ipv6_input.replace(' ','') + if "," in ipv6_input: + ipv6_list = ipv6_input.split(',') + else: + ipv6_list = [ipv6_input] + for ipEntry in ipv6_list: + if ipEntry in seenTheseIPsAlready: + warnings.warn("Provided IPv6 '" + ipEntry + "' in ShapedDevices.csv at row " + str(rowNum) + " is duplicate.", stacklevel=2) + devicesValidatedOrNot = False + seenTheseIPsAlready.append(ipEntry) + else: + if (type(ipaddress.ip_network(ipEntry)) is ipaddress.IPv6Network) or (type(ipaddress.ip_address(ipEntry)) is ipaddress.IPv6Address): + ipv6_subnets_and_hosts.extend(ipEntry) + else: + warnings.warn("Provided IPv6 '" + ipEntry + "' in ShapedDevices.csv at row " + str(rowNum) + " is not valid.", stacklevel=2) + devicesValidatedOrNot = False + seenTheseIPsAlready.append(ipEntry) + except: + warnings.warn("Provided IPv6 '" + ipv6_input + "' in ShapedDevices.csv at row " + str(rowNum) + " is not valid.", stacklevel=2) + devicesValidatedOrNot = False + try: + a = float(downloadMin) + if a < 0.1: + warnings.warn("Provided downloadMin '" + downloadMin + "' in ShapedDevices.csv at row " + str(rowNum) + " is < 0.1 Mbps.", stacklevel=2) + devicesValidatedOrNot = False + except: + warnings.warn("Provided downloadMin '" + downloadMin + "' in ShapedDevices.csv at row " + str(rowNum) + " is not a valid number.", stacklevel=2) + devicesValidatedOrNot = False + try: + a = float(uploadMin) + if a < 0.1: + warnings.warn("Provided uploadMin '" + uploadMin + "' in ShapedDevices.csv at row " + str(rowNum) + " is < 0.1 Mbps.", stacklevel=2) + devicesValidatedOrNot = False + except: + warnings.warn("Provided uploadMin '" + uploadMin + "' in ShapedDevices.csv at row " + str(rowNum) + " is not a valid number.", stacklevel=2) + devicesValidatedOrNot = False + try: + a = float(downloadMax) + if a < 0.1: + warnings.warn("Provided downloadMax '" + downloadMax + "' in ShapedDevices.csv at row " + str(rowNum) + " is < 0.2 Mbps.", stacklevel=2) + devicesValidatedOrNot = False + except: + warnings.warn("Provided downloadMax '" + downloadMax + "' in ShapedDevices.csv at row " + str(rowNum) + " is not a valid number.", stacklevel=2) + devicesValidatedOrNot = False + try: + a = float(uploadMax) + if a < 0.1: + warnings.warn("Provided uploadMax '" + uploadMax + "' in ShapedDevices.csv at row " + str(rowNum) + " is < 0.2 Mbps.", stacklevel=2) + devicesValidatedOrNot = False + except: + warnings.warn("Provided uploadMax '" + uploadMax + "' in ShapedDevices.csv at row " + str(rowNum) + " is not a valid number.", stacklevel=2) + devicesValidatedOrNot = False + + try: + if float(downloadMin) > float(downloadMax): + warnings.warn("Provided downloadMin '" + downloadMin + "' in ShapedDevices.csv at row " + str(rowNum) + " is greater than downloadMax", stacklevel=2) + devicesValidatedOrNot = False + if float(uploadMin) > float(uploadMax): + warnings.warn("Provided uploadMin '" + uploadMin + "' in ShapedDevices.csv at row " + str(rowNum) + " is greater than uploadMax", stacklevel=2) + devicesValidatedOrNot = False + except: + devicesValidatedOrNot = False + + rowNum += 1 + if devicesValidatedOrNot == True: + print("ShapedDevices.csv passed validation") + else: + print("ShapedDevices.csv failed validation") + if networkValidatedOrNot == True: + print("network.json passed validation") + else: + print("network.json failed validation") + if (devicesValidatedOrNot == True) and (networkValidatedOrNot == True): + return True + else: + return False def loadSubscriberCircuits(shapedDevicesFile): - # Load Subscriber Circuits & Devices - subscriberCircuits = [] - knownCircuitIDs = [] - counterForCircuitsWithoutParentNodes = 0 - dictForCircuitsWithoutParentNodes = {} - with open(shapedDevicesFile) as csv_file: - csv_reader = csv.reader(csv_file, delimiter=',') - # Remove comments if any - commentsRemoved = [] - for row in csv_reader: - if not row[0].startswith('#'): - commentsRemoved.append(row) - # Remove header - commentsRemoved.pop(0) - for row in commentsRemoved: - circuitID, circuitName, deviceID, deviceName, ParentNode, mac, ipv4_input, ipv6_input, downloadMin, uploadMin, downloadMax, uploadMax, comment = row - # If in monitorOnlyMode, override bandwidth rates to where no shaping will actually occur - if monitor_mode_only() == True: - downloadMin = 10000 - uploadMin = 10000 - downloadMax = 10000 - uploadMax = 10000 - ipv4_subnets_and_hosts = [] - # Each entry in ShapedDevices.csv can have multiple IPv4s or IPv6s separated by commas. Split them up and parse each - if ipv4_input != "": - ipv4_input = ipv4_input.replace(' ','') - if "," in ipv4_input: - ipv4_list = ipv4_input.split(',') - else: - ipv4_list = [ipv4_input] - for ipEntry in ipv4_list: - ipv4_subnets_and_hosts.append(ipEntry) - ipv6_subnets_and_hosts = [] - if ipv6_input != "": - ipv6_input = ipv6_input.replace(' ','') - if "," in ipv6_input: - ipv6_list = ipv6_input.split(',') - else: - ipv6_list = [ipv6_input] - for ipEntry in ipv6_list: - ipv6_subnets_and_hosts.append(ipEntry) - # If there is something in the circuit ID field - if circuitID != "": - # Seen circuit before - if circuitID in knownCircuitIDs: - for circuit in subscriberCircuits: - if circuit['circuitID'] == circuitID: - if circuit['ParentNode'] != "none": - if circuit['ParentNode'] != ParentNode: - errorMessageString = "Device " + deviceName + " with deviceID " + deviceID + " had different Parent Node from other devices of circuit ID #" + circuitID - raise ValueError(errorMessageString) - # Check if bandwidth parameters match other cdevices of this same circuit ID, but only check if monitorOnlyMode is Off - if monitor_mode_only() == False: - if ((circuit['minDownload'] != float(downloadMin)) - or (circuit['minUpload'] != float(uploadMin)) - or (circuit['maxDownload'] != float(downloadMax)) - or (circuit['maxUpload'] != float(uploadMax))): - warnings.warn("Device " + deviceName + " with ID " + deviceID + " had different bandwidth parameters than other devices on this circuit. Will instead use the bandwidth parameters defined by the first device added to its circuit.", stacklevel=2) - devicesListForCircuit = circuit['devices'] - thisDevice = { - "deviceID": deviceID, - "deviceName": deviceName, - "mac": mac, - "ipv4s": ipv4_subnets_and_hosts, - "ipv6s": ipv6_subnets_and_hosts, - "comment": comment - } - devicesListForCircuit.append(thisDevice) - circuit['devices'] = devicesListForCircuit - # Have not seen circuit before - else: - knownCircuitIDs.append(circuitID) - if ParentNode == "": - ParentNode = "none" - #ParentNode = ParentNode.strip() - deviceListForCircuit = [] - thisDevice = { - "deviceID": deviceID, - "deviceName": deviceName, - "mac": mac, - "ipv4s": ipv4_subnets_and_hosts, - "ipv6s": ipv6_subnets_and_hosts, - "comment": comment - } - deviceListForCircuit.append(thisDevice) - thisCircuit = { - "circuitID": circuitID, - "circuitName": circuitName, - "ParentNode": ParentNode, - "devices": deviceListForCircuit, - "minDownload": float(downloadMin), - "minUpload": float(uploadMin), - "maxDownload": float(downloadMax), - "maxUpload": float(uploadMax), - "classid": '', - "comment": comment - } - if thisCircuit['ParentNode'] == 'none': - thisCircuit['idForCircuitsWithoutParentNodes'] = counterForCircuitsWithoutParentNodes - dictForCircuitsWithoutParentNodes[counterForCircuitsWithoutParentNodes] = ((float(downloadMax))+(float(uploadMax))) - counterForCircuitsWithoutParentNodes += 1 - subscriberCircuits.append(thisCircuit) - # If there is nothing in the circuit ID field - else: - # Copy deviceName to circuitName if none defined already - if circuitName == "": - circuitName = deviceName - if ParentNode == "": - ParentNode = "none" - #ParentNode = ParentNode.strip() - deviceListForCircuit = [] - thisDevice = { - "deviceID": deviceID, - "deviceName": deviceName, - "mac": mac, - "ipv4s": ipv4_subnets_and_hosts, - "ipv6s": ipv6_subnets_and_hosts, - } - deviceListForCircuit.append(thisDevice) - thisCircuit = { - "circuitID": circuitID, - "circuitName": circuitName, - "ParentNode": ParentNode, - "devices": deviceListForCircuit, - "minDownload": float(downloadMin), - "minUpload": float(uploadMin), - "maxDownload": float(downloadMax), - "maxUpload": float(uploadMax), - "classid": '', - "comment": comment - } - if thisCircuit['ParentNode'] == 'none': - thisCircuit['idForCircuitsWithoutParentNodes'] = counterForCircuitsWithoutParentNodes - dictForCircuitsWithoutParentNodes[counterForCircuitsWithoutParentNodes] = ((float(downloadMax))+(float(uploadMax))) - counterForCircuitsWithoutParentNodes += 1 - subscriberCircuits.append(thisCircuit) - return (subscriberCircuits, dictForCircuitsWithoutParentNodes) + # Load Subscriber Circuits & Devices + subscriberCircuits = [] + knownCircuitIDs = [] + counterForCircuitsWithoutParentNodes = 0 + dictForCircuitsWithoutParentNodes = {} + with open(shapedDevicesFile) as csv_file: + csv_reader = csv.reader(csv_file, delimiter=',') + # Remove comments if any + commentsRemoved = [] + for row in csv_reader: + if not row[0].startswith('#'): + commentsRemoved.append(row) + # Remove header + commentsRemoved.pop(0) + for row in commentsRemoved: + # Optional per-circuit SQM override in last column + sqm_override_token = '' + if len(row) > 13: + sqm_override_token = row[13].strip().lower() + circuitID, circuitName, deviceID, deviceName, ParentNode, mac, ipv4_input, ipv6_input, downloadMin, uploadMin, downloadMax, uploadMax, comment = row[0:13] + # If in monitorOnlyMode, override bandwidth rates to where no shaping will actually occur + if monitor_mode_only() == True: + downloadMin = 10000 + uploadMin = 10000 + downloadMax = 10000 + uploadMax = 10000 + ipv4_subnets_and_hosts = [] + # Each entry in ShapedDevices.csv can have multiple IPv4s or IPv6s separated by commas. Split them up and parse each + if ipv4_input != "": + ipv4_input = ipv4_input.replace(' ','') + if "," in ipv4_input: + ipv4_list = ipv4_input.split(',') + else: + ipv4_list = [ipv4_input] + for ipEntry in ipv4_list: + ipv4_subnets_and_hosts.append(ipEntry) + ipv6_subnets_and_hosts = [] + if ipv6_input != "": + ipv6_input = ipv6_input.replace(' ','') + if "," in ipv6_input: + ipv6_list = ipv6_input.split(',') + else: + ipv6_list = [ipv6_input] + for ipEntry in ipv6_list: + ipv6_subnets_and_hosts.append(ipEntry) + # If there is something in the circuit ID field + if circuitID != "": + # Seen circuit before + if circuitID in knownCircuitIDs: + for circuit in subscriberCircuits: + if circuit['circuitID'] == circuitID: + if circuit['ParentNode'] != "none": + if circuit['ParentNode'] != ParentNode: + errorMessageString = "Device " + deviceName + " with deviceID " + deviceID + " had different Parent Node from other devices of circuit ID #" + circuitID + raise ValueError(errorMessageString) + # Check if bandwidth parameters match other cdevices of this same circuit ID, but only check if monitorOnlyMode is Off + if monitor_mode_only() == False: + if ((circuit['minDownload'] != float(downloadMin)) + or (circuit['minUpload'] != float(uploadMin)) + or (circuit['maxDownload'] != float(downloadMax)) + or (circuit['maxUpload'] != float(uploadMax))): + warnings.warn("Device " + deviceName + " with ID " + deviceID + " had different bandwidth parameters than other devices on this circuit. Will instead use the bandwidth parameters defined by the first device added to its circuit.", stacklevel=2) + # If this row specifies an SQM override, but the circuit already has a different one, warn and keep the first. + if sqm_override_token != '': + if 'sqm' in circuit: + if circuit['sqm'] != sqm_override_token: + warnings.warn("Device " + deviceName + " with ID " + deviceID + " had different SQM override than other devices on this circuit. Will instead use the SQM defined by the first device added to its circuit.", stacklevel=2) + else: + circuit['sqm'] = sqm_override_token + devicesListForCircuit = circuit['devices'] + thisDevice = { + "deviceID": deviceID, + "deviceName": deviceName, + "mac": mac, + "ipv4s": ipv4_subnets_and_hosts, + "ipv6s": ipv6_subnets_and_hosts, + "comment": comment + } + devicesListForCircuit.append(thisDevice) + circuit['devices'] = devicesListForCircuit + # Have not seen circuit before + else: + knownCircuitIDs.append(circuitID) + if ParentNode == "": + ParentNode = "none" + #ParentNode = ParentNode.strip() + deviceListForCircuit = [] + thisDevice = { + "deviceID": deviceID, + "deviceName": deviceName, + "mac": mac, + "ipv4s": ipv4_subnets_and_hosts, + "ipv6s": ipv6_subnets_and_hosts, + "comment": comment + } + deviceListForCircuit.append(thisDevice) + thisCircuit = { + "circuitID": circuitID, + "circuitName": circuitName, + "ParentNode": ParentNode, + "devices": deviceListForCircuit, + "minDownload": float(downloadMin), + "minUpload": float(uploadMin), + "maxDownload": float(downloadMax), + "maxUpload": float(uploadMax), + "classid": '', + "comment": comment + } + if sqm_override_token != '': + thisCircuit['sqm'] = sqm_override_token + if thisCircuit['ParentNode'] == 'none': + thisCircuit['idForCircuitsWithoutParentNodes'] = counterForCircuitsWithoutParentNodes + dictForCircuitsWithoutParentNodes[counterForCircuitsWithoutParentNodes] = ((float(downloadMax))+(float(uploadMax))) + counterForCircuitsWithoutParentNodes += 1 + subscriberCircuits.append(thisCircuit) + # If there is nothing in the circuit ID field + else: + # Copy deviceName to circuitName if none defined already + if circuitName == "": + circuitName = deviceName + if ParentNode == "": + ParentNode = "none" + #ParentNode = ParentNode.strip() + deviceListForCircuit = [] + thisDevice = { + "deviceID": deviceID, + "deviceName": deviceName, + "mac": mac, + "ipv4s": ipv4_subnets_and_hosts, + "ipv6s": ipv6_subnets_and_hosts, + } + deviceListForCircuit.append(thisDevice) + thisCircuit = { + "circuitID": circuitID, + "circuitName": circuitName, + "ParentNode": ParentNode, + "devices": deviceListForCircuit, + "minDownload": float(downloadMin), + "minUpload": float(uploadMin), + "maxDownload": float(downloadMax), + "maxUpload": float(uploadMax), + "classid": '', + "comment": comment + } + if sqm_override_token != '': + thisCircuit['sqm'] = sqm_override_token + if thisCircuit['ParentNode'] == 'none': + thisCircuit['idForCircuitsWithoutParentNodes'] = counterForCircuitsWithoutParentNodes + dictForCircuitsWithoutParentNodes[counterForCircuitsWithoutParentNodes] = ((float(downloadMax))+(float(uploadMax))) + counterForCircuitsWithoutParentNodes += 1 + subscriberCircuits.append(thisCircuit) + return (subscriberCircuits, dictForCircuitsWithoutParentNodes) def refreshShapers(): - - # Starting - print("refreshShapers starting at " + datetime.now().strftime("%d/%m/%Y %H:%M:%S")) - # Create a single batch of xdp update commands to execute together - ipMapBatch = BatchedCommands() - - # Warn user if enableActualShellCommands is False, because that would mean no actual commands are executing - if enable_actual_shell_commands() == False: - warnings.warn("enableActualShellCommands is set to False. None of the commands below will actually be executed. Simulated run.", stacklevel=2) - # Warn user if monitorOnlyMode is True, because that would mean no actual shaping is happening - if monitor_mode_only() == True: - warnings.warn("monitorOnlyMode is set to True. Shaping will not occur.", stacklevel=2) - - - # Check if first run since boot - isThisFirstRunSinceBoot = checkIfFirstRunSinceBoot() - - - # Files - shapedDevicesFile = get_shaped_devices_path() - networkJSONfile = get_network_json_path() - - - # Check validation - safeToRunRefresh = False - print("Validating input files '" + shapedDevicesFile + "' and '" + networkJSONfile + "'") - if (validateNetworkAndDevices() == True): - shutil.copyfile('ShapedDevices.csv', 'lastGoodConfig.csv') - shutil.copyfile('network.json', 'lastGoodConfig.json') - print("Backed up good config as lastGoodConfig.csv and lastGoodConfig.json") - safeToRunRefresh = True - else: - if (isThisFirstRunSinceBoot == False): - warnings.warn("Validation failed. Because this is not the first run since boot (queues already set up) - will now exit.", stacklevel=2) - safeToRunRefresh = False - else: - warnings.warn("Validation failed. However - because this is the first run since boot - will load queues from last good config", stacklevel=2) - shapedDevicesFile = 'lastGoodConfig.csv' - networkJSONfile = 'lastGoodConfig.json' - safeToRunRefresh = True - - if safeToRunRefresh == True: - - # Load Subscriber Circuits & Devices - subscriberCircuits, dictForCircuitsWithoutParentNodes = loadSubscriberCircuits(shapedDevicesFile) - - - # Load network hierarchy - with open(networkJSONfile, 'r') as j: - network = json.loads(j.read()) - - - # Pull rx/tx queues / CPU cores available - # Handling the case when the number of queues for interfaces are different - InterfaceAQueuesAvailable = findQueuesAvailable(interface_a()) - InterfaceBQueuesAvailable = findQueuesAvailable(interface_b()) - queuesAvailable = min(InterfaceAQueuesAvailable, InterfaceBQueuesAvailable) - stickOffset = 0 - if on_a_stick(): - print("On-a-stick override dividing queues") - # The idea here is that download use queues 0 - n/2, upload uses the other half - queuesAvailable = math.floor(queuesAvailable / 2) - stickOffset = queuesAvailable - - # If in monitorOnlyMode, override network.json bandwidth rates to where no shaping will actually occur - if monitor_mode_only() == True: - def overrideNetworkBandwidths(data): - for elem in data: - if 'children' in data[elem]: - overrideNetworkBandwidths(data[elem]['children']) - data[elem]['downloadBandwidthMbpsMin'] = 100000 - data[elem]['uploadBandwidthMbpsMin'] = 100000 - overrideNetworkBandwidths(network) - - # Generate Parent Nodes. Spread ShapedDevices.csv which lack defined ParentNode across these (balance across CPUs) - print("Generating parent nodes") - generatedPNs = [] - numberOfGeneratedPNs = queuesAvailable - # If in monitorOnlyMode, override bandwidth rates to where no shaping will actually occur - if monitor_mode_only() == True: - chosenDownloadMbps = 10000 - chosenUploadMbps = 10000 - else: - chosenDownloadMbps = generated_pn_download_mbps() - chosenUploadMbps = generated_pn_upload_mbps() - for x in range(numberOfGeneratedPNs): - genPNname = "Generated_PN_" + str(x+1) - network[genPNname] = { - "downloadBandwidthMbps": chosenDownloadMbps, - "uploadBandwidthMbps": chosenUploadMbps - } - generatedPNs.append(genPNname) - if use_bin_packing_to_balance_cpu(): - print("Using binpacking module to sort circuits by CPU core") - weights = get_weights() - if weights is not None and dictForCircuitsWithoutParentNodes is not None: - for circuitId in dictForCircuitsWithoutParentNodes: - for circuit in subscriberCircuits: - if 'idForCircuitsWithoutParentNodes' in circuit and circuit['idForCircuitsWithoutParentNodes'] == circuitId: - for w in weights: - if w.circuit_id == circuit['circuitID']: - dictForCircuitsWithoutParentNodes[circuitId] = w.weight - bins = binpacking.to_constant_bin_number(dictForCircuitsWithoutParentNodes, numberOfGeneratedPNs) - genPNcounter = 0 - for binItem in bins: - sumItem = 0 - logging.info(generatedPNs[genPNcounter] + " will contain " + str(len(binItem)) + " circuits") - for key in binItem.keys(): - for circuit in subscriberCircuits: - if circuit['ParentNode'] == 'none': - if circuit['idForCircuitsWithoutParentNodes'] == key: - circuit['ParentNode'] = generatedPNs[genPNcounter] - genPNcounter += 1 - if genPNcounter >= queuesAvailable: - genPNcounter = 0 - print("Finished binpacking") - else: - genPNcounter = 0 - for circuit in subscriberCircuits: - if circuit['ParentNode'] == 'none': - circuit['ParentNode'] = generatedPNs[genPNcounter] - genPNcounter += 1 - if genPNcounter >= queuesAvailable: - genPNcounter = 0 - print("Generated parent nodes created") - - # Find the bandwidth minimums for each node by combining mimimums of devices lower in that node's hierarchy - def findBandwidthMins(data, depth): - tabs = ' ' * depth - minDownload = 0 - minUpload = 0 - for elem in data: - for circuit in subscriberCircuits: - if elem == circuit['ParentNode']: - minDownload += circuit['minDownload'] - minUpload += circuit['minUpload'] - if 'children' in data[elem]: - minDL, minUL = findBandwidthMins(data[elem]['children'], depth+1) - minDownload += minDL - minUpload += minUL - if 'downloadBandwidthMbpsMin' in data[elem]: - data[elem]['downloadBandwidthMbpsMin'] = max(data[elem]['downloadBandwidthMbpsMin'], minDownload) - else: - data[elem]['downloadBandwidthMbpsMin'] = max(data[elem]['downloadBandwidthMbps'], minUpload) - if 'uploadBandwidthMbpsMin' in data[elem]: - data[elem]['uploadBandwidthMbpsMin'] = max(data[elem]['uploadBandwidthMbpsMin'], minUpload) - else: - data[elem]['uploadBandwidthMbpsMin'] = max(data[elem]['uploadBandwidthMbps'], minUpload) - return minDownload, minUpload - logging.info("Finding the bandwidth minimums for each node") - minDownload, minUpload = findBandwidthMins(network, 0) - logging.info("Found the bandwidth minimums for each node") - - # Child nodes inherit bandwidth maximums of parents. We apply this here to avoid bugs when compression is applied with flattenA(). - def inheritBandwidthMaxes(data, parentMaxDL, parentMaxUL, parentMinDL, parentMinUL): - for node in data: - if isinstance(node, str): - if (isinstance(data[node], dict)) and (node != 'children'): - # Cap based on this node's max bandwidth, or parent node's max bandwidth, whichever is lower - data[node]['downloadBandwidthMbps'] = min(int(data[node]['downloadBandwidthMbps']),int(parentMaxDL)) - data[node]['uploadBandwidthMbps'] = min(int(data[node]['uploadBandwidthMbps']),int(parentMaxUL)) - data[node]['downloadBandwidthMbpsMin'] = min(int(data[node]['downloadBandwidthMbpsMin']),int(data[node]['downloadBandwidthMbps']),int(parentMinDL)) - data[node]['uploadBandwidthMbpsMin'] = min(int(data[node]['uploadBandwidthMbpsMin']),int(data[node]['uploadBandwidthMbps']),int(parentMinUL)) - # Recursive call this function for children nodes attached to this node - if 'children' in data[node]: - # We need to keep tabs on the minor counter, because we can't have repeating class IDs. Here, we bring back the minor counter from the recursive function - inheritBandwidthMaxes(data[node]['children'], data[node]['downloadBandwidthMbps'], data[node]['uploadBandwidthMbps'], data[node]['downloadBandwidthMbpsMin'], data[node]['uploadBandwidthMbpsMin']) - #return data - # Here is the actual call to the recursive function - inheritBandwidthMaxes(network, parentMaxDL=upstream_bandwidth_capacity_download_mbps(), parentMaxUL=upstream_bandwidth_capacity_upload_mbps(), parentMinDL=upstream_bandwidth_capacity_download_mbps(), parentMinUL=upstream_bandwidth_capacity_upload_mbps()) - - # Compress network.json. HTB only supports 8 levels of HTB depth. Compress to 8 layers if beyond 8. - def flattenB(data): - newDict = {} - for node in data: - if isinstance(node, str): - if (isinstance(data[node], dict)) and (node != 'children'): - newDict[node] = dict(data[node]) - if 'children' in data[node]: - result = flattenB(data[node]['children']) - del newDict[node]['children'] - newDict.update(result) - return newDict - def flattenA(data, depth): - newDict = {} - for node in data: - if isinstance(node, str): - if (isinstance(data[node], dict)) and (node != 'children'): - newDict[node] = dict(data[node]) - if 'children' in data[node]: - result = flattenA(data[node]['children'], depth+2) - del newDict[node]['children'] - if depth <= 8: - newDict[node]['children'] = result - else: - flattened = flattenB(data[node]['children']) - if 'children' in newDict[node]: - newDict[node]['children'].update(flattened) - else: - newDict[node]['children'] = flattened - return newDict - network = flattenA(network, 1) - - # Group circuits by parent node. Reduces runtime for section below this one. - circuits_by_parent_node = {} - circuit_min_down_combined_by_parent_node = {} - circuit_min_up_combined_by_parent_node = {} - for circuit in subscriberCircuits: - #If a device from ShapedDevices.csv lists this node as its Parent Node, attach it as a leaf to this node HTB - if circuit['ParentNode'] not in circuits_by_parent_node: - circuits_by_parent_node[circuit['ParentNode']] = [] - temp = circuits_by_parent_node[circuit['ParentNode']] - temp.append(circuit) - circuits_by_parent_node[circuit['ParentNode']] = temp - if circuit['ParentNode'] not in circuit_min_down_combined_by_parent_node: - circuit_min_down_combined_by_parent_node[circuit['ParentNode']] = 0 - circuit_min_down_combined_by_parent_node[circuit['ParentNode']] += circuit['minDownload'] - if circuit['ParentNode'] not in circuit_min_up_combined_by_parent_node: - circuit_min_up_combined_by_parent_node[circuit['ParentNode']] = 0 - circuit_min_up_combined_by_parent_node[circuit['ParentNode']] += circuit['minUpload'] - - # Parse network structure and add devices from ShapedDevices.csv - print("Parsing network structure and tallying devices") - parentNodes = [] - minorByCPUpreloaded = {} - knownClassIDs = [] - nodes_requiring_min_squashing = {} - # Track minor counter by CPU. This way we can have > 32000 hosts (htb has u16 limit to minor handle) - # Minor numbers start at 3 to reserve 1 for root qdisc and 2 for default class - # With CIRCUIT_PADDING, we leave gaps between nodes to allow future circuit additions - # without disrupting existing ClassID assignments. This maintains stability across reloads. - for x in range(queuesAvailable): - minorByCPUpreloaded[x+1] = 3 - def traverseNetwork(data, depth, major, minorByCPU, queue, parentClassID, upParentClassID, parentMaxDL, parentMaxUL, parentMinDL, parentMinUL): - # ClassID Assignment Strategy: - # - Nodes and circuits are processed in alphabetical order for stability - # - Each node gets a unique minor number that increments sequentially - # - After processing all circuits for a node, we add CIRCUIT_PADDING to the minor counter - # - This creates gaps that allow adding new circuits without affecting other ClassIDs - # - Children are also sorted before recursive processing to ensure deterministic traversal - # For top-level binpacked keys (CpueQueueN), enforce numeric ordering of N - keys = list(data.keys()) - if depth == 0 and len(keys) > 0 and all(k.startswith("CpueQueue") for k in keys): - try: - keys.sort(key=lambda k: int(k.replace("CpueQueue", ""))) - except Exception: - keys = sorted(keys) - else: - keys = sorted(keys) - for node in keys: - #if data[node]['type'] == "virtual": - # print(node + " is a virtual node. Skipping.") - # if depth == 0: - # parentClassID = hex(major) + ':' - # upParentClassID = hex(major+stickOffset) + ':' - # data[node]['parentClassID'] = parentClassID - # data[node]['up_parentClassID'] = upParentClassID - # data[node]['classMajor'] = hex(major) - # data[node]['up_classMajor'] = hex(major + stickOffset) - # data[node]['classMinor'] = hex(minorByCPU[queue]) - # data[node]['cpuNum'] = hex(queue-1) - # data[node]['up_cpuNum'] = hex(queue-1+stickOffset) - # traverseNetwork(data[node]['children'], depth, major, minorByCPU, queue, parentClassID, upParentClassID, parentMaxDL, parentMaxUL) - # continue - circuitsForThisNetworkNode = [] - nodeClassID = hex(major) + ':' + hex(minorByCPU[queue]) - upNodeClassID = hex(major+stickOffset) + ':' + hex(minorByCPU[queue]) - data[node]['classid'] = nodeClassID - data[node]['up_classid'] = upNodeClassID - if depth == 0: - parentClassID = hex(major) + ':' - upParentClassID = hex(major+stickOffset) + ':' - data[node]['parentClassID'] = parentClassID - data[node]['up_parentClassID'] = upParentClassID - # If in monitorOnlyMode, override bandwidth rates to where no shaping will actually occur - if monitor_mode_only() == True: - data[node]['downloadBandwidthMbps'] = 100000 - data[node]['uploadBandwidthMbps'] = 100000 - data[node]['downloadBandwidthMbpsMin'] = 100000 - data[node]['uploadBandwidthMbpsMin'] = 100000 - # If not in monitorOnlyMode - else: - # Cap based on this node's max bandwidth, or parent node's max bandwidth, whichever is lower - data[node]['downloadBandwidthMbps'] = min(data[node]['downloadBandwidthMbps'],parentMaxDL) - data[node]['uploadBandwidthMbps'] = min(data[node]['uploadBandwidthMbps'],parentMaxUL) - data[node]['downloadBandwidthMbpsMin'] = min(data[node]['downloadBandwidthMbpsMin'], data[node]['downloadBandwidthMbps'], parentMinDL) - data[node]['uploadBandwidthMbpsMin'] = min(data[node]['uploadBandwidthMbpsMin'], data[node]['uploadBandwidthMbps'], parentMinUL) - # Calculations are done in findBandwidthMins() to determine optimal HTB rates (mins) and ceils (maxs) - data[node]['classMajor'] = hex(major) - data[node]['up_classMajor'] = hex(major + stickOffset) - data[node]['classMinor'] = hex(minorByCPU[queue]) - data[node]['cpuNum'] = hex(queue-1) - data[node]['up_cpuNum'] = hex(queue-1+stickOffset) - thisParentNode = { - "parentNodeName": node, - "classID": nodeClassID, - "maxDownload": data[node]['downloadBandwidthMbps'], - "maxUpload": data[node]['uploadBandwidthMbps'], - } - parentNodes.append(thisParentNode) - minorByCPU[queue] = minorByCPU[queue] + 1 - # Check for overflow - TC uses u16 for minor class ID (max 65535) - if minorByCPU[queue] > 0xFFFF: - logging.error(f"Minor class ID overflow on CPU {queue}: {minorByCPU[queue]} exceeds TC's u16 limit (65535). Consider increasing queue count or restructuring network hierarchy.") - raise ValueError(f"Minor class ID overflow on CPU {queue}: {minorByCPU[queue]} exceeds limit of 65535") - # If a device from ShapedDevices.csv lists this node as its Parent Node, attach it as a leaf to this node HTB - if node in circuits_by_parent_node: - # If mins of circuits combined exceed min of parent node - set to 1 - override_min_down = None - override_min_up = None - if monitor_mode_only() == False: - if (circuit_min_down_combined_by_parent_node[node] > data[node]['downloadBandwidthMbpsMin']) or (circuit_min_up_combined_by_parent_node[node] > data[node]['uploadBandwidthMbpsMin']): - override_min_down = 1 - override_min_up = 1 - logging.info("The combined minimums of circuits in Parent Node [" + node + "] exceeded that of the parent node. Reducing these circuits' minimums to 1 now.", stacklevel=2) - if ((override_min_down * len(circuits_by_parent_node[node])) > data[node]['downloadBandwidthMbpsMin']) or ((override_min_up * len(circuits_by_parent_node[node])) > data[node]['uploadBandwidthMbpsMin']): - logging.info("Even with this change, minimums will exceed the min rate of the parent node. Using 10 kbps as the minimum for these circuits instead.", stacklevel=2) - nodes_requiring_min_squashing[node] = True - # Sort circuits by name for stable ordering - sorted_circuits = sorted(circuits_by_parent_node[node], - key=lambda c: c.get('circuitName', c.get('circuitID', ''))) - for circuit in sorted_circuits: - if node == circuit['ParentNode']: - if monitor_mode_only() == False: - if circuit['maxDownload'] > data[node]['downloadBandwidthMbps']: - logging.info("downloadMax of Circuit ID [" + circuit['circuitID'] + "] exceeded that of its parent node. Reducing to that of its parent node now.", stacklevel=2) - if circuit['maxUpload'] > data[node]['uploadBandwidthMbps']: - logging.info("uploadMax of Circuit ID [" + circuit['circuitID'] + "] exceeded that of its parent node. Reducing to that of its parent node now.", stacklevel=2) - parentString = hex(major) + ':' - flowIDstring = hex(major) + ':' + hex(minorByCPU[queue]) - upFlowIDstring = hex(major + stickOffset) + ':' + hex(minorByCPU[queue]) - circuit['classid'] = flowIDstring - circuit['up_classid'] = upFlowIDstring - logging.info("Added up_classid to circuit: " + circuit['up_classid']) - # Create circuit dictionary to be added to network structure, eventually output as queuingStructure.json - maxDownload = min(circuit['maxDownload'],data[node]['downloadBandwidthMbps']) - maxUpload = min(circuit['maxUpload'],data[node]['uploadBandwidthMbps']) - if override_min_down: - circuit['minDownload'] = 1 - if override_min_up: - circuit['minUpload'] = 1 - minDownload = min(circuit['minDownload'],maxDownload) - minUpload = min(circuit['minUpload'],maxUpload) - thisNewCircuitItemForNetwork = { - 'maxDownload' : maxDownload, - 'maxUpload' : maxUpload, - 'minDownload' : minDownload, - 'minUpload' : minUpload, - "circuitID": circuit['circuitID'], - "circuitName": circuit['circuitName'], - "ParentNode": circuit['ParentNode'], - "devices": circuit['devices'], - "classid": flowIDstring, - "up_classid" : upFlowIDstring, - "classMajor": hex(major), - "up_classMajor" : hex(major + stickOffset), - "classMinor": hex(minorByCPU[queue]), - "comment": circuit['comment'] - } - # Generate TC commands to be executed later - thisNewCircuitItemForNetwork['devices'] = circuit['devices'] - circuitsForThisNetworkNode.append(thisNewCircuitItemForNetwork) - minorByCPU[queue] = minorByCPU[queue] + 1 - if len(circuitsForThisNetworkNode) > 0: - data[node]['circuits'] = circuitsForThisNetworkNode - - # Add padding for future circuit additions (applies to all nodes) - # This ensures space is reserved even for nodes without circuits - minorByCPU[queue] = minorByCPU[queue] + CIRCUIT_PADDING - - # Recursive call this function for children nodes attached to this node - if 'children' in data[node]: - # Sort children to ensure consistent traversal order - sorted_children = dict(sorted(data[node]['children'].items())) - # We need to keep tabs on the minor counter, because we can't have repeating class IDs. Here, we bring back the minor counter from the recursive function - minorByCPU[queue] = minorByCPU[queue] + 1 - # Check for overflow - TC uses u16 for minor class ID (max 65535) - if minorByCPU[queue] > 0xFFFF: - logging.error(f"Minor class ID overflow on CPU {queue}: {minorByCPU[queue]} exceeds TC's u16 limit (65535). Consider increasing queue count or restructuring network hierarchy.") - raise ValueError(f"Minor class ID overflow on CPU {queue}: {minorByCPU[queue]} exceeds limit of 65535") - minorByCPU = traverseNetwork(sorted_children, depth+1, major, minorByCPU, queue, nodeClassID, upNodeClassID, data[node]['downloadBandwidthMbps'], data[node]['uploadBandwidthMbps'], data[node]['downloadBandwidthMbpsMin'], data[node]['uploadBandwidthMbpsMin']) - # If top level node, increment to next queue / cpu core - if depth == 0: - if queue >= queuesAvailable: - queue = 1 - major = queue - else: - queue += 1 - major += 1 - return minorByCPU - - # If we're in binpacking mode, we need to sort the network structure a bit - bins = [] - if use_bin_packing_to_balance_cpu() and not is_network_flat(): - print("BinPacking is enabled, so we're going to sort your network.") - cpuBin = {} - weights = get_tree_weights() - # Stable tie-breaking: sort by (-weight, name) so equal weights have deterministic order - try: - weights = sorted(weights, key=lambda w: (-int(w.weight), str(w.name))) - except Exception: - pass - for w in weights: - cpuBin[w.name] = w.weight - bins = binpacking.to_constant_bin_number(cpuBin, queuesAvailable) - for x in range(queuesAvailable): - print("Bin " + str(x) + " = ", bins[x]) - binnedNetwork = {} - for cpu in range(queuesAvailable): - cpuKey = "CpueQueue" + str(cpu) - binnedNetwork[cpuKey] = { - 'downloadBandwidthMbps': generated_pn_download_mbps(), - 'uploadBandwidthMbps': generated_pn_upload_mbps(), - 'type': 'site', - 'downloadBandwidthMbpsMin': generated_pn_download_mbps(), - 'uploadBandwidthMbpsMin': generated_pn_upload_mbps(), - 'children': {}, - 'name': cpuKey - } - for node in network: - found = False - for bin in range(queuesAvailable): - if node in bins[bin]: - binnedNetwork["CpueQueue" + str(bin)]['children'][node] = network[node] - found = True - if found == False: - newQueueId = queuesAvailable-1 - binnedNetwork["CpueQueue" + str(newQueueId)]['children'][node] = network[node] - network = binnedNetwork - - # Here is the actual call to the recursive traverseNetwork() function. finalMinor is not used. - minorByCPU = traverseNetwork(network, 0, major=1, minorByCPU=minorByCPUpreloaded, queue=1, parentClassID=None, upParentClassID=None, parentMaxDL=upstream_bandwidth_capacity_download_mbps(), parentMaxUL=upstream_bandwidth_capacity_upload_mbps(), parentMinDL=upstream_bandwidth_capacity_download_mbps(), parentMinUL=upstream_bandwidth_capacity_upload_mbps()) - - bakery = Bakery() - bakery.start_batch() # Initializes the bakery transaction - linuxTCcommands = [] - devicesShaped = [] - # Root HTB Setup - # Create MQ qdisc for each CPU core / rx-tx queue. Generate commands to create corresponding HTB and leaf classes. Prepare commands for execution later - thisInterface = interface_a() - logging.info("# MQ Setup for " + thisInterface) - command = 'qdisc replace dev ' + thisInterface + ' root handle 7FFF: mq' - bakery.setup_mq(queuesAvailable, stickOffset) - linuxTCcommands.append(command) - maxBandwidth = max(upstream_bandwidth_capacity_upload_mbps(), upstream_bandwidth_capacity_download_mbps()) - calculateR2q(maxBandwidth) - for queue in range(queuesAvailable): - command = 'qdisc add dev ' + thisInterface + ' parent 7FFF:' + hex(queue+1) + ' handle ' + hex(queue+1) + ': htb default 2' - linuxTCcommands.append(command) - command = 'class add dev ' + thisInterface + ' parent ' + hex(queue+1) + ': classid ' + hex(queue+1) + ':1 htb rate '+ format_rate_for_tc(upstream_bandwidth_capacity_download_mbps()) + ' ceil ' + format_rate_for_tc(upstream_bandwidth_capacity_download_mbps()) + quantum(upstream_bandwidth_capacity_download_mbps()) - linuxTCcommands.append(command) - command = 'qdisc add dev ' + thisInterface + ' parent ' + hex(queue+1) + ':1 ' + sqm() - linuxTCcommands.append(command) - # Default class - traffic gets passed through this limiter with lower priority if it enters the top HTB without a specific class. - # Technically, that should not even happen. So don't expect much if any traffic in this default class. - # Only 1/4 of defaultClassCapacity is guaranteed (to prevent hitting ceiling of upstream), for the most part it serves as an "up to" ceiling. - command = 'class add dev ' + thisInterface + ' parent ' + hex(queue+1) + ':1 classid ' + hex(queue+1) + ':2 htb rate ' + format_rate_for_tc(round((upstream_bandwidth_capacity_download_mbps()-1)/4)) + ' ceil ' + format_rate_for_tc(upstream_bandwidth_capacity_download_mbps()-1) + ' prio 5' + quantum(upstream_bandwidth_capacity_download_mbps()) - linuxTCcommands.append(command) - command = 'qdisc add dev ' + thisInterface + ' parent ' + hex(queue+1) + ':2 ' + sqm() - linuxTCcommands.append(command) - - # Note the use of stickOffset, and not replacing the root queue if we're on a stick - thisInterface = interface_b() - logging.info("# MQ Setup for " + thisInterface) - if not on_a_stick(): - command = 'qdisc replace dev ' + thisInterface + ' root handle 7FFF: mq' - linuxTCcommands.append(command) - for queue in range(queuesAvailable): - command = 'qdisc add dev ' + thisInterface + ' parent 7FFF:' + hex(queue+stickOffset+1) + ' handle ' + hex(queue+stickOffset+1) + ': htb default 2' - linuxTCcommands.append(command) - command = 'class add dev ' + thisInterface + ' parent ' + hex(queue+stickOffset+1) + ': classid ' + hex(queue+stickOffset+1) + ':1 htb rate '+ format_rate_for_tc(upstream_bandwidth_capacity_upload_mbps()) + ' ceil ' + format_rate_for_tc(upstream_bandwidth_capacity_upload_mbps()) + quantum(upstream_bandwidth_capacity_upload_mbps()) - linuxTCcommands.append(command) - command = 'qdisc add dev ' + thisInterface + ' parent ' + hex(queue+stickOffset+1) + ':1 ' + sqm() - linuxTCcommands.append(command) - # Default class - traffic gets passed through this limiter with lower priority if it enters the top HTB without a specific class. - # Technically, that should not even happen. So don't expect much if any traffic in this default class. - # Only 1/4 of defaultClassCapacity is guarenteed (to prevent hitting ceiling of upstream), for the most part it serves as an "up to" ceiling. - command = 'class add dev ' + thisInterface + ' parent ' + hex(queue+stickOffset+1) + ':1 classid ' + hex(queue+stickOffset+1) + ':2 htb rate ' + format_rate_for_tc(round((upstream_bandwidth_capacity_upload_mbps()-1)/4)) + ' ceil ' + format_rate_for_tc(upstream_bandwidth_capacity_upload_mbps()-1) + ' prio 5' + quantum(upstream_bandwidth_capacity_upload_mbps()) - linuxTCcommands.append(command) - command = 'qdisc add dev ' + thisInterface + ' parent ' + hex(queue+stickOffset+1) + ':2 ' + sqm() - linuxTCcommands.append(command) - - - # Parse network structure. For each tier, generate commands to create corresponding HTB and leaf classes. Prepare commands for execution later - # Define lists for hash filters - print("Preparing TC commands") - def traverseNetwork(data): - - # Cake needs help handling rates lower than 5 Mbps - def sqmFixupRate(rate:int, sqm:str) -> str: - # If we aren't using cake, just return the sqm string - if not sqm.startswith("cake") or "rtt" in sqm: - return sqm - - # If we are using cake, we need to fixup the rate - # Based on: 1 MTU is 1500 bytes, or 12,000 bits. - # At 1 Mbps, (1,000 bits per ms) transmitting an MTU takes 12ms. Add 3ms for overhead, and we get 15ms. - # So 15ms divided by 5 (for 1%) multiplied by 100 yields 300ms. - # The same formula gives 180ms at 2Mbps - # 140ms at 3Mbps - # 120ms at 4Mbps - match rate: - case 1: return sqm + " rtt 300" - case 2: return sqm + " rtt 180" - case 3: return sqm + " rtt 140" - case 4: return sqm + " rtt 120" - case _: return sqm - - for node in sorted(data.keys()): - site_name = data[node]['name'] if 'name' in data[node] else node - bakery.add_site( - site_name, - data[node]['parentClassID'], - data[node]['up_parentClassID'], - int(data[node]['classMinor'], 16), - data[node]['downloadBandwidthMbpsMin'], - data[node]['uploadBandwidthMbpsMin'], - data[node]['downloadBandwidthMbps'], - data[node]['uploadBandwidthMbps'], - ) - command = 'class add dev ' + interface_a() + ' parent ' + data[node]['parentClassID'] + ' classid ' + data[node]['classMinor'] + ' htb rate '+ format_rate_for_tc(data[node]['downloadBandwidthMbpsMin']) + ' ceil '+ format_rate_for_tc(data[node]['downloadBandwidthMbps']) + ' prio 3' + quantum(data[node]['downloadBandwidthMbps']) - linuxTCcommands.append(command) - logging.info("Up ParentClassID: " + data[node]['up_parentClassID']) - logging.info("ClassMinor: " + data[node]['classMinor']) - command = 'class add dev ' + interface_b() + ' parent ' + data[node]['up_parentClassID'] + ' classid ' + data[node]['classMinor'] + ' htb rate '+ format_rate_for_tc(data[node]['uploadBandwidthMbpsMin']) + ' ceil '+ format_rate_for_tc(data[node]['uploadBandwidthMbps']) + ' prio 3' + quantum(data[node]['uploadBandwidthMbps']) - linuxTCcommands.append(command) - if 'circuits' in data[node]: - # Sort circuits by name for stable ordering - sorted_circuits = sorted(data[node]['circuits'], - key=lambda c: c.get('circuitName', c.get('circuitID', ''))) - for circuit in sorted_circuits: - # If circuit mins exceed node mins - handle low min rates of 1 to mean 10 kbps. - # Avoid changing minDownload or minUpload because they are used in queuingStructure.json, and must remain integers. - min_down = circuit['minDownload'] - min_up = circuit['minUpload'] - if node in nodes_requiring_min_squashing: - if min_down == 1: - min_down = 0.01 - if min_up == 1: - min_up = 0.01 - # Generate TC commands to be executed later - tcComment = " # CircuitID: " + circuit['circuitID'] + " DeviceIDs: " - for device in circuit['devices']: - tcComment = '' #tcComment + device['deviceID'] + ', ' - if 'devices' in circuit: - if 'comment' in circuit['devices'][0]: - tcComment = '' # tcComment + '| Comment: ' + circuit['devices'][0]['comment'] - tcComment = tcComment.replace("\n", "") - circuit_name = circuit['circuitID'] if 'circuitID' in circuit else "unknown" - # Collect all IP addresses for this circuit - ip_list = [] - for device in circuit['devices']: - if device['ipv4s']: - ip_list.extend(device['ipv4s']) - if device['ipv6s']: - ip_list.extend(device['ipv6s']) - # Concatenate IPs with comma separator - ip_addresses_str = ','.join(ip_list) - - bakery.add_circuit( - circuit_name, - data[node]['classid'], - data[node]['up_classid'], - int(circuit['classMinor'], 16), - min_down, - min_up, - circuit['maxDownload'], - circuit['maxUpload'], - int(circuit['classMajor'], 16), - int(circuit['up_classMajor'], 16), - ip_addresses_str, - ) - command = 'class add dev ' + interface_a() + ' parent ' + data[node]['classid'] + ' classid ' + circuit['classMinor'] + ' htb rate '+ format_rate_for_tc(min_down) + ' ceil '+ format_rate_for_tc(circuit['maxDownload']) + ' prio 3' + quantum(circuit['maxDownload']) + tcComment - linuxTCcommands.append(command) - # Only add CAKE / fq_codel qdisc if monitorOnlyMode is Off - if monitor_mode_only() == False: - # SQM Fixup for lower rates - useSqm = sqmFixupRate(circuit['maxDownload'], sqm()) - command = 'qdisc add dev ' + interface_a() + ' parent ' + circuit['classMajor'] + ':' + circuit['classMinor'] + ' ' + useSqm - linuxTCcommands.append(command) - command = 'class add dev ' + interface_b() + ' parent ' + data[node]['up_classid'] + ' classid ' + circuit['classMinor'] + ' htb rate '+ format_rate_for_tc(min_up) + ' ceil '+ format_rate_for_tc(circuit['maxUpload']) + ' prio 3' + quantum(circuit['maxUpload']) - linuxTCcommands.append(command) - # Only add CAKE / fq_codel qdisc if monitorOnlyMode is Off - if monitor_mode_only() == False: - # SQM Fixup for lower rates - useSqm = sqmFixupRate(circuit['maxUpload'], sqm()) - command = 'qdisc add dev ' + interface_b() + ' parent ' + circuit['up_classMajor'] + ':' + circuit['classMinor'] + ' ' + useSqm - linuxTCcommands.append(command) - pass - for device in circuit['devices']: - if device['ipv4s']: - for ipv4 in device['ipv4s']: - ipMapBatch.add_ip_mapping(str(ipv4), circuit['classid'], data[node]['cpuNum'], False) - #xdpCPUmapCommands.append('./bin/xdp_iphash_to_cpu_cmdline add --ip ' + str(ipv4) + ' --cpu ' + data[node]['cpuNum'] + ' --classid ' + circuit['classid']) - if on_a_stick(): - ipMapBatch.add_ip_mapping(str(ipv4), circuit['up_classid'], data[node]['up_cpuNum'], True) - #xdpCPUmapCommands.append('./bin/xdp_iphash_to_cpu_cmdline add --ip ' + str(ipv4) + ' --cpu ' + data[node]['up_cpuNum'] + ' --classid ' + circuit['up_classid'] + ' --upload 1') - if device['ipv6s']: - for ipv6 in device['ipv6s']: - ipMapBatch.add_ip_mapping(str(ipv6), circuit['classid'], data[node]['cpuNum'], False) - #xdpCPUmapCommands.append('./bin/xdp_iphash_to_cpu_cmdline add --ip ' + str(ipv6) + ' --cpu ' + data[node]['cpuNum'] + ' --classid ' + circuit['classid']) - if on_a_stick(): - ipMapBatch.add_ip_mapping(str(ipv6), circuit['up_classid'], data[node]['up_cpuNum'], True) - #xdpCPUmapCommands.append('./bin/xdp_iphash_to_cpu_cmdline add --ip ' + str(ipv6) + ' --cpu ' + data[node]['up_cpuNum'] + ' --classid ' + circuit['up_classid'] + ' --upload 1') - if device['deviceName'] not in devicesShaped: - devicesShaped.append(device['deviceName']) - # Recursive call this function for children nodes attached to this node - if 'children' in data[node]: - # Sort children to ensure consistent traversal order - sorted_children = dict(sorted(data[node]['children'].items())) - traverseNetwork(sorted_children) - # Here is the actual call to the recursive traverseNetwork() function. - traverseNetwork(network) - - # Save queuingStructure - queuingStructure = {} - queuingStructure['Network'] = network - queuingStructure['lastUsedClassIDCounterByCPU'] = minorByCPU - queuingStructure['generatedPNs'] = generatedPNs - with open('queuingStructure.json', 'w') as infile: - json.dump(queuingStructure, infile, indent=4) - - - # Record start time of actual filter reload - reloadStartTime = datetime.now() - - - # Clear Prior Settings - # We don't want to do this every time, with lqosd managing queues statefully. - # clearPriorSettings(interface_a(), interface_b()) - - - # Setup XDP and disable XPS regardless of whether it is first run or not (necessary to handle cases where systemctl stop was used) - xdpStartTime = datetime.now() - #if enable_actual_shell_commands(): - # The bakery will handle stale mapping cleanup; avoid clearing mappings here. - # Set up XDP-CPUMAP-TC - logging.info("# XDP Setup") - # Commented out - the daemon does this - #shell('./cpumap-pping/bin/xps_setup.sh -d ' + interfaceA + ' --default --disable') - #shell('./cpumap-pping/bin/xps_setup.sh -d ' + interfaceB + ' --default --disable') - #shell('./cpumap-pping/src/xdp_iphash_to_cpu --dev ' + interfaceA + ' --lan') - #shell('./cpumap-pping/src/xdp_iphash_to_cpu --dev ' + interfaceB + ' --wan') - #shell('./cpumap-pping/src/tc_classify --dev-egress ' + interfaceA) - #shell('./cpumap-pping/src/tc_classify --dev-egress ' + interfaceB) - xdpEndTime = datetime.now() - - - # Execute actual Linux TC commands - tcStartTime = datetime.now() - # print("Executing linux TC class/qdisc commands") - with open('linux_tc.txt', 'w') as f: - for command in linuxTCcommands: - logging.info(command) - f.write(f"{command}\n") - # if logging.DEBUG <= logging.root.level: - # # Do not --force in debug mode, so we can see any errors - # shell("/sbin/tc -b linux_tc.txt") - # else: - # shell("/sbin/tc -f -b linux_tc.txt") - bakery.commit() - tcEndTime = datetime.now() - # print("Executed " + str(len(linuxTCcommands)) + " linux TC class/qdisc commands") - - # Execute actual XDP-CPUMAP-TC filter commands - xdpFilterStartTime = datetime.now() - print("Executing XDP-CPUMAP-TC IP filter commands") - numXdpCommands = ipMapBatch.length() - if enable_actual_shell_commands(): - ipMapBatch.finish_ip_mappings() - ipMapBatch.submit() - #for command in xdpCPUmapCommands: - # logging.info(command) - # commands = command.split(' ') - # proc = subprocess.Popen(commands, stdout=subprocess.DEVNULL) - else: - ipMapBatch.log() - #for command in xdpCPUmapCommands: - # logging.info(command) - print("Executed " + str(numXdpCommands) + " XDP-CPUMAP-TC IP filter commands") - #print(xdpCPUmapCommands) - xdpFilterEndTime = datetime.now() - - - # Record end time of all reload commands - reloadEndTime = datetime.now() - - - # Recap - warn operator if devices were skipped - devicesSkipped = [] - for circuit in subscriberCircuits: - for device in circuit['devices']: - if device['deviceName'] not in devicesShaped: - devicesSkipped.append((device['deviceName'],device['deviceID'])) - if len(devicesSkipped) > 0: - warnings.warn('Some devices were not shaped. Please check to ensure they have a valid ParentNode listed in ShapedDevices.csv:', stacklevel=2) - print("Devices not shaped:") - for entry in devicesSkipped: - name, idNum = entry - print('DeviceID: ' + idNum + '\t DeviceName: ' + name) - - # Save ShapedDevices.csv as ShapedDevices.lastLoaded.csv - shutil.copyfile('ShapedDevices.csv', 'ShapedDevices.lastLoaded.csv') - - # Save for stats - with open('statsByCircuit.json', 'w') as f: - f.write(json.dumps(subscriberCircuits, indent=4)) - with open('statsByParentNode.json', 'w') as f: - f.write(json.dumps(parentNodes, indent=4)) - - - # Record time this run completed at - # filename = os.path.join(_here, 'lastRun.txt') - with open("lastRun.txt", 'w') as file: - file.write(datetime.now().strftime("%d-%b-%Y (%H:%M:%S.%f)")) - - - # Report reload time - reloadTimeSeconds = ((reloadEndTime - reloadStartTime).seconds) + (((reloadEndTime - reloadStartTime).microseconds) / 1000000) - tcTimeSeconds = ((tcEndTime - tcStartTime).seconds) + (((tcEndTime - tcStartTime).microseconds) / 1000000) - xdpSetupTimeSeconds = ((xdpEndTime - xdpStartTime).seconds) + (((xdpEndTime - xdpStartTime).microseconds) / 1000000) - xdpFilterTimeSeconds = ((xdpFilterEndTime - xdpFilterStartTime).seconds) + (((xdpFilterEndTime - xdpFilterStartTime).microseconds) / 1000000) - print("Queue and IP filter reload completed in " + "{:g}".format(round(reloadTimeSeconds,1)) + " seconds") - print("\tTC commands: \t" + "{:g}".format(round(tcTimeSeconds,1)) + " seconds") - print("\tXDP setup: \t " + "{:g}".format(round(xdpSetupTimeSeconds,1)) + " seconds") - print("\tXDP filters: \t " + "{:g}".format(round(xdpFilterTimeSeconds,4)) + " seconds") - - - # Done - print("refreshShapers completed on " + datetime.now().strftime("%d/%m/%Y %H:%M:%S")) + + # Starting + print("refreshShapers starting at " + datetime.now().strftime("%d/%m/%Y %H:%M:%S")) + # Create a single batch of xdp update commands to execute together + ipMapBatch = BatchedCommands() + + # Warn user if enableActualShellCommands is False, because that would mean no actual commands are executing + if enable_actual_shell_commands() == False: + warnings.warn("enableActualShellCommands is set to False. None of the commands below will actually be executed. Simulated run.", stacklevel=2) + # Warn user if monitorOnlyMode is True, because that would mean no actual shaping is happening + if monitor_mode_only() == True: + warnings.warn("monitorOnlyMode is set to True. Shaping will not occur.", stacklevel=2) + + + # Check if first run since boot + isThisFirstRunSinceBoot = checkIfFirstRunSinceBoot() + + + # Files + shapedDevicesFile = get_shaped_devices_path() + networkJSONfile = get_network_json_path() + + + # Check validation + safeToRunRefresh = False + print("Validating input files '" + shapedDevicesFile + "' and '" + networkJSONfile + "'") + if (validateNetworkAndDevices() == True): + shutil.copyfile('ShapedDevices.csv', 'lastGoodConfig.csv') + shutil.copyfile('network.json', 'lastGoodConfig.json') + print("Backed up good config as lastGoodConfig.csv and lastGoodConfig.json") + safeToRunRefresh = True + else: + if (isThisFirstRunSinceBoot == False): + warnings.warn("Validation failed. Because this is not the first run since boot (queues already set up) - will now exit.", stacklevel=2) + safeToRunRefresh = False + else: + warnings.warn("Validation failed. However - because this is the first run since boot - will load queues from last good config", stacklevel=2) + shapedDevicesFile = 'lastGoodConfig.csv' + networkJSONfile = 'lastGoodConfig.json' + safeToRunRefresh = True + + if safeToRunRefresh == True: + + # Load Subscriber Circuits & Devices + subscriberCircuits, dictForCircuitsWithoutParentNodes = loadSubscriberCircuits(shapedDevicesFile) + + + # Load network hierarchy + with open(networkJSONfile, 'r') as j: + network = json.loads(j.read()) + + + # Pull rx/tx queues / CPU cores available + # Handling the case when the number of queues for interfaces are different + InterfaceAQueuesAvailable = findQueuesAvailable(interface_a()) + InterfaceBQueuesAvailable = findQueuesAvailable(interface_b()) + queuesAvailable = min(InterfaceAQueuesAvailable, InterfaceBQueuesAvailable) + stickOffset = 0 + if on_a_stick(): + print("On-a-stick override dividing queues") + # The idea here is that download use queues 0 - n/2, upload uses the other half + queuesAvailable = math.floor(queuesAvailable / 2) + stickOffset = queuesAvailable + + # If in monitorOnlyMode, override network.json bandwidth rates to where no shaping will actually occur + if monitor_mode_only() == True: + def overrideNetworkBandwidths(data): + for elem in data: + if 'children' in data[elem]: + overrideNetworkBandwidths(data[elem]['children']) + data[elem]['downloadBandwidthMbpsMin'] = 100000 + data[elem]['uploadBandwidthMbpsMin'] = 100000 + overrideNetworkBandwidths(network) + + # Generate Parent Nodes. Spread ShapedDevices.csv which lack defined ParentNode across these (balance across CPUs) + print("Generating parent nodes") + generatedPNs = [] + numberOfGeneratedPNs = queuesAvailable + # If in monitorOnlyMode, override bandwidth rates to where no shaping will actually occur + if monitor_mode_only() == True: + chosenDownloadMbps = 10000 + chosenUploadMbps = 10000 + else: + chosenDownloadMbps = generated_pn_download_mbps() + chosenUploadMbps = generated_pn_upload_mbps() + for x in range(numberOfGeneratedPNs): + genPNname = "Generated_PN_" + str(x+1) + network[genPNname] = { + "downloadBandwidthMbps": chosenDownloadMbps, + "uploadBandwidthMbps": chosenUploadMbps + } + generatedPNs.append(genPNname) + if use_bin_packing_to_balance_cpu(): + print("Using binpacking module to sort circuits by CPU core") + weights = get_weights() + if weights is not None and dictForCircuitsWithoutParentNodes is not None: + for circuitId in dictForCircuitsWithoutParentNodes: + for circuit in subscriberCircuits: + if 'idForCircuitsWithoutParentNodes' in circuit and circuit['idForCircuitsWithoutParentNodes'] == circuitId: + for w in weights: + if w.circuit_id == circuit['circuitID']: + dictForCircuitsWithoutParentNodes[circuitId] = w.weight + bins = binpacking.to_constant_bin_number(dictForCircuitsWithoutParentNodes, numberOfGeneratedPNs) + genPNcounter = 0 + for binItem in bins: + sumItem = 0 + logging.info(generatedPNs[genPNcounter] + " will contain " + str(len(binItem)) + " circuits") + for key in binItem.keys(): + for circuit in subscriberCircuits: + if circuit['ParentNode'] == 'none': + if circuit['idForCircuitsWithoutParentNodes'] == key: + circuit['ParentNode'] = generatedPNs[genPNcounter] + genPNcounter += 1 + if genPNcounter >= queuesAvailable: + genPNcounter = 0 + print("Finished binpacking") + else: + genPNcounter = 0 + for circuit in subscriberCircuits: + if circuit['ParentNode'] == 'none': + circuit['ParentNode'] = generatedPNs[genPNcounter] + genPNcounter += 1 + if genPNcounter >= queuesAvailable: + genPNcounter = 0 + print("Generated parent nodes created") + + # Find the bandwidth minimums for each node by combining mimimums of devices lower in that node's hierarchy + def findBandwidthMins(data, depth): + tabs = ' ' * depth + minDownload = 0 + minUpload = 0 + for elem in data: + for circuit in subscriberCircuits: + if elem == circuit['ParentNode']: + minDownload += circuit['minDownload'] + minUpload += circuit['minUpload'] + if 'children' in data[elem]: + minDL, minUL = findBandwidthMins(data[elem]['children'], depth+1) + minDownload += minDL + minUpload += minUL + if 'downloadBandwidthMbpsMin' in data[elem]: + data[elem]['downloadBandwidthMbpsMin'] = max(data[elem]['downloadBandwidthMbpsMin'], minDownload) + else: + data[elem]['downloadBandwidthMbpsMin'] = max(data[elem]['downloadBandwidthMbps'], minUpload) + if 'uploadBandwidthMbpsMin' in data[elem]: + data[elem]['uploadBandwidthMbpsMin'] = max(data[elem]['uploadBandwidthMbpsMin'], minUpload) + else: + data[elem]['uploadBandwidthMbpsMin'] = max(data[elem]['uploadBandwidthMbps'], minUpload) + return minDownload, minUpload + logging.info("Finding the bandwidth minimums for each node") + minDownload, minUpload = findBandwidthMins(network, 0) + logging.info("Found the bandwidth minimums for each node") + + # Child nodes inherit bandwidth maximums of parents. We apply this here to avoid bugs when compression is applied with flattenA(). + def inheritBandwidthMaxes(data, parentMaxDL, parentMaxUL, parentMinDL, parentMinUL): + for node in data: + if isinstance(node, str): + if (isinstance(data[node], dict)) and (node != 'children'): + # Cap based on this node's max bandwidth, or parent node's max bandwidth, whichever is lower + data[node]['downloadBandwidthMbps'] = min(int(data[node]['downloadBandwidthMbps']),int(parentMaxDL)) + data[node]['uploadBandwidthMbps'] = min(int(data[node]['uploadBandwidthMbps']),int(parentMaxUL)) + data[node]['downloadBandwidthMbpsMin'] = min(int(data[node]['downloadBandwidthMbpsMin']),int(data[node]['downloadBandwidthMbps']),int(parentMinDL)) + data[node]['uploadBandwidthMbpsMin'] = min(int(data[node]['uploadBandwidthMbpsMin']),int(data[node]['uploadBandwidthMbps']),int(parentMinUL)) + # Recursive call this function for children nodes attached to this node + if 'children' in data[node]: + # We need to keep tabs on the minor counter, because we can't have repeating class IDs. Here, we bring back the minor counter from the recursive function + inheritBandwidthMaxes(data[node]['children'], data[node]['downloadBandwidthMbps'], data[node]['uploadBandwidthMbps'], data[node]['downloadBandwidthMbpsMin'], data[node]['uploadBandwidthMbpsMin']) + #return data + # Here is the actual call to the recursive function + inheritBandwidthMaxes(network, parentMaxDL=upstream_bandwidth_capacity_download_mbps(), parentMaxUL=upstream_bandwidth_capacity_upload_mbps(), parentMinDL=upstream_bandwidth_capacity_download_mbps(), parentMinUL=upstream_bandwidth_capacity_upload_mbps()) + + # Compress network.json. HTB only supports 8 levels of HTB depth. Compress to 8 layers if beyond 8. + def flattenB(data): + newDict = {} + for node in data: + if isinstance(node, str): + if (isinstance(data[node], dict)) and (node != 'children'): + newDict[node] = dict(data[node]) + if 'children' in data[node]: + result = flattenB(data[node]['children']) + del newDict[node]['children'] + newDict.update(result) + return newDict + def flattenA(data, depth): + newDict = {} + for node in data: + if isinstance(node, str): + if (isinstance(data[node], dict)) and (node != 'children'): + newDict[node] = dict(data[node]) + if 'children' in data[node]: + result = flattenA(data[node]['children'], depth+2) + del newDict[node]['children'] + if depth <= 8: + newDict[node]['children'] = result + else: + flattened = flattenB(data[node]['children']) + if 'children' in newDict[node]: + newDict[node]['children'].update(flattened) + else: + newDict[node]['children'] = flattened + return newDict + network = flattenA(network, 1) + + # Group circuits by parent node. Reduces runtime for section below this one. + circuits_by_parent_node = {} + circuit_min_down_combined_by_parent_node = {} + circuit_min_up_combined_by_parent_node = {} + for circuit in subscriberCircuits: + #If a device from ShapedDevices.csv lists this node as its Parent Node, attach it as a leaf to this node HTB + if circuit['ParentNode'] not in circuits_by_parent_node: + circuits_by_parent_node[circuit['ParentNode']] = [] + temp = circuits_by_parent_node[circuit['ParentNode']] + temp.append(circuit) + circuits_by_parent_node[circuit['ParentNode']] = temp + if circuit['ParentNode'] not in circuit_min_down_combined_by_parent_node: + circuit_min_down_combined_by_parent_node[circuit['ParentNode']] = 0 + circuit_min_down_combined_by_parent_node[circuit['ParentNode']] += circuit['minDownload'] + if circuit['ParentNode'] not in circuit_min_up_combined_by_parent_node: + circuit_min_up_combined_by_parent_node[circuit['ParentNode']] = 0 + circuit_min_up_combined_by_parent_node[circuit['ParentNode']] += circuit['minUpload'] + + # Parse network structure and add devices from ShapedDevices.csv + print("Parsing network structure and tallying devices") + parentNodes = [] + minorByCPUpreloaded = {} + knownClassIDs = [] + nodes_requiring_min_squashing = {} + # Track minor counter by CPU. This way we can have > 32000 hosts (htb has u16 limit to minor handle) + # Minor numbers start at 3 to reserve 1 for root qdisc and 2 for default class + # With CIRCUIT_PADDING, we leave gaps between nodes to allow future circuit additions + # without disrupting existing ClassID assignments. This maintains stability across reloads. + for x in range(queuesAvailable): + minorByCPUpreloaded[x+1] = 3 + def traverseNetwork(data, depth, major, minorByCPU, queue, parentClassID, upParentClassID, parentMaxDL, parentMaxUL, parentMinDL, parentMinUL): + # ClassID Assignment Strategy: + # - Nodes and circuits are processed in alphabetical order for stability + # - Each node gets a unique minor number that increments sequentially + # - After processing all circuits for a node, we add CIRCUIT_PADDING to the minor counter + # - This creates gaps that allow adding new circuits without affecting other ClassIDs + # - Children are also sorted before recursive processing to ensure deterministic traversal + # For top-level binpacked keys (CpueQueueN), enforce numeric ordering of N + keys = list(data.keys()) + if depth == 0 and len(keys) > 0 and all(k.startswith("CpueQueue") for k in keys): + try: + keys.sort(key=lambda k: int(k.replace("CpueQueue", ""))) + except Exception: + keys = sorted(keys) + else: + keys = sorted(keys) + for node in keys: + #if data[node]['type'] == "virtual": + # print(node + " is a virtual node. Skipping.") + # if depth == 0: + # parentClassID = hex(major) + ':' + # upParentClassID = hex(major+stickOffset) + ':' + # data[node]['parentClassID'] = parentClassID + # data[node]['up_parentClassID'] = upParentClassID + # data[node]['classMajor'] = hex(major) + # data[node]['up_classMajor'] = hex(major + stickOffset) + # data[node]['classMinor'] = hex(minorByCPU[queue]) + # data[node]['cpuNum'] = hex(queue-1) + # data[node]['up_cpuNum'] = hex(queue-1+stickOffset) + # traverseNetwork(data[node]['children'], depth, major, minorByCPU, queue, parentClassID, upParentClassID, parentMaxDL, parentMaxUL) + # continue + circuitsForThisNetworkNode = [] + nodeClassID = hex(major) + ':' + hex(minorByCPU[queue]) + upNodeClassID = hex(major+stickOffset) + ':' + hex(minorByCPU[queue]) + data[node]['classid'] = nodeClassID + data[node]['up_classid'] = upNodeClassID + if depth == 0: + parentClassID = hex(major) + ':' + upParentClassID = hex(major+stickOffset) + ':' + data[node]['parentClassID'] = parentClassID + data[node]['up_parentClassID'] = upParentClassID + # If in monitorOnlyMode, override bandwidth rates to where no shaping will actually occur + if monitor_mode_only() == True: + data[node]['downloadBandwidthMbps'] = 100000 + data[node]['uploadBandwidthMbps'] = 100000 + data[node]['downloadBandwidthMbpsMin'] = 100000 + data[node]['uploadBandwidthMbpsMin'] = 100000 + # If not in monitorOnlyMode + else: + # Cap based on this node's max bandwidth, or parent node's max bandwidth, whichever is lower + data[node]['downloadBandwidthMbps'] = min(data[node]['downloadBandwidthMbps'],parentMaxDL) + data[node]['uploadBandwidthMbps'] = min(data[node]['uploadBandwidthMbps'],parentMaxUL) + data[node]['downloadBandwidthMbpsMin'] = min(data[node]['downloadBandwidthMbpsMin'], data[node]['downloadBandwidthMbps'], parentMinDL) + data[node]['uploadBandwidthMbpsMin'] = min(data[node]['uploadBandwidthMbpsMin'], data[node]['uploadBandwidthMbps'], parentMinUL) + # Calculations are done in findBandwidthMins() to determine optimal HTB rates (mins) and ceils (maxs) + data[node]['classMajor'] = hex(major) + data[node]['up_classMajor'] = hex(major + stickOffset) + data[node]['classMinor'] = hex(minorByCPU[queue]) + data[node]['cpuNum'] = hex(queue-1) + data[node]['up_cpuNum'] = hex(queue-1+stickOffset) + thisParentNode = { + "parentNodeName": node, + "classID": nodeClassID, + "maxDownload": data[node]['downloadBandwidthMbps'], + "maxUpload": data[node]['uploadBandwidthMbps'], + } + parentNodes.append(thisParentNode) + minorByCPU[queue] = minorByCPU[queue] + 1 + # Check for overflow - TC uses u16 for minor class ID (max 65535) + if minorByCPU[queue] > 0xFFFF: + logging.error(f"Minor class ID overflow on CPU {queue}: {minorByCPU[queue]} exceeds TC's u16 limit (65535). Consider increasing queue count or restructuring network hierarchy.") + raise ValueError(f"Minor class ID overflow on CPU {queue}: {minorByCPU[queue]} exceeds limit of 65535") + # If a device from ShapedDevices.csv lists this node as its Parent Node, attach it as a leaf to this node HTB + if node in circuits_by_parent_node: + # If mins of circuits combined exceed min of parent node - set to 1 + override_min_down = None + override_min_up = None + if monitor_mode_only() == False: + if (circuit_min_down_combined_by_parent_node[node] > data[node]['downloadBandwidthMbpsMin']) or (circuit_min_up_combined_by_parent_node[node] > data[node]['uploadBandwidthMbpsMin']): + override_min_down = 1 + override_min_up = 1 + logging.info("The combined minimums of circuits in Parent Node [" + node + "] exceeded that of the parent node. Reducing these circuits' minimums to 1 now.", stacklevel=2) + if ((override_min_down * len(circuits_by_parent_node[node])) > data[node]['downloadBandwidthMbpsMin']) or ((override_min_up * len(circuits_by_parent_node[node])) > data[node]['uploadBandwidthMbpsMin']): + logging.info("Even with this change, minimums will exceed the min rate of the parent node. Using 10 kbps as the minimum for these circuits instead.", stacklevel=2) + nodes_requiring_min_squashing[node] = True + # Sort circuits by name for stable ordering + sorted_circuits = sorted(circuits_by_parent_node[node], + key=lambda c: c.get('circuitName', c.get('circuitID', ''))) + for circuit in sorted_circuits: + if node == circuit['ParentNode']: + if monitor_mode_only() == False: + if circuit['maxDownload'] > data[node]['downloadBandwidthMbps']: + logging.info("downloadMax of Circuit ID [" + circuit['circuitID'] + "] exceeded that of its parent node. Reducing to that of its parent node now.", stacklevel=2) + if circuit['maxUpload'] > data[node]['uploadBandwidthMbps']: + logging.info("uploadMax of Circuit ID [" + circuit['circuitID'] + "] exceeded that of its parent node. Reducing to that of its parent node now.", stacklevel=2) + parentString = hex(major) + ':' + flowIDstring = hex(major) + ':' + hex(minorByCPU[queue]) + upFlowIDstring = hex(major + stickOffset) + ':' + hex(minorByCPU[queue]) + circuit['classid'] = flowIDstring + circuit['up_classid'] = upFlowIDstring + logging.info("Added up_classid to circuit: " + circuit['up_classid']) + # Create circuit dictionary to be added to network structure, eventually output as queuingStructure.json + maxDownload = min(circuit['maxDownload'],data[node]['downloadBandwidthMbps']) + maxUpload = min(circuit['maxUpload'],data[node]['uploadBandwidthMbps']) + if override_min_down: + circuit['minDownload'] = 1 + if override_min_up: + circuit['minUpload'] = 1 + minDownload = min(circuit['minDownload'],maxDownload) + minUpload = min(circuit['minUpload'],maxUpload) + thisNewCircuitItemForNetwork = { + 'maxDownload' : maxDownload, + 'maxUpload' : maxUpload, + 'minDownload' : minDownload, + 'minUpload' : minUpload, + "circuitID": circuit['circuitID'], + "circuitName": circuit['circuitName'], + "ParentNode": circuit['ParentNode'], + "devices": circuit['devices'], + "classid": flowIDstring, + "up_classid" : upFlowIDstring, + "classMajor": hex(major), + "up_classMajor" : hex(major + stickOffset), + "classMinor": hex(minorByCPU[queue]), + "comment": circuit['comment'] + } + # Preserve optional per-circuit SQM override for downstream bakery call + if 'sqm' in circuit and circuit['sqm']: + thisNewCircuitItemForNetwork['sqm'] = circuit['sqm'] + # Generate TC commands to be executed later + thisNewCircuitItemForNetwork['devices'] = circuit['devices'] + circuitsForThisNetworkNode.append(thisNewCircuitItemForNetwork) + minorByCPU[queue] = minorByCPU[queue] + 1 + if len(circuitsForThisNetworkNode) > 0: + data[node]['circuits'] = circuitsForThisNetworkNode + + # Add padding for future circuit additions (applies to all nodes) + # This ensures space is reserved even for nodes without circuits + minorByCPU[queue] = minorByCPU[queue] + CIRCUIT_PADDING + + # Recursive call this function for children nodes attached to this node + if 'children' in data[node]: + # Sort children to ensure consistent traversal order + sorted_children = dict(sorted(data[node]['children'].items())) + # We need to keep tabs on the minor counter, because we can't have repeating class IDs. Here, we bring back the minor counter from the recursive function + minorByCPU[queue] = minorByCPU[queue] + 1 + # Check for overflow - TC uses u16 for minor class ID (max 65535) + if minorByCPU[queue] > 0xFFFF: + logging.error(f"Minor class ID overflow on CPU {queue}: {minorByCPU[queue]} exceeds TC's u16 limit (65535). Consider increasing queue count or restructuring network hierarchy.") + raise ValueError(f"Minor class ID overflow on CPU {queue}: {minorByCPU[queue]} exceeds limit of 65535") + minorByCPU = traverseNetwork(sorted_children, depth+1, major, minorByCPU, queue, nodeClassID, upNodeClassID, data[node]['downloadBandwidthMbps'], data[node]['uploadBandwidthMbps'], data[node]['downloadBandwidthMbpsMin'], data[node]['uploadBandwidthMbpsMin']) + # If top level node, increment to next queue / cpu core + if depth == 0: + if queue >= queuesAvailable: + queue = 1 + major = queue + else: + queue += 1 + major += 1 + return minorByCPU + + # If we're in binpacking mode, we need to sort the network structure a bit + bins = [] + if use_bin_packing_to_balance_cpu() and not is_network_flat(): + print("BinPacking is enabled, so we're going to sort your network.") + cpuBin = {} + weights = get_tree_weights() + # Stable tie-breaking: sort by (-weight, name) so equal weights have deterministic order + try: + weights = sorted(weights, key=lambda w: (-int(w.weight), str(w.name))) + except Exception: + pass + for w in weights: + cpuBin[w.name] = w.weight + bins = binpacking.to_constant_bin_number(cpuBin, queuesAvailable) + for x in range(queuesAvailable): + print("Bin " + str(x) + " = ", bins[x]) + binnedNetwork = {} + for cpu in range(queuesAvailable): + cpuKey = "CpueQueue" + str(cpu) + binnedNetwork[cpuKey] = { + 'downloadBandwidthMbps': generated_pn_download_mbps(), + 'uploadBandwidthMbps': generated_pn_upload_mbps(), + 'type': 'site', + 'downloadBandwidthMbpsMin': generated_pn_download_mbps(), + 'uploadBandwidthMbpsMin': generated_pn_upload_mbps(), + 'children': {}, + 'name': cpuKey + } + for node in network: + found = False + for bin in range(queuesAvailable): + if node in bins[bin]: + binnedNetwork["CpueQueue" + str(bin)]['children'][node] = network[node] + found = True + if found == False: + newQueueId = queuesAvailable-1 + binnedNetwork["CpueQueue" + str(newQueueId)]['children'][node] = network[node] + network = binnedNetwork + + # Here is the actual call to the recursive traverseNetwork() function. finalMinor is not used. + minorByCPU = traverseNetwork(network, 0, major=1, minorByCPU=minorByCPUpreloaded, queue=1, parentClassID=None, upParentClassID=None, parentMaxDL=upstream_bandwidth_capacity_download_mbps(), parentMaxUL=upstream_bandwidth_capacity_upload_mbps(), parentMinDL=upstream_bandwidth_capacity_download_mbps(), parentMinUL=upstream_bandwidth_capacity_upload_mbps()) + + bakery = Bakery() + bakery.start_batch() # Initializes the bakery transaction + linuxTCcommands = [] + devicesShaped = [] + # Root HTB Setup + # Create MQ qdisc for each CPU core / rx-tx queue. Generate commands to create corresponding HTB and leaf classes. Prepare commands for execution later + thisInterface = interface_a() + logging.info("# MQ Setup for " + thisInterface) + command = 'qdisc replace dev ' + thisInterface + ' root handle 7FFF: mq' + bakery.setup_mq(queuesAvailable, stickOffset) + linuxTCcommands.append(command) + maxBandwidth = max(upstream_bandwidth_capacity_upload_mbps(), upstream_bandwidth_capacity_download_mbps()) + calculateR2q(maxBandwidth) + for queue in range(queuesAvailable): + command = 'qdisc add dev ' + thisInterface + ' parent 7FFF:' + hex(queue+1) + ' handle ' + hex(queue+1) + ': htb default 2' + linuxTCcommands.append(command) + command = 'class add dev ' + thisInterface + ' parent ' + hex(queue+1) + ': classid ' + hex(queue+1) + ':1 htb rate '+ format_rate_for_tc(upstream_bandwidth_capacity_download_mbps()) + ' ceil ' + format_rate_for_tc(upstream_bandwidth_capacity_download_mbps()) + quantum(upstream_bandwidth_capacity_download_mbps()) + linuxTCcommands.append(command) + command = 'qdisc add dev ' + thisInterface + ' parent ' + hex(queue+1) + ':1 ' + sqm() + linuxTCcommands.append(command) + # Default class - traffic gets passed through this limiter with lower priority if it enters the top HTB without a specific class. + # Technically, that should not even happen. So don't expect much if any traffic in this default class. + # Only 1/4 of defaultClassCapacity is guaranteed (to prevent hitting ceiling of upstream), for the most part it serves as an "up to" ceiling. + command = 'class add dev ' + thisInterface + ' parent ' + hex(queue+1) + ':1 classid ' + hex(queue+1) + ':2 htb rate ' + format_rate_for_tc(round((upstream_bandwidth_capacity_download_mbps()-1)/4)) + ' ceil ' + format_rate_for_tc(upstream_bandwidth_capacity_download_mbps()-1) + ' prio 5' + quantum(upstream_bandwidth_capacity_download_mbps()) + linuxTCcommands.append(command) + command = 'qdisc add dev ' + thisInterface + ' parent ' + hex(queue+1) + ':2 ' + sqm() + linuxTCcommands.append(command) + + # Note the use of stickOffset, and not replacing the root queue if we're on a stick + thisInterface = interface_b() + logging.info("# MQ Setup for " + thisInterface) + if not on_a_stick(): + command = 'qdisc replace dev ' + thisInterface + ' root handle 7FFF: mq' + linuxTCcommands.append(command) + for queue in range(queuesAvailable): + command = 'qdisc add dev ' + thisInterface + ' parent 7FFF:' + hex(queue+stickOffset+1) + ' handle ' + hex(queue+stickOffset+1) + ': htb default 2' + linuxTCcommands.append(command) + command = 'class add dev ' + thisInterface + ' parent ' + hex(queue+stickOffset+1) + ': classid ' + hex(queue+stickOffset+1) + ':1 htb rate '+ format_rate_for_tc(upstream_bandwidth_capacity_upload_mbps()) + ' ceil ' + format_rate_for_tc(upstream_bandwidth_capacity_upload_mbps()) + quantum(upstream_bandwidth_capacity_upload_mbps()) + linuxTCcommands.append(command) + command = 'qdisc add dev ' + thisInterface + ' parent ' + hex(queue+stickOffset+1) + ':1 ' + sqm() + linuxTCcommands.append(command) + # Default class - traffic gets passed through this limiter with lower priority if it enters the top HTB without a specific class. + # Technically, that should not even happen. So don't expect much if any traffic in this default class. + # Only 1/4 of defaultClassCapacity is guarenteed (to prevent hitting ceiling of upstream), for the most part it serves as an "up to" ceiling. + command = 'class add dev ' + thisInterface + ' parent ' + hex(queue+stickOffset+1) + ':1 classid ' + hex(queue+stickOffset+1) + ':2 htb rate ' + format_rate_for_tc(round((upstream_bandwidth_capacity_upload_mbps()-1)/4)) + ' ceil ' + format_rate_for_tc(upstream_bandwidth_capacity_upload_mbps()-1) + ' prio 5' + quantum(upstream_bandwidth_capacity_upload_mbps()) + linuxTCcommands.append(command) + command = 'qdisc add dev ' + thisInterface + ' parent ' + hex(queue+stickOffset+1) + ':2 ' + sqm() + linuxTCcommands.append(command) + + + # Parse network structure. For each tier, generate commands to create corresponding HTB and leaf classes. Prepare commands for execution later + # Define lists for hash filters + print("Preparing TC commands") + def traverseNetwork(data): + + # Cake needs help handling rates lower than 5 Mbps + def sqmFixupRate(rate:int, sqm:str) -> str: + # If we aren't using cake, just return the sqm string + if not sqm.startswith("cake") or "rtt" in sqm: + return sqm + + # If we are using cake, we need to fixup the rate + # Based on: 1 MTU is 1500 bytes, or 12,000 bits. + # At 1 Mbps, (1,000 bits per ms) transmitting an MTU takes 12ms. Add 3ms for overhead, and we get 15ms. + # So 15ms divided by 5 (for 1%) multiplied by 100 yields 300ms. + # The same formula gives 180ms at 2Mbps + # 140ms at 3Mbps + # 120ms at 4Mbps + match rate: + case 1: return sqm + " rtt 300" + case 2: return sqm + " rtt 180" + case 3: return sqm + " rtt 140" + case 4: return sqm + " rtt 120" + case _: return sqm + + for node in sorted(data.keys()): + site_name = data[node]['name'] if 'name' in data[node] else node + bakery.add_site( + site_name, + data[node]['parentClassID'], + data[node]['up_parentClassID'], + int(data[node]['classMinor'], 16), + data[node]['downloadBandwidthMbpsMin'], + data[node]['uploadBandwidthMbpsMin'], + data[node]['downloadBandwidthMbps'], + data[node]['uploadBandwidthMbps'], + ) + command = 'class add dev ' + interface_a() + ' parent ' + data[node]['parentClassID'] + ' classid ' + data[node]['classMinor'] + ' htb rate '+ format_rate_for_tc(data[node]['downloadBandwidthMbpsMin']) + ' ceil '+ format_rate_for_tc(data[node]['downloadBandwidthMbps']) + ' prio 3' + quantum(data[node]['downloadBandwidthMbps']) + linuxTCcommands.append(command) + logging.info("Up ParentClassID: " + data[node]['up_parentClassID']) + logging.info("ClassMinor: " + data[node]['classMinor']) + command = 'class add dev ' + interface_b() + ' parent ' + data[node]['up_parentClassID'] + ' classid ' + data[node]['classMinor'] + ' htb rate '+ format_rate_for_tc(data[node]['uploadBandwidthMbpsMin']) + ' ceil '+ format_rate_for_tc(data[node]['uploadBandwidthMbps']) + ' prio 3' + quantum(data[node]['uploadBandwidthMbps']) + linuxTCcommands.append(command) + if 'circuits' in data[node]: + # Sort circuits by name for stable ordering + sorted_circuits = sorted(data[node]['circuits'], + key=lambda c: c.get('circuitName', c.get('circuitID', ''))) + for circuit in sorted_circuits: + # If circuit mins exceed node mins - handle low min rates of 1 to mean 10 kbps. + # Avoid changing minDownload or minUpload because they are used in queuingStructure.json, and must remain integers. + min_down = circuit['minDownload'] + min_up = circuit['minUpload'] + if node in nodes_requiring_min_squashing: + if min_down == 1: + min_down = 0.01 + if min_up == 1: + min_up = 0.01 + # Generate TC commands to be executed later + tcComment = " # CircuitID: " + circuit['circuitID'] + " DeviceIDs: " + for device in circuit['devices']: + tcComment = '' #tcComment + device['deviceID'] + ', ' + if 'devices' in circuit: + if 'comment' in circuit['devices'][0]: + tcComment = '' # tcComment + '| Comment: ' + circuit['devices'][0]['comment'] + tcComment = tcComment.replace("\n", "") + circuit_name = circuit['circuitID'] if 'circuitID' in circuit else "unknown" + # Collect all IP addresses for this circuit + ip_list = [] + for device in circuit['devices']: + if device['ipv4s']: + ip_list.extend(device['ipv4s']) + if device['ipv6s']: + ip_list.extend(device['ipv6s']) + # Concatenate IPs with comma separator + ip_addresses_str = ','.join(ip_list) + + sqm_override = circuit['sqm'] if 'sqm' in circuit else None + bakery.add_circuit( + circuit_name, + data[node]['classid'], + data[node]['up_classid'], + int(circuit['classMinor'], 16), + min_down, + min_up, + circuit['maxDownload'], + circuit['maxUpload'], + int(circuit['classMajor'], 16), + int(circuit['up_classMajor'], 16), + ip_addresses_str, + sqm_override, + ) + command = 'class add dev ' + interface_a() + ' parent ' + data[node]['classid'] + ' classid ' + circuit['classMinor'] + ' htb rate '+ format_rate_for_tc(min_down) + ' ceil '+ format_rate_for_tc(circuit['maxDownload']) + ' prio 3' + quantum(circuit['maxDownload']) + tcComment + linuxTCcommands.append(command) + # Only add CAKE / fq_codel qdisc if monitorOnlyMode is Off + if monitor_mode_only() == False: + # SQM Fixup for lower rates (and per-circuit override) + def effective_sqm_str(rate, override): + base = sqm() + if override is None or override == '': + return sqmFixupRate(rate, base) + ov = override.lower() + if ov == 'fq_codel': + return 'fq_codel' + if ov == 'cake': + cake_base = base if base.startswith('cake') else 'cake diffserv4' + return sqmFixupRate(rate, cake_base) + return sqmFixupRate(rate, base) + sqm_override = circuit['sqm'] if 'sqm' in circuit else None + useSqm = effective_sqm_str(circuit['maxDownload'], sqm_override) + command = 'qdisc add dev ' + interface_a() + ' parent ' + circuit['classMajor'] + ':' + circuit['classMinor'] + ' ' + useSqm + linuxTCcommands.append(command) + command = 'class add dev ' + interface_b() + ' parent ' + data[node]['up_classid'] + ' classid ' + circuit['classMinor'] + ' htb rate '+ format_rate_for_tc(min_up) + ' ceil '+ format_rate_for_tc(circuit['maxUpload']) + ' prio 3' + quantum(circuit['maxUpload']) + linuxTCcommands.append(command) + # Only add CAKE / fq_codel qdisc if monitorOnlyMode is Off + if monitor_mode_only() == False: + # SQM Fixup for lower rates (and per-circuit override) + sqm_override = circuit['sqm'] if 'sqm' in circuit else None + useSqm = effective_sqm_str(circuit['maxUpload'], sqm_override) + command = 'qdisc add dev ' + interface_b() + ' parent ' + circuit['up_classMajor'] + ':' + circuit['classMinor'] + ' ' + useSqm + linuxTCcommands.append(command) + pass + for device in circuit['devices']: + if device['ipv4s']: + for ipv4 in device['ipv4s']: + ipMapBatch.add_ip_mapping(str(ipv4), circuit['classid'], data[node]['cpuNum'], False) + #xdpCPUmapCommands.append('./bin/xdp_iphash_to_cpu_cmdline add --ip ' + str(ipv4) + ' --cpu ' + data[node]['cpuNum'] + ' --classid ' + circuit['classid']) + if on_a_stick(): + ipMapBatch.add_ip_mapping(str(ipv4), circuit['up_classid'], data[node]['up_cpuNum'], True) + #xdpCPUmapCommands.append('./bin/xdp_iphash_to_cpu_cmdline add --ip ' + str(ipv4) + ' --cpu ' + data[node]['up_cpuNum'] + ' --classid ' + circuit['up_classid'] + ' --upload 1') + if device['ipv6s']: + for ipv6 in device['ipv6s']: + ipMapBatch.add_ip_mapping(str(ipv6), circuit['classid'], data[node]['cpuNum'], False) + #xdpCPUmapCommands.append('./bin/xdp_iphash_to_cpu_cmdline add --ip ' + str(ipv6) + ' --cpu ' + data[node]['cpuNum'] + ' --classid ' + circuit['classid']) + if on_a_stick(): + ipMapBatch.add_ip_mapping(str(ipv6), circuit['up_classid'], data[node]['up_cpuNum'], True) + #xdpCPUmapCommands.append('./bin/xdp_iphash_to_cpu_cmdline add --ip ' + str(ipv6) + ' --cpu ' + data[node]['up_cpuNum'] + ' --classid ' + circuit['up_classid'] + ' --upload 1') + if device['deviceName'] not in devicesShaped: + devicesShaped.append(device['deviceName']) + # Recursive call this function for children nodes attached to this node + if 'children' in data[node]: + # Sort children to ensure consistent traversal order + sorted_children = dict(sorted(data[node]['children'].items())) + traverseNetwork(sorted_children) + # Here is the actual call to the recursive traverseNetwork() function. + traverseNetwork(network) + + # Save queuingStructure + queuingStructure = {} + queuingStructure['Network'] = network + queuingStructure['lastUsedClassIDCounterByCPU'] = minorByCPU + queuingStructure['generatedPNs'] = generatedPNs + with open('queuingStructure.json', 'w') as infile: + json.dump(queuingStructure, infile, indent=4) + + + # Record start time of actual filter reload + reloadStartTime = datetime.now() + + + # Clear Prior Settings + # We don't want to do this every time, with lqosd managing queues statefully. + # clearPriorSettings(interface_a(), interface_b()) + + + # Setup XDP and disable XPS regardless of whether it is first run or not (necessary to handle cases where systemctl stop was used) + xdpStartTime = datetime.now() + #if enable_actual_shell_commands(): + # The bakery will handle stale mapping cleanup; avoid clearing mappings here. + # Set up XDP-CPUMAP-TC + logging.info("# XDP Setup") + # Commented out - the daemon does this + #shell('./cpumap-pping/bin/xps_setup.sh -d ' + interfaceA + ' --default --disable') + #shell('./cpumap-pping/bin/xps_setup.sh -d ' + interfaceB + ' --default --disable') + #shell('./cpumap-pping/src/xdp_iphash_to_cpu --dev ' + interfaceA + ' --lan') + #shell('./cpumap-pping/src/xdp_iphash_to_cpu --dev ' + interfaceB + ' --wan') + #shell('./cpumap-pping/src/tc_classify --dev-egress ' + interfaceA) + #shell('./cpumap-pping/src/tc_classify --dev-egress ' + interfaceB) + xdpEndTime = datetime.now() + + + # Execute actual Linux TC commands + tcStartTime = datetime.now() + # print("Executing linux TC class/qdisc commands") + with open('linux_tc.txt', 'w') as f: + for command in linuxTCcommands: + logging.info(command) + f.write(f"{command}\n") + # if logging.DEBUG <= logging.root.level: + # # Do not --force in debug mode, so we can see any errors + # shell("/sbin/tc -b linux_tc.txt") + # else: + # shell("/sbin/tc -f -b linux_tc.txt") + bakery.commit() + tcEndTime = datetime.now() + # print("Executed " + str(len(linuxTCcommands)) + " linux TC class/qdisc commands") + + # Execute actual XDP-CPUMAP-TC filter commands + xdpFilterStartTime = datetime.now() + print("Executing XDP-CPUMAP-TC IP filter commands") + numXdpCommands = ipMapBatch.length() + if enable_actual_shell_commands(): + ipMapBatch.finish_ip_mappings() + ipMapBatch.submit() + #for command in xdpCPUmapCommands: + # logging.info(command) + # commands = command.split(' ') + # proc = subprocess.Popen(commands, stdout=subprocess.DEVNULL) + else: + ipMapBatch.log() + #for command in xdpCPUmapCommands: + # logging.info(command) + print("Executed " + str(numXdpCommands) + " XDP-CPUMAP-TC IP filter commands") + #print(xdpCPUmapCommands) + xdpFilterEndTime = datetime.now() + + + # Record end time of all reload commands + reloadEndTime = datetime.now() + + + # Recap - warn operator if devices were skipped + devicesSkipped = [] + for circuit in subscriberCircuits: + for device in circuit['devices']: + if device['deviceName'] not in devicesShaped: + devicesSkipped.append((device['deviceName'],device['deviceID'])) + if len(devicesSkipped) > 0: + warnings.warn('Some devices were not shaped. Please check to ensure they have a valid ParentNode listed in ShapedDevices.csv:', stacklevel=2) + print("Devices not shaped:") + for entry in devicesSkipped: + name, idNum = entry + print('DeviceID: ' + idNum + '\t DeviceName: ' + name) + + # Save ShapedDevices.csv as ShapedDevices.lastLoaded.csv + shutil.copyfile('ShapedDevices.csv', 'ShapedDevices.lastLoaded.csv') + + # Save for stats + with open('statsByCircuit.json', 'w') as f: + f.write(json.dumps(subscriberCircuits, indent=4)) + with open('statsByParentNode.json', 'w') as f: + f.write(json.dumps(parentNodes, indent=4)) + + + # Record time this run completed at + # filename = os.path.join(_here, 'lastRun.txt') + with open("lastRun.txt", 'w') as file: + file.write(datetime.now().strftime("%d-%b-%Y (%H:%M:%S.%f)")) + + + # Report reload time + reloadTimeSeconds = ((reloadEndTime - reloadStartTime).seconds) + (((reloadEndTime - reloadStartTime).microseconds) / 1000000) + tcTimeSeconds = ((tcEndTime - tcStartTime).seconds) + (((tcEndTime - tcStartTime).microseconds) / 1000000) + xdpSetupTimeSeconds = ((xdpEndTime - xdpStartTime).seconds) + (((xdpEndTime - xdpStartTime).microseconds) / 1000000) + xdpFilterTimeSeconds = ((xdpFilterEndTime - xdpFilterStartTime).seconds) + (((xdpFilterEndTime - xdpFilterStartTime).microseconds) / 1000000) + print("Queue and IP filter reload completed in " + "{:g}".format(round(reloadTimeSeconds,1)) + " seconds") + print("\tTC commands: \t" + "{:g}".format(round(tcTimeSeconds,1)) + " seconds") + print("\tXDP setup: \t " + "{:g}".format(round(xdpSetupTimeSeconds,1)) + " seconds") + print("\tXDP filters: \t " + "{:g}".format(round(xdpFilterTimeSeconds,4)) + " seconds") + + + # Done + print("refreshShapers completed on " + datetime.now().strftime("%d/%m/%Y %H:%M:%S")) def refreshShapersUpdateOnly(): - # Starting - print("refreshShapers starting at " + datetime.now().strftime("%d/%m/%Y %H:%M:%S")) - - - # Warn user if enableActualShellCommands is False, because that would mean no actual commands are executing - if enable_actual_shell_commands() == False: - warnings.warn("enableActualShellCommands is set to False. None of the commands below will actually be executed. Simulated run.", stacklevel=2) - - - # Files - shapedDevicesFile = 'ShapedDevices.csv' - networkJSONfile = 'network.json' - - - # Check validation - safeToRunRefresh = False - if (validateNetworkAndDevices() == True): - safeToRunRefresh = True - else: - warnings.warn("Validation failed. Will now exit.", stacklevel=2) - - if safeToRunRefresh == True: - networkChanged = False - devicesChanged = False - # Check for changes to network.json - if os.path.isfile('lastGoodConfig.json'): - with open('lastGoodConfig.json', 'r') as j: - originalNetwork = json.loads(j.read()) - with open('network.json', 'r') as j: - newestNetwork = json.loads(j.read()) - ddiff = DeepDiff(originalNetwork, newestNetwork, ignore_order=True) - if ddiff != {}: - networkChanged = True - - # Check for changes to ShapedDevices.csv - newlyUpdatedSubscriberCircuits, newlyUpdatedDictForCircuitsWithoutParentNodes = loadSubscriberCircuits('ShapedDevices.csv') - lastLoadedSubscriberCircuits, lastLoadedDictForCircuitsWithoutParentNodes = loadSubscriberCircuits('ShapedDevices.lastLoaded.csv') - - newlyUpdatedSubscriberCircuitsByID = {} - for circuit in newlyUpdatedSubscriberCircuits: - circuitid = circuit['circuitID'] - newlyUpdatedSubscriberCircuitsByID[circuitid] = circuit - - lastLoadedSubscriberCircuitsByID = {} - for circuit in lastLoadedSubscriberCircuits: - circuitid = circuit['circuitID'] - lastLoadedSubscriberCircuitsByID[circuitid] = circuit - - for circuitID, circuit in lastLoadedSubscriberCircuitsByID.items(): - if (circuitID in newlyUpdatedSubscriberCircuitsByID) and (circuitID in lastLoadedSubscriberCircuitsByID): - if newlyUpdatedSubscriberCircuitsByID[circuitID]['maxDownload'] != lastLoadedSubscriberCircuitsByID[circuitID]['maxDownload']: - devicesChanged = True - if newlyUpdatedSubscriberCircuitsByID[circuitID]['maxUpload'] != lastLoadedSubscriberCircuitsByID[circuitID]['maxUpload']: - devicesChanged = True - if newlyUpdatedSubscriberCircuitsByID[circuitID]['minDownload'] != lastLoadedSubscriberCircuitsByID[circuitID]['minDownload']: - devicesChanged = True - if newlyUpdatedSubscriberCircuitsByID[circuitID]['minUpload'] != lastLoadedSubscriberCircuitsByID[circuitID]['minUpload']: - devicesChanged = True - if newlyUpdatedSubscriberCircuitsByID[circuitID]['devices'] != lastLoadedSubscriberCircuitsByID[circuitID]['devices']: - devicesChanged = True - if newlyUpdatedSubscriberCircuitsByID[circuitID]['ParentNode'] != lastLoadedSubscriberCircuitsByID[circuitID]['ParentNode']: - devicesChanged = True - else: - devicesChanged = True - for circuitID, circuit in newlyUpdatedSubscriberCircuitsByID.items(): - if (circuitID not in lastLoadedSubscriberCircuitsByID): - devicesChanged = True - - - if devicesChanged or networkChanged: - print('Observed changes to ShapedDevices.csv or network.json. Applying full reload now') - refreshShapers() - else: - print('Observed no changes to ShapedDevices.csv or network.json. Leaving queues as is.') - - # Done - print("refreshShapersUpdateOnly completed on " + datetime.now().strftime("%d/%m/%Y %H:%M:%S")) + # Starting + print("refreshShapers starting at " + datetime.now().strftime("%d/%m/%Y %H:%M:%S")) + + + # Warn user if enableActualShellCommands is False, because that would mean no actual commands are executing + if enable_actual_shell_commands() == False: + warnings.warn("enableActualShellCommands is set to False. None of the commands below will actually be executed. Simulated run.", stacklevel=2) + + + # Files + shapedDevicesFile = 'ShapedDevices.csv' + networkJSONfile = 'network.json' + + + # Check validation + safeToRunRefresh = False + if (validateNetworkAndDevices() == True): + safeToRunRefresh = True + else: + warnings.warn("Validation failed. Will now exit.", stacklevel=2) + + if safeToRunRefresh == True: + networkChanged = False + devicesChanged = False + # Check for changes to network.json + if os.path.isfile('lastGoodConfig.json'): + with open('lastGoodConfig.json', 'r') as j: + originalNetwork = json.loads(j.read()) + with open('network.json', 'r') as j: + newestNetwork = json.loads(j.read()) + ddiff = DeepDiff(originalNetwork, newestNetwork, ignore_order=True) + if ddiff != {}: + networkChanged = True + + # Check for changes to ShapedDevices.csv + newlyUpdatedSubscriberCircuits, newlyUpdatedDictForCircuitsWithoutParentNodes = loadSubscriberCircuits('ShapedDevices.csv') + lastLoadedSubscriberCircuits, lastLoadedDictForCircuitsWithoutParentNodes = loadSubscriberCircuits('ShapedDevices.lastLoaded.csv') + + newlyUpdatedSubscriberCircuitsByID = {} + for circuit in newlyUpdatedSubscriberCircuits: + circuitid = circuit['circuitID'] + newlyUpdatedSubscriberCircuitsByID[circuitid] = circuit + + lastLoadedSubscriberCircuitsByID = {} + for circuit in lastLoadedSubscriberCircuits: + circuitid = circuit['circuitID'] + lastLoadedSubscriberCircuitsByID[circuitid] = circuit + + for circuitID, circuit in lastLoadedSubscriberCircuitsByID.items(): + if (circuitID in newlyUpdatedSubscriberCircuitsByID) and (circuitID in lastLoadedSubscriberCircuitsByID): + if newlyUpdatedSubscriberCircuitsByID[circuitID]['maxDownload'] != lastLoadedSubscriberCircuitsByID[circuitID]['maxDownload']: + devicesChanged = True + if newlyUpdatedSubscriberCircuitsByID[circuitID]['maxUpload'] != lastLoadedSubscriberCircuitsByID[circuitID]['maxUpload']: + devicesChanged = True + if newlyUpdatedSubscriberCircuitsByID[circuitID]['minDownload'] != lastLoadedSubscriberCircuitsByID[circuitID]['minDownload']: + devicesChanged = True + if newlyUpdatedSubscriberCircuitsByID[circuitID]['minUpload'] != lastLoadedSubscriberCircuitsByID[circuitID]['minUpload']: + devicesChanged = True + if newlyUpdatedSubscriberCircuitsByID[circuitID]['devices'] != lastLoadedSubscriberCircuitsByID[circuitID]['devices']: + devicesChanged = True + if newlyUpdatedSubscriberCircuitsByID[circuitID]['ParentNode'] != lastLoadedSubscriberCircuitsByID[circuitID]['ParentNode']: + devicesChanged = True + else: + devicesChanged = True + for circuitID, circuit in newlyUpdatedSubscriberCircuitsByID.items(): + if (circuitID not in lastLoadedSubscriberCircuitsByID): + devicesChanged = True + + + if devicesChanged or networkChanged: + print('Observed changes to ShapedDevices.csv or network.json. Applying full reload now') + refreshShapers() + else: + print('Observed no changes to ShapedDevices.csv or network.json. Leaving queues as is.') + + # Done + print("refreshShapersUpdateOnly completed on " + datetime.now().strftime("%d/%m/%Y %H:%M:%S")) if __name__ == '__main__': - # Check that the host lqosd is running - if is_lqosd_alive(): - print("lqosd is running") - else: - print("ERROR: lqosd is not running. Aborting") - os._exit(-1) - - # Check that the configuration file is usable - if check_config(): - print("Configuration from /etc/lqos.conf is usable") - else: - print("ERROR: Unable to load configuration from /etc/lqos.conf") - os.exit(-1) - - # Check that we aren't running LibreQoS.py more than once at a time - if is_libre_already_running(): - print("LibreQoS.py is already running in another process. Aborting.") - os._exit(-1) - - # We've got this far, so create a lock file - create_lock_file() - - parser = argparse.ArgumentParser() - parser.add_argument( - '-d', '--debug', - help="Print lots of debugging statements", - action="store_const", dest="loglevel", const=logging.DEBUG, - default=logging.WARNING, - ) - parser.add_argument( - '-v', '--verbose', - help="Be verbose", - action="store_const", dest="loglevel", const=logging.INFO, - ) - parser.add_argument( - '--updateonly', - help="Only update to reflect changes in ShapedDevices.csv (partial reload)", - action=argparse.BooleanOptionalAction, - ) - parser.add_argument( - '--validate', - help="Just validate network.json and ShapedDevices.csv", - action=argparse.BooleanOptionalAction, - ) - parser.add_argument( - '--clearrules', - help="Clear ip filters, qdiscs, and xdp setup if any", - action=argparse.BooleanOptionalAction, - ) - args = parser.parse_args() - logging.basicConfig(level=args.loglevel) - - if args.validate: - status = validateNetworkAndDevices() - elif args.clearrules: - tearDown(interface_a(), interface_b()) - elif args.updateonly: - # Single-interface updates don't work at all right now. - if on_a_stick(): - print("--updateonly is not supported for single-interface configurations") - os.exit(-1) - refreshShapersUpdateOnly() - else: - # Refresh and/or set up queues - refreshShapers() - - # Free the lock file - free_lock_file() + # Check that the host lqosd is running + if is_lqosd_alive(): + print("lqosd is running") + else: + print("ERROR: lqosd is not running. Aborting") + os._exit(-1) + + # Check that the configuration file is usable + if check_config(): + print("Configuration from /etc/lqos.conf is usable") + else: + print("ERROR: Unable to load configuration from /etc/lqos.conf") + os.exit(-1) + + # Check that we aren't running LibreQoS.py more than once at a time + if is_libre_already_running(): + print("LibreQoS.py is already running in another process. Aborting.") + os._exit(-1) + + # We've got this far, so create a lock file + create_lock_file() + + parser = argparse.ArgumentParser() + parser.add_argument( + '-d', '--debug', + help="Print lots of debugging statements", + action="store_const", dest="loglevel", const=logging.DEBUG, + default=logging.WARNING, + ) + parser.add_argument( + '-v', '--verbose', + help="Be verbose", + action="store_const", dest="loglevel", const=logging.INFO, + ) + parser.add_argument( + '--updateonly', + help="Only update to reflect changes in ShapedDevices.csv (partial reload)", + action=argparse.BooleanOptionalAction, + ) + parser.add_argument( + '--validate', + help="Just validate network.json and ShapedDevices.csv", + action=argparse.BooleanOptionalAction, + ) + parser.add_argument( + '--clearrules', + help="Clear ip filters, qdiscs, and xdp setup if any", + action=argparse.BooleanOptionalAction, + ) + args = parser.parse_args() + logging.basicConfig(level=args.loglevel) + + if args.validate: + status = validateNetworkAndDevices() + elif args.clearrules: + tearDown(interface_a(), interface_b()) + elif args.updateonly: + # Single-interface updates don't work at all right now. + if on_a_stick(): + print("--updateonly is not supported for single-interface configurations") + os.exit(-1) + refreshShapersUpdateOnly() + else: + # Refresh and/or set up queues + refreshShapers() + + # Free the lock file + free_lock_file() diff --git a/src/ShapedDevices.example.csv b/src/ShapedDevices.example.csv index c00eaa36..6ef04f3c 100644 --- a/src/ShapedDevices.example.csv +++ b/src/ShapedDevices.example.csv @@ -16,15 +16,15 @@ # # Backward Compatibility: Existing integer rates continue to work unchanged. # -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 -1,"968 Circle St., Gurnee, IL 60031",1,Device 1,AP_A,,"100.64.0.1, 100.64.0.14",fdd7:b724:0:100::/56,1,1,155,20,Standard integer rates -2,"31 Marconi Street, Lake In The Hills, IL 60156",2,Device 2,AP_A,,100.64.0.2,fdd7:b724:0:200::/56,0.5,0.5,2.5,1.0,Fractional rate example - small plan -3,"255 NW. Newport Ave., Jamestown, NY 14701",3,Device 3,AP_9,,100.64.0.3,fdd7:b724:0:300::/56,1.25,0.75,10.5,5.25,Fractional rate example - medium plan -4,"8493 Campfire Street, Peabody, MA 01960",4,Device 4,AP_9,,100.64.0.4,fdd7:b724:0:400::/56,25.5,12.5,100.5,50.25,Fractional rate example - large plan -2794,"6 Littleton Drive, Ringgold, GA 30736",5,Device 5,AP_11,,100.64.0.5,fdd7:b724:0:500::/56,1,1,105,18,Standard integer rates -2794,"6 Littleton Drive, Ringgold, GA 30736",6,Device 6,AP_11,,100.64.0.6,fdd7:b724:0:600::/56,1,1,105,18,Standard integer rates -5,"93 Oklahoma Ave., Parsippany, NJ 07054",7,Device 7,AP_1,,100.64.0.7,fdd7:b724:0:700::/56,2.0,2.0,25.0,10.0,Mixed decimal rates -6,"74 Bishop Ave., Bakersfield, CA 93306",8,Device 8,AP_1,,100.64.0.8,fdd7:b724:0:800::/56,1,1,105,18,Standard integer rates -7,"9598 Peg Shop Drive, Lutherville Timonium, MD 21093",9,Device 9,AP_7,,100.64.0.9,fdd7:b724:0:900::/56,1,1,105,18,Standard integer rates -8,"115 Gartner Rd., Gettysburg, PA 17325",10,Device 10,AP_7,,100.64.0.10,fdd7:b724:0:a00::/56,0.1,0.1,1.5,1.0,Minimum rate example -9,"525 Birchpond St., Romulus, MI 48174",11,Device 11,Site_1,,100.64.0.11,fdd7:b724:0:b00::/56,1,1,105,18,Standard integer rates +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,sqm +1,"968 Circle St., Gurnee, IL 60031",1,Device 1,AP_A,,"100.64.0.1, 100.64.0.14",fdd7:b724:0:100::/56,1,1,155,20,Standard integer rates, +2,"31 Marconi Street, Lake In The Hills, IL 60156",2,Device 2,AP_A,,100.64.0.2,fdd7:b724:0:200::/56,0.5,0.5,2.5,1.0,Fractional rate example - small plan,fq_codel +3,"255 NW. Newport Ave., Jamestown, NY 14701",3,Device 3,AP_9,,100.64.0.3,fdd7:b724:0:300::/56,1.25,0.75,10.5,5.25,Fractional rate example - medium plan, +4,"8493 Campfire Street, Peabody, MA 01960",4,Device 4,AP_9,,100.64.0.4,fdd7:b724:0:400::/56,25.5,12.5,100.5,50.25,Fractional rate example - large plan,cake +2794,"6 Littleton Drive, Ringgold, GA 30736",5,Device 5,AP_11,,100.64.0.5,fdd7:b724:0:500::/56,1,1,105,18,Standard integer rates, +2794,"6 Littleton Drive, Ringgold, GA 30736",6,Device 6,AP_11,,100.64.0.6,fdd7:b724:0:600::/56,1,1,105,18,Standard integer rates, +5,"93 Oklahoma Ave., Parsippany, NJ 07054",7,Device 7,AP_1,,100.64.0.7,fdd7:b724:0:700::/56,2.0,2.0,25.0,10.0,Mixed decimal rates, +6,"74 Bishop Ave., Bakersfield, CA 93306",8,Device 8,AP_1,,100.64.0.8,fdd7:b724:0:800::/56,1,1,105,18,Standard integer rates, +7,"9598 Peg Shop Drive, Lutherville Timonium, MD 21093",9,Device 9,AP_7,,100.64.0.9,fdd7:b724:0:900::/56,1,1,105,18,Standard integer rates, +8,"115 Gartner Rd., Gettysburg, PA 17325",10,Device 10,AP_7,,100.64.0.10,fdd7:b724:0:a00::/56,0.1,0.1,1.5,1.0,Minimum rate example, +9,"525 Birchpond St., Romulus, MI 48174",11,Device 11,Site_1,,100.64.0.11,fdd7:b724:0:b00::/56,1,1,105,18,Standard integer rates, diff --git a/src/rust/lqos_bakery/src/commands.rs b/src/rust/lqos_bakery/src/commands.rs index e66e62ff..3e4414a7 100644 --- a/src/rust/lqos_bakery/src/commands.rs +++ b/src/rust/lqos_bakery/src/commands.rs @@ -1,13 +1,14 @@ 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, + sqm_tokens_for, }; use allocative::Allocative; use lqos_bus::TcHandle; use lqos_config::LazyQueueMode; use std::collections::HashSet; use std::sync::Arc; -use tracing::{info, warn}; +use tracing::{info, warn, debug}; #[derive(Debug, Clone, Copy, Allocative)] struct AddSiteParams { @@ -21,7 +22,7 @@ struct AddSiteParams { upload_bandwidth_max: f32, } -#[derive(Debug, Clone, Copy, Allocative)] +#[derive(Debug, Clone, Allocative)] struct AddCircuitParams { circuit_hash: i64, parent_class_id: TcHandle, @@ -33,6 +34,8 @@ struct AddCircuitParams { upload_bandwidth_max: f32, class_major: u16, up_class_major: u16, + // Optional per-circuit SQM override: "cake" or "fq_codel" + sqm_override: Option, } /// Execution Mode @@ -46,7 +49,7 @@ pub enum ExecutionMode { /// List of commands that the Bakery system can handle. #[derive(Debug, Clone, Allocative)] -pub enum BakeryCommands { + pub enum BakeryCommands { /// Notification that the bus socket is ready; bakery can seed mappings BusReady, /// Add or update an IP mapping (mirrors `MapIpToFlow` from the bus) @@ -149,6 +152,8 @@ pub enum BakeryCommands { up_class_major: u16, /// Concatenated list of all IPs for this circuit. ip_addresses: String, // Concatenated list of all IPs for this circuit + /// Optional per-circuit SQM override: "cake" or "fq_codel" + sqm_override: Option, }, /// Change a specific HTB class rate on-the-fly; optionally dry-run. StormGuardAdjustment { @@ -223,6 +228,7 @@ impl BakeryCommands { class_major, up_class_major, ip_addresses: _, + sqm_override, } => Self::add_circuit( execution_mode, config, @@ -237,6 +243,7 @@ impl BakeryCommands { upload_bandwidth_max: *upload_bandwidth_max, class_major: *class_major, up_class_major: *up_class_major, + sqm_override: sqm_override.clone(), }, ), _ => None, @@ -582,6 +589,17 @@ impl BakeryCommands { config: &Arc, params: AddCircuitParams, ) -> Option>> { + if let Some(ref s) = params.sqm_override { + if s.eq_ignore_ascii_case("fq_codel") { + debug!( + "Bakery: building AddCircuit with fq_codel override (circuit_hash={}, class_minor=0x{:x}, class_major=0x{:x}, up_class_major=0x{:x})", + params.circuit_hash, + params.class_minor, + params.class_major, + params.up_class_major + ); + } + } let do_htb; let do_sqm; @@ -674,7 +692,11 @@ impl BakeryCommands { "parent".to_string(), format!("0x{:x}:0x{:x}", params.class_major, params.class_minor), ]; - sqm_command.extend(sqm_rate_fixup(params.download_bandwidth_max, config)); + sqm_command.extend(sqm_tokens_for( + params.download_bandwidth_max, + config, + ¶ms.sqm_override, + )); result.push(sqm_command); } @@ -712,7 +734,11 @@ impl BakeryCommands { "parent".to_string(), format!("0x{:x}:0x{:x}", params.up_class_major, params.class_minor), ]; - sqm_command.extend(sqm_rate_fixup(params.upload_bandwidth_max, config)); + sqm_command.extend(sqm_tokens_for( + params.upload_bandwidth_max, + config, + ¶ms.sqm_override, + )); result.push(sqm_command); } diff --git a/src/rust/lqos_bakery/src/diff/circuits.rs b/src/rust/lqos_bakery/src/diff/circuits.rs index 8400cccf..c72c90ae 100644 --- a/src/rust/lqos_bakery/src/diff/circuits.rs +++ b/src/rust/lqos_bakery/src/diff/circuits.rs @@ -102,6 +102,7 @@ fn classify_circuit_change(a: &BakeryCommands, b: &BakeryCommands) -> CircuitCha class_major, up_class_major, ip_addresses, + sqm_override, .. } = a else { @@ -119,6 +120,7 @@ fn classify_circuit_change(a: &BakeryCommands, b: &BakeryCommands) -> CircuitCha class_major: other_class_major, up_class_major: other_up_class_major, ip_addresses: other_ip_addresses, + sqm_override: other_sqm_override, .. } = b else { @@ -139,7 +141,8 @@ fn classify_circuit_change(a: &BakeryCommands, b: &BakeryCommands) -> CircuitCha let speed = download_bandwidth_min != other_download_bandwidth_min || upload_bandwidth_min != other_upload_bandwidth_min || download_bandwidth_max != other_download_bandwidth_max - || upload_bandwidth_max != other_upload_bandwidth_max; + || upload_bandwidth_max != other_upload_bandwidth_max + || sqm_override != other_sqm_override; // treat SQM override changes as speed-level changes let ip = ip_addresses != other_ip_addresses; diff --git a/src/rust/lqos_bakery/src/lib.rs b/src/rust/lqos_bakery/src/lib.rs index be1294c1..bca43ce3 100644 --- a/src/rust/lqos_bakery/src/lib.rs +++ b/src/rust/lqos_bakery/src/lib.rs @@ -77,6 +77,8 @@ struct Migration { final_minor: u16, // IP list for remapping ips: Vec, + // Per-circuit SQM override ("cake" or "fq_codel"), if any + sqm_override: Option, stage: MigrationStage, } @@ -166,6 +168,7 @@ fn build_temp_add_cmd( class_major, up_class_major, ip_addresses, + sqm_override, .. } = base { @@ -181,6 +184,7 @@ fn build_temp_add_cmd( class_major: *class_major, up_class_major: *up_class_major, ip_addresses: ip_addresses.clone(), + sqm_override: sqm_override.clone(), }) } else { None @@ -538,6 +542,7 @@ fn bakery_main(rx: Receiver, tx: Sender) { class_major: mig.class_major, up_class_major: mig.up_class_major, ip_addresses: "".to_string(), + sqm_override: mig.sqm_override.clone(), }, mig.shadow_minor, mig.old_down_min, @@ -604,6 +609,7 @@ fn bakery_main(rx: Receiver, tx: Sender) { class_major: mig.class_major, up_class_major: mig.up_class_major, ip_addresses: "".to_string(), + sqm_override: mig.sqm_override.clone(), }, mig.old_minor, mig.old_down_min, @@ -678,6 +684,7 @@ fn bakery_main(rx: Receiver, tx: Sender) { class_major: mig.class_major, up_class_major: mig.up_class_major, ip_addresses: "".to_string(), + sqm_override: mig.sqm_override.clone(), }, mig.shadow_minor, mig.old_down_min, @@ -922,6 +929,7 @@ fn handle_commit_batch( class_major, up_class_major, ip_addresses, + sqm_override, } = cmd.as_ref() { let was_activated = live_circuits.contains_key(circuit_hash); @@ -956,6 +964,7 @@ fn handle_commit_batch( shadow_minor, final_minor: *class_minor, ips: parse_ip_list(ip_addresses), + sqm_override: sqm_override.clone(), stage: MigrationStage::PrepareShadow, }; migrations.insert(*circuit_hash, mig); diff --git a/src/rust/lqos_bakery/src/queue_math.rs b/src/rust/lqos_bakery/src/queue_math.rs index 5eecd2d0..fec5815c 100644 --- a/src/rust/lqos_bakery/src/queue_math.rs +++ b/src/rust/lqos_bakery/src/queue_math.rs @@ -107,3 +107,47 @@ pub(crate) fn sqm_rate_fixup(rate: f32, config: &Arc) -> Ve } result } + +/// Build SQM token vector for a circuit given an optional per-circuit override. +/// - None: use config default with cake low-rate RTT fixups (existing behavior) +/// - Some("fq_codel"): use fq_codel +/// - Some("cake"): use config default if it starts with "cake", otherwise fallback to +/// "cake diffserv4"; then apply low-rate RTT fixups. +pub(crate) fn sqm_tokens_for( + rate: f32, + config: &Arc, + override_opt: &Option, +) -> Vec { + match override_opt.as_deref() { + None => sqm_rate_fixup(rate, config), + Some("fq_codel") => vec!["fq_codel".to_string()], + Some("cake") => { + let default = &config.queues.default_sqm; + let mut base = if default.starts_with("cake") { + sqm_as_vec(config) + } else { + vec!["cake".to_string(), "diffserv4".to_string()] + }; + // If RTT already specified, leave as-is; otherwise apply low-rate fixups + let has_rtt = base.iter().any(|s| s == "rtt"); + if !has_rtt { + // Mirror the thresholds used in sqm_rate_fixup + if rate <= 1.0 { + base.push("rtt".to_string()); + base.push("300".to_string()); + } else if rate <= 2.0 { + base.push("rtt".to_string()); + base.push("180".to_string()); + } else if rate <= 3.0 { + base.push("rtt".to_string()); + base.push("140".to_string()); + } else if rate <= 4.0 { + base.push("rtt".to_string()); + base.push("120".to_string()); + } + } + base + } + Some(_) => sqm_rate_fixup(rate, config), // defensive fallback + } +} diff --git a/src/rust/lqos_bus/src/bus/request.rs b/src/rust/lqos_bus/src/bus/request.rs index 962bf614..c4d96641 100644 --- a/src/rust/lqos_bus/src/bus/request.rs +++ b/src/rust/lqos_bus/src/bus/request.rs @@ -284,6 +284,8 @@ pub enum BusRequest { up_class_major: u16, /// Concatenated list of IP addresses for the circuit ip_addresses: String, + /// Optional per-circuit SQM override: "cake" or "fq_codel" + sqm_override: Option, }, /// Get current Stormguard statistics diff --git a/src/rust/lqos_config/src/shaped_devices/mod.rs b/src/rust/lqos_config/src/shaped_devices/mod.rs index dc8301d8..56f3d733 100644 --- a/src/rust/lqos_config/src/shaped_devices/mod.rs +++ b/src/rust/lqos_config/src/shaped_devices/mod.rs @@ -133,6 +133,9 @@ impl ConfigShapedDevices { let mut reader = ReaderBuilder::new() .comment(Some(b'#')) .trim(csv::Trim::All) + // Allow optional trailing fields like per-circuit SQM override + // without forcing all rows to match header length. + .flexible(true) .from_reader(utf8_bytes.as_slice()); // Example: StringRecord(["1", "968 Circle St., Gurnee, IL 60031", "1", "Device 1", "", "", "192.168.101.2", "", "25", "5", "10000", "10000", ""]) 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 6df79936..7ab00720 100644 --- a/src/rust/lqos_config/src/shaped_devices/shaped_device.rs +++ b/src/rust/lqos_config/src/shaped_devices/shaped_device.rs @@ -57,6 +57,12 @@ pub struct ShapedDevice { /// Generic comments field, does nothing. pub comment: String, + /// Optional per-circuit SQM override token. Strictly limited to + /// "cake" or "fq_codel" when present. Empty or missing means + /// "use global default". + #[serde(skip_serializing_if = "Option::is_none")] + pub sqm_override: Option, + /// Hash of the circuit ID, used for internal lookups. #[serde(skip)] pub circuit_hash: i64, @@ -75,7 +81,7 @@ impl ShapedDevice { /// /// This function parses a CSV record containing device configuration data and constructs /// a `ShapedDevice` with all necessary fields populated. The CSV record must contain - /// exactly 13 fields in the following order: + /// exactly 13 fields in the following order (optionally a 14th `sqm` field may be present): /// /// 1. Circuit ID /// 2. Circuit Name @@ -90,6 +96,7 @@ impl ShapedDevice { /// 11. Download Max Mbps /// 12. Upload Max Mbps /// 13. Comment + /// 14. sqm (optional; allowed values: "cake" or "fq_codel") /// /// # Arguments /// @@ -106,7 +113,8 @@ impl ShapedDevice { /// * The bandwidth values (min/max upload/download) cannot be parsed as unsigned integers /// * The CSV record doesn't contain the expected number of fields pub fn from_csv(record: &StringRecord) -> Result { - Ok(Self { + // Parse mandatory fields (first 13 entries) + let mut device = Self { circuit_id: record[0].to_string(), circuit_name: record[1].to_string(), device_id: record[2].to_string(), @@ -164,10 +172,28 @@ impl ShapedDevice { rate }, comment: record[12].to_string(), + sqm_override: None, circuit_hash: hash_to_i64(&record[0]), device_hash: hash_to_i64(&record[2]), parent_hash: hash_to_i64(&record[4]), - }) + }; + + // Optional 14th field: per-circuit SQM override token + if record.len() >= 14 { + let token = record[13].trim().to_lowercase(); + if !token.is_empty() { + match token.as_str() { + "cake" | "fq_codel" => device.sqm_override = Some(token), + other => { + return Err(ShapedDevicesError::CsvEntryParseError(format!( + "Invalid sqm override '{other}'. Allowed values: 'cake' or 'fq_codel'" + ))); + } + } + } + } + + Ok(device) } pub(crate) fn parse_cidr_v4(address: &str) -> Result<(Ipv4Addr, u32), ShapedDevicesError> { diff --git a/src/rust/lqos_python/src/lib.rs b/src/rust/lqos_python/src/lib.rs index 85f7cba7..308dd597 100644 --- a/src/rust/lqos_python/src/lib.rs +++ b/src/rust/lqos_python/src/lib.rs @@ -944,6 +944,7 @@ enum BakeryCommands { class_major: u16, up_class_major: u16, ip_addresses: String, + sqm_override: Option, }, } @@ -1028,6 +1029,7 @@ impl Bakery { class_major, up_class_major, ip_addresses, + sqm_override, } => { let command = BusRequest::BakeryAddCircuit { circuit_hash: *circuit_hash, @@ -1041,6 +1043,7 @@ impl Bakery { class_major: *class_major, up_class_major: *up_class_major, ip_addresses: ip_addresses.clone(), + sqm_override: sqm_override.clone(), }; requests.push(command); } @@ -1107,6 +1110,7 @@ impl Bakery { class_major: u16, up_class_major: u16, ip_addresses: String, + sqm_override: Option, ) -> PyResult<()> { let circuit_hash = lqos_utils::hash_to_i64(&circuit_name); //println!("Name: {circuit_name}, hash: {circuit_hash}"); @@ -1122,6 +1126,7 @@ impl Bakery { class_major, up_class_major, ip_addresses, + sqm_override, }; self.queue.push(command); Ok(()) diff --git a/src/rust/lqosd/src/main.rs b/src/rust/lqosd/src/main.rs index 9f5ffbc9..70255c70 100644 --- a/src/rust/lqosd/src/main.rs +++ b/src/rust/lqosd/src/main.rs @@ -574,7 +574,19 @@ fn handle_bus_requests(requests: &[BusRequest], responses: &mut Vec class_major, up_class_major, ip_addresses, + sqm_override, } => { + if let Some(s) = sqm_override.as_ref() { + if s.eq_ignore_ascii_case("fq_codel") { + tracing::info!( + "lqosd: Received BakeryAddCircuit with fq_codel override for circuit_hash={} (parent_class_id={}, up_parent_class_id={}, class_minor=0x{:x})", + circuit_hash, + parent_class_id.as_tc_string(), + up_parent_class_id.as_tc_string(), + class_minor + ); + } + } if let Some(sender) = lqos_bakery::BAKERY_SENDER.get() { let sender = sender.clone(); let _ = sender.send(lqos_bakery::BakeryCommands::AddCircuit { @@ -589,6 +601,7 @@ fn handle_bus_requests(requests: &[BusRequest], responses: &mut Vec class_major: class_major.clone(), up_class_major: up_class_major.clone(), ip_addresses: ip_addresses.clone(), + sqm_override: sqm_override.clone(), }); BusResponse::Ack } else { -- knotmirror 0.0.1 From 8e2b4eb6094ec2382df02e01fbed8a71e94be48a Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Fri, 31 Oct 2025 08:48:31 -0500 Subject: [PATCH 07/11] Feat: Track fq_codel stats, and display them in the web ui. --- src/rust/lqos_bus/src/bus/queue_data.rs | 4 ++ src/rust/lqos_queue_tracker/src/queue_diff.rs | 34 ++++++++++++- .../lqos_queue_tracker/src/queue_store.rs | 37 ++++++++++++-- .../src/queue_types/tc_fq_codel.rs | 48 +++++++++---------- .../src/node_manager/js_build/src/circuit.js | 17 ++++++- .../src/node_manager/static2/circuit.html | 2 +- 6 files changed, 111 insertions(+), 31 deletions(-) diff --git a/src/rust/lqos_bus/src/bus/queue_data.rs b/src/rust/lqos_bus/src/bus/queue_data.rs index 34014321..7c0fd683 100644 --- a/src/rust/lqos_bus/src/bus/queue_data.rs +++ b/src/rust/lqos_bus/src/bus/queue_data.rs @@ -15,6 +15,10 @@ pub struct QueueStoreTransit { //pub prev_upload: Option, pub current_download: CakeTransit, pub current_upload: CakeTransit, + /// Queue kind for downlink (e.g., "cake" or "fq_codel") + pub kind_down: String, + /// Queue kind for uplink (e.g., "cake" or "fq_codel") + pub kind_up: String, } #[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default, Allocative)] diff --git a/src/rust/lqos_queue_tracker/src/queue_diff.rs b/src/rust/lqos_queue_tracker/src/queue_diff.rs index 68d56a74..8e9c96a5 100644 --- a/src/rust/lqos_queue_tracker/src/queue_diff.rs +++ b/src/rust/lqos_queue_tracker/src/queue_diff.rs @@ -8,7 +8,7 @@ pub enum QueueDiff { None, // Mq, // Htb, - // FqCodel, + FqCodel(FqCodelDiff), Cake(CakeDiff), // ClsAct, } @@ -18,6 +18,13 @@ pub(crate) fn make_queue_diff( current: &QueueType, ) -> Result { match previous { + QueueType::FqCodel(..) => match current { + QueueType::FqCodel(..) => Ok(fq_codel_diff(previous, current)?), + _ => { + error!("Queue diffs are not implemented for FqCodel to {:?}", current); + Err(QueueDiffError::NotImplemented) + } + }, QueueType::Cake(..) => match current { QueueType::Cake(..) => Ok(cake_diff(previous, current)?), _ => { @@ -81,3 +88,28 @@ pub enum QueueDiffError { #[error("Not implemented")] NotImplemented, } +#[derive(Serialize, Clone, Debug)] +pub struct FqCodelDiff { + pub bytes: u64, + pub packets: u32, + pub backlog: u32, + pub flows: u16, + pub ddrops: u32, +} + +fn fq_codel_diff(previous: &QueueType, current: &QueueType) -> Result { + if let QueueType::FqCodel(prev) = previous { + if let QueueType::FqCodel(new) = current { + // Delta counters; backlog and flows are instantaneous + let diff = FqCodelDiff { + bytes: new.bytes.saturating_sub(prev.bytes), + packets: new.packets.saturating_sub(prev.packets), + backlog: new.backlog, + flows: new.options.flows, + ddrops: new.drop_overlimit.saturating_sub(prev.drop_overlimit), + }; + return Ok(QueueDiff::FqCodel(diff)); + } + } + Err(QueueDiffError::NotImplemented) +} diff --git a/src/rust/lqos_queue_tracker/src/queue_store.rs b/src/rust/lqos_queue_tracker/src/queue_store.rs index 7bfe9517..6c7e2c46 100644 --- a/src/rust/lqos_queue_tracker/src/queue_store.rs +++ b/src/rust/lqos_queue_tracker/src/queue_store.rs @@ -59,6 +59,17 @@ impl QueueStore { #[allow(clippy::from_over_into)] impl Into for QueueStore { fn into(self) -> QueueStoreTransit { + // Determine queue kinds for display + let kind_down = match &self.current_download { + QueueType::Cake(_) => "cake", + QueueType::FqCodel(_) => "fq_codel", + _ => "", + }; + let kind_up = match &self.current_upload { + QueueType::Cake(_) => "cake", + QueueType::FqCodel(_) => "fq_codel", + _ => "", + }; QueueStoreTransit { history: self .history @@ -71,6 +82,8 @@ impl Into for QueueStore { //prev_upload: self.prev_upload.map(|u| u.into()), current_download: self.current_download.into(), current_upload: self.current_upload.into(), + kind_down: kind_down.to_string(), + kind_up: kind_up.to_string(), } } } @@ -78,15 +91,31 @@ impl Into for QueueStore { #[allow(clippy::from_over_into)] impl Into for QueueDiff { fn into(self) -> CakeDiffTransit { - if let QueueDiff::Cake(c) = &self { - CakeDiffTransit { + match &self { + QueueDiff::Cake(c) => CakeDiffTransit { bytes: c.bytes, packets: c.packets, qlen: c.qlen, tins: c.tins.iter().cloned().map(|t| t.into()).collect(), + }, + QueueDiff::FqCodel(c) => { + // Map fq_codel stats into a Cake-like transit so the UI can render. + // Pad to 4 tins to match typical diffserv4 rendering assumptions in the UI. + let mut tins = Vec::with_capacity(4); + tins.push(CakeDiffTinTransit { + sent_bytes: c.bytes, + backlog_bytes: c.backlog, + drops: c.ddrops, + marks: 0, + base_delay_us: 0, + }); + // Add three zeroed tins for UI expectations + for _ in 0..3 { + tins.push(CakeDiffTinTransit::default()); + } + CakeDiffTransit { bytes: c.bytes, packets: c.packets, qlen: c.backlog, tins } } - } else { - CakeDiffTransit::default() + _ => CakeDiffTransit::default(), } } } diff --git a/src/rust/lqos_queue_tracker/src/queue_types/tc_fq_codel.rs b/src/rust/lqos_queue_tracker/src/queue_types/tc_fq_codel.rs index e6bc6cc8..f44cdca7 100644 --- a/src/rust/lqos_queue_tracker/src/queue_types/tc_fq_codel.rs +++ b/src/rust/lqos_queue_tracker/src/queue_types/tc_fq_codel.rs @@ -14,34 +14,34 @@ use tracing::info; #[derive(Default, Clone, Debug, Serialize)] pub struct TcFqCodel { - handle: TcHandle, + pub(crate) handle: TcHandle, pub(crate) parent: TcHandle, - options: TcFqCodelOptions, - bytes: u64, - packets: u32, // FIXME - for long term data we have to worry about wrapping - drops: u32, - overlimits: u32, - requeues: u32, - backlog: u32, - qlen: u32, - maxpacket: u16, - drop_overlimit: u32, - new_flow_count: u32, - ecn_mark: u32, - new_flows_len: u16, - old_flows_len: u16, + pub(crate) options: TcFqCodelOptions, + pub(crate) bytes: u64, + pub(crate) packets: u32, // FIXME - for long term data we have to worry about wrapping + pub(crate) drops: u32, + pub(crate) overlimits: u32, + pub(crate) requeues: u32, + pub(crate) backlog: u32, + pub(crate) qlen: u32, + pub(crate) maxpacket: u16, + pub(crate) drop_overlimit: u32, + pub(crate) new_flow_count: u32, + pub(crate) ecn_mark: u32, + pub(crate) new_flows_len: u16, + pub(crate) old_flows_len: u16, } #[derive(Default, Clone, Debug, Serialize)] -struct TcFqCodelOptions { - limit: u32, - flows: u16, - quantum: u16, - target: u64, // FIXME target and interval within fq_codel are scaled to ns >> 1024 - interval: u64, // tc scales them back up to us. Ideally ns would make sense throughout. - memory_limit: u32, - ecn: bool, - drop_batch: u16, // FIXME CE_threshold is presently missing from the parser +pub(crate) struct TcFqCodelOptions { + pub(crate) limit: u32, + pub(crate) flows: u16, + pub(crate) quantum: u16, + pub(crate) target: u64, // FIXME target and interval within fq_codel are scaled to ns >> 1024 + pub(crate) interval: u64, // tc scales them back up to us. Ideally ns would make sense throughout. + pub(crate) memory_limit: u32, + pub(crate) ecn: bool, + pub(crate) drop_batch: u16, // FIXME CE_threshold is presently missing from the parser } impl TcFqCodel { diff --git a/src/rust/lqosd/src/node_manager/js_build/src/circuit.js b/src/rust/lqosd/src/node_manager/js_build/src/circuit.js index 9210fe50..d30e89c8 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/circuit.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/circuit.js @@ -737,7 +737,7 @@ function subscribeToCake() { function showNoQueueMessage() { const cakeTab = document.getElementById("cake"); if (cakeTab && !hasReceivedData) { - cakeTab.innerHTML = '

Queue not loaded.

The CAKE queue for this circuit has not been created yet.

'; + cakeTab.innerHTML = '

Queue not loaded.

The shaper queue for this circuit has not been created yet.

'; } } @@ -760,6 +760,21 @@ function subscribeToCake() { // If this is the first data received, restore the original HTML structure if (!hasReceivedData) { hasReceivedData = true; + // Update the tab heading based on queue kind + try { + const kindDown = (msg.kind_down || '').toLowerCase(); + const kindUp = (msg.kind_up || '').toLowerCase(); + let displayKind = 'Shaper Overview'; + if (kindDown === 'cake' || kindUp === 'cake') { + displayKind = 'CAKE Shaper Overview'; + } else if (kindDown === 'fq_codel' || kindUp === 'fq_codel') { + displayKind = 'fq_codel Shaper Overview'; + } + const tabBtn = document.getElementById('cake-tab'); + if (tabBtn) { + tabBtn.innerHTML = ' ' + displayKind; + } + } catch (e) { /* ignore */ } const cakeTab = document.getElementById("cake"); if (cakeTab) { cakeTab.innerHTML = ` diff --git a/src/rust/lqosd/src/node_manager/static2/circuit.html b/src/rust/lqosd/src/node_manager/static2/circuit.html index cdfa4b48..c6086ba0 100644 --- a/src/rust/lqosd/src/node_manager/static2/circuit.html +++ b/src/rust/lqosd/src/node_manager/static2/circuit.html @@ -55,7 +55,7 @@ -- knotmirror 0.0.1 From 5d188d12a0ea6e68fc0336b87cd359dc45dbc0bb Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Fri, 31 Oct 2025 09:01:41 -0500 Subject: [PATCH 08/11] Feat: SQM mode "none" is now available. --- src/LibreQoS.py | 13 ++++++---- src/rust/lqos_bakery/src/commands.rs | 13 +++++++++- .../src/shaped_devices/shaped_device.rs | 2 +- .../lqos_queue_tracker/src/queue_store.rs | 4 +-- .../src/node_manager/js_build/src/circuit.js | 25 +++++++++++++------ 5 files changed, 40 insertions(+), 17 deletions(-) diff --git a/src/LibreQoS.py b/src/LibreQoS.py index 69b16f9d..8e572717 100755 --- a/src/LibreQoS.py +++ b/src/LibreQoS.py @@ -1118,6 +1118,8 @@ def refreshShapers(): if override is None or override == '': return sqmFixupRate(rate, base) ov = override.lower() + if ov == 'none': + return '' if ov == 'fq_codel': return 'fq_codel' if ov == 'cake': @@ -1126,8 +1128,9 @@ def refreshShapers(): return sqmFixupRate(rate, base) sqm_override = circuit['sqm'] if 'sqm' in circuit else None useSqm = effective_sqm_str(circuit['maxDownload'], sqm_override) - command = 'qdisc add dev ' + interface_a() + ' parent ' + circuit['classMajor'] + ':' + circuit['classMinor'] + ' ' + useSqm - linuxTCcommands.append(command) + if useSqm != '': + command = 'qdisc add dev ' + interface_a() + ' parent ' + circuit['classMajor'] + ':' + circuit['classMinor'] + ' ' + useSqm + linuxTCcommands.append(command) command = 'class add dev ' + interface_b() + ' parent ' + data[node]['up_classid'] + ' classid ' + circuit['classMinor'] + ' htb rate '+ format_rate_for_tc(min_up) + ' ceil '+ format_rate_for_tc(circuit['maxUpload']) + ' prio 3' + quantum(circuit['maxUpload']) linuxTCcommands.append(command) # Only add CAKE / fq_codel qdisc if monitorOnlyMode is Off @@ -1135,9 +1138,9 @@ def refreshShapers(): # SQM Fixup for lower rates (and per-circuit override) sqm_override = circuit['sqm'] if 'sqm' in circuit else None useSqm = effective_sqm_str(circuit['maxUpload'], sqm_override) - command = 'qdisc add dev ' + interface_b() + ' parent ' + circuit['up_classMajor'] + ':' + circuit['classMinor'] + ' ' + useSqm - linuxTCcommands.append(command) - pass + if useSqm != '': + command = 'qdisc add dev ' + interface_b() + ' parent ' + circuit['up_classMajor'] + ':' + circuit['classMinor'] + ' ' + useSqm + linuxTCcommands.append(command) for device in circuit['devices']: if device['ipv4s']: for ipv4 in device['ipv4s']: diff --git a/src/rust/lqos_bakery/src/commands.rs b/src/rust/lqos_bakery/src/commands.rs index 3e4414a7..2b00c411 100644 --- a/src/rust/lqos_bakery/src/commands.rs +++ b/src/rust/lqos_bakery/src/commands.rs @@ -601,7 +601,7 @@ impl BakeryCommands { } } let do_htb; - let do_sqm; + let mut do_sqm; if execution_mode == ExecutionMode::Builder { // In builder mode, if we're fully lazy - we don't do anything. @@ -638,6 +638,13 @@ impl BakeryCommands { } } + // If override is 'none', disable SQM regardless of lazy settings + if let Some(ref s) = params.sqm_override { + if s.eq_ignore_ascii_case("none") { + do_sqm = false; + } + } + let mut result = Vec::new(); /* bakery.add_circuit(data[node]['classid'], data[node]['up_classid'], circuit['classMinor'], format_rate_for_tc(min_down), format_rate_for_tc(min_up), format_rate_for_tc(circuit['maxDownload']), format_rate_for_tc(circuit['maxUpload']), quantum(circuit['maxDownload']), quantum(circuit['maxUpload']), circuit['classMajor'], circuit['up_classMajor'], sqmFixupRate(circuit['maxDownload'], sqm()), sqmFixupRate(circuit['maxUpload'], sqm()), tcComment) @@ -771,6 +778,7 @@ impl BakeryCommands { class_minor, class_major, up_class_major, + sqm_override, .. } = self else { @@ -805,6 +813,9 @@ impl BakeryCommands { } } + // If SQM was disabled via override, skip pruning qdisc + let prune_sqm = prune_sqm && !matches!(sqm_override.as_deref(), Some(s) if s.eq_ignore_ascii_case("none")); + if prune_sqm { // Prune the SQM qdisc if !config.on_a_stick_mode() { 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 7ab00720..8250e626 100644 --- a/src/rust/lqos_config/src/shaped_devices/shaped_device.rs +++ b/src/rust/lqos_config/src/shaped_devices/shaped_device.rs @@ -183,7 +183,7 @@ impl ShapedDevice { let token = record[13].trim().to_lowercase(); if !token.is_empty() { match token.as_str() { - "cake" | "fq_codel" => device.sqm_override = Some(token), + "cake" | "fq_codel" | "none" => device.sqm_override = Some(token), other => { return Err(ShapedDevicesError::CsvEntryParseError(format!( "Invalid sqm override '{other}'. Allowed values: 'cake' or 'fq_codel'" diff --git a/src/rust/lqos_queue_tracker/src/queue_store.rs b/src/rust/lqos_queue_tracker/src/queue_store.rs index 6c7e2c46..e5de0068 100644 --- a/src/rust/lqos_queue_tracker/src/queue_store.rs +++ b/src/rust/lqos_queue_tracker/src/queue_store.rs @@ -63,12 +63,12 @@ impl Into for QueueStore { let kind_down = match &self.current_download { QueueType::Cake(_) => "cake", QueueType::FqCodel(_) => "fq_codel", - _ => "", + _ => "none", }; let kind_up = match &self.current_upload { QueueType::Cake(_) => "cake", QueueType::FqCodel(_) => "fq_codel", - _ => "", + _ => "none", }; QueueStoreTransit { history: self diff --git a/src/rust/lqosd/src/node_manager/js_build/src/circuit.js b/src/rust/lqosd/src/node_manager/js_build/src/circuit.js index d30e89c8..bcbd5f5c 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/circuit.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/circuit.js @@ -764,15 +764,24 @@ function subscribeToCake() { try { const kindDown = (msg.kind_down || '').toLowerCase(); const kindUp = (msg.kind_up || '').toLowerCase(); - let displayKind = 'Shaper Overview'; - if (kindDown === 'cake' || kindUp === 'cake') { - displayKind = 'CAKE Shaper Overview'; - } else if (kindDown === 'fq_codel' || kindUp === 'fq_codel') { - displayKind = 'fq_codel Shaper Overview'; - } const tabBtn = document.getElementById('cake-tab'); - if (tabBtn) { - tabBtn.innerHTML = ' ' + displayKind; + const tabLi = tabBtn ? tabBtn.parentElement : null; + if (kindDown === 'none' && kindUp === 'none') { + // Hide the shaper overview tab entirely for SQM=none + if (tabLi) tabLi.style.display = 'none'; + const tabContent = document.getElementById('cake'); + if (tabContent) tabContent.style.display = 'none'; + return; // Skip building graphs + } else { + let displayKind = 'Shaper Overview'; + if (kindDown === 'cake' || kindUp === 'cake') { + displayKind = 'CAKE Shaper Overview'; + } else if (kindDown === 'fq_codel' || kindUp === 'fq_codel') { + displayKind = 'fq_codel Shaper Overview'; + } + if (tabBtn) { + tabBtn.innerHTML = ' ' + displayKind; + } } } catch (e) { /* ignore */ } const cakeTab = document.getElementById("cake"); -- knotmirror 0.0.1 From 07782ebc48f6892500f7448ba48b404ce6bb7726 Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Fri, 31 Oct 2025 09:13:03 -0500 Subject: [PATCH 09/11] Feat: The node manager UI editor lets you override the sqm column. --- .../src/shaped_devices/serializable.rs | 7 ++++++ .../js_build/src/config_devices.js | 22 ++++++++++++++++++- 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/src/rust/lqos_config/src/shaped_devices/serializable.rs b/src/rust/lqos_config/src/shaped_devices/serializable.rs index 447189f2..9703f433 100644 --- a/src/rust/lqos_config/src/shaped_devices/serializable.rs +++ b/src/rust/lqos_config/src/shaped_devices/serializable.rs @@ -19,6 +19,8 @@ pub(crate) struct SerializableShapedDevice { pub download_max_mbps: f32, pub upload_max_mbps: f32, pub comment: String, + /// Optional per-circuit SQM override: "cake", "fq_codel", or "none". Empty = default + pub sqm: String, } impl From<&ShapedDevice> for SerializableShapedDevice { @@ -37,6 +39,11 @@ impl From<&ShapedDevice> for SerializableShapedDevice { download_max_mbps: d.download_max_mbps, upload_max_mbps: d.upload_max_mbps, comment: d.comment.clone(), + sqm: d + .sqm_override + .as_ref() + .map(|s| s.to_string()) + .unwrap_or_else(|| "".to_string()), } } } diff --git a/src/rust/lqosd/src/node_manager/js_build/src/config_devices.js b/src/rust/lqosd/src/node_manager/js_build/src/config_devices.js index 9d57dfa9..432fb4c5 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/config_devices.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/config_devices.js @@ -79,6 +79,7 @@ function newSdRow() { download_max_mbps: 100, upload_max_mbps: 100, comment: "", + sqm_override: "", }); shapedDevices(); } @@ -92,7 +93,7 @@ function shapedDevices() { console.log(shaped_devices); let html = ""; html += ""; - html += ""; + html += ""; html += ""; for (var i=0; i"; + const opts = ["", "cake", "fq_codel", "none"]; // empty means default + const labels = {"": "(default)", "cake": "cake", "fq_codel": "fq_codel", "none": "none"}; + for (let k = 0; k < opts.length; k++) { + const v = opts[k]; + sqmHtml += ""; + } + sqmHtml += ""; + html += sqmHtml; html += ""; html += ""; @@ -156,6 +169,13 @@ function start() { row.download_max_mbps = parseFloat($("#" + rowPrefix(i, "download_max_mbps")).val()); row.upload_max_mbps = parseFloat($("#" + rowPrefix(i, "upload_max_mbps")).val()); row.comment = $("#" + rowPrefix(i, "comment")).val(); + const sqmSel = $("#" + rowPrefix(i, "sqm_override")).val(); + // Store empty selection as undefined (omit) to default to global setting + if (sqmSel && sqmSel.length > 0) { + row.sqm_override = sqmSel; + } else { + delete row.sqm_override; + } } saveNetworkAndDevices(network_json, shaped_devices, (success, message) => { -- knotmirror 0.0.1 From d6bfdad16a09a4b49a408b8904c88aeb2cdaee46 Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Fri, 31 Oct 2025 11:03:30 -0500 Subject: [PATCH 10/11] Feat: config_queues now features an optional setting that bumps circuits at X Mbps (default 1000) to fq_codel. --- src/LibreQoS.py | 16 ++++++++++++++-- src/rust/lqos_bakery/src/queue_math.rs | 9 ++++++++- src/rust/lqos_config/src/etc/v15/queues.rs | 4 ++++ src/rust/lqos_python/src/lib.rs | 13 +++++++++++++ .../node_manager/js_build/src/config_queues.js | 12 +++++++++++- .../src/node_manager/static2/config_queues.html | 6 ++++++ 6 files changed, 56 insertions(+), 4 deletions(-) diff --git a/src/LibreQoS.py b/src/LibreQoS.py index 8e572717..628553b4 100755 --- a/src/LibreQoS.py +++ b/src/LibreQoS.py @@ -27,6 +27,7 @@ from liblqos_python import is_lqosd_alive, clear_ip_mappings, delete_ip_mapping, interface_a, interface_b, enable_actual_shell_commands, use_bin_packing_to_balance_cpu, monitor_mode_only, \ run_shell_commands_as_sudo, generated_pn_download_mbps, generated_pn_upload_mbps, queues_available_override, \ on_a_stick, get_tree_weights, get_weights, is_network_flat, get_libreqos_directory, enable_insight_topology, \ + fast_queues_fq_codel, \ Bakery R2Q = 10 @@ -1115,9 +1116,20 @@ def refreshShapers(): # SQM Fixup for lower rates (and per-circuit override) def effective_sqm_str(rate, override): base = sqm() - if override is None or override == '': + # Treat None, empty, or falsy as no override + if not override: + # Apply fast-queue threshold: prefer fq_codel for very fast circuits when no override + try: + thresh = fast_queues_fq_codel() + except Exception: + thresh = 1000.0 + if rate >= thresh: + return 'fq_codel' return sqmFixupRate(rate, base) - ov = override.lower() + try: + ov = str(override).strip().lower() + except Exception: + ov = '' if ov == 'none': return '' if ov == 'fq_codel': diff --git a/src/rust/lqos_bakery/src/queue_math.rs b/src/rust/lqos_bakery/src/queue_math.rs index fec5815c..64215cf1 100644 --- a/src/rust/lqos_bakery/src/queue_math.rs +++ b/src/rust/lqos_bakery/src/queue_math.rs @@ -119,7 +119,14 @@ pub(crate) fn sqm_tokens_for( override_opt: &Option, ) -> Vec { match override_opt.as_deref() { - None => sqm_rate_fixup(rate, config), + None => { + // Prefer fq_codel for very fast circuits if configured + let threshold = config.queues.fast_queues_fq_codel.unwrap_or(1000.0) as f32; + if rate >= threshold { + return vec!["fq_codel".to_string()]; + } + sqm_rate_fixup(rate, config) + } Some("fq_codel") => vec!["fq_codel".to_string()], Some("cake") => { let default = &config.queues.default_sqm; diff --git a/src/rust/lqos_config/src/etc/v15/queues.rs b/src/rust/lqos_config/src/etc/v15/queues.rs index 9e671a81..9acaac8a 100644 --- a/src/rust/lqos_config/src/etc/v15/queues.rs +++ b/src/rust/lqos_config/src/etc/v15/queues.rs @@ -44,6 +44,9 @@ pub struct QueueConfig { /// Hold-off on creating lazy queues until this many bytes have been seen pub lazy_threshold_bytes: Option, + + /// Auto-change queues to fq_codel if they are greater than or equal to X Mbps. Defaults to 1000. + pub fast_queues_fq_codel: Option, } /// Lazy queue creation modes @@ -74,6 +77,7 @@ impl Default for QueueConfig { lazy_queues: None, // Default to disabled for backward compatibility lazy_expire_seconds: Some(600), // 10 minutes default lazy_threshold_bytes: None, + fast_queues_fq_codel: None, } } } diff --git a/src/rust/lqos_python/src/lib.rs b/src/rust/lqos_python/src/lib.rs index 308dd597..988b2141 100644 --- a/src/rust/lqos_python/src/lib.rs +++ b/src/rust/lqos_python/src/lib.rs @@ -38,6 +38,7 @@ fn liblqos_python(m: &Bound<'_, PyModule>) -> PyResult<()> { // Unified configuration items m.add_function(wrap_pyfunction!(check_config, m)?)?; m.add_function(wrap_pyfunction!(sqm, m)?)?; + m.add_function(wrap_pyfunction!(fast_queues_fq_codel, m)?)?; m.add_function(wrap_pyfunction!( upstream_bandwidth_capacity_download_mbps, m @@ -364,6 +365,18 @@ fn sqm() -> PyResult { Ok(config.queues.default_sqm.clone()) } +/// Returns the Mbps threshold at or above which (if no per-circuit override is set) +/// fq_codel should be preferred to reduce overhead on very fast circuits. +/// Defaults to 1000.0 Mbps if not configured. +#[pyfunction] +fn fast_queues_fq_codel() -> PyResult { + let config = lqos_config::load_config().unwrap(); + Ok(config + .queues + .fast_queues_fq_codel + .unwrap_or(1000.0) as f32) +} + #[pyfunction] fn upstream_bandwidth_capacity_download_mbps() -> PyResult { let config = lqos_config::load_config().unwrap(); diff --git a/src/rust/lqosd/src/node_manager/js_build/src/config_queues.js b/src/rust/lqosd/src/node_manager/js_build/src/config_queues.js index b880cd8d..df3080c6 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/config_queues.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/config_queues.js @@ -39,6 +39,13 @@ function validateConfig() { return false; } + // Validate fast fq_codel threshold (optional) + const fastFq = document.getElementById("fastQueuesFqCodel").value; + if (fastFq && (isNaN(fastFq) || parseFloat(fastFq) < 1)) { + alert("Fast fq_codel threshold must be a number greater than 0"); + return false; + } + return true; } @@ -58,7 +65,9 @@ function updateConfig() { use_binpacking: document.getElementById("useBinpacking").checked, lazy_queues: document.getElementById("lazyQueues").value === "No" ? null : document.getElementById("lazyQueues").value, lazy_expire_seconds: document.getElementById("lazyExpireSeconds").value ? - parseInt(document.getElementById("lazyExpireSeconds").value) : null + parseInt(document.getElementById("lazyExpireSeconds").value) : null, + fast_queues_fq_codel: document.getElementById("fastQueuesFqCodel").value ? + parseFloat(document.getElementById("fastQueuesFqCodel").value) : null }; } @@ -90,6 +99,7 @@ loadConfig(() => { // Optional numeric fields document.getElementById("overrideQueues").value = queues.override_available_queues ?? ""; document.getElementById("lazyExpireSeconds").value = queues.lazy_expire_seconds ?? ""; + document.getElementById("fastQueuesFqCodel").value = queues.fast_queues_fq_codel ?? ""; // Add save button click handler document.getElementById('saveButton').addEventListener('click', () => { diff --git a/src/rust/lqosd/src/node_manager/static2/config_queues.html b/src/rust/lqosd/src/node_manager/static2/config_queues.html index e46d08f3..6dabc1df 100644 --- a/src/rust/lqosd/src/node_manager/static2/config_queues.html +++ b/src/rust/lqosd/src/node_manager/static2/config_queues.html @@ -30,6 +30,12 @@
Total downstream bandwidth capacity
+
+ + +
If unset, defaults to 1000. For circuits with download >= this rate, fq_codel is preferred when no per-circuit override is set.
+
+
-- knotmirror 0.0.1 From 2fb7f972706f50b4229083a0895a28f395e9e5a4 Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Sat, 1 Nov 2025 08:45:14 -0500 Subject: [PATCH 11/11] Feat: You can now specify down/up sqm in ShapedDevices.csv - e.g. `cake/fq_codel` or `none/cake`. The default remains cake, and single entries (`cake`, `fq_codel`, `none` still apply to both directions). --- src/INTEGRATION_HOWTO.md | 30 ++++ src/LibreQoS.py | 45 ++++-- src/ShapedDevices.example.csv | 13 ++ src/lqos.example | 3 + src/rust/lqos_bakery/src/commands.rs | 131 ++++++++++++------ .../src/shaped_devices/shaped_device.rs | 40 +++++- .../js_build/src/config_devices.js | 52 +++++-- 7 files changed, 233 insertions(+), 81 deletions(-) diff --git a/src/INTEGRATION_HOWTO.md b/src/INTEGRATION_HOWTO.md index bd74fe70..2847b639 100644 --- a/src/INTEGRATION_HOWTO.md +++ b/src/INTEGRATION_HOWTO.md @@ -148,5 +148,35 @@ You can also add a call to `net.plotNetworkGraph(False)` (use `True` to also inc ![](testdata/network_new.png) +### Per‑Circuit SQM Overrides (Download/Upload) + +LibreQoS supports optional per‑circuit SQM overrides via the last column (`sqm`) of `ShapedDevices.csv`. + +- Accepted values: + - Single token: `cake`, `fq_codel`, or `none` (applies to both directions) + - Directional: `down/up` where each side is one of `cake`, `fq_codel`, `none`, or empty +- Directional semantics: + - Left token is download, right token is upload (e.g., `cake/fq_codel`) + - Either side may be empty to leave that direction at default (e.g., `cake/` or `/fq_codel`) + - `none` disables the SQM qdisc for that direction +- Normalization: Values are trimmed and lower‑cased; case is ignored on load +- Defaults and fast‑queues: If a side is unspecified (empty) or the entire field is empty, the global default SQM applies for that side. The “fast queues to fq_codel” threshold is evaluated per direction when no explicit override is set. + +Examples: + +``` +# Both directions cake +...,cake + +# Download cake, upload fq_codel +...,cake/fq_codel + +# Download explicit (fq_codel), upload default +...,fq_codel/ + +# Disable upload SQM only +...,/none +``` + ## Longest Prefix Match Tip You could theoretically throttle all unknown IPs until they are associated with a client. For example, you could limit every unknown to 1.5x0.5 with single entry in ShapedDevices.csv, until you associate them with an account. IPs need to be non-exact matches. So you can't have two 192.168.1.1 entries, but you can have a 192.168.1.0/24 subnet and a 192.168.1.2/32 - they aren't duplicates, and the LPM search is smart enough to pick the most exact match. diff --git a/src/LibreQoS.py b/src/LibreQoS.py index 628553b4..6bd3b577 100755 --- a/src/LibreQoS.py +++ b/src/LibreQoS.py @@ -396,7 +396,15 @@ def loadSubscriberCircuits(shapedDevicesFile): # Optional per-circuit SQM override in last column sqm_override_token = '' if len(row) > 13: - sqm_override_token = row[13].strip().lower() + # Normalize: lowercase, trim, collapse spaces around '/' + raw_token = row[13] + token = raw_token.strip().lower() + if '/' in token: + parts = token.split('/', 1) + left = parts[0].strip() + right = parts[1].strip() + token = left + '/' + right + sqm_override_token = token circuitID, circuitName, deviceID, deviceName, ParentNode, mac, ipv4_input, ipv6_input, downloadMin, uploadMin, downloadMax, uploadMax, comment = row[0:13] # If in monitorOnlyMode, override bandwidth rates to where no shaping will actually occur if monitor_mode_only() == True: @@ -1114,11 +1122,24 @@ def refreshShapers(): # Only add CAKE / fq_codel qdisc if monitorOnlyMode is Off if monitor_mode_only() == False: # SQM Fixup for lower rates (and per-circuit override) - def effective_sqm_str(rate, override): + def effective_sqm_str(rate, override, direction): base = sqm() - # Treat None, empty, or falsy as no override - if not override: - # Apply fast-queue threshold: prefer fq_codel for very fast circuits when no override + # Resolve per-direction token from override string + chosen = None + if override: + try: + ov = str(override).strip().lower() + if '/' in ov: + left, right = ov.split('/', 1) + left = left.strip() + right = right.strip() + chosen = left if direction == 'down' else right + else: + chosen = ov + except Exception: + chosen = None + # If no explicit token for this direction, use default behavior + if not chosen: try: thresh = fast_queues_fq_codel() except Exception: @@ -1126,20 +1147,16 @@ def refreshShapers(): if rate >= thresh: return 'fq_codel' return sqmFixupRate(rate, base) - try: - ov = str(override).strip().lower() - except Exception: - ov = '' - if ov == 'none': + if chosen == 'none': return '' - if ov == 'fq_codel': + if chosen == 'fq_codel': return 'fq_codel' - if ov == 'cake': + if chosen == 'cake': cake_base = base if base.startswith('cake') else 'cake diffserv4' return sqmFixupRate(rate, cake_base) return sqmFixupRate(rate, base) sqm_override = circuit['sqm'] if 'sqm' in circuit else None - useSqm = effective_sqm_str(circuit['maxDownload'], sqm_override) + useSqm = effective_sqm_str(circuit['maxDownload'], sqm_override, 'down') if useSqm != '': command = 'qdisc add dev ' + interface_a() + ' parent ' + circuit['classMajor'] + ':' + circuit['classMinor'] + ' ' + useSqm linuxTCcommands.append(command) @@ -1149,7 +1166,7 @@ def refreshShapers(): if monitor_mode_only() == False: # SQM Fixup for lower rates (and per-circuit override) sqm_override = circuit['sqm'] if 'sqm' in circuit else None - useSqm = effective_sqm_str(circuit['maxUpload'], sqm_override) + useSqm = effective_sqm_str(circuit['maxUpload'], sqm_override, 'up') if useSqm != '': command = 'qdisc add dev ' + interface_b() + ' parent ' + circuit['up_classMajor'] + ':' + circuit['classMinor'] + ' ' + useSqm linuxTCcommands.append(command) diff --git a/src/ShapedDevices.example.csv b/src/ShapedDevices.example.csv index 6ef04f3c..3e4149e2 100644 --- a/src/ShapedDevices.example.csv +++ b/src/ShapedDevices.example.csv @@ -16,11 +16,24 @@ # # Backward Compatibility: Existing integer rates continue to work unchanged. # +# Per‑Circuit SQM Override (last column `sqm`): +# - Accepts: "cake", "fq_codel", "none" or directional form "down/up". +# - Directional form: left token applies to download, right to upload. Either side may be empty +# to indicate no override for that direction (e.g., "cake/" or "/fq_codel"). +# - Case is ignored on load; values are normalized to trimmed, lowercase. +# - "none" on a side disables the SQM qdisc for that direction. +# - When a side is unspecified (empty) or the entire field is empty, LibreQoS uses the global +# default SQM for that side and still applies the fast‑queue threshold (fq_codel) per direction. +# 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,sqm 1,"968 Circle St., Gurnee, IL 60031",1,Device 1,AP_A,,"100.64.0.1, 100.64.0.14",fdd7:b724:0:100::/56,1,1,155,20,Standard integer rates, 2,"31 Marconi Street, Lake In The Hills, IL 60156",2,Device 2,AP_A,,100.64.0.2,fdd7:b724:0:200::/56,0.5,0.5,2.5,1.0,Fractional rate example - small plan,fq_codel 3,"255 NW. Newport Ave., Jamestown, NY 14701",3,Device 3,AP_9,,100.64.0.3,fdd7:b724:0:300::/56,1.25,0.75,10.5,5.25,Fractional rate example - medium plan, 4,"8493 Campfire Street, Peabody, MA 01960",4,Device 4,AP_9,,100.64.0.4,fdd7:b724:0:400::/56,25.5,12.5,100.5,50.25,Fractional rate example - large plan,cake +10,"Directional SQM example",12,Device 12,AP_1,,100.64.0.12,,50,20,200,50,Down=cake, Up=fq_codel,cake/fq_codel +11,"Partial override example (down only)",13,Device 13,AP_1,,100.64.0.13,,50,20,200,50,Down=cake, Up=default,cake/ +12,"Partial override example (up only)",14,Device 14,AP_1,,100.64.0.14,,50,20,200,50,Down=default, Up=fq_codel,/fq_codel +13,"Disable upload SQM",15,Device 15,AP_1,,100.64.0.15,,50,20,200,50,Down=default, Up=none,/none 2794,"6 Littleton Drive, Ringgold, GA 30736",5,Device 5,AP_11,,100.64.0.5,fdd7:b724:0:500::/56,1,1,105,18,Standard integer rates, 2794,"6 Littleton Drive, Ringgold, GA 30736",6,Device 6,AP_11,,100.64.0.6,fdd7:b724:0:600::/56,1,1,105,18,Standard integer rates, 5,"93 Oklahoma Ave., Parsippany, NJ 07054",7,Device 7,AP_1,,100.64.0.7,fdd7:b724:0:700::/56,2.0,2.0,25.0,10.0,Mixed decimal rates, diff --git a/src/lqos.example b/src/lqos.example index 72bd97ab..5eaee483 100644 --- a/src/lqos.example +++ b/src/lqos.example @@ -28,6 +28,9 @@ to_network = "eth1" #network_vlan = 3 [queues] +# Global default SQM is a single token list applied to both directions. +# Per-circuit overrides in ShapedDevices.csv may specify directional tokens +# as "down/up" (see ShapedDevices.example.csv and INTEGRATION_HOWTO.md). default_sqm = "cake diffserv4" monitor_only = false uplink_bandwidth_mbps = 100000 diff --git a/src/rust/lqos_bakery/src/commands.rs b/src/rust/lqos_bakery/src/commands.rs index 2b00c411..6ccb2474 100644 --- a/src/rust/lqos_bakery/src/commands.rs +++ b/src/rust/lqos_bakery/src/commands.rs @@ -638,12 +638,26 @@ impl BakeryCommands { } } - // If override is 'none', disable SQM regardless of lazy settings - if let Some(ref s) = params.sqm_override { - if s.eq_ignore_ascii_case("none") { - do_sqm = false; + // Parse per-direction override tokens: single token applies to both; + // directional form is "down/up" with either side optionally empty. + let (down_override_opt, up_override_opt) = (|| -> (Option, Option) { + match ¶ms.sqm_override { + None => (None, None), + Some(s) => { + if s.contains('/') { + let mut it = s.splitn(2, '/'); + let down = it.next().unwrap_or("").trim(); + let up = it.next().unwrap_or("").trim(); + let map = |t: &str| -> Option { + if t.is_empty() { None } else { Some(t.to_string()) } + }; + (map(down), map(up)) + } else { + (Some(s.clone()), Some(s.clone())) + } + } } - } + })(); let mut result = Vec::new(); /* @@ -691,20 +705,22 @@ impl BakeryCommands { ]); } if !config.queues.monitor_only && do_sqm { - let mut sqm_command = vec![ - "qdisc".to_string(), - "replace".to_string(), - "dev".to_string(), - config.isp_interface(), - "parent".to_string(), - format!("0x{:x}:0x{:x}", params.class_major, params.class_minor), - ]; - sqm_command.extend(sqm_tokens_for( - params.download_bandwidth_max, - config, - ¶ms.sqm_override, - )); - result.push(sqm_command); + if !matches!(down_override_opt.as_deref(), Some(s) if s.eq_ignore_ascii_case("none")) { + let mut sqm_command = vec![ + "qdisc".to_string(), + "replace".to_string(), + "dev".to_string(), + config.isp_interface(), + "parent".to_string(), + format!("0x{:x}:0x{:x}", params.class_major, params.class_minor), + ]; + sqm_command.extend(sqm_tokens_for( + params.download_bandwidth_max, + config, + &down_override_opt, + )); + result.push(sqm_command); + } } if do_htb { @@ -733,20 +749,24 @@ impl BakeryCommands { } if !config.queues.monitor_only && do_sqm { - let mut sqm_command = vec![ - "qdisc".to_string(), - "replace".to_string(), - "dev".to_string(), - config.internet_interface(), - "parent".to_string(), - format!("0x{:x}:0x{:x}", params.up_class_major, params.class_minor), - ]; - sqm_command.extend(sqm_tokens_for( - params.upload_bandwidth_max, - config, - ¶ms.sqm_override, - )); - result.push(sqm_command); + if !config.on_a_stick_mode() { + if !matches!(up_override_opt.as_deref(), Some(s) if s.eq_ignore_ascii_case("none")) { + let mut sqm_command = vec![ + "qdisc".to_string(), + "replace".to_string(), + "dev".to_string(), + config.internet_interface(), + "parent".to_string(), + format!("0x{:x}:0x{:x}", params.up_class_major, params.class_minor), + ]; + sqm_command.extend(sqm_tokens_for( + params.upload_bandwidth_max, + config, + &up_override_opt, + )); + result.push(sqm_command); + } + } } Some(result) @@ -813,12 +833,29 @@ impl BakeryCommands { } } - // If SQM was disabled via override, skip pruning qdisc - let prune_sqm = prune_sqm && !matches!(sqm_override.as_deref(), Some(s) if s.eq_ignore_ascii_case("none")); - if prune_sqm { - // Prune the SQM qdisc - if !config.on_a_stick_mode() { + // Determine per-direction pruning based on override tokens + let (down_override_opt, up_override_opt) = match sqm_override.as_ref() { + None => (None, None), + Some(s) => { + if s.contains('/') { + let mut it = s.splitn(2, '/'); + let down = it.next().unwrap_or("").trim(); + let up = it.next().unwrap_or("").trim(); + let map = |t: &str| -> Option { + if t.is_empty() { None } else { Some(t.to_string()) } + }; + (map(down), map(up)) + } else { + (Some(s.clone()), Some(s.clone())) + } + } + }; + + let prune_down = !matches!(down_override_opt.as_deref(), Some(s) if s.eq_ignore_ascii_case("none")); + let prune_up = !matches!(up_override_opt.as_deref(), Some(s) if s.eq_ignore_ascii_case("none")); + + if prune_up && !config.on_a_stick_mode() { result.push(vec![ "qdisc".to_string(), "del".to_string(), @@ -828,14 +865,16 @@ impl BakeryCommands { format!("0x{:x}:0x{:x}", up_class_major, class_minor), ]); } - result.push(vec![ - "qdisc".to_string(), - "del".to_string(), - "dev".to_string(), - config.isp_interface(), - "parent".to_string(), - format!("0x{:x}:0x{:x}", class_major, class_minor), - ]); + if prune_down { + result.push(vec![ + "qdisc".to_string(), + "del".to_string(), + "dev".to_string(), + config.isp_interface(), + "parent".to_string(), + format!("0x{:x}:0x{:x}", class_major, class_minor), + ]); + } } if prune_htb { 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 8250e626..1b162522 100644 --- a/src/rust/lqos_config/src/shaped_devices/shaped_device.rs +++ b/src/rust/lqos_config/src/shaped_devices/shaped_device.rs @@ -96,7 +96,10 @@ impl ShapedDevice { /// 11. Download Max Mbps /// 12. Upload Max Mbps /// 13. Comment - /// 14. sqm (optional; allowed values: "cake" or "fq_codel") + /// 14. sqm (optional; allowed values: "cake", "fq_codel", "none", or + /// a directional override in the form "down/up". Either side may be + /// empty to indicate no override for that direction, e.g. "cake/" or + /// "/fq_codel".) /// /// # Arguments /// @@ -180,15 +183,38 @@ impl ShapedDevice { // Optional 14th field: per-circuit SQM override token if record.len() >= 14 { - let token = record[13].trim().to_lowercase(); - if !token.is_empty() { - match token.as_str() { - "cake" | "fq_codel" | "none" => device.sqm_override = Some(token), - other => { + let raw = record[13].trim(); + if !raw.is_empty() { + // Normalize case and whitespace around optional '/' + let token = raw.to_lowercase(); + if token.contains('/') { + // Directional override: down/up (either may be empty) + let mut parts = token.splitn(2, '/'); + let down = parts.next().unwrap_or("").trim(); + let up = parts.next().unwrap_or("").trim(); + + // Validate each side if present + let valid = |s: &str| -> bool { + matches!(s, "" | "cake" | "fq_codel" | "none") + }; + if !valid(down) || !valid(up) { return Err(ShapedDevicesError::CsvEntryParseError(format!( - "Invalid sqm override '{other}'. Allowed values: 'cake' or 'fq_codel'" + "Invalid directional sqm override '{token}'. Allowed: 'cake', 'fq_codel', 'none', or down/up" ))); } + + // Store normalized (trimmed, lowercase) representation exactly as down/up + device.sqm_override = Some(format!("{down}/{up}")); + } else { + // Single token applies to both directions when used + match token.as_str() { + "cake" | "fq_codel" | "none" => device.sqm_override = Some(token), + other => { + return Err(ShapedDevicesError::CsvEntryParseError(format!( + "Invalid sqm override '{other}'. Allowed values: 'cake', 'fq_codel', 'none', or down/up" + ))); + } + } } } } diff --git a/src/rust/lqosd/src/node_manager/js_build/src/config_devices.js b/src/rust/lqosd/src/node_manager/js_build/src/config_devices.js index 432fb4c5..37d0ef03 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/config_devices.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/config_devices.js @@ -91,9 +91,12 @@ function deleteSdRow(id) { function shapedDevices() { console.log(shaped_devices); - let html = "
Circuit IDCircuit NameDevice IDDevice NameParent NodeMACIPv4IPv6Download MinUpload MinDownload MaxUpload MaxComment
Circuit IDCircuit NameDevice IDDevice NameParent NodeMACIPv4IPv6Download MinUpload MinDownload MaxUpload MaxCommentSQM
"; + let html = "
" + + "SQM overrides can be set per direction. Leave a side blank to use the global default; set to 'none' to disable that side." + + "
"; + html += "
"; html += ""; - html += ""; + html += ""; html += ""; for (var i=0; i"; + // SQM override dropdowns (optional, per direction) + const overrideRaw = (row.sqm_override || "").toLowerCase(); + let downSel = "", upSel = ""; + if (overrideRaw.indexOf('/') !== -1) { + const parts = overrideRaw.split('/') + downSel = (parts[0] || "").trim(); + upSel = (parts[1] || "").trim(); + } else if (overrideRaw.length > 0) { + downSel = overrideRaw; + upSel = overrideRaw; + } const opts = ["", "cake", "fq_codel", "none"]; // empty means default const labels = {"": "(default)", "cake": "cake", "fq_codel": "fq_codel", "none": "none"}; + // Down + let sqmDownHtml = ""; + html += sqmDownHtml; + // Up + let sqmUpHtml = ""; - html += sqmHtml; + sqmUpHtml += ""; + html += sqmUpHtml; html += ""; html += ""; @@ -169,12 +191,14 @@ function start() { row.download_max_mbps = parseFloat($("#" + rowPrefix(i, "download_max_mbps")).val()); row.upload_max_mbps = parseFloat($("#" + rowPrefix(i, "upload_max_mbps")).val()); row.comment = $("#" + rowPrefix(i, "comment")).val(); - const sqmSel = $("#" + rowPrefix(i, "sqm_override")).val(); - // Store empty selection as undefined (omit) to default to global setting - if (sqmSel && sqmSel.length > 0) { - row.sqm_override = sqmSel; + const sqmDown = $("#" + rowPrefix(i, "sqm_override_down")).val().trim().toLowerCase(); + const sqmUp = $("#" + rowPrefix(i, "sqm_override_up")).val().trim().toLowerCase(); + // Compose normalized token string: trimmed, lowercase + if (!sqmDown && !sqmUp) { + delete row.sqm_override; // default behavior } else { - delete row.sqm_override; + // Allow partial overrides; keep slash even if one side empty + row.sqm_override = `${sqmDown}/${sqmUp}`; } }
Circuit IDCircuit NameDevice IDDevice NameParent NodeMACIPv4IPv6Download MinUpload MinDownload MaxUpload MaxCommentSQM
Circuit IDCircuit NameDevice IDDevice NameParent NodeMACIPv4IPv6Download MinUpload MinDownload MaxUpload MaxCommentSQM DownSQM Up
"; + sqmDownHtml += ""; + sqmUpHtml += "