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/58] 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/58] 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/58] 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/58] 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/58] 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/58] 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/58] 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/58] 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/58] 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 c371b2ab6005638f82484b730ce4902bd1345c8a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Robert=20Chac=C3=B3n?= Date: Fri, 31 Oct 2025 14:13:27 -0600 Subject: [PATCH 11/58] Create variables.md --- docs/variables.md | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 docs/variables.md diff --git a/docs/variables.md b/docs/variables.md new file mode 100644 index 00000000..04a86a76 --- /dev/null +++ b/docs/variables.md @@ -0,0 +1,2 @@ +```{eval-rst} +.. |deb_url_v1.5| replace:: https://download.libreqos.com/libreqos_1.5-RC2.202510052233-1_amd64.deb -- knotmirror 0.0.1 From 03f985975a18279f4b27f6347753e29eb8e84fad Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Robert=20Chac=C3=B3n?= Date: Fri, 31 Oct 2025 14:14:17 -0600 Subject: [PATCH 12/58] Update quickstart.md --- docs/v2.0/quickstart.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/v2.0/quickstart.md b/docs/v2.0/quickstart.md index d1040c7b..bedd4a28 100644 --- a/docs/v2.0/quickstart.md +++ b/docs/v2.0/quickstart.md @@ -19,8 +19,8 @@ cd ~ sudo apt-get update sudo apt-get upgrade -wget https://download.libreqos.com/libreqos_1.5-RC2.202510052233-1_amd64.deb -sudo apt install ./libreqos_1.5-RC2.202510052233-1_amd64.deb +wget |deb_url_v1.5| +sudo apt install ./|deb_url_v1.5| ``` ### Git Install (For Developers Only - Not Recommended) -- knotmirror 0.0.1 From 9c0211efb5c368ac543c28879485779f8ef143e6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Robert=20Chac=C3=B3n?= Date: Fri, 31 Oct 2025 14:16:43 -0600 Subject: [PATCH 13/58] Update conf.py --- conf.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/conf.py b/conf.py index 7d97a361..bcb8afcb 100644 --- a/conf.py +++ b/conf.py @@ -13,7 +13,7 @@ author = "Zach Biles" # -- General configuration --------------------------------------------------- # https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration -extensions = ["myst_parser"] +extensions = ["myst_parser","replacements"] templates_path = ["_templates"] exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"] -- knotmirror 0.0.1 From f48786a5e680a3a957f07485a0dd0453872fa74d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Robert=20Chac=C3=B3n?= Date: Fri, 31 Oct 2025 14:17:49 -0600 Subject: [PATCH 14/58] Update quickstart.md --- docs/v2.0/quickstart.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/v2.0/quickstart.md b/docs/v2.0/quickstart.md index bedd4a28..88102152 100644 --- a/docs/v2.0/quickstart.md +++ b/docs/v2.0/quickstart.md @@ -19,8 +19,8 @@ cd ~ sudo apt-get update sudo apt-get upgrade -wget |deb_url_v1.5| -sudo apt install ./|deb_url_v1.5| +wget {{ deb_url_v1.5 }} +sudo apt install ./{{ deb_url_v1.5 }} ``` ### Git Install (For Developers Only - Not Recommended) -- knotmirror 0.0.1 From a0826edc7df14d9ed02aacd045c45cc9aa77c8d6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Robert=20Chac=C3=B3n?= Date: Fri, 31 Oct 2025 14:18:59 -0600 Subject: [PATCH 15/58] Update conf.py --- conf.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/conf.py b/conf.py index bcb8afcb..7d97a361 100644 --- a/conf.py +++ b/conf.py @@ -13,7 +13,7 @@ author = "Zach Biles" # -- General configuration --------------------------------------------------- # https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration -extensions = ["myst_parser","replacements"] +extensions = ["myst_parser"] templates_path = ["_templates"] exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"] -- knotmirror 0.0.1 From e2986556bc2b3494945e48ab23dce2d0c2014053 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Robert=20Chac=C3=B3n?= Date: Fri, 31 Oct 2025 14:20:09 -0600 Subject: [PATCH 16/58] Delete docs/variables.md --- docs/variables.md | 2 -- 1 file changed, 2 deletions(-) delete mode 100644 docs/variables.md diff --git a/docs/variables.md b/docs/variables.md deleted file mode 100644 index 04a86a76..00000000 --- a/docs/variables.md +++ /dev/null @@ -1,2 +0,0 @@ -```{eval-rst} -.. |deb_url_v1.5| replace:: https://download.libreqos.com/libreqos_1.5-RC2.202510052233-1_amd64.deb -- knotmirror 0.0.1 From 59cd486b2156104a541971603ae1d1ff29b85329 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Robert=20Chac=C3=B3n?= Date: Fri, 31 Oct 2025 14:20:27 -0600 Subject: [PATCH 17/58] Update conf.py --- conf.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/conf.py b/conf.py index 7d97a361..43edb08a 100644 --- a/conf.py +++ b/conf.py @@ -23,3 +23,7 @@ exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"] html_theme = "sphinx_rtd_theme" html_static_path = ["_static"] + +rst_epilog = """ +.. |deb_url_v1_5| replace:: https://download.libreqos.com/libreqos_1.5-RC2.202510052233-1_amd64.deb +""" -- knotmirror 0.0.1 From 4facc050f729cd8afe77e000b13087e88f242183 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Robert=20Chac=C3=B3n?= Date: Fri, 31 Oct 2025 14:21:04 -0600 Subject: [PATCH 18/58] Update quickstart.md --- docs/v2.0/quickstart.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/v2.0/quickstart.md b/docs/v2.0/quickstart.md index 88102152..cadc19e7 100644 --- a/docs/v2.0/quickstart.md +++ b/docs/v2.0/quickstart.md @@ -19,8 +19,8 @@ cd ~ sudo apt-get update sudo apt-get upgrade -wget {{ deb_url_v1.5 }} -sudo apt install ./{{ deb_url_v1.5 }} +wget |deb_url_v1_5| +sudo apt install ./|deb_url_v1_5| ``` ### Git Install (For Developers Only - Not Recommended) -- knotmirror 0.0.1 From ccc1f791fdc5f7754750f4179419fd299c065a8f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Robert=20Chac=C3=B3n?= Date: Fri, 31 Oct 2025 14:23:42 -0600 Subject: [PATCH 19/58] Update conf.py --- conf.py | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/conf.py b/conf.py index 43edb08a..d9b77531 100644 --- a/conf.py +++ b/conf.py @@ -15,6 +15,10 @@ author = "Zach Biles" extensions = ["myst_parser"] +myst_enable_extensions = [ + 'substitution' +] + templates_path = ["_templates"] exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"] @@ -24,6 +28,6 @@ exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"] html_theme = "sphinx_rtd_theme" html_static_path = ["_static"] -rst_epilog = """ -.. |deb_url_v1_5| replace:: https://download.libreqos.com/libreqos_1.5-RC2.202510052233-1_amd64.deb -""" +myst_substitutions = { + 'deb_url_v1_5': 'https://download.libreqos.com/libreqos_1.5-RC2.202510052233-1_amd64.deb' +} -- knotmirror 0.0.1 From 76565a43413fa7fb02c538d3b924ad4931101ebe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Robert=20Chac=C3=B3n?= Date: Fri, 31 Oct 2025 14:24:03 -0600 Subject: [PATCH 20/58] Update quickstart.md --- docs/v2.0/quickstart.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/v2.0/quickstart.md b/docs/v2.0/quickstart.md index cadc19e7..35058b7a 100644 --- a/docs/v2.0/quickstart.md +++ b/docs/v2.0/quickstart.md @@ -19,8 +19,8 @@ cd ~ sudo apt-get update sudo apt-get upgrade -wget |deb_url_v1_5| -sudo apt install ./|deb_url_v1_5| +wget {{deb_url_v1_5}} +sudo apt install ./{{deb_url_v1_5}} ``` ### Git Install (For Developers Only - Not Recommended) -- knotmirror 0.0.1 From fc4bd1bd48e628cf689db528b6b780a174359b3d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Robert=20Chac=C3=B3n?= Date: Fri, 31 Oct 2025 14:29:45 -0600 Subject: [PATCH 21/58] Update conf.py --- conf.py | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/conf.py b/conf.py index d9b77531..a1040526 100644 --- a/conf.py +++ b/conf.py @@ -28,6 +28,16 @@ exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"] html_theme = "sphinx_rtd_theme" html_static_path = ["_static"] -myst_substitutions = { - 'deb_url_v1_5': 'https://download.libreqos.com/libreqos_1.5-RC2.202510052233-1_amd64.deb' +def ultimateReplace(app, docname, source): + result = source[0] + for key in app.config.ultimate_replacements: + result = result.replace(key, app.config.ultimate_replacements[key]) + source[0] = result + +ultimate_replacements = { + "{deb_url_v1_5}" : "https://download.libreqos.com/libreqos_1.5-RC2.202510052233-1_amd64.deb" } + +def setup(app): + app.add_config_value('ultimate_replacements', {}, True) + app.connect('source-read', ultimateReplace) -- knotmirror 0.0.1 From 191e8d97e9dc0c6a78574705a44c46f80a4e71c5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Robert=20Chac=C3=B3n?= Date: Fri, 31 Oct 2025 14:30:59 -0600 Subject: [PATCH 22/58] Update quickstart.md --- docs/v2.0/quickstart.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/v2.0/quickstart.md b/docs/v2.0/quickstart.md index 35058b7a..aa4c5a9b 100644 --- a/docs/v2.0/quickstart.md +++ b/docs/v2.0/quickstart.md @@ -19,8 +19,8 @@ cd ~ sudo apt-get update sudo apt-get upgrade -wget {{deb_url_v1_5}} -sudo apt install ./{{deb_url_v1_5}} +wget {deb_url_v1_5} +sudo apt install ./{deb_url_v1_5} ``` ### Git Install (For Developers Only - Not Recommended) -- knotmirror 0.0.1 From 7478e3782c073d4aec79807d50b87a3363fd0e88 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Robert=20Chac=C3=B3n?= Date: Fri, 31 Oct 2025 14:31:19 -0600 Subject: [PATCH 23/58] Update quickstart-es.md --- docs-es/v2.0/quickstart-es.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs-es/v2.0/quickstart-es.md b/docs-es/v2.0/quickstart-es.md index 15df0d5d..a70a630b 100644 --- a/docs-es/v2.0/quickstart-es.md +++ b/docs-es/v2.0/quickstart-es.md @@ -19,8 +19,8 @@ cd ~ sudo apt-get update sudo apt-get upgrade -wget https://download.libreqos.com/libreqos_1.5-RC2.202510052233-1_amd64.deb -sudo apt install ./libreqos_1.5-RC2.202510052233-1_amd64.deb +wget {deb_url_v1_5} +sudo apt install ./{deb_url_v1_5} ``` ### Instalación con Git (Solo para Desarrolladores - No Recomendado) -- knotmirror 0.0.1 From ff2ab11dc7f15c478b9b3dd84bef4d4a665fae9d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Robert=20Chac=C3=B3n?= Date: Fri, 31 Oct 2025 14:32:55 -0600 Subject: [PATCH 24/58] Update conf.py --- conf.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/conf.py b/conf.py index a1040526..10e071d4 100644 --- a/conf.py +++ b/conf.py @@ -6,9 +6,12 @@ # -- Project information ----------------------------------------------------- # https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information +import datetime +year = datetime.date.today().year + project = "LibreQoE" -copyright = "2024, LibreQoE, LLC" -author = "Zach Biles" +copyright = str(year) + ", LibreQoE, LLC" +author = "LibreQoE, LLC" # -- General configuration --------------------------------------------------- # https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration -- knotmirror 0.0.1 From b974fb0fcab4804912bfceaa9ee1e270a4295121 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Robert=20Chac=C3=B3n?= Date: Fri, 31 Oct 2025 14:35:30 -0600 Subject: [PATCH 25/58] Update conf.py --- docs-es/conf.py | 30 +++++++++++++++++++++++++----- 1 file changed, 25 insertions(+), 5 deletions(-) diff --git a/docs-es/conf.py b/docs-es/conf.py index 2a77e4fb..4931d3e6 100644 --- a/docs-es/conf.py +++ b/docs-es/conf.py @@ -6,16 +6,22 @@ # -- Project information ----------------------------------------------------- # https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information -project = "LibreQoS" -copyright = "2024, LibreQoE, LLC" -author = "Zach Biles" -release = "2.0" +import datetime +year = datetime.date.today().year + +project = "LibreQoE" +copyright = str(year) + ", LibreQoE, LLC" +author = "LibreQoE, LLC" # -- General configuration --------------------------------------------------- # https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration extensions = ["myst_parser"] +myst_enable_extensions = [ + 'substitution' +] + templates_path = ["_templates"] exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"] @@ -39,4 +45,18 @@ html_theme_options = { 'sticky_navigation': True, 'includehidden': True, 'titles_only': False -} \ No newline at end of file +} + +def ultimateReplace(app, docname, source): + result = source[0] + for key in app.config.ultimate_replacements: + result = result.replace(key, app.config.ultimate_replacements[key]) + source[0] = result + +ultimate_replacements = { + "{deb_url_v1_5}" : "https://download.libreqos.com/libreqos_1.5-RC2.202510052233-1_amd64.deb" +} + +def setup(app): + app.add_config_value('ultimate_replacements', {}, True) + app.connect('source-read', ultimateReplace) -- knotmirror 0.0.1 From 801ca0d8c50083b8bf29a4ecf7feb91bbf1188f9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Robert=20Chac=C3=B3n?= Date: Fri, 31 Oct 2025 14:36:48 -0600 Subject: [PATCH 26/58] Update conf.py --- docs-es/conf.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs-es/conf.py b/docs-es/conf.py index 4931d3e6..e47eb31a 100644 --- a/docs-es/conf.py +++ b/docs-es/conf.py @@ -54,7 +54,7 @@ def ultimateReplace(app, docname, source): source[0] = result ultimate_replacements = { - "{deb_url_v1_5}" : "https://download.libreqos.com/libreqos_1.5-RC2.202510052233-1_amd64.deb" + "{deb_url_v1_5}" : "libreqos_1.5-RC2.202510052233-1_amd64.deb" } def setup(app): -- knotmirror 0.0.1 From a339d2d09edaf034cfec91cf2b166e550f6f82c0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Robert=20Chac=C3=B3n?= Date: Fri, 31 Oct 2025 14:37:06 -0600 Subject: [PATCH 27/58] Update conf.py --- conf.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/conf.py b/conf.py index 10e071d4..44b34399 100644 --- a/conf.py +++ b/conf.py @@ -38,7 +38,7 @@ def ultimateReplace(app, docname, source): source[0] = result ultimate_replacements = { - "{deb_url_v1_5}" : "https://download.libreqos.com/libreqos_1.5-RC2.202510052233-1_amd64.deb" + "{deb_url_v1_5}" : "libreqos_1.5-RC2.202510052233-1_amd64.deb" } def setup(app): -- knotmirror 0.0.1 From dc8985ba37ec958a0b7bbf78d9e8e70339dc6e2a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Robert=20Chac=C3=B3n?= Date: Fri, 31 Oct 2025 14:37:30 -0600 Subject: [PATCH 28/58] Update quickstart.md --- docs/v2.0/quickstart.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/v2.0/quickstart.md b/docs/v2.0/quickstart.md index aa4c5a9b..13f2eb81 100644 --- a/docs/v2.0/quickstart.md +++ b/docs/v2.0/quickstart.md @@ -19,7 +19,7 @@ cd ~ sudo apt-get update sudo apt-get upgrade -wget {deb_url_v1_5} +wget https://download.libreqos.com/{deb_url_v1_5} sudo apt install ./{deb_url_v1_5} ``` -- knotmirror 0.0.1 From 36e0a0792f83b0f2f8aba8d52af176719754df1c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Robert=20Chac=C3=B3n?= Date: Fri, 31 Oct 2025 14:37:47 -0600 Subject: [PATCH 29/58] Update quickstart-es.md --- docs-es/v2.0/quickstart-es.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs-es/v2.0/quickstart-es.md b/docs-es/v2.0/quickstart-es.md index a70a630b..4b7a0c4a 100644 --- a/docs-es/v2.0/quickstart-es.md +++ b/docs-es/v2.0/quickstart-es.md @@ -19,7 +19,7 @@ cd ~ sudo apt-get update sudo apt-get upgrade -wget {deb_url_v1_5} +wget https://download.libreqos.com/{deb_url_v1_5} sudo apt install ./{deb_url_v1_5} ``` -- knotmirror 0.0.1 From 8d93f8ad5ad24ef0965b39b5e5083169b06a44a8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Robert=20Chac=C3=B3n?= Date: Fri, 31 Oct 2025 14:39:47 -0600 Subject: [PATCH 30/58] Update update.md --- docs-es/v2.0/Updates/update.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs-es/v2.0/Updates/update.md b/docs-es/v2.0/Updates/update.md index e026798c..4788d27b 100644 --- a/docs-es/v2.0/Updates/update.md +++ b/docs-es/v2.0/Updates/update.md @@ -10,8 +10,8 @@ Si usa el puente XDP, el tráfico dejará de pasar brevemente a través del puen cd ~ sudo apt-get update sudo apt-get upgrade -wget https://download.libreqos.com/libreqos_1.5-RC2.202510052233-1_amd64.deb -sudo apt install ./libreqos_1.5-RC2.202510052233-1_amd64.deb +wget https://download.libreqos.com/{deb_url_v1_5} +sudo apt install ./{deb_url_v1_5} sudo systemctl restart lqosd lqos_scheduler ``` -- knotmirror 0.0.1 From 8054dfcac4853d6f25f2bf0ddbd9e97d5f637f94 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Robert=20Chac=C3=B3n?= Date: Fri, 31 Oct 2025 14:40:06 -0600 Subject: [PATCH 31/58] Update update.md --- docs/v2.0/update.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/v2.0/update.md b/docs/v2.0/update.md index 08ed9cd6..ef4c8d3e 100644 --- a/docs/v2.0/update.md +++ b/docs/v2.0/update.md @@ -10,8 +10,8 @@ If you use the XDP bridge, traffic will briefly stop passing through the bridge cd ~ sudo apt-get update sudo apt-get upgrade -wget https://download.libreqos.com/libreqos_1.5-RC2.202510052233-1_amd64.deb -sudo apt install ./libreqos_1.5-RC2.202510052233-1_amd64.deb +wget https://download.libreqos.com/{deb_url_v1_5} +sudo apt install ./{deb_url_v1_5} sudo systemctl restart lqosd lqos_scheduler ``` -- 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 32/58] 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}`; } } -- knotmirror 0.0.1 From e1362779300237194d992a1b4805c1b7c783d35f Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Wed, 5 Nov 2025 12:18:44 -0600 Subject: [PATCH 33/58] Fix: Entering 0 for download or upload (or both) in network.json will no longer effectively crash the queue creation system. Instead, it'll emit a warning and use the default queue bandwidth. Added guardrails to avoid Nanmbps ever appearing. --- src/LibreQoS.py | 94 ++++++++++++++++++++++++++ src/rust/lqos_bakery/src/queue_math.rs | 49 +++++++++++--- 2 files changed, 134 insertions(+), 9 deletions(-) diff --git a/src/LibreQoS.py b/src/LibreQoS.py index 6bd3b577..f02ba0ec 100755 --- a/src/LibreQoS.py +++ b/src/LibreQoS.py @@ -591,6 +591,38 @@ def refreshShapers(): with open(networkJSONfile, 'r') as j: network = json.loads(j.read()) + # Normalize any zero or missing bandwidths in the network model early + # Some users may specify 0 for site bandwidths. HTB requires positive + # rates, so bump zeros to the parent/default capacity and log a warning. + def fix_zero_bandwidths(data, parentMaxDL, parentMaxUL): + for node in data: + if isinstance(node, str): + if (isinstance(data[node], dict)) and (node != 'children'): + # Ensure max bandwidths are positive. If 0 or missing, use parent's defaults. + dl = data[node].get('downloadBandwidthMbps', None) + ul = data[node].get('uploadBandwidthMbps', None) + + if dl is None or (isinstance(dl, (int, float)) and dl <= 0): + logging.warning(f"Node '{node}' has downloadBandwidthMbps set to 0 or missing; using parent/default {parentMaxDL} Mbps.") + data[node]['downloadBandwidthMbps'] = parentMaxDL + if ul is None or (isinstance(ul, (int, float)) and ul <= 0): + logging.warning(f"Node '{node}' has uploadBandwidthMbps set to 0 or missing; using parent/default {parentMaxUL} Mbps.") + data[node]['uploadBandwidthMbps'] = parentMaxUL + + # Recurse into children with this node's maxima as the new parent defaults + if 'children' in data[node]: + fix_zero_bandwidths( + data[node]['children'], + data[node]['downloadBandwidthMbps'], + data[node]['uploadBandwidthMbps'], + ) + + fix_zero_bandwidths( + network, + upstream_bandwidth_capacity_download_mbps(), + upstream_bandwidth_capacity_upload_mbps(), + ) + # Pull rx/tx queues / CPU cores available # Handling the case when the number of queues for interfaces are different @@ -711,6 +743,47 @@ def refreshShapers(): # 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()) + # Ensure site-level minimums are strictly below maximums for HTB classes + def ensure_min_less_than_max(data): + for node in data: + if isinstance(node, str): + if (isinstance(data[node], dict)) and (node != 'children'): + try: + dl_max = float(data[node].get('downloadBandwidthMbps', 0)) + ul_max = float(data[node].get('uploadBandwidthMbps', 0)) + dl_min = float(data[node].get('downloadBandwidthMbpsMin', dl_max)) + ul_min = float(data[node].get('uploadBandwidthMbpsMin', ul_max)) + except Exception: + # If parsing fails, skip adjustment for this node + dl_max = data[node].get('downloadBandwidthMbps', 0) + ul_max = data[node].get('uploadBandwidthMbps', 0) + dl_min = data[node].get('downloadBandwidthMbpsMin', dl_max) + ul_min = data[node].get('uploadBandwidthMbpsMin', ul_max) + + def adjust(min_v, max_v): + # Keep min strictly lower than max; support small max with fractional step + if min_v >= max_v: + if max_v >= 1.0: + return max_v - 1.0 + else: + return max(0.01, max_v - 0.01) + return min_v + + new_dl_min = adjust(dl_min, dl_max) + new_ul_min = adjust(ul_min, ul_max) + if new_dl_min != dl_min: + # Too noisy in practice; keep as debug for diagnostics + logging.debug(f"Node '{node}' min download ({dl_min}) >= max ({dl_max}); lowering min to {new_dl_min}") + data[node]['downloadBandwidthMbpsMin'] = new_dl_min + if new_ul_min != ul_min: + # Too noisy in practice; keep as debug for diagnostics + logging.debug(f"Node '{node}' min upload ({ul_min}) >= max ({ul_max}); lowering min to {new_ul_min}") + data[node]['uploadBandwidthMbpsMin'] = new_ul_min + if 'children' in data[node]: + ensure_min_less_than_max(data[node]['children']) + + ensure_min_less_than_max(network) + # Compress network.json. HTB only supports 8 levels of HTB depth. Compress to 8 layers if beyond 8. def flattenB(data): newDict = {} @@ -1083,6 +1156,27 @@ def refreshShapers(): min_down = 0.01 if min_up == 1: min_up = 0.01 + # Ensure min < max for circuits as well + try: + max_down = float(circuit['maxDownload']) + max_up = float(circuit['maxUpload']) + md = float(min_down) + mu = float(min_up) + except Exception: + max_down = circuit['maxDownload'] + max_up = circuit['maxUpload'] + md = min_down + mu = min_up + if md >= max_down: + new_md = (max_down - 1.0) if max_down >= 1.0 else max(0.01, max_down - 0.01) + # Too noisy in practice; keep as debug for diagnostics + logging.debug(f"Circuit '{circuit.get('circuitID','unknown')}' min download ({md}) >= max ({max_down}); lowering min to {new_md}") + min_down = new_md + if mu >= max_up: + new_mu = (max_up - 1.0) if max_up >= 1.0 else max(0.01, max_up - 0.01) + # Too noisy in practice; keep as debug for diagnostics + logging.debug(f"Circuit '{circuit.get('circuitID','unknown')}' min upload ({mu}) >= max ({max_up}); lowering min to {new_mu}") + min_up = new_mu # Generate TC commands to be executed later tcComment = " # CircuitID: " + circuit['circuitID'] + " DeviceIDs: " for device in circuit['devices']: diff --git a/src/rust/lqos_bakery/src/queue_math.rs b/src/rust/lqos_bakery/src/queue_math.rs index 64215cf1..12fbe7ab 100644 --- a/src/rust/lqos_bakery/src/queue_math.rs +++ b/src/rust/lqos_bakery/src/queue_math.rs @@ -1,4 +1,5 @@ use std::sync::Arc; +use tracing::warn; pub(crate) fn sqm_as_vec(config: &Arc) -> Vec { config @@ -24,16 +25,46 @@ pub(crate) fn format_rate_for_tc(rate: u64) -> String { } pub(crate) fn format_rate_for_tc_f32(rate: f32) -> String { - // 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 >= 1000.0 { - format!("{:.1}gbit", rate as f64 / 1000.0) - } else if rate >= 1.0 { - format!("{:.1}mbit", rate as f64) + // Defensive formatting of a rate in Mbps for TC commands with smart unit selection. + // Guards against NaN/Inf/negative/zero and clamps to sane bounds so `tc` always + // receives a positive, finite value. + + // Lower bound: 0.01 Mbps (10 kbit) to avoid "0kbit" or rounding to zero. + const MIN_RATE_MBPS: f32 = 0.01; + // Upper bound: 10,000,000 Mbps (10 Tbps) — arbitrary but sane cap to avoid infinities. + const MAX_RATE_MBPS: f32 = 10_000_000.0; + + let mut r = rate; + + // Handle NaN/Inf + if !r.is_finite() { + warn!("format_rate_for_tc_f32: non-finite rate detected ({:?}); clamping to {} Mbps", rate, MIN_RATE_MBPS); + r = MIN_RATE_MBPS; + } + + // Clamp to bounds + if r < MIN_RATE_MBPS { + warn!( + "format_rate_for_tc_f32: rate below minimum ({:?}); clamping to {} Mbps", + r, MIN_RATE_MBPS + ); + r = MIN_RATE_MBPS; + } else if r > MAX_RATE_MBPS { + warn!( + "format_rate_for_tc_f32: rate above maximum ({:?}); clamping to {} Mbps", + r, MAX_RATE_MBPS + ); + r = MAX_RATE_MBPS; + } + + // Format using thresholds + if r >= 1000.0 { + format!("{:.1}gbit", r as f64 / 1000.0) + } else if r >= 1.0 { + format!("{:.1}mbit", r as f64) } else { - format!("{:.0}kbit", rate as f64 * 1000.0) + // < 1 Mbps: kbit, whole number to match tc expectations + format!("{:.0}kbit", r as f64 * 1000.0) } } -- knotmirror 0.0.1 From f9c679208fbd55b1875103666668c2b1609ad24b Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Wed, 5 Nov 2025 12:29:12 -0600 Subject: [PATCH 34/58] Fix: Increase control channel timeout. --- src/rust/lqosd/src/lts2_sys/control_channel.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/rust/lqosd/src/lts2_sys/control_channel.rs b/src/rust/lqosd/src/lts2_sys/control_channel.rs index 27a24cdf..f5c56892 100644 --- a/src/rust/lqosd/src/lts2_sys/control_channel.rs +++ b/src/rust/lqosd/src/lts2_sys/control_channel.rs @@ -120,7 +120,7 @@ async fn control_channel_loop(mut builder: ControlChannelBuilder) -> Result<()> Ok(()) } -const TCP_TIMEOUT: Duration = Duration::from_secs(10); +const TCP_TIMEOUT: Duration = Duration::from_secs(30); // Prevent unbounded growth while waiting for Welcome const MAX_PENDING_CHATBOT_MESSAGES: usize = 256; -- knotmirror 0.0.1 From d496dca586deb1bfd5ebca4ca757d843234e79c9 Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Wed, 5 Nov 2025 13:02:41 -0600 Subject: [PATCH 35/58] Fix: Htb mode for the bakery is a lot more strict about order of operations. --- src/rust/lqos_bakery/src/lib.rs | 43 ++++++++++++++++++++++++++++++--- 1 file changed, 40 insertions(+), 3 deletions(-) diff --git a/src/rust/lqos_bakery/src/lib.rs b/src/rust/lqos_bakery/src/lib.rs index bca43ce3..837e91ba 100644 --- a/src/rust/lqos_bakery/src/lib.rs +++ b/src/rust/lqos_bakery/src/lib.rs @@ -197,6 +197,9 @@ pub static ACTIVE_CIRCUITS: AtomicUsize = AtomicUsize::new(0); /// Message Queue sender for the bakery pub static BAKERY_SENDER: OnceLock> = OnceLock::new(); static MQ_CREATED: AtomicBool = AtomicBool::new(false); +/// Indicates that at least one command batch has been processed and applied. +/// Used to avoid racing live activation against initial class creation. +static FIRST_COMMIT_APPLIED: AtomicBool = AtomicBool::new(false); /// Starts the Bakery system, returning a channel sender for sending commands to the Bakery. pub fn start_bakery() -> anyhow::Result> { @@ -1051,6 +1054,16 @@ fn handle_circuit_activity( _ => {} } + // Defer live activation until MQ and at least one commit has fully applied. + if !MQ_CREATED.load(Ordering::Relaxed) || !FIRST_COMMIT_APPLIED.load(Ordering::Relaxed) { + debug!( + "Skipping live activation: MQ_CREATED={}, FIRST_COMMIT_APPLIED={}", + MQ_CREATED.load(Ordering::Relaxed), + FIRST_COMMIT_APPLIED.load(Ordering::Relaxed) + ); + return; + } + let mut commands = Vec::new(); for circuit_id in circuit_ids { if let Some(circuit) = live_circuits.get_mut(&circuit_id) { @@ -1059,9 +1072,30 @@ fn handle_circuit_activity( } if let Some(command) = circuits.get(&circuit_id) { - let Some(cmd) = command.to_commands(&config, ExecutionMode::LiveUpdate) else { - continue; - }; + // On first activation, ensure HTB exists in HTB-lazy mode by prepending + // Builder-mode HTB class creation (idempotent via "class replace"). + let mut cmd = Vec::new(); + match config.queues.lazy_queues.as_ref() { + Some(LazyQueueMode::Htb) => { + if let Some(builder_cmds) = command.to_commands(&config, ExecutionMode::Builder) { + cmd.extend(builder_cmds); + } + if let Some(live_cmds) = command.to_commands(&config, ExecutionMode::LiveUpdate) { + cmd.extend(live_cmds); + } + if cmd.is_empty() { + // No commands to apply for this circuit + continue; + } + } + _ => { + // Full lazy mode handles both HTB and SQM in LiveUpdate; or other modes + let Some(live_cmds) = command.to_commands(&config, ExecutionMode::LiveUpdate) else { + continue; + }; + cmd.extend(live_cmds); + } + } live_circuits.insert(circuit_id, current_timestamp()); commands.extend(cmd); } @@ -1308,4 +1342,7 @@ fn process_batch( let path = Path::new(&config.lqos_directory).join("linux_tc_rust.txt"); write_command_file(&path, &commands); execute_in_memory(&commands, "processing batch"); + + // Mark that at least one batch has been applied, unblocking live activation. + FIRST_COMMIT_APPLIED.store(true, Ordering::Relaxed); } -- knotmirror 0.0.1 From a3b2ef4ae5196062bd3d2084fc25f6eb2f26059b Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Thu, 6 Nov 2025 09:24:55 -0600 Subject: [PATCH 36/58] Feat: New binpacking algorithm, aiming for fewer changes over time (reduced reload churn). --- .gitignore | 1 + src/LibreQoS.py | 259 ++++++++++++++++++++++++++++++++++++++-------- src/README.md | 4 + src/build_dpkg.sh | 6 +- 4 files changed, 223 insertions(+), 47 deletions(-) diff --git a/.gitignore b/.gitignore index c670003c..c32041b0 100644 --- a/.gitignore +++ b/.gitignore @@ -141,3 +141,4 @@ src/bin/lqos_api /src/linux_tc_rust.txt /src/linux_tc_rust_live.txt /src/linux_tc_rust_prune.txt +/src/planner_state.json diff --git a/src/LibreQoS.py b/src/LibreQoS.py index f02ba0ec..97a28638 100755 --- a/src/LibreQoS.py +++ b/src/LibreQoS.py @@ -18,7 +18,7 @@ import psutil import argparse import logging import shutil -import binpacking +import time from deepdiff import DeepDiff from liblqos_python import is_lqosd_alive, clear_ip_mappings, delete_ip_mapping, validate_shaped_devices, \ @@ -665,29 +665,110 @@ def refreshShapers(): } 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") + print("Using internal planner to sort circuits by CPU core") + # Build item list with weights for circuits lacking a ParentNode + items = [] + try: + weights = get_weights() + except Exception as e: + warnings.warn("get_weights() failed; defaulting to equal weights (" + str(e) + ")", stacklevel=2) + weights = None + weight_by_circuit_id = {} + if weights is not None: + try: + for w in weights: + weight_by_circuit_id[str(w.circuit_id)] = float(w.weight) + except Exception: + pass + for circuit in subscriberCircuits: + if circuit.get('ParentNode') == 'none' and 'idForCircuitsWithoutParentNodes' in circuit: + item_id = circuit['idForCircuitsWithoutParentNodes'] + # Prefer provided weights; default to 1.0 + w = dictForCircuitsWithoutParentNodes.get(item_id, 1.0) + # If a specific circuit weight exists, prefer it + if 'circuitID' in circuit and str(circuit['circuitID']) in weight_by_circuit_id: + w = weight_by_circuit_id[str(circuit['circuitID'])] + items.append({"id": item_id, "weight": float(w)}) + + # Prepare bins and capacities + bins_list = [{"id": pn} for pn in generatedPNs] + capacities = {pn: 1.0 for pn in generatedPNs} + + # Load planner state + try: + import bin_planner + except ImportError: + bin_planner = None + # Store planner state directly in lqos_directory (no hidden subdirs) + state_path = os.path.join(get_libreqos_directory(), "planner_state.json") + state = {} + if bin_planner is not None: + state = bin_planner.load_state(state_path) + now_ts = time.time() + prev_assign = {} + last_change_ts = {} + if isinstance(state, dict): + prev_assign = state.get("assignments", {}) or {} + last_change_ts = state.get("last_change_ts", {}) or {} + # Filter previous assignments to only items/bins in this context + item_ids = {str(it["id"]) for it in items} + valid_bins = set(capacities.keys()) + prev_assign = {iid: b for iid, b in prev_assign.items() if iid in item_ids and b in valid_bins} + last_change_ts = {iid: last_change_ts.get(iid, 0.0) for iid in item_ids} + + # Planner parameters + params = { + "candidate_set_size": 4, + "headroom": 0.05, + "alpha": 0.1, + "hysteresis_threshold": 0.03, + "cooldown_seconds": 3600, + "move_budget_per_run": max(1, min(32, int(0.01 * max(1, len(items))))), + "salt": state.get("salt", "default_salt") if isinstance(state, dict) else "default_salt", + "last_change_ts_by_item": last_change_ts, + } + if monitor_mode_only() == True: + params["move_budget_per_run"] = 0 + + if bin_planner is not None: + assignments, changed = bin_planner.plan_assignments( + items, bins_list, capacities, prev_assign, now_ts, params + ) + else: + # Fallback to simple greedy if planner unavailable + bin_loads = {pn: 0.0 for pn in generatedPNs} + pairs = [(str(it["id"]), float(it["weight"])) for it in items] + pairs.sort(key=lambda iw: (-iw[1], str(iw[0]))) + assignments = {} + for item_id, w in pairs: + target_pn = min(bin_loads.items(), key=lambda kv: (kv[1], kv[0]))[0] + assignments[item_id] = target_pn + bin_loads[target_pn] += w + changed = list(assignments.keys()) + + # Apply assignments to circuits + for circuit in subscriberCircuits: + if circuit.get('ParentNode') == 'none' and 'idForCircuitsWithoutParentNodes' in circuit: + item_id = circuit['idForCircuitsWithoutParentNodes'] + if item_id in assignments: + circuit['ParentNode'] = assignments[item_id] + + # Update and save state + if bin_planner is not None and isinstance(state, dict): + if state.get("salt") is None: + state["salt"] = "default_salt" + if "assignments" not in state or not isinstance(state["assignments"], dict): + state["assignments"] = {} + if "last_change_ts" not in state or not isinstance(state["last_change_ts"], dict): + state["last_change_ts"] = {} + for iid, b in assignments.items(): + # record last change time if changed + if iid in changed: + state["last_change_ts"][iid] = now_ts + state["assignments"][iid] = b + bin_planner.save_state(state_path, state) + + print("Finished planning generated parent nodes") else: genPNcounter = 0 for circuit in subscriberCircuits: @@ -1008,21 +1089,87 @@ def refreshShapers(): 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 + print("Planner is enabled, so we're going to sort your network across CPU queues.") + # Build items from top-level nodes with weights + items = [] 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) + weights = get_tree_weights() + except Exception as e: + warnings.warn("get_tree_weights() failed; defaulting to equal weights (" + str(e) + ")", stacklevel=2) + weights = None + weight_by_name = {} + if weights is not None: + try: + for w in weights: + weight_by_name[str(w.name)] = float(w.weight) + except Exception: + pass + for node in network: + w = weight_by_name.get(str(node), 1.0) + items.append({"id": str(node), "weight": float(w)}) + + # Prepare bins and capacities + cpu_keys = ["CpueQueue" + str(cpu) for cpu in range(queuesAvailable)] + bins_list = [{"id": key} for key in cpu_keys] + capacities = {key: 1.0 for key in cpu_keys} + + # Load planner state + try: + import bin_planner + except ImportError: + bin_planner = None + # Store planner state directly in lqos_directory (no hidden subdirs) + state_path = os.path.join(get_libreqos_directory(), "planner_state.json") + state = {} + if bin_planner is not None: + state = bin_planner.load_state(state_path) + now_ts = time.time() + prev_assign = {} + last_change_ts = {} + if isinstance(state, dict): + prev_assign = state.get("assignments", {}) or {} + last_change_ts = state.get("last_change_ts", {}) or {} + item_ids = {str(it["id"]) for it in items} + valid_bins = set(capacities.keys()) + prev_assign = {iid: b for iid, b in prev_assign.items() if iid in item_ids and b in valid_bins} + last_change_ts = {iid: last_change_ts.get(iid, 0.0) for iid in item_ids} + + params = { + "candidate_set_size": 4, + "headroom": 0.05, + "alpha": 0.1, + "hysteresis_threshold": 0.03, + "cooldown_seconds": 3600, + "move_budget_per_run": max(1, min(32, int(0.01 * max(1, len(items))))), + "salt": state.get("salt", "default_salt") if isinstance(state, dict) else "default_salt", + "last_change_ts_by_item": last_change_ts, + } + if monitor_mode_only() == True: + params["move_budget_per_run"] = 0 + + if bin_planner is not None: + assignment, changed = bin_planner.plan_assignments( + items, bins_list, capacities, prev_assign, now_ts, params + ) + else: + # Fallback to simple greedy if planner unavailable + bin_loads = {key: 0.0 for key in cpu_keys} + pairs = [(str(it["id"]), float(it["weight"])) for it in items] + pairs.sort(key=lambda nw: (-nw[1], nw[0])) + assignment = {} + for name, w in pairs: + target = min(bin_loads.items(), key=lambda kv: (kv[1], kv[0]))[0] + assignment[name] = target + bin_loads[target] += w + changed = list(assignment.keys()) + for x in range(queuesAvailable): - print("Bin " + str(x) + " = ", bins[x]) + key = "CpueQueue" + str(x) + assigned = [name for name, tgt in assignment.items() if tgt == key] + print("Bin " + str(x) + " = ", assigned) + + # Build the binned network structure binnedNetwork = {} for cpu in range(queuesAvailable): cpuKey = "CpueQueue" + str(cpu) @@ -1036,16 +1183,26 @@ def refreshShapers(): '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] + tgt = assignment.get(node) + if tgt is None: + tgt = "CpueQueue" + str(queuesAvailable - 1) + binnedNetwork[tgt]['children'][node] = network[node] network = binnedNetwork + # Update and save state + if bin_planner is not None and isinstance(state, dict): + if state.get("salt") is None: + state["salt"] = "default_salt" + if "assignments" not in state or not isinstance(state["assignments"], dict): + state["assignments"] = {} + if "last_change_ts" not in state or not isinstance(state["last_change_ts"], dict): + state["last_change_ts"] = {} + for iid, b in assignment.items(): + if iid in changed: + state["last_change_ts"][iid] = now_ts + state["assignments"][iid] = b + bin_planner.save_state(state_path, state) + # 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()) @@ -1535,9 +1692,23 @@ if __name__ == '__main__': help="Clear ip filters, qdiscs, and xdp setup if any", action=argparse.BooleanOptionalAction, ) + parser.add_argument( + '--planner-reset', + help="Delete planner state file before running", + action=argparse.BooleanOptionalAction, + ) args = parser.parse_args() logging.basicConfig(level=args.loglevel) + if getattr(args, 'planner_reset', False): + try: + state_path = os.path.join(get_libreqos_directory(), "planner_state.json") + if os.path.exists(state_path): + os.remove(state_path) + print(f"Removed planner state: {state_path}") + except Exception as e: + print(f"Warning: could not remove planner state: {e}") + if args.validate: status = validateNetworkAndDevices() elif args.clearrules: diff --git a/src/README.md b/src/README.md index 965f51ca..b85aeee4 100644 --- a/src/README.md +++ b/src/README.md @@ -3,3 +3,7 @@ ![image](https://i0.wp.com/libreqos.io/wp-content/uploads/2023/01/v1.4-alpha-2.png?w=3664&ssl=1) See [wiki here](https://github.com/LibreQoE/LibreQoS/wiki/v1.4) + +## Planner (binpacking replacement) + +LibreQoS now uses an internal planner for assigning circuits and nodes to CPU queues and generated parent nodes. The planner favors stable, stateful assignments to minimize churn and reduce rebuilds, replacing the previous external binpacking dependency. diff --git a/src/build_dpkg.sh b/src/build_dpkg.sh index 401f0e10..f0167bb0 100755 --- a/src/build_dpkg.sh +++ b/src/build_dpkg.sh @@ -113,9 +113,9 @@ pushd /opt/libreqos PIP_BREAK_SYSTEM_PACKAGES=1 python3 -m pip install -r src/requirements.txt sudo PIP_BREAK_SYSTEM_PACKAGES=1 python3 -m pip install -r src/requirements.txt # - Setup Python dependencies as a post-install task - handle issue with packages on Ubuntu Server 24.04 -sudo PIP_BREAK_SYSTEM_PACKAGES=1 pip uninstall binpacking apscheduler deepdiff --yes -PIP_BREAK_SYSTEM_PACKAGES=1 pip uninstall binpacking apscheduler deepdiff --yes -sudo PIP_BREAK_SYSTEM_PACKAGES=1 pip install binpacking apscheduler deepdiff +sudo PIP_BREAK_SYSTEM_PACKAGES=1 pip uninstall apscheduler deepdiff --yes +PIP_BREAK_SYSTEM_PACKAGES=1 pip uninstall apscheduler deepdiff --yes +sudo PIP_BREAK_SYSTEM_PACKAGES=1 pip install apscheduler deepdiff # Ensure folder permissions are correct post-install sudo chown -R $USER /opt/libreqos -- knotmirror 0.0.1 From 3d28df9714c4fc772d30ef05a7a1406c39a551f2 Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Thu, 6 Nov 2025 11:49:33 -0600 Subject: [PATCH 37/58] Feat: UI for viewing CPU affinity. --- .../src/node_manager/js_build/esbuild.sh | 2 +- .../node_manager/js_build/src/cpu_weights.js | 288 +++++++++++ src/rust/lqosd/src/node_manager/local_api.rs | 14 + .../node_manager/local_api/cpu_affinity.rs | 466 ++++++++++++++++++ .../src/node_manager/static2/cpu_weights.html | 50 ++ .../src/node_manager/static2/template.html | 6 + .../lqosd/src/node_manager/static_pages.rs | 1 + 7 files changed, 826 insertions(+), 1 deletion(-) create mode 100644 src/rust/lqosd/src/node_manager/js_build/src/cpu_weights.js create mode 100644 src/rust/lqosd/src/node_manager/local_api/cpu_affinity.rs create mode 100644 src/rust/lqosd/src/node_manager/static2/cpu_weights.html diff --git a/src/rust/lqosd/src/node_manager/js_build/esbuild.sh b/src/rust/lqosd/src/node_manager/js_build/esbuild.sh index 88ceb596..32e763c8 100755 --- a/src/rust/lqosd/src/node_manager/js_build/esbuild.sh +++ b/src/rust/lqosd/src/node_manager/js_build/esbuild.sh @@ -1,6 +1,6 @@ #!/bin/bash set -e -scripts=( index.js template.js login.js first-run.js shaped-devices.js tree.js help.js unknown-ips.js configuration.js circuit.js flow_map.js all_tree_sankey.js asn_explorer.js lts_trial.js config_general.js config_tuning.js config_queues.js config_stormguard.js config_lts.js config_iprange.js config_flows.js config_integration.js config_spylnx.js config_netzur.js config_uisp.js config_powercode.js config_sonar.js config_interface.js config_network.js config_devices.js config_users.js config_wispgate.js chatbot.js) +scripts=( index.js template.js login.js first-run.js shaped-devices.js tree.js help.js unknown-ips.js configuration.js circuit.js flow_map.js all_tree_sankey.js asn_explorer.js lts_trial.js config_general.js config_tuning.js config_queues.js config_stormguard.js config_lts.js config_iprange.js config_flows.js config_integration.js config_spylnx.js config_netzur.js config_uisp.js config_powercode.js config_sonar.js config_interface.js config_network.js config_devices.js config_users.js config_wispgate.js chatbot.js cpu_weights.js) for script in "${scripts[@]}" do echo "Building {$script}" diff --git a/src/rust/lqosd/src/node_manager/js_build/src/cpu_weights.js b/src/rust/lqosd/src/node_manager/js_build/src/cpu_weights.js new file mode 100644 index 00000000..6d2c311a --- /dev/null +++ b/src/rust/lqosd/src/node_manager/js_build/src/cpu_weights.js @@ -0,0 +1,288 @@ +import { clearDiv, theading, simpleRow, simpleRowHtml, enableTooltips } from "./helpers/builders"; +import { DashboardGraph } from "./graphs/dashboard_graph"; + +let state = { + selectedCpu: null, + direction: "down", + page: 1, + pageSize: 50, + plannerEnabled: null, +}; + +let dlMaxPie = null; // dashboard-graph wrapped chart for DL Max distribution + +function fmtMbps(x) { + if (x === null || x === undefined) return "-"; + // keep up to 2 decimals, trim trailing zeros + let s = Number(x).toFixed(2); + s = s.replace(/\.00$/, ""); + return s; +} + +function renderSummary(data) { + const target = document.getElementById("cpuSummary"); + clearDiv(target); + if (!data || !Array.isArray(data) || data.length === 0) { + target.innerHTML = '

