From 7e27d7eb58b0404089f14228d180077e76ee7e06 Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Mon, 24 Mar 2025 14:00:21 -0500 Subject: [PATCH 01/42] Refactor: move blackboard to its own module for cleanliness. --- src/rust/uisp_integration/src/blackboard.rs | 43 +++++++++++++++++++++ src/rust/uisp_integration/src/main.rs | 41 +------------------- 2 files changed, 45 insertions(+), 39 deletions(-) create mode 100644 src/rust/uisp_integration/src/blackboard.rs diff --git a/src/rust/uisp_integration/src/blackboard.rs b/src/rust/uisp_integration/src/blackboard.rs new file mode 100644 index 00000000..59841146 --- /dev/null +++ b/src/rust/uisp_integration/src/blackboard.rs @@ -0,0 +1,43 @@ +//! Collects the blackboard functionality together + +use serde::Serialize; +use tracing::info; +use lqos_bus::BlackboardSystem; + +pub async fn blackboard(subsystem: BlackboardSystem, key: &str, value: &str) { + let Ok(config) = lqos_config::load_config() else { + return; + }; + if !config.long_term_stats.use_insight.unwrap_or(false) { + return; + } + let req = vec![lqos_bus::BusRequest::BlackboardData { + subsystem, + key: key.to_string(), + value: value.to_string(), + }]; + let _ = lqos_bus::bus_request(req).await; +} + +pub async fn blackboard_blob(key: &str, value: T) -> anyhow::Result<()> { + let config = lqos_config::load_config()?; + if !config.long_term_stats.use_insight.unwrap_or(false) { + return Ok(()); + } + let blob = serde_cbor::to_vec(&value)?; + let chunks = blob.chunks(1024 * 16); + info!( + "Blob {key} is {} bytes long, split into {} chunks", + blob.len(), + chunks.len() + ); + for (i, chunk) in chunks.enumerate() { + let req = vec![lqos_bus::BusRequest::BlackboardBlob { + tag: key.to_string(), + part: i, + blob: chunk.to_vec(), + }]; + let _ = lqos_bus::bus_request(req).await; + } + Ok(()) +} \ No newline at end of file diff --git a/src/rust/uisp_integration/src/main.rs b/src/rust/uisp_integration/src/main.rs index 173c76dc..a832f50b 100644 --- a/src/rust/uisp_integration/src/main.rs +++ b/src/rust/uisp_integration/src/main.rs @@ -7,14 +7,14 @@ mod errors; pub mod ip_ranges; mod strategies; pub mod uisp_types; +mod blackboard; use crate::errors::UispIntegrationError; use crate::ip_ranges::IpRanges; -use lqos_bus::BlackboardSystem; use lqos_config::Config; -use serde::Serialize; use tokio::time::Instant; use tracing::{error, info}; +pub use blackboard::*; /// Start the tracing/logging system fn init_tracing() { @@ -35,43 +35,6 @@ fn check_enabled_status(config: &Config) -> Result<(), UispIntegrationError> { } } -pub async fn blackboard(subsystem: BlackboardSystem, key: &str, value: &str) { - let Ok(config) = lqos_config::load_config() else { - return; - }; - if !config.long_term_stats.use_insight.unwrap_or(false) { - return; - } - let req = vec![lqos_bus::BusRequest::BlackboardData { - subsystem, - key: key.to_string(), - value: value.to_string(), - }]; - let _ = lqos_bus::bus_request(req).await; -} - -pub async fn blackboard_blob(key: &str, value: T) -> anyhow::Result<()> { - let config = lqos_config::load_config()?; - if !config.long_term_stats.use_insight.unwrap_or(false) { - return Ok(()); - } - let blob = serde_cbor::to_vec(&value)?; - let chunks = blob.chunks(1024 * 16); - info!( - "Blob {key} is {} bytes long, split into {} chunks", - blob.len(), - chunks.len() - ); - for (i, chunk) in chunks.enumerate() { - let req = vec![lqos_bus::BusRequest::BlackboardBlob { - tag: key.to_string(), - part: i, - blob: chunk.to_vec(), - }]; - let _ = lqos_bus::bus_request(req).await; - } - Ok(()) -} #[tokio::main] async fn main() -> Result<(), UispIntegrationError> { -- knotmirror 0.0.1 From 9ed5cbc0b0566a3f86b95c3136aea60187d14f97 Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Mon, 24 Mar 2025 16:03:52 -0500 Subject: [PATCH 02/42] Feature: "ap_only" is now a strategy for UISP integration. It runs bottom-up, starting at clients and trying to find an access point for them. (This is intended as a jumping off point for "ap_site" as the next strategy, and then revamping "full" to work bottom up). --- .../src/strategies/ap_only.rs | 221 ++++++++++++++++++ .../src/strategies/full/mod.rs | 8 +- .../strategies/full/shaped_devices_writer.rs | 2 +- .../uisp_integration/src/strategies/mod.rs | 6 + 4 files changed, 232 insertions(+), 5 deletions(-) create mode 100644 src/rust/uisp_integration/src/strategies/ap_only.rs diff --git a/src/rust/uisp_integration/src/strategies/ap_only.rs b/src/rust/uisp_integration/src/strategies/ap_only.rs new file mode 100644 index 00000000..c5593fa1 --- /dev/null +++ b/src/rust/uisp_integration/src/strategies/ap_only.rs @@ -0,0 +1,221 @@ +use std::collections::HashMap; +use std::fs::write; +use std::path::Path; +use std::sync::Arc; +use tracing::{error, info, warn}; +use lqos_config::Config; +use crate::blackboard_blob; +use crate::errors::UispIntegrationError; +use crate::ip_ranges::IpRanges; +use crate::strategies::full::shaped_devices_writer::ShapedDevice; +use crate::uisp_types::UispSiteType; + +/// Creates a network with only APs detected +/// from clients. +pub async fn build_ap_only_network( + config: Arc, + ip_ranges: IpRanges, +) -> Result<(), UispIntegrationError> { + // Obtain the UISP data and transform it into easier to work with types + let (sites_raw, devices_raw, data_links_raw) = crate::strategies::full::uisp_fetch::load_uisp_data(config.clone()).await?; + + if let Err(e) = blackboard_blob("uisp_sites", &sites_raw).await { + warn!("Unable to write sites to blackboard: {e:?}"); + } + if let Err(e) = blackboard_blob("uisp_devices", &devices_raw).await { + warn!("Unable to write devices to blackboard: {e:?}"); + } + if let Err(e) = blackboard_blob("uisp_data_links", &data_links_raw).await { + warn!("Unable to write data links to blackboard: {e:?}"); + } + + // If Mikrotik is enabled, we need to fetch the Mikrotik data + let ipv4_to_v6 = crate::strategies::full::mikrotik::mikrotik_data(&config) + .await + .unwrap_or_else(|_| Vec::new()); + + // Parse the UISP data into a more usable format + let (sites, _data_links, devices) = crate::strategies::full::parse::parse_uisp_datasets( + &sites_raw, + &data_links_raw, + &devices_raw, + &config, + &ip_ranges, + ipv4_to_v6, + ); + + // Find the clients + let mut mappings = HashMap::new(); + for client in sites.iter().filter(|s| s.site_type == UispSiteType::Client) { + let mut found = false; + let mut parent = None; + for device in devices_raw.iter().filter(|d| d.get_site_id().unwrap_or_default() == client.id) { + //println!("Client {} has a device {:?}", client.name, device.get_name()); + // Look for Parent AP attributes + if let Some(attr) = &device.attributes { + if let Some(ap) = &attr.apDevice { + if let Some(ap_id) = &ap.id { + //println!("AP ID: {}", ap_id); + if let Some(apdev) = devices_raw.iter().find(|d| d.identification.id == *ap_id) { + //println!("AP Device: {:?}", apdev.get_name()); + parent = Some(("AP", apdev.get_name().unwrap_or_default())); + found = true; + } + } + } + } + + // Look for data links with this device + if !found { + for link in data_links_raw.iter() { + // Check the FROM side + if let Some(from_device) = &link.from.device { + if from_device.identification.id == device.identification.id { + if let Some(to_device) = &link.to.device { + if let Some(apdev) = devices_raw.iter().find(|d| d.identification.id == to_device.identification.id) { + parent = Some(("AP", apdev.get_name().unwrap_or_default())); + found = true; + } + } + } + } + // Check the TO side + if let Some(to_device) = &link.to.device { + if to_device.identification.id == device.identification.id { + if let Some(from_device) = &link.from.device { + if let Some(apdev) = devices_raw.iter().find(|d| d.identification.id == from_device.identification.id) { + parent = Some(("AP", apdev.get_name().unwrap_or_default())); + found = true; + } + } + } + } + } + } + } + + // If we still haven't found anything, let's try data links to the client site as a whole + if !found { + for link in data_links_raw.iter() { + if let Some(from_site) = &link.from.site { + if from_site.identification.id == client.id { + if let Some(to_device) = &link.to.device { + if let Some(apdev) = devices_raw.iter().find(|d| d.identification.id == to_device.identification.id) { + parent = Some(("AP", apdev.get_name().unwrap_or_default())); + found = true; + } + } + } + } + if let Some(to_site) = &link.to.site { + if to_site.identification.id == client.id { + if let Some(from_device) = &link.from.device { + if let Some(apdev) = devices_raw.iter().find(|d| d.identification.id == from_device.identification.id) { + parent = Some(("AP", apdev.get_name().unwrap_or_default())); + found = true; + } + } + } + } + } + } + + if !found { + //println!("Client {} has no obvious parent AP", client.name); + let entry = mappings.entry("Orphans".to_string()).or_insert_with(Vec::new); + entry.push(client.id.clone()); + } else { + //info!("Client {} is connected to {:?}", client.name, parent); + if let Some((_, parent)) = &parent { + let entry = mappings.entry(parent.to_string()).or_insert_with(Vec::new); + entry.push(client.id.clone()); + } + } + } + + // We now have enough to build the network + //println!("{:#?}", mappings); + + // Write network.json + let network_path = Path::new(&config.lqos_directory).join("network.json"); + if network_path.exists() && !config.integration_common.always_overwrite_network_json { + warn!( + "Network.json exists, and always overwrite network json is not true - not writing network.json" + ); + return Ok(()); + } + let mut root = serde_json::Map::new(); + for ap in mappings.keys() { + if let Some(ap_device) = devices.iter().find(|d| d.name == *ap) { + let mut ap_object = serde_json::Map::new(); + // Empy children + ap_object.insert("children".to_string(), serde_json::Map::new().into()); + + // Limits + ap_object.insert("downloadBandwidthMbps".to_string(), serde_json::Value::Number(ap_device.download.into())); + ap_object.insert("uploadBandwidthMbps".to_string(), serde_json::Value::Number(ap_device.upload.into())); + + // Save the entry + root.insert(ap.to_string(), ap_object.into()); + } + } + let json = serde_json::to_string_pretty(&root).unwrap(); + write(network_path, json).map_err(|e| { + error!("Unable to write network.json"); + error!("{e:?}"); + UispIntegrationError::WriteNetJson + })?; + info!("Written network.json"); + + // Write ShapedDevices.csv + let file_path = Path::new(&config.lqos_directory).join("ShapedDevices.csv"); + let mut shaped_devices = Vec::new(); + for (parent, client_ids) in mappings.iter() { + for client_id in client_ids { + let site = sites.iter().find(|s| *client_id == s.id).unwrap(); + let devices = devices.iter().filter(|d| d.site_id == *client_id).collect::>(); + for device in devices.iter().filter(|d| d.has_address()) { + let sd = ShapedDevice { + circuit_id: site.id.clone(), + circuit_name: site.name.clone(), + device_id: device.id.clone(), + device_name: device.name.clone(), + parent_node: parent.clone(), + mac: device.mac.clone(), + ipv4: device.ipv4_list(), + ipv6: device.ipv6_list(), + download_min: (site.max_down_mbps as f32 + * config.uisp_integration.commit_bandwidth_multiplier) + as u64, + upload_min: (site.max_up_mbps as f32 + * config.uisp_integration.commit_bandwidth_multiplier) + as u64, + download_max: (site.max_down_mbps as f32 + * config.uisp_integration.bandwidth_overhead_factor) + as u64, + upload_max: (site.max_up_mbps as f32 + * config.uisp_integration.bandwidth_overhead_factor) + as u64, + comment: "".to_string(), + }; + shaped_devices.push(sd); + } + } + } + let mut writer = csv::WriterBuilder::new() + .has_headers(true) + .from_path(file_path) + .unwrap(); + + for d in shaped_devices.iter() { + writer.serialize(d).unwrap(); + } + writer.flush().map_err(|e| { + error!("Unable to flush CSV file"); + error!("{e:?}"); + UispIntegrationError::CsvError + })?; + info!("Wrote {} lines to ShapedDevices.csv", shaped_devices.len()); + + Ok(()) +} \ No newline at end of file diff --git a/src/rust/uisp_integration/src/strategies/full/mod.rs b/src/rust/uisp_integration/src/strategies/full/mod.rs index 1b526e35..c55b48b2 100644 --- a/src/rust/uisp_integration/src/strategies/full/mod.rs +++ b/src/rust/uisp_integration/src/strategies/full/mod.rs @@ -1,15 +1,15 @@ mod ap_promotion; mod bandwidth_overrides; mod client_site_promotion; -mod mikrotik; +pub mod mikrotik; mod network_json; -mod parse; +pub(crate) mod parse; mod root_site; mod routes_override; -mod shaped_devices_writer; +pub mod shaped_devices_writer; mod squash_single_entry_aps; mod tree_walk; -mod uisp_fetch; +pub(crate) mod uisp_fetch; mod utils; mod zero_capacity_sites; diff --git a/src/rust/uisp_integration/src/strategies/full/shaped_devices_writer.rs b/src/rust/uisp_integration/src/strategies/full/shaped_devices_writer.rs index cc411bb5..d248bcd7 100644 --- a/src/rust/uisp_integration/src/strategies/full/shaped_devices_writer.rs +++ b/src/rust/uisp_integration/src/strategies/full/shaped_devices_writer.rs @@ -7,7 +7,7 @@ use tracing::{error, info}; /// Represents a shaped device in the ShapedDevices.csv file. #[derive(Serialize, Debug)] -struct ShapedDevice { +pub struct ShapedDevice { pub circuit_id: String, pub circuit_name: String, pub device_id: String, diff --git a/src/rust/uisp_integration/src/strategies/mod.rs b/src/rust/uisp_integration/src/strategies/mod.rs index 3cb5875e..8ad8d03c 100644 --- a/src/rust/uisp_integration/src/strategies/mod.rs +++ b/src/rust/uisp_integration/src/strategies/mod.rs @@ -1,5 +1,6 @@ mod flat; mod full; +mod ap_only; use crate::blackboard; use crate::errors::UispIntegrationError; @@ -32,6 +33,11 @@ pub async fn build_with_strategy( full::build_full_network(config, ip_ranges).await?; Ok(()) } + "ap_only" => { + info!("Strategy selected: ap_only"); + ap_only::build_ap_only_network(config, ip_ranges).await?; + Ok(()) + } _ => { error!( "Unknown strategy: {}. Bailing.", -- knotmirror 0.0.1 From a5fac5cc5f9b79a33d784a8cb8bd90443b6191bf Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Mon, 24 Mar 2025 16:12:33 -0500 Subject: [PATCH 03/42] Feat: Support metadata on ap_only --- src/rust/uisp_integration/src/strategies/ap_only.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/rust/uisp_integration/src/strategies/ap_only.rs b/src/rust/uisp_integration/src/strategies/ap_only.rs index c5593fa1..1d348dfe 100644 --- a/src/rust/uisp_integration/src/strategies/ap_only.rs +++ b/src/rust/uisp_integration/src/strategies/ap_only.rs @@ -155,6 +155,10 @@ pub async fn build_ap_only_network( ap_object.insert("downloadBandwidthMbps".to_string(), serde_json::Value::Number(ap_device.download.into())); ap_object.insert("uploadBandwidthMbps".to_string(), serde_json::Value::Number(ap_device.upload.into())); + // Metadata + ap_object.insert("type".to_string(), "AP".to_string().into()); + ap_object.insert("uisp_device".to_string(), ap_device.id.clone().into()); + // Save the entry root.insert(ap.to_string(), ap_object.into()); } -- knotmirror 0.0.1 From 8b5f3f80b55177220a9a7558341384655527e085 Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Tue, 25 Mar 2025 09:12:02 -0500 Subject: [PATCH 04/42] Refactor: Move much functionality for data wrangling into a common class. --- .../src/strategies/ap_only.rs | 126 +---------- .../src/strategies/ap_site.rs | 22 ++ .../uisp_integration/src/strategies/common.rs | 200 ++++++++++++++++++ .../uisp_integration/src/strategies/mod.rs | 7 + 4 files changed, 235 insertions(+), 120 deletions(-) create mode 100644 src/rust/uisp_integration/src/strategies/ap_site.rs create mode 100644 src/rust/uisp_integration/src/strategies/common.rs diff --git a/src/rust/uisp_integration/src/strategies/ap_only.rs b/src/rust/uisp_integration/src/strategies/ap_only.rs index 1d348dfe..6c2ee777 100644 --- a/src/rust/uisp_integration/src/strategies/ap_only.rs +++ b/src/rust/uisp_integration/src/strategies/ap_only.rs @@ -7,6 +7,7 @@ use lqos_config::Config; use crate::blackboard_blob; use crate::errors::UispIntegrationError; use crate::ip_ranges::IpRanges; +use crate::strategies::common::UispData; use crate::strategies::full::shaped_devices_writer::ShapedDevice; use crate::uisp_types::UispSiteType; @@ -16,125 +17,10 @@ pub async fn build_ap_only_network( config: Arc, ip_ranges: IpRanges, ) -> Result<(), UispIntegrationError> { - // Obtain the UISP data and transform it into easier to work with types - let (sites_raw, devices_raw, data_links_raw) = crate::strategies::full::uisp_fetch::load_uisp_data(config.clone()).await?; - - if let Err(e) = blackboard_blob("uisp_sites", &sites_raw).await { - warn!("Unable to write sites to blackboard: {e:?}"); - } - if let Err(e) = blackboard_blob("uisp_devices", &devices_raw).await { - warn!("Unable to write devices to blackboard: {e:?}"); - } - if let Err(e) = blackboard_blob("uisp_data_links", &data_links_raw).await { - warn!("Unable to write data links to blackboard: {e:?}"); - } - - // If Mikrotik is enabled, we need to fetch the Mikrotik data - let ipv4_to_v6 = crate::strategies::full::mikrotik::mikrotik_data(&config) - .await - .unwrap_or_else(|_| Vec::new()); - - // Parse the UISP data into a more usable format - let (sites, _data_links, devices) = crate::strategies::full::parse::parse_uisp_datasets( - &sites_raw, - &data_links_raw, - &devices_raw, - &config, - &ip_ranges, - ipv4_to_v6, - ); + let uisp_data = UispData::fetch_uisp_data(config.clone(), ip_ranges).await?; // Find the clients - let mut mappings = HashMap::new(); - for client in sites.iter().filter(|s| s.site_type == UispSiteType::Client) { - let mut found = false; - let mut parent = None; - for device in devices_raw.iter().filter(|d| d.get_site_id().unwrap_or_default() == client.id) { - //println!("Client {} has a device {:?}", client.name, device.get_name()); - // Look for Parent AP attributes - if let Some(attr) = &device.attributes { - if let Some(ap) = &attr.apDevice { - if let Some(ap_id) = &ap.id { - //println!("AP ID: {}", ap_id); - if let Some(apdev) = devices_raw.iter().find(|d| d.identification.id == *ap_id) { - //println!("AP Device: {:?}", apdev.get_name()); - parent = Some(("AP", apdev.get_name().unwrap_or_default())); - found = true; - } - } - } - } - - // Look for data links with this device - if !found { - for link in data_links_raw.iter() { - // Check the FROM side - if let Some(from_device) = &link.from.device { - if from_device.identification.id == device.identification.id { - if let Some(to_device) = &link.to.device { - if let Some(apdev) = devices_raw.iter().find(|d| d.identification.id == to_device.identification.id) { - parent = Some(("AP", apdev.get_name().unwrap_or_default())); - found = true; - } - } - } - } - // Check the TO side - if let Some(to_device) = &link.to.device { - if to_device.identification.id == device.identification.id { - if let Some(from_device) = &link.from.device { - if let Some(apdev) = devices_raw.iter().find(|d| d.identification.id == from_device.identification.id) { - parent = Some(("AP", apdev.get_name().unwrap_or_default())); - found = true; - } - } - } - } - } - } - } - - // If we still haven't found anything, let's try data links to the client site as a whole - if !found { - for link in data_links_raw.iter() { - if let Some(from_site) = &link.from.site { - if from_site.identification.id == client.id { - if let Some(to_device) = &link.to.device { - if let Some(apdev) = devices_raw.iter().find(|d| d.identification.id == to_device.identification.id) { - parent = Some(("AP", apdev.get_name().unwrap_or_default())); - found = true; - } - } - } - } - if let Some(to_site) = &link.to.site { - if to_site.identification.id == client.id { - if let Some(from_device) = &link.from.device { - if let Some(apdev) = devices_raw.iter().find(|d| d.identification.id == from_device.identification.id) { - parent = Some(("AP", apdev.get_name().unwrap_or_default())); - found = true; - } - } - } - } - } - } - - if !found { - //println!("Client {} has no obvious parent AP", client.name); - let entry = mappings.entry("Orphans".to_string()).or_insert_with(Vec::new); - entry.push(client.id.clone()); - } else { - //info!("Client {} is connected to {:?}", client.name, parent); - if let Some((_, parent)) = &parent { - let entry = mappings.entry(parent.to_string()).or_insert_with(Vec::new); - entry.push(client.id.clone()); - } - } - } - - // We now have enough to build the network - //println!("{:#?}", mappings); + let mappings = uisp_data.map_clients_to_aps(); // Write network.json let network_path = Path::new(&config.lqos_directory).join("network.json"); @@ -146,7 +32,7 @@ pub async fn build_ap_only_network( } let mut root = serde_json::Map::new(); for ap in mappings.keys() { - if let Some(ap_device) = devices.iter().find(|d| d.name == *ap) { + if let Some(ap_device) = uisp_data.devices.iter().find(|d| d.name == *ap) { let mut ap_object = serde_json::Map::new(); // Empy children ap_object.insert("children".to_string(), serde_json::Map::new().into()); @@ -176,8 +62,8 @@ pub async fn build_ap_only_network( let mut shaped_devices = Vec::new(); for (parent, client_ids) in mappings.iter() { for client_id in client_ids { - let site = sites.iter().find(|s| *client_id == s.id).unwrap(); - let devices = devices.iter().filter(|d| d.site_id == *client_id).collect::>(); + let site = uisp_data.sites.iter().find(|s| *client_id == s.id).unwrap(); + let devices = uisp_data.devices.iter().filter(|d| d.site_id == *client_id).collect::>(); for device in devices.iter().filter(|d| d.has_address()) { let sd = ShapedDevice { circuit_id: site.id.clone(), diff --git a/src/rust/uisp_integration/src/strategies/ap_site.rs b/src/rust/uisp_integration/src/strategies/ap_site.rs new file mode 100644 index 00000000..b74d9ab5 --- /dev/null +++ b/src/rust/uisp_integration/src/strategies/ap_site.rs @@ -0,0 +1,22 @@ +use std::collections::HashMap; +use std::fs::write; +use std::path::Path; +use std::sync::Arc; +use tracing::{error, info, warn}; +use lqos_config::Config; +use crate::blackboard_blob; +use crate::errors::UispIntegrationError; +use crate::ip_ranges::IpRanges; +use crate::strategies::full::shaped_devices_writer::ShapedDevice; +use crate::uisp_types::UispSiteType; + +/// Creates a network with APs detected from clients, +/// and then a single site above them (shared if the site +/// matches). +pub async fn build_ap_site_network( + config: Arc, + ip_ranges: IpRanges, +) -> Result<(), UispIntegrationError> { + + Ok(()) +} \ No newline at end of file diff --git a/src/rust/uisp_integration/src/strategies/common.rs b/src/rust/uisp_integration/src/strategies/common.rs new file mode 100644 index 00000000..bc8fbc53 --- /dev/null +++ b/src/rust/uisp_integration/src/strategies/common.rs @@ -0,0 +1,200 @@ +use std::collections::HashMap; +use std::sync::Arc; +use tracing::warn; +use lqos_config::Config; +use uisp::{DataLink, Device, Site}; +use crate::blackboard_blob; +use crate::ip_ranges::IpRanges; +use crate::strategies::full::uisp_fetch::load_uisp_data; +use crate::errors::UispIntegrationError; +use crate::strategies::full::parse::parse_uisp_datasets; +use crate::uisp_types::{UispDataLink, UispDevice, UispSite, UispSiteType}; + +pub(crate) struct UispData { + pub sites_raw: Vec, + pub devices_raw: Vec, + pub data_links_raw: Vec, + pub sites: Vec, + pub devices: Vec, + pub data_links: Vec, +} + +impl UispData { + pub(crate) async fn fetch_uisp_data( + config: Arc, + ip_ranges: IpRanges, + ) -> std::result::Result { + // Obtain the UISP data and transform it into easier to work with types + let (sites_raw, devices_raw, data_links_raw) = load_uisp_data(config.clone()).await?; + + if let Err(e) = blackboard_blob("uisp_sites", &sites_raw).await { + warn!("Unable to write sites to blackboard: {e:?}"); + } + if let Err(e) = blackboard_blob("uisp_devices", &devices_raw).await { + warn!("Unable to write devices to blackboard: {e:?}"); + } + if let Err(e) = blackboard_blob("uisp_data_links", &data_links_raw).await { + warn!("Unable to write data links to blackboard: {e:?}"); + } + + // If Mikrotik is enabled, we need to fetch the Mikrotik data + let ipv4_to_v6 = crate::strategies::full::mikrotik::mikrotik_data(&config) + .await + .unwrap_or_else(|_| Vec::new()); + + // Parse the UISP data into a more usable format + let (sites, _data_links, devices) = parse_uisp_datasets( + &sites_raw, + &data_links_raw, + &devices_raw, + &config, + &ip_ranges, + ipv4_to_v6, + ); + + Ok(UispData { + sites_raw, + devices_raw, + data_links_raw, + sites, + devices, + data_links: _data_links, + }) + } + + pub fn find_client_sites(&self) -> Vec<&UispSite> { + self.sites.iter().filter(|s| s.site_type == UispSiteType::Client).collect() + } + + pub fn find_devices_in_site(&self, site_id: &str) -> Vec<&Device> { + self.devices_raw.iter().filter(|d| d.get_site_id().unwrap_or_default() == site_id).collect() + } + + pub fn find_device_by_id(&self, device_id: &str) -> Option<&Device> { + self.devices_raw.iter().find(|d| d.identification.id == device_id) + } + + pub fn find_data_links_featuring_device(&self, device_id: &str) -> Vec<&DataLink> { + self. + data_links_raw. + iter() + .filter(|dl| { + if let Some(from_device) = &dl.from.device { + from_device.identification.id == device_id + } else if let Some(to_device) = &dl.to.device { + to_device.identification.id == device_id + } else { + false + } + }) + .collect() + } + + pub fn find_data_links_featuring_site(&self, site_id: &str) -> Vec<&DataLink> { + self. + data_links_raw. + iter() + .filter(|dl| { + if let Some(from_site) = &dl.from.site { + from_site.identification.id == site_id + } else if let Some(to_site) = &dl.to.site { + to_site.identification.id == site_id + } else { + false + } + }) + .collect() + } + + pub fn map_clients_to_aps(&self) -> HashMap> { + let mut mappings = HashMap::new(); + for client in self.find_client_sites() { + let mut found = false; + let mut parent = None; + for device in self.find_devices_in_site(&client.id) { + //println!("Client {} has a device {:?}", client.name, device.get_name()); + // Look for Parent AP attributes + if let Some(attr) = &device.attributes { + if let Some(ap) = &attr.apDevice { + if let Some(ap_id) = &ap.id { + //println!("AP ID: {}", ap_id); + if let Some(apdev) = self.find_device_by_id(ap_id) { + //println!("AP Device: {:?}", apdev.get_name()); + parent = Some(("AP", apdev.get_name().unwrap_or_default())); + found = true; + } + } + } + } + + // Look for data links with this device + if !found { + for link in self.find_data_links_featuring_device(&device.identification.id) { + // Check the FROM side + if let Some(from_device) = &link.from.device { + if from_device.identification.id == device.identification.id { + if let Some(to_device) = &link.to.device { + if let Some(apdev) = self.find_device_by_id(&to_device.identification.id) { + parent = Some(("AP", apdev.get_name().unwrap_or_default())); + found = true; + } + } + } + } + // Check the TO side + if let Some(to_device) = &link.to.device { + if to_device.identification.id == device.identification.id { + if let Some(from_device) = &link.from.device { + if let Some(apdev) = self.find_device_by_id(&from_device.identification.id) { + parent = Some(("AP", apdev.get_name().unwrap_or_default())); + found = true; + } + } + } + } + } + } + } + + // If we still haven't found anything, let's try data links to the client site as a whole + if !found { + for link in self.find_data_links_featuring_site(&client.id) { + if let Some(from_site) = &link.from.site { + if from_site.identification.id == client.id { + if let Some(to_device) = &link.to.device { + if let Some(apdev) = self.find_device_by_id(&to_device.identification.id) { + parent = Some(("AP", apdev.get_name().unwrap_or_default())); + found = true; + } + } + } + } + if let Some(to_site) = &link.to.site { + if to_site.identification.id == client.id { + if let Some(from_device) = &link.from.device { + if let Some(apdev) = self.find_device_by_id(&from_device.identification.id) { + parent = Some(("AP", apdev.get_name().unwrap_or_default())); + found = true; + } + } + } + } + } + } + + if !found { + //println!("Client {} has no obvious parent AP", client.name); + let entry = mappings.entry("Orphans".to_string()).or_insert_with(Vec::new); + entry.push(client.id.clone()); + } else { + //info!("Client {} is connected to {:?}", client.name, parent); + if let Some((_, parent)) = &parent { + let entry = mappings.entry(parent.to_string()).or_insert_with(Vec::new); + entry.push(client.id.clone()); + } + } + } + mappings + } +} + diff --git a/src/rust/uisp_integration/src/strategies/mod.rs b/src/rust/uisp_integration/src/strategies/mod.rs index 8ad8d03c..e89f40ab 100644 --- a/src/rust/uisp_integration/src/strategies/mod.rs +++ b/src/rust/uisp_integration/src/strategies/mod.rs @@ -1,6 +1,8 @@ mod flat; mod full; mod ap_only; +mod ap_site; +mod common; use crate::blackboard; use crate::errors::UispIntegrationError; @@ -38,6 +40,11 @@ pub async fn build_with_strategy( ap_only::build_ap_only_network(config, ip_ranges).await?; Ok(()) } + "ap_site" => { + info!("Strategy selected: ap_site"); + ap_site::build_ap_site_network(config, ip_ranges).await?; + Ok(()) + } _ => { error!( "Unknown strategy: {}. Bailing.", -- knotmirror 0.0.1 From 191798efcbb5a567e990c70de339f6cbf1ce20da Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Tue, 25 Mar 2025 09:49:39 -0500 Subject: [PATCH 05/42] Fix: Don't count APs that go to the same client site! --- .../src/strategies/ap_site.rs | 24 +++++++++---- .../uisp_integration/src/strategies/common.rs | 34 +++++++++++++------ 2 files changed, 42 insertions(+), 16 deletions(-) diff --git a/src/rust/uisp_integration/src/strategies/ap_site.rs b/src/rust/uisp_integration/src/strategies/ap_site.rs index b74d9ab5..10a0bf76 100644 --- a/src/rust/uisp_integration/src/strategies/ap_site.rs +++ b/src/rust/uisp_integration/src/strategies/ap_site.rs @@ -1,13 +1,8 @@ -use std::collections::HashMap; -use std::fs::write; -use std::path::Path; use std::sync::Arc; -use tracing::{error, info, warn}; use lqos_config::Config; -use crate::blackboard_blob; use crate::errors::UispIntegrationError; use crate::ip_ranges::IpRanges; -use crate::strategies::full::shaped_devices_writer::ShapedDevice; +use crate::strategies::common::UispData; use crate::uisp_types::UispSiteType; /// Creates a network with APs detected from clients, @@ -17,6 +12,23 @@ pub async fn build_ap_site_network( config: Arc, ip_ranges: IpRanges, ) -> Result<(), UispIntegrationError> { + let uisp_data = UispData::fetch_uisp_data(config.clone(), ip_ranges).await?; + + // Find the clients + let ap_mappings = uisp_data.map_clients_to_aps(); + + // Locate any APs that are located within client sites + for (ap_name, _) in ap_mappings.iter() { + if let Some(device) = uisp_data.find_device_by_name(ap_name) { + if let Some(device_site_id) = device.get_site_id() { + if let Some(device_site) = uisp_data.sites.iter().find(|s| s.id == device_site_id) { + if device_site.site_type == UispSiteType::Client { + println!("Found AP {} in client site {}", ap_name, device_site.name); + } + } + } + } + } Ok(()) } \ No newline at end of file diff --git a/src/rust/uisp_integration/src/strategies/common.rs b/src/rust/uisp_integration/src/strategies/common.rs index bc8fbc53..be51140c 100644 --- a/src/rust/uisp_integration/src/strategies/common.rs +++ b/src/rust/uisp_integration/src/strategies/common.rs @@ -74,6 +74,10 @@ impl UispData { self.devices_raw.iter().find(|d| d.identification.id == device_id) } + pub fn find_device_by_name(&self, device_name: &str) -> Option<&Device> { + self.devices_raw.iter().find(|d| d.get_name().unwrap_or_default() == device_name) + } + pub fn find_data_links_featuring_device(&self, device_id: &str) -> Vec<&DataLink> { self. data_links_raw. @@ -120,8 +124,10 @@ impl UispData { //println!("AP ID: {}", ap_id); if let Some(apdev) = self.find_device_by_id(ap_id) { //println!("AP Device: {:?}", apdev.get_name()); - parent = Some(("AP", apdev.get_name().unwrap_or_default())); - found = true; + if apdev.get_site_id().unwrap_or_default() != client.id { + parent = Some(("AP", apdev.get_name().unwrap_or_default())); + found = true; + } } } } @@ -135,8 +141,10 @@ impl UispData { if from_device.identification.id == device.identification.id { if let Some(to_device) = &link.to.device { if let Some(apdev) = self.find_device_by_id(&to_device.identification.id) { - parent = Some(("AP", apdev.get_name().unwrap_or_default())); - found = true; + if apdev.get_site_id().unwrap_or_default() != client.id { + parent = Some(("AP", apdev.get_name().unwrap_or_default())); + found = true; + } } } } @@ -146,8 +154,10 @@ impl UispData { if to_device.identification.id == device.identification.id { if let Some(from_device) = &link.from.device { if let Some(apdev) = self.find_device_by_id(&from_device.identification.id) { - parent = Some(("AP", apdev.get_name().unwrap_or_default())); - found = true; + if apdev.get_site_id().unwrap_or_default() != client.id { + parent = Some(("AP", apdev.get_name().unwrap_or_default())); + found = true; + } } } } @@ -163,8 +173,10 @@ impl UispData { if from_site.identification.id == client.id { if let Some(to_device) = &link.to.device { if let Some(apdev) = self.find_device_by_id(&to_device.identification.id) { - parent = Some(("AP", apdev.get_name().unwrap_or_default())); - found = true; + if apdev.get_site_id().unwrap_or_default() != client.id { + parent = Some(("AP", apdev.get_name().unwrap_or_default())); + found = true; + } } } } @@ -173,8 +185,10 @@ impl UispData { if to_site.identification.id == client.id { if let Some(from_device) = &link.from.device { if let Some(apdev) = self.find_device_by_id(&from_device.identification.id) { - parent = Some(("AP", apdev.get_name().unwrap_or_default())); - found = true; + if apdev.get_site_id().unwrap_or_default() != client.id { + parent = Some(("AP", apdev.get_name().unwrap_or_default())); + found = true; + } } } } -- knotmirror 0.0.1 From 6ee397051b637e9326c9f0a23d9cec9ed990d65d Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Tue, 25 Mar 2025 15:25:21 -0500 Subject: [PATCH 06/42] Feature: "ap_site" mode generates all clients, with an AP on top. The APs are then grouped into parent sites. "Relays" are not specially supported yet and may well end up orphaned. --- src/rust/uisp_integration/Cargo.toml | 2 +- .../src/strategies/ap_site.rs | 202 +++++++++++++++++- .../uisp_integration/src/strategies/common.rs | 27 ++- 3 files changed, 223 insertions(+), 8 deletions(-) diff --git a/src/rust/uisp_integration/Cargo.toml b/src/rust/uisp_integration/Cargo.toml index f9c0400b..2378356a 100644 --- a/src/rust/uisp_integration/Cargo.toml +++ b/src/rust/uisp_integration/Cargo.toml @@ -19,4 +19,4 @@ serde_json = { workspace = true } ip_network_table = { workspace = true } ip_network = { workspace = true } serde_cbor = { workspace = true } -lqos_bus = { path = "../lqos_bus" } \ No newline at end of file +lqos_bus = { path = "../lqos_bus" } diff --git a/src/rust/uisp_integration/src/strategies/ap_site.rs b/src/rust/uisp_integration/src/strategies/ap_site.rs index 10a0bf76..ff91319e 100644 --- a/src/rust/uisp_integration/src/strategies/ap_site.rs +++ b/src/rust/uisp_integration/src/strategies/ap_site.rs @@ -1,10 +1,24 @@ +use std::collections::HashMap; +use std::fs::write; +use std::path::Path; use std::sync::Arc; +use tracing::{error, info, warn}; use lqos_config::Config; use crate::errors::UispIntegrationError; use crate::ip_ranges::IpRanges; use crate::strategies::common::UispData; +use crate::strategies::full::shaped_devices_writer::ShapedDevice; use crate::uisp_types::UispSiteType; +#[derive(Debug, Ord, PartialOrd, Eq, PartialEq, Clone)] +pub enum GraphMapping { + Root, + SiteByName(String), + GeneratedSiteByName(String), + AccessPointByName(String), + ClientById(String), +} + /// Creates a network with APs detected from clients, /// and then a single site above them (shared if the site /// matches). @@ -17,18 +31,196 @@ pub async fn build_ap_site_network( // Find the clients let ap_mappings = uisp_data.map_clients_to_aps(); - // Locate any APs that are located within client sites - for (ap_name, _) in ap_mappings.iter() { + // Make AP Layer entries + let mut access_points = HashMap::new(); + for (ap_name, client_ids) in ap_mappings.iter() { + let mut ap_layer = Layer { + id: GraphMapping::AccessPointByName(ap_name.clone()), + children: Vec::new(), + }; + for client_id in client_ids.iter() { + ap_layer.children.push(Layer { + id: GraphMapping::ClientById(client_id.clone()), + children: Vec::new(), + }); + } + access_points.insert(ap_name.clone(), ap_layer); + } + + // Site mappings + let mut sites = HashMap::new(); + for (ap_name, client_ids) in ap_mappings.iter() { if let Some(device) = uisp_data.find_device_by_name(ap_name) { if let Some(device_site_id) = device.get_site_id() { if let Some(device_site) = uisp_data.sites.iter().find(|s| s.id == device_site_id) { - if device_site.site_type == UispSiteType::Client { - println!("Found AP {} in client site {}", ap_name, device_site.name); - } + let site_entry = sites.entry(device_site.name.clone()).or_insert_with(|| { + Layer { + id: GraphMapping::SiteByName(device_site.name.clone()), + children: Vec::new(), + } + }); + let ap_map = access_points.get(ap_name).unwrap().clone(); + site_entry.children.push(ap_map); } } + } else { + let mut detached = Layer { + id: GraphMapping::SiteByName(ap_name.clone()), + children: vec![], + }; + for client_id in client_ids.iter() { + detached.children.push(Layer { + id: GraphMapping::ClientById(client_id.clone()), + children: vec![], + }); + } + sites.insert(ap_name.clone(), detached); } } + let mut root = Layer { + id: GraphMapping::Root, + children: sites.values().cloned().collect(), + }; + println!("{:#?}", root); + + let mut shaped_devices = Vec::new(); + let net_json = root.walk_children(None, &uisp_data, &mut shaped_devices, &config); + + let network_path = Path::new(&config.lqos_directory).join("network.json"); + if network_path.exists() && !config.integration_common.always_overwrite_network_json { + warn!( + "Network.json exists, and always overwrite network json is not true - not writing network.json" + ); + return Ok(()); + } + let json = serde_json::to_string_pretty(&net_json).unwrap(); + write(network_path, json).map_err(|e| { + error!("Unable to write network.json"); + error!("{e:?}"); + UispIntegrationError::WriteNetJson + })?; + info!("Written network.json"); + + let file_path = Path::new(&config.lqos_directory).join("ShapedDevices.csv"); + let mut writer = csv::WriterBuilder::new() + .has_headers(true) + .from_path(file_path) + .unwrap(); + + for d in shaped_devices.iter() { + writer.serialize(d).unwrap(); + } + writer.flush().map_err(|e| { + error!("Unable to flush CSV file"); + error!("{e:?}"); + UispIntegrationError::CsvError + })?; + info!("Wrote {} lines to ShapedDevices.csv", shaped_devices.len()); Ok(()) +} + +#[derive(Debug, Clone)] +struct Layer { + id: GraphMapping, + children: Vec, +} + +impl Layer { + fn walk_children( + &self, + parent: Option<&str>, + uisp_data: &UispData, + shaped_devices: &mut Vec, + config: &Config, + ) -> serde_json::Map { + let mut children = serde_json::Map::new(); + let parent_name = match &self.id { + GraphMapping::SiteByName(name) | GraphMapping::AccessPointByName(name) + | GraphMapping::GeneratedSiteByName(name) => { + name.to_owned() + } + _ => "".to_owned() + }; + for child in self.children.iter() { + match &child.id { + GraphMapping::SiteByName(name) | GraphMapping::AccessPointByName(name) + | GraphMapping::GeneratedSiteByName(name) => { + children.insert(name.clone(), child.walk_children(Some(&parent_name), uisp_data, shaped_devices, config).into()); + } + GraphMapping::ClientById(client_id) => { + let _ = child.walk_children(Some(&parent_name), uisp_data, shaped_devices, config); + } + _ => {} + } + } + let mut root = serde_json::Map::new(); + if let Some(parent) = parent { + match &self.id { + GraphMapping::SiteByName(name) => { + root.insert("type".to_string(), "Site".into()); + root.insert("name".to_string(), name.clone().into()); + if let Some(site) = uisp_data.sites.iter().find(|s| s.name == *name) { + root.insert("downloadBandwidthMbps".to_owned(), site.max_down_mbps.into()); + root.insert("uploadBandwidthMbps".to_owned(), site.max_up_mbps.into()); + root.insert("uisp_site".to_string(), site.id.clone().into()); + } + } + GraphMapping::AccessPointByName(name) => { + root.insert("type".to_string(), "AP".into()); + root.insert("name".to_string(), name.clone().into()); + if let Some(device) = uisp_data.devices.iter().find(|d| d.name == *name) { + root.insert("downloadBandwidthMbps".to_owned(), device.download.into()); + root.insert("uploadBandwidthMbps".to_owned(), device.upload.into()); + root.insert("uisp_device".to_string(), device.id.clone().into()); + } + } + GraphMapping::GeneratedSiteByName(name) => { + root.insert("type".to_string(), "AP".into()); + root.insert("name".to_string(), name.clone().into()); + if let Some(device) = uisp_data.devices.iter().find(|d| d.name == *name) { + root.insert("downloadBandwidthMbps".to_owned(), device.download.into()); + root.insert("uploadBandwidthMbps".to_owned(), device.upload.into()); + root.insert("uisp_device".to_string(), device.id.clone().into()); + } + } + GraphMapping::ClientById(client_id) => { + if let Some(site) = uisp_data.sites.iter().find(|c| c.id == *client_id) { + let devices = uisp_data.devices.iter().filter(|d| d.site_id == *client_id).collect::>(); + for device in devices.iter().filter(|d| d.has_address()) { + let sd = ShapedDevice { + circuit_id: site.id.clone(), + circuit_name: site.name.clone(), + device_id: device.id.clone(), + device_name: device.name.clone(), + parent_node: parent.to_owned(), + mac: device.mac.clone(), + ipv4: device.ipv4_list(), + ipv6: device.ipv6_list(), + download_min: (site.max_down_mbps as f32 + * config.uisp_integration.commit_bandwidth_multiplier) + as u64, + upload_min: (site.max_up_mbps as f32 + * config.uisp_integration.commit_bandwidth_multiplier) + as u64, + download_max: (site.max_down_mbps as f32 + * config.uisp_integration.bandwidth_overhead_factor) + as u64, + upload_max: (site.max_up_mbps as f32 + * config.uisp_integration.bandwidth_overhead_factor) + as u64, + comment: "".to_string(), + }; + shaped_devices.push(sd); + } + } else { + warn!("Client not found: {}", client_id); + } + } + _ => {} + } + } + root.insert("children".to_string(), serde_json::to_value(children).unwrap()); + root + } } \ No newline at end of file diff --git a/src/rust/uisp_integration/src/strategies/common.rs b/src/rust/uisp_integration/src/strategies/common.rs index be51140c..e1157942 100644 --- a/src/rust/uisp_integration/src/strategies/common.rs +++ b/src/rust/uisp_integration/src/strategies/common.rs @@ -78,6 +78,14 @@ impl UispData { self.devices_raw.iter().find(|d| d.get_name().unwrap_or_default() == device_name) } + pub fn find_site_by_name(&self, site_name: &str) -> Option<&Site> { + self.sites_raw.iter().find(|s| s.name().unwrap_or_default() == site_name) + } + + pub fn find_site_by_id(&self, site_id: &str) -> Option<&Site> { + self.sites_raw.iter().find(|s| s.id == site_id) + } + pub fn find_data_links_featuring_device(&self, device_id: &str) -> Vec<&DataLink> { self. data_links_raw. @@ -133,9 +141,24 @@ impl UispData { } } + // Look in Site-DeviceSite + if !found { + if let Some(device_site) = &device.identification.site { + if let Some(apdev) = self.find_device_by_id(&device_site.id) { + if apdev.get_site_id().unwrap_or_default() != client.id { + parent = Some(("AP", apdev.get_name().unwrap_or_default())); + found = true; + } + } + } + } + // Look for data links with this device if !found { - for link in self.find_data_links_featuring_device(&device.identification.id) { + if client.name.contains("Dunlap") { + println!("{:#?}", self.find_data_links_featuring_device(&device.identification.id)); + } + for link in self.data_links_raw.iter() { // Check the FROM side if let Some(from_device) = &link.from.device { if from_device.identification.id == device.identification.id { @@ -168,7 +191,7 @@ impl UispData { // If we still haven't found anything, let's try data links to the client site as a whole if !found { - for link in self.find_data_links_featuring_site(&client.id) { + for link in self.data_links_raw.iter() { if let Some(from_site) = &link.from.site { if from_site.identification.id == client.id { if let Some(to_device) = &link.to.device { -- knotmirror 0.0.1 From fb3e58b8585b031c3ab78380502f51580411e526 Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Sat, 29 Mar 2025 11:37:48 -0500 Subject: [PATCH 07/42] WIP: Starting to flag edge-cases. --- .../src/strategies/ap_site.rs | 74 ++++++++++++++++++- 1 file changed, 71 insertions(+), 3 deletions(-) diff --git a/src/rust/uisp_integration/src/strategies/ap_site.rs b/src/rust/uisp_integration/src/strategies/ap_site.rs index ff91319e..16674f0d 100644 --- a/src/rust/uisp_integration/src/strategies/ap_site.rs +++ b/src/rust/uisp_integration/src/strategies/ap_site.rs @@ -1,4 +1,4 @@ -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use std::fs::write; use std::path::Path; use std::sync::Arc; @@ -28,6 +28,14 @@ pub async fn build_ap_site_network( ) -> Result<(), UispIntegrationError> { let uisp_data = UispData::fetch_uisp_data(config.clone(), ip_ranges).await?; + // Find trouble-spots! + find_troublesome_sites(&uisp_data) + .map_err(|e|{ + error!("Error finding troublesome sites"); + error!("{e:?}"); + UispIntegrationError::UnknownSiteType + })?; + // Find the clients let ap_mappings = uisp_data.map_clients_to_aps(); @@ -81,7 +89,7 @@ pub async fn build_ap_site_network( id: GraphMapping::Root, children: sites.values().cloned().collect(), }; - println!("{:#?}", root); + //println!("{:#?}", root); let mut shaped_devices = Vec::new(); let net_json = root.walk_children(None, &uisp_data, &mut shaped_devices, &config); @@ -148,7 +156,7 @@ impl Layer { | GraphMapping::GeneratedSiteByName(name) => { children.insert(name.clone(), child.walk_children(Some(&parent_name), uisp_data, shaped_devices, config).into()); } - GraphMapping::ClientById(client_id) => { + GraphMapping::ClientById(_client_id) => { let _ = child.walk_children(Some(&parent_name), uisp_data, shaped_devices, config); } _ => {} @@ -223,4 +231,64 @@ impl Layer { root.insert("children".to_string(), serde_json::to_value(children).unwrap()); root } +} + +fn find_troublesome_sites( + data: &UispData, +) -> anyhow::Result<()> { + find_clients_with_multiple_entry_points(data)?; + find_clients_linked_from_other_clients(data)?; + Ok(()) +} + +fn find_clients_with_multiple_entry_points( + data: &UispData, +) -> anyhow::Result<()> { + for client in data.find_client_sites() { + let mut links_to_client = HashSet::new(); + for link in data.data_links_raw.iter() { + if let (Some(from_site), Some(to_site)) = (&link.from.site, &link.to.site) { + if from_site.identification.id == client.id && to_site.identification.id != client.id { + links_to_client.insert(to_site.identification.id.clone()); + } else if from_site.identification.id != client.id && to_site.identification.id == client.id { + links_to_client.insert(from_site.identification.id.clone()); + } + } + } + if links_to_client.len() > 1 { + warn!( + "Client {} has multiple entry points: {:?}", + client.name, links_to_client + ); + } + } + + Ok(()) +} + +fn find_clients_linked_from_other_clients( + data: &UispData +) -> anyhow::Result<()> { + let all_clients = data.find_client_sites(); + for client in &all_clients { + for link in data.data_links_raw.iter() { + if let (Some(from_site), Some(to_site)) = (&link.from.site, &link.to.site) { + if from_site.identification.id == client.id && to_site.identification.id != client.id + && all_clients.iter().any(|c| c.id == to_site.identification.id) { + warn!( + "Client {} is linked from another client: {}", + client.name, to_site.identification.id + ); + } + if from_site.identification.id != client.id && to_site.identification.id == client.id + && all_clients.iter().any(|c| c.id == from_site.identification.id) { + warn!( + "Client {} is linked to another client: {}", + client.name, from_site.identification.id + ); + } + } + } + } + Ok(()) } \ No newline at end of file -- knotmirror 0.0.1 From d340438dcd8eb7fcaf2c30358f22d506e01a2f10 Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Mon, 31 Mar 2025 09:43:41 -0500 Subject: [PATCH 08/42] WIP: Store the edge-cases and leave them as warnings for now. --- .../src/strategies/ap_site.rs | 31 +++++++++++++------ 1 file changed, 22 insertions(+), 9 deletions(-) diff --git a/src/rust/uisp_integration/src/strategies/ap_site.rs b/src/rust/uisp_integration/src/strategies/ap_site.rs index 16674f0d..419954a1 100644 --- a/src/rust/uisp_integration/src/strategies/ap_site.rs +++ b/src/rust/uisp_integration/src/strategies/ap_site.rs @@ -29,7 +29,7 @@ pub async fn build_ap_site_network( let uisp_data = UispData::fetch_uisp_data(config.clone(), ip_ranges).await?; // Find trouble-spots! - find_troublesome_sites(&uisp_data) + let trouble = find_troublesome_sites(&uisp_data) .map_err(|e|{ error!("Error finding troublesome sites"); error!("{e:?}"); @@ -233,17 +233,26 @@ impl Layer { } } +struct TroublesomeClients { + multi_entry_points: HashSet, + client_of_clients: HashSet, +} + fn find_troublesome_sites( data: &UispData, -) -> anyhow::Result<()> { - find_clients_with_multiple_entry_points(data)?; - find_clients_linked_from_other_clients(data)?; - Ok(()) +) -> anyhow::Result { + let multi_entry_points = find_clients_with_multiple_entry_points(data)?; + let client_of_clients = find_clients_linked_from_other_clients(data)?; + Ok(TroublesomeClients { + multi_entry_points, + client_of_clients, + }) } fn find_clients_with_multiple_entry_points( data: &UispData, -) -> anyhow::Result<()> { +) -> anyhow::Result> { + let mut result = HashSet::new(); for client in data.find_client_sites() { let mut links_to_client = HashSet::new(); for link in data.data_links_raw.iter() { @@ -260,16 +269,18 @@ fn find_clients_with_multiple_entry_points( "Client {} has multiple entry points: {:?}", client.name, links_to_client ); + result.insert(client.id.clone()); } } - Ok(()) + Ok(result) } fn find_clients_linked_from_other_clients( data: &UispData -) -> anyhow::Result<()> { +) -> anyhow::Result> { let all_clients = data.find_client_sites(); + let mut result = HashSet::new(); for client in &all_clients { for link in data.data_links_raw.iter() { if let (Some(from_site), Some(to_site)) = (&link.from.site, &link.to.site) { @@ -279,6 +290,7 @@ fn find_clients_linked_from_other_clients( "Client {} is linked from another client: {}", client.name, to_site.identification.id ); + result.insert(client.id.clone()); } if from_site.identification.id != client.id && to_site.identification.id == client.id && all_clients.iter().any(|c| c.id == from_site.identification.id) { @@ -286,9 +298,10 @@ fn find_clients_linked_from_other_clients( "Client {} is linked to another client: {}", client.name, from_site.identification.id ); + result.insert(client.id.clone()); } } } } - Ok(()) + Ok(result) } \ No newline at end of file -- knotmirror 0.0.1 From c4d7d821663c1fff7080cd978e5eedca104577f3 Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Mon, 31 Mar 2025 10:52:33 -0500 Subject: [PATCH 09/42] Fix: no "children" node at the top --- src/rust/uisp_integration/src/strategies/ap_site.rs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/rust/uisp_integration/src/strategies/ap_site.rs b/src/rust/uisp_integration/src/strategies/ap_site.rs index 419954a1..93a20172 100644 --- a/src/rust/uisp_integration/src/strategies/ap_site.rs +++ b/src/rust/uisp_integration/src/strategies/ap_site.rs @@ -29,7 +29,7 @@ pub async fn build_ap_site_network( let uisp_data = UispData::fetch_uisp_data(config.clone(), ip_ranges).await?; // Find trouble-spots! - let trouble = find_troublesome_sites(&uisp_data) + let _trouble = find_troublesome_sites(&uisp_data) .map_err(|e|{ error!("Error finding troublesome sites"); error!("{e:?}"); @@ -228,7 +228,13 @@ impl Layer { _ => {} } } - root.insert("children".to_string(), serde_json::to_value(children).unwrap()); + if parent.is_some() { + root.insert("children".to_string(), serde_json::to_value(children).unwrap()); + } else { + for child in children { + root.insert(child.0, child.1); + } + } root } } -- knotmirror 0.0.1 From b395317e1c93718e309ec825c68c48cfe20d92b4 Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Mon, 31 Mar 2025 14:34:14 -0500 Subject: [PATCH 10/42] WIP: Decently connected graph for full2 --- src/rust/Cargo.lock | 17 ++ src/rust/uisp_integration/Cargo.toml | 1 + .../src/strategies/ap_site.rs | 112 +++++----- .../uisp_integration/src/strategies/full2.rs | 194 ++++++++++++++++++ .../uisp_integration/src/strategies/mod.rs | 6 + 5 files changed, 280 insertions(+), 50 deletions(-) create mode 100644 src/rust/uisp_integration/src/strategies/full2.rs diff --git a/src/rust/Cargo.lock b/src/rust/Cargo.lock index 8197b3cd..a4f75c8f 100644 --- a/src/rust/Cargo.lock +++ b/src/rust/Cargo.lock @@ -1054,6 +1054,12 @@ dependencies = [ "windows-sys 0.59.0", ] +[[package]] +name = "fixedbitset" +version = "0.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d674e81391d1e1ab681a28d99df07927c6d4aa5b027d7da16ba32d1d21ecd99" + [[package]] name = "flate2" version = "1.1.0" @@ -2577,6 +2583,16 @@ version = "2.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3148f5046208a5d56bcfc03053e3ca6334e51da8dfb19b6cdc8b306fae3283e" +[[package]] +name = "petgraph" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3672b37090dbd86368a4145bc067582552b29c27377cad4e0a306c97f9bd7772" +dependencies = [ + "fixedbitset", + "indexmap", +] + [[package]] name = "pin-project" version = "1.1.10" @@ -4023,6 +4039,7 @@ dependencies = [ "ip_network_table", "lqos_bus", "lqos_config", + "petgraph", "serde", "serde_cbor", "serde_json", diff --git a/src/rust/uisp_integration/Cargo.toml b/src/rust/uisp_integration/Cargo.toml index 2378356a..69f91697 100644 --- a/src/rust/uisp_integration/Cargo.toml +++ b/src/rust/uisp_integration/Cargo.toml @@ -20,3 +20,4 @@ ip_network_table = { workspace = true } ip_network = { workspace = true } serde_cbor = { workspace = true } lqos_bus = { path = "../lqos_bus" } +petgraph = "0.7.1" diff --git a/src/rust/uisp_integration/src/strategies/ap_site.rs b/src/rust/uisp_integration/src/strategies/ap_site.rs index 93a20172..c7fca8d5 100644 --- a/src/rust/uisp_integration/src/strategies/ap_site.rs +++ b/src/rust/uisp_integration/src/strategies/ap_site.rs @@ -40,51 +40,12 @@ pub async fn build_ap_site_network( let ap_mappings = uisp_data.map_clients_to_aps(); // Make AP Layer entries - let mut access_points = HashMap::new(); - for (ap_name, client_ids) in ap_mappings.iter() { - let mut ap_layer = Layer { - id: GraphMapping::AccessPointByName(ap_name.clone()), - children: Vec::new(), - }; - for client_id in client_ids.iter() { - ap_layer.children.push(Layer { - id: GraphMapping::ClientById(client_id.clone()), - children: Vec::new(), - }); - } - access_points.insert(ap_name.clone(), ap_layer); - } + let access_points = get_ap_layer(&ap_mappings); // Site mappings - let mut sites = HashMap::new(); - for (ap_name, client_ids) in ap_mappings.iter() { - if let Some(device) = uisp_data.find_device_by_name(ap_name) { - if let Some(device_site_id) = device.get_site_id() { - if let Some(device_site) = uisp_data.sites.iter().find(|s| s.id == device_site_id) { - let site_entry = sites.entry(device_site.name.clone()).or_insert_with(|| { - Layer { - id: GraphMapping::SiteByName(device_site.name.clone()), - children: Vec::new(), - } - }); - let ap_map = access_points.get(ap_name).unwrap().clone(); - site_entry.children.push(ap_map); - } - } - } else { - let mut detached = Layer { - id: GraphMapping::SiteByName(ap_name.clone()), - children: vec![], - }; - for client_id in client_ids.iter() { - detached.children.push(Layer { - id: GraphMapping::ClientById(client_id.clone()), - children: vec![], - }); - } - sites.insert(ap_name.clone(), detached); - } - } + let sites = map_sites_above_aps(&uisp_data, ap_mappings, access_points); + + // Insert the root let mut root = Layer { id: GraphMapping::Root, children: sites.values().cloned().collect(), @@ -128,10 +89,61 @@ pub async fn build_ap_site_network( Ok(()) } +pub(crate) fn map_sites_above_aps(uisp_data: &UispData, ap_mappings: HashMap>, access_points: HashMap) -> HashMap { + let mut sites = HashMap::new(); + for (ap_name, client_ids) in ap_mappings.iter() { + if let Some(device) = uisp_data.find_device_by_name(ap_name) { + if let Some(device_site_id) = device.get_site_id() { + if let Some(device_site) = uisp_data.sites.iter().find(|s| s.id == device_site_id) { + let site_entry = sites.entry(device_site.name.clone()).or_insert_with(|| { + Layer { + id: GraphMapping::SiteByName(device_site.name.clone()), + children: Vec::new(), + } + }); + let ap_map = access_points.get(ap_name).unwrap().clone(); + site_entry.children.push(ap_map); + } + } + } else { + let mut detached = Layer { + id: GraphMapping::SiteByName(ap_name.clone()), + children: vec![], + }; + for client_id in client_ids.iter() { + detached.children.push(Layer { + id: GraphMapping::ClientById(client_id.clone()), + children: vec![], + }); + } + sites.insert(ap_name.clone(), detached); + } + } + sites +} + +pub(crate) fn get_ap_layer(ap_mappings: &HashMap>) -> HashMap { + let mut access_points = HashMap::new(); + for (ap_name, client_ids) in ap_mappings.iter() { + let mut ap_layer = Layer { + id: GraphMapping::AccessPointByName(ap_name.clone()), + children: Vec::new(), + }; + for client_id in client_ids.iter() { + ap_layer.children.push(Layer { + id: GraphMapping::ClientById(client_id.clone()), + children: Vec::new(), + }); + } + access_points.insert(ap_name.clone(), ap_layer); + } + access_points +} + #[derive(Debug, Clone)] -struct Layer { - id: GraphMapping, - children: Vec, +pub(crate) struct Layer { + pub(crate) id: GraphMapping, + pub(crate) children: Vec, } impl Layer { @@ -239,12 +251,12 @@ impl Layer { } } -struct TroublesomeClients { - multi_entry_points: HashSet, - client_of_clients: HashSet, +pub struct TroublesomeClients { + pub multi_entry_points: HashSet, + pub client_of_clients: HashSet, } -fn find_troublesome_sites( +pub(crate) fn find_troublesome_sites( data: &UispData, ) -> anyhow::Result { let multi_entry_points = find_clients_with_multiple_entry_points(data)?; diff --git a/src/rust/uisp_integration/src/strategies/full2.rs b/src/rust/uisp_integration/src/strategies/full2.rs new file mode 100644 index 00000000..af8a488c --- /dev/null +++ b/src/rust/uisp_integration/src/strategies/full2.rs @@ -0,0 +1,194 @@ +use std::sync::Arc; +use petgraph::data::Build; +use tracing::{error, warn}; +use lqos_config::Config; +use uisp::{DataLinkSite, Site}; +use crate::errors::UispIntegrationError; +use crate::ip_ranges::IpRanges; +use crate::strategies::ap_site::GraphMapping; +use crate::strategies::common::UispData; +use crate::uisp_types::UispSiteType; + +pub async fn build_full_network_v2( + config: Arc, + ip_ranges: IpRanges, +) -> Result<(), UispIntegrationError> { + // Fetch the data + let uisp_data = UispData::fetch_uisp_data(config.clone(), ip_ranges).await?; + + // Report on obvious UISP errors that should be fixed + let _trouble = crate::strategies::ap_site::find_troublesome_sites(&uisp_data) + .map_err(|e|{ + error!("Error finding troublesome sites"); + error!("{e:?}"); + UispIntegrationError::UnknownSiteType + })?; + + // Find the clients + let ap_mappings = uisp_data.map_clients_to_aps(); + + // Make AP Layer entries + let access_points = crate::strategies::ap_site::get_ap_layer(&ap_mappings); + + // Site mappings + let sites = crate::strategies::ap_site::map_sites_above_aps(&uisp_data, ap_mappings, access_points); + + // Insert the root + let mut root = crate::strategies::ap_site::Layer { + id: GraphMapping::Root, + children: sites.values().cloned().collect(), + }; + + // Now transform this into a Petgraph graph + let mut graph = petgraph::Graph::::new(); + root.walk_to_pet_graph(&mut graph, None); + + // Then add other sites + for site in uisp_data.sites_raw.iter() { + // Skip clients + if site.is_client_site() { + continue; + } + // Find the node index of an entry in the graph if there is one + let mut node_index = graph + .node_indices() + .find(|i| graph[*i] == GraphMapping::SiteByName(site.name_or_blank())); + + // If it already exists, then we're interested in finding links between it and other sites + if let Some(node_index) = node_index { + // Do nothing + } else { + // If it doesn't exist, then we need to add it + graph.add_node(GraphMapping::SiteByName(site.name_or_blank())); + } + } + + // Now iterate all the links! + for link in uisp_data.data_links_raw.iter() { + if let Some(from_site) = &link.from.site { + if let Some(to_site) = &link.to.site { + add_link_if_new(from_site, to_site, &mut graph, &uisp_data.sites_raw); + } + } + } + + // Find the root + let root_site_name = config.uisp_integration.site.clone(); + let Some(root_idx) = graph.node_indices().find(|n| { + if let GraphMapping::SiteByName(name) = &graph[*n] { + *name == root_site_name + } else { + false + } + }) else { + error!("Unable to locate the root note, {}", root_site_name); + return Err(UispIntegrationError::NoRootSite); + }; + + // Working up to adding the shaper to the detected (named) root + let mut orphans = None; + for node in graph.node_indices() { + if node == root_idx { + continue; + } + let a_star_run = petgraph::algo::astar(&graph, root_idx, |n| n == node, |e| 1, |_| 0); + + let all_paths = petgraph::algo::all_simple_paths::, _>(&graph, node, root_idx, 0, None) + .collect::>(); + + if a_star_run.is_none() { + warn!("No path is detected from {:?} to {}", graph[node], root_site_name); + if orphans.is_none() { + orphans = Some(graph.add_node(GraphMapping::GeneratedSiteByName("Orphans".to_string()))); + graph.add_edge(node, root_idx, ()); + } + if let Some(orphans) = orphans { + graph.add_edge(node, orphans, ()); + } + } else { + //println!("Path detected from {:?} to {}", graph[node], root_site_name); + if all_paths.len() > 1 { + println!("Multiple paths detected from {:?} to {}", graph[node], root_site_name); + } + } + } + + // Do topology tracing to find downstream routes and flag alternatives + + // Save the dot file + //println!("{:?}", petgraph::dot::Dot::with_config(&graph, &[petgraph::dot::Config::EdgeNoLabel])); + + Ok(()) +} + +fn add_link_if_new( + from_site: &DataLinkSite, + to_site: &DataLinkSite, + graph: &mut petgraph::Graph, + sites_raw: &[Site], +) { + if from_site.identification.id == to_site.identification.id { + // If the sites are the same, we don't need to add an edge + return; + } + let Some(site_a) = sites_raw.iter().find(|s| s.id == from_site.identification.id) else { + return; + }; + if site_a.is_client_site() { + return; + } + let Some(node_a) = graph.node_indices().find(|n| graph[*n] == GraphMapping::SiteByName(site_a.name_or_blank())) else { + return; + }; + let Some(site_b) = sites_raw.iter().find(|s| s.id == to_site.identification.id) else { + return; + }; + if site_b.is_client_site() { + return; + } + let Some(node_b) = graph.node_indices().find(|n| graph[*n] == GraphMapping::SiteByName(site_b.name_or_blank())) else { + return; + }; + + + if graph.contains_edge(node_a, node_b) { + // If the edge already exists, we don't need to add it + return; + } + if graph.contains_edge(node_b, node_a) { + // If the edge already exists in the opposite direction, we don't need to add it + return; + } + + // Add the edge + //println!("Adding edge from {:?} to {:?}", graph[node_a], graph[node_b]); + graph.add_edge(node_a, node_b, ()); +} + +impl crate::strategies::ap_site::Layer { + fn walk_to_pet_graph( + &self, + graph: &mut petgraph::Graph, + parent: Option, + ) { + // Add the current node + if let GraphMapping::ClientById(..) = self.id { + // If this is a client, we don't want to add it to the graph + return; + } + let node_index = if let GraphMapping::Root = self.id { + None + } else { + let node_index = graph.add_node(self.id.clone()); + if let Some(parent_index) = parent { + graph.add_edge(parent_index, node_index, ()); + } + Some(node_index) + }; + + // Recursively walk to children + for child in &self.children { + child.walk_to_pet_graph(graph, node_index); + } + } +} \ No newline at end of file diff --git a/src/rust/uisp_integration/src/strategies/mod.rs b/src/rust/uisp_integration/src/strategies/mod.rs index e89f40ab..d1efb669 100644 --- a/src/rust/uisp_integration/src/strategies/mod.rs +++ b/src/rust/uisp_integration/src/strategies/mod.rs @@ -3,6 +3,7 @@ mod full; mod ap_only; mod ap_site; mod common; +mod full2; use crate::blackboard; use crate::errors::UispIntegrationError; @@ -45,6 +46,11 @@ pub async fn build_with_strategy( ap_site::build_ap_site_network(config, ip_ranges).await?; Ok(()) } + "full2" => { + info!("Strategy selected: full2"); + full2::build_full_network_v2(config, ip_ranges).await?; + Ok(()) + } _ => { error!( "Unknown strategy: {}. Bailing.", -- knotmirror 0.0.1 From 8c7671abce7869e35c3179ca1c5deeaccde85b91 Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Mon, 31 Mar 2025 16:02:18 -0500 Subject: [PATCH 11/42] WIP: full2 is mostly connected now --- .../src/strategies/ap_site.rs | 32 ++- .../uisp_integration/src/strategies/full2.rs | 203 ++++++++++++++---- 2 files changed, 193 insertions(+), 42 deletions(-) diff --git a/src/rust/uisp_integration/src/strategies/ap_site.rs b/src/rust/uisp_integration/src/strategies/ap_site.rs index c7fca8d5..5cfc6862 100644 --- a/src/rust/uisp_integration/src/strategies/ap_site.rs +++ b/src/rust/uisp_integration/src/strategies/ap_site.rs @@ -19,6 +19,18 @@ pub enum GraphMapping { ClientById(String), } +impl GraphMapping { + pub(crate) fn name(&self) -> String { + match self { + GraphMapping::SiteByName(name) => name.clone(), + GraphMapping::AccessPointByName(name) => name.clone(), + GraphMapping::GeneratedSiteByName(name) => name.clone(), + GraphMapping::ClientById(client_id) => client_id.clone(), + _ => "".to_string() + } + } +} + /// Creates a network with APs detected from clients, /// and then a single site above them (shared if the site /// matches). @@ -70,6 +82,13 @@ pub async fn build_ap_site_network( })?; info!("Written network.json"); + let _ = write_shaped_devices(&config, &mut shaped_devices); + info!("Wrote {} lines to ShapedDevices.csv", shaped_devices.len()); + + Ok(()) +} + +pub(crate) fn write_shaped_devices(config: &Arc, shaped_devices: &mut Vec) -> Result<(), UispIntegrationError> { let file_path = Path::new(&config.lqos_directory).join("ShapedDevices.csv"); let mut writer = csv::WriterBuilder::new() .has_headers(true) @@ -85,7 +104,6 @@ pub async fn build_ap_site_network( UispIntegrationError::CsvError })?; info!("Wrote {} lines to ShapedDevices.csv", shaped_devices.len()); - Ok(()) } @@ -147,7 +165,17 @@ pub(crate) struct Layer { } impl Layer { - fn walk_children( + pub fn name(&self) -> String { + match &self.id { + GraphMapping::SiteByName(name) => name.clone(), + GraphMapping::AccessPointByName(name) => name.clone(), + GraphMapping::GeneratedSiteByName(name) => name.clone(), + GraphMapping::ClientById(client_id) => client_id.clone(), + _ => "".to_string() + } + } + + pub(crate) fn walk_children( &self, parent: Option<&str>, uisp_data: &UispData, diff --git a/src/rust/uisp_integration/src/strategies/full2.rs b/src/rust/uisp_integration/src/strategies/full2.rs index af8a488c..fca1c809 100644 --- a/src/rust/uisp_integration/src/strategies/full2.rs +++ b/src/rust/uisp_integration/src/strategies/full2.rs @@ -1,13 +1,20 @@ -use std::sync::Arc; -use petgraph::data::Build; -use tracing::{error, warn}; -use lqos_config::Config; -use uisp::{DataLinkSite, Site}; +use std::collections::HashMap; use crate::errors::UispIntegrationError; use crate::ip_ranges::IpRanges; use crate::strategies::ap_site::GraphMapping; use crate::strategies::common::UispData; -use crate::uisp_types::UispSiteType; +use crate::uisp_types::{UispDevice, UispSiteType}; +use lqos_config::Config; +use petgraph::data::Build; +use std::sync::Arc; +use tracing::{error, info, warn}; +use uisp::{DataLinkDevice, DataLinkSite, Device, Site}; + +#[derive(Debug, Clone)] +pub enum LinkMapping { + Ethernet, + DevicePair(String, String), +} pub async fn build_full_network_v2( config: Arc, @@ -17,12 +24,11 @@ pub async fn build_full_network_v2( let uisp_data = UispData::fetch_uisp_data(config.clone(), ip_ranges).await?; // Report on obvious UISP errors that should be fixed - let _trouble = crate::strategies::ap_site::find_troublesome_sites(&uisp_data) - .map_err(|e|{ - error!("Error finding troublesome sites"); - error!("{e:?}"); - UispIntegrationError::UnknownSiteType - })?; + let _trouble = crate::strategies::ap_site::find_troublesome_sites(&uisp_data).map_err(|e| { + error!("Error finding troublesome sites"); + error!("{e:?}"); + UispIntegrationError::UnknownSiteType + })?; // Find the clients let ap_mappings = uisp_data.map_clients_to_aps(); @@ -31,7 +37,8 @@ pub async fn build_full_network_v2( let access_points = crate::strategies::ap_site::get_ap_layer(&ap_mappings); // Site mappings - let sites = crate::strategies::ap_site::map_sites_above_aps(&uisp_data, ap_mappings, access_points); + let sites = + crate::strategies::ap_site::map_sites_above_aps(&uisp_data, ap_mappings, access_points); // Insert the root let mut root = crate::strategies::ap_site::Layer { @@ -40,8 +47,8 @@ pub async fn build_full_network_v2( }; // Now transform this into a Petgraph graph - let mut graph = petgraph::Graph::::new(); - root.walk_to_pet_graph(&mut graph, None); + let mut graph = petgraph::Graph::::new(); + root.walk_site_ap_to_pet_graph(&mut graph, None); // Then add other sites for site in uisp_data.sites_raw.iter() { @@ -55,7 +62,7 @@ pub async fn build_full_network_v2( .find(|i| graph[*i] == GraphMapping::SiteByName(site.name_or_blank())); // If it already exists, then we're interested in finding links between it and other sites - if let Some(node_index) = node_index { + if let Some(_node_index) = node_index { // Do nothing } else { // If it doesn't exist, then we need to add it @@ -67,11 +74,20 @@ pub async fn build_full_network_v2( for link in uisp_data.data_links_raw.iter() { if let Some(from_site) = &link.from.site { if let Some(to_site) = &link.to.site { - add_link_if_new(from_site, to_site, &mut graph, &uisp_data.sites_raw); + add_link_if_new( + from_site, + to_site, + &link.from.device, + &link.to.device, + &mut graph, + &uisp_data.sites_raw, + ); } } } + + // Find the root let root_site_name = config.uisp_integration.site.clone(); let Some(root_idx) = graph.node_indices().find(|n| { @@ -91,53 +107,146 @@ pub async fn build_full_network_v2( if node == root_idx { continue; } - let a_star_run = petgraph::algo::astar(&graph, root_idx, |n| n == node, |e| 1, |_| 0); - - let all_paths = petgraph::algo::all_simple_paths::, _>(&graph, node, root_idx, 0, None) - .collect::>(); + let a_star_run = petgraph::algo::astar( + &graph, + root_idx, + |n| n == node, + |e| (10_000u64).saturating_sub(link_capacity_mbps(&e.weight(), &uisp_data.devices)), + |_| 0, + ); if a_star_run.is_none() { - warn!("No path is detected from {:?} to {}", graph[node], root_site_name); + warn!( + "No path is detected from {:?} to {}", + graph[node], root_site_name + ); if orphans.is_none() { - orphans = Some(graph.add_node(GraphMapping::GeneratedSiteByName("Orphans".to_string()))); - graph.add_edge(node, root_idx, ()); + orphans = + Some(graph.add_node(GraphMapping::GeneratedSiteByName("Orphans".to_string()))); + graph.add_edge(root_idx, orphans.unwrap(), LinkMapping::Ethernet); } if let Some(orphans) = orphans { - graph.add_edge(node, orphans, ()); + graph.add_edge(node, orphans, LinkMapping::Ethernet); } } else { + let all_paths = + petgraph::algo::all_simple_paths::, _>(&graph, node, root_idx, 0, None) + .collect::>(); + //println!("Path detected from {:?} to {}", graph[node], root_site_name); if all_paths.len() > 1 { - println!("Multiple paths detected from {:?} to {}", graph[node], root_site_name); + println!( + "Multiple paths detected from {:?} to {}", + graph[node], root_site_name + ); } } } - // Do topology tracing to find downstream routes and flag alternatives - // Save the dot file - //println!("{:?}", petgraph::dot::Dot::with_config(&graph, &[petgraph::dot::Config::EdgeNoLabel])); + let dot_data = format!("{:?}", petgraph::dot::Dot::with_config(&graph, &[petgraph::dot::Config::EdgeNoLabel])); + let _ = std::fs::write("graph.dot", dot_data.as_bytes()); + let _ = std::process::Command::new("dot") + .arg("-Tpng") + .arg("graph.dot") + .arg("-o") + .arg("graph.png") + .output(); + + // Build the output data + let mut shaped_devices = Vec::new(); + let _ = root.walk_children(None, &uisp_data, &mut shaped_devices, &config); + + // Write SD + let _ = crate::strategies::ap_site::write_shaped_devices(&config, &mut shaped_devices); + info!("Wrote {} lines to ShapedDevices.csv", shaped_devices.len()); + + // Figure out the network.json layers + let mut parents = HashMap::new(); + for node in graph.node_indices() { + if node == root_idx { + continue; + } + match &graph[node] { + GraphMapping::GeneratedSiteByName(name) | GraphMapping::SiteByName(name) | + GraphMapping::AccessPointByName(name) => { + let route = petgraph::algo::astar( + &graph, + root_idx, + |n| n == node, + |e| (10_000u64).saturating_sub(link_capacity_mbps(&e.weight(), &uisp_data.devices)), + |_| 0, + ).unwrap_or((0, vec![])); + + if route.1.is_empty() { + //println!("No path detected from {:?} to {}", graph[node], root_site_name); + parents.insert(name, ("Orphans".to_owned(), (config.queues.generated_pn_download_mbps, config.queues.generated_pn_upload_mbps)); + } else { + let parent = graph[route.1[route.1.len() - 2]].name(); + parents.insert(name, (parent, network_json_capacity(&config))); + } + + //let parent_index = route.1.iter().last().unwrap(); + //let parent = graph[*parent_index].clone(); + //println!("Parent of {:?} is {:?}", graph[node], parent); + } + _ => {} + } + } + println!("Parents: {:#?}", parents); Ok(()) } +fn network_json_capacity( + config: &Arc +) -> (u64, u64) { + (config.queues.generated_pn_download_mbps, config.queues.generated_pn_upload_mbps) +} + +fn link_capacity_mbps(link_mapping: &LinkMapping, devices: &[UispDevice]) -> u64 { + match link_mapping { + LinkMapping::Ethernet => 10_000, + LinkMapping::DevicePair(device_a, device_b) => { + let mut capacity = 0; + if let Some(device_a) = devices.iter().find(|d| d.id == *device_a) { + capacity = device_a.download; + } else if let Some(device_b) = devices.iter().find(|d| d.id == *device_b) { + capacity = device_b.download; + } else { + capacity = 10_000; + } + + capacity + } + } +} + fn add_link_if_new( from_site: &DataLinkSite, to_site: &DataLinkSite, - graph: &mut petgraph::Graph, + from_device: &Option, + to_device: &Option, + graph: &mut petgraph::Graph, sites_raw: &[Site], ) { if from_site.identification.id == to_site.identification.id { // If the sites are the same, we don't need to add an edge return; } - let Some(site_a) = sites_raw.iter().find(|s| s.id == from_site.identification.id) else { + let Some(site_a) = sites_raw + .iter() + .find(|s| s.id == from_site.identification.id) + else { return; }; if site_a.is_client_site() { return; } - let Some(node_a) = graph.node_indices().find(|n| graph[*n] == GraphMapping::SiteByName(site_a.name_or_blank())) else { + let Some(node_a) = graph + .node_indices() + .find(|n| graph[*n] == GraphMapping::SiteByName(site_a.name_or_blank())) + else { return; }; let Some(site_b) = sites_raw.iter().find(|s| s.id == to_site.identification.id) else { @@ -146,11 +255,13 @@ fn add_link_if_new( if site_b.is_client_site() { return; } - let Some(node_b) = graph.node_indices().find(|n| graph[*n] == GraphMapping::SiteByName(site_b.name_or_blank())) else { + let Some(node_b) = graph + .node_indices() + .find(|n| graph[*n] == GraphMapping::SiteByName(site_b.name_or_blank())) + else { return; }; - if graph.contains_edge(node_a, node_b) { // If the edge already exists, we don't need to add it return; @@ -160,15 +271,27 @@ fn add_link_if_new( return; } + // Try to figure out the type of link + let mut link_type = LinkMapping::Ethernet; + + if let Some(device_a) = &from_device { + if let Some(device_b) = &to_device { + link_type = LinkMapping::DevicePair( + device_a.identification.id.clone(), + device_b.identification.id.clone(), + ); + } + } + // Add the edge //println!("Adding edge from {:?} to {:?}", graph[node_a], graph[node_b]); - graph.add_edge(node_a, node_b, ()); + graph.add_edge(node_a, node_b, link_type); } impl crate::strategies::ap_site::Layer { - fn walk_to_pet_graph( + fn walk_site_ap_to_pet_graph( &self, - graph: &mut petgraph::Graph, + graph: &mut petgraph::Graph, parent: Option, ) { // Add the current node @@ -181,14 +304,14 @@ impl crate::strategies::ap_site::Layer { } else { let node_index = graph.add_node(self.id.clone()); if let Some(parent_index) = parent { - graph.add_edge(parent_index, node_index, ()); + graph.add_edge(parent_index, node_index, LinkMapping::Ethernet); } Some(node_index) }; // Recursively walk to children for child in &self.children { - child.walk_to_pet_graph(graph, node_index); + child.walk_site_ap_to_pet_graph(graph, node_index); } } -} \ No newline at end of file +} -- knotmirror 0.0.1 From 930c8ae65600b155537d714fb3a460de771a2efa Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Tue, 1 Apr 2025 10:18:44 -0500 Subject: [PATCH 12/42] WIP: Checkpoint while I work on a different branch. --- .../uisp_integration/src/strategies/full2.rs | 143 +++++++++++++++++- 1 file changed, 137 insertions(+), 6 deletions(-) diff --git a/src/rust/uisp_integration/src/strategies/full2.rs b/src/rust/uisp_integration/src/strategies/full2.rs index fca1c809..29d2a39e 100644 --- a/src/rust/uisp_integration/src/strategies/full2.rs +++ b/src/rust/uisp_integration/src/strategies/full2.rs @@ -86,7 +86,44 @@ pub async fn build_full_network_v2( } } - + // Now we make a heroic effort to find sites that are linked through UISP's semi-broken + // API! + for graph_node in graph.node_indices() { + let name = graph[graph_node].name(); + if let Some(site_info) = uisp_data.find_site_by_name(&name) { + let site_id = &site_info.id; + for device in uisp_data.devices_raw.iter() { + if let Some(site) = &device.identification.site { + if site.id == *site_id { + if let Some(attr) = &device.attributes { + if let Some(ap) = &attr.apDevice { + if let Some(ap_device_id) = &ap.id { + if let Some(ap_device) = uisp_data.devices_raw.iter().find(|d| d.get_id() == *ap_device_id) { + if ap_device.get_site_id().unwrap_or_default() != *site_id { + // After all this nesting, we have found a link + if let Some(other_site) = uisp_data.sites_raw.iter().find(|s| s.id == ap_device.get_site_id().unwrap_or_default()) { + if !other_site.is_client_site() { + // Add the link + //println!("Adding link from {} to {}", name, other_site.name_or_blank()); + add_link_if_new_from_ap_check( + &site_info, + other_site, + device, + ap_device, + &mut graph, + ) + } + } + } + } + } + } + } + } + } + } + } + } // Find the root let root_site_name = config.uisp_integration.site.clone(); @@ -180,10 +217,20 @@ pub async fn build_full_network_v2( if route.1.is_empty() { //println!("No path detected from {:?} to {}", graph[node], root_site_name); - parents.insert(name, ("Orphans".to_owned(), (config.queues.generated_pn_download_mbps, config.queues.generated_pn_upload_mbps)); + parents.insert(name, ("Orphans".to_owned(), (config.queues.generated_pn_download_mbps, config.queues.generated_pn_upload_mbps))); } else { - let parent = graph[route.1[route.1.len() - 2]].name(); - parents.insert(name, (parent, network_json_capacity(&config))); + let parent_node = route.1[route.1.len() - 2]; + // We need the weight from node to parent_node in the graph edges + if let Some(edge) = graph.find_edge(parent_node, node) { + // From EdgeIndex to LinkMapping + let edge = graph[edge].clone(); + //println!("FOUND THE EDGE: {:?}", edge); + + let parent = graph[route.1[route.1.len() - 2]].name(); + parents.insert(name, (parent, network_json_capacity(&config, &edge, &uisp_data.devices))); + } else { + panic!("DID NOT FIND THE EDGE"); + } } //let parent_index = route.1.iter().last().unwrap(); @@ -193,14 +240,52 @@ pub async fn build_full_network_v2( _ => {} } } - println!("Parents: {:#?}", parents); + //println!("Parents: {:#?}", parents); + + // Write the network.json file + let mut network_json = serde_json::Map::new(); + for (name, (parent, (download, upload))) in parents.iter().filter(|(_, (parent, _))| *parent == root_site_name) { + network_json.insert(name.clone().into(), walk_parents().into()); + } Ok(()) } +fn walk_parents() -> serde_json::Map { + +} + fn network_json_capacity( - config: &Arc + config: &Arc, + link: &LinkMapping, + devices: &[UispDevice], ) -> (u64, u64) { + // Handle ignoring capacity + if config.uisp_integration.ignore_calculated_capacity { + return (config.queues.generated_pn_download_mbps, config.queues.generated_pn_upload_mbps); + } + + // Handle the link type + match link { + LinkMapping::Ethernet => { + return (config.queues.generated_pn_download_mbps, config.queues.generated_pn_upload_mbps); + } + LinkMapping::DevicePair(device_a, device_b) => { + // Find the devices + let device_a = devices.iter().find(|d| d.id == *device_a); + let device_b = devices.iter().find(|d| d.id == *device_b); + + if let Some(device_a) = device_a { + if let Some(device_b) = device_b { + return ( + device_a.download, + device_b.upload, + ); + } + } + } + } + (config.queues.generated_pn_download_mbps, config.queues.generated_pn_upload_mbps) } @@ -222,6 +307,52 @@ fn link_capacity_mbps(link_mapping: &LinkMapping, devices: &[UispDevice]) -> u64 } } +fn add_link_if_new_from_ap_check( + site_a: &Site, + site_b: &Site, + device_a: &Device, + device_b: &Device, + graph: &mut petgraph::Graph, +) { + if site_a.id == site_b.id { + // If the sites are the same, we don't need to add an edge + return; + } + let Some(node_a) = graph + .node_indices() + .find(|n| graph[*n] == GraphMapping::SiteByName(site_a.name_or_blank())) + else { + return; + }; + let Some(node_b) = graph + .node_indices() + .find(|n| graph[*n] == GraphMapping::SiteByName(site_b.name_or_blank())) + else { + return; + }; + + if graph.contains_edge(node_a, node_b) { + // If the edge already exists, we don't need to add it + return; + } + if graph.contains_edge(node_b, node_a) { + // If the edge already exists in the opposite direction, we don't need to add it + return; + } + + // Try to figure out the type of link + let mut link_type = LinkMapping::Ethernet; + + link_type = LinkMapping::DevicePair( + device_a.identification.id.clone(), + device_b.identification.id.clone(), + ); + + // Add the edge + println!("(AP Scan) Adding edge from {:?} to {:?}", graph[node_a], graph[node_b]); + graph.add_edge(node_a, node_b, link_type); +} + fn add_link_if_new( from_site: &DataLinkSite, to_site: &DataLinkSite, -- knotmirror 0.0.1 From 875be581b9ab544f5e0169740da7273fc4af741c Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Wed, 2 Apr 2025 13:07:52 -0500 Subject: [PATCH 13/42] The network.json is written for full2. (Limits aren't all detected yet) --- .../uisp_integration/src/strategies/full2.rs | 42 ++++++++++++++++++- 1 file changed, 40 insertions(+), 2 deletions(-) diff --git a/src/rust/uisp_integration/src/strategies/full2.rs b/src/rust/uisp_integration/src/strategies/full2.rs index 29d2a39e..322dc805 100644 --- a/src/rust/uisp_integration/src/strategies/full2.rs +++ b/src/rust/uisp_integration/src/strategies/full2.rs @@ -1,4 +1,6 @@ use std::collections::HashMap; +use std::fs::write; +use std::path::Path; use crate::errors::UispIntegrationError; use crate::ip_ranges::IpRanges; use crate::strategies::ap_site::GraphMapping; @@ -245,14 +247,50 @@ pub async fn build_full_network_v2( // Write the network.json file let mut network_json = serde_json::Map::new(); for (name, (parent, (download, upload))) in parents.iter().filter(|(_, (parent, _))| *parent == root_site_name) { - network_json.insert(name.clone().into(), walk_parents().into()); + network_json.insert(name.clone().into(), walk_parents(&parents, name, &config, *download, *upload).into()); } + let network_path = Path::new(&config.lqos_directory).join("network.json"); + if network_path.exists() && !config.integration_common.always_overwrite_network_json { + warn!( + "Network.json exists, and always overwrite network json is not true - not writing network.json" + ); + return Ok(()); + } + let json = serde_json::to_string_pretty(&network_json).unwrap(); + write(network_path, json).map_err(|e| { + error!("Unable to write network.json"); + error!("{e:?}"); + UispIntegrationError::WriteNetJson + })?; + info!("Written network.json"); Ok(()) } -fn walk_parents() -> serde_json::Map { +fn walk_parents( + parents: &HashMap<&String, (String, (u64, u64))>, + name: &String, + config: &Arc, + download: u64, + upload: u64, +) -> serde_json::Map { + let mut map = serde_json::Map::new(); + + // Entries are name, type, uisp_device or site, downloadBandwidthMbps, uploadBandwidthMbps, children + map.insert("name".into(), name.clone().into()); + map.insert("downloadBandwidthMbps".into(), download.into()); + map.insert("uploadBandwidthMbps".into(), upload.into()); + + let mut children = serde_json::Map::new(); + for (name, (parent, (download, upload))) in parents.iter().filter(|(_, (parent, _))| + *parent == *name) { + let child = walk_parents(parents, name, config, *download, *upload); + children.insert(name.clone().into(), child.into()); + } + + map.insert("children".into(), children.into()); + map } fn network_json_capacity( -- knotmirror 0.0.1 From 7752f2aaef27a9d471d091bc9b62c5ba0f577f5e Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Wed, 2 Apr 2025 16:33:38 -0500 Subject: [PATCH 14/42] It makes network json files... --- .../uisp_integration/src/strategies/common.rs | 3 - .../uisp_integration/src/strategies/full2.rs | 361 +++++++++++------- 2 files changed, 232 insertions(+), 132 deletions(-) diff --git a/src/rust/uisp_integration/src/strategies/common.rs b/src/rust/uisp_integration/src/strategies/common.rs index e1157942..843ac37d 100644 --- a/src/rust/uisp_integration/src/strategies/common.rs +++ b/src/rust/uisp_integration/src/strategies/common.rs @@ -155,9 +155,6 @@ impl UispData { // Look for data links with this device if !found { - if client.name.contains("Dunlap") { - println!("{:#?}", self.find_data_links_featuring_device(&device.identification.id)); - } for link in self.data_links_raw.iter() { // Check the FROM side if let Some(from_device) = &link.from.device { diff --git a/src/rust/uisp_integration/src/strategies/full2.rs b/src/rust/uisp_integration/src/strategies/full2.rs index 322dc805..6810f9dc 100644 --- a/src/rust/uisp_integration/src/strategies/full2.rs +++ b/src/rust/uisp_integration/src/strategies/full2.rs @@ -1,9 +1,8 @@ -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use std::fs::write; use std::path::Path; use crate::errors::UispIntegrationError; use crate::ip_ranges::IpRanges; -use crate::strategies::ap_site::GraphMapping; use crate::strategies::common::UispData; use crate::uisp_types::{UispDevice, UispSiteType}; use lqos_config::Config; @@ -11,6 +10,27 @@ use petgraph::data::Build; use std::sync::Arc; use tracing::{error, info, warn}; use uisp::{DataLinkDevice, DataLinkSite, Device, Site}; +use petgraph::visit::EdgeRef; +use crate::strategies::ap_site::Layer; + +#[derive(Debug, Ord, PartialOrd, Eq, PartialEq, Clone)] +pub enum GraphMapping { + Root { name: String, id: String }, + Site { name: String, id: String }, + GeneratedSite { name: String }, + AccessPoint { name: String, id: String }, +} + +impl GraphMapping { + pub fn name(&self) -> String { + match self { + GraphMapping::Root { name, .. } => name.clone(), + GraphMapping::Site { name, .. } => name.clone(), + GraphMapping::GeneratedSite { name } => name.clone(), + GraphMapping::AccessPoint { name, .. } => name.clone(), + } + } +} #[derive(Debug, Clone)] pub enum LinkMapping { @@ -18,6 +38,8 @@ pub enum LinkMapping { DevicePair(String, String), } +type GraphType = petgraph::Graph; + pub async fn build_full_network_v2( config: Arc, ip_ranges: IpRanges, @@ -32,106 +54,39 @@ pub async fn build_full_network_v2( UispIntegrationError::UnknownSiteType })?; - // Find the clients - let ap_mappings = uisp_data.map_clients_to_aps(); - - // Make AP Layer entries - let access_points = crate::strategies::ap_site::get_ap_layer(&ap_mappings); - - // Site mappings - let sites = - crate::strategies::ap_site::map_sites_above_aps(&uisp_data, ap_mappings, access_points); - - // Insert the root - let mut root = crate::strategies::ap_site::Layer { - id: GraphMapping::Root, - children: sites.values().cloned().collect(), - }; + // Create a new graph + let mut graph = GraphType::new(); - // Now transform this into a Petgraph graph - let mut graph = petgraph::Graph::::new(); - root.walk_site_ap_to_pet_graph(&mut graph, None); + // Find the root + let root_site_name = config.uisp_integration.site.clone(); - // Then add other sites - for site in uisp_data.sites_raw.iter() { - // Skip clients - if site.is_client_site() { + // Add all sites to the graph + let mut site_map = HashMap::new(); + for site in uisp_data.sites_raw.iter().filter(|s| !s.is_client_site()) { + let site_name = site.name_or_blank(); + let id = site.id.clone(); + if site_name == root_site_name { + // Add the root site + let root_entry = GraphMapping::Root { + name: site_name, + id, + }; + let root_ref = graph.add_node(root_entry); + site_map.insert(site.id.clone(), root_ref); continue; } - // Find the node index of an entry in the graph if there is one - let mut node_index = graph - .node_indices() - .find(|i| graph[*i] == GraphMapping::SiteByName(site.name_or_blank())); - - // If it already exists, then we're interested in finding links between it and other sites - if let Some(_node_index) = node_index { - // Do nothing - } else { - // If it doesn't exist, then we need to add it - graph.add_node(GraphMapping::SiteByName(site.name_or_blank())); - } - } - - // Now iterate all the links! - for link in uisp_data.data_links_raw.iter() { - if let Some(from_site) = &link.from.site { - if let Some(to_site) = &link.to.site { - add_link_if_new( - from_site, - to_site, - &link.from.device, - &link.to.device, - &mut graph, - &uisp_data.sites_raw, - ); - } - } - } - - // Now we make a heroic effort to find sites that are linked through UISP's semi-broken - // API! - for graph_node in graph.node_indices() { - let name = graph[graph_node].name(); - if let Some(site_info) = uisp_data.find_site_by_name(&name) { - let site_id = &site_info.id; - for device in uisp_data.devices_raw.iter() { - if let Some(site) = &device.identification.site { - if site.id == *site_id { - if let Some(attr) = &device.attributes { - if let Some(ap) = &attr.apDevice { - if let Some(ap_device_id) = &ap.id { - if let Some(ap_device) = uisp_data.devices_raw.iter().find(|d| d.get_id() == *ap_device_id) { - if ap_device.get_site_id().unwrap_or_default() != *site_id { - // After all this nesting, we have found a link - if let Some(other_site) = uisp_data.sites_raw.iter().find(|s| s.id == ap_device.get_site_id().unwrap_or_default()) { - if !other_site.is_client_site() { - // Add the link - //println!("Adding link from {} to {}", name, other_site.name_or_blank()); - add_link_if_new_from_ap_check( - &site_info, - other_site, - device, - ap_device, - &mut graph, - ) - } - } - } - } - } - } - } - } - } - } - } + let site_entry = GraphMapping::Site { + name: site_name, + id, + }; + let site_ref = graph.add_node(site_entry); + site_map.insert(site.id.clone(), site_ref); } - // Find the root - let root_site_name = config.uisp_integration.site.clone(); + // Locate the root site in the graph let Some(root_idx) = graph.node_indices().find(|n| { - if let GraphMapping::SiteByName(name) = &graph[*n] { - *name == root_site_name + if let GraphMapping::Root{name: _, id: _} = &graph[*n] { + true } else { false } @@ -140,16 +95,65 @@ pub async fn build_full_network_v2( return Err(UispIntegrationError::NoRootSite); }; - // Working up to adding the shaper to the detected (named) root - let mut orphans = None; - for node in graph.node_indices() { - if node == root_idx { + // Iterate all UISP devices and if their parent site is in the graph, add them + let mut device_map = HashMap::new(); + for device in uisp_data.devices_raw.iter() { + let Some(site_id) = &device.identification.site else { + continue; + }; + let site_id = &site_id.id; + let Some(site_ref) = site_map.get(site_id) else { + continue; + }; + let device_entry = GraphMapping::AccessPoint { + name: device.get_name().unwrap_or_default(), + id: device.identification.id.clone(), + }; + let device_ref = graph.add_node(device_entry); + device_map.insert(device.identification.id.clone(), device_ref); + graph.add_edge(*site_ref, device_ref, LinkMapping::Ethernet); + } + + // Now we iterate all the data links looking for DEVICE linkage + for link in uisp_data.data_links_raw.iter() { + let Some(from_device) = &link.from.device else { + continue; + }; + let Some(to_device) = &link.to.device else { + continue; + }; + let Some(a_ref) = device_map.get(&from_device.identification.id) else {; + continue; + }; + let Some(b_ref) = device_map.get(&to_device.identification.id) else { + continue; + }; + if a_ref == b_ref { + // If the devices are the same, we don't need to add an edge + continue; + } + if graph.contains_edge(*a_ref, *b_ref) { + // If the edge already exists, we don't need to add it + continue; + } + if graph.contains_edge(*b_ref, *a_ref) { + // If the edge already exists in the opposite direction, we don't need to add it + continue; + } + graph.add_edge(*a_ref, *b_ref, LinkMapping::DevicePair(from_device.identification.id.clone(), to_device.identification.id.clone())); + } + + // Now we iterate only sites, looking for connectivity to the root + let orphans = graph.add_node(GraphMapping::GeneratedSite{ name: "Orphans".to_string()}); + graph.add_edge(root_idx, orphans, LinkMapping::Ethernet); + for (_, site_ref) in site_map.iter() { + if *site_ref == root_idx { continue; } let a_star_run = petgraph::algo::astar( &graph, root_idx, - |n| n == node, + |n| n == *site_ref, |e| (10_000u64).saturating_sub(link_capacity_mbps(&e.weight(), &uisp_data.devices)), |_| 0, ); @@ -157,41 +161,124 @@ pub async fn build_full_network_v2( if a_star_run.is_none() { warn!( "No path is detected from {:?} to {}", - graph[node], root_site_name + graph[*site_ref], root_site_name ); - if orphans.is_none() { - orphans = - Some(graph.add_node(GraphMapping::GeneratedSiteByName("Orphans".to_string()))); - graph.add_edge(root_idx, orphans.unwrap(), LinkMapping::Ethernet); - } - if let Some(orphans) = orphans { - graph.add_edge(node, orphans, LinkMapping::Ethernet); + graph.add_edge(*site_ref, orphans, LinkMapping::Ethernet); + } + } + + // Client mapping + let client_mappings = uisp_data.map_clients_to_aps(); + + // Find the APs that have clients + let mut aps_with_clients = HashSet::new(); + for (ap_name, _client_ids) in client_mappings.iter() { + let Some(ap_device) = uisp_data.devices_raw.iter().find(|d| d.get_name().unwrap_or_default() == *ap_name) else { + // Orphaning is already handled + continue; + }; + aps_with_clients.insert(ap_device.identification.id.clone()); + } + + // Count linkages to APs + let mut ap_link_count = HashMap::::new(); + for edge_ref in graph.edge_references() { + if let GraphMapping::AccessPoint{ref name, ref id} = graph[edge_ref.source()] { + let entry = ap_link_count.entry(id.clone()).or_insert(0); + *entry += 1; + }; + if let GraphMapping::AccessPoint{ref name, ref id} = graph[edge_ref.target()] { + let entry = ap_link_count.entry(id.clone()).or_insert(0); + *entry += 1; + }; + } + + // Cull the APs that have no clients or only one link + let mut to_remove = Vec::new(); + for (ap_id, ap_ref) in device_map.iter() { + if aps_with_clients.contains(ap_id) { + continue; + } + if let Some(link_count) = ap_link_count.get(ap_id) { + if *link_count > 1 { + continue; } - } else { - let all_paths = - petgraph::algo::all_simple_paths::, _>(&graph, node, root_idx, 0, None) - .collect::>(); - - //println!("Path detected from {:?} to {}", graph[node], root_site_name); - if all_paths.len() > 1 { - println!( - "Multiple paths detected from {:?} to {}", - graph[node], root_site_name - ); + } + to_remove.push(*ap_ref); + } + info!("Removing {} APs with no clients or only one link", to_remove.len()); + for ap_ref in to_remove.iter() { + graph.remove_node(*ap_ref); + } + + // Visualizer + save_dot_file(&graph)?; + + // Figure out the network.json layers + let mut parents = HashMap::new(); + for node in graph.node_indices() { + if node == root_idx { + continue; + } + match &graph[node] { + GraphMapping::GeneratedSite{name} | GraphMapping::Site{name, ..} | + GraphMapping::AccessPoint{name, ..} => { + let route = petgraph::algo::astar( + &graph, + root_idx, + |n| n == node, + |e| (10_000u64).saturating_sub(link_capacity_mbps(&e.weight(), &uisp_data.devices)), + |_| 0, + ).unwrap_or((0, vec![])); + + if route.1.is_empty() { + //println!("No path detected from {:?} to {}", graph[node], root_site_name); + parents.insert(name, ("Orphans".to_owned(), (config.queues.generated_pn_download_mbps, config.queues.generated_pn_upload_mbps))); + } else { + let parent_node = route.1[route.1.len() - 2]; + // We need the weight from node to parent_node in the graph edges + if let Some(edge) = graph.find_edge(parent_node, node) { + // From EdgeIndex to LinkMapping + let edge = graph[edge].clone(); + //println!("FOUND THE EDGE: {:?}", edge); + + let parent = graph[route.1[route.1.len() - 2]].name(); + parents.insert(name, (parent, network_json_capacity(&config, &edge, &uisp_data.devices))); + } else { + panic!("DID NOT FIND THE EDGE"); + } + } + + //let parent_index = route.1.iter().last().unwrap(); + //let parent = graph[*parent_index].clone(); + //println!("Parent of {:?} is {:?}", graph[node], parent); } + _ => {} } } + //println!("Parents: {:#?}", parents); - // Save the dot file - let dot_data = format!("{:?}", petgraph::dot::Dot::with_config(&graph, &[petgraph::dot::Config::EdgeNoLabel])); - let _ = std::fs::write("graph.dot", dot_data.as_bytes()); - let _ = std::process::Command::new("dot") - .arg("-Tpng") - .arg("graph.dot") - .arg("-o") - .arg("graph.png") - .output(); + // Write the network.json file + let mut network_json = serde_json::Map::new(); + for (name, (parent, (download, upload))) in parents.iter().filter(|(_, (parent, _))| *parent == root_site_name) { + network_json.insert(name.clone().into(), walk_parents(&parents, name, &config, *download, *upload).into()); + } + let network_path = Path::new(&config.lqos_directory).join("network.json"); + if network_path.exists() && !config.integration_common.always_overwrite_network_json { + warn!( + "Network.json exists, and always overwrite network json is not true - not writing network.json" + ); + return Ok(()); + } + let json = serde_json::to_string_pretty(&network_json).unwrap(); + write(network_path, json).map_err(|e| { + error!("Unable to write network.json"); + error!("{e:?}"); + UispIntegrationError::WriteNetJson + })?; + info!("Written network.json"); + /* // Build the output data let mut shaped_devices = Vec::new(); let _ = root.walk_children(None, &uisp_data, &mut shaped_devices, &config); @@ -262,11 +349,24 @@ pub async fn build_full_network_v2( error!("{e:?}"); UispIntegrationError::WriteNetJson })?; - info!("Written network.json"); + info!("Written network.json");*/ Ok(()) } +fn save_dot_file(graph: &GraphType) -> Result<(), UispIntegrationError> { + // Save the dot file + let dot_data = format!("{:?}", petgraph::dot::Dot::with_config(graph, &[petgraph::dot::Config::EdgeNoLabel])); + let _ = std::fs::write("graph.dot", dot_data.as_bytes()); + let _ = std::process::Command::new("dot") + .arg("-Tpng") + .arg("graph.dot") + .arg("-o") + .arg("graph.png") + .output(); + Ok(()) +} + fn walk_parents( parents: &HashMap<&String, (String, (u64, u64))>, name: &String, @@ -327,6 +427,7 @@ fn network_json_capacity( (config.queues.generated_pn_download_mbps, config.queues.generated_pn_upload_mbps) } + fn link_capacity_mbps(link_mapping: &LinkMapping, devices: &[UispDevice]) -> u64 { match link_mapping { LinkMapping::Ethernet => 10_000, @@ -345,6 +446,7 @@ fn link_capacity_mbps(link_mapping: &LinkMapping, devices: &[UispDevice]) -> u64 } } +/* fn add_link_if_new_from_ap_check( site_a: &Site, site_b: &Site, @@ -484,3 +586,4 @@ impl crate::strategies::ap_site::Layer { } } } +*/ \ No newline at end of file -- knotmirror 0.0.1 From b5fdb4c0a31497be94877eb7fa36ede37f0bcab1 Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Wed, 2 Apr 2025 16:46:14 -0500 Subject: [PATCH 15/42] Try this one --- src/rust/uisp_integration/src/strategies/full2.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/rust/uisp_integration/src/strategies/full2.rs b/src/rust/uisp_integration/src/strategies/full2.rs index 6810f9dc..69e6c59a 100644 --- a/src/rust/uisp_integration/src/strategies/full2.rs +++ b/src/rust/uisp_integration/src/strategies/full2.rs @@ -207,9 +207,9 @@ pub async fn build_full_network_v2( to_remove.push(*ap_ref); } info!("Removing {} APs with no clients or only one link", to_remove.len()); - for ap_ref in to_remove.iter() { + /*for ap_ref in to_remove.iter() { graph.remove_node(*ap_ref); - } + }*/ // Visualizer save_dot_file(&graph)?; -- knotmirror 0.0.1 From 698d7a5a802e495001cd239d54313cc09573d6a5 Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Thu, 3 Apr 2025 13:28:07 -0500 Subject: [PATCH 16/42] Bidirectional graph mode made a lot of things work better! --- src/rust/uisp/src/lib.rs | 2 +- .../uisp_integration/src/strategies/full2.rs | 49 +++++++++---------- 2 files changed, 25 insertions(+), 26 deletions(-) diff --git a/src/rust/uisp/src/lib.rs b/src/rust/uisp/src/lib.rs index 8b1b0cf7..d9e993b5 100644 --- a/src/rust/uisp/src/lib.rs +++ b/src/rust/uisp/src/lib.rs @@ -42,7 +42,7 @@ pub async fn load_all_sites(config: Arc) -> Result> { /// Load all devices from UISP that are authorized, and include their full interface definitions pub async fn load_all_devices_with_interfaces(config: Arc) -> Result> { Ok(nms_request_get_vec( - "devices?withInterfaces=true&authorized=true", + "devices?withInterfaces=true", &config.uisp_integration.token, &config.uisp_integration.url, ) diff --git a/src/rust/uisp_integration/src/strategies/full2.rs b/src/rust/uisp_integration/src/strategies/full2.rs index 69e6c59a..233d5d7a 100644 --- a/src/rust/uisp_integration/src/strategies/full2.rs +++ b/src/rust/uisp_integration/src/strategies/full2.rs @@ -8,9 +8,10 @@ use crate::uisp_types::{UispDevice, UispSiteType}; use lqos_config::Config; use petgraph::data::Build; use std::sync::Arc; +use petgraph::Undirected; use tracing::{error, info, warn}; use uisp::{DataLinkDevice, DataLinkSite, Device, Site}; -use petgraph::visit::EdgeRef; +use petgraph::visit::{EdgeRef, NodeRef}; use crate::strategies::ap_site::Layer; #[derive(Debug, Ord, PartialOrd, Eq, PartialEq, Clone)] @@ -38,7 +39,7 @@ pub enum LinkMapping { DevicePair(String, String), } -type GraphType = petgraph::Graph; +type GraphType = petgraph::Graph; pub async fn build_full_network_v2( config: Arc, @@ -55,13 +56,14 @@ pub async fn build_full_network_v2( })?; // Create a new graph - let mut graph = GraphType::new(); + let mut graph = GraphType::new_undirected(); // Find the root let root_site_name = config.uisp_integration.site.clone(); // Add all sites to the graph let mut site_map = HashMap::new(); + let mut root_idx = None; for site in uisp_data.sites_raw.iter().filter(|s| !s.is_client_site()) { let site_name = site.name_or_blank(); let id = site.id.clone(); @@ -72,6 +74,7 @@ pub async fn build_full_network_v2( id, }; let root_ref = graph.add_node(root_entry); + root_idx = Some(root_ref); site_map.insert(site.id.clone(), root_ref); continue; } @@ -82,18 +85,7 @@ pub async fn build_full_network_v2( let site_ref = graph.add_node(site_entry); site_map.insert(site.id.clone(), site_ref); } - - // Locate the root site in the graph - let Some(root_idx) = graph.node_indices().find(|n| { - if let GraphMapping::Root{name: _, id: _} = &graph[*n] { - true - } else { - false - } - }) else { - error!("Unable to locate the root note, {}", root_site_name); - return Err(UispIntegrationError::NoRootSite); - }; + let root_idx = root_idx.expect("Root site not found"); // Iterate all UISP devices and if their parent site is in the graph, add them let mut device_map = HashMap::new(); @@ -111,7 +103,7 @@ pub async fn build_full_network_v2( }; let device_ref = graph.add_node(device_entry); device_map.insert(device.identification.id.clone(), device_ref); - graph.add_edge(*site_ref, device_ref, LinkMapping::Ethernet); + let _ = graph.add_edge(device_ref, *site_ref, LinkMapping::Ethernet); } // Now we iterate all the data links looking for DEVICE linkage @@ -132,29 +124,36 @@ pub async fn build_full_network_v2( // If the devices are the same, we don't need to add an edge continue; } + if let Some(dev_a) = uisp_data.devices_raw.iter().find(|d| d.get_id() == from_device.identification.id) { + if let Some(dev_b) = uisp_data.devices_raw.iter().find(|d| d.get_id() == to_device.identification.id) { + if dev_a.get_site_id().unwrap_or_default() == dev_b.get_site_id().unwrap_or_default() { + // If the devices are in the same site, we don't need to add an edge + continue; + } + } + } if graph.contains_edge(*a_ref, *b_ref) { // If the edge already exists, we don't need to add it continue; } - if graph.contains_edge(*b_ref, *a_ref) { - // If the edge already exists in the opposite direction, we don't need to add it - continue; - } graph.add_edge(*a_ref, *b_ref, LinkMapping::DevicePair(from_device.identification.id.clone(), to_device.identification.id.clone())); } // Now we iterate only sites, looking for connectivity to the root let orphans = graph.add_node(GraphMapping::GeneratedSite{ name: "Orphans".to_string()}); graph.add_edge(root_idx, orphans, LinkMapping::Ethernet); + for (_, site_ref) in site_map.iter() { if *site_ref == root_idx { continue; } let a_star_run = petgraph::algo::astar( &graph, - root_idx, - |n| n == *site_ref, - |e| (10_000u64).saturating_sub(link_capacity_mbps(&e.weight(), &uisp_data.devices)), + *site_ref, + |n| { + n.id() == root_idx.id() + }, + |e| 0, |_| 0, ); @@ -207,9 +206,9 @@ pub async fn build_full_network_v2( to_remove.push(*ap_ref); } info!("Removing {} APs with no clients or only one link", to_remove.len()); - /*for ap_ref in to_remove.iter() { + for ap_ref in to_remove.iter() { graph.remove_node(*ap_ref); - }*/ + } // Visualizer save_dot_file(&graph)?; -- knotmirror 0.0.1 From 237b760ed71e126d1c2e1ef49d6522d2638b18e8 Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Thu, 3 Apr 2025 15:13:18 -0500 Subject: [PATCH 17/42] Cleanup --- .../uisp_integration/src/strategies/full2.rs | 238 +----------------- 1 file changed, 11 insertions(+), 227 deletions(-) diff --git a/src/rust/uisp_integration/src/strategies/full2.rs b/src/rust/uisp_integration/src/strategies/full2.rs index 233d5d7a..bef53a54 100644 --- a/src/rust/uisp_integration/src/strategies/full2.rs +++ b/src/rust/uisp_integration/src/strategies/full2.rs @@ -4,15 +4,12 @@ use std::path::Path; use crate::errors::UispIntegrationError; use crate::ip_ranges::IpRanges; use crate::strategies::common::UispData; -use crate::uisp_types::{UispDevice, UispSiteType}; +use crate::uisp_types::UispDevice; use lqos_config::Config; -use petgraph::data::Build; use std::sync::Arc; use petgraph::Undirected; use tracing::{error, info, warn}; -use uisp::{DataLinkDevice, DataLinkSite, Device, Site}; use petgraph::visit::{EdgeRef, NodeRef}; -use crate::strategies::ap_site::Layer; #[derive(Debug, Ord, PartialOrd, Eq, PartialEq, Clone)] pub enum GraphMapping { @@ -114,7 +111,7 @@ pub async fn build_full_network_v2( let Some(to_device) = &link.to.device else { continue; }; - let Some(a_ref) = device_map.get(&from_device.identification.id) else {; + let Some(a_ref) = device_map.get(&from_device.identification.id) else { continue; }; let Some(b_ref) = device_map.get(&to_device.identification.id) else { @@ -153,7 +150,7 @@ pub async fn build_full_network_v2( |n| { n.id() == root_idx.id() }, - |e| 0, + |_| 0, |_| 0, ); @@ -182,11 +179,11 @@ pub async fn build_full_network_v2( // Count linkages to APs let mut ap_link_count = HashMap::::new(); for edge_ref in graph.edge_references() { - if let GraphMapping::AccessPoint{ref name, ref id} = graph[edge_ref.source()] { + if let GraphMapping::AccessPoint{ref id, ..} = graph[edge_ref.source()] { let entry = ap_link_count.entry(id.clone()).or_insert(0); *entry += 1; }; - if let GraphMapping::AccessPoint{ref name, ref id} = graph[edge_ref.target()] { + if let GraphMapping::AccessPoint{ref id, ..} = graph[edge_ref.target()] { let entry = ap_link_count.entry(id.clone()).or_insert(0); *entry += 1; }; @@ -259,8 +256,8 @@ pub async fn build_full_network_v2( // Write the network.json file let mut network_json = serde_json::Map::new(); - for (name, (parent, (download, upload))) in parents.iter().filter(|(_, (parent, _))| *parent == root_site_name) { - network_json.insert(name.clone().into(), walk_parents(&parents, name, &config, *download, *upload).into()); + for (name, (_parent, (download, upload))) in parents.iter().filter(|(_, (parent, _))| *parent == root_site_name) { + network_json.insert((*name).into(), walk_parents(&parents, name, &config, *download, *upload).into()); } let network_path = Path::new(&config.lqos_directory).join("network.json"); if network_path.exists() && !config.integration_common.always_overwrite_network_json { @@ -277,78 +274,7 @@ pub async fn build_full_network_v2( })?; info!("Written network.json"); - /* - // Build the output data - let mut shaped_devices = Vec::new(); - let _ = root.walk_children(None, &uisp_data, &mut shaped_devices, &config); - - // Write SD - let _ = crate::strategies::ap_site::write_shaped_devices(&config, &mut shaped_devices); - info!("Wrote {} lines to ShapedDevices.csv", shaped_devices.len()); - - // Figure out the network.json layers - let mut parents = HashMap::new(); - for node in graph.node_indices() { - if node == root_idx { - continue; - } - match &graph[node] { - GraphMapping::GeneratedSiteByName(name) | GraphMapping::SiteByName(name) | - GraphMapping::AccessPointByName(name) => { - let route = petgraph::algo::astar( - &graph, - root_idx, - |n| n == node, - |e| (10_000u64).saturating_sub(link_capacity_mbps(&e.weight(), &uisp_data.devices)), - |_| 0, - ).unwrap_or((0, vec![])); - - if route.1.is_empty() { - //println!("No path detected from {:?} to {}", graph[node], root_site_name); - parents.insert(name, ("Orphans".to_owned(), (config.queues.generated_pn_download_mbps, config.queues.generated_pn_upload_mbps))); - } else { - let parent_node = route.1[route.1.len() - 2]; - // We need the weight from node to parent_node in the graph edges - if let Some(edge) = graph.find_edge(parent_node, node) { - // From EdgeIndex to LinkMapping - let edge = graph[edge].clone(); - //println!("FOUND THE EDGE: {:?}", edge); - - let parent = graph[route.1[route.1.len() - 2]].name(); - parents.insert(name, (parent, network_json_capacity(&config, &edge, &uisp_data.devices))); - } else { - panic!("DID NOT FIND THE EDGE"); - } - } - - //let parent_index = route.1.iter().last().unwrap(); - //let parent = graph[*parent_index].clone(); - //println!("Parent of {:?} is {:?}", graph[node], parent); - } - _ => {} - } - } - //println!("Parents: {:#?}", parents); - - // Write the network.json file - let mut network_json = serde_json::Map::new(); - for (name, (parent, (download, upload))) in parents.iter().filter(|(_, (parent, _))| *parent == root_site_name) { - network_json.insert(name.clone().into(), walk_parents(&parents, name, &config, *download, *upload).into()); - } - let network_path = Path::new(&config.lqos_directory).join("network.json"); - if network_path.exists() && !config.integration_common.always_overwrite_network_json { - warn!( - "Network.json exists, and always overwrite network json is not true - not writing network.json" - ); - return Ok(()); - } - let json = serde_json::to_string_pretty(&network_json).unwrap(); - write(network_path, json).map_err(|e| { - error!("Unable to write network.json"); - error!("{e:?}"); - UispIntegrationError::WriteNetJson - })?; - info!("Written network.json");*/ + // TODO: ShapedDevices Ok(()) } @@ -381,10 +307,10 @@ fn walk_parents( map.insert("uploadBandwidthMbps".into(), upload.into()); let mut children = serde_json::Map::new(); - for (name, (parent, (download, upload))) in parents.iter().filter(|(_, (parent, _))| + for (name, (_parent, (download, upload))) in parents.iter().filter(|(_, (parent, _))| *parent == *name) { let child = walk_parents(parents, name, config, *download, *upload); - children.insert(name.clone().into(), child.into()); + children.insert((*name).into(), child.into()); } map.insert("children".into(), children.into()); @@ -431,7 +357,7 @@ fn link_capacity_mbps(link_mapping: &LinkMapping, devices: &[UispDevice]) -> u64 match link_mapping { LinkMapping::Ethernet => 10_000, LinkMapping::DevicePair(device_a, device_b) => { - let mut capacity = 0; + let capacity ; if let Some(device_a) = devices.iter().find(|d| d.id == *device_a) { capacity = device_a.download; } else if let Some(device_b) = devices.iter().find(|d| d.id == *device_b) { @@ -444,145 +370,3 @@ fn link_capacity_mbps(link_mapping: &LinkMapping, devices: &[UispDevice]) -> u64 } } } - -/* -fn add_link_if_new_from_ap_check( - site_a: &Site, - site_b: &Site, - device_a: &Device, - device_b: &Device, - graph: &mut petgraph::Graph, -) { - if site_a.id == site_b.id { - // If the sites are the same, we don't need to add an edge - return; - } - let Some(node_a) = graph - .node_indices() - .find(|n| graph[*n] == GraphMapping::SiteByName(site_a.name_or_blank())) - else { - return; - }; - let Some(node_b) = graph - .node_indices() - .find(|n| graph[*n] == GraphMapping::SiteByName(site_b.name_or_blank())) - else { - return; - }; - - if graph.contains_edge(node_a, node_b) { - // If the edge already exists, we don't need to add it - return; - } - if graph.contains_edge(node_b, node_a) { - // If the edge already exists in the opposite direction, we don't need to add it - return; - } - - // Try to figure out the type of link - let mut link_type = LinkMapping::Ethernet; - - link_type = LinkMapping::DevicePair( - device_a.identification.id.clone(), - device_b.identification.id.clone(), - ); - - // Add the edge - println!("(AP Scan) Adding edge from {:?} to {:?}", graph[node_a], graph[node_b]); - graph.add_edge(node_a, node_b, link_type); -} - -fn add_link_if_new( - from_site: &DataLinkSite, - to_site: &DataLinkSite, - from_device: &Option, - to_device: &Option, - graph: &mut petgraph::Graph, - sites_raw: &[Site], -) { - if from_site.identification.id == to_site.identification.id { - // If the sites are the same, we don't need to add an edge - return; - } - let Some(site_a) = sites_raw - .iter() - .find(|s| s.id == from_site.identification.id) - else { - return; - }; - if site_a.is_client_site() { - return; - } - let Some(node_a) = graph - .node_indices() - .find(|n| graph[*n] == GraphMapping::SiteByName(site_a.name_or_blank())) - else { - return; - }; - let Some(site_b) = sites_raw.iter().find(|s| s.id == to_site.identification.id) else { - return; - }; - if site_b.is_client_site() { - return; - } - let Some(node_b) = graph - .node_indices() - .find(|n| graph[*n] == GraphMapping::SiteByName(site_b.name_or_blank())) - else { - return; - }; - - if graph.contains_edge(node_a, node_b) { - // If the edge already exists, we don't need to add it - return; - } - if graph.contains_edge(node_b, node_a) { - // If the edge already exists in the opposite direction, we don't need to add it - return; - } - - // Try to figure out the type of link - let mut link_type = LinkMapping::Ethernet; - - if let Some(device_a) = &from_device { - if let Some(device_b) = &to_device { - link_type = LinkMapping::DevicePair( - device_a.identification.id.clone(), - device_b.identification.id.clone(), - ); - } - } - - // Add the edge - //println!("Adding edge from {:?} to {:?}", graph[node_a], graph[node_b]); - graph.add_edge(node_a, node_b, link_type); -} - -impl crate::strategies::ap_site::Layer { - fn walk_site_ap_to_pet_graph( - &self, - graph: &mut petgraph::Graph, - parent: Option, - ) { - // Add the current node - if let GraphMapping::ClientById(..) = self.id { - // If this is a client, we don't want to add it to the graph - return; - } - let node_index = if let GraphMapping::Root = self.id { - None - } else { - let node_index = graph.add_node(self.id.clone()); - if let Some(parent_index) = parent { - graph.add_edge(parent_index, node_index, LinkMapping::Ethernet); - } - Some(node_index) - }; - - // Recursively walk to children - for child in &self.children { - child.walk_site_ap_to_pet_graph(graph, node_index); - } - } -} -*/ \ No newline at end of file -- knotmirror 0.0.1 From 535922410749344c901d4d980865a201672b2a38 Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Thu, 3 Apr 2025 15:34:50 -0500 Subject: [PATCH 18/42] full2 now writes ShapedDevices --- .../uisp_integration/src/strategies/full2.rs | 52 ++++++++++++++++++- 1 file changed, 51 insertions(+), 1 deletion(-) diff --git a/src/rust/uisp_integration/src/strategies/full2.rs b/src/rust/uisp_integration/src/strategies/full2.rs index bef53a54..b625dd16 100644 --- a/src/rust/uisp_integration/src/strategies/full2.rs +++ b/src/rust/uisp_integration/src/strategies/full2.rs @@ -10,6 +10,7 @@ use std::sync::Arc; use petgraph::Undirected; use tracing::{error, info, warn}; use petgraph::visit::{EdgeRef, NodeRef}; +use crate::strategies::full::shaped_devices_writer::ShapedDevice; #[derive(Debug, Ord, PartialOrd, Eq, PartialEq, Clone)] pub enum GraphMapping { @@ -274,7 +275,56 @@ pub async fn build_full_network_v2( })?; info!("Written network.json"); - // TODO: ShapedDevices + // Shaped Devices + let mut shaped_devices = Vec::new(); + + println!("{client_mappings:?}"); + for (ap_id, client_sites) in client_mappings.iter() { + for site_id in client_sites.iter() { + let Some(ap_device) = uisp_data.devices.iter().find(|d| d.name == *ap_id) else { + continue; + }; + let Some(site) = uisp_data.sites.iter().find(|s| s.id == *site_id) else { + continue; + }; + for device in uisp_data.devices.iter().filter(|d| d.site_id == *site_id) { + if !device.has_address() { + continue; + } + let shaped_device = ShapedDevice { + circuit_id: site.id.to_owned(), + circuit_name: site.name.to_owned(), + device_id: device.id.to_owned(), + device_name: device.name.to_owned(), + parent_node: ap_device.name.to_owned(), + mac: device.mac.to_owned(), + ipv4: device.ipv4_list(), + ipv6: device.ipv6_list(), + download_min: (config.uisp_integration.commit_bandwidth_multiplier * site.max_down_mbps as f32) as u64, + upload_min: (config.uisp_integration.commit_bandwidth_multiplier * site.max_up_mbps as f32) as u64, + download_max: site.max_down_mbps, + upload_max: site.max_up_mbps, + comment: "".to_string(), + }; + shaped_devices.push(shaped_device); + } + } + } + let file_path = Path::new(&config.lqos_directory).join("ShapedDevices.csv"); + let mut writer = csv::WriterBuilder::new() + .has_headers(true) + .from_path(file_path) + .unwrap(); + + for d in shaped_devices.iter() { + writer.serialize(d).unwrap(); + } + writer.flush().map_err(|e| { + error!("Unable to flush CSV file"); + error!("{e:?}"); + UispIntegrationError::CsvError + })?; + info!("Wrote {} lines to ShapedDevices.csv", shaped_devices.len()); Ok(()) } -- knotmirror 0.0.1 From da54b6826363f879597dc1f928c547f7d5fc0c33 Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Thu, 3 Apr 2025 16:35:30 -0500 Subject: [PATCH 19/42] Full2 now reads override files. --- .../src/strategies/full/mod.rs | 4 +-- .../uisp_integration/src/strategies/full2.rs | 27 ++++++++++++++----- 2 files changed, 23 insertions(+), 8 deletions(-) diff --git a/src/rust/uisp_integration/src/strategies/full/mod.rs b/src/rust/uisp_integration/src/strategies/full/mod.rs index c55b48b2..14ef22d0 100644 --- a/src/rust/uisp_integration/src/strategies/full/mod.rs +++ b/src/rust/uisp_integration/src/strategies/full/mod.rs @@ -1,11 +1,11 @@ mod ap_promotion; -mod bandwidth_overrides; +pub(crate) mod bandwidth_overrides; mod client_site_promotion; pub mod mikrotik; mod network_json; pub(crate) mod parse; mod root_site; -mod routes_override; +pub(crate) mod routes_override; pub mod shaped_devices_writer; mod squash_single_entry_aps; mod tree_walk; diff --git a/src/rust/uisp_integration/src/strategies/full2.rs b/src/rust/uisp_integration/src/strategies/full2.rs index b625dd16..846f5287 100644 --- a/src/rust/uisp_integration/src/strategies/full2.rs +++ b/src/rust/uisp_integration/src/strategies/full2.rs @@ -53,6 +53,10 @@ pub async fn build_full_network_v2( UispIntegrationError::UnknownSiteType })?; + // Load overrides + let bandwidth_overrides = crate::strategies::full::bandwidth_overrides::get_site_bandwidth_overrides(&config)?; + let routing_overrides = crate::strategies::full::routes_override::get_route_overrides(&config)?; + // Create a new graph let mut graph = GraphType::new_undirected(); @@ -232,15 +236,27 @@ pub async fn build_full_network_v2( //println!("No path detected from {:?} to {}", graph[node], root_site_name); parents.insert(name, ("Orphans".to_owned(), (config.queues.generated_pn_download_mbps, config.queues.generated_pn_upload_mbps))); } else { + let mut capacity = (config.queues.generated_pn_download_mbps,config.queues.generated_pn_upload_mbps); + if !config.uisp_integration.ignore_calculated_capacity { + match &graph[node] { + GraphMapping::AccessPoint { name, id } => { + if let Some(device) = uisp_data.devices.iter().find(|d| d.id == *id) { + println!("Device: {} / {}", device.download, device.upload); + capacity = (device.download, device.upload); + if let Some(bw_override) = bandwidth_overrides.get(&device.name) { + capacity = (bw_override.0 as u64, bw_override.1 as u64); + } + } + } + _ => {} + } + } + let parent_node = route.1[route.1.len() - 2]; // We need the weight from node to parent_node in the graph edges if let Some(edge) = graph.find_edge(parent_node, node) { - // From EdgeIndex to LinkMapping - let edge = graph[edge].clone(); - //println!("FOUND THE EDGE: {:?}", edge); - let parent = graph[route.1[route.1.len() - 2]].name(); - parents.insert(name, (parent, network_json_capacity(&config, &edge, &uisp_data.devices))); + parents.insert(name, (parent, capacity)); } else { panic!("DID NOT FIND THE EDGE"); } @@ -278,7 +294,6 @@ pub async fn build_full_network_v2( // Shaped Devices let mut shaped_devices = Vec::new(); - println!("{client_mappings:?}"); for (ap_id, client_sites) in client_mappings.iter() { for site_id in client_sites.iter() { let Some(ap_device) = uisp_data.devices.iter().find(|d| d.name == *ap_id) else { -- knotmirror 0.0.1 From 0835cd9281b8e4ee421e9b4185a1cea0b727fe06 Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Thu, 3 Apr 2025 16:41:34 -0500 Subject: [PATCH 20/42] The calculated graph is included in the submission blob. Route overrides are now applied as "FROM NAME", "TO NAME", "BANDWIDTH" --- src/rust/Cargo.lock | 2 ++ src/rust/uisp_integration/Cargo.toml | 2 +- .../uisp_integration/src/strategies/full2.rs | 25 ++++++++++++++----- 3 files changed, 22 insertions(+), 7 deletions(-) diff --git a/src/rust/Cargo.lock b/src/rust/Cargo.lock index a4f75c8f..365108b7 100644 --- a/src/rust/Cargo.lock +++ b/src/rust/Cargo.lock @@ -2591,6 +2591,8 @@ checksum = "3672b37090dbd86368a4145bc067582552b29c27377cad4e0a306c97f9bd7772" dependencies = [ "fixedbitset", "indexmap", + "serde", + "serde_derive", ] [[package]] diff --git a/src/rust/uisp_integration/Cargo.toml b/src/rust/uisp_integration/Cargo.toml index 69f91697..a9cdd794 100644 --- a/src/rust/uisp_integration/Cargo.toml +++ b/src/rust/uisp_integration/Cargo.toml @@ -20,4 +20,4 @@ ip_network_table = { workspace = true } ip_network = { workspace = true } serde_cbor = { workspace = true } lqos_bus = { path = "../lqos_bus" } -petgraph = "0.7.1" +petgraph = { version = "0.7.1", features = ["serde-1"] } diff --git a/src/rust/uisp_integration/src/strategies/full2.rs b/src/rust/uisp_integration/src/strategies/full2.rs index 846f5287..da2fad22 100644 --- a/src/rust/uisp_integration/src/strategies/full2.rs +++ b/src/rust/uisp_integration/src/strategies/full2.rs @@ -10,9 +10,12 @@ use std::sync::Arc; use petgraph::Undirected; use tracing::{error, info, warn}; use petgraph::visit::{EdgeRef, NodeRef}; +use serde::Serialize; +use crate::blackboard_blob; +use crate::strategies::full::routes_override::RouteOverride; use crate::strategies::full::shaped_devices_writer::ShapedDevice; -#[derive(Debug, Ord, PartialOrd, Eq, PartialEq, Clone)] +#[derive(Debug, Ord, PartialOrd, Eq, PartialEq, Clone, Serialize)] pub enum GraphMapping { Root { name: String, id: String }, Site { name: String, id: String }, @@ -31,7 +34,7 @@ impl GraphMapping { } } -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Serialize)] pub enum LinkMapping { Ethernet, DevicePair(String, String), @@ -214,6 +217,7 @@ pub async fn build_full_network_v2( // Visualizer save_dot_file(&graph)?; + let _ = blackboard_blob("UISP-Graph", &graph).await; // Figure out the network.json layers let mut parents = HashMap::new(); @@ -228,7 +232,7 @@ pub async fn build_full_network_v2( &graph, root_idx, |n| n == node, - |e| (10_000u64).saturating_sub(link_capacity_mbps(&e.weight(), &uisp_data.devices)), + |e| (10_000u64).saturating_sub(link_capacity_mbps(&e.weight(), &uisp_data.devices, &routing_overrides)), |_| 0, ).unwrap_or((0, vec![])); @@ -418,15 +422,24 @@ fn network_json_capacity( } -fn link_capacity_mbps(link_mapping: &LinkMapping, devices: &[UispDevice]) -> u64 { +fn link_capacity_mbps(link_mapping: &LinkMapping, devices: &[UispDevice], route_overrides: &[RouteOverride]) -> u64 { match link_mapping { LinkMapping::Ethernet => 10_000, LinkMapping::DevicePair(device_a, device_b) => { let capacity ; + if let Some(device_a) = devices.iter().find(|d| d.id == *device_a) { - capacity = device_a.download; + if let Some(override_a) = route_overrides.iter().find(|o| o.from_site == device_a.name) { + capacity = override_a.cost as u64; + } else { + capacity = device_a.download; + } } else if let Some(device_b) = devices.iter().find(|d| d.id == *device_b) { - capacity = device_b.download; + if let Some(override_b) = route_overrides.iter().find(|o| o.from_site == device_b.name) { + capacity = override_b.cost as u64; + } else { + capacity = device_b.download; + } } else { capacity = 10_000; } -- knotmirror 0.0.1 From 698500b969579baa5858cfcafa74ec94b066b41a Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Thu, 3 Apr 2025 16:42:43 -0500 Subject: [PATCH 21/42] Include TO side of overrides --- src/rust/uisp_integration/src/strategies/full2.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/rust/uisp_integration/src/strategies/full2.rs b/src/rust/uisp_integration/src/strategies/full2.rs index da2fad22..016cd723 100644 --- a/src/rust/uisp_integration/src/strategies/full2.rs +++ b/src/rust/uisp_integration/src/strategies/full2.rs @@ -429,13 +429,13 @@ fn link_capacity_mbps(link_mapping: &LinkMapping, devices: &[UispDevice], route_ let capacity ; if let Some(device_a) = devices.iter().find(|d| d.id == *device_a) { - if let Some(override_a) = route_overrides.iter().find(|o| o.from_site == device_a.name) { + if let Some(override_a) = route_overrides.iter().find(|o| o.from_site == device_a.name || o.to_site == device_a.name) { capacity = override_a.cost as u64; } else { capacity = device_a.download; } } else if let Some(device_b) = devices.iter().find(|d| d.id == *device_b) { - if let Some(override_b) = route_overrides.iter().find(|o| o.from_site == device_b.name) { + if let Some(override_b) = route_overrides.iter().find(|o| o.from_site == device_b.name || o.to_site == device_b.name) { capacity = override_b.cost as u64; } else { capacity = device_b.download; -- knotmirror 0.0.1 From 674dccd10f7b64cdfe2fe58a0b9c0d600ea8abdb Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Fri, 4 Apr 2025 10:59:54 -0500 Subject: [PATCH 22/42] Full2 and Ap-Site now include sufficient metadata for clustered rendering. --- .../src/strategies/ap_site.rs | 3 + .../uisp_integration/src/strategies/full2.rs | 82 +++++++++++++------ 2 files changed, 61 insertions(+), 24 deletions(-) diff --git a/src/rust/uisp_integration/src/strategies/ap_site.rs b/src/rust/uisp_integration/src/strategies/ap_site.rs index 5cfc6862..6377de26 100644 --- a/src/rust/uisp_integration/src/strategies/ap_site.rs +++ b/src/rust/uisp_integration/src/strategies/ap_site.rs @@ -212,11 +212,13 @@ impl Layer { root.insert("downloadBandwidthMbps".to_owned(), site.max_down_mbps.into()); root.insert("uploadBandwidthMbps".to_owned(), site.max_up_mbps.into()); root.insert("uisp_site".to_string(), site.id.clone().into()); + root.insert("parent_site".to_string(), name.to_string().into()); } } GraphMapping::AccessPointByName(name) => { root.insert("type".to_string(), "AP".into()); root.insert("name".to_string(), name.clone().into()); + root.insert("parent_site".to_string(), parent.to_string().into()); if let Some(device) = uisp_data.devices.iter().find(|d| d.name == *name) { root.insert("downloadBandwidthMbps".to_owned(), device.download.into()); root.insert("uploadBandwidthMbps".to_owned(), device.upload.into()); @@ -226,6 +228,7 @@ impl Layer { GraphMapping::GeneratedSiteByName(name) => { root.insert("type".to_string(), "AP".into()); root.insert("name".to_string(), name.clone().into()); + root.insert("parent_site".to_string(), name.to_string().into()); if let Some(device) = uisp_data.devices.iter().find(|d| d.name == *name) { root.insert("downloadBandwidthMbps".to_owned(), device.download.into()); root.insert("uploadBandwidthMbps".to_owned(), device.upload.into()); diff --git a/src/rust/uisp_integration/src/strategies/full2.rs b/src/rust/uisp_integration/src/strategies/full2.rs index 016cd723..2d877f69 100644 --- a/src/rust/uisp_integration/src/strategies/full2.rs +++ b/src/rust/uisp_integration/src/strategies/full2.rs @@ -20,7 +20,7 @@ pub enum GraphMapping { Root { name: String, id: String }, Site { name: String, id: String }, GeneratedSite { name: String }, - AccessPoint { name: String, id: String }, + AccessPoint { name: String, id: String, site_name: String }, } impl GraphMapping { @@ -105,6 +105,7 @@ pub async fn build_full_network_v2( let device_entry = GraphMapping::AccessPoint { name: device.get_name().unwrap_or_default(), id: device.identification.id.clone(), + site_name: graph[*site_ref].name(), }; let device_ref = graph.add_node(device_entry); device_map.insert(device.identification.id.clone(), device_ref); @@ -220,7 +221,7 @@ pub async fn build_full_network_v2( let _ = blackboard_blob("UISP-Graph", &graph).await; // Figure out the network.json layers - let mut parents = HashMap::new(); + let mut parents = HashMap::::new(); for node in graph.node_indices() { if node == root_idx { continue; @@ -238,14 +239,18 @@ pub async fn build_full_network_v2( if route.1.is_empty() { //println!("No path detected from {:?} to {}", graph[node], root_site_name); - parents.insert(name, ("Orphans".to_owned(), (config.queues.generated_pn_download_mbps, config.queues.generated_pn_upload_mbps))); + parents.insert(name.to_owned(), NetJsonParent { + parent_name: "Orphans".to_string(), + mapping: &graph[node], + download: config.queues.generated_pn_download_mbps, + upload: config.queues.generated_pn_upload_mbps, + }); } else { let mut capacity = (config.queues.generated_pn_download_mbps,config.queues.generated_pn_upload_mbps); if !config.uisp_integration.ignore_calculated_capacity { match &graph[node] { - GraphMapping::AccessPoint { name, id } => { + GraphMapping::AccessPoint { name, id, .. } => { if let Some(device) = uisp_data.devices.iter().find(|d| d.id == *id) { - println!("Device: {} / {}", device.download, device.upload); capacity = (device.download, device.upload); if let Some(bw_override) = bandwidth_overrides.get(&device.name) { capacity = (bw_override.0 as u64, bw_override.1 as u64); @@ -260,25 +265,32 @@ pub async fn build_full_network_v2( // We need the weight from node to parent_node in the graph edges if let Some(edge) = graph.find_edge(parent_node, node) { let parent = graph[route.1[route.1.len() - 2]].name(); - parents.insert(name, (parent, capacity)); + parents.insert(name.to_owned(), NetJsonParent { + parent_name: parent, + mapping: &graph[node], + download: capacity.0, + upload: capacity.1, + }); } else { panic!("DID NOT FIND THE EDGE"); } } - - //let parent_index = route.1.iter().last().unwrap(); - //let parent = graph[*parent_index].clone(); - //println!("Parent of {:?} is {:?}", graph[node], parent); } _ => {} } } - //println!("Parents: {:#?}", parents); + println!("{parents:?}"); // Write the network.json file let mut network_json = serde_json::Map::new(); - for (name, (_parent, (download, upload))) in parents.iter().filter(|(_, (parent, _))| *parent == root_site_name) { - network_json.insert((*name).into(), walk_parents(&parents, name, &config, *download, *upload).into()); + for (name, node_info) in parents.iter().filter(|(name, parent)| parent.parent_name == root_site_name) { + network_json.insert(name.into(), walk_parents( + &parents, + name, + &node_info, + &config, + &graph, + ).into()); } let network_path = Path::new(&config.lqos_directory).join("network.json"); if network_path.exists() && !config.integration_common.always_overwrite_network_json { @@ -348,10 +360,18 @@ pub async fn build_full_network_v2( Ok(()) } +#[derive(Debug)] +struct NetJsonParent<'a> { + parent_name: String, + mapping: &'a GraphMapping, + download: u64, + upload: u64, +} + fn save_dot_file(graph: &GraphType) -> Result<(), UispIntegrationError> { // Save the dot file let dot_data = format!("{:?}", petgraph::dot::Dot::with_config(graph, &[petgraph::dot::Config::EdgeNoLabel])); - let _ = std::fs::write("graph.dot", dot_data.as_bytes()); + let _ = write("graph.dot", dot_data.as_bytes()); let _ = std::process::Command::new("dot") .arg("-Tpng") .arg("graph.dot") @@ -362,24 +382,38 @@ fn save_dot_file(graph: &GraphType) -> Result<(), UispIntegrationError> { } fn walk_parents( - parents: &HashMap<&String, (String, (u64, u64))>, + parents: &HashMap, name: &String, + node_info: &NetJsonParent, config: &Arc, - download: u64, - upload: u64, + graph: &GraphType, ) -> serde_json::Map { let mut map = serde_json::Map::new(); - // Entries are name, type, uisp_device or site, downloadBandwidthMbps, uploadBandwidthMbps, children map.insert("name".into(), name.clone().into()); - map.insert("downloadBandwidthMbps".into(), download.into()); - map.insert("uploadBandwidthMbps".into(), upload.into()); + map.insert("downloadBandwidthMbps".into(), node_info.download.into()); + map.insert("uploadBandwidthMbps".into(), node_info.upload.into()); + match node_info.mapping { + GraphMapping::Root { id, .. } | GraphMapping::Site { id, .. } => { + map.insert("type".into(), "Site".into()); + map.insert("uisp_site".into(), id.clone().into()); + map.insert("parent_site".into(), name.clone().into()); + } + GraphMapping::GeneratedSite { .. } => { + map.insert("type".into(), "Site".into()); + } + GraphMapping::AccessPoint { name: _, id, site_name } => { + map.insert("type".into(), "AP".into()); + map.insert("parent_site".into(), site_name.clone().into()); + map.insert("uisp_device".into(), id.clone().into()); + } + } let mut children = serde_json::Map::new(); - for (name, (_parent, (download, upload))) in parents.iter().filter(|(_, (parent, _))| - *parent == *name) { - let child = walk_parents(parents, name, config, *download, *upload); - children.insert((*name).into(), child.into()); + for (name, node_info) in parents.iter().filter(|(_, node_info)| + node_info.parent_name == *name) { + let child = walk_parents(parents, name, &node_info, config, graph); + children.insert(name.into(), child.into()); } map.insert("children".into(), children.into()); -- knotmirror 0.0.1 From 6176d85ddd46d2c85a480b7e63eda7116e55f82a Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Fri, 4 Apr 2025 11:13:04 -0500 Subject: [PATCH 23/42] Refactor: cleanup --- .../src/strategies/ap_only.rs | 3 - .../src/strategies/ap_site.rs | 43 +-- .../uisp_integration/src/strategies/common.rs | 40 --- .../uisp_integration/src/strategies/full2.rs | 268 ++++++------------ .../src/strategies/full2/dot.rs | 16 ++ .../src/strategies/full2/graph_mapping.rs | 20 ++ .../src/strategies/full2/link_mapping.rs | 7 + .../src/strategies/full2/net_json_parent.rs | 53 ++++ 8 files changed, 183 insertions(+), 267 deletions(-) create mode 100644 src/rust/uisp_integration/src/strategies/full2/dot.rs create mode 100644 src/rust/uisp_integration/src/strategies/full2/graph_mapping.rs create mode 100644 src/rust/uisp_integration/src/strategies/full2/link_mapping.rs create mode 100644 src/rust/uisp_integration/src/strategies/full2/net_json_parent.rs diff --git a/src/rust/uisp_integration/src/strategies/ap_only.rs b/src/rust/uisp_integration/src/strategies/ap_only.rs index 6c2ee777..731a8735 100644 --- a/src/rust/uisp_integration/src/strategies/ap_only.rs +++ b/src/rust/uisp_integration/src/strategies/ap_only.rs @@ -1,15 +1,12 @@ -use std::collections::HashMap; use std::fs::write; use std::path::Path; use std::sync::Arc; use tracing::{error, info, warn}; use lqos_config::Config; -use crate::blackboard_blob; use crate::errors::UispIntegrationError; use crate::ip_ranges::IpRanges; use crate::strategies::common::UispData; use crate::strategies::full::shaped_devices_writer::ShapedDevice; -use crate::uisp_types::UispSiteType; /// Creates a network with only APs detected /// from clients. diff --git a/src/rust/uisp_integration/src/strategies/ap_site.rs b/src/rust/uisp_integration/src/strategies/ap_site.rs index 6377de26..9f61dc75 100644 --- a/src/rust/uisp_integration/src/strategies/ap_site.rs +++ b/src/rust/uisp_integration/src/strategies/ap_site.rs @@ -8,29 +8,16 @@ use crate::errors::UispIntegrationError; use crate::ip_ranges::IpRanges; use crate::strategies::common::UispData; use crate::strategies::full::shaped_devices_writer::ShapedDevice; -use crate::uisp_types::UispSiteType; #[derive(Debug, Ord, PartialOrd, Eq, PartialEq, Clone)] pub enum GraphMapping { Root, SiteByName(String), - GeneratedSiteByName(String), + //GeneratedSiteByName(String), AccessPointByName(String), ClientById(String), } -impl GraphMapping { - pub(crate) fn name(&self) -> String { - match self { - GraphMapping::SiteByName(name) => name.clone(), - GraphMapping::AccessPointByName(name) => name.clone(), - GraphMapping::GeneratedSiteByName(name) => name.clone(), - GraphMapping::ClientById(client_id) => client_id.clone(), - _ => "".to_string() - } - } -} - /// Creates a network with APs detected from clients, /// and then a single site above them (shared if the site /// matches). @@ -58,7 +45,7 @@ pub async fn build_ap_site_network( let sites = map_sites_above_aps(&uisp_data, ap_mappings, access_points); // Insert the root - let mut root = Layer { + let root = Layer { id: GraphMapping::Root, children: sites.values().cloned().collect(), }; @@ -165,16 +152,6 @@ pub(crate) struct Layer { } impl Layer { - pub fn name(&self) -> String { - match &self.id { - GraphMapping::SiteByName(name) => name.clone(), - GraphMapping::AccessPointByName(name) => name.clone(), - GraphMapping::GeneratedSiteByName(name) => name.clone(), - GraphMapping::ClientById(client_id) => client_id.clone(), - _ => "".to_string() - } - } - pub(crate) fn walk_children( &self, parent: Option<&str>, @@ -184,16 +161,14 @@ impl Layer { ) -> serde_json::Map { let mut children = serde_json::Map::new(); let parent_name = match &self.id { - GraphMapping::SiteByName(name) | GraphMapping::AccessPointByName(name) - | GraphMapping::GeneratedSiteByName(name) => { + GraphMapping::SiteByName(name) | GraphMapping::AccessPointByName(name) => { name.to_owned() } _ => "".to_owned() }; for child in self.children.iter() { match &child.id { - GraphMapping::SiteByName(name) | GraphMapping::AccessPointByName(name) - | GraphMapping::GeneratedSiteByName(name) => { + GraphMapping::SiteByName(name) | GraphMapping::AccessPointByName(name) => { children.insert(name.clone(), child.walk_children(Some(&parent_name), uisp_data, shaped_devices, config).into()); } GraphMapping::ClientById(_client_id) => { @@ -225,16 +200,6 @@ impl Layer { root.insert("uisp_device".to_string(), device.id.clone().into()); } } - GraphMapping::GeneratedSiteByName(name) => { - root.insert("type".to_string(), "AP".into()); - root.insert("name".to_string(), name.clone().into()); - root.insert("parent_site".to_string(), name.to_string().into()); - if let Some(device) = uisp_data.devices.iter().find(|d| d.name == *name) { - root.insert("downloadBandwidthMbps".to_owned(), device.download.into()); - root.insert("uploadBandwidthMbps".to_owned(), device.upload.into()); - root.insert("uisp_device".to_string(), device.id.clone().into()); - } - } GraphMapping::ClientById(client_id) => { if let Some(site) = uisp_data.sites.iter().find(|c| c.id == *client_id) { let devices = uisp_data.devices.iter().filter(|d| d.site_id == *client_id).collect::>(); diff --git a/src/rust/uisp_integration/src/strategies/common.rs b/src/rust/uisp_integration/src/strategies/common.rs index 843ac37d..dd736867 100644 --- a/src/rust/uisp_integration/src/strategies/common.rs +++ b/src/rust/uisp_integration/src/strategies/common.rs @@ -78,46 +78,6 @@ impl UispData { self.devices_raw.iter().find(|d| d.get_name().unwrap_or_default() == device_name) } - pub fn find_site_by_name(&self, site_name: &str) -> Option<&Site> { - self.sites_raw.iter().find(|s| s.name().unwrap_or_default() == site_name) - } - - pub fn find_site_by_id(&self, site_id: &str) -> Option<&Site> { - self.sites_raw.iter().find(|s| s.id == site_id) - } - - pub fn find_data_links_featuring_device(&self, device_id: &str) -> Vec<&DataLink> { - self. - data_links_raw. - iter() - .filter(|dl| { - if let Some(from_device) = &dl.from.device { - from_device.identification.id == device_id - } else if let Some(to_device) = &dl.to.device { - to_device.identification.id == device_id - } else { - false - } - }) - .collect() - } - - pub fn find_data_links_featuring_site(&self, site_id: &str) -> Vec<&DataLink> { - self. - data_links_raw. - iter() - .filter(|dl| { - if let Some(from_site) = &dl.from.site { - from_site.identification.id == site_id - } else if let Some(to_site) = &dl.to.site { - to_site.identification.id == site_id - } else { - false - } - }) - .collect() - } - pub fn map_clients_to_aps(&self) -> HashMap> { let mut mappings = HashMap::new(); for client in self.find_client_sites() { diff --git a/src/rust/uisp_integration/src/strategies/full2.rs b/src/rust/uisp_integration/src/strategies/full2.rs index 2d877f69..4f2ec122 100644 --- a/src/rust/uisp_integration/src/strategies/full2.rs +++ b/src/rust/uisp_integration/src/strategies/full2.rs @@ -1,3 +1,8 @@ +mod graph_mapping; +mod link_mapping; +mod dot; +mod net_json_parent; + use std::collections::{HashMap, HashSet}; use std::fs::write; use std::path::Path; @@ -7,39 +12,18 @@ use crate::strategies::common::UispData; use crate::uisp_types::UispDevice; use lqos_config::Config; use std::sync::Arc; -use petgraph::Undirected; +use petgraph::{Graph, Undirected}; +use petgraph::graph::NodeIndex; use tracing::{error, info, warn}; use petgraph::visit::{EdgeRef, NodeRef}; -use serde::Serialize; use crate::blackboard_blob; +use crate::strategies::full2::dot::save_dot_file; +use crate::strategies::full2::graph_mapping::GraphMapping; +use crate::strategies::full2::link_mapping::LinkMapping; +use crate::strategies::full2::net_json_parent::{walk_parents, NetJsonParent}; use crate::strategies::full::routes_override::RouteOverride; use crate::strategies::full::shaped_devices_writer::ShapedDevice; -#[derive(Debug, Ord, PartialOrd, Eq, PartialEq, Clone, Serialize)] -pub enum GraphMapping { - Root { name: String, id: String }, - Site { name: String, id: String }, - GeneratedSite { name: String }, - AccessPoint { name: String, id: String, site_name: String }, -} - -impl GraphMapping { - pub fn name(&self) -> String { - match self { - GraphMapping::Root { name, .. } => name.clone(), - GraphMapping::Site { name, .. } => name.clone(), - GraphMapping::GeneratedSite { name } => name.clone(), - GraphMapping::AccessPoint { name, .. } => name.clone(), - } - } -} - -#[derive(Debug, Clone, Serialize)] -pub enum LinkMapping { - Ethernet, - DevicePair(String, String), -} - type GraphType = petgraph::Graph; pub async fn build_full_network_v2( @@ -69,86 +53,19 @@ pub async fn build_full_network_v2( // Add all sites to the graph let mut site_map = HashMap::new(); let mut root_idx = None; - for site in uisp_data.sites_raw.iter().filter(|s| !s.is_client_site()) { - let site_name = site.name_or_blank(); - let id = site.id.clone(); - if site_name == root_site_name { - // Add the root site - let root_entry = GraphMapping::Root { - name: site_name, - id, - }; - let root_ref = graph.add_node(root_entry); - root_idx = Some(root_ref); - site_map.insert(site.id.clone(), root_ref); - continue; - } - let site_entry = GraphMapping::Site { - name: site_name, - id, - }; - let site_ref = graph.add_node(site_entry); - site_map.insert(site.id.clone(), site_ref); - } + add_all_sites_to_graph(&uisp_data, &mut graph, &root_site_name, &mut site_map, &mut root_idx); let root_idx = root_idx.expect("Root site not found"); // Iterate all UISP devices and if their parent site is in the graph, add them let mut device_map = HashMap::new(); - for device in uisp_data.devices_raw.iter() { - let Some(site_id) = &device.identification.site else { - continue; - }; - let site_id = &site_id.id; - let Some(site_ref) = site_map.get(site_id) else { - continue; - }; - let device_entry = GraphMapping::AccessPoint { - name: device.get_name().unwrap_or_default(), - id: device.identification.id.clone(), - site_name: graph[*site_ref].name(), - }; - let device_ref = graph.add_node(device_entry); - device_map.insert(device.identification.id.clone(), device_ref); - let _ = graph.add_edge(device_ref, *site_ref, LinkMapping::Ethernet); - } + add_devices_to_graph(&uisp_data, &mut graph, &mut site_map, &mut device_map); // Now we iterate all the data links looking for DEVICE linkage - for link in uisp_data.data_links_raw.iter() { - let Some(from_device) = &link.from.device else { - continue; - }; - let Some(to_device) = &link.to.device else { - continue; - }; - let Some(a_ref) = device_map.get(&from_device.identification.id) else { - continue; - }; - let Some(b_ref) = device_map.get(&to_device.identification.id) else { - continue; - }; - if a_ref == b_ref { - // If the devices are the same, we don't need to add an edge - continue; - } - if let Some(dev_a) = uisp_data.devices_raw.iter().find(|d| d.get_id() == from_device.identification.id) { - if let Some(dev_b) = uisp_data.devices_raw.iter().find(|d| d.get_id() == to_device.identification.id) { - if dev_a.get_site_id().unwrap_or_default() == dev_b.get_site_id().unwrap_or_default() { - // If the devices are in the same site, we don't need to add an edge - continue; - } - } - } - if graph.contains_edge(*a_ref, *b_ref) { - // If the edge already exists, we don't need to add it - continue; - } - graph.add_edge(*a_ref, *b_ref, LinkMapping::DevicePair(from_device.identification.id.clone(), to_device.identification.id.clone())); - } + add_device_links_to_graph(&uisp_data, &mut graph, &mut device_map); // Now we iterate only sites, looking for connectivity to the root let orphans = graph.add_node(GraphMapping::GeneratedSite{ name: "Orphans".to_string()}); graph.add_edge(root_idx, orphans, LinkMapping::Ethernet); - for (_, site_ref) in site_map.iter() { if *site_ref == root_idx { continue; @@ -249,7 +166,7 @@ pub async fn build_full_network_v2( let mut capacity = (config.queues.generated_pn_download_mbps,config.queues.generated_pn_upload_mbps); if !config.uisp_integration.ignore_calculated_capacity { match &graph[node] { - GraphMapping::AccessPoint { name, id, .. } => { + GraphMapping::AccessPoint { id, .. } => { if let Some(device) = uisp_data.devices.iter().find(|d| d.id == *id) { capacity = (device.download, device.upload); if let Some(bw_override) = bandwidth_overrides.get(&device.name) { @@ -263,7 +180,7 @@ pub async fn build_full_network_v2( let parent_node = route.1[route.1.len() - 2]; // We need the weight from node to parent_node in the graph edges - if let Some(edge) = graph.find_edge(parent_node, node) { + if let Some(_edge) = graph.find_edge(parent_node, node) { let parent = graph[route.1[route.1.len() - 2]].name(); parents.insert(name.to_owned(), NetJsonParent { parent_name: parent, @@ -279,11 +196,10 @@ pub async fn build_full_network_v2( _ => {} } } - println!("{parents:?}"); // Write the network.json file let mut network_json = serde_json::Map::new(); - for (name, node_info) in parents.iter().filter(|(name, parent)| parent.parent_name == root_site_name) { + for (name, node_info) in parents.iter().filter(|(_name, parent)| parent.parent_name == root_site_name) { network_json.insert(name.into(), walk_parents( &parents, name, @@ -360,102 +276,84 @@ pub async fn build_full_network_v2( Ok(()) } -#[derive(Debug)] -struct NetJsonParent<'a> { - parent_name: String, - mapping: &'a GraphMapping, - download: u64, - upload: u64, -} - -fn save_dot_file(graph: &GraphType) -> Result<(), UispIntegrationError> { - // Save the dot file - let dot_data = format!("{:?}", petgraph::dot::Dot::with_config(graph, &[petgraph::dot::Config::EdgeNoLabel])); - let _ = write("graph.dot", dot_data.as_bytes()); - let _ = std::process::Command::new("dot") - .arg("-Tpng") - .arg("graph.dot") - .arg("-o") - .arg("graph.png") - .output(); - Ok(()) -} - -fn walk_parents( - parents: &HashMap, - name: &String, - node_info: &NetJsonParent, - config: &Arc, - graph: &GraphType, -) -> serde_json::Map { - let mut map = serde_json::Map::new(); - // Entries are name, type, uisp_device or site, downloadBandwidthMbps, uploadBandwidthMbps, children - map.insert("name".into(), name.clone().into()); - map.insert("downloadBandwidthMbps".into(), node_info.download.into()); - map.insert("uploadBandwidthMbps".into(), node_info.upload.into()); - match node_info.mapping { - GraphMapping::Root { id, .. } | GraphMapping::Site { id, .. } => { - map.insert("type".into(), "Site".into()); - map.insert("uisp_site".into(), id.clone().into()); - map.insert("parent_site".into(), name.clone().into()); +fn add_device_links_to_graph(uisp_data: &UispData, graph: &mut Graph, device_map: &mut HashMap) { + for link in uisp_data.data_links_raw.iter() { + let Some(from_device) = &link.from.device else { + continue; + }; + let Some(to_device) = &link.to.device else { + continue; + }; + let Some(a_ref) = device_map.get(&from_device.identification.id) else { + continue; + }; + let Some(b_ref) = device_map.get(&to_device.identification.id) else { + continue; + }; + if a_ref == b_ref { + // If the devices are the same, we don't need to add an edge + continue; } - GraphMapping::GeneratedSite { .. } => { - map.insert("type".into(), "Site".into()); + if let Some(dev_a) = uisp_data.devices_raw.iter().find(|d| d.get_id() == from_device.identification.id) { + if let Some(dev_b) = uisp_data.devices_raw.iter().find(|d| d.get_id() == to_device.identification.id) { + if dev_a.get_site_id().unwrap_or_default() == dev_b.get_site_id().unwrap_or_default() { + // If the devices are in the same site, we don't need to add an edge + continue; + } + } } - GraphMapping::AccessPoint { name: _, id, site_name } => { - map.insert("type".into(), "AP".into()); - map.insert("parent_site".into(), site_name.clone().into()); - map.insert("uisp_device".into(), id.clone().into()); + if graph.contains_edge(*a_ref, *b_ref) { + // If the edge already exists, we don't need to add it + continue; } + graph.add_edge(*a_ref, *b_ref, LinkMapping::DevicePair(from_device.identification.id.clone(), to_device.identification.id.clone())); } - - let mut children = serde_json::Map::new(); - for (name, node_info) in parents.iter().filter(|(_, node_info)| - node_info.parent_name == *name) { - let child = walk_parents(parents, name, &node_info, config, graph); - children.insert(name.into(), child.into()); - } - - map.insert("children".into(), children.into()); - - map } -fn network_json_capacity( - config: &Arc, - link: &LinkMapping, - devices: &[UispDevice], -) -> (u64, u64) { - // Handle ignoring capacity - if config.uisp_integration.ignore_calculated_capacity { - return (config.queues.generated_pn_download_mbps, config.queues.generated_pn_upload_mbps); +fn add_devices_to_graph(uisp_data: &UispData, graph: &mut Graph, site_map: &mut HashMap, device_map: &mut HashMap) { + for device in uisp_data.devices_raw.iter() { + let Some(site_id) = &device.identification.site else { + continue; + }; + let site_id = &site_id.id; + let Some(site_ref) = site_map.get(site_id) else { + continue; + }; + let device_entry = GraphMapping::AccessPoint { + name: device.get_name().unwrap_or_default(), + id: device.identification.id.clone(), + site_name: graph[*site_ref].name(), + }; + let device_ref = graph.add_node(device_entry); + device_map.insert(device.identification.id.clone(), device_ref); + let _ = graph.add_edge(device_ref, *site_ref, LinkMapping::Ethernet); } +} - // Handle the link type - match link { - LinkMapping::Ethernet => { - return (config.queues.generated_pn_download_mbps, config.queues.generated_pn_upload_mbps); - } - LinkMapping::DevicePair(device_a, device_b) => { - // Find the devices - let device_a = devices.iter().find(|d| d.id == *device_a); - let device_b = devices.iter().find(|d| d.id == *device_b); - - if let Some(device_a) = device_a { - if let Some(device_b) = device_b { - return ( - device_a.download, - device_b.upload, - ); - } - } +pub fn add_all_sites_to_graph(uisp_data: &UispData, graph: &mut Graph, root_site_name: &String, site_map: &mut HashMap, root_idx: &mut Option) { + for site in uisp_data.sites_raw.iter().filter(|s| !s.is_client_site()) { + let site_name = site.name_or_blank(); + let id = site.id.clone(); + if site_name == *root_site_name { + // Add the root site + let root_entry = GraphMapping::Root { + name: site_name, + id, + }; + let root_ref = graph.add_node(root_entry); + *root_idx = Some(root_ref); + site_map.insert(site.id.clone(), root_ref); + continue; } + let site_entry = GraphMapping::Site { + name: site_name, + id, + }; + let site_ref = graph.add_node(site_entry); + site_map.insert(site.id.clone(), site_ref); } - - (config.queues.generated_pn_download_mbps, config.queues.generated_pn_upload_mbps) } - fn link_capacity_mbps(link_mapping: &LinkMapping, devices: &[UispDevice], route_overrides: &[RouteOverride]) -> u64 { match link_mapping { LinkMapping::Ethernet => 10_000, diff --git a/src/rust/uisp_integration/src/strategies/full2/dot.rs b/src/rust/uisp_integration/src/strategies/full2/dot.rs new file mode 100644 index 00000000..aeb2823e --- /dev/null +++ b/src/rust/uisp_integration/src/strategies/full2/dot.rs @@ -0,0 +1,16 @@ +use std::fs::write; +use crate::errors::UispIntegrationError; +use crate::strategies::full2::GraphType; + +pub fn save_dot_file(graph: &GraphType) -> Result<(), UispIntegrationError> { + // Save the dot file + let dot_data = format!("{:?}", petgraph::dot::Dot::with_config(graph, &[petgraph::dot::Config::EdgeNoLabel])); + let _ = write("graph.dot", dot_data.as_bytes()); + let _ = std::process::Command::new("dot") + .arg("-Tpng") + .arg("graph.dot") + .arg("-o") + .arg("graph.png") + .output(); + Ok(()) +} \ No newline at end of file diff --git a/src/rust/uisp_integration/src/strategies/full2/graph_mapping.rs b/src/rust/uisp_integration/src/strategies/full2/graph_mapping.rs new file mode 100644 index 00000000..853a1666 --- /dev/null +++ b/src/rust/uisp_integration/src/strategies/full2/graph_mapping.rs @@ -0,0 +1,20 @@ +use serde::Serialize; + +#[derive(Debug, Ord, PartialOrd, Eq, PartialEq, Clone, Serialize)] +pub enum GraphMapping { + Root { name: String, id: String }, + Site { name: String, id: String }, + GeneratedSite { name: String }, + AccessPoint { name: String, id: String, site_name: String }, +} + +impl GraphMapping { + pub fn name(&self) -> String { + match self { + GraphMapping::Root { name, .. } => name.clone(), + GraphMapping::Site { name, .. } => name.clone(), + GraphMapping::GeneratedSite { name } => name.clone(), + GraphMapping::AccessPoint { name, .. } => name.clone(), + } + } +} \ No newline at end of file diff --git a/src/rust/uisp_integration/src/strategies/full2/link_mapping.rs b/src/rust/uisp_integration/src/strategies/full2/link_mapping.rs new file mode 100644 index 00000000..b07356f7 --- /dev/null +++ b/src/rust/uisp_integration/src/strategies/full2/link_mapping.rs @@ -0,0 +1,7 @@ +use serde::Serialize; + +#[derive(Debug, Clone, Serialize)] +pub enum LinkMapping { + Ethernet, + DevicePair(String, String), +} \ No newline at end of file diff --git a/src/rust/uisp_integration/src/strategies/full2/net_json_parent.rs b/src/rust/uisp_integration/src/strategies/full2/net_json_parent.rs new file mode 100644 index 00000000..ceeb13e4 --- /dev/null +++ b/src/rust/uisp_integration/src/strategies/full2/net_json_parent.rs @@ -0,0 +1,53 @@ +use std::collections::HashMap; +use std::sync::Arc; +use lqos_config::Config; +use crate::strategies::full2::graph_mapping::GraphMapping; +use crate::strategies::full2::GraphType; + +#[derive(Debug)] +pub struct NetJsonParent<'a> { + pub parent_name: String, + pub mapping: &'a GraphMapping, + pub download: u64, + pub upload: u64, +} + +pub fn walk_parents( + parents: &HashMap, + name: &String, + node_info: &NetJsonParent, + config: &Arc, + graph: &GraphType, +) -> serde_json::Map { + let mut map = serde_json::Map::new(); + // Entries are name, type, uisp_device or site, downloadBandwidthMbps, uploadBandwidthMbps, children + map.insert("name".into(), name.clone().into()); + map.insert("downloadBandwidthMbps".into(), node_info.download.into()); + map.insert("uploadBandwidthMbps".into(), node_info.upload.into()); + match node_info.mapping { + GraphMapping::Root { id, .. } | GraphMapping::Site { id, .. } => { + map.insert("type".into(), "Site".into()); + map.insert("uisp_site".into(), id.clone().into()); + map.insert("parent_site".into(), name.clone().into()); + } + GraphMapping::GeneratedSite { .. } => { + map.insert("type".into(), "Site".into()); + } + GraphMapping::AccessPoint { name: _, id, site_name } => { + map.insert("type".into(), "AP".into()); + map.insert("parent_site".into(), site_name.clone().into()); + map.insert("uisp_device".into(), id.clone().into()); + } + } + + let mut children = serde_json::Map::new(); + for (name, node_info) in parents.iter().filter(|(_, node_info)| + node_info.parent_name == *name) { + let child = walk_parents(parents, name, &node_info, config, graph); + children.insert(name.into(), child.into()); + } + + map.insert("children".into(), children.into()); + + map +} \ No newline at end of file -- knotmirror 0.0.1 From 1b8ed100e6dd385df2f6fd9f292f55c9d161ede5 Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Mon, 7 Apr 2025 11:16:55 -0500 Subject: [PATCH 24/42] Fix: Take into account commit bandwidth multiplier. --- .../uisp_integration/src/strategies/full2.rs | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/src/rust/uisp_integration/src/strategies/full2.rs b/src/rust/uisp_integration/src/strategies/full2.rs index 4f2ec122..c9cc1def 100644 --- a/src/rust/uisp_integration/src/strategies/full2.rs +++ b/src/rust/uisp_integration/src/strategies/full2.rs @@ -238,6 +238,14 @@ pub async fn build_full_network_v2( if !device.has_address() { continue; } + + let download = (site.max_down_mbps as f32) * config.uisp_integration.bandwidth_overhead_factor; + let upload = (site.max_up_mbps as f32) * config.uisp_integration.bandwidth_overhead_factor; + let download_min = (download * config.uisp_integration.commit_bandwidth_multiplier) as u64; + let upload_min = (upload * config.uisp_integration.commit_bandwidth_multiplier) as u64; + let download_max = download as u64; + let upload_max = upload as u64; + let shaped_device = ShapedDevice { circuit_id: site.id.to_owned(), circuit_name: site.name.to_owned(), @@ -247,10 +255,10 @@ pub async fn build_full_network_v2( mac: device.mac.to_owned(), ipv4: device.ipv4_list(), ipv6: device.ipv6_list(), - download_min: (config.uisp_integration.commit_bandwidth_multiplier * site.max_down_mbps as f32) as u64, - upload_min: (config.uisp_integration.commit_bandwidth_multiplier * site.max_up_mbps as f32) as u64, - download_max: site.max_down_mbps, - upload_max: site.max_up_mbps, + download_min, + upload_min, + download_max, + upload_max, comment: "".to_string(), }; shaped_devices.push(shaped_device); -- knotmirror 0.0.1 From b8e6dd4bf3820c7bed9bbedab0dce538c6cf6cc2 Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Mon, 7 Apr 2025 11:27:32 -0500 Subject: [PATCH 25/42] Fix: Zero capacity is replaced with generated PN capacity on device read (for empty devices) --- src/rust/uisp_integration/src/uisp_types/uisp_device.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/rust/uisp_integration/src/uisp_types/uisp_device.rs b/src/rust/uisp_integration/src/uisp_types/uisp_device.rs index 06211719..52eb3fbd 100644 --- a/src/rust/uisp_integration/src/uisp_types/uisp_device.rs +++ b/src/rust/uisp_integration/src/uisp_types/uisp_device.rs @@ -53,6 +53,12 @@ impl UispDevice { upload = ul as u64 / 1000000; } } + if download == 0 { + download = config.queues.generated_pn_download_mbps; + } + if upload == 0 { + upload = config.queues.generated_pn_upload_mbps; + } // Accumulate IP address listings if let Some(interfaces) = &device.interfaces { -- knotmirror 0.0.1 From f70492044ae75d059f89f6e8c139cf2dfba4b7a6 Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Mon, 7 Apr 2025 11:30:13 -0500 Subject: [PATCH 26/42] "full2" is now the default/replacement for "full". --- src/rust/uisp_integration/src/strategies/mod.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/rust/uisp_integration/src/strategies/mod.rs b/src/rust/uisp_integration/src/strategies/mod.rs index d1efb669..8d0e777f 100644 --- a/src/rust/uisp_integration/src/strategies/mod.rs +++ b/src/rust/uisp_integration/src/strategies/mod.rs @@ -31,11 +31,11 @@ pub async fn build_with_strategy( flat::build_flat_network(config, ip_ranges).await?; Ok(()) } - "full" => { + /*"full" => { info!("Strategy selected: full"); full::build_full_network(config, ip_ranges).await?; Ok(()) - } + }*/ "ap_only" => { info!("Strategy selected: ap_only"); ap_only::build_ap_only_network(config, ip_ranges).await?; @@ -46,7 +46,7 @@ pub async fn build_with_strategy( ap_site::build_ap_site_network(config, ip_ranges).await?; Ok(()) } - "full2" => { + "full" | "full2" => { info!("Strategy selected: full2"); full2::build_full_network_v2(config, ip_ranges).await?; Ok(()) -- knotmirror 0.0.1 From 702b626152e2518d9ea2aa00db73f178d66028f8 Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Mon, 7 Apr 2025 11:32:30 -0500 Subject: [PATCH 27/42] Include "troublesome client" list in the blackboard for reference. --- src/rust/uisp_integration/src/strategies/ap_site.rs | 9 +++++++-- src/rust/uisp_integration/src/strategies/full2.rs | 3 ++- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/src/rust/uisp_integration/src/strategies/ap_site.rs b/src/rust/uisp_integration/src/strategies/ap_site.rs index 9f61dc75..c0de4937 100644 --- a/src/rust/uisp_integration/src/strategies/ap_site.rs +++ b/src/rust/uisp_integration/src/strategies/ap_site.rs @@ -4,6 +4,7 @@ use std::path::Path; use std::sync::Arc; use tracing::{error, info, warn}; use lqos_config::Config; +use crate::blackboard_blob; use crate::errors::UispIntegrationError; use crate::ip_ranges::IpRanges; use crate::strategies::common::UispData; @@ -28,7 +29,7 @@ pub async fn build_ap_site_network( let uisp_data = UispData::fetch_uisp_data(config.clone(), ip_ranges).await?; // Find trouble-spots! - let _trouble = find_troublesome_sites(&uisp_data) + let _trouble = find_troublesome_sites(&uisp_data).await .map_err(|e|{ error!("Error finding troublesome sites"); error!("{e:?}"); @@ -252,11 +253,15 @@ pub struct TroublesomeClients { pub client_of_clients: HashSet, } -pub(crate) fn find_troublesome_sites( +pub(crate) async fn find_troublesome_sites( data: &UispData, ) -> anyhow::Result { let multi_entry_points = find_clients_with_multiple_entry_points(data)?; let client_of_clients = find_clients_linked_from_other_clients(data)?; + + let _ = blackboard_blob("UISP-Trouble-MultiEntry", multi_entry_points.clone()).await; + let _ = blackboard_blob("UISP-Trouble-ClientOfClient", client_of_clients.clone()).await; + Ok(TroublesomeClients { multi_entry_points, client_of_clients, diff --git a/src/rust/uisp_integration/src/strategies/full2.rs b/src/rust/uisp_integration/src/strategies/full2.rs index c9cc1def..c52c9e12 100644 --- a/src/rust/uisp_integration/src/strategies/full2.rs +++ b/src/rust/uisp_integration/src/strategies/full2.rs @@ -34,7 +34,8 @@ pub async fn build_full_network_v2( let uisp_data = UispData::fetch_uisp_data(config.clone(), ip_ranges).await?; // Report on obvious UISP errors that should be fixed - let _trouble = crate::strategies::ap_site::find_troublesome_sites(&uisp_data).map_err(|e| { + let _trouble = crate::strategies::ap_site::find_troublesome_sites(&uisp_data).await + .map_err(|e| { error!("Error finding troublesome sites"); error!("{e:?}"); UispIntegrationError::UnknownSiteType -- knotmirror 0.0.1 From 60d8a3dfe6319225f5bf7cbcf0febd2f869bea47 Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Mon, 7 Apr 2025 11:46:44 -0500 Subject: [PATCH 28/42] Downgrade "I don't know how to parse" for network.json to info, since we're adding all kinds of metadata now! --- src/rust/lqos_queue_tracker/src/queue_structure/queue_node.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/rust/lqos_queue_tracker/src/queue_structure/queue_node.rs b/src/rust/lqos_queue_tracker/src/queue_structure/queue_node.rs index bea56490..61e14a04 100644 --- a/src/rust/lqos_queue_tracker/src/queue_structure/queue_node.rs +++ b/src/rust/lqos_queue_tracker/src/queue_structure/queue_node.rs @@ -3,7 +3,7 @@ use lqos_bus::TcHandle; use lqos_utils::hash_to_i64; use lqos_utils::hex_string::read_hex_string; use serde_json::Value; -use tracing::{error, warn}; +use tracing::{error, info, warn}; #[derive(Default, Clone, Debug)] pub struct QueueNode { @@ -238,7 +238,7 @@ impl QueueNode { "idForCircuitsWithoutParentNodes" | "type" => { // Ignore } - _ => error!("I don't know how to parse key: [{key}]"), + _ => info!("I don't know how to parse key: [{key}]"), } } } else { -- knotmirror 0.0.1 From bebba9def0c5956eecf11a18ddc0d5d71fdf21af Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Tue, 8 Apr 2025 08:51:45 -0500 Subject: [PATCH 29/42] Cleanup: cargo fmt run --- src/rust/uisp_integration/src/blackboard.rs | 4 +- src/rust/uisp_integration/src/main.rs | 5 +- .../src/strategies/ap_only.rs | 28 +- .../src/strategies/ap_site.rs | 113 +++++--- .../uisp_integration/src/strategies/common.rs | 59 +++-- .../uisp_integration/src/strategies/full2.rs | 241 ++++++++++++------ .../src/strategies/full2/dot.rs | 9 +- .../src/strategies/full2/graph_mapping.rs | 22 +- .../src/strategies/full2/link_mapping.rs | 2 +- .../src/strategies/full2/net_json_parent.rs | 20 +- .../uisp_integration/src/strategies/mod.rs | 4 +- 11 files changed, 331 insertions(+), 176 deletions(-) diff --git a/src/rust/uisp_integration/src/blackboard.rs b/src/rust/uisp_integration/src/blackboard.rs index 59841146..958f7c05 100644 --- a/src/rust/uisp_integration/src/blackboard.rs +++ b/src/rust/uisp_integration/src/blackboard.rs @@ -1,8 +1,8 @@ //! Collects the blackboard functionality together +use lqos_bus::BlackboardSystem; use serde::Serialize; use tracing::info; -use lqos_bus::BlackboardSystem; pub async fn blackboard(subsystem: BlackboardSystem, key: &str, value: &str) { let Ok(config) = lqos_config::load_config() else { @@ -40,4 +40,4 @@ pub async fn blackboard_blob(key: &str, value: T) -> anyhow::Resul let _ = lqos_bus::bus_request(req).await; } Ok(()) -} \ No newline at end of file +} diff --git a/src/rust/uisp_integration/src/main.rs b/src/rust/uisp_integration/src/main.rs index a832f50b..419f706e 100644 --- a/src/rust/uisp_integration/src/main.rs +++ b/src/rust/uisp_integration/src/main.rs @@ -2,19 +2,19 @@ //! be ported back to Python, with Rust support structures - but I'll iterate //! faster in Rust. +mod blackboard; #[warn(missing_docs)] mod errors; pub mod ip_ranges; mod strategies; pub mod uisp_types; -mod blackboard; use crate::errors::UispIntegrationError; use crate::ip_ranges::IpRanges; +pub use blackboard::*; use lqos_config::Config; use tokio::time::Instant; use tracing::{error, info}; -pub use blackboard::*; /// Start the tracing/logging system fn init_tracing() { @@ -35,7 +35,6 @@ fn check_enabled_status(config: &Config) -> Result<(), UispIntegrationError> { } } - #[tokio::main] async fn main() -> Result<(), UispIntegrationError> { let now = Instant::now(); diff --git a/src/rust/uisp_integration/src/strategies/ap_only.rs b/src/rust/uisp_integration/src/strategies/ap_only.rs index 731a8735..4ca1761f 100644 --- a/src/rust/uisp_integration/src/strategies/ap_only.rs +++ b/src/rust/uisp_integration/src/strategies/ap_only.rs @@ -1,12 +1,12 @@ -use std::fs::write; -use std::path::Path; -use std::sync::Arc; -use tracing::{error, info, warn}; -use lqos_config::Config; use crate::errors::UispIntegrationError; use crate::ip_ranges::IpRanges; use crate::strategies::common::UispData; use crate::strategies::full::shaped_devices_writer::ShapedDevice; +use lqos_config::Config; +use std::fs::write; +use std::path::Path; +use std::sync::Arc; +use tracing::{error, info, warn}; /// Creates a network with only APs detected /// from clients. @@ -35,8 +35,14 @@ pub async fn build_ap_only_network( ap_object.insert("children".to_string(), serde_json::Map::new().into()); // Limits - ap_object.insert("downloadBandwidthMbps".to_string(), serde_json::Value::Number(ap_device.download.into())); - ap_object.insert("uploadBandwidthMbps".to_string(), serde_json::Value::Number(ap_device.upload.into())); + ap_object.insert( + "downloadBandwidthMbps".to_string(), + serde_json::Value::Number(ap_device.download.into()), + ); + ap_object.insert( + "uploadBandwidthMbps".to_string(), + serde_json::Value::Number(ap_device.upload.into()), + ); // Metadata ap_object.insert("type".to_string(), "AP".to_string().into()); @@ -60,7 +66,11 @@ pub async fn build_ap_only_network( for (parent, client_ids) in mappings.iter() { for client_id in client_ids { let site = uisp_data.sites.iter().find(|s| *client_id == s.id).unwrap(); - let devices = uisp_data.devices.iter().filter(|d| d.site_id == *client_id).collect::>(); + let devices = uisp_data + .devices + .iter() + .filter(|d| d.site_id == *client_id) + .collect::>(); for device in devices.iter().filter(|d| d.has_address()) { let sd = ShapedDevice { circuit_id: site.id.clone(), @@ -105,4 +115,4 @@ pub async fn build_ap_only_network( info!("Wrote {} lines to ShapedDevices.csv", shaped_devices.len()); Ok(()) -} \ No newline at end of file +} diff --git a/src/rust/uisp_integration/src/strategies/ap_site.rs b/src/rust/uisp_integration/src/strategies/ap_site.rs index c0de4937..ac278985 100644 --- a/src/rust/uisp_integration/src/strategies/ap_site.rs +++ b/src/rust/uisp_integration/src/strategies/ap_site.rs @@ -1,14 +1,14 @@ -use std::collections::{HashMap, HashSet}; -use std::fs::write; -use std::path::Path; -use std::sync::Arc; -use tracing::{error, info, warn}; -use lqos_config::Config; use crate::blackboard_blob; use crate::errors::UispIntegrationError; use crate::ip_ranges::IpRanges; use crate::strategies::common::UispData; use crate::strategies::full::shaped_devices_writer::ShapedDevice; +use lqos_config::Config; +use std::collections::{HashMap, HashSet}; +use std::fs::write; +use std::path::Path; +use std::sync::Arc; +use tracing::{error, info, warn}; #[derive(Debug, Ord, PartialOrd, Eq, PartialEq, Clone)] pub enum GraphMapping { @@ -29,12 +29,11 @@ pub async fn build_ap_site_network( let uisp_data = UispData::fetch_uisp_data(config.clone(), ip_ranges).await?; // Find trouble-spots! - let _trouble = find_troublesome_sites(&uisp_data).await - .map_err(|e|{ - error!("Error finding troublesome sites"); - error!("{e:?}"); - UispIntegrationError::UnknownSiteType - })?; + let _trouble = find_troublesome_sites(&uisp_data).await.map_err(|e| { + error!("Error finding troublesome sites"); + error!("{e:?}"); + UispIntegrationError::UnknownSiteType + })?; // Find the clients let ap_mappings = uisp_data.map_clients_to_aps(); @@ -76,7 +75,10 @@ pub async fn build_ap_site_network( Ok(()) } -pub(crate) fn write_shaped_devices(config: &Arc, shaped_devices: &mut Vec) -> Result<(), UispIntegrationError> { +pub(crate) fn write_shaped_devices( + config: &Arc, + shaped_devices: &mut Vec, +) -> Result<(), UispIntegrationError> { let file_path = Path::new(&config.lqos_directory).join("ShapedDevices.csv"); let mut writer = csv::WriterBuilder::new() .has_headers(true) @@ -95,18 +97,23 @@ pub(crate) fn write_shaped_devices(config: &Arc, shaped_devices: &mut Ve Ok(()) } -pub(crate) fn map_sites_above_aps(uisp_data: &UispData, ap_mappings: HashMap>, access_points: HashMap) -> HashMap { +pub(crate) fn map_sites_above_aps( + uisp_data: &UispData, + ap_mappings: HashMap>, + access_points: HashMap, +) -> HashMap { let mut sites = HashMap::new(); for (ap_name, client_ids) in ap_mappings.iter() { if let Some(device) = uisp_data.find_device_by_name(ap_name) { if let Some(device_site_id) = device.get_site_id() { if let Some(device_site) = uisp_data.sites.iter().find(|s| s.id == device_site_id) { - let site_entry = sites.entry(device_site.name.clone()).or_insert_with(|| { - Layer { - id: GraphMapping::SiteByName(device_site.name.clone()), - children: Vec::new(), - } - }); + let site_entry = + sites + .entry(device_site.name.clone()) + .or_insert_with(|| Layer { + id: GraphMapping::SiteByName(device_site.name.clone()), + children: Vec::new(), + }); let ap_map = access_points.get(ap_name).unwrap().clone(); site_entry.children.push(ap_map); } @@ -165,15 +172,21 @@ impl Layer { GraphMapping::SiteByName(name) | GraphMapping::AccessPointByName(name) => { name.to_owned() } - _ => "".to_owned() + _ => "".to_owned(), }; for child in self.children.iter() { match &child.id { GraphMapping::SiteByName(name) | GraphMapping::AccessPointByName(name) => { - children.insert(name.clone(), child.walk_children(Some(&parent_name), uisp_data, shaped_devices, config).into()); + children.insert( + name.clone(), + child + .walk_children(Some(&parent_name), uisp_data, shaped_devices, config) + .into(), + ); } GraphMapping::ClientById(_client_id) => { - let _ = child.walk_children(Some(&parent_name), uisp_data, shaped_devices, config); + let _ = + child.walk_children(Some(&parent_name), uisp_data, shaped_devices, config); } _ => {} } @@ -185,7 +198,10 @@ impl Layer { root.insert("type".to_string(), "Site".into()); root.insert("name".to_string(), name.clone().into()); if let Some(site) = uisp_data.sites.iter().find(|s| s.name == *name) { - root.insert("downloadBandwidthMbps".to_owned(), site.max_down_mbps.into()); + root.insert( + "downloadBandwidthMbps".to_owned(), + site.max_down_mbps.into(), + ); root.insert("uploadBandwidthMbps".to_owned(), site.max_up_mbps.into()); root.insert("uisp_site".to_string(), site.id.clone().into()); root.insert("parent_site".to_string(), name.to_string().into()); @@ -203,7 +219,11 @@ impl Layer { } GraphMapping::ClientById(client_id) => { if let Some(site) = uisp_data.sites.iter().find(|c| c.id == *client_id) { - let devices = uisp_data.devices.iter().filter(|d| d.site_id == *client_id).collect::>(); + let devices = uisp_data + .devices + .iter() + .filter(|d| d.site_id == *client_id) + .collect::>(); for device in devices.iter().filter(|d| d.has_address()) { let sd = ShapedDevice { circuit_id: site.id.clone(), @@ -238,7 +258,10 @@ impl Layer { } } if parent.is_some() { - root.insert("children".to_string(), serde_json::to_value(children).unwrap()); + root.insert( + "children".to_string(), + serde_json::to_value(children).unwrap(), + ); } else { for child in children { root.insert(child.0, child.1); @@ -253,9 +276,7 @@ pub struct TroublesomeClients { pub client_of_clients: HashSet, } -pub(crate) async fn find_troublesome_sites( - data: &UispData, -) -> anyhow::Result { +pub(crate) async fn find_troublesome_sites(data: &UispData) -> anyhow::Result { let multi_entry_points = find_clients_with_multiple_entry_points(data)?; let client_of_clients = find_clients_linked_from_other_clients(data)?; @@ -268,17 +289,19 @@ pub(crate) async fn find_troublesome_sites( }) } -fn find_clients_with_multiple_entry_points( - data: &UispData, -) -> anyhow::Result> { +fn find_clients_with_multiple_entry_points(data: &UispData) -> anyhow::Result> { let mut result = HashSet::new(); for client in data.find_client_sites() { let mut links_to_client = HashSet::new(); for link in data.data_links_raw.iter() { if let (Some(from_site), Some(to_site)) = (&link.from.site, &link.to.site) { - if from_site.identification.id == client.id && to_site.identification.id != client.id { + if from_site.identification.id == client.id + && to_site.identification.id != client.id + { links_to_client.insert(to_site.identification.id.clone()); - } else if from_site.identification.id != client.id && to_site.identification.id == client.id { + } else if from_site.identification.id != client.id + && to_site.identification.id == client.id + { links_to_client.insert(from_site.identification.id.clone()); } } @@ -295,24 +318,30 @@ fn find_clients_with_multiple_entry_points( Ok(result) } -fn find_clients_linked_from_other_clients( - data: &UispData -) -> anyhow::Result> { +fn find_clients_linked_from_other_clients(data: &UispData) -> anyhow::Result> { let all_clients = data.find_client_sites(); let mut result = HashSet::new(); for client in &all_clients { for link in data.data_links_raw.iter() { if let (Some(from_site), Some(to_site)) = (&link.from.site, &link.to.site) { - if from_site.identification.id == client.id && to_site.identification.id != client.id - && all_clients.iter().any(|c| c.id == to_site.identification.id) { + if from_site.identification.id == client.id + && to_site.identification.id != client.id + && all_clients + .iter() + .any(|c| c.id == to_site.identification.id) + { warn!( "Client {} is linked from another client: {}", client.name, to_site.identification.id ); result.insert(client.id.clone()); } - if from_site.identification.id != client.id && to_site.identification.id == client.id - && all_clients.iter().any(|c| c.id == from_site.identification.id) { + if from_site.identification.id != client.id + && to_site.identification.id == client.id + && all_clients + .iter() + .any(|c| c.id == from_site.identification.id) + { warn!( "Client {} is linked to another client: {}", client.name, from_site.identification.id @@ -323,4 +352,4 @@ fn find_clients_linked_from_other_clients( } } Ok(result) -} \ No newline at end of file +} diff --git a/src/rust/uisp_integration/src/strategies/common.rs b/src/rust/uisp_integration/src/strategies/common.rs index dd736867..8c5e699e 100644 --- a/src/rust/uisp_integration/src/strategies/common.rs +++ b/src/rust/uisp_integration/src/strategies/common.rs @@ -1,14 +1,14 @@ -use std::collections::HashMap; -use std::sync::Arc; -use tracing::warn; -use lqos_config::Config; -use uisp::{DataLink, Device, Site}; use crate::blackboard_blob; -use crate::ip_ranges::IpRanges; -use crate::strategies::full::uisp_fetch::load_uisp_data; use crate::errors::UispIntegrationError; +use crate::ip_ranges::IpRanges; use crate::strategies::full::parse::parse_uisp_datasets; +use crate::strategies::full::uisp_fetch::load_uisp_data; use crate::uisp_types::{UispDataLink, UispDevice, UispSite, UispSiteType}; +use lqos_config::Config; +use std::collections::HashMap; +use std::sync::Arc; +use tracing::warn; +use uisp::{DataLink, Device, Site}; pub(crate) struct UispData { pub sites_raw: Vec, @@ -63,19 +63,29 @@ impl UispData { } pub fn find_client_sites(&self) -> Vec<&UispSite> { - self.sites.iter().filter(|s| s.site_type == UispSiteType::Client).collect() + self.sites + .iter() + .filter(|s| s.site_type == UispSiteType::Client) + .collect() } pub fn find_devices_in_site(&self, site_id: &str) -> Vec<&Device> { - self.devices_raw.iter().filter(|d| d.get_site_id().unwrap_or_default() == site_id).collect() + self.devices_raw + .iter() + .filter(|d| d.get_site_id().unwrap_or_default() == site_id) + .collect() } pub fn find_device_by_id(&self, device_id: &str) -> Option<&Device> { - self.devices_raw.iter().find(|d| d.identification.id == device_id) + self.devices_raw + .iter() + .find(|d| d.identification.id == device_id) } pub fn find_device_by_name(&self, device_name: &str) -> Option<&Device> { - self.devices_raw.iter().find(|d| d.get_name().unwrap_or_default() == device_name) + self.devices_raw + .iter() + .find(|d| d.get_name().unwrap_or_default() == device_name) } pub fn map_clients_to_aps(&self) -> HashMap> { @@ -120,9 +130,12 @@ impl UispData { if let Some(from_device) = &link.from.device { if from_device.identification.id == device.identification.id { if let Some(to_device) = &link.to.device { - if let Some(apdev) = self.find_device_by_id(&to_device.identification.id) { + if let Some(apdev) = + self.find_device_by_id(&to_device.identification.id) + { if apdev.get_site_id().unwrap_or_default() != client.id { - parent = Some(("AP", apdev.get_name().unwrap_or_default())); + parent = + Some(("AP", apdev.get_name().unwrap_or_default())); found = true; } } @@ -133,9 +146,12 @@ impl UispData { if let Some(to_device) = &link.to.device { if to_device.identification.id == device.identification.id { if let Some(from_device) = &link.from.device { - if let Some(apdev) = self.find_device_by_id(&from_device.identification.id) { + if let Some(apdev) = + self.find_device_by_id(&from_device.identification.id) + { if apdev.get_site_id().unwrap_or_default() != client.id { - parent = Some(("AP", apdev.get_name().unwrap_or_default())); + parent = + Some(("AP", apdev.get_name().unwrap_or_default())); found = true; } } @@ -152,7 +168,9 @@ impl UispData { if let Some(from_site) = &link.from.site { if from_site.identification.id == client.id { if let Some(to_device) = &link.to.device { - if let Some(apdev) = self.find_device_by_id(&to_device.identification.id) { + if let Some(apdev) = + self.find_device_by_id(&to_device.identification.id) + { if apdev.get_site_id().unwrap_or_default() != client.id { parent = Some(("AP", apdev.get_name().unwrap_or_default())); found = true; @@ -164,7 +182,9 @@ impl UispData { if let Some(to_site) = &link.to.site { if to_site.identification.id == client.id { if let Some(from_device) = &link.from.device { - if let Some(apdev) = self.find_device_by_id(&from_device.identification.id) { + if let Some(apdev) = + self.find_device_by_id(&from_device.identification.id) + { if apdev.get_site_id().unwrap_or_default() != client.id { parent = Some(("AP", apdev.get_name().unwrap_or_default())); found = true; @@ -178,7 +198,9 @@ impl UispData { if !found { //println!("Client {} has no obvious parent AP", client.name); - let entry = mappings.entry("Orphans".to_string()).or_insert_with(Vec::new); + let entry = mappings + .entry("Orphans".to_string()) + .or_insert_with(Vec::new); entry.push(client.id.clone()); } else { //info!("Client {} is connected to {:?}", client.name, parent); @@ -191,4 +213,3 @@ impl UispData { mappings } } - diff --git a/src/rust/uisp_integration/src/strategies/full2.rs b/src/rust/uisp_integration/src/strategies/full2.rs index c52c9e12..6b7836ca 100644 --- a/src/rust/uisp_integration/src/strategies/full2.rs +++ b/src/rust/uisp_integration/src/strategies/full2.rs @@ -1,28 +1,28 @@ +mod dot; mod graph_mapping; mod link_mapping; -mod dot; mod net_json_parent; -use std::collections::{HashMap, HashSet}; -use std::fs::write; -use std::path::Path; +use crate::blackboard_blob; use crate::errors::UispIntegrationError; use crate::ip_ranges::IpRanges; use crate::strategies::common::UispData; +use crate::strategies::full::routes_override::RouteOverride; +use crate::strategies::full::shaped_devices_writer::ShapedDevice; +use crate::strategies::full2::dot::save_dot_file; +use crate::strategies::full2::graph_mapping::GraphMapping; +use crate::strategies::full2::link_mapping::LinkMapping; +use crate::strategies::full2::net_json_parent::{NetJsonParent, walk_parents}; use crate::uisp_types::UispDevice; use lqos_config::Config; -use std::sync::Arc; -use petgraph::{Graph, Undirected}; use petgraph::graph::NodeIndex; -use tracing::{error, info, warn}; use petgraph::visit::{EdgeRef, NodeRef}; -use crate::blackboard_blob; -use crate::strategies::full2::dot::save_dot_file; -use crate::strategies::full2::graph_mapping::GraphMapping; -use crate::strategies::full2::link_mapping::LinkMapping; -use crate::strategies::full2::net_json_parent::{walk_parents, NetJsonParent}; -use crate::strategies::full::routes_override::RouteOverride; -use crate::strategies::full::shaped_devices_writer::ShapedDevice; +use petgraph::{Graph, Undirected}; +use std::collections::{HashMap, HashSet}; +use std::fs::write; +use std::path::Path; +use std::sync::Arc; +use tracing::{error, info, warn}; type GraphType = petgraph::Graph; @@ -34,15 +34,17 @@ pub async fn build_full_network_v2( let uisp_data = UispData::fetch_uisp_data(config.clone(), ip_ranges).await?; // Report on obvious UISP errors that should be fixed - let _trouble = crate::strategies::ap_site::find_troublesome_sites(&uisp_data).await + let _trouble = crate::strategies::ap_site::find_troublesome_sites(&uisp_data) + .await .map_err(|e| { - error!("Error finding troublesome sites"); - error!("{e:?}"); - UispIntegrationError::UnknownSiteType - })?; + error!("Error finding troublesome sites"); + error!("{e:?}"); + UispIntegrationError::UnknownSiteType + })?; // Load overrides - let bandwidth_overrides = crate::strategies::full::bandwidth_overrides::get_site_bandwidth_overrides(&config)?; + let bandwidth_overrides = + crate::strategies::full::bandwidth_overrides::get_site_bandwidth_overrides(&config)?; let routing_overrides = crate::strategies::full::routes_override::get_route_overrides(&config)?; // Create a new graph @@ -54,7 +56,13 @@ pub async fn build_full_network_v2( // Add all sites to the graph let mut site_map = HashMap::new(); let mut root_idx = None; - add_all_sites_to_graph(&uisp_data, &mut graph, &root_site_name, &mut site_map, &mut root_idx); + add_all_sites_to_graph( + &uisp_data, + &mut graph, + &root_site_name, + &mut site_map, + &mut root_idx, + ); let root_idx = root_idx.expect("Root site not found"); // Iterate all UISP devices and if their parent site is in the graph, add them @@ -65,21 +73,16 @@ pub async fn build_full_network_v2( add_device_links_to_graph(&uisp_data, &mut graph, &mut device_map); // Now we iterate only sites, looking for connectivity to the root - let orphans = graph.add_node(GraphMapping::GeneratedSite{ name: "Orphans".to_string()}); + let orphans = graph.add_node(GraphMapping::GeneratedSite { + name: "Orphans".to_string(), + }); graph.add_edge(root_idx, orphans, LinkMapping::Ethernet); for (_, site_ref) in site_map.iter() { if *site_ref == root_idx { continue; } - let a_star_run = petgraph::algo::astar( - &graph, - *site_ref, - |n| { - n.id() == root_idx.id() - }, - |_| 0, - |_| 0, - ); + let a_star_run = + petgraph::algo::astar(&graph, *site_ref, |n| n.id() == root_idx.id(), |_| 0, |_| 0); if a_star_run.is_none() { warn!( @@ -96,7 +99,11 @@ pub async fn build_full_network_v2( // Find the APs that have clients let mut aps_with_clients = HashSet::new(); for (ap_name, _client_ids) in client_mappings.iter() { - let Some(ap_device) = uisp_data.devices_raw.iter().find(|d| d.get_name().unwrap_or_default() == *ap_name) else { + let Some(ap_device) = uisp_data + .devices_raw + .iter() + .find(|d| d.get_name().unwrap_or_default() == *ap_name) + else { // Orphaning is already handled continue; }; @@ -106,11 +113,11 @@ pub async fn build_full_network_v2( // Count linkages to APs let mut ap_link_count = HashMap::::new(); for edge_ref in graph.edge_references() { - if let GraphMapping::AccessPoint{ref id, ..} = graph[edge_ref.source()] { + if let GraphMapping::AccessPoint { ref id, .. } = graph[edge_ref.source()] { let entry = ap_link_count.entry(id.clone()).or_insert(0); *entry += 1; }; - if let GraphMapping::AccessPoint{ref id, ..} = graph[edge_ref.target()] { + if let GraphMapping::AccessPoint { ref id, .. } = graph[edge_ref.target()] { let entry = ap_link_count.entry(id.clone()).or_insert(0); *entry += 1; }; @@ -129,7 +136,10 @@ pub async fn build_full_network_v2( } to_remove.push(*ap_ref); } - info!("Removing {} APs with no clients or only one link", to_remove.len()); + info!( + "Removing {} APs with no clients or only one link", + to_remove.len() + ); for ap_ref in to_remove.iter() { graph.remove_node(*ap_ref); } @@ -145,36 +155,52 @@ pub async fn build_full_network_v2( continue; } match &graph[node] { - GraphMapping::GeneratedSite{name} | GraphMapping::Site{name, ..} | - GraphMapping::AccessPoint{name, ..} => { + GraphMapping::GeneratedSite { name } + | GraphMapping::Site { name, .. } + | GraphMapping::AccessPoint { name, .. } => { let route = petgraph::algo::astar( &graph, root_idx, |n| n == node, - |e| (10_000u64).saturating_sub(link_capacity_mbps(&e.weight(), &uisp_data.devices, &routing_overrides)), + |e| { + (10_000u64).saturating_sub(link_capacity_mbps( + &e.weight(), + &uisp_data.devices, + &routing_overrides, + )) + }, |_| 0, - ).unwrap_or((0, vec![])); + ) + .unwrap_or((0, vec![])); if route.1.is_empty() { //println!("No path detected from {:?} to {}", graph[node], root_site_name); - parents.insert(name.to_owned(), NetJsonParent { - parent_name: "Orphans".to_string(), - mapping: &graph[node], - download: config.queues.generated_pn_download_mbps, - upload: config.queues.generated_pn_upload_mbps, - }); + parents.insert( + name.to_owned(), + NetJsonParent { + parent_name: "Orphans".to_string(), + mapping: &graph[node], + download: config.queues.generated_pn_download_mbps, + upload: config.queues.generated_pn_upload_mbps, + }, + ); } else { - let mut capacity = (config.queues.generated_pn_download_mbps,config.queues.generated_pn_upload_mbps); - if !config.uisp_integration.ignore_calculated_capacity { - match &graph[node] { - GraphMapping::AccessPoint { id, .. } => { - if let Some(device) = uisp_data.devices.iter().find(|d| d.id == *id) { - capacity = (device.download, device.upload); - if let Some(bw_override) = bandwidth_overrides.get(&device.name) { - capacity = (bw_override.0 as u64, bw_override.1 as u64); - } + let mut capacity = ( + config.queues.generated_pn_download_mbps, + config.queues.generated_pn_upload_mbps, + ); + if !config.uisp_integration.ignore_calculated_capacity { + match &graph[node] { + GraphMapping::AccessPoint { id, .. } => { + if let Some(device) = uisp_data.devices.iter().find(|d| d.id == *id) + { + capacity = (device.download, device.upload); + if let Some(bw_override) = bandwidth_overrides.get(&device.name) + { + capacity = (bw_override.0 as u64, bw_override.1 as u64); } } + } _ => {} } } @@ -183,12 +209,15 @@ pub async fn build_full_network_v2( // We need the weight from node to parent_node in the graph edges if let Some(_edge) = graph.find_edge(parent_node, node) { let parent = graph[route.1[route.1.len() - 2]].name(); - parents.insert(name.to_owned(), NetJsonParent { - parent_name: parent, - mapping: &graph[node], - download: capacity.0, - upload: capacity.1, - }); + parents.insert( + name.to_owned(), + NetJsonParent { + parent_name: parent, + mapping: &graph[node], + download: capacity.0, + upload: capacity.1, + }, + ); } else { panic!("DID NOT FIND THE EDGE"); } @@ -200,14 +229,14 @@ pub async fn build_full_network_v2( // Write the network.json file let mut network_json = serde_json::Map::new(); - for (name, node_info) in parents.iter().filter(|(_name, parent)| parent.parent_name == root_site_name) { - network_json.insert(name.into(), walk_parents( - &parents, - name, - &node_info, - &config, - &graph, - ).into()); + for (name, node_info) in parents + .iter() + .filter(|(_name, parent)| parent.parent_name == root_site_name) + { + network_json.insert( + name.into(), + walk_parents(&parents, name, &node_info, &config, &graph).into(), + ); } let network_path = Path::new(&config.lqos_directory).join("network.json"); if network_path.exists() && !config.integration_common.always_overwrite_network_json { @@ -240,10 +269,14 @@ pub async fn build_full_network_v2( continue; } - let download = (site.max_down_mbps as f32) * config.uisp_integration.bandwidth_overhead_factor; - let upload = (site.max_up_mbps as f32) * config.uisp_integration.bandwidth_overhead_factor; - let download_min = (download * config.uisp_integration.commit_bandwidth_multiplier) as u64; - let upload_min = (upload * config.uisp_integration.commit_bandwidth_multiplier) as u64; + let download = + (site.max_down_mbps as f32) * config.uisp_integration.bandwidth_overhead_factor; + let upload = + (site.max_up_mbps as f32) * config.uisp_integration.bandwidth_overhead_factor; + let download_min = + (download * config.uisp_integration.commit_bandwidth_multiplier) as u64; + let upload_min = + (upload * config.uisp_integration.commit_bandwidth_multiplier) as u64; let download_max = download as u64; let upload_max = upload as u64; @@ -285,7 +318,11 @@ pub async fn build_full_network_v2( Ok(()) } -fn add_device_links_to_graph(uisp_data: &UispData, graph: &mut Graph, device_map: &mut HashMap) { +fn add_device_links_to_graph( + uisp_data: &UispData, + graph: &mut Graph, + device_map: &mut HashMap, +) { for link in uisp_data.data_links_raw.iter() { let Some(from_device) = &link.from.device else { continue; @@ -303,9 +340,19 @@ fn add_device_links_to_graph(uisp_data: &UispData, graph: &mut Graph, site_map: &mut HashMap, device_map: &mut HashMap) { +fn add_devices_to_graph( + uisp_data: &UispData, + graph: &mut Graph, + site_map: &mut HashMap, + device_map: &mut HashMap, +) { for device in uisp_data.devices_raw.iter() { let Some(site_id) = &device.identification.site else { continue; @@ -339,7 +398,13 @@ fn add_devices_to_graph(uisp_data: &UispData, graph: &mut Graph, root_site_name: &String, site_map: &mut HashMap, root_idx: &mut Option) { +pub fn add_all_sites_to_graph( + uisp_data: &UispData, + graph: &mut Graph, + root_site_name: &String, + site_map: &mut HashMap, + root_idx: &mut Option, +) { for site in uisp_data.sites_raw.iter().filter(|s| !s.is_client_site()) { let site_name = site.name_or_blank(); let id = site.id.clone(); @@ -363,20 +428,30 @@ pub fn add_all_sites_to_graph(uisp_data: &UispData, graph: &mut Graph u64 { +fn link_capacity_mbps( + link_mapping: &LinkMapping, + devices: &[UispDevice], + route_overrides: &[RouteOverride], +) -> u64 { match link_mapping { LinkMapping::Ethernet => 10_000, LinkMapping::DevicePair(device_a, device_b) => { - let capacity ; + let capacity; if let Some(device_a) = devices.iter().find(|d| d.id == *device_a) { - if let Some(override_a) = route_overrides.iter().find(|o| o.from_site == device_a.name || o.to_site == device_a.name) { + if let Some(override_a) = route_overrides + .iter() + .find(|o| o.from_site == device_a.name || o.to_site == device_a.name) + { capacity = override_a.cost as u64; } else { capacity = device_a.download; } } else if let Some(device_b) = devices.iter().find(|d| d.id == *device_b) { - if let Some(override_b) = route_overrides.iter().find(|o| o.from_site == device_b.name || o.to_site == device_b.name) { + if let Some(override_b) = route_overrides + .iter() + .find(|o| o.from_site == device_b.name || o.to_site == device_b.name) + { capacity = override_b.cost as u64; } else { capacity = device_b.download; diff --git a/src/rust/uisp_integration/src/strategies/full2/dot.rs b/src/rust/uisp_integration/src/strategies/full2/dot.rs index aeb2823e..f0521548 100644 --- a/src/rust/uisp_integration/src/strategies/full2/dot.rs +++ b/src/rust/uisp_integration/src/strategies/full2/dot.rs @@ -1,10 +1,13 @@ -use std::fs::write; use crate::errors::UispIntegrationError; use crate::strategies::full2::GraphType; +use std::fs::write; pub fn save_dot_file(graph: &GraphType) -> Result<(), UispIntegrationError> { // Save the dot file - let dot_data = format!("{:?}", petgraph::dot::Dot::with_config(graph, &[petgraph::dot::Config::EdgeNoLabel])); + let dot_data = format!( + "{:?}", + petgraph::dot::Dot::with_config(graph, &[petgraph::dot::Config::EdgeNoLabel]) + ); let _ = write("graph.dot", dot_data.as_bytes()); let _ = std::process::Command::new("dot") .arg("-Tpng") @@ -13,4 +16,4 @@ pub fn save_dot_file(graph: &GraphType) -> Result<(), UispIntegrationError> { .arg("graph.png") .output(); Ok(()) -} \ No newline at end of file +} diff --git a/src/rust/uisp_integration/src/strategies/full2/graph_mapping.rs b/src/rust/uisp_integration/src/strategies/full2/graph_mapping.rs index 853a1666..1de9deb6 100644 --- a/src/rust/uisp_integration/src/strategies/full2/graph_mapping.rs +++ b/src/rust/uisp_integration/src/strategies/full2/graph_mapping.rs @@ -2,10 +2,22 @@ use serde::Serialize; #[derive(Debug, Ord, PartialOrd, Eq, PartialEq, Clone, Serialize)] pub enum GraphMapping { - Root { name: String, id: String }, - Site { name: String, id: String }, - GeneratedSite { name: String }, - AccessPoint { name: String, id: String, site_name: String }, + Root { + name: String, + id: String, + }, + Site { + name: String, + id: String, + }, + GeneratedSite { + name: String, + }, + AccessPoint { + name: String, + id: String, + site_name: String, + }, } impl GraphMapping { @@ -17,4 +29,4 @@ impl GraphMapping { GraphMapping::AccessPoint { name, .. } => name.clone(), } } -} \ No newline at end of file +} diff --git a/src/rust/uisp_integration/src/strategies/full2/link_mapping.rs b/src/rust/uisp_integration/src/strategies/full2/link_mapping.rs index b07356f7..161815aa 100644 --- a/src/rust/uisp_integration/src/strategies/full2/link_mapping.rs +++ b/src/rust/uisp_integration/src/strategies/full2/link_mapping.rs @@ -4,4 +4,4 @@ use serde::Serialize; pub enum LinkMapping { Ethernet, DevicePair(String, String), -} \ No newline at end of file +} diff --git a/src/rust/uisp_integration/src/strategies/full2/net_json_parent.rs b/src/rust/uisp_integration/src/strategies/full2/net_json_parent.rs index ceeb13e4..517acf78 100644 --- a/src/rust/uisp_integration/src/strategies/full2/net_json_parent.rs +++ b/src/rust/uisp_integration/src/strategies/full2/net_json_parent.rs @@ -1,8 +1,8 @@ +use crate::strategies::full2::GraphType; +use crate::strategies::full2::graph_mapping::GraphMapping; +use lqos_config::Config; use std::collections::HashMap; use std::sync::Arc; -use lqos_config::Config; -use crate::strategies::full2::graph_mapping::GraphMapping; -use crate::strategies::full2::GraphType; #[derive(Debug)] pub struct NetJsonParent<'a> { @@ -33,7 +33,11 @@ pub fn walk_parents( GraphMapping::GeneratedSite { .. } => { map.insert("type".into(), "Site".into()); } - GraphMapping::AccessPoint { name: _, id, site_name } => { + GraphMapping::AccessPoint { + name: _, + id, + site_name, + } => { map.insert("type".into(), "AP".into()); map.insert("parent_site".into(), site_name.clone().into()); map.insert("uisp_device".into(), id.clone().into()); @@ -41,8 +45,10 @@ pub fn walk_parents( } let mut children = serde_json::Map::new(); - for (name, node_info) in parents.iter().filter(|(_, node_info)| - node_info.parent_name == *name) { + for (name, node_info) in parents + .iter() + .filter(|(_, node_info)| node_info.parent_name == *name) + { let child = walk_parents(parents, name, &node_info, config, graph); children.insert(name.into(), child.into()); } @@ -50,4 +56,4 @@ pub fn walk_parents( map.insert("children".into(), children.into()); map -} \ No newline at end of file +} diff --git a/src/rust/uisp_integration/src/strategies/mod.rs b/src/rust/uisp_integration/src/strategies/mod.rs index 8d0e777f..38c0d240 100644 --- a/src/rust/uisp_integration/src/strategies/mod.rs +++ b/src/rust/uisp_integration/src/strategies/mod.rs @@ -1,8 +1,8 @@ -mod flat; -mod full; mod ap_only; mod ap_site; mod common; +mod flat; +mod full; mod full2; use crate::blackboard; -- knotmirror 0.0.1 From 50647117d3a5b4cc20c273d818f2da91575c6176 Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Tue, 8 Apr 2025 08:55:44 -0500 Subject: [PATCH 30/42] Feat: better verbage for loading and applying bandwidth overrides. --- .../uisp_integration/src/strategies/full/bandwidth_overrides.rs | 2 +- src/rust/uisp_integration/src/strategies/full2.rs | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/rust/uisp_integration/src/strategies/full/bandwidth_overrides.rs b/src/rust/uisp_integration/src/strategies/full/bandwidth_overrides.rs index 0908aeec..d448cfd7 100644 --- a/src/rust/uisp_integration/src/strategies/full/bandwidth_overrides.rs +++ b/src/rust/uisp_integration/src/strategies/full/bandwidth_overrides.rs @@ -56,7 +56,7 @@ pub fn get_site_bandwidth_overrides( let parent_node = result[0].to_string(); if let Some(d) = numeric_string_to_f32(&result[1]) { if let Some(u) = numeric_string_to_f32(&result[2]) { - info!("Using bandiwdth override: {}, {}/{}", parent_node, d, u); + info!("Loaded bandiwdth override: {}, {}/{}", parent_node, d, u); overrides.insert(parent_node, (d, u)); } else { error!("Cannot parse {} as float on line {line}", &result[2]); diff --git a/src/rust/uisp_integration/src/strategies/full2.rs b/src/rust/uisp_integration/src/strategies/full2.rs index 6b7836ca..2f4f97e0 100644 --- a/src/rust/uisp_integration/src/strategies/full2.rs +++ b/src/rust/uisp_integration/src/strategies/full2.rs @@ -197,6 +197,7 @@ pub async fn build_full_network_v2( capacity = (device.download, device.upload); if let Some(bw_override) = bandwidth_overrides.get(&device.name) { + info!("Applying bandwidth override for {}", device.name); capacity = (bw_override.0 as u64, bw_override.1 as u64); } } -- knotmirror 0.0.1 From 0fc6fa48526ada8d679f98eb343813a4e049c654 Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Tue, 8 Apr 2025 09:56:41 -0500 Subject: [PATCH 31/42] Feat: better verbage for loading and applying bandwidth overrides. --- src/rust/uisp_integration/src/strategies/full2.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/rust/uisp_integration/src/strategies/full2.rs b/src/rust/uisp_integration/src/strategies/full2.rs index 2f4f97e0..a2314e5d 100644 --- a/src/rust/uisp_integration/src/strategies/full2.rs +++ b/src/rust/uisp_integration/src/strategies/full2.rs @@ -198,7 +198,9 @@ pub async fn build_full_network_v2( if let Some(bw_override) = bandwidth_overrides.get(&device.name) { info!("Applying bandwidth override for {}", device.name); + info!("Capacity was: {} / {}", capacity.0, capacity.1); capacity = (bw_override.0 as u64, bw_override.1 as u64); + info!("Capacity is now: {} / {}", capacity.0, capacity.1); } } } -- knotmirror 0.0.1 From e89dfd45b9ce24b50de132f9425b2219cce7c58a Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Tue, 8 Apr 2025 10:15:02 -0500 Subject: [PATCH 32/42] WIP: trying to diagnose blackboard submission issue. --- src/rust/uisp_integration/src/blackboard.rs | 5 ++++- src/rust/uisp_integration/src/strategies/ap_site.rs | 4 ++-- src/rust/uisp_integration/src/strategies/full2.rs | 12 +++++++++++- 3 files changed, 17 insertions(+), 4 deletions(-) diff --git a/src/rust/uisp_integration/src/blackboard.rs b/src/rust/uisp_integration/src/blackboard.rs index 958f7c05..ba62398a 100644 --- a/src/rust/uisp_integration/src/blackboard.rs +++ b/src/rust/uisp_integration/src/blackboard.rs @@ -37,7 +37,10 @@ pub async fn blackboard_blob(key: &str, value: T) -> anyhow::Resul part: i, blob: chunk.to_vec(), }]; - let _ = lqos_bus::bus_request(req).await; + let err = lqos_bus::bus_request(req).await; + if let Err(e) = err { + tracing::error!("Error writing to blackboard (only an error if lqosd is running): {e:?}"); + } } Ok(()) } diff --git a/src/rust/uisp_integration/src/strategies/ap_site.rs b/src/rust/uisp_integration/src/strategies/ap_site.rs index ac278985..b7939d6e 100644 --- a/src/rust/uisp_integration/src/strategies/ap_site.rs +++ b/src/rust/uisp_integration/src/strategies/ap_site.rs @@ -280,8 +280,8 @@ pub(crate) async fn find_troublesome_sites(data: &UispData) -> anyhow::Result::new(); -- knotmirror 0.0.1 From f69a038f988b8fe09c7346555b3fb0a410464ec5 Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Tue, 8 Apr 2025 10:36:57 -0500 Subject: [PATCH 33/42] Fix: site bandwidth overrides should work now. --- src/rust/uisp_integration/src/strategies/full2.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/rust/uisp_integration/src/strategies/full2.rs b/src/rust/uisp_integration/src/strategies/full2.rs index bcd4c3cd..3c6f0dcd 100644 --- a/src/rust/uisp_integration/src/strategies/full2.rs +++ b/src/rust/uisp_integration/src/strategies/full2.rs @@ -201,6 +201,14 @@ pub async fn build_full_network_v2( ); if !config.uisp_integration.ignore_calculated_capacity { match &graph[node] { + GraphMapping::Site { name, .. } => { + if let Some(bw_override) = bandwidth_overrides.get(name) { + info!("Applying bandwidth override for {}", name); + info!("Capacity was: {} / {}", capacity.0, capacity.1); + capacity = (bw_override.0 as u64, bw_override.1 as u64); + info!("Capacity is now: {} / {}", capacity.0, capacity.1); + } + } GraphMapping::AccessPoint { id, .. } => { if let Some(device) = uisp_data.devices.iter().find(|d| d.id == *id) { -- knotmirror 0.0.1 From c8dc935702c1c8f4f5a7ac3f35751e1e07c05fb7 Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Tue, 8 Apr 2025 10:45:06 -0500 Subject: [PATCH 34/42] WIP: Blackboard test --- src/rust/uisp_integration/src/strategies/ap_site.rs | 4 ++-- src/rust/uisp_integration/src/strategies/full2.rs | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/rust/uisp_integration/src/strategies/ap_site.rs b/src/rust/uisp_integration/src/strategies/ap_site.rs index b7939d6e..3e1e5b79 100644 --- a/src/rust/uisp_integration/src/strategies/ap_site.rs +++ b/src/rust/uisp_integration/src/strategies/ap_site.rs @@ -280,8 +280,8 @@ pub(crate) async fn find_troublesome_sites(data: &UispData) -> anyhow::Result::new(); -- knotmirror 0.0.1 From 3ef7f01144ef4b2a52a0f9250fe45f63e0fcc77d Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Wed, 9 Apr 2025 10:17:39 -0500 Subject: [PATCH 35/42] Feature: routing is now bi-directional on a directed graph, giving a graph from which one can plot "from any point to any other point" (needed for multi-homing). Bandwidth formula of "min(path)". --- .../uisp_integration/src/strategies/full2.rs | 258 ++++++++++++------ .../src/strategies/full2/link_mapping.rs | 17 +- 2 files changed, 196 insertions(+), 79 deletions(-) diff --git a/src/rust/uisp_integration/src/strategies/full2.rs b/src/rust/uisp_integration/src/strategies/full2.rs index 476ad328..f7aeaa90 100644 --- a/src/rust/uisp_integration/src/strategies/full2.rs +++ b/src/rust/uisp_integration/src/strategies/full2.rs @@ -17,14 +17,14 @@ use crate::uisp_types::UispDevice; use lqos_config::Config; use petgraph::graph::NodeIndex; use petgraph::visit::{EdgeRef, NodeRef}; -use petgraph::{Graph, Undirected}; +use petgraph::{Directed, Graph, Undirected}; use std::collections::{HashMap, HashSet}; use std::fs::write; use std::path::Path; use std::sync::Arc; use tracing::{error, info, warn}; -type GraphType = petgraph::Graph; +type GraphType = petgraph::Graph; pub async fn build_full_network_v2( config: Arc, @@ -58,7 +58,7 @@ pub async fn build_full_network_v2( let routing_overrides = crate::strategies::full::routes_override::get_route_overrides(&config)?; // Create a new graph - let mut graph = GraphType::new_undirected(); + let mut graph = GraphType::new(); // Find the root let root_site_name = config.uisp_integration.site.clone(); @@ -77,16 +77,17 @@ pub async fn build_full_network_v2( // Iterate all UISP devices and if their parent site is in the graph, add them let mut device_map = HashMap::new(); - add_devices_to_graph(&uisp_data, &mut graph, &mut site_map, &mut device_map); + add_devices_to_graph(&uisp_data, &mut graph, &mut site_map, &mut device_map, &config); // Now we iterate all the data links looking for DEVICE linkage - add_device_links_to_graph(&uisp_data, &mut graph, &mut device_map); + add_device_links_to_graph(&uisp_data, &mut graph, &mut device_map, &config); // Now we iterate only sites, looking for connectivity to the root let orphans = graph.add_node(GraphMapping::GeneratedSite { name: "Orphans".to_string(), }); - graph.add_edge(root_idx, orphans, LinkMapping::Ethernet); + graph.add_edge(root_idx, orphans, LinkMapping::ethernet(config.queues.generated_pn_download_mbps)); + graph.add_edge(orphans, root_idx, LinkMapping::ethernet(config.queues.generated_pn_upload_mbps)); for (_, site_ref) in site_map.iter() { if *site_ref == root_idx { continue; @@ -99,7 +100,8 @@ pub async fn build_full_network_v2( "No path is detected from {:?} to {}", graph[*site_ref], root_site_name ); - graph.add_edge(*site_ref, orphans, LinkMapping::Ethernet); + graph.add_edge(*site_ref, orphans, LinkMapping::ethernet(config.queues.generated_pn_download_mbps)); + graph.add_edge(orphans, *site_ref, LinkMapping::ethernet(config.queues.generated_pn_upload_mbps)); } } @@ -168,12 +170,13 @@ pub async fn build_full_network_v2( GraphMapping::GeneratedSite { name } | GraphMapping::Site { name, .. } | GraphMapping::AccessPoint { name, .. } => { - let route = petgraph::algo::astar( + // Generate two routes - one per direction + let route_from_root_to_node = petgraph::algo::astar( &graph, root_idx, |n| n == node, |e| { - (10_000u64).saturating_sub(link_capacity_mbps( + (10_000u64).saturating_sub(link_capacity_mbps_for_routing( &e.weight(), &uisp_data.devices, &routing_overrides, @@ -183,7 +186,30 @@ pub async fn build_full_network_v2( ) .unwrap_or((0, vec![])); - if route.1.is_empty() { + let route_from_node_to_root = petgraph::algo::astar( + &graph, + node, + |n| n == root_idx, + |e| { + (10_000u64).saturating_sub(link_capacity_mbps_for_routing( + &e.weight(), + &uisp_data.devices, + &routing_overrides, + )) + }, + |_| 0, + ) + .unwrap_or((0, vec![])); + + // println!("From node to root:"); + // println!("{:?}", route_from_node_to_root); + // println!("{:?}", edges_from_node_path(&graph, &route_from_node_to_root.1)); + // + // println!("From root to node:"); + // println!("{:?}", route_from_root_to_node); + // println!("{:?}", edges_from_node_path(&graph, &route_from_root_to_node.1)); + + if route_from_root_to_node.1.is_empty() { //println!("No path detected from {:?} to {}", graph[node], root_site_name); parents.insert( name.to_owned(), @@ -195,48 +221,46 @@ pub async fn build_full_network_v2( }, ); } else { - let mut capacity = ( - config.queues.generated_pn_download_mbps, - config.queues.generated_pn_upload_mbps, - ); - if !config.uisp_integration.ignore_calculated_capacity { - match &graph[node] { - GraphMapping::Site { name, .. } => { - if let Some(bw_override) = bandwidth_overrides.get(name) { - info!("Applying bandwidth override for {}", name); - info!("Capacity was: {} / {}", capacity.0, capacity.1); - capacity = (bw_override.0 as u64, bw_override.1 as u64); - info!("Capacity is now: {} / {}", capacity.0, capacity.1); - } - } - GraphMapping::AccessPoint { id, .. } => { - if let Some(device) = uisp_data.devices.iter().find(|d| d.id == *id) - { - capacity = (device.download, device.upload); - if let Some(bw_override) = bandwidth_overrides.get(&device.name) - { - info!("Applying bandwidth override for {}", device.name); - info!("Capacity was: {} / {}", capacity.0, capacity.1); - capacity = (bw_override.0 as u64, bw_override.1 as u64); - info!("Capacity is now: {} / {}", capacity.0, capacity.1); - } - } - } - _ => {} + // Obtain capacities from route traversal + let mut download_capacity = min_capacity_along_route(&graph, &route_from_root_to_node.1); + let mut upload_capacity = min_capacity_along_route(&graph, &route_from_node_to_root.1); + + // 0 isn't possible + if download_capacity < 1 { + download_capacity = config.queues.generated_pn_download_mbps; + } + if upload_capacity < 1 { + upload_capacity = config.queues.generated_pn_upload_mbps; + } + + // Ignore option + if config.uisp_integration.ignore_calculated_capacity { + download_capacity = config.queues.generated_pn_download_mbps; + upload_capacity = config.queues.generated_pn_upload_mbps; + } + + // Overrides + if !bandwidth_overrides.is_empty() { + if let Some(bw_override) = bandwidth_overrides.get(name) { + info!("Applying bandwidth override for {}", name); + info!("Capacity was: {} / {}", download_capacity, upload_capacity); + download_capacity = bw_override.0 as u64; + upload_capacity = bw_override.1 as u64; + info!("Capacity is now: {} / {}", download_capacity, upload_capacity); } } - let parent_node = route.1[route.1.len() - 2]; + let parent_node = route_from_root_to_node.1[route_from_root_to_node.1.len() - 2]; // We need the weight from node to parent_node in the graph edges if let Some(_edge) = graph.find_edge(parent_node, node) { - let parent = graph[route.1[route.1.len() - 2]].name(); + let parent = graph[route_from_root_to_node.1[route_from_root_to_node.1.len() - 2]].name(); parents.insert( name.to_owned(), NetJsonParent { parent_name: parent, mapping: &graph[node], - download: capacity.0, - upload: capacity.1, + download: download_capacity, + upload: upload_capacity, }, ); } else { @@ -301,12 +325,20 @@ pub async fn build_full_network_v2( let download_max = download as u64; let upload_max = upload as u64; + let parent_node = { + if parents.get(&ap_device.name).is_some() { + ap_device.name.clone() + } else { + "Orphans".to_string() + } + }; + let shaped_device = ShapedDevice { circuit_id: site.id.to_owned(), circuit_name: site.name.to_owned(), device_id: device.id.to_owned(), device_name: device.name.to_owned(), - parent_node: ap_device.name.to_owned(), + parent_node, mac: device.mac.to_owned(), ipv4: device.ipv4_list(), ipv6: device.ipv6_list(), @@ -341,8 +373,9 @@ pub async fn build_full_network_v2( fn add_device_links_to_graph( uisp_data: &UispData, - graph: &mut Graph, + graph: &mut GraphType, device_map: &mut HashMap, + config: &Arc, ) { for link in uisp_data.data_links_raw.iter() { let Some(from_device) = &link.from.device else { @@ -383,22 +416,55 @@ fn add_device_links_to_graph( // If the edge already exists, we don't need to add it continue; } + if graph.contains_edge(*b_ref, *a_ref) { + // If the edge already exists, we don't need to add it + continue; + } + + let (down, up) = get_capacity_from_datalink_device( + &from_device.identification.id, + &uisp_data.devices, + &config, + ); graph.add_edge( *a_ref, *b_ref, - LinkMapping::DevicePair( - from_device.identification.id.clone(), - to_device.identification.id.clone(), - ), + LinkMapping::DevicePair { + device_a: from_device.identification.id.clone(), + device_b: to_device.identification.id.clone(), + speed_mbps: down, + }, + ); + graph.add_edge( + *b_ref, + *a_ref, + LinkMapping::DevicePair { + device_b: from_device.identification.id.clone(), + device_a: to_device.identification.id.clone(), + speed_mbps: up, + }, ); } } +fn get_capacity_from_datalink_device( + device_id: &str, + devices: &[UispDevice], + config: &Arc, +) -> (u64, u64) { + if let Some(device) = devices.iter().find(|d| d.id == device_id) { + return (device.download, device.upload); + } + + (config.queues.generated_pn_download_mbps, config.queues.generated_pn_upload_mbps) +} + fn add_devices_to_graph( uisp_data: &UispData, - graph: &mut Graph, + graph: &mut GraphType, site_map: &mut HashMap, device_map: &mut HashMap, + config: &Arc, ) { for device in uisp_data.devices_raw.iter() { let Some(site_id) = &device.identification.site else { @@ -415,13 +481,14 @@ fn add_devices_to_graph( }; let device_ref = graph.add_node(device_entry); device_map.insert(device.identification.id.clone(), device_ref); - let _ = graph.add_edge(device_ref, *site_ref, LinkMapping::Ethernet); + let _ = graph.add_edge(device_ref, *site_ref, LinkMapping::ethernet(config.queues.generated_pn_download_mbps)); + let _ = graph.add_edge(*site_ref, device_ref, LinkMapping::ethernet(config.queues.generated_pn_upload_mbps)); } } pub fn add_all_sites_to_graph( uisp_data: &UispData, - graph: &mut Graph, + graph: &mut GraphType, root_site_name: &String, site_map: &mut HashMap, root_idx: &mut Option, @@ -449,39 +516,76 @@ pub fn add_all_sites_to_graph( } } -fn link_capacity_mbps( +fn link_capacity_mbps_for_routing( link_mapping: &LinkMapping, devices: &[UispDevice], route_overrides: &[RouteOverride], ) -> u64 { match link_mapping { - LinkMapping::Ethernet => 10_000, - LinkMapping::DevicePair(device_a, device_b) => { - let capacity; - - if let Some(device_a) = devices.iter().find(|d| d.id == *device_a) { - if let Some(override_a) = route_overrides - .iter() - .find(|o| o.from_site == device_a.name || o.to_site == device_a.name) - { - capacity = override_a.cost as u64; - } else { - capacity = device_a.download; - } - } else if let Some(device_b) = devices.iter().find(|d| d.id == *device_b) { - if let Some(override_b) = route_overrides - .iter() - .find(|o| o.from_site == device_b.name || o.to_site == device_b.name) - { - capacity = override_b.cost as u64; - } else { - capacity = device_b.download; - } - } else { - capacity = 10_000; + LinkMapping::Ethernet { speed_mbps } => *speed_mbps, + LinkMapping::DevicePair { speed_mbps, device_a, device_b } => { + // Check for overrides: make sure we have both devices (we need names, are storing IDs) + let Some(device_a) = devices.iter().find(|d| d.id == *device_a) else { + return *speed_mbps; + }; + let Some(device_b) = devices.iter().find(|d| d.id == *device_b) else { + return *speed_mbps; + }; + + // Check for the direct direction + if let Some(route_override) = route_overrides + .iter() + .find(|route_override| + (route_override.from_site == device_a.name || route_override.to_site == device_a.name) + && (route_override.from_site == device_b.name || route_override.to_site == device_b.name) + ) { + return route_override.cost as u64; + } + + // Check for the reverse direction + if let Some(route_override) = route_overrides + .iter() + .find(|route_override| + (route_override.from_site == device_b.name || route_override.to_site == device_b.name) + && (route_override.from_site == device_a.name || route_override.to_site == device_a.name) + ) { + return route_override.cost as u64; } - capacity + *speed_mbps } } } + +use petgraph::prelude::*; + +fn edges_from_node_path( + graph: &GraphType, + path: &[NodeIndex], +) -> Vec +{ + let mut edge_ids = Vec::new(); + for window in path.windows(2) { + let source = window[0]; + let target = window[1]; + // This assumes a directed graph; if undirected, you might need to check both directions + if let Some(edge) = graph.find_edge(source, target) { + edge_ids.push(edge); + } else { + // Handle case where no edge is found (could be error or special case) + panic!("No edge found between {:?} and {:?}", source, target); + } + } + edge_ids +} + +fn min_capacity_along_route( + graph: &GraphType, + path: &[NodeIndex], +) -> u64 { + edges_from_node_path(graph, path) + .iter() + .map(|edge| graph[*edge].capacity_mbps()) + .min() + .unwrap_or(0) +} \ No newline at end of file diff --git a/src/rust/uisp_integration/src/strategies/full2/link_mapping.rs b/src/rust/uisp_integration/src/strategies/full2/link_mapping.rs index 161815aa..9bc71b3e 100644 --- a/src/rust/uisp_integration/src/strategies/full2/link_mapping.rs +++ b/src/rust/uisp_integration/src/strategies/full2/link_mapping.rs @@ -2,6 +2,19 @@ use serde::Serialize; #[derive(Debug, Clone, Serialize)] pub enum LinkMapping { - Ethernet, - DevicePair(String, String), + Ethernet { speed_mbps: u64 }, + DevicePair { device_a: String, device_b: String, speed_mbps: u64, } } + +impl LinkMapping { + pub fn ethernet(speed_mbps: u64) -> Self { + LinkMapping::Ethernet { speed_mbps } + } + + pub fn capacity_mbps(&self) -> u64 { + match self { + LinkMapping::Ethernet { speed_mbps } => *speed_mbps, + LinkMapping::DevicePair { speed_mbps, .. } => *speed_mbps, + } + } +} \ No newline at end of file -- knotmirror 0.0.1 From a053aeef9c696847d2a7642ef68603ce1b176e6c Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Wed, 9 Apr 2025 10:59:30 -0500 Subject: [PATCH 36/42] Fix: detected AP capacities are applied to the total weight calculation. --- .../uisp_integration/src/strategies/full2.rs | 37 ++++++++++++++++++- .../src/strategies/full2/graph_mapping.rs | 2 + .../src/strategies/full2/net_json_parent.rs | 1 + 3 files changed, 39 insertions(+), 1 deletion(-) diff --git a/src/rust/uisp_integration/src/strategies/full2.rs b/src/rust/uisp_integration/src/strategies/full2.rs index f7aeaa90..88e1c6f4 100644 --- a/src/rust/uisp_integration/src/strategies/full2.rs +++ b/src/rust/uisp_integration/src/strategies/full2.rs @@ -77,7 +77,7 @@ pub async fn build_full_network_v2( // Iterate all UISP devices and if their parent site is in the graph, add them let mut device_map = HashMap::new(); - add_devices_to_graph(&uisp_data, &mut graph, &mut site_map, &mut device_map, &config); + add_devices_to_graph(&uisp_data, &mut graph, &mut site_map, &mut device_map, &config, &bandwidth_overrides); // Now we iterate all the data links looking for DEVICE linkage add_device_links_to_graph(&uisp_data, &mut graph, &mut device_map, &config); @@ -225,6 +225,14 @@ pub async fn build_full_network_v2( let mut download_capacity = min_capacity_along_route(&graph, &route_from_root_to_node.1); let mut upload_capacity = min_capacity_along_route(&graph, &route_from_node_to_root.1); + // Apply AP capacities + if let GraphMapping::AccessPoint { download_mbps, upload_mbps, .. } = &graph[node] { + //println!("AP device capacity: {download_mbps}/{upload_mbps} (prev {download_capacity}/{upload_capacity})"); + download_capacity = u64::min(download_capacity, *download_mbps); + upload_capacity = u64::min(upload_capacity, *upload_mbps); + //println!("Now: {download_capacity}/{upload_capacity}"); + } + // 0 isn't possible if download_capacity < 1 { download_capacity = config.queues.generated_pn_download_mbps; @@ -465,19 +473,45 @@ fn add_devices_to_graph( site_map: &mut HashMap, device_map: &mut HashMap, config: &Arc, + bandwidth_overrides: &BandwidthOverrides, ) { for device in uisp_data.devices_raw.iter() { let Some(site_id) = &device.identification.site else { continue; }; let site_id = &site_id.id; + let Some(device_details) = uisp_data.devices.iter().find(|d| d.id == device.identification.id) else { + continue; + }; let Some(site_ref) = site_map.get(site_id) else { continue; }; + let mut download_mbps = device_details.download; + let mut upload_mbps = device_details.upload; + + if download_mbps < 1 { + download_mbps = config.queues.generated_pn_download_mbps; + } + if upload_mbps < 1 { + upload_mbps = config.queues.generated_pn_upload_mbps; + } + + if config.uisp_integration.ignore_calculated_capacity { + download_mbps = config.queues.generated_pn_download_mbps; + upload_mbps = config.queues.generated_pn_upload_mbps; + } + + if let Some(bw_override) = bandwidth_overrides.get(&device.get_name().unwrap_or_default()) { + download_mbps = bw_override.0 as u64; + upload_mbps = bw_override.1 as u64; + } + let device_entry = GraphMapping::AccessPoint { name: device.get_name().unwrap_or_default(), id: device.identification.id.clone(), site_name: graph[*site_ref].name(), + download_mbps, + upload_mbps, }; let device_ref = graph.add_node(device_entry); device_map.insert(device.identification.id.clone(), device_ref); @@ -558,6 +592,7 @@ fn link_capacity_mbps_for_routing( } use petgraph::prelude::*; +use crate::strategies::full::bandwidth_overrides::BandwidthOverrides; fn edges_from_node_path( graph: &GraphType, diff --git a/src/rust/uisp_integration/src/strategies/full2/graph_mapping.rs b/src/rust/uisp_integration/src/strategies/full2/graph_mapping.rs index 1de9deb6..b5698dbd 100644 --- a/src/rust/uisp_integration/src/strategies/full2/graph_mapping.rs +++ b/src/rust/uisp_integration/src/strategies/full2/graph_mapping.rs @@ -17,6 +17,8 @@ pub enum GraphMapping { name: String, id: String, site_name: String, + download_mbps: u64, + upload_mbps: u64, }, } diff --git a/src/rust/uisp_integration/src/strategies/full2/net_json_parent.rs b/src/rust/uisp_integration/src/strategies/full2/net_json_parent.rs index 517acf78..347aec9f 100644 --- a/src/rust/uisp_integration/src/strategies/full2/net_json_parent.rs +++ b/src/rust/uisp_integration/src/strategies/full2/net_json_parent.rs @@ -37,6 +37,7 @@ pub fn walk_parents( name: _, id, site_name, + .. } => { map.insert("type".into(), "AP".into()); map.insert("parent_site".into(), site_name.clone().into()); -- knotmirror 0.0.1 From 98cfb6f52a66a55efa66193b3c399b3abe48a9f4 Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Wed, 9 Apr 2025 11:16:20 -0500 Subject: [PATCH 37/42] Fix: warning cleanup --- src/rust/uisp_integration/src/strategies/ap_site.rs | 2 ++ src/rust/uisp_integration/src/strategies/common.rs | 6 +++--- src/rust/uisp_integration/src/strategies/full/mod.rs | 1 + src/rust/uisp_integration/src/strategies/full2.rs | 2 +- 4 files changed, 7 insertions(+), 4 deletions(-) diff --git a/src/rust/uisp_integration/src/strategies/ap_site.rs b/src/rust/uisp_integration/src/strategies/ap_site.rs index 3e1e5b79..3533337c 100644 --- a/src/rust/uisp_integration/src/strategies/ap_site.rs +++ b/src/rust/uisp_integration/src/strategies/ap_site.rs @@ -272,7 +272,9 @@ impl Layer { } pub struct TroublesomeClients { + #[allow(dead_code)] // Used in serialization pub multi_entry_points: HashSet, + #[allow(dead_code)] // Used in serialization pub client_of_clients: HashSet, } diff --git a/src/rust/uisp_integration/src/strategies/common.rs b/src/rust/uisp_integration/src/strategies/common.rs index 8c5e699e..20020266 100644 --- a/src/rust/uisp_integration/src/strategies/common.rs +++ b/src/rust/uisp_integration/src/strategies/common.rs @@ -3,7 +3,7 @@ use crate::errors::UispIntegrationError; use crate::ip_ranges::IpRanges; use crate::strategies::full::parse::parse_uisp_datasets; use crate::strategies::full::uisp_fetch::load_uisp_data; -use crate::uisp_types::{UispDataLink, UispDevice, UispSite, UispSiteType}; +use crate::uisp_types::{UispDevice, UispSite, UispSiteType}; use lqos_config::Config; use std::collections::HashMap; use std::sync::Arc; @@ -16,7 +16,7 @@ pub(crate) struct UispData { pub data_links_raw: Vec, pub sites: Vec, pub devices: Vec, - pub data_links: Vec, + //pub data_links: Vec, } impl UispData { @@ -58,7 +58,7 @@ impl UispData { data_links_raw, sites, devices, - data_links: _data_links, + //data_links: _data_links, }) } diff --git a/src/rust/uisp_integration/src/strategies/full/mod.rs b/src/rust/uisp_integration/src/strategies/full/mod.rs index 14ef22d0..f1552261 100644 --- a/src/rust/uisp_integration/src/strategies/full/mod.rs +++ b/src/rust/uisp_integration/src/strategies/full/mod.rs @@ -1,3 +1,4 @@ +#![allow(dead_code)] mod ap_promotion; pub(crate) mod bandwidth_overrides; mod client_site_promotion; diff --git a/src/rust/uisp_integration/src/strategies/full2.rs b/src/rust/uisp_integration/src/strategies/full2.rs index 88e1c6f4..42f07c1e 100644 --- a/src/rust/uisp_integration/src/strategies/full2.rs +++ b/src/rust/uisp_integration/src/strategies/full2.rs @@ -17,7 +17,7 @@ use crate::uisp_types::UispDevice; use lqos_config::Config; use petgraph::graph::NodeIndex; use petgraph::visit::{EdgeRef, NodeRef}; -use petgraph::{Directed, Graph, Undirected}; +use petgraph::Directed; use std::collections::{HashMap, HashSet}; use std::fs::write; use std::path::Path; -- knotmirror 0.0.1 From 31fef42a9265aa56ec14a0a8a24373627f6d4a27 Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Wed, 9 Apr 2025 11:28:51 -0500 Subject: [PATCH 38/42] Fix: only display error about blackboard if compiled in debug mode --- src/rust/uisp_integration/src/blackboard.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/rust/uisp_integration/src/blackboard.rs b/src/rust/uisp_integration/src/blackboard.rs index ba62398a..7f15b3b4 100644 --- a/src/rust/uisp_integration/src/blackboard.rs +++ b/src/rust/uisp_integration/src/blackboard.rs @@ -38,6 +38,7 @@ pub async fn blackboard_blob(key: &str, value: T) -> anyhow::Resul blob: chunk.to_vec(), }]; let err = lqos_bus::bus_request(req).await; + #[cfg(debug_assertions)] if let Err(e) = err { tracing::error!("Error writing to blackboard (only an error if lqosd is running): {e:?}"); } -- knotmirror 0.0.1 From 53342087d017c44cfceb821645fe01906ab6aa48 Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Wed, 9 Apr 2025 11:30:58 -0500 Subject: [PATCH 39/42] Fix: Shaped Devices speeds have minimums. --- src/rust/uisp_integration/src/strategies/full2.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/rust/uisp_integration/src/strategies/full2.rs b/src/rust/uisp_integration/src/strategies/full2.rs index 42f07c1e..364fa216 100644 --- a/src/rust/uisp_integration/src/strategies/full2.rs +++ b/src/rust/uisp_integration/src/strategies/full2.rs @@ -333,6 +333,11 @@ pub async fn build_full_network_v2( let download_max = download as u64; let upload_max = upload as u64; + let download_min = u64::max(1, download_min); + let upload_min = u64::max(1, upload_min); + let download_max = u64::max(4, download_max); + let upload_max = u64::max(4, upload_max); + let parent_node = { if parents.get(&ap_device.name).is_some() { ap_device.name.clone() -- knotmirror 0.0.1 From 54c3b51b9d1c33ca2287a478a722806a7c8c7291 Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Wed, 9 Apr 2025 11:40:13 -0500 Subject: [PATCH 40/42] Fix: add "visited" guard to avoid circular recursion --- src/rust/uisp_integration/src/strategies/full2.rs | 3 ++- .../src/strategies/full2/net_json_parent.rs | 11 ++++++++--- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/src/rust/uisp_integration/src/strategies/full2.rs b/src/rust/uisp_integration/src/strategies/full2.rs index 364fa216..2f2aa3f1 100644 --- a/src/rust/uisp_integration/src/strategies/full2.rs +++ b/src/rust/uisp_integration/src/strategies/full2.rs @@ -282,13 +282,14 @@ pub async fn build_full_network_v2( // Write the network.json file let mut network_json = serde_json::Map::new(); + let mut visited = HashSet::new(); for (name, node_info) in parents .iter() .filter(|(_name, parent)| parent.parent_name == root_site_name) { network_json.insert( name.into(), - walk_parents(&parents, name, &node_info, &config, &graph).into(), + walk_parents(&parents, name, &node_info, &config, &graph, &mut visited).into(), ); } let network_path = Path::new(&config.lqos_directory).join("network.json"); diff --git a/src/rust/uisp_integration/src/strategies/full2/net_json_parent.rs b/src/rust/uisp_integration/src/strategies/full2/net_json_parent.rs index 347aec9f..97e7eadf 100644 --- a/src/rust/uisp_integration/src/strategies/full2/net_json_parent.rs +++ b/src/rust/uisp_integration/src/strategies/full2/net_json_parent.rs @@ -1,7 +1,7 @@ use crate::strategies::full2::GraphType; use crate::strategies::full2::graph_mapping::GraphMapping; use lqos_config::Config; -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use std::sync::Arc; #[derive(Debug)] @@ -18,6 +18,7 @@ pub fn walk_parents( node_info: &NetJsonParent, config: &Arc, graph: &GraphType, + visited: &mut HashSet, ) -> serde_json::Map { let mut map = serde_json::Map::new(); // Entries are name, type, uisp_device or site, downloadBandwidthMbps, uploadBandwidthMbps, children @@ -48,9 +49,13 @@ pub fn walk_parents( let mut children = serde_json::Map::new(); for (name, node_info) in parents .iter() - .filter(|(_, node_info)| node_info.parent_name == *name) + .filter(|(_node_name, node_info)| node_info.parent_name == *name) { - let child = walk_parents(parents, name, &node_info, config, graph); + if visited.contains(name) { + continue; + } + visited.insert(name.to_string()); + let child = walk_parents(parents, name, &node_info, config, graph, visited); children.insert(name.into(), child.into()); } -- knotmirror 0.0.1 From 84a33062f65887f210555f4f3e4453ba169022e9 Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Wed, 16 Apr 2025 10:28:18 -0500 Subject: [PATCH 41/42] FIXES #694 - Adds airmax and LTU capacity multipliers back in. --- src/rust/uisp_integration/src/uisp_types/uisp_device.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/rust/uisp_integration/src/uisp_types/uisp_device.rs b/src/rust/uisp_integration/src/uisp_types/uisp_device.rs index 52eb3fbd..ac776cbc 100644 --- a/src/rust/uisp_integration/src/uisp_types/uisp_device.rs +++ b/src/rust/uisp_integration/src/uisp_types/uisp_device.rs @@ -52,6 +52,14 @@ impl UispDevice { if let Some(ul) = overview.uplinkCapacity { upload = ul as u64 / 1000000; } + if device.get_model().unwrap_or_default().contains("R5AC") { + download = ((download as f64) * config.uisp_integration.airmax_capacity as f64) as u64; + upload = ((upload as f64) * config.uisp_integration.airmax_capacity as f64) as u64; + } + if device.get_model().unwrap_or_default().contains("LTU") { + download = ((download as f64) * config.uisp_integration.ltu_capacity as f64) as u64; + upload = ((upload as f64) * config.uisp_integration.ltu_capacity as f64) as u64; + } } if download == 0 { download = config.queues.generated_pn_download_mbps; -- knotmirror 0.0.1 From ab2b6cd6468d749992462dc8f9b25db8f2c7cb39 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Robert=20Chac=C3=B3n?= Date: Wed, 16 Apr 2025 09:50:49 -0600 Subject: [PATCH 42/42] Update uisp_device.rs --- src/rust/uisp_integration/src/uisp_types/uisp_device.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/rust/uisp_integration/src/uisp_types/uisp_device.rs b/src/rust/uisp_integration/src/uisp_types/uisp_device.rs index ac776cbc..2ee189fd 100644 --- a/src/rust/uisp_integration/src/uisp_types/uisp_device.rs +++ b/src/rust/uisp_integration/src/uisp_types/uisp_device.rs @@ -52,7 +52,7 @@ impl UispDevice { if let Some(ul) = overview.uplinkCapacity { upload = ul as u64 / 1000000; } - if device.get_model().unwrap_or_default().contains("R5AC") { + if device.get_model().unwrap_or_default().contains("5AC") { download = ((download as f64) * config.uisp_integration.airmax_capacity as f64) as u64; upload = ((upload as f64) * config.uisp_integration.airmax_capacity as f64) as u64; } -- knotmirror 0.0.1