From 5459dd320287cdd6a454abf5d359cdce61c87e4c Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Fri, 3 Oct 2025 14:36:21 -0500 Subject: [PATCH] WIP: Add in the ability to override bandwidth by site with the overrides file. --- src/rust/lqos_overrides/src/main.rs | 52 ++++++++++- src/rust/lqos_overrides/src/overrides_file.rs | 34 +++++++ src/rust/lqos_python/src/lib.rs | 27 ++++++ src/scheduler.py | 91 ++++++++++++++++++- 4 files changed, 202 insertions(+), 2 deletions(-) diff --git a/src/rust/lqos_overrides/src/main.rs b/src/rust/lqos_overrides/src/main.rs index f5a00ea5..88afda54 100644 --- a/src/rust/lqos_overrides/src/main.rs +++ b/src/rust/lqos_overrides/src/main.rs @@ -4,7 +4,7 @@ use anyhow::{anyhow, Result}; use clap::{Args, Parser, Subcommand}; use lqos_config::ShapedDevice; -use lqos_overrides::{CircuitAdjustment, OverrideFile}; +use lqos_overrides::{CircuitAdjustment, NetworkAdjustment, OverrideFile}; #[derive(Parser, Debug)] #[command(name = "lqos_overrides")] @@ -26,6 +26,11 @@ enum Commands { #[command(subcommand)] command: AdjustmentsCommand, }, + /// Manage network (network.json) adjustments + NetworkAdjustments { + #[command(subcommand)] + command: NetworkAdjustmentsCommand, + }, } #[derive(Subcommand, Debug)] @@ -58,6 +63,16 @@ enum AdjustmentsCommand { List, } +#[derive(Subcommand, Debug)] +enum NetworkAdjustmentsCommand { + /// Add site speed adjustment + AddSiteSpeed(AddSiteSpeedArgs), + /// Remove a network adjustment by index (see list) + DeleteIndex { #[arg(long)] index: usize }, + /// List current network adjustments + List, +} + #[derive(Args, Debug)] struct AddArgs { #[arg(long)] @@ -176,6 +191,16 @@ struct AddDeviceSpeedArgs { max_upload_bandwidth: Option, } +#[derive(Args, Debug, Default)] +struct AddSiteSpeedArgs { + #[arg(long)] + site_name: String, + #[arg(long)] + download_bandwidth_mbps: Option, + #[arg(long)] + upload_bandwidth_mbps: Option, +} + fn main() -> Result<()> { let cli = Cli::parse(); @@ -274,6 +299,31 @@ fn main() -> Result<()> { println!("{}", serde_json::to_string_pretty(&list)?); } }, + Commands::NetworkAdjustments { command: cmd } => match cmd { + NetworkAdjustmentsCommand::AddSiteSpeed(args) => { + let adj = NetworkAdjustment::AdjustSiteSpeed { + site_name: args.site_name, + download_bandwidth_mbps: args.download_bandwidth_mbps, + upload_bandwidth_mbps: args.upload_bandwidth_mbps, + }; + overrides.add_network_adjustment(adj); + overrides.save()?; + println!("Added site speed adjustment; overrides saved."); + } + NetworkAdjustmentsCommand::DeleteIndex { index } => { + let ok = overrides.remove_network_adjustment_by_index(index); + if ok { + overrides.save()?; + println!("Removed network adjustment at index {index}; overrides saved."); + } else { + println!("No network adjustment at index {index}."); + } + } + NetworkAdjustmentsCommand::List => { + let list = overrides.network_adjustments(); + println!("{}", serde_json::to_string_pretty(&list)?); + } + }, } Ok(()) diff --git a/src/rust/lqos_overrides/src/overrides_file.rs b/src/rust/lqos_overrides/src/overrides_file.rs index 0a3e0479..f29da9f2 100644 --- a/src/rust/lqos_overrides/src/overrides_file.rs +++ b/src/rust/lqos_overrides/src/overrides_file.rs @@ -30,14 +30,29 @@ pub enum CircuitAdjustment { ReparentCircuit { circuit_id: String, parent_node: String }, } +#[derive(Serialize, Deserialize, Clone, Debug)] +#[serde(tag = "type", rename_all = "snake_case")] +pub enum NetworkAdjustment { + AdjustSiteSpeed { + site_name: String, + download_bandwidth_mbps: Option, + upload_bandwidth_mbps: Option, + }, +} + #[derive(Serialize, Deserialize, Default)] pub struct OverrideFile { /// Devices that will be persisted into ShapedDevices.csv by the scheduler. Useful /// for adding persistent "catch all", or API-controlled new devices that are somehow detached /// from the scheduler integration. + #[serde(default, alias = "devices_to_append")] persistent_devices: Vec, /// Adjustments that the scheduler will apply to circuits/devices when persisting CSV. + #[serde(default)] circuit_adjustments: Vec, + /// Adjustments that affect network.json structure/settings. + #[serde(default)] + network_adjustments: Vec, } impl OverrideFile { @@ -77,6 +92,11 @@ impl OverrideFile { &self.circuit_adjustments } + /// Borrow the list of network adjustments without modifying the file. + pub fn network_adjustments(&self) -> &[NetworkAdjustment] { + &self.network_adjustments + } + /// Add or replace a shaped device by `device_id`. Returns true if changed. pub fn add_persistent_shaped_device_return_changed(&mut self, device: ShapedDevice) -> bool { if let Some(existing) = self @@ -124,4 +144,18 @@ impl OverrideFile { } false } + + /// Add a network adjustment entry. + pub fn add_network_adjustment(&mut self, adj: NetworkAdjustment) { + self.network_adjustments.push(adj); + } + + /// Remove a network adjustment by index. Returns true if removed. + pub fn remove_network_adjustment_by_index(&mut self, index: usize) -> bool { + if index < self.network_adjustments.len() { + self.network_adjustments.remove(index); + return true; + } + false + } } diff --git a/src/rust/lqos_python/src/lib.rs b/src/rust/lqos_python/src/lib.rs index 344ea4d8..2ad79a02 100644 --- a/src/rust/lqos_python/src/lib.rs +++ b/src/rust/lqos_python/src/lib.rs @@ -101,6 +101,7 @@ fn liblqos_python(m: &Bound<'_, PyModule>) -> PyResult<()> { m.add_function(wrap_pyfunction!(get_libreqos_directory, m)?)?; m.add_function(wrap_pyfunction!(overrides_persistent_devices, m)?)?; m.add_function(wrap_pyfunction!(overrides_circuit_adjustments, m)?)?; + m.add_function(wrap_pyfunction!(overrides_network_adjustments, m)?)?; m.add_function(wrap_pyfunction!(is_network_flat, m)?)?; m.add_function(wrap_pyfunction!(blackboard_finish, m)?)?; m.add_function(wrap_pyfunction!(blackboard_submit, m)?)?; @@ -396,6 +397,32 @@ fn overrides_circuit_adjustments(py: Python<'_>) -> PyResult> { Ok(out) } +/// Returns the list of network adjustments as Python dicts. +#[pyfunction] +fn overrides_network_adjustments(py: Python<'_>) -> PyResult> { + let overrides = match lqos_overrides::OverrideFile::load() { + Ok(o) => o, + Err(e) => return Err(PyOSError::new_err(e.to_string())), + }; + + let mut out: Vec = Vec::new(); + for adj in overrides.network_adjustments().iter() { + let d = PyDict::new(py); + match adj { + lqos_overrides::NetworkAdjustment::AdjustSiteSpeed { site_name, download_bandwidth_mbps, upload_bandwidth_mbps } => { + d.set_item("type", "adjust_site_speed")?; + d.set_item("site_name", site_name.clone())?; + if let Some(v) = download_bandwidth_mbps { d.set_item("download_bandwidth_mbps", *v)?; } + if let Some(v) = upload_bandwidth_mbps { d.set_item("upload_bandwidth_mbps", *v)?; } + } + } + let obj: PyObject = d.unbind().into(); + out.push(obj); + } + + Ok(out) +} + #[pyfunction] fn is_libre_already_running() -> PyResult { let lock_path = Path::new(LOCK_FILE); diff --git a/src/scheduler.py b/src/scheduler.py index 073f0957..23845536 100644 --- a/src/scheduler.py +++ b/src/scheduler.py @@ -2,6 +2,7 @@ import time import datetime import csv import io +import json import chardet from LibreQoS import refreshShapers, refreshShapersUpdateOnly import subprocess @@ -10,7 +11,7 @@ from io import StringIO from liblqos_python import automatic_import_uisp, automatic_import_splynx, queue_refresh_interval_mins, \ automatic_import_powercode, automatic_import_sonar, influx_db_enabled, get_libreqos_directory, \ blackboard_finish, blackboard_submit, automatic_import_wispgate, enable_insight_topology, insight_topology_role, \ - calculate_hash, scheduler_alive, scheduler_error, overrides_persistent_devices, overrides_circuit_adjustments + calculate_hash, scheduler_alive, scheduler_error, overrides_persistent_devices, overrides_circuit_adjustments, overrides_network_adjustments if automatic_import_splynx(): from integrationSplynx import importFromSplynx @@ -23,6 +24,7 @@ if automatic_import_wispgate(): from apscheduler.schedulers.background import BlockingScheduler from apscheduler.executors.pool import ThreadPoolExecutor import os.path +import os ads = BlockingScheduler(executors={'default': ThreadPoolExecutor(1)}) network_hash = 0 @@ -271,6 +273,93 @@ def apply_lqos_overrides(): write_shaped_devices_csv(path, header if header else SHAPED_DEVICES_HEADER, merged_rows) print("Updated ShapedDevices.csv with overrides") + # 3) Load, adjust, and optionally save network.json + nj_path = network_json_path() + network = load_network_json(nj_path) + net_changed = apply_network_adjustments(network) + if net_changed: + write_network_json(nj_path, network) + print("Updated network.json with overrides") + + +# --------------- Network JSON handling --------------- + +def network_json_path() -> str: + base_dir = get_libreqos_directory() + if enable_insight_topology(): + insight_path = os.path.join(base_dir, "network.insight.json") + if os.path.exists(insight_path): + return insight_path + return os.path.join(base_dir, "network.json") + + +def load_network_json(path: str): + if not os.path.isfile(path): + return {} + with open(path, 'r', encoding='utf-8') as f: + try: + return json.loads(f.read()) + except Exception: + return {} + + +def apply_network_adjustments(network: dict) -> bool: + """Apply network adjustments from overrides to the network JSON structure. + + Currently supports: adjust_site_speed (by site_name) updating + downloadBandwidthMbps and uploadBandwidthMbps at the matching node. + Returns True if any changes were applied. + """ + try: + adjustments = overrides_network_adjustments() + except Exception as e: + print(f"Failed to read network adjustments: {e}") + return False + + if not adjustments: + return False + + def adjust_node(tree: dict, site: str, dl_opt, ul_opt) -> bool: + changed_local = False + for key in list(tree.keys()): + if key == 'children': + child = tree.get('children') + if isinstance(child, dict): + if adjust_node(child, site, dl_opt, ul_opt): + changed_local = True + continue + node = tree.get(key) + if isinstance(node, dict): + if key == site: + if dl_opt is not None: + node['downloadBandwidthMbps'] = int(dl_opt) + changed_local = True + if ul_opt is not None: + node['uploadBandwidthMbps'] = int(ul_opt) + changed_local = True + # Recurse into children + if 'children' in node and isinstance(node['children'], dict): + if adjust_node(node['children'], site, dl_opt, ul_opt): + changed_local = True + return changed_local + + net_changed = False + for adj in adjustments: + if adj.get('type') == 'adjust_site_speed': + site = adj.get('site_name', '') + dl = adj.get('download_bandwidth_mbps', None) + ul = adj.get('upload_bandwidth_mbps', None) + if site: + if adjust_node(network, site, dl, ul): + net_changed = True + + return net_changed + + +def write_network_json(path: str, network: dict): + with open(path, 'w', encoding='utf-8') as f: + f.write(json.dumps(network, indent=4)) + def importAndShapeFullReload(): importFromCRM() -- knotmirror 0.0.1