No queue structure found. Run LibreQoS to generate queuingStructure.json.

'; + return; + } + + // Update binpacking badge in header bar + const badge = document.getElementById('binpackBadge'); + const enabled = !!state.plannerEnabled; + if (badge) { + badge.className = `badge ${enabled ? 'bg-success' : 'bg-secondary'}`; + badge.textContent = enabled ? "Binpacking: Enabled" : "Binpacking: Disabled"; + } + // Optional Insight promo below summary + if (!window.hasInsight) { + const promo = document.createElement("div"); + promo.className = "text-muted small mb-2"; + promo.innerHTML = `Enable Insight to make binpacking smarter with historical and recent data.`; + target.appendChild(promo); + } + + // Build a row with table (left) and chart (right) + const row = document.createElement('div'); + row.className = 'row'; + const left = document.createElement('div'); + left.className = 'col-12 col-lg-8'; + const right = document.createElement('div'); + right.className = 'col-12 col-lg-4'; + + const table = document.createElement("table"); + table.classList.add("table", "table-striped", "table-sm"); + const thead = document.createElement("thead"); + thead.appendChild(theading("CPU")); + thead.appendChild(theading("DL Circuits")); + thead.appendChild(theading("DL Min (Mbps)")); + thead.appendChild(theading("DL Max (Mbps)")); + thead.appendChild(theading("Actions")); + table.appendChild(thead); + const tbody = document.createElement("tbody"); + + // helper to build a centered cell + const centerCell = (text) => { + const td = simpleRow(String(text)); + td.classList.add('text-center'); + return td; + }; + + data.forEach((row) => { + const tr = document.createElement("tr"); + tr.appendChild(centerCell(row.cpu)); + tr.appendChild(centerCell(row.download.circuits)); + tr.appendChild(centerCell(fmtMbps(row.download.min_sum_mbps))); + tr.appendChild(centerCell(fmtMbps(row.download.max_sum_mbps))); + + const actions = document.createElement("td"); + actions.classList.add('text-center'); + const downBtn = document.createElement("button"); + downBtn.className = "btn btn-sm btn-outline-primary me-1"; + downBtn.innerHTML = " View"; + downBtn.onclick = () => { + state.selectedCpu = row.cpu; + state.direction = "down"; + state.page = 1; + renderDetailsHeader(); + fetchCircuits(); + }; + + actions.appendChild(downBtn); + tr.appendChild(actions); + tbody.appendChild(tr); + }); + + table.appendChild(tbody); + left.appendChild(table); + + // Right column pie chart (DL Max per CPU) + const chartDiv = document.createElement('div'); + chartDiv.id = 'cpuDlMaxPie'; + chartDiv.style.width = '100%'; + chartDiv.style.height = '260px'; + right.appendChild(chartDiv); + + row.appendChild(left); + row.appendChild(right); + target.appendChild(row); + + // Build donut (ring) chart with theme support + try { + // Recreate the graph each render to bind to the fresh DOM + if (dlMaxPie && dlMaxPie.chart) { + try { dlMaxPie.chart.dispose(); } catch (_) {} + dlMaxPie = null; + } + dlMaxPie = new DashboardGraph('cpuDlMaxPie'); + const seriesData = data.map((row) => ({ + name: `CPU ${row.cpu}`, + value: Number(row.download.max_sum_mbps || 0) + })); + dlMaxPie.option = { + tooltip: { trigger: 'item' }, + legend: { show: false }, + series: [ + { + name: 'DL Max by CPU', + type: 'pie', + radius: ['55%','80%'], + center: ['50%', '50%'], + avoidLabelOverlap: true, + data: seriesData, + label: { + show: true, + formatter: '{b}: {d}%' + } + } + ] + }; + dlMaxPie.chart.setOption(dlMaxPie.option); + dlMaxPie.chart.hideLoading(); + } catch (e) { + // If echarts is unavailable, leave chart blank + } +} + +function renderDetailsHeader() { + const label = document.getElementById("currentCpuLabel"); + if (state.selectedCpu === null) { + label.textContent = ""; + } else { + label.textContent = ` – CPU ${state.selectedCpu}`; + } +} + +function renderCircuits(page) { + const target = document.getElementById("circuitsTable"); + clearDiv(target); + + if (!page || !Array.isArray(page.items)) { + target.innerHTML = '

No circuits found for this CPU.

'; + return; + } + + const smallNote = document.createElement("div"); + smallNote.className = "text-muted small mb-1"; + smallNote.innerText = `Total: ${page.total.toLocaleString()} circuits`; + target.appendChild(smallNote); + + const table = document.createElement("table"); + table.classList.add("table", "table-striped", "table-sm"); + const thead = document.createElement("thead"); + thead.appendChild(theading("Circuit ID")); + thead.appendChild(theading("Circuit Name")); + thead.appendChild(theading("Parent")); + thead.appendChild(theading("ClassID")); + thead.appendChild(theading("Min (Mbps)")); + thead.appendChild(theading("Max (Mbps)")); + thead.appendChild(theading("IPs")); + table.appendChild(thead); + const tbody = document.createElement("tbody"); + + page.items.forEach((c) => { + const tr = document.createElement("tr"); + const idCell = document.createElement("td"); + if (c.circuit_id) { + const a = document.createElement("a"); + a.href = `circuit.html?id=${encodeURIComponent(c.circuit_id)}`; + a.textContent = c.circuit_id; + idCell.appendChild(a); + } else { + idCell.textContent = ""; + } + tr.appendChild(idCell); + tr.appendChild(simpleRow(c.circuit_name || "")); + tr.appendChild(simpleRow(c.parent_node || "")); + tr.appendChild(simpleRow(c.classid || "")); + tr.appendChild(simpleRow(fmtMbps(c.min_mbps))); + tr.appendChild(simpleRow(fmtMbps(c.max_mbps))); + tr.appendChild(simpleRow(String(c.ip_count || 0))); + tbody.appendChild(tr); + }); + + table.appendChild(tbody); + target.appendChild(table); +} + +async function fetchSummary() { + try { + const r = await fetch("/local-api/cpuAffinity/summary"); + if (!r.ok) throw new Error(`${r.status}`); + const data = await r.json(); + // data is { entries: [...] } or just array depending on server; we returned a tuple-like wrapper + const entries = Array.isArray(data) ? data : (data["0"] ? data : (data["entries"] || data)); + // Get planner enabled flag from config + try { + const c = await fetch("/local-api/getConfig"); + if (c.ok) { + const cfg = await c.json(); + state.plannerEnabled = !!(cfg.queues && cfg.queues.use_binpacking); + } + } catch (_) {} + renderSummary(entries); // In our implementation: array + } catch (e) { + document.getElementById("cpuSummary").innerHTML = `
Failed to load summary: ${e}
`; + } +} + +async function fetchCircuits() { + const target = document.getElementById("circuitsTable"); + target.innerHTML = ' Loading circuits...'; + const dir = state.direction; + const cpu = state.selectedCpu; + if (cpu === null || cpu === undefined) { + target.innerHTML = ' Select a CPU from the table above.'; + return; + } + const params = new URLSearchParams(); + params.set("direction", dir); + params.set("page", String(state.page)); + params.set("page_size", String(state.pageSize)); + // no search param + try { + const r = await fetch(`/local-api/cpuAffinity/circuits/${cpu}?` + params.toString()); + if (!r.ok) throw new Error(`${r.status}`); + const data = await r.json(); + renderCircuits(data); + } catch (e) { + target.innerHTML = `
Failed to load circuits: ${e}
`; + } +} + +// Wire up controls +function initControls() { + const pageSizeInput = document.getElementById("pageSize"); + const btnPrev = document.getElementById("btnPrev"); + const btnNext = document.getElementById("btnNext"); + const btnRefresh = document.getElementById("btnRefresh"); + pageSizeInput.onchange = () => { + let v = parseInt(pageSizeInput.value || "50", 10); + if (!Number.isFinite(v) || v < 10) v = 10; + if (v > 1000) v = 1000; + state.pageSize = v; + state.page = 1; + fetchCircuits(); + }; + btnPrev.onclick = () => { + if (state.page > 1) { + state.page -= 1; + fetchCircuits(); + } + }; + btnNext.onclick = () => { + state.page += 1; + fetchCircuits(); + }; + btnRefresh.onclick = () => { + fetchSummary(); + if (state.selectedCpu !== null) fetchCircuits(); + }; +} + +// Initialize +initControls(); +renderDetailsHeader(); +fetchSummary().then(() => enableTooltips()); + +// No preview section (binpacking) in this view diff --git a/src/rust/lqosd/src/node_manager/local_api.rs b/src/rust/lqosd/src/node_manager/local_api.rs index a6d0ddf7..dddf2a20 100644 --- a/src/rust/lqosd/src/node_manager/local_api.rs +++ b/src/rust/lqosd/src/node_manager/local_api.rs @@ -8,6 +8,7 @@ mod flow_explorer; mod flow_map; pub mod lts; mod network_tree; +mod cpu_affinity; mod packet_analysis; mod reload_libreqos; mod scheduler; @@ -66,6 +67,19 @@ pub fn local_api(shaper_query: tokio::sync::mpsc::Sender) -> ) .route("/pcapDump/:id", get(packet_analysis::pcap_dump)) .route("/flowMap", get(flow_map::flow_lat_lon)) + .route("/cpuAffinity/summary", get(cpu_affinity::cpu_affinity_summary)) + .route( + "/cpuAffinity/circuits/:cpu", + get(cpu_affinity::cpu_affinity_circuits), + ) + .route( + "/cpuAffinity/circuitsAll", + get(cpu_affinity::cpu_affinity_circuits_all), + ) + .route( + "/cpuAffinity/previewWeights", + get(cpu_affinity::cpu_affinity_preview_weights), + ) .route("/globalWarnings", get(warnings::get_global_warnings)) .route("/asnList", get(flow_explorer::asn_list)) .route("/countryList", get(flow_explorer::country_list)) diff --git a/src/rust/lqosd/src/node_manager/local_api/cpu_affinity.rs b/src/rust/lqosd/src/node_manager/local_api/cpu_affinity.rs new file mode 100644 index 00000000..e42e6c1d --- /dev/null +++ b/src/rust/lqosd/src/node_manager/local_api/cpu_affinity.rs @@ -0,0 +1,466 @@ +use axum::{extract::Path, extract::Query, Json}; +use serde::Serialize; +use serde_json::Value; +use std::collections::HashMap; +use std::path::PathBuf; + +#[derive(Serialize, Clone, Debug)] +pub struct CpuSideSummary { + pub circuits: usize, + pub min_sum_mbps: f64, + pub max_sum_mbps: f64, +} + +#[derive(Serialize, Clone, Debug)] +pub struct CpuAffinitySummaryEntry { + pub cpu: u32, + pub download: CpuSideSummary, + pub upload: CpuSideSummary, +} + +#[derive(Serialize, Clone, Debug)] +pub struct CpuAffinitySummaryResponse(pub Vec); + +#[derive(Serialize, Clone, Debug)] +pub struct CircuitBrief { + pub circuit_id: Option, + pub circuit_name: Option, + pub parent_node: Option, + pub classid: Option, + pub min_mbps: f64, + pub max_mbps: f64, + pub ip_count: usize, +} + +#[derive(Serialize, Clone, Debug)] +pub struct CpuAffinityCircuitsPage { + pub cpu: u32, + pub direction: String, + pub total: usize, + pub page: usize, + pub page_size: usize, + pub items: Vec, +} + +#[derive(Debug, Default, Clone)] +struct CircuitRecord { + cpu_down: Option, + cpu_up: Option, + min_down: f64, + max_down: f64, + min_up: f64, + max_up: f64, + classid_down: Option, + classid_up: Option, + circuit_id: Option, + circuit_name: Option, + parent_node: Option, + ip_count: usize, +} + +// Query params for the circuits endpoint +#[derive(Debug, Default, Clone, serde::Deserialize)] +pub struct CircuitsQuery { + pub direction: Option, // "down" | "up" (default: down) + pub page: Option, // default 1 + pub page_size: Option, // default 100 + pub search: Option, // substring match on id/name +} + +fn queuing_structure_path() -> Option { + let cfg = lqos_config::load_config().ok()?; + let mut p = PathBuf::from(cfg.lqos_directory.clone()); + p.push("queuingStructure.json"); + Some(p) +} + +fn parse_hex_u32(s: &str) -> Option { + // Accept formats like "0x1" or decimal strings + if let Some(stripped) = s.strip_prefix("0x").or_else(|| s.strip_prefix("0X")) { + u32::from_str_radix(stripped, 16).ok() + } else { + s.parse::().ok() + } +} + +fn val_as_f64(v: &Value) -> Option { + if let Some(x) = v.as_f64() { + Some(x) + } else if let Some(x) = v.as_i64() { + Some(x as f64) + } else if let Some(x) = v.as_u64() { + Some(x as f64) + } else if let Some(s) = v.as_str() { + s.parse::().ok() + } else { + None + } +} + +fn collect_ip_count(circuit: &serde_json::Map) -> usize { + let mut count = 0usize; + if let Some(Value::Array(devs)) = circuit.get("devices") { + for d in devs { + if let Value::Object(dev) = d { + if let Some(Value::Array(v4s)) = dev.get("ipv4s") { + count += v4s.len(); + } + if let Some(Value::Array(v6s)) = dev.get("ipv6s") { + count += v6s.len(); + } + } + } + } + count +} + +fn add_circuit_records( + parent_name: Option<&str>, + node: &serde_json::Map, + out: &mut Vec, +) { + // Helper: parse a JSON object that represents a circuit-level entry + fn parse_circuit_map( + parent_name: Option<&str>, + cm: &serde_json::Map, + ) -> CircuitRecord { + let mut rec = CircuitRecord::default(); + // cpu numbers + if let Some(Value::String(s)) = cm.get("cpuNum") { + rec.cpu_down = parse_hex_u32(s); + } else if let Some(Value::String(s)) = cm.get("classMajor") { + if let Some(mut v) = parse_hex_u32(s) { rec.cpu_down = Some(v.saturating_sub(1)); } + } else if let Some(Value::String(s)) = cm.get("classid") { + // Fallback: parse major from TC handle like "0x1:0x51" + if let Some((maj, _)) = s.split_once(':') { + if let Some(mut v) = parse_hex_u32(maj) { rec.cpu_down = Some(v.saturating_sub(1)); } + } + } + if let Some(Value::String(s)) = cm.get("up_cpuNum") { + rec.cpu_up = parse_hex_u32(s); + } else if let Some(Value::String(s)) = cm.get("up_classMajor") { + if let Some(mut v) = parse_hex_u32(s) { rec.cpu_up = Some(v.saturating_sub(1)); } + } else if let Some(Value::String(s)) = cm.get("up_classid") { + if let Some((maj, _)) = s.split_once(':') { + if let Some(mut v) = parse_hex_u32(maj) { rec.cpu_up = Some(v.saturating_sub(1)); } + } + } + // classids + if let Some(Value::String(s)) = cm.get("classid") { + rec.classid_down = Some(s.clone()); + } + if let Some(Value::String(s)) = cm.get("up_classid") { + rec.classid_up = Some(s.clone()); + } + // bandwidths + if let Some(v) = cm.get("minDownload").and_then(val_as_f64) { + rec.min_down = v; + } + if let Some(v) = cm.get("maxDownload").and_then(val_as_f64) { + rec.max_down = v; + } + if let Some(v) = cm.get("minUpload").and_then(val_as_f64) { + rec.min_up = v; + } + if let Some(v) = cm.get("maxUpload").and_then(val_as_f64) { + rec.max_up = v; + } + // identity + if let Some(Value::String(s)) = cm.get("circuitID") { + if !s.is_empty() { rec.circuit_id = Some(s.clone()); } + } + if let Some(Value::String(s)) = cm.get("circuitName") { + if !s.is_empty() { rec.circuit_name = Some(s.clone()); } + } + if rec.circuit_name.is_none() { + // Fallback to the JSON key is not available here; leave empty + } + rec.parent_node = parent_name.map(|x| x.to_string()); + // IP count + rec.ip_count = collect_ip_count(cm); + rec + } + + // Process circuits array at this node + if let Some(Value::Array(circuits)) = node.get("circuits") { + for c in circuits { + if let Value::Object(cm) = c { + out.push(parse_circuit_map(parent_name, cm)); + } + } + } + + // Also check children: some builds embed circuits directly as child entries (rare). + if let Some(Value::Object(children)) = node.get("children") { + for (child_name, child_value) in children.iter() { + if let Value::Object(child_map) = child_value { + // Treat as circuit only if it has a devices array (avoids counting structural nodes) + let is_circuit_like = matches!(child_map.get("devices"), Some(Value::Array(_))) + || child_map.get("circuitID").is_some(); + if is_circuit_like { + out.push(parse_circuit_map(Some(child_name.as_str()), child_map)); + } + add_circuit_records(Some(child_name.as_str()), child_map, out); + } + } + } +} + +fn load_all_circuits() -> Vec { + let Some(path) = queuing_structure_path() else { + return Vec::new(); + }; + let raw = match std::fs::read_to_string(path) { + Ok(s) => s, + Err(_) => return Vec::new(), + }; + let json: Value = match serde_json::from_str(&raw) { + Ok(v) => v, + Err(_) => return Vec::new(), + }; + let mut circuits = Vec::new(); + if let Value::Object(map) = json { + if let Some(Value::Object(net)) = map.get("Network") { + for (_k, v) in net.iter() { + if let Value::Object(node) = v { + add_circuit_records(None, node, &mut circuits); + } + } + } + } + circuits +} + +pub async fn cpu_affinity_summary() -> Json { + let circuits = load_all_circuits(); + let mut down: HashMap = HashMap::new(); + let mut up: HashMap = HashMap::new(); + + for c in circuits.iter() { + if let Some(cpu) = c.cpu_down { + let entry = down.entry(cpu).or_insert((0, 0.0, 0.0)); + entry.0 += 1; + entry.1 += c.min_down; + entry.2 += c.max_down; + } + if let Some(cpu) = c.cpu_up { + let entry = up.entry(cpu).or_insert((0, 0.0, 0.0)); + entry.0 += 1; + entry.1 += c.min_up; + entry.2 += c.max_up; + } + } + + // Union of CPUs seen in either direction + let mut cpus: Vec = down.keys().chain(up.keys()).copied().collect(); + cpus.sort_unstable(); + cpus.dedup(); + + let mut entries = Vec::with_capacity(cpus.len()); + for cpu in cpus.into_iter() { + let d = down.get(&cpu).cloned().unwrap_or((0, 0.0, 0.0)); + let u = up.get(&cpu).cloned().unwrap_or((0, 0.0, 0.0)); + entries.push(CpuAffinitySummaryEntry { + cpu, + download: CpuSideSummary { + circuits: d.0, + min_sum_mbps: d.1, + max_sum_mbps: d.2, + }, + upload: CpuSideSummary { + circuits: u.0, + min_sum_mbps: u.1, + max_sum_mbps: u.2, + }, + }); + } + + Json(CpuAffinitySummaryResponse(entries)) +} + +pub async fn cpu_affinity_circuits( + Path(cpu): Path, + Query(q): Query, +) -> Json { + let direction = q + .direction + .as_deref() + .map(|s| if s.eq_ignore_ascii_case("up") { "up" } else { "down" }) + .unwrap_or("down"); + + let page = q.page.unwrap_or(1).max(1); + let page_size = q.page_size.unwrap_or(100).clamp(1, 1000); + let search = q.search.as_deref().map(|s| s.to_lowercase()); + + let circuits = load_all_circuits(); + let mut filtered: Vec = circuits + .into_iter() + .filter(|c| match direction { + "up" => c.cpu_up == Some(cpu), + _ => c.cpu_down == Some(cpu), + }) + .filter(|c| { + if let Some(ref needle) = search { + let id = c.circuit_id.as_deref().unwrap_or("").to_lowercase(); + let nm = c.circuit_name.as_deref().unwrap_or("").to_lowercase(); + id.contains(needle) || nm.contains(needle) + } else { + true + } + }) + .map(|c| CircuitBrief { + circuit_id: c.circuit_id, + circuit_name: c.circuit_name, + parent_node: c.parent_node, + classid: if direction == "up" { + c.classid_up + } else { + c.classid_down + }, + min_mbps: if direction == "up" { c.min_up } else { c.min_down }, + max_mbps: if direction == "up" { c.max_up } else { c.max_down }, + ip_count: c.ip_count, + }) + .collect(); + + // Sort by circuit name, then id + filtered.sort_by(|a, b| { + let an = a.circuit_name.as_deref().unwrap_or(""); + let bn = b.circuit_name.as_deref().unwrap_or(""); + let ord = an.cmp(bn); + if ord == std::cmp::Ordering::Equal { + a.circuit_id + .as_deref() + .unwrap_or("") + .cmp(b.circuit_id.as_deref().unwrap_or("")) + } else { + ord + } + }); + + let total = filtered.len(); + let start = (page - 1) * page_size; + let end = std::cmp::min(start + page_size, total); + let page_items = if start < total { + filtered[start..end].to_vec() + } else { + Vec::new() + }; + + Json(CpuAffinityCircuitsPage { + cpu, + direction: direction.to_string(), + total, + page, + page_size, + items: page_items, + }) +} + +// Return all circuits (direction-filtered) without pagination to support client-side previews. +pub async fn cpu_affinity_circuits_all( + Query(q): Query, +) -> Json> { + let direction = q + .direction + .as_deref() + .map(|s| if s.eq_ignore_ascii_case("up") { "up" } else { "down" }) + .unwrap_or("down"); + let search = q.search.as_deref().map(|s| s.to_lowercase()); + + let circuits = load_all_circuits(); + let mut items: Vec = circuits + .into_iter() + .filter(|c| { + if let Some(ref needle) = search { + let id = c.circuit_id.as_deref().unwrap_or("").to_lowercase(); + let nm = c.circuit_name.as_deref().unwrap_or("").to_lowercase(); + id.contains(needle) || nm.contains(needle) + } else { + true + } + }) + .map(|c| CircuitBrief { + circuit_id: c.circuit_id, + circuit_name: c.circuit_name, + parent_node: c.parent_node, + classid: if direction == "up" { + c.classid_up + } else { + c.classid_down + }, + min_mbps: if direction == "up" { c.min_up } else { c.min_down }, + max_mbps: if direction == "up" { c.max_up } else { c.max_down }, + ip_count: c.ip_count, + }) + .collect(); + + // Sort deterministically + items.sort_by(|a, b| { + let an = a.circuit_name.as_deref().unwrap_or(""); + let bn = b.circuit_name.as_deref().unwrap_or(""); + let ord = an.cmp(bn); + if ord == std::cmp::Ordering::Equal { + a.circuit_id + .as_deref() + .unwrap_or("") + .cmp(b.circuit_id.as_deref().unwrap_or("")) + } else { + ord + } + }); + + Json(items) +} + +#[derive(Serialize, Clone, Debug)] +pub struct PreviewWeightItem { + pub key: String, + pub weight: f64, +} + +// Minimal payload for preview: just (key, weight) for each circuit in a direction. +pub async fn cpu_affinity_preview_weights( + Query(q): Query, +) -> Json> { + let direction = q + .direction + .as_deref() + .map(|s| if s.eq_ignore_ascii_case("up") { "up" } else { "down" }) + .unwrap_or("down"); + let search = q.search.as_deref().map(|s| s.to_lowercase()); + + let circuits = load_all_circuits(); + let mut items: Vec = circuits + .into_iter() + .filter(|c| { + if let Some(ref needle) = search { + let id = c.circuit_id.as_deref().unwrap_or("").to_lowercase(); + let nm = c.circuit_name.as_deref().unwrap_or("").to_lowercase(); + id.contains(needle) || nm.contains(needle) + } else { + true + } + }) + .map(|c| PreviewWeightItem { + key: c + .circuit_id + .clone() + .or(c.circuit_name.clone()) + .unwrap_or_else(|| String::new()), + weight: if direction == "up" { c.max_up } else { c.max_down }, + }) + .collect(); + + // Deterministic ordering for ties + items.sort_by(|a, b| { + let ow = b.weight.partial_cmp(&a.weight).unwrap_or(std::cmp::Ordering::Equal); + if ow == std::cmp::Ordering::Equal { + a.key.cmp(&b.key) + } else { + ow + } + }); + + Json(items) +} diff --git a/src/rust/lqosd/src/node_manager/static2/cpu_weights.html b/src/rust/lqosd/src/node_manager/static2/cpu_weights.html new file mode 100644 index 00000000..b1ef93e7 --- /dev/null +++ b/src/rust/lqosd/src/node_manager/static2/cpu_weights.html @@ -0,0 +1,50 @@ +
+
+
+
+
CPU Affinity
+

View current circuit placement per CPU/queue from the active TC plan.

+
+
+
+
+ + +
+
+ Binpacking: … +
+
+ +
+
+
+
+ +
+ Loading CPU summary... +
+ +
+ +
+
+
+ Circuits + +
+
+ + +
+
+
+ Select a CPU from the table above. +
+
+
+
+ + diff --git a/src/rust/lqosd/src/node_manager/static2/template.html b/src/rust/lqosd/src/node_manager/static2/template.html index 0f192af8..88540ba2 100644 --- a/src/rust/lqosd/src/node_manager/static2/template.html +++ b/src/rust/lqosd/src/node_manager/static2/template.html @@ -87,6 +87,12 @@ ASN Explorer + + %%LTS_LINK%% %%API_LINK%% diff --git a/src/rust/lqosd/src/node_manager/static_pages.rs b/src/rust/lqosd/src/node_manager/static_pages.rs index ae69edc7..ec838011 100644 --- a/src/rust/lqosd/src/node_manager/static_pages.rs +++ b/src/rust/lqosd/src/node_manager/static_pages.rs @@ -63,6 +63,7 @@ pub(super) fn static_routes() -> Result { "config_wispgate.html", "config_stormguard.html", "api.html", + "cpu_weights.html", ]; // Iterate through pages and construct the router -- knotmirror 0.0.1 From ed2387194740701feefc7e6066bd58abc6fd3da3 Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Thu, 6 Nov 2025 12:12:23 -0600 Subject: [PATCH 38/58] Fix: Improve planner fairness/scoring, and expose the actual scores in the affinity page. --- src/LibreQoS.py | 20 +++++++ .../node_manager/js_build/src/cpu_weights.js | 28 +++++++--- .../node_manager/local_api/cpu_affinity.rs | 54 +++++++++++-------- 3 files changed, 72 insertions(+), 30 deletions(-) diff --git a/src/LibreQoS.py b/src/LibreQoS.py index 97a28638..378c7c21 100755 --- a/src/LibreQoS.py +++ b/src/LibreQoS.py @@ -897,6 +897,19 @@ def refreshShapers(): return newDict network = flattenA(network, 1) + # Prepare planner weights (actual weighting may come from Insight or CSV defaults) + weight_by_circuit_id = {} + try: + weights = get_weights() + for w in weights: + try: + weight_by_circuit_id[str(w.circuit_id)] = float(w.weight) + except Exception: + pass + except Exception: + # If we can't get weights, leave mapping empty; UI will fall back + weight_by_circuit_id = {} + # Group circuits by parent node. Reduces runtime for section below this one. circuits_by_parent_node = {} circuit_min_down_combined_by_parent_node = {} @@ -1053,6 +1066,13 @@ def refreshShapers(): "classMinor": hex(minorByCPU[queue]), "comment": circuit['comment'] } + # Attach the planner weight if available (real weighting used by the planner) + try: + cid = str(circuit.get('circuitID','')) + if cid in weight_by_circuit_id: + thisNewCircuitItemForNetwork['planner_weight'] = weight_by_circuit_id[cid] + except Exception: + pass # Preserve optional per-circuit SQM override for downstream bakery call if 'sqm' in circuit and circuit['sqm']: thisNewCircuitItemForNetwork['sqm'] = circuit['sqm'] diff --git a/src/rust/lqosd/src/node_manager/js_build/src/cpu_weights.js b/src/rust/lqosd/src/node_manager/js_build/src/cpu_weights.js index 6d2c311a..bc7360b1 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/cpu_weights.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/cpu_weights.js @@ -55,7 +55,7 @@ function renderSummary(data) { const thead = document.createElement("thead"); thead.appendChild(theading("CPU")); thead.appendChild(theading("DL Circuits")); - thead.appendChild(theading("DL Min (Mbps)")); + thead.appendChild(theading("Weight")); thead.appendChild(theading("DL Max (Mbps)")); thead.appendChild(theading("Actions")); table.appendChild(thead); @@ -68,11 +68,17 @@ function renderSummary(data) { return td; }; + // simple weight formatter + const fmtWeight = (x) => { + const n = Number(x || 0); + return n > 0 ? n.toLocaleString() : '-'; + }; + data.forEach((row) => { const tr = document.createElement("tr"); tr.appendChild(centerCell(row.cpu)); tr.appendChild(centerCell(row.download.circuits)); - tr.appendChild(centerCell(fmtMbps(row.download.min_sum_mbps))); + tr.appendChild(centerCell(fmtWeight(row.download && row.download.weight_sum))); tr.appendChild(centerCell(fmtMbps(row.download.max_sum_mbps))); const actions = document.createElement("td"); @@ -115,10 +121,14 @@ function renderSummary(data) { dlMaxPie = null; } dlMaxPie = new DashboardGraph('cpuDlMaxPie'); - const seriesData = data.map((row) => ({ - name: `CPU ${row.cpu}`, - value: Number(row.download.max_sum_mbps || 0) - })); + const seriesData = data.map((row) => { + const w = Number((row.download && row.download.weight_sum) ? row.download.weight_sum : 0); + const v = Number(row.download.max_sum_mbps || 0); + return { + name: `CPU ${row.cpu}`, + value: (w > 0 ? w : v) + }; + }); dlMaxPie.option = { tooltip: { trigger: 'item' }, legend: { show: false }, @@ -174,7 +184,7 @@ function renderCircuits(page) { thead.appendChild(theading("Circuit Name")); thead.appendChild(theading("Parent")); thead.appendChild(theading("ClassID")); - thead.appendChild(theading("Min (Mbps)")); + thead.appendChild(theading("Weight")); thead.appendChild(theading("Max (Mbps)")); thead.appendChild(theading("IPs")); table.appendChild(thead); @@ -195,7 +205,9 @@ function renderCircuits(page) { tr.appendChild(simpleRow(c.circuit_name || "")); tr.appendChild(simpleRow(c.parent_node || "")); tr.appendChild(simpleRow(c.classid || "")); - tr.appendChild(simpleRow(fmtMbps(c.min_mbps))); + const weightCell = document.createElement('td'); + weightCell.innerText = (c.weight && c.weight > 0) ? c.weight.toLocaleString() : '-'; + tr.appendChild(weightCell); tr.appendChild(simpleRow(fmtMbps(c.max_mbps))); tr.appendChild(simpleRow(String(c.ip_count || 0))); tbody.appendChild(tr); diff --git a/src/rust/lqosd/src/node_manager/local_api/cpu_affinity.rs b/src/rust/lqosd/src/node_manager/local_api/cpu_affinity.rs index e42e6c1d..652213ab 100644 --- a/src/rust/lqosd/src/node_manager/local_api/cpu_affinity.rs +++ b/src/rust/lqosd/src/node_manager/local_api/cpu_affinity.rs @@ -9,6 +9,7 @@ pub struct CpuSideSummary { pub circuits: usize, pub min_sum_mbps: f64, pub max_sum_mbps: f64, + pub weight_sum: f64, } #[derive(Serialize, Clone, Debug)] @@ -27,8 +28,8 @@ pub struct CircuitBrief { pub circuit_name: Option, pub parent_node: Option, pub classid: Option, - pub min_mbps: f64, pub max_mbps: f64, + pub weight: f64, pub ip_count: usize, } @@ -50,6 +51,7 @@ struct CircuitRecord { max_down: f64, min_up: f64, max_up: f64, + planner_weight: f64, classid_down: Option, classid_up: Option, circuit_id: Option, @@ -152,19 +154,23 @@ fn add_circuit_records( if let Some(Value::String(s)) = cm.get("up_classid") { rec.classid_up = Some(s.clone()); } - // bandwidths - if let Some(v) = cm.get("minDownload").and_then(val_as_f64) { - rec.min_down = v; - } - if let Some(v) = cm.get("maxDownload").and_then(val_as_f64) { - rec.max_down = v; - } - if let Some(v) = cm.get("minUpload").and_then(val_as_f64) { - rec.min_up = v; - } - if let Some(v) = cm.get("maxUpload").and_then(val_as_f64) { - rec.max_up = v; - } + // bandwidths + if let Some(v) = cm.get("minDownload").and_then(val_as_f64) { + rec.min_down = v; + } + if let Some(v) = cm.get("maxDownload").and_then(val_as_f64) { + rec.max_down = v; + } + if let Some(v) = cm.get("minUpload").and_then(val_as_f64) { + rec.min_up = v; + } + if let Some(v) = cm.get("maxUpload").and_then(val_as_f64) { + rec.max_up = v; + } + // planner weight if present + if let Some(v) = cm.get("planner_weight").and_then(val_as_f64) { + rec.planner_weight = v; + } // identity if let Some(Value::String(s)) = cm.get("circuitID") { if !s.is_empty() { rec.circuit_id = Some(s.clone()); } @@ -233,21 +239,23 @@ fn load_all_circuits() -> Vec { pub async fn cpu_affinity_summary() -> Json { let circuits = load_all_circuits(); - let mut down: HashMap = HashMap::new(); - let mut up: HashMap = HashMap::new(); + let mut down: HashMap = HashMap::new(); + let mut up: HashMap = HashMap::new(); for c in circuits.iter() { if let Some(cpu) = c.cpu_down { - let entry = down.entry(cpu).or_insert((0, 0.0, 0.0)); + let entry = down.entry(cpu).or_insert((0, 0.0, 0.0, 0.0)); entry.0 += 1; entry.1 += c.min_down; entry.2 += c.max_down; + entry.3 += c.planner_weight; } if let Some(cpu) = c.cpu_up { - let entry = up.entry(cpu).or_insert((0, 0.0, 0.0)); + let entry = up.entry(cpu).or_insert((0, 0.0, 0.0, 0.0)); entry.0 += 1; entry.1 += c.min_up; entry.2 += c.max_up; + entry.3 += c.planner_weight; } } @@ -258,19 +266,21 @@ pub async fn cpu_affinity_summary() -> Json { let mut entries = Vec::with_capacity(cpus.len()); for cpu in cpus.into_iter() { - let d = down.get(&cpu).cloned().unwrap_or((0, 0.0, 0.0)); - let u = up.get(&cpu).cloned().unwrap_or((0, 0.0, 0.0)); + let d = down.get(&cpu).cloned().unwrap_or((0, 0.0, 0.0, 0.0)); + let u = up.get(&cpu).cloned().unwrap_or((0, 0.0, 0.0, 0.0)); entries.push(CpuAffinitySummaryEntry { cpu, download: CpuSideSummary { circuits: d.0, min_sum_mbps: d.1, max_sum_mbps: d.2, + weight_sum: d.3, }, upload: CpuSideSummary { circuits: u.0, min_sum_mbps: u.1, max_sum_mbps: u.2, + weight_sum: u.3, }, }); } @@ -317,8 +327,8 @@ pub async fn cpu_affinity_circuits( } else { c.classid_down }, - min_mbps: if direction == "up" { c.min_up } else { c.min_down }, max_mbps: if direction == "up" { c.max_up } else { c.max_down }, + weight: c.planner_weight, ip_count: c.ip_count, }) .collect(); @@ -389,8 +399,8 @@ pub async fn cpu_affinity_circuits_all( } else { c.classid_down }, - min_mbps: if direction == "up" { c.min_up } else { c.min_down }, max_mbps: if direction == "up" { c.max_up } else { c.max_down }, + weight: c.planner_weight, ip_count: c.ip_count, }) .collect(); -- knotmirror 0.0.1 From 2b250925419c5e4957f846e944c03c1e93a01539 Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Thu, 6 Nov 2025 12:30:55 -0600 Subject: [PATCH 39/58] Fix: Add override for 1000 as calculated weight, because it acts as a sentinel for incomplete data. --- src/LibreQoS.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/LibreQoS.py b/src/LibreQoS.py index 378c7c21..6648af02 100755 --- a/src/LibreQoS.py +++ b/src/LibreQoS.py @@ -1070,7 +1070,11 @@ def refreshShapers(): try: cid = str(circuit.get('circuitID','')) if cid in weight_by_circuit_id: - thisNewCircuitItemForNetwork['planner_weight'] = weight_by_circuit_id[cid] + w = float(weight_by_circuit_id[cid]) + # Treat 1000 as a sentinel default from Insight; use maxDownload instead + if abs(w - 1000.0) < 1e-6: + w = float(maxDownload) + thisNewCircuitItemForNetwork['planner_weight'] = w except Exception: pass # Preserve optional per-circuit SQM override for downstream bakery call -- knotmirror 0.0.1 From b88548aadafabd4f0f131002fcc58c3f2fb0e34f Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Thu, 6 Nov 2025 13:02:59 -0600 Subject: [PATCH 40/58] Fix: Missing script --- src/LibreQoS.py | 12 +- src/bin_planner.py | 277 +++++++++++++++++++++++++++++++++++++++++++++ src/build_dpkg.sh | 1 + src/build_rust.sh | 8 ++ 4 files changed, 296 insertions(+), 2 deletions(-) create mode 100644 src/bin_planner.py diff --git a/src/LibreQoS.py b/src/LibreQoS.py index 6648af02..a85643b3 100755 --- a/src/LibreQoS.py +++ b/src/LibreQoS.py @@ -766,7 +766,11 @@ def refreshShapers(): if iid in changed: state["last_change_ts"][iid] = now_ts state["assignments"][iid] = b - bin_planner.save_state(state_path, state) + try: + print(f"Saving planner state to {state_path} (generated PNs)") + bin_planner.save_state(state_path, state) + except Exception as e: + warnings.warn(f"Failed to save planner state at {state_path}: {e}", stacklevel=2) print("Finished planning generated parent nodes") else: @@ -1225,7 +1229,11 @@ def refreshShapers(): if iid in changed: state["last_change_ts"][iid] = now_ts state["assignments"][iid] = b - bin_planner.save_state(state_path, state) + try: + print(f"Saving planner state to {state_path} (top-level CPU binning)") + bin_planner.save_state(state_path, state) + except Exception as e: + warnings.warn(f"Failed to save planner state at {state_path}: {e}", stacklevel=2) # 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()) diff --git a/src/bin_planner.py b/src/bin_planner.py new file mode 100644 index 00000000..f1b4a478 --- /dev/null +++ b/src/bin_planner.py @@ -0,0 +1,277 @@ +""" +Internal planner for stable, damped item-to-bin assignments. + +This module exposes a minimal interface initially, to be expanded in later +steps. The baseline implementation uses a simple greedy balancing strategy +as a placeholder to replace the external binpacking dependency. +""" + +from typing import Dict, List, Tuple, Any, Iterable +import hashlib +import math +import json +import os +import time + + +def plan_assignments( + items: List[Dict[str, Any]], + bins: List[Dict[str, Any]], + capacities: Dict[str, float], + previous_assignments: Dict[str, str], + now_ts: float, + params: Dict[str, Any], +) -> Tuple[Dict[str, str], List[str]]: + """ + Compute item -> bin assignments with a repair-oriented approach. + + items: list of { "id": str, "weight": float } + bins: list of { "id": str } + capacities: { bin_id: capacity_float } + previous_assignments: { item_id: bin_id } + now_ts: current UNIX timestamp + params: planner parameters (optional keys): + - candidate_set_size: int + - headroom: float in [0,1) + - alpha: float >= 0 + - hysteresis_threshold: float >= 0 + - cooldown_seconds: int >= 0 + - move_budget_per_run: int >= 0 + - salt: str + - last_change_ts_by_item: { item_id: unix_ts } + - movement_penalty_k: float >= 0 (default 0) + - penalty_tau_seconds: float > 0 (default 3600) + + Returns (assignments, changed_items) + """ + # Defaults + L = int(params.get("candidate_set_size", 4)) + headroom = float(params.get("headroom", 0.05)) + alpha = float(params.get("alpha", 0.1)) + hysteresis = float(params.get("hysteresis_threshold", 0.03)) + cooldown_s = int(params.get("cooldown_seconds", 3600)) + salt = str(params.get("salt", "default_salt")) + last_change_ts = params.get("last_change_ts_by_item", {}) or {} + penalty_k = float(params.get("movement_penalty_k", 0.0)) + penalty_tau = float(params.get("penalty_tau_seconds", 3600.0)) + + bin_ids: List[str] = [b["id"] for b in bins] + cap = {bid: float(capacities.get(bid, 1.0)) for bid in bin_ids} + # Avoid zero/negative capacity + for bid, c in list(cap.items()): + if c <= 0: + cap[bid] = 1e-9 + + # Normalize items + item_list: List[Tuple[str, float]] = [] + for it in items: + it_id = str(it.get("id")) + w = float(it.get("weight", 1.0)) + item_list.append((it_id, w)) + + # Current assignment: keep valid previous assignments + assignment: Dict[str, str] = {} + load: Dict[str, float] = {bid: 0.0 for bid in bin_ids} + for it_id, w in item_list: + prev = previous_assignments.get(it_id) + if prev in cap: + assignment[it_id] = prev + load[prev] += w + + # Cold start: assign items without previous placement via greedy using HRW candidates + missing = [(it_id, w) for it_id, w in item_list if it_id not in assignment] + weights_by_bin = {bid: cap[bid] for bid in bin_ids} + missing.sort(key=lambda t: (-t[1], t[0])) + initially_assigned: List[str] = [] + for it_id, w in missing: + candidates = hrw_candidates(it_id, bin_ids, weights_by_bin, max(L, 1), salt) + # Choose the least loaded among candidates; break ties by HRW rank, not lexicographic bin id + if candidates: + rank = {bid: idx for idx, bid in enumerate(candidates)} + tgt = min(candidates, key=lambda bid: (load[bid] / cap[bid], rank[bid])) + else: + # As a fallback, rank all bins by HRW order to avoid lexicographic bias + all_rank_list = hrw_candidates(it_id, bin_ids, weights_by_bin, len(bin_ids), salt) + all_rank = {bid: idx for idx, bid in enumerate(all_rank_list)} + tgt = min(bin_ids, key=lambda bid: (load[bid] / cap[bid], all_rank.get(bid, 1_000_000))) + assignment[it_id] = tgt + load[tgt] += w + initially_assigned.append(it_id) + + def score(loads: Dict[str, float]) -> float: + s = 0.0 + for bid in bin_ids: + denom = cap[bid] * max(1.0 - headroom, 1e-6) + lj = loads[bid] / denom + over = max(0.0, lj - 1.0) + s += over * over + # Add a small balancing term + if alpha > 0.0: + for bid in bin_ids: + lj = loads[bid] / cap[bid] + s += alpha * (lj * lj) + return s + + # Initial score + base_score = score(load) + + # Decide moves by considering HRW top-L candidates per item + move_budget = params.get("move_budget_per_run") + if move_budget is None: + move_budget = max(1, min(32, int(0.01 * max(1, len(item_list))))) + moves_left = int(move_budget) + + # Worklist: heavier items first + work = sorted(item_list, key=lambda t: (-t[1], t[0])) + changed_items: List[str] = [] + + for it_id, w in work: + if moves_left <= 0: + break + cur = assignment.get(it_id) + candidates = hrw_candidates(it_id, bin_ids, weights_by_bin, max(L, 1), salt) + # Ensure current bin is considered + if cur and cur not in candidates: + candidates.append(cur) + best_gain = 0.0 + best_tgt = cur + for tgt in candidates: + if tgt == cur: + continue + # simulate move + if cur: + load[cur] -= w + load[tgt] += w + new_score = score(load) + # revert + load[tgt] -= w + if cur: + load[cur] += w + gain = base_score - new_score + if gain > best_gain: + best_gain = gain + best_tgt = tgt + + if best_tgt and best_tgt != cur: + # Cooldown check + last_ts = float(last_change_ts.get(it_id, 0.0)) + age = max(0.0, float(now_ts) - last_ts) + if age < float(cooldown_s): + continue + # Movement penalty + penalty = 0.0 + if penalty_k > 0.0 and penalty_tau > 0.0: + penalty = penalty_k * float(w) * math.exp(-age / penalty_tau) + net_gain = best_gain - penalty + # Hysteresis threshold: relative to base_score magnitude or absolute small value if base is tiny + threshold = max(hysteresis * max(1.0, base_score), 1e-6) + if net_gain >= threshold: + # apply move + if cur: + load[cur] -= w + load[best_tgt] += w + assignment[it_id] = best_tgt + changed_items.append(it_id) + # update base score and budget + base_score -= best_gain + moves_left -= 1 + + # Mark initial placements as changes so callers can timestamp them + for iid in initially_assigned: + if iid not in changed_items: + changed_items.append(iid) + + return assignment, changed_items + + +def load_state(path: str) -> Dict[str, Any]: + """ + Load planner state from JSON. If missing or invalid, return a fresh state. + """ + fresh = { + "algo_version": "v1", + "salt": None, + "assignments": {}, + "last_change_ts": {}, + "updated_at": None, + } + try: + if not os.path.exists(path): + return fresh + with open(path, 'r', encoding='utf-8') as f: + data = json.load(f) + # Minimal validation + if not isinstance(data, dict): + return fresh + for k in ["algo_version", "salt", "assignments", "last_change_ts", "updated_at"]: + if k not in data: + data[k] = fresh.get(k) + if data.get("salt") is None: + data["salt"] = _generate_salt() + # TTL: invalidate if older than 24 hours + try: + updated_at = float(data.get("updated_at") or 0.0) + if updated_at <= 0.0: + return data + now = time.time() + if (now - updated_at) > 24 * 3600: + # Regenerate: return a fresh state with a new salt + fresh["salt"] = _generate_salt() + return fresh + except Exception: + # If parsing fails, return fresh + fresh["salt"] = _generate_salt() + return fresh + return data + except Exception: + return fresh + + +def save_state(path: str, state: Dict[str, Any]) -> None: + """ + Save planner state to JSON. Creates parent directory if necessary. + """ + try: + os.makedirs(os.path.dirname(path), exist_ok=True) + except Exception: + pass + state = dict(state) + state["updated_at"] = time.time() + if state.get("salt") is None: + state["salt"] = _generate_salt() + with open(path, 'w', encoding='utf-8') as f: + json.dump(state, f, indent=2, sort_keys=True) + + +def _generate_salt() -> str: + return hashlib.sha256(str(time.time_ns()).encode('utf-8')).hexdigest() + + +def hrw_candidates( + item_id: str, + bin_ids: List[str], + weights_by_bin: Dict[str, float], + L: int, + salt: str, +) -> List[str]: + """ + Weighted Rendezvous (HRW) hashing: return top-L candidate bins for an item. + + score(bin) = weight(bin) / -ln(U), where U derives deterministically from + SHA-256(salt || item_id || bin_id). + """ + scores: List[Tuple[float, str]] = [] + for bid in bin_ids: + w = float(weights_by_bin.get(bid, 1.0)) + # Deterministic uniform in (0,1) + h = hashlib.sha256((salt + '|' + str(item_id) + '|' + str(bid)).encode('utf-8')).digest() + # Use first 8 bytes for a 64-bit integer + r = int.from_bytes(h[:8], byteorder='big', signed=False) + # Map to (0,1). Avoid 0 by adding a tiny epsilon. + U = max((r / 2**64), 1e-12) + score = w / (-math.log(U)) if U < 1.0 else float('inf') + scores.append((score, bid)) + scores.sort(key=lambda t: (-t[0], t[1])) + if L <= 0: + return [] + return [bid for _, bid in scores[:min(L, len(scores))]] diff --git a/src/build_dpkg.sh b/src/build_dpkg.sh index f0167bb0..54044266 100755 --- a/src/build_dpkg.sh +++ b/src/build_dpkg.sh @@ -24,6 +24,7 @@ LQOS_FILES=( integrationRestHttp.py integrationSonar.py integrationSplynx.py + bin_planner.py integrationUISP.py LibreQoS.py lqos.example diff --git a/src/build_rust.sh b/src/build_rust.sh index d57b8b99..64e3193e 100755 --- a/src/build_rust.sh +++ b/src/build_rust.sh @@ -98,6 +98,14 @@ popd > /dev/null || exit cp rust/target/$TARGET/liblqos_python.so ./liblqos_python.so.new mv liblqos_python.so.new liblqos_python.so +# Ensure the internal planner module is present for LibreQoS.py +if [ ! -f "bin_planner.py" ]; then + echo "Warning: bin_planner.py not found in $(pwd). The planner will be unavailable to LibreQoS.py." + echo "If you are updating a running system, make sure bin_planner.py is deployed alongside LibreQoS.py." +else + echo "bin_planner.py present." +fi + # Update the lqos_api binary echo "Updating lqos_api binary..." bash ./update_api.sh || echo "Warning: Failed to update lqos_api (continuing)." -- knotmirror 0.0.1 From 5fc06d6693e1a228969e1ab8444358281d64c147 Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Thu, 6 Nov 2025 13:23:41 -0600 Subject: [PATCH 41/58] Fix: Ignore obviously defaulted circuits. --- src/LibreQoS.py | 30 +++++++++++--- .../node_manager/js_build/src/cpu_weights.js | 9 ++++- .../node_manager/local_api/cpu_affinity.rs | 40 ++++++++++++------- 3 files changed, 58 insertions(+), 21 deletions(-) diff --git a/src/LibreQoS.py b/src/LibreQoS.py index a85643b3..b68acdf7 100755 --- a/src/LibreQoS.py +++ b/src/LibreQoS.py @@ -688,6 +688,14 @@ def refreshShapers(): # If a specific circuit weight exists, prefer it if 'circuitID' in circuit and str(circuit['circuitID']) in weight_by_circuit_id: w = weight_by_circuit_id[str(circuit['circuitID'])] + # Ignore placeholder default rates for weight purposes + try: + default_rate = float(generated_pn_download_mbps()) + max_dl = float(circuit.get('maxDownload', 0)) + if abs(max_dl - default_rate) < 1e-6: + w = 0.0 + except Exception: + pass items.append({"id": item_id, "weight": float(w)}) # Prepare bins and capacities @@ -1070,15 +1078,27 @@ def refreshShapers(): "classMinor": hex(minorByCPU[queue]), "comment": circuit['comment'] } - # Attach the planner weight if available (real weighting used by the planner) + # Attach the planner weight used by the planner/UI summary + # Priority: explicit weight -> fallback to maxDownload try: cid = str(circuit.get('circuitID','')) + w = None if cid in weight_by_circuit_id: w = float(weight_by_circuit_id[cid]) - # Treat 1000 as a sentinel default from Insight; use maxDownload instead - if abs(w - 1000.0) < 1e-6: - w = float(maxDownload) - thisNewCircuitItemForNetwork['planner_weight'] = w + if w is None: + w = float(maxDownload) + # Treat 1000 as a sentinel default from Insight; use maxDownload instead + if abs(w - 1000.0) < 1e-6: + w = float(maxDownload) + # If the circuit's configured rate equals the generated PN default, + # ignore it for weight purposes. + try: + default_rate = float(generated_pn_download_mbps()) + if abs(float(maxDownload) - default_rate) < 1e-6: + w = 0.0 + except Exception: + pass + thisNewCircuitItemForNetwork['planner_weight'] = w except Exception: pass # Preserve optional per-circuit SQM override for downstream bakery call diff --git a/src/rust/lqosd/src/node_manager/js_build/src/cpu_weights.js b/src/rust/lqosd/src/node_manager/js_build/src/cpu_weights.js index bc7360b1..42e5890f 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/cpu_weights.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/cpu_weights.js @@ -192,6 +192,9 @@ function renderCircuits(page) { page.items.forEach((c) => { const tr = document.createElement("tr"); + if (c.ignored || (c.weight !== undefined && c.weight <= 0)) { + tr.classList.add('text-muted'); + } const idCell = document.createElement("td"); if (c.circuit_id) { const a = document.createElement("a"); @@ -206,7 +209,11 @@ function renderCircuits(page) { tr.appendChild(simpleRow(c.parent_node || "")); tr.appendChild(simpleRow(c.classid || "")); const weightCell = document.createElement('td'); - weightCell.innerText = (c.weight && c.weight > 0) ? c.weight.toLocaleString() : '-'; + if (c.ignored || (c.weight !== undefined && c.weight <= 0)) { + weightCell.innerHTML = "ignored"; + } else { + weightCell.innerText = (c.weight && c.weight > 0) ? c.weight.toLocaleString() : '-'; + } tr.appendChild(weightCell); tr.appendChild(simpleRow(fmtMbps(c.max_mbps))); tr.appendChild(simpleRow(String(c.ip_count || 0))); diff --git a/src/rust/lqosd/src/node_manager/local_api/cpu_affinity.rs b/src/rust/lqosd/src/node_manager/local_api/cpu_affinity.rs index 652213ab..1ea5b0a4 100644 --- a/src/rust/lqosd/src/node_manager/local_api/cpu_affinity.rs +++ b/src/rust/lqosd/src/node_manager/local_api/cpu_affinity.rs @@ -31,6 +31,7 @@ pub struct CircuitBrief { pub max_mbps: f64, pub weight: f64, pub ip_count: usize, + pub ignored: bool, } #[derive(Serialize, Clone, Debug)] @@ -52,6 +53,7 @@ struct CircuitRecord { min_up: f64, max_up: f64, planner_weight: f64, + has_planner_weight: bool, classid_down: Option, classid_up: Option, circuit_id: Option, @@ -131,20 +133,20 @@ fn add_circuit_records( if let Some(Value::String(s)) = cm.get("cpuNum") { rec.cpu_down = parse_hex_u32(s); } else if let Some(Value::String(s)) = cm.get("classMajor") { - if let Some(mut v) = parse_hex_u32(s) { rec.cpu_down = Some(v.saturating_sub(1)); } + if let Some(v) = parse_hex_u32(s) { rec.cpu_down = Some(v.saturating_sub(1)); } } else if let Some(Value::String(s)) = cm.get("classid") { // Fallback: parse major from TC handle like "0x1:0x51" if let Some((maj, _)) = s.split_once(':') { - if let Some(mut v) = parse_hex_u32(maj) { rec.cpu_down = Some(v.saturating_sub(1)); } + if let Some(v) = parse_hex_u32(maj) { rec.cpu_down = Some(v.saturating_sub(1)); } } } if let Some(Value::String(s)) = cm.get("up_cpuNum") { rec.cpu_up = parse_hex_u32(s); } else if let Some(Value::String(s)) = cm.get("up_classMajor") { - if let Some(mut v) = parse_hex_u32(s) { rec.cpu_up = Some(v.saturating_sub(1)); } + if let Some(v) = parse_hex_u32(s) { rec.cpu_up = Some(v.saturating_sub(1)); } } else if let Some(Value::String(s)) = cm.get("up_classid") { if let Some((maj, _)) = s.split_once(':') { - if let Some(mut v) = parse_hex_u32(maj) { rec.cpu_up = Some(v.saturating_sub(1)); } + if let Some(v) = parse_hex_u32(maj) { rec.cpu_up = Some(v.saturating_sub(1)); } } } // classids @@ -170,6 +172,7 @@ fn add_circuit_records( // planner weight if present if let Some(v) = cm.get("planner_weight").and_then(val_as_f64) { rec.planner_weight = v; + rec.has_planner_weight = true; } // identity if let Some(Value::String(s)) = cm.get("circuitID") { @@ -243,19 +246,24 @@ pub async fn cpu_affinity_summary() -> Json { let mut up: HashMap = HashMap::new(); for c in circuits.iter() { + let ignored = c.has_planner_weight && c.planner_weight <= 0.0; if let Some(cpu) = c.cpu_down { - let entry = down.entry(cpu).or_insert((0, 0.0, 0.0, 0.0)); - entry.0 += 1; - entry.1 += c.min_down; - entry.2 += c.max_down; - entry.3 += c.planner_weight; + if !ignored { + let entry = down.entry(cpu).or_insert((0, 0.0, 0.0, 0.0)); + entry.0 += 1; + entry.1 += c.min_down; + entry.2 += c.max_down; + entry.3 += c.planner_weight; + } } if let Some(cpu) = c.cpu_up { - let entry = up.entry(cpu).or_insert((0, 0.0, 0.0, 0.0)); - entry.0 += 1; - entry.1 += c.min_up; - entry.2 += c.max_up; - entry.3 += c.planner_weight; + if !ignored { + let entry = up.entry(cpu).or_insert((0, 0.0, 0.0, 0.0)); + entry.0 += 1; + entry.1 += c.min_up; + entry.2 += c.max_up; + entry.3 += c.planner_weight; + } } } @@ -330,6 +338,7 @@ pub async fn cpu_affinity_circuits( max_mbps: if direction == "up" { c.max_up } else { c.max_down }, weight: c.planner_weight, ip_count: c.ip_count, + ignored: c.has_planner_weight && c.planner_weight <= 0.0, }) .collect(); @@ -402,6 +411,7 @@ pub async fn cpu_affinity_circuits_all( max_mbps: if direction == "up" { c.max_up } else { c.max_down }, weight: c.planner_weight, ip_count: c.ip_count, + ignored: c.has_planner_weight && c.planner_weight <= 0.0, }) .collect(); @@ -457,7 +467,7 @@ pub async fn cpu_affinity_preview_weights( .circuit_id .clone() .or(c.circuit_name.clone()) - .unwrap_or_else(|| String::new()), + .unwrap_or_default(), weight: if direction == "up" { c.max_up } else { c.max_down }, }) .collect(); -- knotmirror 0.0.1 From d5348d003d20f8b5e59f8ac4f02bffa6b441b11f Mon Sep 17 00:00:00 2001 From: "Herbert \"TheBracket\" Wolverson" Date: Thu, 6 Nov 2025 16:24:35 -0600 Subject: [PATCH 42/58] UI tabs (#839) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Feat: The UI now supports tabs. * UI: Traffic Overview dashlets (Top ASN, Children, World Map).\n- Add WS channels: EndpointLatLon, AsnTopDownload/Upload with tickers\n- Add color-blind friendly scales; respect day/night\n- Client-side smoothing + empty-state for Sankey + Maps\n- Update default Overview tab; move existing to System Overview\n\nNote: Excludes planning doc. * Fix: World maps blank — dynamically load ECharts world map JSON if not present; then render points. * Prefers local world map asset: try vendor/echarts_world.js first, fallback to CDN. Document shipping the asset in vendor. * Vendor the world map * Layout: If a saved old (pre-tabs) layout exists, reset to new default tabs instead of converting to a single 'Dashboard' tab; clear stale saved layout. * Dark mode: force graph container background to pure black for world maps to improve contrast; keep light mode white. * Overview: add 'Last 5 Minutes Throughput' as full-width (size 12) at top; remove smaller ring from System Overview. * WIP: Tweaking the map displays * WIP: World map colors. * WIP: World map colors. * WIP: World map colors. * WIP: World map colors. * WIP: World map colors. * WIP: World map colors. --- .../src/dashlets/children_sankey_down.js | 110 +++++ .../src/dashlets/children_sankey_up.js | 102 ++++ .../js_build/src/dashlets/dashlet_index.js | 23 +- .../js_build/src/dashlets/top_asn_download.js | 148 ++++++ .../js_build/src/dashlets/top_asn_upload.js | 135 +++++ .../js_build/src/dashlets/world_map_down.js | 169 +++++++ .../js_build/src/dashlets/world_map_up.js | 95 ++++ .../js_build/src/helpers/color_scales.js | 46 ++ .../src/node_manager/js_build/src/index.js | 83 +++- .../src/lq_js_common/dashboard/dashboard.js | 467 +++++++++++------- .../dashboard/dashboard_editor.js | 461 ++++++++++++++--- .../src/lq_js_common/dashboard/layout.js | 121 ++++- .../src/node_manager/static2/vendor/world.js | 20 + .../src/node_manager/ws/published_channels.rs | 3 + src/rust/lqosd/src/node_manager/ws/ticker.rs | 4 + .../src/node_manager/ws/ticker/asn_top.rs | 139 ++++++ .../node_manager/ws/ticker/endpoint_latlon.rs | 50 ++ 17 files changed, 1882 insertions(+), 294 deletions(-) create mode 100644 src/rust/lqosd/src/node_manager/js_build/src/dashlets/children_sankey_down.js create mode 100644 src/rust/lqosd/src/node_manager/js_build/src/dashlets/children_sankey_up.js create mode 100644 src/rust/lqosd/src/node_manager/js_build/src/dashlets/top_asn_download.js create mode 100644 src/rust/lqosd/src/node_manager/js_build/src/dashlets/top_asn_upload.js create mode 100644 src/rust/lqosd/src/node_manager/js_build/src/dashlets/world_map_down.js create mode 100644 src/rust/lqosd/src/node_manager/js_build/src/dashlets/world_map_up.js create mode 100644 src/rust/lqosd/src/node_manager/js_build/src/helpers/color_scales.js create mode 100644 src/rust/lqosd/src/node_manager/static2/vendor/world.js create mode 100644 src/rust/lqosd/src/node_manager/ws/ticker/asn_top.rs create mode 100644 src/rust/lqosd/src/node_manager/ws/ticker/endpoint_latlon.rs diff --git a/src/rust/lqosd/src/node_manager/js_build/src/dashlets/children_sankey_down.js b/src/rust/lqosd/src/node_manager/js_build/src/dashlets/children_sankey_down.js new file mode 100644 index 00000000..5a6dcc4e --- /dev/null +++ b/src/rust/lqosd/src/node_manager/js_build/src/dashlets/children_sankey_down.js @@ -0,0 +1,110 @@ +import {BaseDashlet} from "../lq_js_common/dashboard/base_dashlet"; +import {DashboardGraph} from "../graphs/dashboard_graph"; +import {colorByRetransmitPct} from "../helpers/color_scales"; + +class ChildrenSankeyGraph extends DashboardGraph { + constructor(id, direction) { + super(id); + this.direction = direction; // 'down' or 'up' + this.option = { + series: [ + { type: 'sankey', data: [], links: [], nodeAlign: direction==='up'?'right':'left', lineStyle: { color: 'gradient', curveness: 0.5 } } + ], + tooltip: { show: true } + }; + this.chart.setOption(this.option); + } + update(items) { + const nodes = [{ name: 'Shaper' }]; + const links = []; + items.forEach(it => { + const color = colorByRetransmitPct(it.rxmit ?? 0); + nodes.push({ name: it.name, itemStyle: { color } }); + if (this.direction === 'down') { + links.push({ source: it.name, target: 'Shaper', value: it.value }); + } else { + links.push({ source: 'Shaper', target: it.name, value: it.value }); + } + }); + this.option.series[0].data = nodes; + this.option.series[0].links = links; + this.chart.hideLoading(); + this.chart.setOption(this.option); + } +} + +export class ShaperChildrenDown extends BaseDashlet { + constructor(slot) { + super(slot); + this.last=null; this._emptyId = this.id + "_empty"; + this._smooth = new Map(); + this._ALPHA = 0.3; this._ALPHA_RX = 0.2; this._DECAY = 0.15; this._LINGER = 3; + } + canBeSlowedDown(){ return true; } + title(){ return "Shaper Children (Download)"; } + tooltip(){ return "
Child Throughput

Top child nodes by download throughput."; } + subscribeTo(){ return ["TreeSummary"]; } + buildContainer(){ let b = super.buildContainer(); b.appendChild(this.graphDiv()); return b; } + setup(){ this.graph = new ChildrenSankeyGraph(this.graphDivId(), 'down'); if (this.last) this.graph.update(this.last); } + _showEmpty(show, msg = "No recent data"){ + const card = document.getElementById(this.id); + if (!card) return; + let empty = document.getElementById(this._emptyId); + if (!empty) { + empty = document.createElement('div'); + empty.id = this._emptyId; + empty.classList.add('text-center','text-muted','small'); + empty.style.padding = '12px'; + card.appendChild(empty); + } + empty.textContent = msg; + const graph = document.getElementById(this.graphDivId()); + if (show) { + empty.style.display = ''; + if (graph) graph.style.display = 'none'; + } else { + empty.style.display = 'none'; + if (graph) graph.style.display = ''; + } + } + _smoothItems(items){ + const present = new Set(); + items.forEach(it => { + present.add(it.name); + const prev = this._smooth.get(it.name) || { v: 0, rx: 0, linger: this._LINGER }; + const v = (1 - this._ALPHA) * prev.v + this._ALPHA * it.value; + const rx = (1 - this._ALPHA_RX) * prev.rx + this._ALPHA_RX * (it.rxmit || 0); + this._smooth.set(it.name, { v, rx, linger: this._LINGER }); + }); + for (const [name, state] of Array.from(this._smooth.entries())) { + if (!present.has(name)) { + const v = state.v * (1 - this._DECAY); + const linger = state.linger - 1; + if (linger <= 0 || v < 1) this._smooth.delete(name); else this._smooth.set(name, { v, rx: state.rx, linger }); + } + } + let out = Array.from(this._smooth.entries()).map(([name,s]) => ({ name, value: s.v, rxmit: s.rx })); + out.sort((a,b)=> b.value - a.value); + return out.slice(0,9); + } + onMessage(msg){ + if (msg.event !== "TreeSummary") return; + // msg.data: [ [id, metrics], [id, metrics], ... ] - first is root + let rows = (msg.data || []).slice(1).map(r => { + const m = r[1] || {}; + const name = m.name || String(r[0]); + const down = Number((m.current_throughput||[0,0])[0]||0); + const rxmit = (m.current_tcp_packets && m.current_tcp_packets[0] > 0) + ? ( (m.current_retransmits?.[0]||0) / Math.max(1, m.current_tcp_packets?.[0]||0) ) * 100.0 + : 0; + return { name, value: down, rxmit }; + }); + rows = this._smoothItems(rows); + const hasData = rows.some(r => r.value > 0.5); + this._showEmpty(!hasData); + if (hasData) { + this.last = rows; + this.graph.update(rows); + } + } +} diff --git a/src/rust/lqosd/src/node_manager/js_build/src/dashlets/children_sankey_up.js b/src/rust/lqosd/src/node_manager/js_build/src/dashlets/children_sankey_up.js new file mode 100644 index 00000000..00015933 --- /dev/null +++ b/src/rust/lqosd/src/node_manager/js_build/src/dashlets/children_sankey_up.js @@ -0,0 +1,102 @@ +import {BaseDashlet} from "../lq_js_common/dashboard/base_dashlet"; +import {DashboardGraph} from "../graphs/dashboard_graph"; +import {colorByRetransmitPct} from "../helpers/color_scales"; + +class ChildrenSankeyGraphUp extends DashboardGraph { + constructor(id) { + super(id); + this.option = { + series: [ { type: 'sankey', data: [], links: [], nodeAlign: 'right', lineStyle: { color: 'gradient', curveness: 0.5 } } ], + tooltip: { show: true } + }; + this.chart.setOption(this.option); + } + update(items){ + const nodes = [{ name: 'Shaper' }]; + const links = []; + items.forEach(it => { + const color = colorByRetransmitPct(it.rxmit ?? 0); + nodes.push({ name: it.name, itemStyle: { color } }); + links.push({ source: 'Shaper', target: it.name, value: it.value }); + }); + this.option.series[0].data = nodes; + this.option.series[0].links = links; + this.chart.hideLoading(); + this.chart.setOption(this.option); + } +} + +export class ShaperChildrenUp extends BaseDashlet { + constructor(slot){ + super(slot); + this.last=null; this._emptyId = this.id + "_empty"; + this._smooth = new Map(); + this._ALPHA = 0.3; this._ALPHA_RX = 0.2; this._DECAY = 0.15; this._LINGER = 3; + } + canBeSlowedDown(){ return true; } + title(){ return "Shaper Children (Upload)"; } + tooltip(){ return "

Child Throughput

Top child nodes by upload throughput."; } + subscribeTo(){ return ["TreeSummary"]; } + buildContainer(){ let b=super.buildContainer(); b.appendChild(this.graphDiv()); return b; } + setup(){ this.graph = new ChildrenSankeyGraphUp(this.graphDivId()); if (this.last) this.graph.update(this.last); } + _showEmpty(show, msg = "No recent data"){ + const card = document.getElementById(this.id); + if (!card) return; + let empty = document.getElementById(this._emptyId); + if (!empty) { + empty = document.createElement('div'); + empty.id = this._emptyId; + empty.classList.add('text-center','text-muted','small'); + empty.style.padding = '12px'; + card.appendChild(empty); + } + empty.textContent = msg; + const graph = document.getElementById(this.graphDivId()); + if (show) { + empty.style.display = ''; + if (graph) graph.style.display = 'none'; + } else { + empty.style.display = 'none'; + if (graph) graph.style.display = ''; + } + } + _smoothItems(items){ + const present = new Set(); + items.forEach(it => { + present.add(it.name); + const prev = this._smooth.get(it.name) || { v: 0, rx: 0, linger: this._LINGER }; + const v = (1 - this._ALPHA) * prev.v + this._ALPHA * it.value; + const rx = (1 - this._ALPHA_RX) * prev.rx + this._ALPHA_RX * (it.rxmit || 0); + this._smooth.set(it.name, { v, rx, linger: this._LINGER }); + }); + for (const [name, state] of Array.from(this._smooth.entries())) { + if (!present.has(name)) { + const v = state.v * (1 - this._DECAY); + const linger = state.linger - 1; + if (linger <= 0 || v < 1) this._smooth.delete(name); else this._smooth.set(name, { v, rx: state.rx, linger }); + } + } + let out = Array.from(this._smooth.entries()).map(([name,s]) => ({ name, value: s.v, rxmit: s.rx })); + out.sort((a,b)=> b.value - a.value); + return out.slice(0,9); + } + onMessage(msg){ + if (msg.event !== "TreeSummary") return; + let rows = (msg.data || []).slice(1).map(r => { + const m = r[1] || {}; + const name = m.name || String(r[0]); + const up = Number((m.current_throughput||[0,0])[1]||0); + const rxmit = (m.current_tcp_packets && m.current_tcp_packets[1] > 0) + ? ( (m.current_retransmits?.[1]||0) / Math.max(1, m.current_tcp_packets?.[1]||0) ) * 100.0 + : 0; + return { name, value: up, rxmit }; + }); + rows = this._smoothItems(rows); + const hasData = rows.some(r => r.value > 0.5); + this._showEmpty(!hasData); + if (hasData) { + this.last = rows; + this.graph.update(rows); + } + } +} diff --git a/src/rust/lqosd/src/node_manager/js_build/src/dashlets/dashlet_index.js b/src/rust/lqosd/src/node_manager/js_build/src/dashlets/dashlet_index.js index 0b8edded..e5c13ddb 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/dashlets/dashlet_index.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/dashlets/dashlet_index.js @@ -30,6 +30,13 @@ import {LtsLast24Hours} from "./ltsLast24Hours"; import {TcpRetransmitsDash} from "./total_retransmits"; import {StormguardStatusDashlet} from "./stormguard_status"; import {BakeryStatusDashlet} from "./bakery_status"; +// New Traffic Overview dashlets +import {ShaperTopAsnDownload} from "./top_asn_download"; +import {ShaperTopAsnUpload} from "./top_asn_upload"; +import {ShaperChildrenDown} from "./children_sankey_down"; +import {ShaperChildrenUp} from "./children_sankey_up"; +import {ShaperWorldMapDown} from "./world_map_down"; +import {ShaperWorldMapUp} from "./world_map_up"; export const DashletMenu = [ { name: "Throughput Bits/Second", tag: "throughputBps", size: 3, category: "Throughput" }, @@ -64,6 +71,13 @@ export const DashletMenu = [ { name: "(Insight) Last 24 Hours", tag: "ltsLast24", size: 3, category: "Insight" }, { name: "Stormguard Bandwidth Adjustments", tag: "stormguardStatus", size: 6, category: "Queue Management" }, { name: "Bakery Circuit Activity", tag: "bakeryStatus", size: 6, category: "Queue Management" }, + // Traffic Overview (Insight-like) + { name: "Shaper Top ASN (Download)", tag: "shaperTopAsnDown", size: 6, category: "Traffic" }, + { name: "Shaper Top ASN (Upload)", tag: "shaperTopAsnUp", size: 6, category: "Traffic" }, + { name: "Shaper Children (Download)", tag: "shaperChildrenDown", size: 6, category: "Traffic" }, + { name: "Shaper Children (Upload)", tag: "shaperChildrenUp", size: 6, category: "Traffic" }, + { name: "Shaper World Map (Download)", tag: "shaperWorldMapDown", size: 6, category: "Traffic" }, + { name: "Shaper World Map (Upload)", tag: "shaperWorldMapUp", size: 6, category: "Traffic" }, ]; export function widgetFactory(widgetName, count) { @@ -101,10 +115,17 @@ export function widgetFactory(widgetName, count) { case "ltsLast24" : widget = new LtsLast24Hours(count); break; case "stormguardStatus" : widget = new StormguardStatusDashlet(count); break; case "bakeryStatus" : widget = new BakeryStatusDashlet(count); break; + // Traffic Overview + case "shaperTopAsnDown" : widget = new ShaperTopAsnDownload(count); break; + case "shaperTopAsnUp" : widget = new ShaperTopAsnUpload(count); break; + case "shaperChildrenDown": widget = new ShaperChildrenDown(count); break; + case "shaperChildrenUp" : widget = new ShaperChildrenUp(count); break; + case "shaperWorldMapDown": widget = new ShaperWorldMapDown(count); break; + case "shaperWorldMapUp" : widget = new ShaperWorldMapUp(count); break; default: { console.log("I don't know how to construct a widget of type [" + widgetName + "]"); return null; } } return widget; -} \ No newline at end of file +} diff --git a/src/rust/lqosd/src/node_manager/js_build/src/dashlets/top_asn_download.js b/src/rust/lqosd/src/node_manager/js_build/src/dashlets/top_asn_download.js new file mode 100644 index 00000000..c5d9eedb --- /dev/null +++ b/src/rust/lqosd/src/node_manager/js_build/src/dashlets/top_asn_download.js @@ -0,0 +1,148 @@ +import {BaseDashlet} from "../lq_js_common/dashboard/base_dashlet"; +import {DashboardGraph} from "../graphs/dashboard_graph"; +import {colorByRetransmitPct} from "../helpers/color_scales"; + +class TopAsnSankeyGraph extends DashboardGraph { + constructor(id, direction) { + super(id); + this.direction = direction; // 'down' or 'up' + this.option = { + tooltip: { show: true }, + series: [ + { + type: 'sankey', + data: [], + links: [], + nodeAlign: direction === 'up' ? 'right' : 'left', + lineStyle: { color: 'gradient', curveness: 0.5 }, + } + ] + }; + this.chart.setOption(this.option); + } + + update(items) { + const nodes = []; + const links = []; + const shaperNode = { name: 'Shaper' }; + nodes.push(shaperNode); + + items.forEach((row, idx) => { + const color = colorByRetransmitPct(row.rxmit ?? 0); + nodes.push({ name: row.name, itemStyle: { color } }); + if (this.direction === 'down') { + links.push({ source: row.name, target: 'Shaper', value: row.value }); + } else { + links.push({ source: 'Shaper', target: row.name, value: row.value }); + } + }); + + this.option.series[0].data = nodes; + this.option.series[0].links = links; + this.chart.hideLoading(); + this.chart.setOption(this.option); + } +} + +export class ShaperTopAsnDownload extends BaseDashlet { + constructor(slot) { + super(slot); + this.last = null; + this._emptyId = this.id + "_empty"; + // Smoothing state + this._smooth = new Map(); // name -> {v, rx, linger} + this._ALPHA = 0.3; // EMA factor for values + this._ALPHA_RX = 0.2; // EMA factor for retransmit% + this._DECAY = 0.15; // decay when absent (fraction per tick) + this._LINGER = 3; // keep absent items for a few ticks + } + canBeSlowedDown() { return true; } + title() { return "Shaper Top ASN (Download)"; } + tooltip() { return "

Top Download ASNs

Aggregated from live top flows by rate (bps)."; } + subscribeTo() { return ["AsnTopDownload", "TopFlowsRate"]; } + buildContainer() { let b = super.buildContainer(); b.appendChild(this.graphDiv()); return b; } + setup() { this.graph = new TopAsnSankeyGraph(this.graphDivId(), 'down'); if (this.last) this.graph.update(this.last); } + _showEmpty(show, msg = "No recent data") { + const card = document.getElementById(this.id); + if (!card) return; + let empty = document.getElementById(this._emptyId); + if (!empty) { + empty = document.createElement('div'); + empty.id = this._emptyId; + empty.classList.add('text-center','text-muted','small'); + empty.style.padding = '12px'; + card.appendChild(empty); + } + empty.textContent = msg; + const graph = document.getElementById(this.graphDivId()); + if (show) { + empty.style.display = ''; + if (graph) graph.style.display = 'none'; + } else { + empty.style.display = 'none'; + if (graph) graph.style.display = ''; + } + } + _smoothItems(items) { + const present = new Set(); + // Update present items + items.forEach(it => { + present.add(it.name); + const prev = this._smooth.get(it.name) || { v: 0, rx: 0, linger: this._LINGER }; + const v = (1 - this._ALPHA) * prev.v + this._ALPHA * it.value; + const rx = (1 - this._ALPHA_RX) * prev.rx + this._ALPHA_RX * (it.rxmit || 0); + this._smooth.set(it.name, { v, rx, linger: this._LINGER }); + }); + // Decay missing items + for (const [name, state] of Array.from(this._smooth.entries())) { + if (!present.has(name)) { + const v = state.v * (1 - this._DECAY); + const linger = state.linger - 1; + if (linger <= 0 || v < 1) { + this._smooth.delete(name); + } else { + this._smooth.set(name, { v, rx: state.rx, linger }); + } + } + } + // Build output + let out = Array.from(this._smooth.entries()).map(([name, s]) => ({ name, value: s.v, rxmit: s.rx })); + out.sort((a,b)=> b.value - a.value); + return out.slice(0, 9); + } + onMessage(msg) { + if (msg.event === "AsnTopDownload") { + let items = (msg.data || []).map(r => ({ name: r.name, value: Number(r.value||0), rxmit: Number(r.retransmit_percent||0) })); + items = this._smoothItems(items); + const hasData = items.some(it => it.value > 0.5); + this._showEmpty(!hasData); + if (hasData) { + this.last = items; + this.graph.update(items); + } + return; + } + if (msg.event !== "TopFlowsRate") return; + const map = new Map(); + (msg.data || []).forEach(f => { + const key = f.remote_asn_name && f.remote_asn_name.length > 0 ? f.remote_asn_name : (f.remote_ip || "Unknown"); + const val = Number(f.rate_estimate_bps?.down || 0); + const rxmitD = (f.tcp_retransmits?.down || 0) / Math.max(1, f.packets_sent?.down || 0) * 100.0; // % + const cur = map.get(key) || { name: key, value: 0, rxmit: 0, samples: 0 }; + cur.value += val; + cur.rxmit += isFinite(rxmitD) ? rxmitD : 0; + cur.samples += 1; + map.set(key, cur); + }); + let items = Array.from(map.values()).map(v => ({ name: v.name, value: v.value, rxmit: v.samples ? v.rxmit / v.samples : 0 })); + items.sort((a,b)=> b.value - a.value); + items = items.slice(0, 9); + items = this._smoothItems(items); + const hasData = items.some(it => it.value > 0.5); + this._showEmpty(!hasData); + if (hasData) { + this.last = items; + this.graph.update(items); + } + } +} diff --git a/src/rust/lqosd/src/node_manager/js_build/src/dashlets/top_asn_upload.js b/src/rust/lqosd/src/node_manager/js_build/src/dashlets/top_asn_upload.js new file mode 100644 index 00000000..ee533cfa --- /dev/null +++ b/src/rust/lqosd/src/node_manager/js_build/src/dashlets/top_asn_upload.js @@ -0,0 +1,135 @@ +import {BaseDashlet} from "../lq_js_common/dashboard/base_dashlet"; +import {DashboardGraph} from "../graphs/dashboard_graph"; +import {colorByRetransmitPct} from "../helpers/color_scales"; + +class TopAsnSankeyGraphUp extends DashboardGraph { + constructor(id) { + super(id); + this.option = { + tooltip: { show: true }, + series: [ + { + type: 'sankey', + data: [], + links: [], + nodeAlign: 'right', + lineStyle: { color: 'gradient', curveness: 0.5 }, + } + ] + }; + this.chart.setOption(this.option); + } + update(items) { + const nodes = [{ name: 'Shaper' }]; + const links = []; + items.forEach(row => { + const color = colorByRetransmitPct(row.rxmit ?? 0); + nodes.push({ name: row.name, itemStyle: { color } }); + links.push({ source: 'Shaper', target: row.name, value: row.value }); + }); + this.option.series[0].data = nodes; + this.option.series[0].links = links; + this.chart.hideLoading(); + this.chart.setOption(this.option); + } +} + +export class ShaperTopAsnUpload extends BaseDashlet { + constructor(slot) { + super(slot); + this.last = null; + this._emptyId = this.id + "_empty"; + // Smoothing state + this._smooth = new Map(); // name -> {v, rx, linger} + this._ALPHA = 0.3; + this._ALPHA_RX = 0.2; + this._DECAY = 0.15; + this._LINGER = 3; + } + canBeSlowedDown() { return true; } + title() { return "Shaper Top ASN (Upload)"; } + tooltip() { return "

Top Upload ASNs

Aggregated from live top flows by rate (bps)."; } + subscribeTo() { return ["AsnTopUpload", "TopFlowsRate"]; } + buildContainer() { let b = super.buildContainer(); b.appendChild(this.graphDiv()); return b; } + setup() { this.graph = new TopAsnSankeyGraphUp(this.graphDivId()); if (this.last) this.graph.update(this.last); } + _showEmpty(show, msg = "No recent data") { + const card = document.getElementById(this.id); + if (!card) return; + let empty = document.getElementById(this._emptyId); + if (!empty) { + empty = document.createElement('div'); + empty.id = this._emptyId; + empty.classList.add('text-center','text-muted','small'); + empty.style.padding = '12px'; + card.appendChild(empty); + } + empty.textContent = msg; + const graph = document.getElementById(this.graphDivId()); + if (show) { + empty.style.display = ''; + if (graph) graph.style.display = 'none'; + } else { + empty.style.display = 'none'; + if (graph) graph.style.display = ''; + } + } + _smoothItems(items) { + const present = new Set(); + items.forEach(it => { + present.add(it.name); + const prev = this._smooth.get(it.name) || { v: 0, rx: 0, linger: this._LINGER }; + const v = (1 - this._ALPHA) * prev.v + this._ALPHA * it.value; + const rx = (1 - this._ALPHA_RX) * prev.rx + this._ALPHA_RX * (it.rxmit || 0); + this._smooth.set(it.name, { v, rx, linger: this._LINGER }); + }); + for (const [name, state] of Array.from(this._smooth.entries())) { + if (!present.has(name)) { + const v = state.v * (1 - this._DECAY); + const linger = state.linger - 1; + if (linger <= 0 || v < 1) { + this._smooth.delete(name); + } else { + this._smooth.set(name, { v, rx: state.rx, linger }); + } + } + } + let out = Array.from(this._smooth.entries()).map(([name, s]) => ({ name, value: s.v, rxmit: s.rx })); + out.sort((a,b)=> b.value - a.value); + return out.slice(0, 9); + } + onMessage(msg) { + if (msg.event === "AsnTopUpload") { + let items = (msg.data || []).map(r => ({ name: r.name, value: Number(r.value||0), rxmit: Number(r.retransmit_percent||0) })); + items = this._smoothItems(items); + const hasData = items.some(it => it.value > 0.5); + this._showEmpty(!hasData); + if (hasData) { + this.last = items; + this.graph.update(items); + } + return; + } + if (msg.event !== "TopFlowsRate") return; + const map = new Map(); + (msg.data || []).forEach(f => { + const key = f.remote_asn_name && f.remote_asn_name.length > 0 ? f.remote_asn_name : (f.remote_ip || "Unknown"); + const val = Number(f.rate_estimate_bps?.up || 0); + const rxmitU = (f.tcp_retransmits?.up || 0) / Math.max(1, f.packets_sent?.up || 0) * 100.0; // % + const cur = map.get(key) || { name: key, value: 0, rxmit: 0, samples: 0 }; + cur.value += val; + cur.rxmit += isFinite(rxmitU) ? rxmitU : 0; + cur.samples += 1; + map.set(key, cur); + }); + let items = Array.from(map.values()).map(v => ({ name: v.name, value: v.value, rxmit: v.samples ? v.rxmit / v.samples : 0 })); + items.sort((a,b)=> b.value - a.value); + items = items.slice(0, 9); + items = this._smoothItems(items); + const hasData = items.some(it => it.value > 0.5); + this._showEmpty(!hasData); + if (hasData) { + this.last = items; + this.graph.update(items); + } + } +} diff --git a/src/rust/lqosd/src/node_manager/js_build/src/dashlets/world_map_down.js b/src/rust/lqosd/src/node_manager/js_build/src/dashlets/world_map_down.js new file mode 100644 index 00000000..5d35b3d4 --- /dev/null +++ b/src/rust/lqosd/src/node_manager/js_build/src/dashlets/world_map_down.js @@ -0,0 +1,169 @@ +import {BaseDashlet} from "../lq_js_common/dashboard/base_dashlet"; +import {DashboardGraph} from "../graphs/dashboard_graph"; +import {colorByRttMs} from "../helpers/color_scales"; +import {isDarkMode} from "../helpers/dark_mode"; + +function ensureWorldMap() { + try { + if (typeof echarts !== 'undefined' && echarts.getMap && echarts.getMap('world')) { + return Promise.resolve(); + } + } catch (_) {} + if (window._worldMapPromise) return window._worldMapPromise; + window._worldMapPromise = new Promise((resolve, reject) => { + // Try local vendor first (static2/vendor/world.js) + const load = (src, onfail) => { + const s = document.createElement('script'); + s.src = src; + s.onload = () => resolve(); + s.onerror = () => onfail ? onfail() : reject(); + document.head.appendChild(s); + }; + load('vendor/world.js', () => { + // Fallback to CDN if local not present + load('https://fastly.jsdelivr.net/npm/echarts@4.9.0/map/js/world.js'); + }); + }); + return window._worldMapPromise; +} + +export class WorldMap3DGraph extends DashboardGraph { + constructor(id) { + super(id); + // Do not dim the world map; remove the global 'muted' filter. + if (this.dom && this.dom.classList) { + this.dom.classList.remove('muted'); + } + const envColor = isDarkMode() ? '#000000' : '#e6eaef'; + const landColor = isDarkMode() ? '#6a6a6a' : '#bcbcbc'; + this.option = { + backgroundColor: 'transparent', + geo3D: { + map: 'world', + shading: 'realistic', + silent: true, + // Match page theme: black in dark mode, light grey in light mode + environment: envColor, + realisticMaterial: { roughness: 0.8, metalness: 0 }, + // Disable post-processing to avoid shimmer/pulsing + postEffect: { enable: false }, + groundPlane: { show: false }, + light: { + main: { intensity: 1.0, alpha: 30 }, + ambient: { intensity: 0.0 } + }, + viewControl: { distance: 70, alpha: 89, panMouseButton: 'left', rotateMouseButton: 'right' }, + itemStyle: { + color: landColor, + // Hide coastlines/outlines that appear as stray dots at this zoom + borderColor: landColor, + borderWidth: 0.3 + }, + regionHeight: 0.5 + }, + series: [ + { + type: 'scatter3D', + coordinateSystem: 'geo3D', + // Remove additive blending that causes glow in dark mode + // blendMode: 'lighter', + symbolSize: 2, + itemStyle: { opacity: 0.6 }, + lineStyle: { width: 0.2, opacity: 0.05 }, + data: [] + } + ] + }; + this.chart.setOption(this.option); + this.baseApplied = false; + } + update(data){ + this.chart.hideLoading(); + // Ensure the base option (with geo3D) is applied once after the world map is registered. + if (!this.baseApplied && typeof echarts !== 'undefined' && echarts.getMap && echarts.getMap('world')) { + this.chart.setOption(this.option, true); + this.baseApplied = true; + } + // Then only update series data to avoid re-rendering geo3D and post effects + this.chart.setOption({ series: [{ data }] }, false, false); + } + onThemeChange(){ + // Only adjust the environment to maintain appropriate background + const envColor = isDarkMode() ? '#000000' : '#e6eaef'; + const landColor = isDarkMode() ? '#6a6a6a' : '#bcbcbc'; + if (!this.option.geo3D) this.option.geo3D = {}; + this.option.geo3D.environment = envColor; + if (!this.option.geo3D.itemStyle) this.option.geo3D.itemStyle = {}; + this.option.geo3D.itemStyle.color = landColor; + this.option.geo3D.itemStyle.borderColor = landColor; + this.chart.setOption(this.option, true); + this.baseApplied = true; + } +} + +export class ShaperWorldMapDown extends BaseDashlet { + constructor(slot){ super(slot); this.last = null; this._emptyId = this.id + "_empty"; } + canBeSlowedDown(){ return true; } + title(){ return "Shaper World Map (Download)"; } + tooltip(){ return "

World Map

Endpoint locations sized by traffic and colored by RTT."; } + subscribeTo(){ return ["EndpointLatLon"]; } + buildContainer(){ let b=super.buildContainer(); b.appendChild(this.graphDiv()); return b; } + setup(){ this.graph = new WorldMap3DGraph(this.graphDivId()); if (this.last) this.graph.update(this.last); } + _showEmpty(show, msg = "No recent data"){ + const card = document.getElementById(this.id); + if (!card) return; + let empty = document.getElementById(this._emptyId); + if (!empty) { + empty = document.createElement('div'); + empty.id = this._emptyId; + empty.classList.add('text-center','text-muted','small'); + empty.style.padding = '12px'; + card.appendChild(empty); + } + empty.textContent = msg; + const graph = document.getElementById(this.graphDivId()); + if (show) { + empty.style.display = ''; + if (graph) graph.style.display = 'none'; + } else { + empty.style.display = 'none'; + if (graph) graph.style.display = ''; + } + } + onMessage(msg){ + if (msg.event !== "EndpointLatLon") return; + const rows = msg.data || []; + let maxBytes = 0; + for (let i=0;i maxBytes) maxBytes = b; + } + const minSize = 1, maxSize = 8; + const out = []; + for (let i=0;i 0) { + norm = Math.sqrt(bytes / maxBytes); + if (!isFinite(norm) || norm < 0) norm = 0; + if (norm > 1) norm = 1; + } + const size = Math.round(minSize + (maxSize - minSize) * norm); + out.push({ value: [lon, lat], symbolSize: size, itemStyle: { color, opacity: 0.6 } }); + } + const hasData = out.length > 0; + this._showEmpty(!hasData); + if (hasData) { + this.last = out; + ensureWorldMap().then(() => { + this.graph.update(out); + }).catch(() => { + // If the world map fails to load, still attempt to render points + this.graph.update(out); + }); + } + } +} diff --git a/src/rust/lqosd/src/node_manager/js_build/src/dashlets/world_map_up.js b/src/rust/lqosd/src/node_manager/js_build/src/dashlets/world_map_up.js new file mode 100644 index 00000000..f3908c5f --- /dev/null +++ b/src/rust/lqosd/src/node_manager/js_build/src/dashlets/world_map_up.js @@ -0,0 +1,95 @@ +import {BaseDashlet} from "../lq_js_common/dashboard/base_dashlet"; +import {WorldMap3DGraph as _WorldMap3DGraph} from "./world_map_down"; +import {colorByRttMs} from "../helpers/color_scales"; + +function ensureWorldMap() { + try { + if (typeof echarts !== 'undefined' && echarts.getMap && echarts.getMap('world')) { + return Promise.resolve(); + } + } catch (_) {} + if (window._worldMapPromise) return window._worldMapPromise; + window._worldMapPromise = new Promise((resolve, reject) => { + const load = (src, onfail) => { + const s = document.createElement('script'); + s.src = src; + s.onload = () => resolve(); + s.onerror = () => onfail ? onfail() : reject(); + document.head.appendChild(s); + }; + // Prefer local vendor file if shipped (static2/vendor/world.js) + load('vendor/world.js', () => { + load('https://fastly.jsdelivr.net/npm/echarts@4.9.0/map/js/world.js'); + }); + }); + return window._worldMapPromise; +} + +// Reuse the same graph implementation; differ in title/tooltip only +class WorldMap3DGraph extends _WorldMap3DGraph {} + +export class ShaperWorldMapUp extends BaseDashlet { + constructor(slot){ super(slot); this.last = null; this._emptyId = this.id + "_empty"; } + canBeSlowedDown(){ return true; } + title(){ return "Shaper World Map (Upload)"; } + tooltip(){ return "

World Map

Endpoint locations sized by traffic and colored by RTT."; } + subscribeTo(){ return ["EndpointLatLon"]; } + buildContainer(){ let b=super.buildContainer(); b.appendChild(this.graphDiv()); return b; } + setup(){ this.graph = new WorldMap3DGraph(this.graphDivId()); if (this.last) this.graph.update(this.last); } + _showEmpty(show, msg = "No recent data"){ + const card = document.getElementById(this.id); + if (!card) return; + let empty = document.getElementById(this._emptyId); + if (!empty) { + empty = document.createElement('div'); + empty.id = this._emptyId; + empty.classList.add('text-center','text-muted','small'); + empty.style.padding = '12px'; + card.appendChild(empty); + } + empty.textContent = msg; + const graph = document.getElementById(this.graphDivId()); + if (show) { + empty.style.display = ''; + if (graph) graph.style.display = 'none'; + } else { + empty.style.display = 'none'; + if (graph) graph.style.display = ''; + } + } + onMessage(msg){ + if (msg.event !== "EndpointLatLon") return; + const rows = msg.data || []; + let maxBytes = 0; + for (let i=0;i maxBytes) maxBytes = b; + } + const minSize = 1, maxSize = 8; + const out = []; + for (let i=0;i 0) { + norm = Math.sqrt(bytes / maxBytes); + if (!isFinite(norm) || norm < 0) norm = 0; + if (norm > 1) norm = 1; + } + const size = Math.round(minSize + (maxSize - minSize) * norm); + const color = colorByRttMs(rtt, 200); + out.push({ value: [lon, lat], symbolSize: size, itemStyle: { color, opacity: 0.6 } }); + } + const hasData = out.length > 0; + this._showEmpty(!hasData); + if (hasData) { + this.last = out; + ensureWorldMap().then(() => { + this.graph.update(out); + }).catch(() => { + this.graph.update(out); + }); + } + } +} diff --git a/src/rust/lqosd/src/node_manager/js_build/src/helpers/color_scales.js b/src/rust/lqosd/src/node_manager/js_build/src/helpers/color_scales.js new file mode 100644 index 00000000..c51f59e0 --- /dev/null +++ b/src/rust/lqosd/src/node_manager/js_build/src/helpers/color_scales.js @@ -0,0 +1,46 @@ +import {isColorBlindMode} from "./colorblind"; +import {lerpGreenToRedViaOrange} from "./scaling"; + +// Viridis color scale interpolation (0..1) +function lerpViridis(t) { + const stops = [ + [68, 1, 84], // #440154 + [59, 82, 139], // #3B528B + [33, 145, 140], // #21918C + [94, 201, 98], // #5EC962 + [253, 231, 37], // #FDE725 + ]; + if (t <= 0) return "#440154"; + if (t >= 1) return "#FDE725"; + let idx = t * (stops.length - 1); + let i = Math.floor(idx); + let frac = idx - i; + let c0 = stops[i], c1 = stops[i + 1]; + let r = Math.round(c0[0] + frac * (c1[0] - c0[0])); + let g = Math.round(c0[1] + frac * (c1[1] - c0[1])); + let b = Math.round(c0[2] + frac * (c1[2] - c0[2])); + return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1); +} + +// Color by retransmit percentage (0..10). +// Normal mode: green->red by lower is better. +// Color blind mode: viridis gradient (0..1) where higher moves toward yellow. +export function colorByRetransmitPct(pct0to10) { + const p = Math.min(10, Math.max(0, pct0to10)); + if (isColorBlindMode()) { + return lerpViridis(p / 10.0); + } else { + return lerpGreenToRedViaOrange(10 - p, 10); + } +} + +// Color by RTT ms with a soft cap (default 200ms). +export function colorByRttMs(rttMs, capMs = 200) { + const r = Math.min(capMs, Math.max(0, Number(rttMs) || 0)); + if (isColorBlindMode()) { + return lerpViridis(r / capMs); + } else { + return lerpGreenToRedViaOrange(capMs - r, capMs); + } +} + diff --git a/src/rust/lqosd/src/node_manager/js_build/src/index.js b/src/rust/lqosd/src/node_manager/js_build/src/index.js index 0c6d2af3..7a570503 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/index.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/index.js @@ -5,30 +5,65 @@ import {globalWarningToasts} from "./toasts/global_warnings"; import {showTimeControls} from "./components/timescale"; import {DashletMenu, widgetFactory} from "./dashlets/dashlet_index"; -const defaultLayout = [ - {name: "Throughput Bits/Second", tag: "throughputBps", size:2}, - {name: "Shaped/Unshaped Pie", tag: "shapedUnshaped", size :2}, - {name: "Throughput Packets/Second", tag: "throughputPps", size:2}, - {name: "Tracked Flows Counter", tag: "trackedFlowsCount", size:2}, - {name: "Last 5 Minutes Throughput", tag: "throughputRing" ,size:2}, - {name: "Round-Trip Time Histogram", tag: "rttHistogram", size:2}, - {name: "Network Tree Sankey", tag: "networkTreeSankey",size:6}, - {name: "Network Tree Summary", tag:"treeSummary", size:6}, - {name: "Top 10 Downloaders", tag: "top10downloaders", size:6}, - {name: "Worst 10 Round-Trip Time", tag: "worst10downloaders", size:6}, - {name: "Worst 10 Retransmits", tag: "worst10retransmits", size:6}, - {name: "Top 10 Flows (total bytes)", tag: "top10flowsBytes", size:6}, - {name: "Top 10 Flows (rate)", tag: "top10flowsRate", size:6}, - {name: "Top 10 Endpoints by Country", tag: "top10endpointsCountry", size:6}, - {name: "Ether Protocols",tag: "etherProtocols", size:6}, - {name: "IP Protocols", tag:"ipProtocols", size:6}, - {name: "CPU Utilization",tag:"cpu",size:3}, - {name: "RAM Utilization", tag:"ram", size :3}, - {name: "Combined Top 10 Box", tag: "combinedTop10", size:6}, - {name: "Total Cake Stats", tag:"totalCakeStats", size:6}, - {name: "Circuits At Capacity", tag: "circuitCapacity", size:6}, - {name: "Tree Nodes At Capacity", tag:"treeCapacity", size:6} -]; +const defaultLayout = { + version: 2, + activeTab: 0, + tabs: [ + { + name: "Overview", + dashlets: [ + { tag: "throughputRing", size: 12 }, + { tag: "shaperTopAsnDown", size: 6 }, + { tag: "shaperTopAsnUp", size: 6 }, + { tag: "shaperChildrenDown", size: 6 }, + { tag: "shaperChildrenUp", size: 6 }, + { tag: "shaperWorldMapDown", size: 6 }, + { tag: "shaperWorldMapUp", size: 6 } + ] + }, + { + name: "System Overview", + dashlets: [ + { tag: "throughputBps", size: 2 }, + { tag: "shapedUnshaped", size: 2 }, + { tag: "throughputPps", size: 2 }, + { tag: "trackedFlowsCount", size: 2 }, + { tag: "rttHistogram", size: 2 }, + { tag: "cpu", size: 3 }, + { tag: "ram", size: 3 } + ] + }, + { + name: "Network", + dashlets: [ + { tag: "networkTreeSankey", size: 6 }, + { tag: "treeSummary", size: 6 }, + { tag: "circuitCapacity", size: 6 }, + { tag: "treeCapacity", size: 6 } + ] + }, + { + name: "Top 10", + dashlets: [ + { tag: "top10downloaders", size: 6 }, + { tag: "worst10downloaders", size: 6 }, + { tag: "worst10retransmits", size: 6 }, + { tag: "top10flowsBytes", size: 6 }, + { tag: "top10flowsRate", size: 6 }, + { tag: "top10endpointsCountry", size: 6 }, + { tag: "combinedTop10", size: 6 } + ] + }, + { + name: "Protocols & Cake", + dashlets: [ + { tag: "etherProtocols", size: 6 }, + { tag: "ipProtocols", size: 6 }, + { tag: "totalCakeStats", size: 6 } + ] + } + ] +}; window.timeGraphs = []; showTimeControls("timescale"); diff --git a/src/rust/lqosd/src/node_manager/js_build/src/lq_js_common/dashboard/dashboard.js b/src/rust/lqosd/src/node_manager/js_build/src/lq_js_common/dashboard/dashboard.js index bcf193e8..9c5be336 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/lq_js_common/dashboard/dashboard.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/lq_js_common/dashboard/dashboard.js @@ -35,8 +35,10 @@ export class Dashboard { // Content this.dashlets = []; + this.tabDashlets = {}; // dashlets organized by tab this.layout = new DashboardLayout(cookieName, defaultLayout); - this.dashletIdentities = this.layout.dashlets; + // During edit mode, this holds the active tab's dashlets being edited + this.dashletIdentities = []; // Data Wrangling this.channels = []; @@ -56,36 +58,152 @@ export class Dashboard { build() { this.#filterWidgetList(); - let childDivs = this.#buildWidgetChildDivs(); - this.childIds = []; - childDivs.forEach((d) => { this.childIds.push(d.id); }); this.#clearRenderedDashboard(); - childDivs.forEach((d) => { this.parentDiv.appendChild(d) }); + this.#buildTabUI(); + this.#buildTabContents(); this.#buildChannelList(this.dashlets); this.#webSocketSubscription(); } + #buildTabUI() { + // Create tab navigation + let tabNav = document.createElement('ul'); + tabNav.classList.add('nav', 'nav-tabs', 'mb-3'); + tabNav.id = this.divName + '_tabs'; + + this.layout.tabs.forEach((tab, index) => { + let li = document.createElement('li'); + li.classList.add('nav-item'); + + let a = document.createElement('a'); + a.classList.add('nav-link'); + if (index === this.layout.activeTab) { + a.classList.add('active'); + } + a.href = '#'; + a.innerText = tab.name; + a.onclick = (e) => { + e.preventDefault(); + this.switchTab(index); + }; + + li.appendChild(a); + tabNav.appendChild(li); + }); + + this.parentDiv.appendChild(tabNav); + } + + #buildTabContents() { + // Create tab content container + let tabContent = document.createElement('div'); + tabContent.classList.add('tab-content'); + tabContent.id = this.divName + '_tab_content'; + + this.childIds = []; + + this.layout.tabs.forEach((tab, tabIndex) => { + let tabPane = document.createElement('div'); + tabPane.classList.add('tab-pane', 'row'); + tabPane.id = this.divName + '_tab_' + tabIndex; + + if (tabIndex === this.layout.activeTab) { + tabPane.classList.add('active'); + tabPane.style.display = 'flex'; + } else { + tabPane.style.display = 'none'; + } + + // Build dashlets for this tab + let tabDashlets = this.tabDashlets[tabIndex] || []; + tabDashlets.forEach(dashlet => { + let div = dashlet.buildContainer(); + this.childIds.push(div.id); + tabPane.appendChild(div); + }); + + tabContent.appendChild(tabPane); + }); + + this.parentDiv.appendChild(tabContent); + } + + switchTab(tabIndex) { + if (tabIndex === this.layout.activeTab) return; + + // Update active tab in layout + this.layout.activeTab = tabIndex; + this.layout.save(this.layout); + + // Update tab navigation + let tabs = document.querySelectorAll('#' + this.divName + '_tabs .nav-link'); + tabs.forEach((tab, index) => { + if (index === tabIndex) { + tab.classList.add('active'); + } else { + tab.classList.remove('active'); + } + }); + + // Update tab content visibility + let tabPanes = document.querySelectorAll('#' + this.divName + '_tab_content .tab-pane'); + tabPanes.forEach((pane, index) => { + if (index === tabIndex) { + pane.classList.add('active'); + pane.style.display = 'flex'; + // Notify dashlets in this tab that they're now visible + let tabDashlets = this.tabDashlets[index] || []; + tabDashlets.forEach(dashlet => { + if (dashlet.onTabActivated) { + dashlet.onTabActivated(); + } + }); + + // Resize all ECharts instances in the newly visible tab + setTimeout(() => { + const charts = pane.querySelectorAll('.dashgraph, .dashgraphZoomed'); + charts.forEach(chartDiv => { + if (typeof echarts !== 'undefined') { + const chart = echarts.getInstanceByDom(chartDiv); + if (chart) { + chart.resize(); + } + } + }); + }, 0); + } else { + pane.classList.remove('active'); + pane.style.display = 'none'; + } + }); + } + #filterWidgetList() { this.dashlets = []; - for (let i=0; i { + this.tabDashlets[tabIndex] = []; + + tab.dashlets.forEach((dashletDef) => { + let widget = this.widgetFactory(dashletDef.tag, globalIndex); + if (widget == null) return; // Skip build + + widget.size = dashletDef.size; + widget.tabIndex = tabIndex; + + this.dashlets.push(widget); + this.tabDashlets[tabIndex].push(widget); + globalIndex++; + }); + }); } - #buildWidgetChildDivs() { - let childDivs = []; - for (let i=0; i 1) { + while (this.parentDiv.children.length > 0) { this.parentDiv.removeChild(this.parentDiv.lastChild); } } @@ -152,18 +270,7 @@ export class Dashboard { editDiv.id = this.divName + "_edit"; editDiv.innerHTML = ""; editDiv.onclick = () => { - // New Editor - let initialElements = []; - console.log("Layout", this.layout); - for (let i=0; i { let category = "Uncategorized"; @@ -176,12 +283,11 @@ export class Dashboard { }); }); - openDashboardEditor(initialElements, availableElements, function(newLayout) { + openDashboardEditor(this.layout, availableElements, (newLayout) => { console.log("New dashboard layout:", newLayout); - let template = JSON.stringify(newLayout); - localStorage.setItem(window.cookieName, template); + this.layout.save(newLayout); window.location.reload(); - }); + }, this.cookieName); }; // Cadence Picker @@ -234,6 +340,8 @@ export class Dashboard { editDiv.style.marginLeft = "0"; let toasts = document.getElementById("toasts"); this.editingDashboard = true; + // Work on a copy of the active tab's dashlets so indices align with visible widgets + this.dashletIdentities = JSON.parse(JSON.stringify(this.#getActiveTabDashlets())); // Add the editing elements let row = document.createElement("div"); @@ -280,7 +388,7 @@ export class Dashboard { let didSomething = false; this.dashletMenu.forEach((d) => { if (d.tag === myTag) { - this.dashletIdentities.push(d); + this.dashletIdentities.push({ tag: d.tag, size: d.size }); didSomething = true; } }); @@ -337,174 +445,148 @@ export class Dashboard { saveGroup.appendChild(saveAppend); c3.appendChild(saveGroup); - //c3.appendChild(lbl); - //c3.appendChild(saveDashName); - //c3.appendChild(saveBtn); - let c4 = document.createElement("div"); c4.classList.add("col-3"); - c4.appendChild(heading5Icon("cloud", "Load Layout")) - let listRemote = document.createElement("div"); - listRemote.classList.add("dropdown"); - let listBtnRemote = document.createElement("button"); - listBtnRemote.type = "button"; - listBtnRemote.classList.add("btn", "btn-secondary", "dropdown-toggle", "btn-sm"); - listBtnRemote.setAttribute("data-bs-toggle", "dropdown"); - listBtnRemote.innerHTML = " Load Layout"; - listRemote.appendChild(listBtnRemote); - let listUlRemote = document.createElement("ul"); - listUlRemote.classList.add("dropdown-menu"); - listUlRemote.id = "remoteDashletList"; - listRemote.appendChild(listUlRemote); - c4.appendChild(listRemote); - if (this.savedDashUrl.length > 0) { - $.get(this.savedDashUrl, (data) => { - let parent = document.getElementById("remoteDashletList"); - data.forEach((d) => { - let li = document.createElement("li"); - let link = document.createElement("a"); - link.innerText = d; - let filename = d; - link.onclick = () => { - console.log("Loading " + d); + c4.appendChild(heading5Icon("save", "Saved Layouts")); + $.get(this.savedDashUrl, (data) => { + let list = document.createElement("ul"); + list.classList.add("list-group", "list-group-numbered"); + data.entries.forEach((d) => { + let i = document.createElement("li"); + i.classList.add("list-group-item","list-group-item-action"); + let ln = document.createElement("a"); + ln.href = "#"; + ln.innerHTML = " " + d.name; + ln.onclick = () => { + let resp = confirm("Load [" + d.name + "] from [" + d.path + "]?"); + if (resp) { $.ajax({ type: "POST", url: "/local-api/dashletGet", - data: JSON.stringify({theme: filename}), - contentType: 'application/json', - success: (data) => { - this.dashletIdentities = data; + data: JSON.stringify({name: d.name}), + contentType : 'application/json', + success: (x) => { + console.log(x); + this.dashletIdentities = x.entries; this.layout.save(this.dashletIdentities); localStorage.setItem("forceEditMode", "true"); window.location.reload(); } }); } - li.appendChild(link); - parent.appendChild(li); - }); + }; + let dl = document.createElement("a"); + dl.classList.add("badge","text-bg-danger"); + dl.style.float = "right"; + dl.href = "#"; + dl.innerHTML = " Delete"; + dl.onclick = () => { + let resp = confirm("Delete [" + d.name + "] from [" + d.path + "]?"); + if (resp) { + $.ajax({ + type: "POST", + url: "/local-api/dashletDelete", + data: JSON.stringify({name: d.name}), + contentType : 'application/json', + success: () => { + localStorage.setItem("forceEditMode", "true"); + window.location.reload(); + } + }); + } + } + i.appendChild(ln); + i.appendChild(dl); + list.appendChild(i); }); - } + c4.appendChild(list); + }); row.appendChild(c1); row.appendChild(c2); - if (this.savedDashUrl.length > 0) { - row.appendChild(c3); - row.appendChild(c4); - } + row.appendChild(c3); + row.appendChild(c4); editDiv.appendChild(row); - - - // Decorate all the dashboard elements with controls after a refresh period - requestAnimationFrame(() => { - setTimeout(() => { this.#updateEditDecorations() }); - }); - toasts.appendChild(editDiv); - } - #replaceDashletList() { - resetWS(); - - // Apply - this.build(); - let self = this; - requestAnimationFrame(() => { - setTimeout(() => { self.#updateEditDecorations() }); - }); + // Insert the inline edit buttons + let editDivParent = document.getElementById(this.childIds[0]); + if (editDivParent != null) { + let div = document.getElementById(this.childIds[0]); + let clientRect = div.getClientRects()[0]; + let clientLeft = (clientRect.left - 10) + "px"; + let clientTop = (clientRect.top - 20) + "px"; + for (let i = 0; i < this.dashlets.length; i++) { + let div = document.getElementById(this.childIds[i]); + if (div !== null) { + let clientRect = div.getClientRects()[0]; + let clientTop = (clientRect.top - 20) + "px"; + let clientLeft = (clientRect.left + 10) + "px"; + let clientMiddleX = (clientRect.left + 80) + "px"; + let clientMiddleY = (clientRect.top + 18) + "px"; + + // Up Button + let myI = i; + editDiv.appendChild(this.#dashEditButton( + clientLeft, + clientTop, + "arrow-up", + "secondary", + () => { if (myI > 0) this.clickUp(myI); } + )); - // Persist - this.layout.save(this.dashletIdentities); - } + // Down Button + let myI2 = i; + editDiv.appendChild(this.#dashEditButton( + (clientRect.left + 20) + "px", + clientTop, + "arrow-down", + "secondary", + () => { if (myI2 < (this.dashlets.length - 1)) this.clickDown(myI2); } + )); - #updateEditDecorations() { - let oldEditDiv = document.getElementById("divEditorElements"); - if (oldEditDiv !== null) editDiv.remove(); + // Trash Button + let myI3 = i; + editDiv.appendChild(this.#dashEditButton( + clientMiddleX, + clientMiddleY, + "trash", + "danger", + () => { + this.clickTrash(myI3); + } + )); - let editDivParent = document.getElementById("dashboardEditingDiv"); - let editDiv = document.createElement("div"); - editDiv.id = "divEditorElements"; - - for (let i=0; i 0) { - let myI = i; + // Expand Button + let myI4 = i; editDiv.appendChild(this.#dashEditButton( clientLeft, - clientMiddleY, - "arrow-circle-left", - "warning", + clientTop, + "plus-circle", + "secondary", () => { - this.clickUp(myI); + this.zoomIn(myI4); } )); - } - // Right Navigation Arrow - if (i < this.childIds.length-1) { - let myI = i; + // Contract Button + let myI5 = i; editDiv.appendChild(this.#dashEditButton( - clientRight, - clientMiddleY, - "arrow-circle-right", - "warning", + (clientRect.left + 40) + "px", + clientTop, + "minus-circle", + "secondary", () => { - this.clickDown(myI); + this.zoomOut(myI5); } )); + } else { + console.log("Warning: NULL div found in dashlet list"); } - - // Trash Button - let myI = i; - editDiv.appendChild(this.#dashEditButton( - clientMiddleX, - clientMiddleY, - "trash", - "danger", - () => { - this.clickTrash(myI); - } - )); - - // Expand Button - let myI2 = i; - editDiv.appendChild(this.#dashEditButton( - clientLeft, - clientTop, - "plus-circle", - "secondary", - () => { - this.zoomIn(myI2); - } - )); - - // Contract Button - let myI3 = i; - editDiv.appendChild(this.#dashEditButton( - (clientRect.left + 40) + "px", - clientTop, - "minus-circle", - "secondary", - () => { - this.zoomOut(myI3); - } - )); - } else { - console.log("Warning: NULL div found in dashlet list"); } - } - editDivParent.appendChild(editDiv); + editDivParent.appendChild(editDiv); + } } #dashEditButton(left, top, iconSuffix, style, closure) { @@ -538,7 +620,6 @@ export class Dashboard { let toReplace = this.dashletIdentities[i-1]; this.dashletIdentities[i-1] = toMove; this.dashletIdentities[i] = toReplace; - this.#replaceDashletList(); } @@ -547,47 +628,55 @@ export class Dashboard { let toReplace = this.dashletIdentities[i+1]; this.dashletIdentities[i+1] = toMove; this.dashletIdentities[i] = toReplace; - this.#replaceDashletList(); } clickTrash(i) { this.dashletIdentities.splice(i, 1); - this.layout.save(this.dashletIdentities); - localStorage.setItem("forceEditMode", "true"); - window.location.reload(); + this.#replaceDashletList(); } zoomIn(i) { - console.log(i); if (this.dashletIdentities[i].size < 12) { this.dashletIdentities[i].size += 1; } - this.layout.save(this.dashletIdentities); - localStorage.setItem("forceEditMode", "true"); - window.location.reload(); + this.#replaceDashletList(); } zoomOut(i) { if (this.dashletIdentities[i].size > 1) { this.dashletIdentities[i].size -= 1; } - this.layout.save(this.dashletIdentities); - localStorage.setItem("forceEditMode", "true"); - window.location.reload(); + this.#replaceDashletList(); } removeAll() { this.dashletIdentities = []; - this.layout.save(this.dashletIdentities); - localStorage.setItem("forceEditMode", "true"); - window.location.reload(); + this.#replaceDashletList(); } addAll() { - this.dashletIdentities = DashletMenu; - this.layout.save(this.dashletIdentities); + // Add all known widgets into current tab as tag/size pairs + this.dashletIdentities = this.dashletMenu.map(d => ({ tag: d.tag, size: d.size })); + this.#replaceDashletList(); + } + + #getActiveTabDashlets() { + const t = this.layout.activeTab || 0; + if (this.layout.tabs && this.layout.tabs[t] && Array.isArray(this.layout.tabs[t].dashlets)) { + return this.layout.tabs[t].dashlets; + } + return []; + } + + #replaceDashletList() { + // Persist the current tab’s dashlets and reload to apply + const t = this.layout.activeTab || 0; + if (this.layout.tabs && this.layout.tabs[t]) { + this.layout.tabs[t].dashlets = this.dashletIdentities; + } + this.layout.save(this.layout); localStorage.setItem("forceEditMode", "true"); window.location.reload(); } -} \ No newline at end of file +} diff --git a/src/rust/lqosd/src/node_manager/js_build/src/lq_js_common/dashboard/dashboard_editor.js b/src/rust/lqosd/src/node_manager/js_build/src/lq_js_common/dashboard/dashboard_editor.js index 7f3c78e9..7f0ef835 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/lq_js_common/dashboard/dashboard_editor.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/lq_js_common/dashboard/dashboard_editor.js @@ -1,11 +1,22 @@ /** - * Opens a full screen modal that lets the user edit dashboard items. - * @param {Array} initialElements - Array of objects representing current dashboard items. Each object should have a "name" and a "size" (1–12). + * Opens a full screen modal that lets the user edit dashboard items with tab support. + * @param {Object} layout - The current dashboard layout object with tabs * @param {Array} availableElements - Array of objects representing available elements to add (each with a "name" and default "size"). - * @param {Function} callback - A function that will be called with the new array of dashboard items when the user clicks "Done". + * @param {Function} callback - A function that will be called with the new layout when the user clicks "Done". + * @param {String} cookieName - The localStorage key for saving the dashboard layout. */ -export function openDashboardEditor(initialElements, availableElements, callback) { - // Build modal HTML with a fullscreen modal, a grid area and an available panel. +export function openDashboardEditor(layout, availableElements, callback, cookieName) { + // Keep track of current tab and layout state + let currentLayout = JSON.parse(JSON.stringify(layout)); // Deep copy + let activeTabIndex = currentLayout.activeTab || 0; + + // Create a lookup map for widget names by tag + const widgetNameLookup = {}; + availableElements.forEach(element => { + widgetNameLookup[element.tag] = element.name; + }); + + // Build modal HTML with tab support var modalHtml = `

" + let html = "" return html; } @@ -1026,56 +1026,56 @@ function validateSd() { // Download Min controlId = "#" + rowPrefix(i, "download_min_mbps"); let download_min = $(controlId).val(); - download_min = parseInt(download_min); + download_min = parseFloat(download_min); if (isNaN(download_min)) { valid = false; errors.push("Download min is not a valid number"); $(controlId).addClass("invalid"); - } else if (download_min < 1) { + } else if (download_min < 0.1) { valid = false; - errors.push("Download min must be 1 or more"); + errors.push("Download min must be 0.1 or more"); $(controlId).addClass("invalid"); } // Upload Min controlId = "#" + rowPrefix(i, "upload_min_mbps"); let upload_min = $(controlId).val(); - upload_min = parseInt(upload_min); + upload_min = parseFloat(upload_min); if (isNaN(upload_min)) { valid = false; errors.push("Upload min is not a valid number"); $(controlId).addClass("invalid"); - } else if (upload_min < 1) { + } else if (upload_min < 0.1) { valid = false; - errors.push("Upload min must be 1 or more"); + errors.push("Upload min must be 0.1 or more"); $(controlId).addClass("invalid"); } // Download Max controlId = "#" + rowPrefix(i, "download_max_mbps"); let download_max = $(controlId).val(); - upload_min = parseInt(download_max); + download_max = parseFloat(download_max); if (isNaN(download_max)) { valid = false; errors.push("Download Max is not a valid number"); $(controlId).addClass("invalid"); - } else if (download_max < 1) { + } else if (download_max < 0.2) { valid = false; - errors.push("Download Max must be 1 or more"); + errors.push("Download Max must be 0.2 or more"); $(controlId).addClass("invalid"); } // Upload Max controlId = "#" + rowPrefix(i, "upload_max_mbps"); let upload_max = $(controlId).val(); - upload_min = parseInt(upload_max); + upload_max = parseFloat(upload_max); if (isNaN(upload_max)) { valid = false; errors.push("Upload Max is not a valid number"); $(controlId).addClass("invalid"); - } else if (upload_max < 1) { + } else if (upload_max < 0.2) { valid = false; - errors.push("Upload Max must be 1 or more"); + errors.push("Upload Max must be 0.2 or more"); $(controlId).addClass("invalid"); } } @@ -1123,10 +1123,10 @@ function saveNetAndDevices() { row.mac = $("#" + rowPrefix(i, "mac")).val(); row.ipv4 = ipAddressesToTuple($("#" + rowPrefix(i, "ipv4")).val()); row.ipv6 = ipAddressesToTuple($("#" + rowPrefix(i, "ipv6")).val()); - row.download_min_mbps = parseInt($("#" + rowPrefix(i, "download_min_mbps")).val()); - row.upload_min_mbps = parseInt($("#" + rowPrefix(i, "upload_min_mbps")).val()); - row.download_max_mbps = parseInt($("#" + rowPrefix(i, "download_max_mbps")).val()); - row.upload_max_mbps = parseInt($("#" + rowPrefix(i, "upload_max_mbps")).val()); + row.download_min_mbps = parseFloat($("#" + rowPrefix(i, "download_min_mbps")).val()); + row.upload_min_mbps = parseFloat($("#" + rowPrefix(i, "upload_min_mbps")).val()); + 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(); } diff --git a/src/rust/lqosd/src/shaped_devices_tracker/mod.rs b/src/rust/lqosd/src/shaped_devices_tracker/mod.rs index 555033c8..d941c8ae 100644 --- a/src/rust/lqosd/src/shaped_devices_tracker/mod.rs +++ b/src/rust/lqosd/src/shaped_devices_tracker/mod.rs @@ -217,7 +217,8 @@ pub fn get_all_circuits() -> BusResponse { let mut device_id = None; let mut device_name = None; let mut parent_node = None; - let mut plan = DownUpOrder { down: 0.0, up: 0.0 }; + // Plan is expressed in Mbps as f32 + let mut plan: DownUpOrder = DownUpOrder { down: 0.0, up: 0.0 }; let lookup = match ip { IpAddr::V4(ip) => ip.to_ipv6_mapped(), IpAddr::V6(ip) => ip, @@ -228,8 +229,8 @@ pub fn get_all_circuits() -> BusResponse { device_id = Some(devices.devices[*c.1].device_id.clone()); device_name = Some(devices.devices[*c.1].device_name.clone()); parent_node = Some(devices.devices[*c.1].parent_node.clone()); - plan.down = devices.devices[*c.1].download_max_mbps; - plan.up = devices.devices[*c.1].upload_max_mbps; + plan.down = devices.devices[*c.1].download_max_mbps.round(); + plan.up = devices.devices[*c.1].upload_max_mbps.round(); } Circuit { -- knotmirror 0.0.1 From ddda727e04b0fe69aad6f65294068fc6f1704e17 Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Fri, 7 Nov 2025 12:39:44 -0600 Subject: [PATCH 49/58] Fix: All websocket connections now check for an http vs https prefix. --- .../node_manager/js_build/src/lq_js_common/dashboard/ws.js | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/rust/lqosd/src/node_manager/js_build/src/lq_js_common/dashboard/ws.js b/src/rust/lqosd/src/node_manager/js_build/src/lq_js_common/dashboard/ws.js index 240e2516..02ef9010 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/lq_js_common/dashboard/ws.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/lq_js_common/dashboard/ws.js @@ -1,4 +1,5 @@ // Setup any WS feeds for this page +import { ws_proto } from '../../pubsub/ws.js'; let ws = null; export function subscribeWS(channels, handler) { @@ -9,7 +10,7 @@ export function subscribeWS(channels, handler) { ws.close(); } - ws = new WebSocket('ws://' + window.location.host + '/websocket/ws'); + ws = new WebSocket(ws_proto() + window.location.host + '/websocket/ws'); ws.onopen = () => { for (let i=0; i Date: Fri, 7 Nov 2025 13:05:49 -0600 Subject: [PATCH 50/58] Feat: Now show 2 layers (clamped) on the live sankey displays. --- .../src/dashlets/children_sankey_down.js | 96 ++++++++-- .../src/dashlets/children_sankey_up.js | 81 +++++++-- .../js_build/src/dashlets/top_tree_sankey.js | 168 +++++++++++++----- .../src/node_manager/ws/published_channels.rs | 1 + src/rust/lqosd/src/node_manager/ws/ticker.rs | 2 + 5 files changed, 280 insertions(+), 68 deletions(-) diff --git a/src/rust/lqosd/src/node_manager/js_build/src/dashlets/children_sankey_down.js b/src/rust/lqosd/src/node_manager/js_build/src/dashlets/children_sankey_down.js index 5a6dcc4e..74d6f3c6 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/dashlets/children_sankey_down.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/dashlets/children_sankey_down.js @@ -15,19 +15,26 @@ class ChildrenSankeyGraph extends DashboardGraph { this.chart.setOption(this.option); } update(items) { - const nodes = [{ name: 'Shaper' }]; - const links = []; - items.forEach(it => { - const color = colorByRetransmitPct(it.rxmit ?? 0); - nodes.push({ name: it.name, itemStyle: { color } }); - if (this.direction === 'down') { - links.push({ source: it.name, target: 'Shaper', value: it.value }); - } else { - links.push({ source: 'Shaper', target: it.name, value: it.value }); - } - }); - this.option.series[0].data = nodes; - this.option.series[0].links = links; + // Backward compatibility: if items is an array of {name,value,rxmit}, draw 1-level + if (Array.isArray(items)) { + const nodes = [{ name: 'Shaper' }]; + const links = []; + items.forEach(it => { + const color = colorByRetransmitPct(it.rxmit ?? 0); + nodes.push({ name: it.name, itemStyle: { color } }); + if (this.direction === 'down') { + links.push({ source: it.name, target: 'Shaper', value: it.value }); + } else { + links.push({ source: 'Shaper', target: it.name, value: it.value }); + } + }); + this.option.series[0].data = nodes; + this.option.series[0].links = links; + } else if (items && items.nodes && items.links) { + // New 2-level path: items = { nodes, links } + this.option.series[0].data = items.nodes; + this.option.series[0].links = items.links; + } this.chart.hideLoading(); this.chart.setOption(this.option); } @@ -39,11 +46,13 @@ export class ShaperChildrenDown extends BaseDashlet { this.last=null; this._emptyId = this.id + "_empty"; this._smooth = new Map(); this._ALPHA = 0.3; this._ALPHA_RX = 0.2; this._DECAY = 0.15; this._LINGER = 3; + this._lastSummary = null; // raw TreeSummary + this._lastL2 = null; // TreeSummaryL2 } canBeSlowedDown(){ return true; } title(){ return "Shaper Children (Download)"; } tooltip(){ return "
Child Throughput

Top child nodes by download throughput."; } - subscribeTo(){ return ["TreeSummary"]; } + subscribeTo(){ return ["TreeSummary", "TreeSummaryL2"]; } buildContainer(){ let b = super.buildContainer(); b.appendChild(this.graphDiv()); return b; } setup(){ this.graph = new ChildrenSankeyGraph(this.graphDivId(), 'down'); if (this.last) this.graph.update(this.last); } _showEmpty(show, msg = "No recent data"){ @@ -87,9 +96,66 @@ export class ShaperChildrenDown extends BaseDashlet { out.sort((a,b)=> b.value - a.value); return out.slice(0,9); } + _renderTwoLevel(){ + if (!this._lastSummary || !this._lastL2) return false; + // Build parent map + const parentMap = new Map(); + (this._lastSummary || []).slice(1).forEach(r => parentMap.set(r[0], r[1])); + + const nodes = [{ name: 'Shaper' }]; + const links = []; + let hasData = false; + + for (const [parentId, children] of this._lastL2) { + const p = parentMap.get(parentId); + if (!p) continue; + const pName = p.name || String(parentId); + // Parent color by rxmit (download) + let pRx = 0; + if ((p.current_tcp_packets?.[0]||0) > 0) { + pRx = ((p.current_retransmits?.[0]||0) / Math.max(1, p.current_tcp_packets?.[0]||0)) * 100.0; + } + nodes.push({ name: pName, itemStyle: { color: colorByRetransmitPct(pRx) } }); + + let parentSum = 0; + for (const [, c] of children) { + const v = Number((c.current_throughput?.[0]||0)); + if (v <= 0) continue; + parentSum += v; + hasData = hasData || v > 0.5; + let cRx = 0; + if ((c.current_tcp_packets?.[0]||0) > 0) { + cRx = ((c.current_retransmits?.[0]||0) / Math.max(1, c.current_tcp_packets?.[0]||0)) * 100.0; + } + nodes.push({ name: c.name, itemStyle: { color: colorByRetransmitPct(cRx) } }); + links.push({ source: c.name, target: pName, value: v }); + } + if (parentSum > 0) { + links.push({ source: pName, target: 'Shaper', value: parentSum }); + } + } + + this._showEmpty(!hasData); + if (hasData) { + this.graph.update({ nodes, links }); + return true; + } + return false; + } + onMessage(msg){ + if (msg.event === "TreeSummary") { + this._lastSummary = msg.data; + } else if (msg.event === "TreeSummaryL2") { + this._lastL2 = msg.data; + } else { + return; + } + + // Prefer 2-level; if unavailable, fallback to 1-level smoothing + if (this._renderTwoLevel()) return; + if (msg.event !== "TreeSummary") return; - // msg.data: [ [id, metrics], [id, metrics], ... ] - first is root let rows = (msg.data || []).slice(1).map(r => { const m = r[1] || {}; const name = m.name || String(r[0]); diff --git a/src/rust/lqosd/src/node_manager/js_build/src/dashlets/children_sankey_up.js b/src/rust/lqosd/src/node_manager/js_build/src/dashlets/children_sankey_up.js index 00015933..16f9ea11 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/dashlets/children_sankey_up.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/dashlets/children_sankey_up.js @@ -12,15 +12,20 @@ class ChildrenSankeyGraphUp extends DashboardGraph { this.chart.setOption(this.option); } update(items){ - const nodes = [{ name: 'Shaper' }]; - const links = []; - items.forEach(it => { - const color = colorByRetransmitPct(it.rxmit ?? 0); - nodes.push({ name: it.name, itemStyle: { color } }); - links.push({ source: 'Shaper', target: it.name, value: it.value }); - }); - this.option.series[0].data = nodes; - this.option.series[0].links = links; + if (Array.isArray(items)) { + const nodes = [{ name: 'Shaper' }]; + const links = []; + items.forEach(it => { + const color = colorByRetransmitPct(it.rxmit ?? 0); + nodes.push({ name: it.name, itemStyle: { color } }); + links.push({ source: 'Shaper', target: it.name, value: it.value }); + }); + this.option.series[0].data = nodes; + this.option.series[0].links = links; + } else if (items && items.nodes && items.links) { + this.option.series[0].data = items.nodes; + this.option.series[0].links = items.links; + } this.chart.hideLoading(); this.chart.setOption(this.option); } @@ -32,11 +37,13 @@ export class ShaperChildrenUp extends BaseDashlet { this.last=null; this._emptyId = this.id + "_empty"; this._smooth = new Map(); this._ALPHA = 0.3; this._ALPHA_RX = 0.2; this._DECAY = 0.15; this._LINGER = 3; + this._lastSummary = null; + this._lastL2 = null; } canBeSlowedDown(){ return true; } title(){ return "Shaper Children (Upload)"; } tooltip(){ return "

Child Throughput

Top child nodes by upload throughput."; } - subscribeTo(){ return ["TreeSummary"]; } + subscribeTo(){ return ["TreeSummary", "TreeSummaryL2"]; } buildContainer(){ let b=super.buildContainer(); b.appendChild(this.graphDiv()); return b; } setup(){ this.graph = new ChildrenSankeyGraphUp(this.graphDivId()); if (this.last) this.graph.update(this.last); } _showEmpty(show, msg = "No recent data"){ @@ -80,7 +87,61 @@ export class ShaperChildrenUp extends BaseDashlet { out.sort((a,b)=> b.value - a.value); return out.slice(0,9); } + _renderTwoLevel(){ + if (!this._lastSummary || !this._lastL2) return false; + const parentMap = new Map(); + (this._lastSummary || []).slice(1).forEach(r => parentMap.set(r[0], r[1])); + + const nodes = [{ name: 'Shaper' }]; + const links = []; + let hasData = false; + + for (const [parentId, children] of this._lastL2) { + const p = parentMap.get(parentId); + if (!p) continue; + const pName = p.name || String(parentId); + // Parent color by rxmit (upload) + let pRx = 0; + if ((p.current_tcp_packets?.[1]||0) > 0) { + pRx = ((p.current_retransmits?.[1]||0) / Math.max(1, p.current_tcp_packets?.[1]||0)) * 100.0; + } + nodes.push({ name: pName, itemStyle: { color: colorByRetransmitPct(pRx) } }); + + let parentSum = 0; + for (const [, c] of children) { + const v = Number((c.current_throughput?.[1]||0)); + if (v <= 0) continue; + parentSum += v; + hasData = hasData || v > 0.5; + let cRx = 0; + if ((c.current_tcp_packets?.[1]||0) > 0) { + cRx = ((c.current_retransmits?.[1]||0) / Math.max(1, c.current_tcp_packets?.[1]||0)) * 100.0; + } + nodes.push({ name: c.name, itemStyle: { color: colorByRetransmitPct(cRx) } }); + links.push({ source: pName, target: c.name, value: v }); + } + if (parentSum > 0) { + links.push({ source: 'Shaper', target: pName, value: parentSum }); + } + } + + this._showEmpty(!hasData); + if (hasData) { + this.graph.update({ nodes, links }); + return true; + } + return false; + } + onMessage(msg){ + if (msg.event === "TreeSummary") { + this._lastSummary = msg.data; + } else if (msg.event === "TreeSummaryL2") { + this._lastL2 = msg.data; + } else { return; } + + if (this._renderTwoLevel()) return; + if (msg.event !== "TreeSummary") return; let rows = (msg.data || []).slice(1).map(r => { const m = r[1] || {}; diff --git a/src/rust/lqosd/src/node_manager/js_build/src/dashlets/top_tree_sankey.js b/src/rust/lqosd/src/node_manager/js_build/src/dashlets/top_tree_sankey.js index 2191cb76..29ecc036 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/dashlets/top_tree_sankey.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/dashlets/top_tree_sankey.js @@ -69,6 +69,8 @@ class TopTreeSankeyGraph extends DashboardGraph { export class TopTreeSankey extends BaseDashlet { constructor(slot) { super(slot); + this._lastTreeSummary = null; + this._lastL2 = null; } canBeSlowedDown() { @@ -84,7 +86,7 @@ export class TopTreeSankey extends BaseDashlet { } subscribeTo() { - return [ "TreeSummary" ]; + return [ "TreeSummary", "TreeSummaryL2" ]; } buildContainer() { @@ -100,63 +102,143 @@ export class TopTreeSankey extends BaseDashlet { onMessage(msg) { if (msg.event === "TreeSummary") { - //console.log(msg.data); + this._lastTreeSummary = msg.data; + } else if (msg.event === "TreeSummaryL2") { + this._lastL2 = msg.data; + } else { + return; + } + + if (!this._lastTreeSummary) return; + + let redact = isRedacted(); - let redact = isRedacted(); + // Build 2-level sankey if L2 is present, else fallback to 1-level + const nodes = []; + const links = []; + nodes.push({ name: "Root", label: "Root" }); - let nodes = []; - let links = []; + const firstLevel = (this._lastTreeSummary || []).slice(1); - nodes.push({ - name: "Root", - label: "Root", - }); + // Map of parent id -> parent transport for quick lookup + const parentMap = new Map(); + firstLevel.forEach((r) => parentMap.set(r[0], r[1])); - msg.data.slice(1).forEach((r) => { - let label = { - fontSize: 9, - color: "#999" - }; + // Helper to build node style from RTT + const nodeStyleFromRtt = (name, rttsArr) => { + let rtt = 0; + if (rttsArr && rttsArr.length > 0) { + rtt = rttsArr[0]; + } else if (lastRtt[name] !== undefined) { + rtt = lastRtt[name]; + } + lastRtt[name] = rtt; + const rttPercent = Math.min(100, (rtt / 200) * 100); + const color = isColorBlindMode() + ? lerpViridis(rttPercent / 100) + : lerpGreenToRedViaOrange(200 - rtt, 200); + return { itemStyle: { color } }; + }; + + if (this._lastL2 && Array.isArray(this._lastL2) && this._lastL2.length > 0) { + // L2 data shape: [ [parent_id, [ [child_id, child_transport], ... ] ], ... ] + for (const [parentId, children] of this._lastL2) { + const p = parentMap.get(parentId); + if (!p) continue; + + // Parent node styling + const pName = p.name; + const label = { fontSize: 9, color: "#999" }; if (redact) label.fontFamily = "Illegible"; - let name = r[1].name; - let bytes = r[1].current_throughput[0]; - let bytesAsMegabits = bytes / 1000000; - let maxBytes = r[1].max_throughput[0] / 8; - let percent = Math.min(100, (bytesAsMegabits / maxBytes) * 100); - let capacityColor = isColorBlindMode() + const pStyle = nodeStyleFromRtt(pName, p.rtts); + nodes.push({ name: pName, label, ...pStyle }); + + // Compute Root->Parent value as sum of included child totals (down + up) + let parentSum = 0; + // Compute link color from parent's capacity percent (as before) + const bytesAsMegabits = p.current_throughput[0] / 1000000; + const maxBytes = p.max_throughput[0] / 8; + const percent = Math.min(100, maxBytes > 0 ? (bytesAsMegabits / maxBytes) * 100 : 0); + const capacityColor = isColorBlindMode() ? lerpViridis(percent / 100) : lerpGreenToRedViaOrange(100 - percent, 100); - if (r[1].rtts.length > 0) { - lastRtt[name] = r[1].rtts[0]; - } else { - lastRtt[name] = 0; - } - let rttPercent = Math.min(100, (lastRtt[name] / 200) * 100); - let color = isColorBlindMode() - ? lerpViridis(rttPercent / 100) - : lerpGreenToRedViaOrange(200 - lastRtt[name], 200); - - if (bytesAsMegabits > 0) { - nodes.push({ - name: r[1].name, - label: label, - itemStyle: { - color: color - } + for (const [, child] of children) { + const cName = child.name; + const cTotal = (child.current_throughput?.[0] || 0) + (child.current_throughput?.[1] || 0); + if (cTotal <= 0) continue; + parentSum += cTotal; + + // Child node and link parent->child + const cLabel = { fontSize: 9, color: "#999" }; + if (redact) cLabel.fontFamily = "Illegible"; + const cStyle = nodeStyleFromRtt(cName, child.rtts); + nodes.push({ name: cName, label: cLabel, ...cStyle }); + + // Link color for child can use child's capacity percent + const cBytesAsMegabits = (child.current_throughput?.[0] || 0) / 1000000; + const cMaxBytes = (child.max_throughput?.[0] || 0) / 8; + const cPercent = Math.min(100, cMaxBytes > 0 ? (cBytesAsMegabits / cMaxBytes) * 100 : 0); + const cCapacityColor = isColorBlindMode() + ? lerpViridis(cPercent / 100) + : lerpGreenToRedViaOrange(100 - cPercent, 100); + + links.push({ + source: pName, + target: cName, + value: cTotal, + lineStyle: { color: cCapacityColor }, }); + } + + if (parentSum > 0) { links.push({ source: "Root", - target: r[1].name, - value: r[1].current_throughput[0] + r[1].current_throughput[1], - lineStyle: { - color: capacityColor, - } + target: pName, + value: parentSum, + lineStyle: { color: capacityColor }, }); } - }); + } this.graph.update(nodes, links); + return; } + + // Fallback to 1-level sankey using current logic + firstLevel.forEach((r) => { + let label = { fontSize: 9, color: "#999" }; + if (redact) label.fontFamily = "Illegible"; + + let name = r[1].name; + let bytes = r[1].current_throughput[0]; + let bytesAsMegabits = bytes / 1000000; + let maxBytes = r[1].max_throughput[0] / 8; + let percent = Math.min(100, maxBytes > 0 ? (bytesAsMegabits / maxBytes) * 100 : 0); + let capacityColor = isColorBlindMode() + ? lerpViridis(percent / 100) + : lerpGreenToRedViaOrange(100 - percent, 100); + + if (r[1].rtts.length > 0) { + lastRtt[name] = r[1].rtts[0]; + } else { + lastRtt[name] = 0; + } + let rttPercent = Math.min(100, (lastRtt[name] / 200) * 100); + let color = isColorBlindMode() + ? lerpViridis(rttPercent / 100) + : lerpGreenToRedViaOrange(200 - lastRtt[name], 200); + + if (bytesAsMegabits > 0) { + nodes.push({ name: r[1].name, label, itemStyle: { color } }); + links.push({ + source: "Root", + target: r[1].name, + value: r[1].current_throughput[0] + r[1].current_throughput[1], + lineStyle: { color: capacityColor }, + }); + } + }); + this.graph.update(nodes, links); } } diff --git a/src/rust/lqosd/src/node_manager/ws/published_channels.rs b/src/rust/lqosd/src/node_manager/ws/published_channels.rs index ff94c917..47c3a591 100644 --- a/src/rust/lqosd/src/node_manager/ws/published_channels.rs +++ b/src/rust/lqosd/src/node_manager/ws/published_channels.rs @@ -21,6 +21,7 @@ pub enum PublishedChannels { Cpu, Ram, TreeSummary, + TreeSummaryL2, QueueStatsTotal, NetworkTree, NetworkTreeClients, diff --git a/src/rust/lqosd/src/node_manager/ws/ticker.rs b/src/rust/lqosd/src/node_manager/ws/ticker.rs index ba6e14c7..879f7874 100644 --- a/src/rust/lqosd/src/node_manager/ws/ticker.rs +++ b/src/rust/lqosd/src/node_manager/ws/ticker.rs @@ -24,6 +24,7 @@ mod top_flows; mod asn_top; mod tree_capacity; mod tree_summary; +mod tree_summary_l2; use crate::system_stats::SystemStats; pub use network_tree::all_circuits; @@ -65,6 +66,7 @@ async fn one_second_cadence( flow_endpoints::flow_duration(channels.clone(), bus_tx.clone()), endpoint_latlon::endpoint_latlon(channels.clone(), bus_tx.clone()), tree_summary::tree_summary(channels.clone(), bus_tx.clone()), + tree_summary_l2::tree_summary_l2(channels.clone()), network_tree::all_subscribers(channels.clone(), bus_tx.clone()), queue_stats_total::queue_stats_totals(channels.clone()), network_tree::network_tree(channels.clone(), bus_tx.clone()), -- knotmirror 0.0.1 From 1012aa017c9a992eef1cb84e8f232d121906429e Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Fri, 7 Nov 2025 13:07:30 -0600 Subject: [PATCH 51/58] Feat: Now show 2 layers (clamped) on the live sankey displays. --- .../node_manager/ws/ticker/tree_summary_l2.rs | 70 +++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 src/rust/lqosd/src/node_manager/ws/ticker/tree_summary_l2.rs diff --git a/src/rust/lqosd/src/node_manager/ws/ticker/tree_summary_l2.rs b/src/rust/lqosd/src/node_manager/ws/ticker/tree_summary_l2.rs new file mode 100644 index 00000000..000f6d1b --- /dev/null +++ b/src/rust/lqosd/src/node_manager/ws/ticker/tree_summary_l2.rs @@ -0,0 +1,70 @@ +use crate::node_manager::ws::publish_subscribe::PubSub; +use crate::node_manager::ws::published_channels::PublishedChannels; +use crate::shaped_devices_tracker::NETWORK_JSON; +use lqos_config::NetworkJsonTransport; +use serde_json::json; +use std::collections::BTreeMap; +use std::sync::Arc; + +/// Publishes a curated two-level summary of the network tree: +/// root -> first-level parents -> top-N second-level children across all parents. +/// N is currently fixed at 10. Only includes second-level items, grouped by parent id. +/// Data shape: +/// { +/// "event": "TreeSummaryL2", +/// "data": [ [ parent_id, [ [child_id, NetworkJsonTransport], ... ] ], ... ] +/// } +pub async fn tree_summary_l2(channels: Arc) { + if !channels + .is_channel_alive(PublishedChannels::TreeSummaryL2) + .await + { + return; + } + + // Build top-N second-level children across all first-level parents + let grouped: Vec<(usize, Vec<(usize, NetworkJsonTransport)>)> = { + let net_json = NETWORK_JSON.read(); + let nodes = net_json.get_nodes_when_ready(); + // Collect candidates as (parent_idx, child_idx, transport, total_bytes_per_sec) + let mut candidates: Vec<(usize, usize, NetworkJsonTransport, u64)> = Vec::new(); + + // Identify first-level parents (immediate_parent == Some(0)) + for (p_idx, p_node) in nodes.iter().enumerate() { + if p_node.immediate_parent == Some(0) { + // For each child-of-child under this parent + for (c_idx, c_node) in nodes.iter().enumerate() { + if c_node.immediate_parent == Some(p_idx) { + let t = c_node.clone_to_transit(); + let total = t.current_throughput.0 + t.current_throughput.1; + candidates.push((p_idx, c_idx, t, total)); + } + } + } + } + + // Sort by total throughput descending and cap to N + candidates.sort_by(|a, b| b.3.cmp(&a.3)); + let n: usize = 10; + if candidates.len() > n { + candidates.truncate(n); + } + + // Group by parent id + let mut map: BTreeMap> = BTreeMap::new(); + for (p_idx, c_idx, t, _total) in candidates.into_iter() { + map.entry(p_idx).or_default().push((c_idx, t)); + } + map.into_iter().collect() + }; + + let message = json!({ + "event": PublishedChannels::TreeSummaryL2.to_string(), + "data": grouped, + }) + .to_string(); + channels + .send(PublishedChannels::TreeSummaryL2, message) + .await; +} + -- knotmirror 0.0.1 From ce5d8937fc785c865f1ec5de5dbc7d3b62f82c59 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Robert=20Chac=C3=B3n?= Date: Fri, 7 Nov 2025 12:46:08 -0700 Subject: [PATCH 52/58] Update configuration.md --- docs/v2.0/configuration.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/v2.0/configuration.md b/docs/v2.0/configuration.md index 953ba541..213e5626 100644 --- a/docs/v2.0/configuration.md +++ b/docs/v2.0/configuration.md @@ -123,6 +123,10 @@ For networks with no Parent Nodes (no strictly defined Access Points or Sites) e echo "{}" > network.json ``` +#### CPU Considerations + +cpu + ##### CSV to JSON conversion helper You can use -- knotmirror 0.0.1 From 8bf287f33e2747c30e432cc9839a56daffe73cd0 Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Fri, 7 Nov 2025 14:13:53 -0600 Subject: [PATCH 53/58] Feat: Adds an "urgent issues" channel allowing Python (and other external systems) to provide emergency alerts to the node manager display. Uses that to alert of the "tc overflow". FIXES #801 --- src/LibreQoS.py | 23 +++- src/rust/lqos_bus/src/bus/mod.rs | 4 +- src/rust/lqos_bus/src/bus/request.rs | 44 +++++++ src/rust/lqos_bus/src/bus/response.rs | 23 ++++ src/rust/lqos_bus/src/lib.rs | 4 +- src/rust/lqos_python/src/lib.rs | 49 ++++++- src/rust/lqosd/src/main.rs | 13 ++ src/rust/lqosd/src/node_manager/local_api.rs | 5 + .../src/node_manager/local_api/urgent.rs | 123 ++++++++++++++++++ .../src/node_manager/static2/template.html | 119 +++++++++++++++++ src/rust/lqosd/src/node_manager/template.rs | 11 ++ src/rust/lqosd/src/urgent.rs | 100 ++++++++++++++ 12 files changed, 511 insertions(+), 7 deletions(-) create mode 100644 src/rust/lqosd/src/node_manager/local_api/urgent.rs create mode 100644 src/rust/lqosd/src/urgent.rs diff --git a/src/LibreQoS.py b/src/LibreQoS.py index b68acdf7..37a6ce5b 100755 --- a/src/LibreQoS.py +++ b/src/LibreQoS.py @@ -30,6 +30,13 @@ from liblqos_python import is_lqosd_alive, clear_ip_mappings, delete_ip_mapping, fast_queues_fq_codel, \ Bakery +# Optional: urgent issue submission (available in newer liblqos_python) +try: + from liblqos_python import submit_urgent_issue # type: ignore +except Exception: + def submit_urgent_issue(*_args, **_kwargs): + return False + R2Q = 10 #MAX_R2Q = 200_000 MAX_R2Q = 60_000 # See https://lartc.vger.kernel.narkive.com/NKaH1ZNG/htb-quantum-of-class-100001-is-small-consider-r2q-change @@ -1022,7 +1029,13 @@ def refreshShapers(): 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.") + msg = f"Minor class ID overflow on CPU {queue}: {minorByCPU[queue]} exceeds TC's u16 limit (65535). Consider increasing queue count or restructuring network hierarchy." + logging.error(msg) + try: + ctx = json.dumps({"cpu": queue, "minor": minorByCPU[queue]}) + submit_urgent_issue("LibreQoS", "Error", "TC_U16_OVERFLOW", msg, ctx, f"TC_U16_OVERFLOW_CPU_{queue}") + except Exception: + pass 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: @@ -1123,7 +1136,13 @@ def refreshShapers(): 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.") + msg = f"Minor class ID overflow on CPU {queue}: {minorByCPU[queue]} exceeds TC's u16 limit (65535). Consider increasing queue count or restructuring network hierarchy." + logging.error(msg) + try: + ctx = json.dumps({"cpu": queue, "minor": minorByCPU[queue]}) + submit_urgent_issue("LibreQoS", "Error", "TC_U16_OVERFLOW", msg, ctx, f"TC_U16_OVERFLOW_CPU_{queue}") + except Exception: + pass 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 diff --git a/src/rust/lqos_bus/src/bus/mod.rs b/src/rust/lqos_bus/src/bus/mod.rs index ee1e08db..8aed0a53 100644 --- a/src/rust/lqos_bus/src/bus/mod.rs +++ b/src/rust/lqos_bus/src/bus/mod.rs @@ -11,8 +11,8 @@ mod unix_socket_server; pub use client::{LibreqosBusClient, bus_request}; pub use queue_data::*; pub use reply::BusReply; -pub use request::{BlackboardSystem, BusRequest, TopFlowType}; -pub use response::BusResponse; +pub use request::{BlackboardSystem, BusRequest, TopFlowType, UrgentSeverity, UrgentSource}; +pub use response::{BakeryStatsSnapshot, BusResponse, UrgentIssue}; pub use session::BusSession; use thiserror::Error; use tracing::error; diff --git a/src/rust/lqos_bus/src/bus/request.rs b/src/rust/lqos_bus/src/bus/request.rs index c4d96641..128b19c9 100644 --- a/src/rust/lqos_bus/src/bus/request.rs +++ b/src/rust/lqos_bus/src/bus/request.rs @@ -6,6 +6,28 @@ use allocative::Allocative; use lqos_config::Tunables; use serde::{Deserialize, Serialize}; +/// Source system for an urgent issue +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Copy, Allocative)] +pub enum UrgentSource { + /// Raised by the scheduler process + Scheduler, + /// Raised by the LibreQoS Python orchestrator + LibreQoS, + /// Raised by the local API server + API, + /// Raised by lqosd or other components + System, +} + +/// Severity of an urgent issue +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Copy, Allocative)] +pub enum UrgentSeverity { + /// Error requires attention + Error, + /// Warning is informative/high-visibility + Warning, +} + /// One or more `BusRequest` objects must be included in a `BusSession` /// request. Each `BusRequest` represents a single request for action /// or data. @@ -308,6 +330,28 @@ pub enum BusRequest { /// Check the scheduler status CheckSchedulerStatus, + + /// Submit an urgent issue for high-priority operator visibility + SubmitUrgentIssue { + /// Source of the issue + source: UrgentSource, + /// Severity of the issue + severity: UrgentSeverity, + /// Machine-readable code for the issue (e.g. TC_U16_OVERFLOW) + code: String, + /// Human-readable message for display + message: String, + /// Optional JSON context payload + context: Option, + /// Optional key to deduplicate repeated submissions + dedupe_key: Option, + }, + + /// Retrieve current urgent issues + GetUrgentIssues, + + /// Clear a specific urgent issue by ID + ClearUrgentIssue(u64), } /// Defines the parts of the blackboard diff --git a/src/rust/lqos_bus/src/bus/response.rs b/src/rust/lqos_bus/src/bus/response.rs index e421e46b..2dff1922 100644 --- a/src/rust/lqos_bus/src/bus/response.rs +++ b/src/rust/lqos_bus/src/bus/response.rs @@ -11,6 +11,26 @@ use lqos_utils::units::DownUpOrder; use serde::{Deserialize, Serialize}; use std::net::IpAddr; +/// An urgent issue to be displayed prominently in the UI +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Allocative)] +pub struct UrgentIssue { + /// Unique identifier + pub id: u64, + /// Unix timestamp (seconds) + pub ts: u64, + /// Source component + pub source: crate::bus::request::UrgentSource, + /// Severity level + pub severity: crate::bus::request::UrgentSeverity, + /// Machine-readable code (e.g., TC_U16_OVERFLOW) + pub code: String, + /// Human-readable message + pub message: String, + /// Optional JSON context + pub context: Option, + /// Optional dedupe key + pub dedupe_key: Option, +} /// Serializable snapshot of BakeryStats for bus transmission #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Allocative)] pub struct BakeryStatsSnapshot { @@ -187,4 +207,7 @@ pub enum BusResponse { /// Any error message from integrations error: Option, }, + + /// List of urgent issues + UrgentIssues(Vec), } diff --git a/src/rust/lqos_bus/src/lib.rs b/src/rust/lqos_bus/src/lib.rs index 9b249d48..e016094d 100644 --- a/src/rust/lqos_bus/src/lib.rs +++ b/src/rust/lqos_bus/src/lib.rs @@ -21,11 +21,11 @@ pub use ip_stats::{ tos_parser, }; mod tc_handle; -pub use bus::response::BakeryStatsSnapshot; +pub use bus::response::{BakeryStatsSnapshot, UrgentIssue}; pub use bus::{ BUS_SOCKET_PATH, BlackboardSystem, BusReply, BusRequest, BusResponse, BusSession, CakeDiffTinTransit, CakeDiffTransit, CakeTransit, LibreqosBusClient, QueueStoreTransit, - TopFlowType, UnixSocketServer, bus_request, + TopFlowType, UnixSocketServer, UrgentSeverity, UrgentSource, bus_request, }; pub use tc_handle::TcHandle; diff --git a/src/rust/lqos_python/src/lib.rs b/src/rust/lqos_python/src/lib.rs index 988b2141..5774d612 100644 --- a/src/rust/lqos_python/src/lib.rs +++ b/src/rust/lqos_python/src/lib.rs @@ -1,6 +1,6 @@ #![allow(non_local_definitions)] // Temporary: rewrite required for much of this, for newer PyO3. #![allow(unsafe_op_in_unsafe_fn)] -use lqos_bus::{BlackboardSystem, BusRequest, BusResponse, TcHandle}; +use lqos_bus::{BlackboardSystem, BusRequest, BusResponse, TcHandle, UrgentSource, UrgentSeverity}; use lqos_utils::hex_string::read_hex_string; use nix::libc::getpid; use pyo3::exceptions::PyOSError; @@ -117,6 +117,7 @@ fn liblqos_python(m: &Bound<'_, PyModule>) -> PyResult<()> { m.add_function(wrap_pyfunction!(calculate_hash, m)?)?; m.add_function(wrap_pyfunction!(scheduler_alive, m)?)?; m.add_function(wrap_pyfunction!(scheduler_error, m)?)?; + m.add_function(wrap_pyfunction!(submit_urgent_issue, m)?)?; m.add_class::()?; Ok(()) @@ -1170,3 +1171,49 @@ fn scheduler_error(_py: Python, error: String) -> PyResult { } Ok(false) } + +/// Submit an urgent issue for prominent display in the Node Manager UI. +/// +/// Parameters: +/// - source: one of "Scheduler", "LibreQoS", "API", "System" +/// - severity: "Error" or "Warning" +/// - code: short machine-readable code (e.g., "TC_U16_OVERFLOW") +/// - message: human-readable description +/// - context: optional JSON string with extra details +/// - dedupe_key: optional key to deduplicate repeats (e.g., code+cpu) +#[pyfunction] +fn submit_urgent_issue( + _py: Python, + source: String, + severity: String, + code: String, + message: String, + context: Option, + dedupe_key: Option, +) -> PyResult { + let src = match source.to_ascii_lowercase().as_str() { + "scheduler" => UrgentSource::Scheduler, + "libreqos" => UrgentSource::LibreQoS, + "api" => UrgentSource::API, + _ => UrgentSource::System, + }; + let sev = match severity.to_ascii_lowercase().as_str() { + "warning" => UrgentSeverity::Warning, + _ => UrgentSeverity::Error, + }; + if let Ok(reply) = run_query(vec![BusRequest::SubmitUrgentIssue { + source: src, + severity: sev, + code, + message, + context, + dedupe_key, + }]) { + for resp in reply.iter() { + if let BusResponse::Ack = resp { + return Ok(true); + } + } + } + Ok(false) +} diff --git a/src/rust/lqosd/src/main.rs b/src/rust/lqosd/src/main.rs index 70255c70..1f66eb0a 100644 --- a/src/rust/lqosd/src/main.rs +++ b/src/rust/lqosd/src/main.rs @@ -19,6 +19,7 @@ mod stats; mod system_stats; mod throughput_tracker; mod tool_status; +mod urgent; mod tuning; mod validation; mod version_checks; @@ -639,6 +640,18 @@ fn handle_bus_requests(requests: &[BusRequest], responses: &mut Vec let error = tool_status::scheduler_error_message(); BusResponse::SchedulerStatus { running, error } } + BusRequest::SubmitUrgentIssue { source, severity, code, message, context, dedupe_key } => { + urgent::submit(*source, *severity, code.clone(), message.clone(), context.clone(), dedupe_key.clone()); + BusResponse::Ack + } + BusRequest::GetUrgentIssues => { + let list = urgent::list(); + BusResponse::UrgentIssues(list) + } + BusRequest::ClearUrgentIssue(id) => { + urgent::clear(*id); + BusResponse::Ack + } }); } } diff --git a/src/rust/lqosd/src/node_manager/local_api.rs b/src/rust/lqosd/src/node_manager/local_api.rs index dddf2a20..df6b8fea 100644 --- a/src/rust/lqosd/src/node_manager/local_api.rs +++ b/src/rust/lqosd/src/node_manager/local_api.rs @@ -12,6 +12,7 @@ mod cpu_affinity; mod packet_analysis; mod reload_libreqos; mod scheduler; +mod urgent; mod search; mod shaped_device_api; mod support; @@ -117,6 +118,10 @@ pub fn local_api(shaper_query: tokio::sync::mpsc::Sender) -> .route("/ltsRecentMedian", get(lts::recent_medians)) .route("/scheduler/status", get(scheduler::scheduler_status)) .route("/scheduler/details", get(scheduler::scheduler_details)) + .route("/urgent/status", get(urgent::urgent_status)) + .route("/urgent/list", get(urgent::urgent_list)) + .route("/urgent/clear/:id", post(urgent::urgent_clear)) + .route("/urgent/clear_all", post(urgent::urgent_clear_all)) .route("/chatbot_sso_token", get(chatbot_sso_token)) .layer(Extension(shaper_query)) .layer(CorsLayer::very_permissive()) diff --git a/src/rust/lqosd/src/node_manager/local_api/urgent.rs b/src/rust/lqosd/src/node_manager/local_api/urgent.rs new file mode 100644 index 00000000..03c7c93e --- /dev/null +++ b/src/rust/lqosd/src/node_manager/local_api/urgent.rs @@ -0,0 +1,123 @@ +use axum::extract::Path; +use axum::http::StatusCode; +use axum::Json; +use serde::Serialize; + +use crate::urgent; + +// Remove ANSI escape sequences (basic CSI/OSC handling) for browser display +fn strip_ansi(input: &str) -> String { + let bytes = input.as_bytes(); + let mut out = String::with_capacity(bytes.len()); + let mut i = 0; + while i < bytes.len() { + if bytes[i] == 0x1B { + // ESC sequence + i += 1; + if i >= bytes.len() { + break; + } + match bytes[i] as char { + '[' => { + // CSI: ESC [ ... final byte 0x40..=0x7E + i += 1; + while i < bytes.len() { + let b = bytes[i]; + if (0x40..=0x7E).contains(&b) { + i += 1; + break; + } + i += 1; + } + } + ']' => { + // OSC: ESC ] ... BEL (0x07) or ESC \ + i += 1; + while i < bytes.len() { + if bytes[i] == 0x07 { + i += 1; + break; + } + if bytes[i] == 0x1B { + // ESC + if i + 1 < bytes.len() && bytes[i + 1] as char == '\\' { + i += 2; // ESC \ + break; + } + } + i += 1; + } + } + _ => { + // Other ESC-seq: skip next char at least + i += 1; + } + } + } else { + out.push(bytes[i] as char); + i += 1; + } + } + out +} + +#[derive(Serialize)] +pub struct UrgentStatus { + pub has_urgent: bool, + pub count: usize, +} + +#[derive(Serialize)] +pub struct UrgentItem { + pub id: u64, + pub ts: u64, + pub source: String, + pub severity: String, + pub code: String, + pub message: String, + pub context: Option, +} + +#[derive(Serialize)] +pub struct UrgentList { + pub items: Vec, +} + +pub async fn urgent_status() -> (StatusCode, Json) { + let items = urgent::list(); + ( + StatusCode::OK, + Json(UrgentStatus { has_urgent: !items.is_empty(), count: items.len() }), + ) +} + +pub async fn urgent_list() -> (StatusCode, Json) { + let items = urgent::list(); + let items: Vec = items + .into_iter() + .map(|i| UrgentItem { + id: i.id, + ts: i.ts, + source: format!("{:?}", i.source), + severity: format!("{:?}", i.severity), + code: i.code, + message: strip_ansi(&i.message), + context: i.context, + }) + .collect(); + (StatusCode::OK, Json(UrgentList { items })) +} + +pub async fn urgent_clear(Path(id): Path) -> (StatusCode, &'static str) { + let ok = urgent::clear(id); + if ok { + (StatusCode::OK, "OK") + } else { + (StatusCode::NOT_FOUND, "NOT_FOUND") + } +} + +pub async fn urgent_clear_all() -> (StatusCode, &'static str) { + urgent::clear_all(); + (StatusCode::OK, "OK") +} diff --git a/src/rust/lqosd/src/node_manager/static2/template.html b/src/rust/lqosd/src/node_manager/static2/template.html index 88540ba2..0c2fa7c6 100644 --- a/src/rust/lqosd/src/node_manager/static2/template.html +++ b/src/rust/lqosd/src/node_manager/static2/template.html @@ -116,6 +116,7 @@ Reload LibreQoS + %%URGENT_STATUS%% %%SCHEDULER_STATUS%%


@@ -210,6 +211,27 @@ + + +
LibreQoS %%VERSION%%. © Copyright 2022-2024, LibreQoE LLC. All Rights Reserved.
@@ -231,6 +253,103 @@ }); obs.observe(container, { childList: true, subtree: true }); })(); + + // Urgent Issues: poll status, update badge, and show modal with details + (function(){ + const containerId = 'urgentStatus'; + const linkId = 'urgentStatusLink'; + const badgeId = 'urgentBadge'; + + function ensurePlaceholder(){ + // no-op: server injects a placeholder; if not present, skip + return document.getElementById(containerId) !== null; + } + + function renderStatus(count){ + const cont = document.getElementById(containerId); + if (!cont) return; + const cls = count > 0 ? 'text-danger' : 'text-secondary'; + const icon = count > 0 ? 'fa-bell' : 'fa-bell-slash'; + cont.innerHTML = ` + + Urgent Issues + ${count} + `; + $("#"+containerId).off("click").on("click", `#${linkId}`, (e)=>{ + e.preventDefault(); + showModal(); + }); + } + + function poll(){ + if (!ensurePlaceholder()) return; + $.get('/local-api/urgent/status', (res)=>{ + renderStatus(res.count||0); + }); + } + + function showModal(){ + const modalEl = document.getElementById('urgentModal'); + if (!modalEl) return; + new bootstrap.Modal(modalEl,{focus:true}).show(); + const holder = document.getElementById('urgentListContainer'); + holder.innerHTML = `
Loading...
`; + $.get('/local-api/urgent/list', (res)=>{ + const items = res.items||[]; + if (items.length===0){ holder.innerHTML = '
No urgent issues.
'; return; } + const table = document.createElement('table'); + table.className = 'table table-sm table-striped'; + const tbody = document.createElement('tbody'); + items.forEach(it=>{ + const tr = document.createElement('tr'); + const td = document.createElement('td'); + const when = new Date(it.ts*1000).toLocaleString(); + const sev = it.severity === 'Error' ? 'danger' : 'warning'; + td.innerHTML = ` +
+ ${it.severity} + ${it.code} + (${it.source}) + ${when} + +
+
${it.message}
+ ${it.context?`
${it.context}
`:''} + `; + tr.appendChild(td); + tbody.appendChild(tr); + }); + table.appendChild(tbody); + // Clear existing content and insert table + holder.innerHTML = ''; + holder.appendChild(table); + // Bind clear buttons (acknowledge) + $(holder).off('click').on('click','a.urgent-clear', function(e){ + e.preventDefault(); + const id = $(this).data('id'); + $.post(`/local-api/urgent/clear/${id}`, ()=>{ showModal(); poll(); }); + }); + }).fail(()=>{ + holder.innerHTML = '
Failed to load urgent issues.
'; + }); + } + + // Initial placeholder in case server didn’t inject content (defensive) + if (!document.getElementById(containerId)){ + const ul = document.querySelector('.sidebar .navbar-nav'); + if (ul){ + const li = document.createElement('li'); li.className='nav-item'; li.id=containerId; ul.appendChild(li); + } + } + // Clear all action + $(document).off('click','#urgentClearAll').on('click','#urgentClearAll', function(){ + $.post('/local-api/urgent/clear_all', ()=>{ showModal(); poll(); }); + }); + + // Start polling + poll(); + setInterval(poll, 30000); + })(); diff --git a/src/rust/lqosd/src/node_manager/template.rs b/src/rust/lqosd/src/node_manager/template.rs index 12c5473d..2fd818d7 100644 --- a/src/rust/lqosd/src/node_manager/template.rs +++ b/src/rust/lqosd/src/node_manager/template.rs @@ -167,6 +167,17 @@ pub async fn apply_templates( "##; let byte_string = byte_string.replace("%%SCHEDULER_STATUS%%", scheduler_placeholder); + // Placeholder for urgent issues indicator + let urgent_placeholder = r##" + +"##; + let byte_string = byte_string.replace("%%URGENT_STATUS%%", urgent_placeholder); + let byte_string = byte_string.replace("%CACHEBUSTERS%", &format!("?gh={}", GIT_HASH)); if let Some(length) = res_parts.headers.get_mut("content-length") { *length = HeaderValue::from(byte_string.len()); diff --git a/src/rust/lqosd/src/urgent.rs b/src/rust/lqosd/src/urgent.rs new file mode 100644 index 00000000..483798af --- /dev/null +++ b/src/rust/lqosd/src/urgent.rs @@ -0,0 +1,100 @@ +use std::collections::VecDeque; +use std::sync::atomic::{AtomicU64, Ordering}; + +use lqos_bus::{UrgentIssue, UrgentSeverity, UrgentSource}; +use parking_lot::Mutex; + +use lqos_utils::unix_time::unix_now; + +static NEXT_ID: AtomicU64 = AtomicU64::new(0); +static URGENT: Mutex> = Mutex::new(VecDeque::new()); + +const MAX_ISSUES: usize = 100; +const TTL_SECONDS: u64 = 24 * 60 * 60; // 24h +const DEDUPE_WINDOW_SECONDS: u64 = 300; // 5 minutes + +fn now_unix() -> u64 { + if let Ok(n) = unix_now() { + n + } else { + 0 + } +} + +fn prune_expired(q: &mut VecDeque) { + let now = now_unix(); + while let Some(front) = q.front() { + if front.ts + TTL_SECONDS < now { + q.pop_front(); + } else { + break; + } + } + while q.len() > MAX_ISSUES { + q.pop_front(); + } +} + +pub fn submit( + source: UrgentSource, + severity: UrgentSeverity, + code: String, + message: String, + context: Option, + dedupe_key: Option, +) { + let ts = now_unix(); + let id = NEXT_ID.fetch_add(1, Ordering::Relaxed) + 1; + let mut guard = URGENT.lock(); + prune_expired(&mut guard); + + // Dedupe: same (code, dedupe_key) within window → update timestamp/message + let key = dedupe_key.clone().unwrap_or_else(|| code.clone()); + if let Some(existing) = guard.iter_mut().rev().find(|i| { + (i.code == code) + && (i.dedupe_key.as_deref().unwrap_or("") == key) + && (ts.saturating_sub(i.ts) <= DEDUPE_WINDOW_SECONDS) + }) { + existing.ts = ts; + existing.message = message; + existing.context = context; + return; + } + + let issue = UrgentIssue { + id, + ts, + source, + severity, + code, + message, + context, + dedupe_key: Some(key), + }; + guard.push_back(issue); + prune_expired(&mut guard); +} + +pub fn list() -> Vec { + let mut guard = URGENT.lock(); + prune_expired(&mut guard); + let mut v: Vec = guard.iter().cloned().collect(); + v.sort_by_key(|i| i.ts); + v.reverse(); + v +} + +pub fn clear(id: u64) -> bool { + let mut guard = URGENT.lock(); + if let Some(pos) = guard.iter().position(|i| i.id == id) { + guard.remove(pos); + true + } else { + false + } +} + +pub fn clear_all() { + let mut guard = URGENT.lock(); + guard.clear(); +} -- knotmirror 0.0.1 From f0f84a4290cba99097d78762f4e034eb0b702aec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Robert=20Chac=C3=B3n?= Date: Fri, 7 Nov 2025 16:04:33 -0700 Subject: [PATCH 54/58] Update index.rst --- index.rst | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/index.rst b/index.rst index 6daa34a2..c596407e 100644 --- a/index.rst +++ b/index.rst @@ -29,8 +29,9 @@ Welcome to the LibreQoS documentation .. toctree:: :maxdepth: 1 - :caption: Insight Features + :caption: Insight + docs/v2.0/insight docs/v2.0/api .. toctree:: -- knotmirror 0.0.1 From aa616e46bc18fffeeb6007d55bfbb001fae0d3ba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Robert=20Chac=C3=B3n?= Date: Fri, 7 Nov 2025 16:17:57 -0700 Subject: [PATCH 55/58] Create insight.md --- docs/v2.0/insight.md | 48 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 docs/v2.0/insight.md diff --git a/docs/v2.0/insight.md b/docs/v2.0/insight.md new file mode 100644 index 00000000..a6724eb4 --- /dev/null +++ b/docs/v2.0/insight.md @@ -0,0 +1,48 @@ +# LibreQoS Insight (Insight) + +## About Insight +Learn more about Insight on our website, [here](https://libreqos.io/insight/). + +## Insight UI + +### Taskbar + +taskbar + +If you have more than one LibreQoS shaper box, you can select the shaper box you want to view using the Shaper Nodes dropdown box (located just below the search box). + +### Time Selector + +image + +By clicking the time selector (Last 24 Hours by default) you can set the time range for data display anywhere from 15 minutes to 28 days. You can also specify custom time periods (Now minus X minutes) or highly-specific detailed time periods. + +### Dashboard + +You can see which shaper box "perspective" is in use by the listed shpaer box name at the top-left corner next to "Select a destination". + +01 dashboard + +The dashboard for LibreQoS Insight is widget-based, and has multiple tabs - each of which can be edited. + +#### Traffic Overview Tab + +The default tab is the Traffic Overview tab - which displays both Live traffic levels as well as top-traffic endpoints - both by ASN and by Node. + +#### Shaper Tab + +02 shaper tab + +The Shaper tab shows high-level stats for a particular LibreQoS shaper box. + +- Active Circuit Count: The number of active customer circuits observed - based on the subscriber's traffic movement. +- Throughput: Shaper box throuhgput +- Shaper Packets: Packet-per-second rate of the Shaper box over time. +- Shaper TCP Retransmits Percentage: The percentage of TCP packets observed that were retransmitted. Consider this a proxy for packet loss. This value should typically remain below 1 % across the network. +- Shaper CAKE Activity: How active the CAKE shapers are on the network over time. +- Shaper Round Trip Time: The Round Trip Time average of traffic moving across the network. +- Shaper Round Trip Time Histogram: The Round Trip Time average of traffic moving across the network in histogram format. +- Shaper CPU Utilization: The peak and average CPU utilization of the shaper box over time. +- Shaper Memory Utilization: The RAM utilization of the shaper box over time. + +#### Children Tab -- knotmirror 0.0.1 From 8844855ccd1c5c4a1b272e03b40abc37f2b26136 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Robert=20Chac=C3=B3n?= Date: Fri, 7 Nov 2025 16:28:59 -0700 Subject: [PATCH 56/58] Update insight.md --- docs/v2.0/insight.md | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/docs/v2.0/insight.md b/docs/v2.0/insight.md index a6724eb4..5bfadf4b 100644 --- a/docs/v2.0/insight.md +++ b/docs/v2.0/insight.md @@ -46,3 +46,39 @@ The Shaper tab shows high-level stats for a particular LibreQoS shaper box. - Shaper Memory Utilization: The RAM utilization of the shaper box over time. #### Children Tab + +03 child view + +- Shaper Child Throughput: The throughput of each top-level child node on the shaper box. +- Shaper Child TCP Retransmits: This can be used to spot outliers top-level nodes with regard to Retransmits (packet loss). +- Shaper Child Round Trip Time: This can be used to spot outliers top-level nodes with regard to Round Trip Time. + +#### Heatmaps + +04 heatmap + +This view shows the Round Trip Time, Retransmit, and Capacity heatmaps for the top-level nodes on this shaper box. + +#### Site Rankings + +05 health + +This tab shows the health of Sites / Access Points / etc across the network in terms of their Round Trip Time, TCP Retransmits, and Capacity in each direction. + +### Node Map + +06 map + +This view allows you to identify the general topology of the network from LibreQoS Insight's perspective. If you hover over the bands between nodes, it will display the current throughput and TCP retransmits for that leg of the network. + +### Libby (AI Assistant) +07 libby + +Libby is LibreQoS Insight's AI Chat Assistant. Libby can help with questions you may have about using LibreQoS or LibreQoS Insight. Libby leverages the official LibreQoS documentation to help yu with any questions you may have. Libby can access both live and long-term data - both from synced LibreQoS shaper boxes and from Insight itself. Libby can reply to queries in most major languages with automatic translation. + +You may find new ways to use Libby that we had not originally considered. Please feel welcome to share with us ways you have found Libby to help your workflow. + +### Site Heatmap +08 heatmap + +This view provides RTT, Retransmit, and Capacity heatmaps for every Access Point, OLT, and Site across your network in one view. This allows you to quickly spot trouble points on your network. -- knotmirror 0.0.1 From 25ff0c2497d7b9c46fd2bf2f6dda6690044bd9ed Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Robert=20Chac=C3=B3n?= Date: Fri, 7 Nov 2025 16:37:13 -0700 Subject: [PATCH 57/58] Update insight.md --- docs/v2.0/insight.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/docs/v2.0/insight.md b/docs/v2.0/insight.md index 5bfadf4b..f80e3a1d 100644 --- a/docs/v2.0/insight.md +++ b/docs/v2.0/insight.md @@ -82,3 +82,19 @@ You may find new ways to use Libby that we had not originally considered. Please 08 heatmap This view provides RTT, Retransmit, and Capacity heatmaps for every Access Point, OLT, and Site across your network in one view. This allows you to quickly spot trouble points on your network. + +### Tree History + +09 tree history + +The Tree History is based on the Tree Overview display from the LibreQoS WebUI, and displays the sankey over time to help quickly identify network bottlenecks impacting performance. + +### Reports +10 report + +LibreQoS Insight enables you to trigger AI-generated reports on specific subscriber circuits. These reports draw in from the customer's last 7 days of network activity - including per-ASN performance characteristics, network topology context, and geographic context. The report identifies the User Profile, Key Findings, Critical Issues, Performance Trends, an Upgrade Recommendation, and suggestions for items to manually review. + +### Alerts +11 alerts + +The Alerts section provides you with automated warnings of out-of-norm performance for nodes across the network (Access Points, OLTs, Sites). -- knotmirror 0.0.1 From 7678015f5ab45fa63a157f9d95da50dacd92afef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Robert=20Chac=C3=B3n?= Date: Fri, 7 Nov 2025 16:39:15 -0700 Subject: [PATCH 58/58] Update insight.md --- docs/v2.0/insight.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/v2.0/insight.md b/docs/v2.0/insight.md index f80e3a1d..79974dc1 100644 --- a/docs/v2.0/insight.md +++ b/docs/v2.0/insight.md @@ -21,12 +21,12 @@ By clicking the time selector (Last 24 Hours by default) you can set the time ra You can see which shaper box "perspective" is in use by the listed shpaer box name at the top-left corner next to "Select a destination". -01 dashboard - The dashboard for LibreQoS Insight is widget-based, and has multiple tabs - each of which can be edited. #### Traffic Overview Tab +01 dashboard + The default tab is the Traffic Overview tab - which displays both Live traffic levels as well as top-traffic endpoints - both by ASN and by Node. #### Shaper Tab @@ -36,7 +36,7 @@ The default tab is the Traffic Overview tab - which displays both Live traffic l The Shaper tab shows high-level stats for a particular LibreQoS shaper box. - Active Circuit Count: The number of active customer circuits observed - based on the subscriber's traffic movement. -- Throughput: Shaper box throuhgput +- Throughput: Shaper box throughput - Shaper Packets: Packet-per-second rate of the Shaper box over time. - Shaper TCP Retransmits Percentage: The percentage of TCP packets observed that were retransmitted. Consider this a proxy for packet loss. This value should typically remain below 1 % across the network. - Shaper CAKE Activity: How active the CAKE shapers are on the network over time. @@ -74,7 +74,7 @@ This view allows you to identify the general topology of the network from LibreQ ### Libby (AI Assistant) 07 libby -Libby is LibreQoS Insight's AI Chat Assistant. Libby can help with questions you may have about using LibreQoS or LibreQoS Insight. Libby leverages the official LibreQoS documentation to help yu with any questions you may have. Libby can access both live and long-term data - both from synced LibreQoS shaper boxes and from Insight itself. Libby can reply to queries in most major languages with automatic translation. +Libby is LibreQoS Insight's AI Chat Assistant. Libby can help with questions you may have about using LibreQoS or LibreQoS Insight. Libby leverages the official LibreQoS documentation to help you with any questions you may have. Libby can access both live and long-term data - both from synced LibreQoS shaper boxes and from Insight itself. Libby can reply to queries in most major languages with automatic translation. You may find new ways to use Libby that we had not originally considered. Please feel welcome to share with us ways you have found Libby to help your workflow.
Circuit IDCircuit NameDevice IDDevice NameParent NodeMACIPv4IPv6Download MinUpload MinDownload MaxUpload MaxCommentSQM
Circuit IDCircuit NameDevice IDDevice NameParent NodeMACIPv4IPv6Download MinUpload MinDownload MaxUpload MaxCommentSQM DownSQM Up
"; + sqmDownHtml += ""; + sqmUpHtml += "