From d5faadc165fa801e6e0f8485f5c6704faf632666 Mon Sep 17 00:00:00 2001 From: rchac Date: Tue, 23 Sep 2025 00:17:00 +0000 Subject: [PATCH 01/61] netzur --- docs-es/Quickstart/configuration.md | 2 +- docs-es/Quickstart/services-and-run.md | 2 +- docs-es/v2.0/Quickstart/configuration.md | 2 +- docs-es/v2.0/Quickstart/services-and-run.md | 4 +- docs-es/v2.0/components-es.md | 6 +- docs-es/v2.0/configuration-es.md | 2 +- docs-es/v2.0/integrations-es.md | 26 ++++++++ docs/Quickstart/configuration.md | 2 +- docs/Quickstart/services-and-run.md | 2 +- docs/v2.0/components.md | 4 +- docs/v2.0/configuration.md | 2 +- docs/v2.0/integrations.md | 26 ++++++++ src/rust/Cargo.lock | 2 + .../lqos_config/src/etc/python_migration.rs | 6 ++ src/rust/lqos_config/src/etc/test_data.rs | 6 ++ src/rust/lqos_config/src/etc/v15/example.toml | 8 ++- src/rust/lqos_config/src/etc/v15/mod.rs | 1 + .../src/etc/v15/netzur_integration.rs | 38 +++++++++++ .../lqos_config/src/etc/v15/top_config.rs | 4 ++ src/rust/lqos_python/Cargo.toml | 4 ++ src/rust/lqos_python/src/lib.rs | 60 +++++++++++++++++ .../src/node_manager/js_build/esbuild.sh | 2 +- .../js_build/src/config/config_helper.js | 3 +- .../js_build/src/config_netzur.js | 66 +++++++++++++++++++ .../js_build/src/configuration.js | 6 ++ .../node_manager/static2/config_netzur.html | 33 ++++++++++ .../node_manager/static2/configuration.html | 29 +++++++- src/scheduler.py | 8 +++ 28 files changed, 338 insertions(+), 18 deletions(-) create mode 100644 src/rust/lqos_config/src/etc/v15/netzur_integration.rs create mode 100644 src/rust/lqosd/src/node_manager/js_build/src/config_netzur.js create mode 100644 src/rust/lqosd/src/node_manager/static2/config_netzur.html diff --git a/docs-es/Quickstart/configuration.md b/docs-es/Quickstart/configuration.md index 835ee0f9..c663f430 100644 --- a/docs-es/Quickstart/configuration.md +++ b/docs-es/Quickstart/configuration.md @@ -49,7 +49,7 @@ configurando el siguiente contenido de archivo: {} ``` -Si planea usar las integraciones UISP o Splynx incorporadas, todavía no es necesario crear un archivo network.json. +Si planea usar las integraciones UISP, Splynx o Netzur incorporadas, todavía no es necesario crear un archivo network.json. Si planea usar las integraciones UISP incorporadas, este se creará automáticamente en su primera ejecución (asumiendo que network.json no esté ya presente). Después puede modificar network.json para que refleje más ajustadamente su topología. diff --git a/docs-es/Quickstart/services-and-run.md b/docs-es/Quickstart/services-and-run.md index a5beddd2..5ef154c0 100644 --- a/docs-es/Quickstart/services-and-run.md +++ b/docs-es/Quickstart/services-and-run.md @@ -10,7 +10,7 @@ lqos_node_manager lqos_scheduler -- lqos_scheduler maneja estadísticas y realiza actualizaciones continuas de los modeladores de LibreQoS, incluida la extracción de cualquier integración de CRM habilitada (UISP, Splynx). +- lqos_scheduler maneja estadísticas y realiza actualizaciones continuas de los modeladores de LibreQoS, incluida la extracción de cualquier integración de CRM habilitada (UISP, Splynx, Netzur). - Al iniciar: ejecuta una configuración completa de colas - Cada 10 segundos: Grafica estadísticas de ancho de banda y latencia - Cada 30 segundos: Actualiza colas, extrayendo nueva configuración de la integración de CRM si está habilitada diff --git a/docs-es/v2.0/Quickstart/configuration.md b/docs-es/v2.0/Quickstart/configuration.md index 3c5ea137..74188f72 100644 --- a/docs-es/v2.0/Quickstart/configuration.md +++ b/docs-es/v2.0/Quickstart/configuration.md @@ -34,7 +34,7 @@ Más información sobre cómo [configurar integraciones aquí](../TechnicalDocs/ Network.json permite a los operadores de ISP definir una topología de red jerárquica o una topología de red plana. -Si planea utilizar las integraciones UISP o Splynx integradas, no es necesario que cree un archivo network.json todavía. +Si planea utilizar las integraciones UISP, Splynx o Netzur integradas, no es necesario que cree un archivo network.json todavía. Si planea utilizar la integración UISP integrada, esta se creará automáticamente la primera vez que se ejecute (suponiendo que network.json aún no exista). Si no va a utilizar una integración, puede definir manualmente el archivo network.json siguiendo el archivo de plantilla: network.example.json diff --git a/docs-es/v2.0/Quickstart/services-and-run.md b/docs-es/v2.0/Quickstart/services-and-run.md index 5c23ea5f..1e4c6864 100644 --- a/docs-es/v2.0/Quickstart/services-and-run.md +++ b/docs-es/v2.0/Quickstart/services-and-run.md @@ -9,7 +9,7 @@ ### lqos_scheduler -- lqos_scheduler performs continuous refreshes of LibreQoS' shapers, including pulling from any enabled CRM Integrations (UISP, Splynx). +- lqos_scheduler performs continuous refreshes of LibreQoS' shapers, including pulling from any enabled CRM Integrations (UISP, Splynx, Netzur). - Actions: - On start: Run a full setup of queues - Every X minutes: Update queues, pulling new configuration from CRM integration, if enabled. @@ -34,7 +34,7 @@ Lqosd will provide specific reasons it failed, such as an interface not being up In the background, lqos_scheduler runs the Python script scheduler.py, which in turn runs the Python script LibreQoS.py -- scheduler.py: performs continuous refreshes of LibreQoS' shapers, including pulling from any enabled CRM Integrations (UISP, Splynx). +- scheduler.py: performs continuous refreshes of LibreQoS' shapers, including pulling from any enabled CRM Integrations (UISP, Splynx, Netzur). - LibreQoS.py: creates and updates queues / shaping of devices One-time runs of these individual components can be very helpful for debugging and to make sure everything is correctly configured. diff --git a/docs-es/v2.0/components-es.md b/docs-es/v2.0/components-es.md index 55cc6ea6..1a3e6ef7 100644 --- a/docs-es/v2.0/components-es.md +++ b/docs-es/v2.0/components-es.md @@ -9,7 +9,7 @@ ### lqos_scheduler -- lqos_scheduler realiza actualizaciones continuas de los reguladores de tráfico (shapers) de LibreQoS, incluyendo la obtención de datos desde cualquier integración CRM habilitada (UISP, Splynx). +- lqos_scheduler realiza actualizaciones continuas de los reguladores de tráfico (shapers) de LibreQoS, incluyendo la obtención de datos desde cualquier integración CRM habilitada (UISP, Splynx, Netzur). - Acciones realizadas: - Al iniciar: Realiza una configuración completa de las filas. - Cada X minutos: Actualiza las colas, obteniendo nueva configuración desde la integración CRM, si está habilitada. @@ -34,7 +34,7 @@ Lqosd indicará las razones específicas por las cuales falló, como una interfa En segundo plano, lqos_scheduler ejecuta el script de Python scheduler.py, el cual a su vez ejecuta el script de Python LibreQoS.py -- scheduler.py: realiza actualizaciones continuas de los reguladores de tráfico (shapers) de LibreQoS, incluyendo la obtención de datos desde cualquier integración CRM habilitada (UISP, Splynx). +- scheduler.py: realiza actualizaciones continuas de los reguladores de tráfico (shapers) de LibreQoS, incluyendo la obtención de datos desde cualquier integración CRM habilitada (UISP, Splynx, Netzur). - LibreQoS.py: se encarga de crear y actualizar las filas y el regulamiento de tráfico de los dispositivos. Ejecuciones puntuales de estos componentes individuales pueden ser de gran ayuda para depurar y asegurar que todo esté correctamente configurado. @@ -67,4 +67,4 @@ Una vez que se hayan corregido los errores, reinicie el servicio lqos_scheduler ```shell sudo systemctl start lqos_scheduler -``` \ No newline at end of file +``` diff --git a/docs-es/v2.0/configuration-es.md b/docs-es/v2.0/configuration-es.md index c970bf26..ef720b4d 100644 --- a/docs-es/v2.0/configuration-es.md +++ b/docs-es/v2.0/configuration-es.md @@ -46,7 +46,7 @@ Más información sobre [configuración de integraciones aquí.](integrations-es Network.json permite a los operadores de internet (ISP) definir una topología de red jerárquica o plana. -Si planea usar las integraciones ya incluidas en LibreQoS de UISP o Splynx, no necesita todavía crear un archivo network.json. +Si planea usar las integraciones ya incluidas en LibreQoS de UISP, Splynx o Netzur, no necesita todavía crear un archivo network.json. Si planea usar la integración ya incluida de UISP, el archivo network.json se creará en automático durante la primera ejecución (siempre y cuando network.json no exista previamente). Si no planea usar una integración, puede definir manualmente el archivo network.json siguiendo el archivo de plantilla - [network.example.json](https://github.com/LibreQoE/LibreQoS/blob/develop/src/network.example.json). A continuación se muestra una ilustración en tabla del network.example.json. diff --git a/docs-es/v2.0/integrations-es.md b/docs-es/v2.0/integrations-es.md index 9ab0329f..952c795d 100644 --- a/docs-es/v2.0/integrations-es.md +++ b/docs-es/v2.0/integrations-es.md @@ -5,6 +5,7 @@ + [Promover Nodos a Raíz (Optimización de Rendimiento)](#promover-nodos-a-raíz-optimización-de-rendimiento) + [Acceso API de Splynx](#acceso-api-de-splynx) + [Sobrescrituras de Splynx](#sobrescrituras-de-splynx) + * [Integración con Netzur](#integración-con-netzur) * [Integración con UISP](#integración-con-uisp) + [Estrategias de Topología](#estrategias-de-topología-1) + [Estrategias de Manejo de Suspensiones](#estrategias-de-manejo-de-suspensiones) @@ -125,6 +126,31 @@ sudo cp /opt/libreqos/src/integrationSplynxBandwidths.template.csv /opt/libreqos ``` Y luego editaría el CSV con LibreOffice o el editor de CSV de su preferencia. +## Integración con Netzur + +Los despliegues de Netzur proporcionan un endpoint REST con información de zonas y clientes protegido con token Bearer. Configure la sección `[netzur_integration]` en `/etc/lqos.conf`: + +```ini +[netzur_integration] +enable_netzur = true +api_key = "su-token-netzur" +api_url = "https://netzur.ejemplo.com/api/libreqos" +timeout_secs = 60 +``` + +- `enable_netzur` habilita la importación automática desde `lqos_scheduler`. +- `api_key` es el token Bearer generado dentro de Netzur. +- `api_url` debe devolver un JSON con los arreglos `zones` (convertidos en sitios) y `customers` (convertidos en circuitos y dispositivos). +- `timeout_secs` permite incrementar el tiempo de espera de la petición cuando el API responde lentamente (por defecto 60 segundos). + +Para una importación manual: + +```bash +python3 integrationNetzur.py +``` + +La integración actualiza `ShapedDevices.csv` y, salvo que `always_overwrite_network_json` esté deshabilitado, también `network.json`. Ajuste la opción Integración → Común si necesita preservar un `network.json` existente entre ejecuciones de Netzur. + ## Integración con UISP Primero, configure los parámetros relevantes de UISP en `/etc/lqos.conf`. diff --git a/docs/Quickstart/configuration.md b/docs/Quickstart/configuration.md index 430bc0b1..92ef27a2 100644 --- a/docs/Quickstart/configuration.md +++ b/docs/Quickstart/configuration.md @@ -45,7 +45,7 @@ setting the following file content: {} ``` -If you plan to use the built-in UISP or Splynx integrations, you do not need to create a network.json file quite yet. +If you plan to use the built-in UISP, Splynx, or Netzur integrations, you do not need to create a network.json file quite yet. If you plan to use the built-in UISP integration, it will create this automatically on its first run (assuming network.json is not already present). You can then modify the network.json to more accurately reflect your topology. diff --git a/docs/Quickstart/services-and-run.md b/docs/Quickstart/services-and-run.md index 733db9b4..207dc030 100644 --- a/docs/Quickstart/services-and-run.md +++ b/docs/Quickstart/services-and-run.md @@ -10,7 +10,7 @@ lqos_node_manager lqos_scheduler -- lqos_scheduler handles statistics and performs continuous refreshes of LibreQoS' shapers, including pulling from any enabled CRM Integrations (UISP, Splynx). +- lqos_scheduler handles statistics and performs continuous refreshes of LibreQoS' shapers, including pulling from any enabled CRM Integrations (UISP, Splynx, Netzur). - On start: Run a full setup of queues - Every 10 seconds: Graph bandwidth and latency stats - Every 30 minutes: Update queues, pulling new configuration from CRM integration if enabled diff --git a/docs/v2.0/components.md b/docs/v2.0/components.md index 4b5d9f95..352f6c04 100644 --- a/docs/v2.0/components.md +++ b/docs/v2.0/components.md @@ -9,7 +9,7 @@ ### lqos_scheduler -- lqos_scheduler performs continuous refreshes of LibreQoS' shapers, including pulling from any enabled CRM Integrations (UISP, Splynx). +- lqos_scheduler performs continuous refreshes of LibreQoS' shapers, including pulling from any enabled CRM Integrations (UISP, Splynx, Netzur). - Actions: - On start: Run a full setup of queues - Every X minutes: Update queues, pulling new configuration from CRM integration, if enabled. @@ -34,7 +34,7 @@ Lqosd will provide specific reasons it failed, such as an interface not being up In the background, lqos_scheduler runs the Python script scheduler.py, which in turn runs the Python script LibreQoS.py -- scheduler.py: performs continuous refreshes of LibreQoS' shapers, including pulling from any enabled CRM Integrations (UISP, Splynx). +- scheduler.py: performs continuous refreshes of LibreQoS' shapers, including pulling from any enabled CRM Integrations (UISP, Splynx, Netzur). - LibreQoS.py: creates and updates queues / shaping of devices One-time runs of these individual components can be very helpful for debugging and to make sure everything is correctly configured. diff --git a/docs/v2.0/configuration.md b/docs/v2.0/configuration.md index e0105870..bc29b5fe 100644 --- a/docs/v2.0/configuration.md +++ b/docs/v2.0/configuration.md @@ -46,7 +46,7 @@ Learn more about [configuring integrations here](integrations.md). Network.json allows ISP operators to define a Hierarchical Network Topology, or Flat Network Topology. -If you plan to use the built-in UISP or Splynx integrations, you do not need to create a network.json file quite yet. +If you plan to use the built-in UISP, Splynx, or Netzur integrations, you do not need to create a network.json file quite yet. If you plan to use the built-in UISP integration, it will create this automatically on its first run (assuming network.json is not already present). If you will not be using an integration, you can manually define the network.json following the template file - [network.example.json](https://github.com/LibreQoE/LibreQoS/blob/develop/src/network.example.json). Below is a table illustration of network.example.json. diff --git a/docs/v2.0/integrations.md b/docs/v2.0/integrations.md index 5a3ba38c..5c1b1a59 100644 --- a/docs/v2.0/integrations.md +++ b/docs/v2.0/integrations.md @@ -5,6 +5,7 @@ + [Promote to Root Nodes (Performance Optimization)](#promote-to-root-nodes-performance-optimization) + [Splynx API Access](#splynx-api-access) + [Splynx Overrides](#splynx-overrides) + * [Netzur Integration](#netzur-integration) * [UISP Integration](#uisp-integration) + [Topology Strategies](#topology-strategies-1) + [Suspension Handling Strategies](#suspension-handling-strategies) @@ -126,6 +127,31 @@ sudo cp /opt/libreqos/src/integrationSplynxBandwidths.template.csv /opt/libreqos ``` And edit the CSV using LibreOffice or your preferred CSV editor. +## Netzur Integration + +Netzur deployments expose subscriber and zone inventories via a REST endpoint secured with a Bearer token. Configure `/etc/lqos.conf` as follows: + +```ini +[netzur_integration] +enable_netzur = true +api_key = "your-netzur-token" +api_url = "https://netzur.example.com/api/libreqos" +timeout_secs = 60 +``` + +- `enable_netzur` toggles automatic imports by `lqos_scheduler`. +- `api_key` is the Bearer token generated inside Netzur. +- `api_url` must return JSON containing `zones` (mapped to sites) and `customers` (mapped to client circuits and devices). +- `timeout_secs` overrides the default HTTP timeout (60 seconds) when the API is slow. + +Run a manual import with: + +```bash +python3 integrationNetzur.py +``` + +The integration regenerates `ShapedDevices.csv` and, unless `always_overwrite_network_json` is disabled, updates `network.json`. Adjust the Integration → Common settings if you need to preserve an existing network map between Netzur syncs. + ## UISP Integration First, set the relevant parameters for UISP in `/etc/lqos.conf`. diff --git a/src/rust/Cargo.lock b/src/rust/Cargo.lock index 01ab2363..86958614 100644 --- a/src/rust/Cargo.lock +++ b/src/rust/Cargo.lock @@ -1976,7 +1976,9 @@ dependencies = [ "reqwest", "serde", "sysinfo", + "tempfile", "tokio", + "toml", ] [[package]] diff --git a/src/rust/lqos_config/src/etc/python_migration.rs b/src/rust/lqos_config/src/etc/python_migration.rs index 0b8ef32f..e68dbe55 100644 --- a/src/rust/lqos_config/src/etc/python_migration.rs +++ b/src/rust/lqos_config/src/etc/python_migration.rs @@ -89,6 +89,12 @@ pub struct PythonMigration { pub splynx_api_key: String, pub splynx_api_secret: String, pub splynx_api_url: String, + #[serde(rename = "automaticImportNetzur")] + pub automatic_import_netzur: bool, + pub netzur_api_key: String, + pub netzur_api_url: String, + #[serde(rename = "netzur_api_timeout")] + pub netzur_api_timeout: i64, #[serde(rename = "automaticImportUISP")] pub automatic_import_uisp: bool, #[serde(rename = "uispAuthToken")] diff --git a/src/rust/lqos_config/src/etc/test_data.rs b/src/rust/lqos_config/src/etc/test_data.rs index 53ad92d0..6acd266c 100644 --- a/src/rust/lqos_config/src/etc/test_data.rs +++ b/src/rust/lqos_config/src/etc/test_data.rs @@ -136,6 +136,12 @@ splynx_api_secret = '' # Everything before /api/2.0/ on your Splynx instance splynx_api_url = 'https://YOUR_URL.splynx.app' +# Netzur Integration +automaticImportNetzur = False +netzur_api_key = '' +netzur_api_url = 'https://api.netzur.example.com' +netzur_api_timeout = 60 + # UISP integration automaticImportUISP = False uispAuthToken = '' diff --git a/src/rust/lqos_config/src/etc/v15/example.toml b/src/rust/lqos_config/src/etc/v15/example.toml index 4a1e0892..b5aaa9bd 100644 --- a/src/rust/lqos_config/src/etc/v15/example.toml +++ b/src/rust/lqos_config/src/etc/v15/example.toml @@ -60,6 +60,12 @@ api_key = "" api_secret = "" url = "" +[netzur_integration] +enable_netzur = false +api_key = "" +api_url = "" +timeout_secs = 60 + [uisp_integration] enable_uisp = false token = "" @@ -95,4 +101,4 @@ enable_influxdb = false url = "http://localhost:8086" org = "libreqos" bucket = "Your ISP Name Here" -token = "" \ No newline at end of file +token = "" diff --git a/src/rust/lqos_config/src/etc/v15/mod.rs b/src/rust/lqos_config/src/etc/v15/mod.rs index 128331bf..e187c32c 100644 --- a/src/rust/lqos_config/src/etc/v15/mod.rs +++ b/src/rust/lqos_config/src/etc/v15/mod.rs @@ -12,6 +12,7 @@ mod powercode_integration; mod queues; mod sonar_integration; mod spylnx_integration; +mod netzur_integration; mod tuning; mod uisp_integration; mod wispgate; diff --git a/src/rust/lqos_config/src/etc/v15/netzur_integration.rs b/src/rust/lqos_config/src/etc/v15/netzur_integration.rs new file mode 100644 index 00000000..1d7b4d31 --- /dev/null +++ b/src/rust/lqos_config/src/etc/v15/netzur_integration.rs @@ -0,0 +1,38 @@ +use allocative::Allocative; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Allocative)] +pub struct NetzurIntegration { + pub enable_netzur: bool, + pub api_key: String, + pub api_url: String, + #[serde(default = "default_timeout_secs")] + pub timeout_secs: u64, +} + +fn default_timeout_secs() -> u64 { + 60 +} + +impl Default for NetzurIntegration { + fn default() -> Self { + NetzurIntegration { + enable_netzur: false, + api_key: "".to_string(), + api_url: "".to_string(), + timeout_secs: default_timeout_secs(), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn default_timeout_is_sixty_seconds() { + let integration = NetzurIntegration::default(); + assert_eq!(integration.timeout_secs, 60); + assert!(!integration.enable_netzur); + } +} diff --git a/src/rust/lqos_config/src/etc/v15/top_config.rs b/src/rust/lqos_config/src/etc/v15/top_config.rs index 46740086..0e1d6256 100644 --- a/src/rust/lqos_config/src/etc/v15/top_config.rs +++ b/src/rust/lqos_config/src/etc/v15/top_config.rs @@ -58,6 +58,9 @@ pub struct Config { /// Spylnx Integration pub spylnx_integration: super::spylnx_integration::SplynxIntegration, + /// Netzur Integration + pub netzur_integration: super::netzur_integration::NetzurIntegration, + /// UISP Integration pub uisp_integration: super::uisp_integration::UispIntegration, @@ -147,6 +150,7 @@ impl Default for Config { ip_ranges: super::ip_ranges::IpRanges::default(), integration_common: super::integration_common::IntegrationConfig::default(), spylnx_integration: super::spylnx_integration::SplynxIntegration::default(), + netzur_integration: super::netzur_integration::NetzurIntegration::default(), uisp_integration: super::uisp_integration::UispIntegration::default(), powercode_integration: super::powercode_integration::PowercodeIntegration::default(), sonar_integration: super::sonar_integration::SonarIntegration::default(), diff --git a/src/rust/lqos_python/Cargo.toml b/src/rust/lqos_python/Cargo.toml index ad0f341c..71a04e32 100644 --- a/src/rust/lqos_python/Cargo.toml +++ b/src/rust/lqos_python/Cargo.toml @@ -20,3 +20,7 @@ nix = { workspace = true } reqwest = { workspace = true } serde = { workspace = true } chrono = "0.4.33" + +[dev-dependencies] +tempfile = "3.10" +toml = "0.8" diff --git a/src/rust/lqos_python/src/lib.rs b/src/rust/lqos_python/src/lib.rs index 1aece90f..51e553ff 100644 --- a/src/rust/lqos_python/src/lib.rs +++ b/src/rust/lqos_python/src/lib.rs @@ -71,8 +71,12 @@ fn liblqos_python(m: &Bound<'_, PyModule>) -> PyResult<()> { m.add_function(wrap_pyfunction!(splynx_api_secret, m)?)?; m.add_function(wrap_pyfunction!(splynx_api_url, m)?)?; m.add_function(wrap_pyfunction!(splynx_strategy, m)?)?; + m.add_function(wrap_pyfunction!(netzur_api_key, m)?)?; + m.add_function(wrap_pyfunction!(netzur_api_url, m)?)?; + m.add_function(wrap_pyfunction!(netzur_api_timeout, m)?)?; m.add_function(wrap_pyfunction!(automatic_import_uisp, m)?)?; m.add_function(wrap_pyfunction!(automatic_import_splynx, m)?)?; + m.add_function(wrap_pyfunction!(automatic_import_netzur, m)?)?; m.add_function(wrap_pyfunction!(queue_refresh_interval_mins, m)?)?; m.add_function(wrap_pyfunction!(automatic_import_powercode, m)?)?; m.add_function(wrap_pyfunction!(powercode_api_key, m)?)?; @@ -573,6 +577,24 @@ fn splynx_strategy() -> PyResult { } } +#[pyfunction] +fn netzur_api_key() -> PyResult { + let config = lqos_config::load_config().unwrap(); + Ok(config.netzur_integration.api_key.clone()) +} + +#[pyfunction] +fn netzur_api_url() -> PyResult { + let config = lqos_config::load_config().unwrap(); + Ok(config.netzur_integration.api_url.clone()) +} + +#[pyfunction] +fn netzur_api_timeout() -> PyResult { + let config = lqos_config::load_config().unwrap(); + Ok(config.netzur_integration.timeout_secs) +} + #[pyfunction] fn automatic_import_uisp() -> PyResult { let config = lqos_config::load_config().unwrap(); @@ -585,6 +607,44 @@ fn automatic_import_splynx() -> PyResult { Ok(config.spylnx_integration.enable_spylnx) } +#[pyfunction] +fn automatic_import_netzur() -> PyResult { + let config = lqos_config::load_config().unwrap(); + Ok(config.netzur_integration.enable_netzur) +} + +#[cfg(test)] +mod tests { + use super::*; + use tempfile::NamedTempFile; + + fn write_test_config() -> NamedTempFile { + let mut cfg = lqos_config::Config::default(); + cfg.netzur_integration.enable_netzur = true; + cfg.netzur_integration.api_key = "test-netzur-key".to_string(); + cfg.netzur_integration.api_url = "https://netzur.test/api".to_string(); + cfg.netzur_integration.timeout_secs = 45; + + let toml = toml::to_string_pretty(&cfg).unwrap(); + let file = NamedTempFile::new().unwrap(); + std::fs::write(file.path(), toml).unwrap(); + file + } + + #[test] + fn netzur_bindings_surface_config_values() { + let file = write_test_config(); + std::env::set_var("LQOS_CONFIG", file.path()); + + assert_eq!(netzur_api_key().unwrap(), "test-netzur-key"); + assert_eq!(netzur_api_url().unwrap(), "https://netzur.test/api"); + assert_eq!(netzur_api_timeout().unwrap(), 45); + assert!(automatic_import_netzur().unwrap()); + + std::env::remove_var("LQOS_CONFIG"); + } +} + #[pyfunction] fn queue_refresh_interval_mins() -> PyResult { let config = lqos_config::load_config().unwrap(); diff --git a/src/rust/lqosd/src/node_manager/js_build/esbuild.sh b/src/rust/lqosd/src/node_manager/js_build/esbuild.sh index e0e7af3c..38ff2bd8 100755 --- a/src/rust/lqosd/src/node_manager/js_build/esbuild.sh +++ b/src/rust/lqosd/src/node_manager/js_build/esbuild.sh @@ -1,6 +1,6 @@ #!/bin/bash set -e -scripts=( index.js template.js login.js first-run.js shaped-devices.js tree.js help.js unknown-ips.js configuration.js circuit.js flow_map.js all_tree_sankey.js asn_explorer.js lts_trial.js config_general.js config_tuning.js config_queues.js config_stormguard.js config_lts.js config_iprange.js config_flows.js config_integration.js config_spylnx.js config_uisp.js config_powercode.js config_sonar.js config_interface.js config_network.js config_devices.js config_users.js config_wispgate.js ) +scripts=( index.js template.js login.js first-run.js shaped-devices.js tree.js help.js unknown-ips.js configuration.js circuit.js flow_map.js all_tree_sankey.js asn_explorer.js lts_trial.js config_general.js config_tuning.js config_queues.js config_stormguard.js config_lts.js config_iprange.js config_flows.js config_integration.js config_spylnx.js config_netzur.js config_uisp.js config_powercode.js config_sonar.js config_interface.js config_network.js config_devices.js config_users.js config_wispgate.js ) for script in "${scripts[@]}" do echo "Building {$script}" diff --git a/src/rust/lqosd/src/node_manager/js_build/src/config/config_helper.js b/src/rust/lqosd/src/node_manager/js_build/src/config/config_helper.js index 37013295..2a33606a 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/config/config_helper.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/config/config_helper.js @@ -146,6 +146,7 @@ export function renderConfigMenu(currentPage) { { href: "config_flows.html", icon: "fa-arrow-circle-down", text: "Flow Tracking", id: "flows" }, { href: "config_integration.html", icon: "fa-link", text: "Integration - Common", id: "integration" }, { href: "config_spylnx.html", icon: "fa-link", text: "Splynx", id: "spylnx" }, + { href: "config_netzur.html", icon: "fa-link", text: "Netzur", id: "netzur" }, { href: "config_uisp.html", icon: "fa-link", text: "UISP", id: "uisp" }, { href: "config_powercode.html", icon: "fa-link", text: "Powercode", id: "powercode" }, { href: "config_sonar.html", icon: "fa-link", text: "Sonar", id: "sonar" }, @@ -180,4 +181,4 @@ export function renderConfigMenu(currentPage) { // If no specific container, inject at the beginning of the body document.body.insertAdjacentHTML('afterbegin', menuHtml); } -} \ No newline at end of file +} diff --git a/src/rust/lqosd/src/node_manager/js_build/src/config_netzur.js b/src/rust/lqosd/src/node_manager/js_build/src/config_netzur.js new file mode 100644 index 00000000..61cb3b58 --- /dev/null +++ b/src/rust/lqosd/src/node_manager/js_build/src/config_netzur.js @@ -0,0 +1,66 @@ +import {saveConfig, loadConfig, renderConfigMenu} from "./config/config_helper"; + +function validateConfig() { + const enabled = document.getElementById("enableNetzur").checked; + if (!enabled) { + return true; + } + + const apiKey = document.getElementById("netzurApiKey").value.trim(); + if (!apiKey) { + alert("API Key is required when Netzur integration is enabled"); + return false; + } + + const urlValue = document.getElementById("netzurApiUrl").value.trim(); + if (!urlValue) { + alert("API URL is required when Netzur integration is enabled"); + return false; + } + + try { + new URL(urlValue); + } catch (_) { + alert("API URL must be a valid URL"); + return false; + } + + const timeout = parseInt(document.getElementById("netzurTimeout").value, 10); + if (Number.isNaN(timeout) || timeout <= 0) { + alert("Timeout must be a positive number of seconds"); + return false; + } + + return true; +} + +function updateConfig() { + window.config.netzur_integration = { + enable_netzur: document.getElementById("enableNetzur").checked, + api_key: document.getElementById("netzurApiKey").value.trim(), + api_url: document.getElementById("netzurApiUrl").value.trim(), + timeout_secs: parseInt(document.getElementById("netzurTimeout").value, 10) || 60 + }; +} + +renderConfigMenu('netzur'); + +loadConfig(() => { + if (!window.config) { + console.error("Configuration not loaded"); + return; + } + + const cfg = window.config.netzur_integration ?? {}; + document.getElementById("enableNetzur").checked = cfg.enable_netzur ?? false; + document.getElementById("netzurApiKey").value = cfg.api_key ?? ""; + document.getElementById("netzurApiUrl").value = cfg.api_url ?? ""; + document.getElementById("netzurTimeout").value = cfg.timeout_secs ?? 60; + + document.getElementById("saveNetzur").addEventListener('click', () => { + if (validateConfig()) { + updateConfig(); + saveConfig(() => alert("Netzur configuration saved")); + } + }); +}); diff --git a/src/rust/lqosd/src/node_manager/js_build/src/configuration.js b/src/rust/lqosd/src/node_manager/js_build/src/configuration.js index 701ca9fa..f6405e9d 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/configuration.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/configuration.js @@ -76,6 +76,12 @@ const bindings = [ { field: "bindSplynxApiSecret", path: ".spylnx_integration.api_secret", data: "string", editable: true }, { field: "bindSplynxApiUrl", path: ".spylnx_integration.url", data: "string", editable: true }, + // Netzur + { field: "bindNetzurEnable", path: ".netzur_integration.enable_netzur", data: "bool", editable: true }, + { field: "bindNetzurApiKey", path: ".netzur_integration.api_key", data: "string", editable: true }, + { field: "bindNetzurApiUrl", path: ".netzur_integration.api_url", data: "string", editable: true }, + { field: "bindNetzurTimeout", path: ".netzur_integration.timeout_secs", data: "integer", editable: true }, + // UISP { field: "bindUispEnable", path: ".uisp_integration.enable_uisp", data: "bool", editable: true }, { field: "bindUispToken", path: ".uisp_integration.token", data: "string", editable: true }, diff --git a/src/rust/lqosd/src/node_manager/static2/config_netzur.html b/src/rust/lqosd/src/node_manager/static2/config_netzur.html new file mode 100644 index 00000000..5fd9afad --- /dev/null +++ b/src/rust/lqosd/src/node_manager/static2/config_netzur.html @@ -0,0 +1,33 @@ +
+
+
+
+
+ + +
Toggle automated imports from Netzur CRM
+
+ +
+ + +
Bearer token generated within Netzur
+
+ +
+ + +
Base endpoint serving the zones/customers payload
+
+ +
+ + +
Adjust only if the API routinely needs more than 60 seconds
+
+ + +
+
+
+ diff --git a/src/rust/lqosd/src/node_manager/static2/configuration.html b/src/rust/lqosd/src/node_manager/static2/configuration.html index a9ba106d..efad88cf 100644 --- a/src/rust/lqosd/src/node_manager/static2/configuration.html +++ b/src/rust/lqosd/src/node_manager/static2/configuration.html @@ -58,6 +58,10 @@ type="button" role="tab" aria-controls="v-pills-settings" aria-selected="false"> Splynx +

-

- Download support data to a local file. You can send this to LibreQoS via the - chat or email (as part of an ongoing support discussion).
- -

-

- Submit support data directly to LibreQoS. Please contact us when you do this, - with detailed information about the problems you are experiencing. Repeatedly hitting this - button will get you slower - or no - service!
- -

+ @@ -114,73 +104,6 @@ - - - + - \ No newline at end of file + -- knotmirror 0.0.1 From 8390c54272b60ae38a7e715567c691209ffa22a3 Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Fri, 3 Oct 2025 12:08:42 -0500 Subject: [PATCH 09/61] Chore: Remove lqos_support_tool from the shipping build (since we're retiring the server that handles the back-end). --- src/build_dpkg.sh | 14 +++++++++++--- src/build_rust.sh | 2 +- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/src/build_dpkg.sh b/src/build_dpkg.sh index 9b7a9455..f3a4a990 100755 --- a/src/build_dpkg.sh +++ b/src/build_dpkg.sh @@ -56,7 +56,6 @@ RUSTPROGS=( lqos_setup lqos_map_perf uisp_integration - lqos_support_tool ) #################################################### @@ -89,8 +88,17 @@ popd > /dev/null || exit # Build the Rust programs (before the control file, we need to LDD lqosd) pushd rust > /dev/null || exit -#cargo clean -cargo build --all --release +# Build only required binaries and artifacts (exclude lqos_support_tool executable) +cargo build --release \ + -p lqosd \ + -p lqtop \ + -p xdp_iphash_to_cpu_cmdline \ + -p xdp_pping \ + -p lqusers \ + -p lqos_setup \ + -p lqos_map_perf \ + -p uisp_integration \ + -p lqos_python popd > /dev/null || exit # Create the post-installation file diff --git a/src/build_rust.sh b/src/build_rust.sh index 783bf92f..d57b8b99 100755 --- a/src/build_rust.sh +++ b/src/build_rust.sh @@ -38,7 +38,7 @@ rustup update # Start building echo "Please wait while the system is compiled. Service will not be interrupted during this stage." -PROGS="lqosd lqtop xdp_iphash_to_cpu_cmdline xdp_pping lqusers lqos_map_perf uisp_integration lqos_support_tool" +PROGS="lqosd lqtop xdp_iphash_to_cpu_cmdline xdp_pping lqusers lqos_map_perf uisp_integration" mkdir -p bin/static pushd rust > /dev/null || exit #cargo clean -- knotmirror 0.0.1 From e2fdf13b1b29e136681ec0191b97f67616698198 Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Fri, 3 Oct 2025 12:20:50 -0500 Subject: [PATCH 10/61] Fix: Improve the look, clean broken icond fix spacing on the help page. --- .../lqosd/src/node_manager/static2/help.html | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/rust/lqosd/src/node_manager/static2/help.html b/src/rust/lqosd/src/node_manager/static2/help.html index f6fa318c..56ffd2f5 100644 --- a/src/rust/lqosd/src/node_manager/static2/help.html +++ b/src/rust/lqosd/src/node_manager/static2/help.html @@ -11,9 +11,9 @@

- Support LibreQoS Today + Support LibreQoS Today -

@@ -46,7 +46,7 @@
-
Learn
+
Learn

Learn about LibreQoS, bufferbloat and our battle against Internet latency at our YouTube channel. @@ -58,13 +58,13 @@

-
Connect
+
Connect

We're on social media! Connect with us at:

@@ -75,7 +75,7 @@
Tools
-

+

Sanity check reads your configuration and looks for common issues. This should be your first step when troubleshooting the system.
-- knotmirror 0.0.1 From 54a11bfb0fb57e0958fb0ac2ec8821bf9742a416 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Robert=20Chac=C3=B3n?= Date: Sun, 5 Oct 2025 08:51:01 -0600 Subject: [PATCH 11/61] Update requirements.md --- docs/v2.0/requirements.md | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/docs/v2.0/requirements.md b/docs/v2.0/requirements.md index 2bae62c6..1c3f4fef 100644 --- a/docs/v2.0/requirements.md +++ b/docs/v2.0/requirements.md @@ -33,7 +33,7 @@ Below is a table of approximate aggregate capacity, assuming a CPU with a [singl ### Hyper-threading -It is recommended to disable Hyper-Threading (Simultaneous Multi-Threading) in the BIOS/UEFI settings, as it can interfere with XDP processing. +Please [disable Hyper-Threading](https://www.youtube.com/watch?v=G70QtUAxomU) (Simultaneous Multi-Threading) in the BIOS/UEFI settings, as it can interfere with XDP processing. ### Memory * Recommended RAM: @@ -66,6 +66,10 @@ It is recommended to disable Hyper-Threading (Simultaneous Multi-Threading) in t | ECC | No | | Power | 19V DC | +##### MS-01 Notes: + +As with any machine running LibreQoS, please be sure to [disable hyperthreading](prereq.html). Specific to the MS-01, please consider [replacing the thermal paste](https://www.youtube.com/watch?v=G70QtUAxomU) to lower CPU temps by about 20 degrees celcius (Note: this may void the warranty). + #### Rackmount Servers (10G to 100G) | Throughput | 10 Gbps | 10 Gbps | 25 Gbps | 50 Gbps | 100 Gbps | @@ -84,6 +88,10 @@ It is recommended to disable Hyper-Threading (Simultaneous Multi-Threading) in t Another cost-effective solution is to procure a used server from a reputable vendor, such as [TheServerStore](https://www.theserverstore.com/). Such vendors often stock servers capable of 10 Gbps throughput, for around $500 USD. +#### Server Setup Prerequisites + +[Server Setup Prerequisites](prereq.html) + ### Network Interface Requirements * One management network interface completely separate from the traffic shaping interfaces. Usually this would be the Ethernet interface built in to the motherboard. * A Dedicated Network Interface Card for Two Shaping Interfaces -- knotmirror 0.0.1 From ee6fe6e542bb509c27596a589cf444e43a42c626 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Robert=20Chac=C3=B3n?= Date: Sun, 5 Oct 2025 12:37:01 -0600 Subject: [PATCH 12/61] Update VERSION_STRING --- src/VERSION_STRING | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/VERSION_STRING b/src/VERSION_STRING index 18fbd424..6fb6ca1c 100644 --- a/src/VERSION_STRING +++ b/src/VERSION_STRING @@ -1 +1 @@ -1.5-RC1 +1.5-RC2 -- knotmirror 0.0.1 From fae50846c05951ef2dfa6eaf4bd550db6ddced6c Mon Sep 17 00:00:00 2001 From: rchac Date: Sun, 5 Oct 2025 15:59:17 -0600 Subject: [PATCH 13/61] fix merge issues --- src/scheduler.py | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/src/scheduler.py b/src/scheduler.py index 357a288a..4e6790cc 100644 --- a/src/scheduler.py +++ b/src/scheduler.py @@ -81,19 +81,15 @@ def importFromCRM(): print(error_msg) scheduler_error(error_msg) elif automatic_import_splynx(): -<<<<<<< HEAD try: - importFromSplynx() + capture_output_and_run(importFromSplynx) except: print("Failed to import from Splynx") elif automatic_import_netzur(): try: - importFromNetzur() + capture_output_and_run(importFromNetzur) except: print("Failed to import from Netzur") -======= - capture_output_and_run(importFromSplynx) ->>>>>>> develop elif automatic_import_powercode(): capture_output_and_run(importFromPowercode) elif automatic_import_sonar(): -- knotmirror 0.0.1 From 7d8c8419811c6bb8af0969b1444eb1bf2b38f166 Mon Sep 17 00:00:00 2001 From: rchac Date: Sun, 5 Oct 2025 16:29:12 -0600 Subject: [PATCH 14/61] make netzur config optional --- .../lqos_config/src/etc/v15/top_config.rs | 7 ++-- src/rust/lqos_python/src/lib.rs | 32 ++++++++++++++++--- 2 files changed, 32 insertions(+), 7 deletions(-) diff --git a/src/rust/lqos_config/src/etc/v15/top_config.rs b/src/rust/lqos_config/src/etc/v15/top_config.rs index f46d2598..0a1f7e14 100644 --- a/src/rust/lqos_config/src/etc/v15/top_config.rs +++ b/src/rust/lqos_config/src/etc/v15/top_config.rs @@ -58,8 +58,9 @@ pub struct Config { /// Spylnx Integration pub spylnx_integration: super::spylnx_integration::SplynxIntegration, - /// Netzur Integration - pub netzur_integration: super::netzur_integration::NetzurIntegration, + /// Netzur Integration configuration. Optional so older configs without this + /// section still deserialize cleanly. + pub netzur_integration: Option, /// UISP Integration pub uisp_integration: super::uisp_integration::UispIntegration, @@ -150,7 +151,7 @@ impl Default for Config { ip_ranges: super::ip_ranges::IpRanges::default(), integration_common: super::integration_common::IntegrationConfig::default(), spylnx_integration: super::spylnx_integration::SplynxIntegration::default(), - netzur_integration: super::netzur_integration::NetzurIntegration::default(), + netzur_integration: Some(super::netzur_integration::NetzurIntegration::default()), uisp_integration: super::uisp_integration::UispIntegration::default(), powercode_integration: super::powercode_integration::PowercodeIntegration::default(), sonar_integration: super::sonar_integration::SonarIntegration::default(), diff --git a/src/rust/lqos_python/src/lib.rs b/src/rust/lqos_python/src/lib.rs index ac5c0602..85f7cba7 100644 --- a/src/rust/lqos_python/src/lib.rs +++ b/src/rust/lqos_python/src/lib.rs @@ -595,19 +595,37 @@ fn splynx_strategy() -> PyResult { #[pyfunction] fn netzur_api_key() -> PyResult { let config = lqos_config::load_config().unwrap(); - Ok(config.netzur_integration.api_key.clone()) + Ok( + config + .netzur_integration + .as_ref() + .map(|cfg| cfg.api_key.clone()) + .unwrap_or_default(), + ) } #[pyfunction] fn netzur_api_url() -> PyResult { let config = lqos_config::load_config().unwrap(); - Ok(config.netzur_integration.api_url.clone()) + Ok( + config + .netzur_integration + .as_ref() + .map(|cfg| cfg.api_url.clone()) + .unwrap_or_default(), + ) } #[pyfunction] fn netzur_api_timeout() -> PyResult { let config = lqos_config::load_config().unwrap(); - Ok(config.netzur_integration.timeout_secs) + Ok( + config + .netzur_integration + .as_ref() + .map(|cfg| cfg.timeout_secs) + .unwrap_or(60), + ) } #[pyfunction] @@ -625,7 +643,13 @@ fn automatic_import_splynx() -> PyResult { #[pyfunction] fn automatic_import_netzur() -> PyResult { let config = lqos_config::load_config().unwrap(); - Ok(config.netzur_integration.enable_netzur) + Ok( + config + .netzur_integration + .as_ref() + .map(|cfg| cfg.enable_netzur) + .unwrap_or(false), + ) } #[pyfunction] -- knotmirror 0.0.1 From 96c9ca599ff1ca8eaa2ced461c653bc9bf6c0842 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Robert=20Chac=C3=B3n?= Date: Sun, 5 Oct 2025 16:39:09 -0600 Subject: [PATCH 15/61] Update quickstart.md --- docs/v2.0/quickstart.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/v2.0/quickstart.md b/docs/v2.0/quickstart.md index fa6190db..17cd115c 100644 --- a/docs/v2.0/quickstart.md +++ b/docs/v2.0/quickstart.md @@ -19,10 +19,10 @@ cd ~ sudo apt-get update sudo apt-get upgrade -wget https://libreqos.io/wp-content/uploads/2025/08/libreqos_1.5-RC1.202508272111-1_amd64.zip +wget http://download.libreqos.com/libreqos_1.5-RC2.202510052233-1_amd64.deb sudo apt-get install unzip -unzip libreqos_1.5-RC1.202508272111-1_amd64.zip -sudo apt install ./libreqos_1.5-RC1.202508272111-1_amd64.deb +unzip libreqos_1.5-RC2.202510052233-1_amd64.deb +sudo apt install ./libreqos_1.5-RC2.202510052233-1_amd64.deb ``` ### Git Install (For Developers Only - Not Recommended) -- knotmirror 0.0.1 From 7178781f51e7e791dc408e75be1c2a9801a2a818 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Robert=20Chac=C3=B3n?= Date: Sun, 5 Oct 2025 16:39:33 -0600 Subject: [PATCH 16/61] Update quickstart-es.md --- docs-es/v2.0/quickstart-es.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs-es/v2.0/quickstart-es.md b/docs-es/v2.0/quickstart-es.md index d794a2f8..ea8f852b 100644 --- a/docs-es/v2.0/quickstart-es.md +++ b/docs-es/v2.0/quickstart-es.md @@ -19,10 +19,10 @@ cd ~ sudo apt-get update sudo apt-get upgrade -wget https://libreqos.io/wp-content/uploads/2025/08/libreqos_1.5-RC1.202508272111-1_amd64.zip +wget http://download.libreqos.com/libreqos_1.5-RC2.202510052233-1_amd64.deb sudo apt-get install unzip -unzip libreqos_1.5-RC1.202508272111-1_amd64.zip -sudo apt install ./libreqos_1.5-RC1.202508272111-1_amd64.deb +unzip libreqos_1.5-RC2.202510052233-1_amd64.deb +sudo apt install ./libreqos_1.5-RC2.202510052233-1_amd64.deb ``` ### Instalación con Git (Solo para Desarrolladores - No Recomendado) -- knotmirror 0.0.1 From 268d9c423ce6a25b51511750e189f6dda2de8590 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Robert=20Chac=C3=B3n?= Date: Sun, 5 Oct 2025 16:40:25 -0600 Subject: [PATCH 17/61] Update update.md --- docs-es/v2.0/Updates/update.md | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/docs-es/v2.0/Updates/update.md b/docs-es/v2.0/Updates/update.md index a5808531..845ddec4 100644 --- a/docs-es/v2.0/Updates/update.md +++ b/docs-es/v2.0/Updates/update.md @@ -10,10 +10,8 @@ Si usa el puente XDP, el tráfico dejará de pasar brevemente a través del puen cd ~ sudo apt-get update sudo apt-get upgrade -wget https://libreqos.io/wp-content/uploads/2025/08/libreqos_1.5-RC1.202508272111-1_amd64.zip -sudo apt-get install unzip -unzip libreqos_1.5-RC1.202508272111-1_amd64.zip -sudo apt install ./libreqos_1.5-RC1.202508272111-1_amd64.deb +wget http://download.libreqos.com/libreqos_1.5-RC2.202510052233-1_amd64.deb +sudo apt install ./libreqos_1.5-RC2.202510052233-1_amd64.deb sudo systemctl restart lqosd lqos_scheduler ``` -- knotmirror 0.0.1 From 740ac5a806eb7d9fdc300f0cae10de813e74cd7b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Robert=20Chac=C3=B3n?= Date: Sun, 5 Oct 2025 16:40:43 -0600 Subject: [PATCH 18/61] Update update.md --- docs/v2.0/update.md | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/docs/v2.0/update.md b/docs/v2.0/update.md index 86c1fc10..dd3e3dab 100644 --- a/docs/v2.0/update.md +++ b/docs/v2.0/update.md @@ -10,10 +10,8 @@ If you use the XDP bridge, traffic will briefly stop passing through the bridge cd ~ sudo apt-get update sudo apt-get upgrade -wget https://libreqos.io/wp-content/uploads/2025/08/libreqos_1.5-RC1.202508272111-1_amd64.zip -sudo apt-get install unzip -unzip libreqos_1.5-RC1.202508272111-1_amd64.zip -sudo apt install ./libreqos_1.5-RC1.202508272111-1_amd64.deb +wget http://download.libreqos.com/libreqos_1.5-RC2.202510052233-1_amd64.deb +sudo apt install ./libreqos_1.5-RC2.202510052233-1_amd64.deb sudo systemctl restart lqosd lqos_scheduler ``` -- knotmirror 0.0.1 From 66b1f7e3805cf229e73a7a4df211c6ad7f78b576 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Robert=20Chac=C3=B3n?= Date: Sun, 5 Oct 2025 16:41:02 -0600 Subject: [PATCH 19/61] Update quickstart.md --- docs/v2.0/quickstart.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/docs/v2.0/quickstart.md b/docs/v2.0/quickstart.md index 17cd115c..e0f5826a 100644 --- a/docs/v2.0/quickstart.md +++ b/docs/v2.0/quickstart.md @@ -20,8 +20,6 @@ cd ~ sudo apt-get update sudo apt-get upgrade wget http://download.libreqos.com/libreqos_1.5-RC2.202510052233-1_amd64.deb -sudo apt-get install unzip -unzip libreqos_1.5-RC2.202510052233-1_amd64.deb sudo apt install ./libreqos_1.5-RC2.202510052233-1_amd64.deb ``` -- knotmirror 0.0.1 From d14907be06097444dd034533dd91ab336aac6a87 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Robert=20Chac=C3=B3n?= Date: Sun, 5 Oct 2025 16:41:25 -0600 Subject: [PATCH 20/61] Update quickstart-es.md --- docs-es/v2.0/quickstart-es.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/docs-es/v2.0/quickstart-es.md b/docs-es/v2.0/quickstart-es.md index ea8f852b..d20ad538 100644 --- a/docs-es/v2.0/quickstart-es.md +++ b/docs-es/v2.0/quickstart-es.md @@ -20,8 +20,6 @@ cd ~ sudo apt-get update sudo apt-get upgrade wget http://download.libreqos.com/libreqos_1.5-RC2.202510052233-1_amd64.deb -sudo apt-get install unzip -unzip libreqos_1.5-RC2.202510052233-1_amd64.deb sudo apt install ./libreqos_1.5-RC2.202510052233-1_amd64.deb ``` -- knotmirror 0.0.1 From 18a4ad9c115d63fb4c1451371fc2d7eb992a3172 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Robert=20Chac=C3=B3n?= Date: Sun, 5 Oct 2025 16:47:27 -0600 Subject: [PATCH 21/61] Update requirements.md --- docs/v2.0/requirements.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/v2.0/requirements.md b/docs/v2.0/requirements.md index 1c3f4fef..c5cf8568 100644 --- a/docs/v2.0/requirements.md +++ b/docs/v2.0/requirements.md @@ -33,7 +33,7 @@ Below is a table of approximate aggregate capacity, assuming a CPU with a [singl ### Hyper-threading -Please [disable Hyper-Threading](https://www.youtube.com/watch?v=G70QtUAxomU) (Simultaneous Multi-Threading) in the BIOS/UEFI settings, as it can interfere with XDP processing. +Please [disable Hyper-Threading](prereq.md) (Simultaneous Multi-Threading) in the BIOS/UEFI settings, as it can interfere with XDP processing. ### Memory * Recommended RAM: @@ -68,7 +68,7 @@ Please [disable Hyper-Threading](https://www.youtube.com/watch?v=G70QtUAxomU) (S ##### MS-01 Notes: -As with any machine running LibreQoS, please be sure to [disable hyperthreading](prereq.html). Specific to the MS-01, please consider [replacing the thermal paste](https://www.youtube.com/watch?v=G70QtUAxomU) to lower CPU temps by about 20 degrees celcius (Note: this may void the warranty). +As with any machine running LibreQoS, please be sure to [disable hyperthreading](prereq.md). Specific to the MS-01, please consider [replacing the thermal paste](https://www.youtube.com/watch?v=G70QtUAxomU) to lower CPU temps by about 20 degrees celcius (Note: this may void the warranty). #### Rackmount Servers (10G to 100G) @@ -90,7 +90,7 @@ Such vendors often stock servers capable of 10 Gbps throughput, for around $500 #### Server Setup Prerequisites -[Server Setup Prerequisites](prereq.html) +[Server Setup Prerequisites](prereq.md) ### Network Interface Requirements * One management network interface completely separate from the traffic shaping interfaces. Usually this would be the Ethernet interface built in to the motherboard. -- knotmirror 0.0.1 From a741b84a47138bce26496d93e14dbf6422e1cec4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Robert=20Chac=C3=B3n?= Date: Sun, 5 Oct 2025 16:47:49 -0600 Subject: [PATCH 22/61] Update requirements-es.md --- docs-es/v2.0/requirements-es.md | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/docs-es/v2.0/requirements-es.md b/docs-es/v2.0/requirements-es.md index 45090b39..f4a842af 100644 --- a/docs-es/v2.0/requirements-es.md +++ b/docs-es/v2.0/requirements-es.md @@ -33,7 +33,7 @@ A continuación se muestra una tabla de la capacidad agregada aproximada, suponi ### Hyper-threading -Se recomienda desactivar Hyper-Threading (Simultaneous Multi-Threading) en la configuración del BIOS/UEFI, ya que puede interferir con el procesamiento de XDP. +Se recomienda [desactivar Hyper-Threading](prereq-es.md) (Simultaneous Multi-Threading) en la configuración del BIOS/UEFI, ya que puede interferir con el procesamiento de XDP. ### Memory * RAM Recomendada: @@ -66,6 +66,10 @@ Se recomienda disponer de 50 GB o más de espacio en disco, tanto para servidore | ECC | No | | Energía | 19V DC | +##### MS-01 Notes: + +Al igual que con cualquier máquina que ejecute LibreQoS, asegúrese de [desactivar Hyper-Threading](prereq-es.md). Específicamente para el MS-01, considere [reemplazar la pasta térmica](https://www.youtube.com/watch?v=G70QtUAxomU) para reducir la temperatura de la CPU en aproximadamente 20 grados centígrados (Nota: esto puede anular la garantía). + #### Servidores Rackmount (10G to 100G) | Rendimiento | 10 Gbps | 10 Gbps | 25 Gbps | 50 Gbps | 100 Gbps | @@ -84,6 +88,10 @@ Se recomienda disponer de 50 GB o más de espacio en disco, tanto para servidore Otra solución rentable es adquirir un servidor usado de un proveedor de confianza, como [TheServerStore](https://www.theserverstore.com/). Estos proveedores suelen ofrecer servidores capaces de manejar un rendimiento de 10 Gbps, por alrededor de 500 USD. +#### Server Setup Prerequisites + +[Requisitos previos para la configuración del servidor](prereq-es.md) + ### Requisitos de Interfaces de Red * Una interfaz de red de administración completamente separada de las interfaces de regulamiento de tráfico. Usualmente esta sería la interfaz Ethernet integrada en la placa base. * Una Tarjeta de Red Dedicada para Dos Interfaces de Regulamiento -- knotmirror 0.0.1 From cdc8884ee5f5f93e51c71969b73fd82ca9024236 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Robert=20Chac=C3=B3n?= Date: Sun, 5 Oct 2025 16:50:25 -0600 Subject: [PATCH 23/61] Update update.md --- docs/v2.0/update.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/v2.0/update.md b/docs/v2.0/update.md index dd3e3dab..08ed9cd6 100644 --- a/docs/v2.0/update.md +++ b/docs/v2.0/update.md @@ -10,7 +10,7 @@ If you use the XDP bridge, traffic will briefly stop passing through the bridge cd ~ sudo apt-get update sudo apt-get upgrade -wget http://download.libreqos.com/libreqos_1.5-RC2.202510052233-1_amd64.deb +wget https://download.libreqos.com/libreqos_1.5-RC2.202510052233-1_amd64.deb sudo apt install ./libreqos_1.5-RC2.202510052233-1_amd64.deb sudo systemctl restart lqosd lqos_scheduler ``` -- knotmirror 0.0.1 From 3a44851558395559594b1e92f08b52280186b505 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Robert=20Chac=C3=B3n?= Date: Sun, 5 Oct 2025 16:50:38 -0600 Subject: [PATCH 24/61] Update quickstart.md --- docs/v2.0/quickstart.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/v2.0/quickstart.md b/docs/v2.0/quickstart.md index e0f5826a..d1040c7b 100644 --- a/docs/v2.0/quickstart.md +++ b/docs/v2.0/quickstart.md @@ -19,7 +19,7 @@ cd ~ sudo apt-get update sudo apt-get upgrade -wget http://download.libreqos.com/libreqos_1.5-RC2.202510052233-1_amd64.deb +wget https://download.libreqos.com/libreqos_1.5-RC2.202510052233-1_amd64.deb sudo apt install ./libreqos_1.5-RC2.202510052233-1_amd64.deb ``` -- knotmirror 0.0.1 From 9317a655477e9f4be5a3d985e9582e9b48af32d9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Robert=20Chac=C3=B3n?= Date: Sun, 5 Oct 2025 16:50:53 -0600 Subject: [PATCH 25/61] Update update.md --- docs-es/v2.0/Updates/update.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs-es/v2.0/Updates/update.md b/docs-es/v2.0/Updates/update.md index 845ddec4..e026798c 100644 --- a/docs-es/v2.0/Updates/update.md +++ b/docs-es/v2.0/Updates/update.md @@ -10,7 +10,7 @@ Si usa el puente XDP, el tráfico dejará de pasar brevemente a través del puen cd ~ sudo apt-get update sudo apt-get upgrade -wget http://download.libreqos.com/libreqos_1.5-RC2.202510052233-1_amd64.deb +wget https://download.libreqos.com/libreqos_1.5-RC2.202510052233-1_amd64.deb sudo apt install ./libreqos_1.5-RC2.202510052233-1_amd64.deb sudo systemctl restart lqosd lqos_scheduler ``` -- knotmirror 0.0.1 From 98109465e2b79bc75871bb4f95ff37f994fbcabd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Robert=20Chac=C3=B3n?= Date: Sun, 5 Oct 2025 16:51:04 -0600 Subject: [PATCH 26/61] Update quickstart-es.md --- docs-es/v2.0/quickstart-es.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs-es/v2.0/quickstart-es.md b/docs-es/v2.0/quickstart-es.md index d20ad538..15df0d5d 100644 --- a/docs-es/v2.0/quickstart-es.md +++ b/docs-es/v2.0/quickstart-es.md @@ -19,7 +19,7 @@ cd ~ sudo apt-get update sudo apt-get upgrade -wget http://download.libreqos.com/libreqos_1.5-RC2.202510052233-1_amd64.deb +wget https://download.libreqos.com/libreqos_1.5-RC2.202510052233-1_amd64.deb sudo apt install ./libreqos_1.5-RC2.202510052233-1_amd64.deb ``` -- knotmirror 0.0.1 From 415eef2740a77458a48198770c4cb66d284462e9 Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Mon, 6 Oct 2025 10:27:22 -0500 Subject: [PATCH 27/61] Fix: Build script doesn't care if services aren't running. --- src/build_dpkg.sh | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/src/build_dpkg.sh b/src/build_dpkg.sh index 2ee40354..93cd30cd 100755 --- a/src/build_dpkg.sh +++ b/src/build_dpkg.sh @@ -116,18 +116,21 @@ sudo chown -R $USER /opt/libreqos cp /opt/libreqos/src/bin/lqosd.service.example /etc/systemd/system/lqosd.service cp /opt/libreqos/src/bin/lqos_scheduler.service.example /etc/systemd/system/lqos_scheduler.service cp /opt/libreqos/src/bin/lqos_api.service.example /etc/systemd/system/lqos_api.service -/bin/systemctl daemon-reload +/bin/systemctl daemon-reload || true /bin/systemctl stop lqos_node_manager || true # In case it's running from a previous release /bin/systemctl disable lqos_node_manager || true # In case it's running from a previous release -/bin/systemctl enable lqosd lqos_scheduler lqos_api -/bin/systemctl start lqosd lqos_scheduler lqos_api +/bin/systemctl enable lqosd lqos_scheduler lqos_api || true +/bin/systemctl start lqosd lqos_scheduler lqos_api || true EOF # Uninstall Script cat < postrm #!/bin/bash -/bin/systemctl stop lqosd lqos_scheduler lqos_api -/bin/systemctl disable lqosd lqos_scheduler lqos_api +set +e +/bin/systemctl stop lqosd lqos_scheduler lqos_api || true +/bin/systemctl disable lqosd lqos_scheduler lqos_api || true +/bin/systemctl daemon-reload || true +exit 0 EOF chmod a+x postinst postrm popd > /dev/null || exit -- knotmirror 0.0.1 From 935f7c0c926f9481d0546732ba5b9b8b92e1fefa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Robert=20Chac=C3=B3n?= Date: Thu, 9 Oct 2025 21:37:37 -0600 Subject: [PATCH 28/61] Update prereq.md --- docs/v2.0/prereq.md | 26 +++++++++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/docs/v2.0/prereq.md b/docs/v2.0/prereq.md index ec75681d..606b222d 100644 --- a/docs/v2.0/prereq.md +++ b/docs/v2.0/prereq.md @@ -1,6 +1,8 @@ -# Server Setup Prerequisites +# Prerequisites -## Disable Hyper-Threading in the BIOS +## Servers & Hypervisors + +### Disable Hyper-Threading in the BIOS Disable hyperthreading on the BIOS/UEFI of your host system. Hyperthreaading is also known as Simultaneous Multi Threading (SMT) on AMD systems. Disabling this is very important for optimal performance of the XDP cpumap filtering and, in turn, throughput and latency. - Boot, pressing the appropriate key to enter the BIOS settings @@ -8,6 +10,24 @@ Disable hyperthreading on the BIOS/UEFI of your host system. Hyperthreaading is - For Intel systems, you will also have to navigate the settings to find the "hyperthrading" toggle option. On HP servers it's under ```System Configuration > BIOS/Platform Configuration (RBSU) > Processor Options > Intel (R) Hyperthreading Options.``` - Save changes and reboot -## Disable SR-IOV in the BIOS +### Disable SR-IOV in the BIOS SR-IOV can disable XDP native (driver mode) on Physical Functions (PFs), forcing XDP Generic (SKB) and reducing performance and stability for LibreQoS. Disable SR-IOV in BIOS/UEFI for NICs used by LibreQoS. If per-slot/per-port options exist, set them to Disabled. + +## Hypervisors + +### Proxmox + +For Proxmox VMs, NIC passthrough is required to achieve throughput above 10 Gbps (XDP vs generic XDP). + +LibreQoS requires 2 or more RX/TX queues, so when using Proxmox, please be sure to enable [Multiqueue](https://forum.proxmox.com/threads/where-is-multiqueue.146783/) for the shaping interfaces assigned to the VM. Multiqueue should be set equal to the number of vCPU cores assigned to the VM. + +### Hyper-V + +#### Hyper-V MAC Spoofing (If Inside a VM) + +If your LibreQoS system is running inside Hyper-V and you’ve bridged two vNICs (eth1, eth2) — Hyper-V will block traffic from the bridge because the bridge generates frames with different MACs than the vNIC’s assigned MAC. To fix this on a Windows host: +``` +Set-VMNetworkAdapter -VMName "YourLinuxVM" -MacAddressSpoofing On +``` +Then restart the VM. -- knotmirror 0.0.1 From f34a265ee97609b330149e6420835930a684943e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Robert=20Chac=C3=B3n?= Date: Thu, 9 Oct 2025 21:38:57 -0600 Subject: [PATCH 29/61] Update prereq-es.md --- docs-es/v2.0/prereq-es.md | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/docs-es/v2.0/prereq-es.md b/docs-es/v2.0/prereq-es.md index 1c21aa06..11013f68 100644 --- a/docs-es/v2.0/prereq-es.md +++ b/docs-es/v2.0/prereq-es.md @@ -1,6 +1,8 @@ # Requisitos previos para la configuración del servidor -## Desactivar Hyper-Threading +## Servidores e hipervisores + +### Desactivar Hyper-Threading Desactiva el Hyper-Threading en la BIOS/UEFI de tu sistema host. El Hyper-Threading también se conoce como Simultaneous Multi Threading (SMT) en sistemas AMD. Desactivarlo es muy importante para obtener un rendimiento óptimo del filtrado cpumap con XDP y, por ende, mejorar el rendimiento y la latencia. - Inicia el sistema y presiona la tecla correspondiente para entrar a la configuración de la BIOS. @@ -8,6 +10,24 @@ Desactiva el Hyper-Threading en la BIOS/UEFI de tu sistema host. El Hyper-Thread - En sistemas Intel, también deberás buscar la opción para desactivar el Hyper-Threading en ajustes. En servidores HP, por ejemplo, está ubicada en: ```System Configuration > BIOS/Platform Configuration (RBSU) > Processor Options > Intel (R) Hyperthreading Options``` - Guarda los cambios y reinicia el sistema. -## Desactivar SR-IOV en la BIOS +### Desactivar SR-IOV en la BIOS SR-IOV puede desactivar XDP nativo (modo controlador) en las Funciones Físicas (PF), forzando XDP Genérico (SKB) y reduciendo el rendimiento y la estabilidad de LibreQoS. Desactive SR-IOV en la BIOS/UEFI para las tarjetas de red (NIC) utilizadas por LibreQoS. Si existen opciones por ranura/por puerto, desactívelas. + +## Hipervisores + +### Proxmox + +Para las máquinas virtuales Proxmox, se requiere el paso a través de la tarjeta de red (NIC) para alcanzar un rendimiento superior a 10 Gbps (XDP vs. XDP genérico). + +LibreQoS requiere dos o más colas RX/TX, por lo que al usar Proxmox, asegúrese de habilitar [Multicola](https://forum.proxmox.com/threads/where-is-multiqueue.146783/) para las interfaces de modelado asignadas a la máquina virtual. La multicola debe tener un valor igual al número de núcleos de vCPU asignados a la máquina virtual. + +### Hyper-V + +#### Suplantación de MAC en Hyper-V (Si está dentro de una máquina virtual) + +Si su sistema LibreQoS se ejecuta dentro de Hyper-V y ha conectado dos vNIC (eth1, eth2), Hyper-V bloqueará el tráfico del puente porque este genera tramas con direcciones MAC diferentes a la asignada a la vNIC. Para solucionar esto en un host Windows: +``` +Set-VMNetworkAdapter -VMName "YourLinuxVM" -MacAddressSpoofing On +``` +Luego, reinicie la máquina virtual. -- knotmirror 0.0.1 From 9ea09f65940427cd3a18c1bff76953f6ab77fa94 Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Thu, 30 Oct 2025 13:10:09 -0500 Subject: [PATCH 30/61] Feat: IP mappings are now retained in the bakery, allowing us to skip the "full clear and reload all mappings" step. Paves the way for better circuit change handling. --- src/LibreQoS.py | 9 +- src/rust/Cargo.lock | 1 + src/rust/lqos_bakery/Cargo.toml | 1 + src/rust/lqos_bakery/src/commands.rs | 22 +++ src/rust/lqos_bakery/src/lib.rs | 225 +++++++++++++++++++++++++++ src/rust/lqosd/src/main.rs | 40 ++++- 6 files changed, 288 insertions(+), 10 deletions(-) diff --git a/src/LibreQoS.py b/src/LibreQoS.py index 87e09a40..fa16bb6f 100755 --- a/src/LibreQoS.py +++ b/src/LibreQoS.py @@ -157,8 +157,7 @@ def tearDown(interfaceA, interfaceB): # Full teardown of everything for exiting LibreQoS if enable_actual_shell_commands(): # Clear IP filters and remove xdp program from interfaces - #result = os.system('./bin/xdp_iphash_to_cpu_cmdline clear') - clear_ip_mappings() # Use the bus + # The bakery tracks and prunes mappings; avoid clearing everything here. clearPriorSettings(interfaceA, interfaceB) def findQueuesAvailable(interfaceName): @@ -1135,10 +1134,8 @@ def refreshShapers(): # Setup XDP and disable XPS regardless of whether it is first run or not (necessary to handle cases where systemctl stop was used) xdpStartTime = datetime.now() - if enable_actual_shell_commands(): - # Here we use os.system for the command, because otherwise it sometimes gltiches out with Popen in shell() - #result = os.system('./bin/xdp_iphash_to_cpu_cmdline clear') - clear_ip_mappings() # Use the bus + #if enable_actual_shell_commands(): + # The bakery will handle stale mapping cleanup; avoid clearing mappings here. # Set up XDP-CPUMAP-TC logging.info("# XDP Setup") # Commented out - the daemon does this diff --git a/src/rust/Cargo.lock b/src/rust/Cargo.lock index 86958614..d2a592a0 100644 --- a/src/rust/Cargo.lock +++ b/src/rust/Cargo.lock @@ -1896,6 +1896,7 @@ dependencies = [ "lqos_config", "once_cell", "parking_lot", + "tokio", "tracing", ] diff --git a/src/rust/lqos_bakery/Cargo.toml b/src/rust/lqos_bakery/Cargo.toml index 38adce64..fac885ae 100644 --- a/src/rust/lqos_bakery/Cargo.toml +++ b/src/rust/lqos_bakery/Cargo.toml @@ -13,3 +13,4 @@ once_cell.workspace = true allocative.workspace = true allocative_derive.workspace = true parking_lot.workspace = true +tokio.workspace = true diff --git a/src/rust/lqos_bakery/src/commands.rs b/src/rust/lqos_bakery/src/commands.rs index dc90098f..d6e670e3 100644 --- a/src/rust/lqos_bakery/src/commands.rs +++ b/src/rust/lqos_bakery/src/commands.rs @@ -47,6 +47,28 @@ pub enum ExecutionMode { /// List of commands that the Bakery system can handle. #[derive(Debug, Clone, Allocative)] pub enum BakeryCommands { + /// Add or update an IP mapping (mirrors `MapIpToFlow` from the bus) + MapIp { + /// The IP address to map (may include CIDR prefix) + ip_address: String, + /// Classifier handle (major:minor) + tc_handle: TcHandle, + /// CPU index + cpu: u32, + /// Upload map (on-a-stick second map) + upload: bool, + }, + /// Delete an IP mapping (mirrors `DelIpFlow` from the bus) + DelIp { + /// The IP address to unmap (may include CIDR prefix) + ip_address: String, + /// Upload map (on-a-stick second map) + upload: bool, + }, + /// Clear all IP mappings (mirrors `ClearIpFlow` from the bus) + ClearIpAll, + /// Commit the current set of staged IP mappings and perform stale cleanup. + CommitMappings, /// Send this when circuits are seen by the throughput tracker OnCircuitActivity { /// All active circuit IDs diff --git a/src/rust/lqos_bakery/src/lib.rs b/src/rust/lqos_bakery/src/lib.rs index 5464f681..91ec75cc 100644 --- a/src/rust/lqos_bakery/src/lib.rs +++ b/src/rust/lqos_bakery/src/lib.rs @@ -39,6 +39,7 @@ use crate::queue_math::format_rate_for_tc_f32; use crate::utils::{execute_in_memory, write_command_file}; pub use commands::BakeryCommands; use lqos_config::{Config, LazyQueueMode}; +use lqos_bus::{BusRequest, BusResponse, LibreqosBusClient, TcHandle}; /// Count of Bakery-Managed circuits that are currently active. pub static ACTIVE_CIRCUITS: AtomicUsize = AtomicUsize::new(0); @@ -70,6 +71,145 @@ fn bakery_main(rx: Receiver, tx: Sender) { let mut circuits: HashMap> = HashMap::new(); let mut live_circuits: HashMap = HashMap::new(); + // Mapping state + #[derive(Clone, Hash, PartialEq, Eq, Debug)] + struct MappingKey { + ip: String, + prefix: u32, + upload: bool, + } + #[derive(Clone, Debug)] + struct MappingVal { + handle: TcHandle, + cpu: u32, + } + // Current kernel view (authoritative state) as tracked by the bakery + let mut mapping_current: HashMap = HashMap::new(); + // Next desired set staged during a batch (Python batches or other tools) + let mut mapping_staged: Option> = None; + // Keys that exist in the kernel but we couldn't classify to a known circuit (never delete automatically) + let mut mapping_unknown: HashSet = HashSet::new(); + let mut mapping_seeded: bool = false; + + fn parse_ip_and_prefix(ip: &str) -> (String, u32) { + if let Some((addr, pfx)) = ip.split_once('/') { + if let Ok(n) = pfx.parse::() { + return (addr.to_string(), n); + } + } + // No prefix provided; infer by address family + // Simple heuristic: ':' suggests IPv6 + if ip.contains(':') { + (ip.to_string(), 128) + } else { + (ip.to_string(), 32) + } + } + + fn handle_map_ip( + ip_address: &str, + tc_handle: TcHandle, + cpu: u32, + upload: bool, + mapping_staged: &mut Option>, + ) { + let (ip, prefix) = parse_ip_and_prefix(ip_address); + let key = MappingKey { ip, prefix, upload }; + let val = MappingVal { handle: tc_handle, cpu }; + if mapping_staged.is_none() { + *mapping_staged = Some(HashMap::new()); + } + if let Some(stage) = mapping_staged.as_mut() { + stage.insert(key, val); + } + } + + fn handle_del_ip( + ip_address: &str, + upload: bool, + mapping_staged: &mut Option>, + mapping_current: &mut HashMap, + ) { + // Best-effort deletion: if exact prefix was provided, remove that, else try common host prefixes + let (ip, prefix) = parse_ip_and_prefix(ip_address); + let key = MappingKey { ip: ip.clone(), prefix, upload }; + if let Some(stage) = mapping_staged.as_mut() { + stage.remove(&key); + } + mapping_current.remove(&key); + } + + fn build_handle_sets( + circuits: &HashMap>, + ) -> (HashSet, HashSet) { + let mut down = HashSet::new(); + let mut up = HashSet::new(); + for (_k, v) in circuits.iter() { + if let BakeryCommands::AddCircuit { + class_minor, + class_major, + up_class_major, + .. + } = v.as_ref() + { + let down_tc = TcHandle::from_u32(((*class_major as u32) << 16) | (*class_minor as u32)); + let up_tc = TcHandle::from_u32(((*up_class_major as u32) << 16) | (*class_minor as u32)); + down.insert(down_tc); + up.insert(up_tc); + } + } + (down, up) + } + + fn attempt_seed_mappings( + circuits: &HashMap>, + mapping_current: &mut HashMap, + mapping_unknown: &mut HashSet, + ) -> anyhow::Result<()> { + // Build classification sets + let (down_set, up_set) = build_handle_sets(circuits); + + // Create a small runtime to make a one-shot bus request + let rt = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build()?; + rt.block_on(async { + let mut bus = LibreqosBusClient::new().await?; + let reply = bus.request(vec![BusRequest::ListIpFlow]).await?; + for r in reply.iter() { + if let BusResponse::MappedIps(list) = r { + for m in list.iter() { + // m.ip_address does not include prefix, prefix_length is provided + let key = MappingKey { + ip: m.ip_address.clone(), + prefix: m.prefix_length, + upload: if up_set.contains(&m.tc_handle) { + true + } else if down_set.contains(&m.tc_handle) { + false + } else { + // Unknown mapping (do not delete automatically) + let k = MappingKey { + ip: m.ip_address.clone(), + prefix: m.prefix_length, + upload: false, // default; upload is unknown + }; + mapping_unknown.insert(k.clone()); + mapping_current.insert( + k, + MappingVal { handle: m.tc_handle, cpu: m.cpu }, + ); + continue; + }, + }; + mapping_current.insert(key, MappingVal { handle: m.tc_handle, cpu: m.cpu }); + } + } + } + anyhow::Ok(()) + }) + } + { let Ok(config) = lqos_config::load_config() else { error!("Failed to load configuration, exiting Bakery thread."); @@ -86,6 +226,91 @@ fn bakery_main(rx: Receiver, tx: Sender) { debug!("Bakery received command: {:?}", command); match command { + // Mapping events (mirrored from lqosd bus handling) + BakeryCommands::MapIp { + ip_address, + tc_handle, + cpu, + upload, + } => { + handle_map_ip(&ip_address, tc_handle, cpu, upload, &mut mapping_staged); + } + BakeryCommands::DelIp { ip_address, upload } => { + handle_del_ip(&ip_address, upload, &mut mapping_staged, &mut mapping_current); + } + BakeryCommands::ClearIpAll => { + mapping_current.clear(); + mapping_unknown.clear(); + mapping_staged = None; + } + BakeryCommands::CommitMappings => { + // Ensure we are seeded before first commit to avoid assuming empty kernel state. + if !mapping_seeded { + match attempt_seed_mappings(&circuits, &mut mapping_current, &mut mapping_unknown) { + Ok(_) => { + info!("Bakery: Seeded IP mappings from kernel"); + mapping_seeded = true; + } + Err(e) => warn!("Bakery: Failed to seed IP mappings: {:?}", e), + } + } + + if let Some(staged) = mapping_staged.take() { + // Remove stale mappings: present in current, not in staged; never delete unknowns + let mut stale = Vec::new(); + for k in mapping_current.keys() { + if mapping_unknown.contains(k) { + continue; // don't touch unknowns + } + if !staged.contains_key(k) { + stale.push(k.clone()); + } + } + + if !stale.is_empty() { + // Batch deletions via the bus client + let rt = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build(); + if let Ok(rt) = rt { + let stale_to_delete = stale.clone(); + let _ = rt.block_on(async move { + if let Ok(mut bus) = LibreqosBusClient::new().await { + // chunk operations to keep request sizes reasonable + const CHUNK: usize = 512; + for chunk in stale_to_delete.chunks(CHUNK) { + let mut reqs = Vec::with_capacity(chunk.len()); + for k in chunk.iter() { + // Recompose an IP string with prefix if not host (/32 or /128) + let ip = if k.prefix == 32 || k.prefix == 128 { + k.ip.clone() + } else { + format!("{}/{}", k.ip, k.prefix) + }; + reqs.push(BusRequest::DelIpFlow { + ip_address: ip, + upload: k.upload, + }); + } + let _ = bus.request(reqs).await; + } + } + }); + } else { + warn!("Bakery: Unable to create runtime for stale IP deletions"); + } + + for k in stale.into_iter() { + mapping_current.remove(&k); + } + } + + // Merge staged into current (they are already applied in kernel by lqosd) + for (k, v) in staged.into_iter() { + mapping_current.insert(k, v); + } + } + } BakeryCommands::StartBatch => { batch = Some(Vec::new()); } diff --git a/src/rust/lqosd/src/main.rs b/src/rust/lqosd/src/main.rs index f3d4e5b4..a3919369 100644 --- a/src/rust/lqosd/src/main.rs +++ b/src/rust/lqosd/src/main.rs @@ -350,10 +350,42 @@ fn handle_bus_requests(requests: &[BusRequest], responses: &mut Vec tc_handle, cpu, upload, - } => map_ip_to_flow(ip_address, tc_handle, *cpu, *upload), - BusRequest::ClearHotCache => clear_hot_cache(), - BusRequest::DelIpFlow { ip_address, upload } => del_ip_flow(ip_address, *upload), - BusRequest::ClearIpFlow => clear_ip_flows(), + } => { + let resp = map_ip_to_flow(ip_address, tc_handle, *cpu, *upload); + if let Some(sender) = lqos_bakery::BAKERY_SENDER.get() { + let _ = sender.send(lqos_bakery::BakeryCommands::MapIp { + ip_address: ip_address.clone(), + tc_handle: *tc_handle, + cpu: *cpu, + upload: *upload, + }); + } + resp + } + BusRequest::ClearHotCache => { + // Let the bakery finalize staged mapping changes, then clear hot cache. + if let Some(sender) = lqos_bakery::BAKERY_SENDER.get() { + let _ = sender.send(lqos_bakery::BakeryCommands::CommitMappings); + } + clear_hot_cache() + } + BusRequest::DelIpFlow { ip_address, upload } => { + let resp = del_ip_flow(ip_address, *upload); + if let Some(sender) = lqos_bakery::BAKERY_SENDER.get() { + let _ = sender.send(lqos_bakery::BakeryCommands::DelIp { + ip_address: ip_address.clone(), + upload: *upload, + }); + } + resp + } + BusRequest::ClearIpFlow => { + let resp = clear_ip_flows(); + if let Some(sender) = lqos_bakery::BAKERY_SENDER.get() { + let _ = sender.send(lqos_bakery::BakeryCommands::ClearIpAll); + } + resp + } BusRequest::ListIpFlow => list_mapped_ips(), BusRequest::XdpPping => throughput_tracker::xdp_pping_compat(), BusRequest::RttHistogram => throughput_tracker::rtt_histogram::<50>(), -- knotmirror 0.0.1 From 956415e5717cdb6936d3d85afcb9607b5a137c6a Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Thu, 30 Oct 2025 13:40:13 -0500 Subject: [PATCH 31/61] Feat: Dynamic circuit changes Circuits can now be added, removed, change speed and IP without triggering a full reload. Changes happen in-place (circuits are removed and re-added, not ideal but works around TC bugs). --- src/rust/lqos_bakery/src/commands.rs | 2 + src/rust/lqos_bakery/src/diff/circuits.rs | 121 ++++++++------ src/rust/lqos_bakery/src/diff/mod.rs | 2 +- src/rust/lqos_bakery/src/lib.rs | 182 +++++++++++++--------- src/rust/lqosd/src/main.rs | 15 ++ 5 files changed, 202 insertions(+), 120 deletions(-) diff --git a/src/rust/lqos_bakery/src/commands.rs b/src/rust/lqos_bakery/src/commands.rs index d6e670e3..e66e62ff 100644 --- a/src/rust/lqos_bakery/src/commands.rs +++ b/src/rust/lqos_bakery/src/commands.rs @@ -47,6 +47,8 @@ pub enum ExecutionMode { /// List of commands that the Bakery system can handle. #[derive(Debug, Clone, Allocative)] pub enum BakeryCommands { + /// Notification that the bus socket is ready; bakery can seed mappings + BusReady, /// Add or update an IP mapping (mirrors `MapIpToFlow` from the bus) MapIp { /// The IP address to map (may include CIDR prefix) diff --git a/src/rust/lqos_bakery/src/diff/circuits.rs b/src/rust/lqos_bakery/src/diff/circuits.rs index cc9f21b1..8400cccf 100644 --- a/src/rust/lqos_bakery/src/diff/circuits.rs +++ b/src/rust/lqos_bakery/src/diff/circuits.rs @@ -3,13 +3,17 @@ use std::collections::HashMap; use std::sync::Arc; use tracing::warn; +pub(crate) struct CircuitDiffCategories<'a> { + pub newly_added: Vec<&'a Arc>, + pub removed_circuits: Vec, + pub speed_changed: Vec<&'a Arc>, + pub ip_changed: Vec<&'a Arc>, + pub structural_changed: Vec<&'a Arc>, +} + pub(crate) enum CircuitDiffResult<'a> { NoChange, - CircuitsChanged { - newly_added: Vec<&'a Arc>, - removed_circuits: Vec, // Just store the circuit hash for removal - updated_circuits: Vec<&'a Arc>, - }, + Categorized(CircuitDiffCategories<'a>), } pub(crate) fn diff_circuits<'a>( @@ -27,46 +31,67 @@ pub(crate) fn diff_circuits<'a>( }) .collect(); - // Find any circuits that have been added to `new_circuits` and not in `old_circuits` let mut newly_added = Vec::new(); + let mut removed_circuits = Vec::new(); + let mut speed_changed = Vec::new(); + let mut ip_changed = Vec::new(); + let mut structural_changed = Vec::new(); + for (circuit_hash, new_cmd) in &new_circuits { if !old_circuits.contains_key(circuit_hash) { newly_added.push(*new_cmd); } } - // Find any circuits that have been removed from `new_circuits`, but were in `old_circuits` - let mut removed_circuits = Vec::new(); for circuit_hash in old_circuits.keys() { if !new_circuits.contains_key(circuit_hash) { removed_circuits.push(*circuit_hash); } } - // Find any circuits that have changed in `new_circuits` compared to `old_circuits` - let mut updated_circuits = Vec::new(); for (circuit_hash, old_cmd) in old_circuits { - if let Some(new_cmd) = new_circuits.get(circuit_hash) - && has_circuit_changed(old_cmd.as_ref(), new_cmd.as_ref()) { - updated_circuits.push(*new_cmd); + if let Some(new_cmd) = new_circuits.get(circuit_hash) { + match classify_circuit_change(old_cmd.as_ref(), new_cmd.as_ref()) { + CircuitChange::None => {} + CircuitChange::Structural => structural_changed.push(*new_cmd), + CircuitChange::Speed => speed_changed.push(*new_cmd), + CircuitChange::Ip => ip_changed.push(*new_cmd), + CircuitChange::SpeedAndIp => { + speed_changed.push(*new_cmd); + ip_changed.push(*new_cmd); + } } + } } - // If there are any changes, return them - if !newly_added.is_empty() || !removed_circuits.is_empty() || !updated_circuits.is_empty() { - CircuitDiffResult::CircuitsChanged { + if !newly_added.is_empty() + || !removed_circuits.is_empty() + || !speed_changed.is_empty() + || !ip_changed.is_empty() + || !structural_changed.is_empty() + { + CircuitDiffResult::Categorized(CircuitDiffCategories { newly_added, removed_circuits, - updated_circuits, - } + speed_changed, + ip_changed, + structural_changed, + }) } else { CircuitDiffResult::NoChange } } -fn has_circuit_changed(circuit_a: &BakeryCommands, circuit_b: &BakeryCommands) -> bool { +enum CircuitChange { + None, + Structural, + Speed, + Ip, + SpeedAndIp, +} + +fn classify_circuit_change(a: &BakeryCommands, b: &BakeryCommands) -> CircuitChange { let BakeryCommands::AddCircuit { - circuit_hash, parent_class_id, up_parent_class_id, class_minor, @@ -77,16 +102,13 @@ fn has_circuit_changed(circuit_a: &BakeryCommands, circuit_b: &BakeryCommands) - class_major, up_class_major, ip_addresses, - } = circuit_a + .. + } = a else { - warn!( - "circuit_changed called on non-circuit command: {:?}", - circuit_a - ); - return false; // Not a circuit command + warn!("classify_circuit_change called on non-circuit command: {:?}", a); + return CircuitChange::None; }; let BakeryCommands::AddCircuit { - circuit_hash: other_circuit_hash, parent_class_id: other_parent_class_id, up_parent_class_id: other_up_parent_class_id, class_minor: other_class_minor, @@ -97,31 +119,34 @@ fn has_circuit_changed(circuit_a: &BakeryCommands, circuit_b: &BakeryCommands) - class_major: other_class_major, up_class_major: other_up_class_major, ip_addresses: other_ip_addresses, - } = circuit_b + .. + } = b else { - warn!( - "circuit_changed called on non-circuit command: {:?}", - circuit_b - ); - return false; // Not a circuit command + warn!("classify_circuit_change called on non-circuit command: {:?}", b); + return CircuitChange::None; }; - if circuit_hash != other_circuit_hash { - // This should never happen - warn!( - "Circuit hashes do not match: {} != {}", - circuit_hash, other_circuit_hash - ); - return false; // Different circuit hashes - } - - parent_class_id != other_parent_class_id + // Structural change? + let structural = parent_class_id != other_parent_class_id || up_parent_class_id != other_up_parent_class_id || class_minor != other_class_minor - || download_bandwidth_min != other_download_bandwidth_min + || class_major != other_class_major + || up_class_major != other_up_class_major; + + if structural { + return CircuitChange::Structural; + } + + let speed = download_bandwidth_min != other_download_bandwidth_min || upload_bandwidth_min != other_upload_bandwidth_min || download_bandwidth_max != other_download_bandwidth_max - || upload_bandwidth_max != other_upload_bandwidth_max - || class_major != other_class_major - || up_class_major != other_up_class_major - || ip_addresses != other_ip_addresses + || upload_bandwidth_max != other_upload_bandwidth_max; + + let ip = ip_addresses != other_ip_addresses; + + match (speed, ip) { + (false, false) => CircuitChange::None, + (true, false) => CircuitChange::Speed, + (false, true) => CircuitChange::Ip, + (true, true) => CircuitChange::SpeedAndIp, + } } diff --git a/src/rust/lqos_bakery/src/diff/mod.rs b/src/rust/lqos_bakery/src/diff/mod.rs index 020a029d..23120f73 100644 --- a/src/rust/lqos_bakery/src/diff/mod.rs +++ b/src/rust/lqos_bakery/src/diff/mod.rs @@ -1,5 +1,5 @@ mod circuits; mod sites; -pub(crate) use circuits::{CircuitDiffResult, diff_circuits}; +pub(crate) use circuits::{CircuitDiffCategories, CircuitDiffResult, diff_circuits}; pub(crate) use sites::{SiteDiffResult, diff_sites}; diff --git a/src/rust/lqos_bakery/src/lib.rs b/src/rust/lqos_bakery/src/lib.rs index 91ec75cc..3c9b7609 100644 --- a/src/rust/lqos_bakery/src/lib.rs +++ b/src/rust/lqos_bakery/src/lib.rs @@ -34,7 +34,7 @@ use tracing::{debug, error, info, warn}; use utils::current_timestamp; pub(crate) const CHANNEL_CAPACITY: usize = 65536; // 64k capacity for Bakery commands use crate::commands::ExecutionMode; -use crate::diff::{SiteDiffResult, diff_sites}; +use crate::diff::{CircuitDiffResult, SiteDiffResult, diff_circuits, diff_sites}; use crate::queue_math::format_rate_for_tc_f32; use crate::utils::{execute_in_memory, write_command_file}; pub use commands::BakeryCommands; @@ -235,6 +235,19 @@ fn bakery_main(rx: Receiver, tx: Sender) { } => { handle_map_ip(&ip_address, tc_handle, cpu, upload, &mut mapping_staged); } + BakeryCommands::BusReady => { + if !mapping_seeded { + match attempt_seed_mappings(&circuits, &mut mapping_current, &mut mapping_unknown) { + Ok(_) => { + let total = mapping_current.len(); + let unknown = mapping_unknown.len(); + info!("Bakery mappings seeded: total={}, unknown={}", total, unknown); + mapping_seeded = true; + } + Err(e) => warn!("Bakery: Failed to seed IP mappings at bus-ready: {:?}", e), + } + } + } BakeryCommands::DelIp { ip_address, upload } => { handle_del_ip(&ip_address, upload, &mut mapping_staged, &mut mapping_current); } @@ -248,7 +261,9 @@ fn bakery_main(rx: Receiver, tx: Sender) { if !mapping_seeded { match attempt_seed_mappings(&circuits, &mut mapping_current, &mut mapping_unknown) { Ok(_) => { - info!("Bakery: Seeded IP mappings from kernel"); + let total = mapping_current.len(); + let unknown = mapping_unknown.len(); + info!("Bakery mappings seeded: total={}, unknown={}", total, unknown); mapping_seeded = true; } Err(e) => warn!("Bakery: Failed to seed IP mappings: {:?}", e), @@ -444,37 +459,41 @@ fn handle_commit_batch( let site_change_mode = diff_sites(&new_batch, sites); if matches!(site_change_mode, SiteDiffResult::RebuildRequired) { // If the site structure has changed, we need to rebuild everything. - info!("Site structure has changed, performing full reload."); + info!("Bakery full reload: site_struct=1, circuit_struct=0"); full_reload(batch, sites, circuits, live_circuits, &config, new_batch); MQ_CREATED.store(true, std::sync::atomic::Ordering::Relaxed); return; } - let circuit_change_mode = diff::diff_circuits(&new_batch, circuits); + let circuit_change_mode = diff_circuits(&new_batch, circuits); // If neither has changed, there's nothing to do. if matches!(site_change_mode, SiteDiffResult::NoChange) - && matches!(circuit_change_mode, diff::CircuitDiffResult::NoChange) + && matches!(circuit_change_mode, CircuitDiffResult::NoChange) { // No changes detected, skip processing info!("No changes detected in batch, skipping processing."); return; } - // Check if we should do a full reload based on the number of circuit changes - if let diff::CircuitDiffResult::CircuitsChanged { - newly_added: _, - removed_circuits: _, - updated_circuits: _, - } = &circuit_change_mode - { - full_reload(batch, sites, circuits, live_circuits, &config, new_batch); - return; // Skip the rest of this CommitBatch processing + // If any structural changes occurred, do a full reload + if let CircuitDiffResult::Categorized(categories) = &circuit_change_mode { + if !categories.structural_changed.is_empty() { + info!( + "Bakery full reload: site_struct=0, circuit_struct={}", + categories.structural_changed.len() + ); + full_reload(batch, sites, circuits, live_circuits, &config, new_batch); + MQ_CREATED.store(true, std::sync::atomic::Ordering::Relaxed); + return; + } } // Declare any site speed changes that need to be applied. We're sending them // to ourselves as future commands via the BakeryCommands channel. + let mut site_speed_change_count = 0usize; if let SiteDiffResult::SpeedChanges { changes } = site_change_mode { + site_speed_change_count = changes.len(); for change in &changes { let BakeryCommands::AddSite { site_hash, @@ -499,6 +518,7 @@ fn handle_commit_batch( upload_bandwidth_max: *upload_bandwidth_max, }) { error!("Channel full, falling back to full rebuild: {}", e); + info!("Bakery full reload: site_struct=0, circuit_struct=0"); full_reload( batch, sites, @@ -512,89 +532,109 @@ fn handle_commit_batch( } } - // Now we can process circuit changes - if let diff::CircuitDiffResult::CircuitsChanged { - newly_added, - removed_circuits, - updated_circuits, - } = circuit_change_mode - { - // Process removed circuits (including those that are being updated) - let mut circuits_to_remove = removed_circuits; - if !updated_circuits.is_empty() { - // For updates, we need to remove the old version first - for cmd in &updated_circuits { - if let BakeryCommands::AddCircuit { circuit_hash, .. } = cmd.as_ref() { - circuits_to_remove.push(*circuit_hash); - } - } - } + // Now we can process circuit changes incrementally + if let CircuitDiffResult::Categorized(categories) = circuit_change_mode { + // One-line summary of changes (info!) + info!( + "Bakery changes: sites_speed={}, circuits_added={}, removed={}, speed={}, ip={}", + site_speed_change_count, + categories.newly_added.len(), + categories.removed_circuits.len(), + categories.speed_changed.len(), + categories.ip_changed.len() + ); - // Removing circuits. - if !circuits_to_remove.is_empty() { - for circuit_hash in circuits_to_remove { + // 1) Removals + if !categories.removed_circuits.is_empty() { + for circuit_hash in categories.removed_circuits { if let Some(circuit) = circuits.remove(&circuit_hash) { let was_activated = live_circuits.contains_key(&circuit_hash); - - // Only generate removal commands if appropriate for the mode let commands = match config.queues.lazy_queues.as_ref() { + None | Some(LazyQueueMode::No) => circuit.to_prune(&config, true), + Some(LazyQueueMode::Htb) => { + if was_activated { circuit.to_prune(&config, false) } else { None } + } + Some(LazyQueueMode::Full) => { + if was_activated { circuit.to_prune(&config, true) } else { None } + } + }; + if let Some(cmd) = commands { execute_in_memory(&cmd, "removing circuit"); } + live_circuits.remove(&circuit_hash); + } else { + warn!("RemoveCircuit received for unknown circuit: {}", circuit_hash); + } + } + } + + // 2) Speed changes (avoid linux TC deadlock by removing qdisc first) + if !categories.speed_changed.is_empty() { + let mut commands = Vec::new(); + for cmd in &categories.speed_changed { + if let BakeryCommands::AddCircuit { circuit_hash, .. } = cmd.as_ref() { + let was_activated = live_circuits.contains_key(circuit_hash); + match config.queues.lazy_queues.as_ref() { None | Some(LazyQueueMode::No) => { - // Non-lazy: everything was created, delete everything - circuit.to_prune(&config, true) + // Remove both HTB and CAKE; then re-add fully + if let Some(prune) = cmd.to_prune(&config, true) { commands.extend(prune); } + if let Some(add) = cmd.to_commands(&config, ExecutionMode::Builder) { commands.extend(add); } + circuits.insert(*circuit_hash, Arc::clone(cmd)); } Some(LazyQueueMode::Htb) => { - // HTB mode: only delete CAKE if it was created if was_activated { - circuit.to_prune(&config, false) // This will only delete CAKE, not HTB + // Remove CAKE only + if let Some(prune) = cmd.to_prune(&config, false) { commands.extend(prune); } + // Update HTB with Builder (HTB only in Htb mode) + if let Some(add_htb) = cmd.to_commands(&config, ExecutionMode::Builder) { commands.extend(add_htb); } + // Re-add CAKE via LiveUpdate to minimize unshaped window + if let Some(add_qdisc) = cmd.to_commands(&config, ExecutionMode::LiveUpdate) { commands.extend(add_qdisc); } } else { - None // CAKE was never created, nothing to delete + // Not active: just ensure HTB state reflects new rates + if let Some(add_htb) = cmd.to_commands(&config, ExecutionMode::Builder) { commands.extend(add_htb); } } + circuits.insert(*circuit_hash, Arc::clone(cmd)); } Some(LazyQueueMode::Full) => { - // Full lazy: only delete the circuit if activated if was_activated { - circuit.to_prune(&config, true) + // Remove both, re-add in LiveUpdate (HTB + CAKE) + if let Some(prune) = cmd.to_prune(&config, true) { commands.extend(prune); } + if let Some(add_all) = cmd.to_commands(&config, ExecutionMode::LiveUpdate) { commands.extend(add_all); } } else { - None // Nothing was created, nothing to delete + // Not active: no TC state to touch; just record new definition } + circuits.insert(*circuit_hash, Arc::clone(cmd)); } - }; - - if let Some(cmd) = commands { - execute_in_memory(&cmd, "removing circuit"); } - live_circuits.remove(&circuit_hash); - } else { - warn!( - "RemoveCircuit received for unknown circuit: {}", - circuit_hash - ); - continue; } } + if !commands.is_empty() { + execute_in_memory(&commands, "updating circuit speeds"); + } } - // Newly added is a little harder - if !newly_added.is_empty() { - // Collect both newly added and updated circuits - let mut all_new_circuits: Vec<&Arc> = newly_added; - all_new_circuits.extend(updated_circuits); - let commands: Vec> = all_new_circuits + // 3) Additions + if !categories.newly_added.is_empty() { + let commands: Vec> = categories + .newly_added .iter() .filter_map(|c| c.to_commands(&config, ExecutionMode::Builder)) .flatten() .collect(); - if commands.is_empty() { - debug!("No commands to execute for newly added circuits."); - } else { + if !commands.is_empty() { execute_in_memory(&commands, "adding new circuits"); - // Update the circuit map with the newly added circuits - for command in all_new_circuits { - if let BakeryCommands::AddCircuit { circuit_hash, .. } = command.as_ref() { - circuits.insert(*circuit_hash, Arc::clone(command)); - } else { - warn!("AddCircuit received a non-circuit command: {:?}", command); - } + } + for command in categories.newly_added { + if let BakeryCommands::AddCircuit { circuit_hash, .. } = command.as_ref() { + circuits.insert(*circuit_hash, Arc::clone(command)); + } + } + } + + // 4) IP-only changes require no TC commands; mappings already handled by mapping engine + // We still refresh the stored circuit snapshot for those entries + if !categories.ip_changed.is_empty() { + for command in categories.ip_changed { + if let BakeryCommands::AddCircuit { circuit_hash, .. } = command.as_ref() { + circuits.insert(*circuit_hash, Arc::clone(command)); } } } diff --git a/src/rust/lqosd/src/main.rs b/src/rust/lqosd/src/main.rs index a3919369..9f5ffbc9 100644 --- a/src/rust/lqosd/src/main.rs +++ b/src/rust/lqosd/src/main.rs @@ -250,6 +250,21 @@ fn main() -> Result<()> { return; }; tokio_runtime.block_on(async { + // Notify bakery when the bus socket becomes available + tokio::spawn(async move { + use tokio::time::{sleep, Duration}; + // Wait up to ~5 seconds for the socket to appear + for _ in 0..100u32 { + if tokio::fs::metadata(lqos_bus::BUS_SOCKET_PATH).await.is_ok() { + break; + } + sleep(Duration::from_millis(50)).await; + } + if let Some(sender) = lqos_bakery::BAKERY_SENDER.get() { + let _ = sender.send(lqos_bakery::BakeryCommands::BusReady); + } + }); + tokio::spawn(async move { match lts2_sys::control_channel::start_control_channel(control_channel) .await -- knotmirror 0.0.1 From c1249bf4992d6ef892f4cb1e11c25fcc8c3eca0f Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Thu, 30 Oct 2025 13:58:56 -0500 Subject: [PATCH 32/61] Feat: Transactional circuit speed changes. Changing speed on a circuit is a 3-step process: create a temporary circuit, switch mappings to it. Remove the old circuit after a delay, and add in a replacement and switch mappings. After a final delay, remove the temporary circuit. This ensures that circuits remain shaped throughout the change process, and should minimize packet loss. --- src/rust/Cargo.lock | 1 + src/rust/lqos_bakery/Cargo.toml | 1 + src/rust/lqos_bakery/src/lib.rs | 430 ++++++++++++++++++++++++++++++-- 3 files changed, 410 insertions(+), 22 deletions(-) diff --git a/src/rust/Cargo.lock b/src/rust/Cargo.lock index d2a592a0..61cf32fd 100644 --- a/src/rust/Cargo.lock +++ b/src/rust/Cargo.lock @@ -1894,6 +1894,7 @@ dependencies = [ "crossbeam-channel", "lqos_bus", "lqos_config", + "lqos_sys", "once_cell", "parking_lot", "tokio", diff --git a/src/rust/lqos_bakery/Cargo.toml b/src/rust/lqos_bakery/Cargo.toml index fac885ae..74fb8abc 100644 --- a/src/rust/lqos_bakery/Cargo.toml +++ b/src/rust/lqos_bakery/Cargo.toml @@ -6,6 +6,7 @@ edition = "2024" [dependencies] lqos_config = { path = "../lqos_config" } lqos_bus = { path = "../lqos_bus" } +lqos_sys = { path = "../lqos_sys" } anyhow.workspace = true tracing.workspace = true crossbeam-channel.workspace = true diff --git a/src/rust/lqos_bakery/src/lib.rs b/src/rust/lqos_bakery/src/lib.rs index 3c9b7609..a995c320 100644 --- a/src/rust/lqos_bakery/src/lib.rs +++ b/src/rust/lqos_bakery/src/lib.rs @@ -40,6 +40,152 @@ use crate::utils::{execute_in_memory, write_command_file}; pub use commands::BakeryCommands; use lqos_config::{Config, LazyQueueMode}; use lqos_bus::{BusRequest, BusResponse, LibreqosBusClient, TcHandle}; +use lqos_sys; // direct mapping control for live-move to avoid bus full-sync side-effects + +// ---------------------- Live-Move Types and Helpers (module scope) ---------------------- + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum MigrationStage { + PrepareShadow, + SwapToShadow, + BuildFinal, + SwapToFinal, + TeardownShadow, + Done, +} + +#[derive(Clone, Debug)] +struct Migration { + circuit_hash: i64, + // Parent handles and majors + parent_class_id: TcHandle, + up_parent_class_id: TcHandle, + class_major: u16, + up_class_major: u16, + // Old and new rates + old_down_min: f32, + old_down_max: f32, + old_up_min: f32, + old_up_max: f32, + new_down_min: f32, + new_down_max: f32, + new_up_min: f32, + new_up_max: f32, + // Minors + old_minor: u16, + shadow_minor: u16, + final_minor: u16, + // IP list for remapping + ips: Vec, + stage: MigrationStage, +} + +fn parse_ip_list(s: &str) -> Vec { + s.split(',') + .map(|x| x.trim().to_string()) + .filter(|x| !x.is_empty()) + .collect() +} + +fn parse_ip_and_prefix(ip: &str) -> (String, u32) { + if let Some((addr, pfx)) = ip.split_once('/') { + if let Ok(n) = pfx.parse::() { + return (addr.to_string(), n); + } + } + if ip.contains(':') { (ip.to_string(), 128) } else { (ip.to_string(), 32) } +} + +fn tc_handle_from_major_minor(major: u16, minor: u16) -> TcHandle { + TcHandle::from_u32(((major as u32) << 16) | (minor as u32)) +} + +fn used_minors_for_parent( + circuits: &HashMap>, + parent: &TcHandle, +) -> HashSet { + let mut set = HashSet::new(); + for (_k, v) in circuits.iter() { + if let BakeryCommands::AddCircuit { + parent_class_id, + class_minor, + .. + } = v.as_ref() + { + if parent_class_id == parent { + set.insert(*class_minor); + } + } + } + set +} + +fn find_free_minor( + circuits: &HashMap>, + down_parent: &TcHandle, + up_parent: &TcHandle, +) -> Option { + let used_down = used_minors_for_parent(circuits, down_parent); + let used_up = used_minors_for_parent(circuits, up_parent); + for start in [0x2000u16, 0x4000, 0x6000, 0x8000, 0xA000, 0xC000, 0xE000] { + let end = start.saturating_add(0x1FFF); + for m in start..=end.min(0xFFFE) { + if !used_down.contains(&m) && !used_up.contains(&m) { + return Some(m); + } + } + } + for m in 1..=0xFFFEu16 { + if !used_down.contains(&m) && !used_up.contains(&m) { + return Some(m); + } + } + None +} + +fn add_commands_for_circuit( + cmd: &BakeryCommands, + config: &Arc, + mode: ExecutionMode, +) -> Option>> { + cmd.to_commands(config, mode) +} + +fn build_temp_add_cmd( + base: &BakeryCommands, + minor: u16, + down_min: f32, + down_max: f32, + up_min: f32, + up_max: f32, +) -> Option { + if let BakeryCommands::AddCircuit { + circuit_hash, + parent_class_id, + up_parent_class_id, + class_major, + up_class_major, + ip_addresses, + .. + } = base + { + Some(BakeryCommands::AddCircuit { + circuit_hash: *circuit_hash, + parent_class_id: *parent_class_id, + up_parent_class_id: *up_parent_class_id, + class_minor: minor, + download_bandwidth_min: down_min, + upload_bandwidth_min: up_min, + download_bandwidth_max: down_max, + upload_bandwidth_max: up_max, + class_major: *class_major, + up_class_major: *up_class_major, + ip_addresses: ip_addresses.clone(), + }) + } else { + None + } +} /// Count of Bakery-Managed circuits that are currently active. pub static ACTIVE_CIRCUITS: AtomicUsize = AtomicUsize::new(0); @@ -91,6 +237,9 @@ fn bakery_main(rx: Receiver, tx: Sender) { let mut mapping_unknown: HashSet = HashSet::new(); let mut mapping_seeded: bool = false; + let mut migrations: HashMap = HashMap::new(); + const MIGRATIONS_PER_TICK: usize = 16; + fn parse_ip_and_prefix(ip: &str) -> (String, u32) { if let Some((addr, pfx)) = ip.split_once('/') { if let Ok(n) = pfx.parse::() { @@ -336,6 +485,7 @@ fn bakery_main(rx: Receiver, tx: Sender) { &mut circuits, &mut live_circuits, &tx, + &mut migrations, ); } BakeryCommands::MqSetup { .. } => { @@ -359,6 +509,194 @@ fn bakery_main(rx: Receiver, tx: Sender) { BakeryCommands::Tick => { // Reset per-cycle counters at the start of the tick handle_tick(&mut circuits, &mut live_circuits, &mut sites); + + // Advance live-move migrations + let Ok(config) = lqos_config::load_config() else { + error!("Failed to load configuration, exiting Bakery thread."); + continue; + }; + let mut advanced = 0usize; + let mut to_remove = Vec::new(); + for (_hash, mig) in migrations.iter_mut() { + if advanced >= MIGRATIONS_PER_TICK { + break; + } + match mig.stage { + MigrationStage::PrepareShadow => { + // Create shadow HTB+CAKE with OLD rates + if let Some(temp) = build_temp_add_cmd( + &BakeryCommands::AddCircuit { + circuit_hash: mig.circuit_hash, + parent_class_id: mig.parent_class_id, + up_parent_class_id: mig.up_parent_class_id, + class_minor: mig.shadow_minor, + download_bandwidth_min: mig.old_down_min, + upload_bandwidth_min: mig.old_up_min, + download_bandwidth_max: mig.old_down_max, + upload_bandwidth_max: mig.old_up_max, + class_major: mig.class_major, + up_class_major: mig.up_class_major, + ip_addresses: "".to_string(), + }, + mig.shadow_minor, + mig.old_down_min, + mig.old_down_max, + mig.old_up_min, + mig.old_up_max, + ) { + let mut cmds = Vec::new(); + match config.queues.lazy_queues.as_ref() { + None | Some(LazyQueueMode::No) => { + if let Some(c) = add_commands_for_circuit(&temp, &config, ExecutionMode::Builder) { cmds.extend(c); } + } + Some(LazyQueueMode::Htb) => { + if let Some(c) = add_commands_for_circuit(&temp, &config, ExecutionMode::Builder) { cmds.extend(c); } + if let Some(c) = add_commands_for_circuit(&temp, &config, ExecutionMode::LiveUpdate) { cmds.extend(c); } + } + Some(LazyQueueMode::Full) => { + if let Some(c) = add_commands_for_circuit(&temp, &config, ExecutionMode::LiveUpdate) { cmds.extend(c); } + } + } + if !cmds.is_empty() { execute_in_memory(&cmds, "live-move: create shadow"); } + mig.stage = MigrationStage::SwapToShadow; + advanced += 1; + } else { + warn!("live-move: failed to build shadow add cmd for {}", mig.circuit_hash); + mig.stage = MigrationStage::Done; + advanced += 1; + } + } + MigrationStage::SwapToShadow => { + // Remap all IPs to shadow handles using existing CPU + for ip in &mig.ips { + let (ip_s, prefix) = parse_ip_and_prefix(ip); + for &upload in &[false, true] { + let key = MappingKey { ip: ip_s.clone(), prefix, upload }; + let cpu = mapping_current.get(&key).map(|v| v.cpu).unwrap_or(0); + let handle = if upload { + tc_handle_from_major_minor(mig.up_class_major, mig.shadow_minor) + } else { + tc_handle_from_major_minor(mig.class_major, mig.shadow_minor) + }; + let _ = lqos_sys::add_ip_to_tc(&ip_s, handle, cpu, upload); + // Update local mapping view + mapping_current.insert(key.clone(), MappingVal { handle, cpu }); + } + } + // Clear the hot cache directly + let _ = lqos_sys::clear_hot_cache(); + mig.stage = MigrationStage::BuildFinal; + advanced += 1; + } + MigrationStage::BuildFinal => { + // Delete old classes/qdiscs and create final with NEW rates at original minor + if let Some(old_cmd) = build_temp_add_cmd( + &BakeryCommands::AddCircuit { + circuit_hash: mig.circuit_hash, + parent_class_id: mig.parent_class_id, + up_parent_class_id: mig.up_parent_class_id, + class_minor: mig.old_minor, + download_bandwidth_min: mig.old_down_min, + upload_bandwidth_min: mig.old_up_min, + download_bandwidth_max: mig.old_down_max, + upload_bandwidth_max: mig.old_up_max, + class_major: mig.class_major, + up_class_major: mig.up_class_major, + ip_addresses: "".to_string(), + }, + mig.old_minor, + mig.old_down_min, + mig.old_down_max, + mig.old_up_min, + mig.old_up_max, + ) { + let mut cmds = Vec::new(); + if let Some(prune) = old_cmd.to_prune(&config, true) { cmds.extend(prune); } + // Final add (new rates) at final_minor + if let Some(final_cmd) = build_temp_add_cmd( + &old_cmd, + mig.final_minor, + mig.new_down_min, + mig.new_down_max, + mig.new_up_min, + mig.new_up_max, + ) { + match config.queues.lazy_queues.as_ref() { + None | Some(LazyQueueMode::No) => { + if let Some(c) = add_commands_for_circuit(&final_cmd, &config, ExecutionMode::Builder) { cmds.extend(c); } + } + Some(LazyQueueMode::Htb) => { + if let Some(c) = add_commands_for_circuit(&final_cmd, &config, ExecutionMode::Builder) { cmds.extend(c); } + if let Some(c) = add_commands_for_circuit(&final_cmd, &config, ExecutionMode::LiveUpdate) { cmds.extend(c); } + } + Some(LazyQueueMode::Full) => { + if let Some(c) = add_commands_for_circuit(&final_cmd, &config, ExecutionMode::LiveUpdate) { cmds.extend(c); } + } + } + } + if !cmds.is_empty() { execute_in_memory(&cmds, "live-move: build final"); } + mig.stage = MigrationStage::SwapToFinal; + advanced += 1; + } else { + warn!("live-move: failed to build old prune cmd for {}", mig.circuit_hash); + mig.stage = MigrationStage::Done; + advanced += 1; + } + } + MigrationStage::SwapToFinal => { + for ip in &mig.ips { + let (ip_s, prefix) = parse_ip_and_prefix(ip); + for &upload in &[false, true] { + let key = MappingKey { ip: ip_s.clone(), prefix, upload }; + let cpu = mapping_current.get(&key).map(|v| v.cpu).unwrap_or(0); + let handle = if upload { + tc_handle_from_major_minor(mig.up_class_major, mig.final_minor) + } else { + tc_handle_from_major_minor(mig.class_major, mig.final_minor) + }; + let _ = lqos_sys::add_ip_to_tc(&ip_s, handle, cpu, upload); + mapping_current.insert(key.clone(), MappingVal { handle, cpu }); + } + } + let _ = lqos_sys::clear_hot_cache(); + mig.stage = MigrationStage::TeardownShadow; + advanced += 1; + } + MigrationStage::TeardownShadow => { + // Remove shadow classes + if let Some(shadow_cmd) = build_temp_add_cmd( + &BakeryCommands::AddCircuit { + circuit_hash: mig.circuit_hash, + parent_class_id: mig.parent_class_id, + up_parent_class_id: mig.up_parent_class_id, + class_minor: mig.shadow_minor, + download_bandwidth_min: mig.old_down_min, + upload_bandwidth_min: mig.old_up_min, + download_bandwidth_max: mig.old_down_max, + upload_bandwidth_max: mig.old_up_max, + class_major: mig.class_major, + up_class_major: mig.up_class_major, + ip_addresses: "".to_string(), + }, + mig.shadow_minor, + mig.old_down_min, + mig.old_down_max, + mig.old_up_min, + mig.old_up_max, + ) { + if let Some(prune) = shadow_cmd.to_prune(&config, true) { + execute_in_memory(&prune, "live-move: prune shadow"); + } + } + mig.stage = MigrationStage::Done; + advanced += 1; + } + MigrationStage::Done => { + to_remove.push(mig.circuit_hash); + } + } + } + for h in to_remove { migrations.remove(&h); } } BakeryCommands::ChangeSiteSpeedLive { site_hash, @@ -436,6 +774,7 @@ fn handle_commit_batch( circuits: &mut HashMap>, live_circuits: &mut HashMap, tx: &Sender, + migrations: &mut HashMap, ) { let Ok(config) = lqos_config::load_config() else { error!("Failed to load configuration, exiting Bakery thread."); @@ -568,46 +907,93 @@ fn handle_commit_batch( // 2) Speed changes (avoid linux TC deadlock by removing qdisc first) if !categories.speed_changed.is_empty() { - let mut commands = Vec::new(); + let mut immediate_commands = Vec::new(); for cmd in &categories.speed_changed { - if let BakeryCommands::AddCircuit { circuit_hash, .. } = cmd.as_ref() { + if let BakeryCommands::AddCircuit { + circuit_hash, + parent_class_id, + up_parent_class_id, + class_minor, + download_bandwidth_min, + upload_bandwidth_min, + download_bandwidth_max, + upload_bandwidth_max, + class_major, + up_class_major, + ip_addresses, + } = cmd.as_ref() + { let was_activated = live_circuits.contains_key(circuit_hash); + if was_activated { + // Attempt live-move + if let Some(shadow_minor) = find_free_minor(circuits, parent_class_id, up_parent_class_id) { + // Find old command for old rates + if let Some(old_cmd) = circuits.get(circuit_hash) { + if let BakeryCommands::AddCircuit { + download_bandwidth_min: old_down_min, + upload_bandwidth_min: old_up_min, + download_bandwidth_max: old_down_max, + upload_bandwidth_max: old_up_max, + .. + } = old_cmd.as_ref() + { + let mig = Migration { + circuit_hash: *circuit_hash, + parent_class_id: *parent_class_id, + up_parent_class_id: *up_parent_class_id, + class_major: *class_major, + up_class_major: *up_class_major, + old_down_min: *old_down_min, + old_down_max: *old_down_max, + old_up_min: *old_up_min, + old_up_max: *old_up_max, + new_down_min: *download_bandwidth_min, + new_down_max: *download_bandwidth_max, + new_up_min: *upload_bandwidth_min, + new_up_max: *upload_bandwidth_max, + old_minor: *class_minor, + shadow_minor, + final_minor: *class_minor, + ips: parse_ip_list(ip_addresses), + stage: MigrationStage::PrepareShadow, + }; + migrations.insert(*circuit_hash, mig); + // Update desired circuit definition now + circuits.insert(*circuit_hash, Arc::clone(cmd)); + continue; // skip immediate path + } + } + } + } + // Fallback: immediate safe update match config.queues.lazy_queues.as_ref() { None | Some(LazyQueueMode::No) => { - // Remove both HTB and CAKE; then re-add fully - if let Some(prune) = cmd.to_prune(&config, true) { commands.extend(prune); } - if let Some(add) = cmd.to_commands(&config, ExecutionMode::Builder) { commands.extend(add); } - circuits.insert(*circuit_hash, Arc::clone(cmd)); + if let Some(prune) = cmd.to_prune(&config, true) { immediate_commands.extend(prune); } + if let Some(add) = cmd.to_commands(&config, ExecutionMode::Builder) { immediate_commands.extend(add); } } Some(LazyQueueMode::Htb) => { if was_activated { - // Remove CAKE only - if let Some(prune) = cmd.to_prune(&config, false) { commands.extend(prune); } - // Update HTB with Builder (HTB only in Htb mode) - if let Some(add_htb) = cmd.to_commands(&config, ExecutionMode::Builder) { commands.extend(add_htb); } - // Re-add CAKE via LiveUpdate to minimize unshaped window - if let Some(add_qdisc) = cmd.to_commands(&config, ExecutionMode::LiveUpdate) { commands.extend(add_qdisc); } + if let Some(prune) = cmd.to_prune(&config, false) { immediate_commands.extend(prune); } + if let Some(add_htb) = cmd.to_commands(&config, ExecutionMode::Builder) { immediate_commands.extend(add_htb); } + if let Some(add_qdisc) = cmd.to_commands(&config, ExecutionMode::LiveUpdate) { immediate_commands.extend(add_qdisc); } } else { - // Not active: just ensure HTB state reflects new rates - if let Some(add_htb) = cmd.to_commands(&config, ExecutionMode::Builder) { commands.extend(add_htb); } + if let Some(add_htb) = cmd.to_commands(&config, ExecutionMode::Builder) { immediate_commands.extend(add_htb); } } - circuits.insert(*circuit_hash, Arc::clone(cmd)); } Some(LazyQueueMode::Full) => { if was_activated { - // Remove both, re-add in LiveUpdate (HTB + CAKE) - if let Some(prune) = cmd.to_prune(&config, true) { commands.extend(prune); } - if let Some(add_all) = cmd.to_commands(&config, ExecutionMode::LiveUpdate) { commands.extend(add_all); } + if let Some(prune) = cmd.to_prune(&config, true) { immediate_commands.extend(prune); } + if let Some(add_all) = cmd.to_commands(&config, ExecutionMode::LiveUpdate) { immediate_commands.extend(add_all); } } else { - // Not active: no TC state to touch; just record new definition + // No TC ops } - circuits.insert(*circuit_hash, Arc::clone(cmd)); } } + circuits.insert(*circuit_hash, Arc::clone(cmd)); } } - if !commands.is_empty() { - execute_in_memory(&commands, "updating circuit speeds"); + if !immediate_commands.is_empty() { + execute_in_memory(&immediate_commands, "updating circuit speeds (fallback)"); } } -- knotmirror 0.0.1 From 5acf54fd78f7aef84efa0ca6e22559caa9b69c28 Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Thu, 30 Oct 2025 14:09:24 -0500 Subject: [PATCH 33/61] Feat: Improve the sorting handling to try to minimize structural (HTB tree) changes on reload. --- src/LibreQoS.py | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/src/LibreQoS.py b/src/LibreQoS.py index fa16bb6f..86b36092 100755 --- a/src/LibreQoS.py +++ b/src/LibreQoS.py @@ -755,7 +755,16 @@ def refreshShapers(): # - After processing all circuits for a node, we add CIRCUIT_PADDING to the minor counter # - This creates gaps that allow adding new circuits without affecting other ClassIDs # - Children are also sorted before recursive processing to ensure deterministic traversal - for node in sorted(data.keys()): + # For top-level binpacked keys (CpueQueueN), enforce numeric ordering of N + keys = list(data.keys()) + if depth == 0 and len(keys) > 0 and all(k.startswith("CpueQueue") for k in keys): + try: + keys.sort(key=lambda k: int(k.replace("CpueQueue", ""))) + except Exception: + keys = sorted(keys) + else: + keys = sorted(keys) + for node in keys: #if data[node]['type'] == "virtual": # print(node + " is a virtual node. Skipping.") # if depth == 0: @@ -903,6 +912,11 @@ def refreshShapers(): print("BinPacking is enabled, so we're going to sort your network.") cpuBin = {} weights = get_tree_weights() + # Stable tie-breaking: sort by (-weight, name) so equal weights have deterministic order + try: + weights = sorted(weights, key=lambda w: (-int(w.weight), str(w.name))) + except Exception: + pass for w in weights: cpuBin[w.name] = w.weight bins = binpacking.to_constant_bin_number(cpuBin, queuesAvailable) @@ -917,7 +931,8 @@ def refreshShapers(): 'type': 'site', 'downloadBandwidthMbpsMin': generated_pn_download_mbps(), 'uploadBandwidthMbpsMin': generated_pn_upload_mbps(), - 'children': {} + 'children': {}, + 'name': cpuKey } for node in network: found = False @@ -1009,7 +1024,7 @@ def refreshShapers(): case _: return sqm for node in sorted(data.keys()): - site_name = data[node]['name'] if 'name' in data[node] else "root" + site_name = data[node]['name'] if 'name' in data[node] else node bakery.add_site( site_name, data[node]['parentClassID'], -- knotmirror 0.0.1 From 725519e9dd723daa52a088089903c88eb789cf9e Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Thu, 30 Oct 2025 15:18:08 -0500 Subject: [PATCH 34/61] Chore: minor warning cleanup --- src/rust/lqos_bakery/src/diff/mod.rs | 2 +- src/rust/lqos_bakery/src/lib.rs | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/src/rust/lqos_bakery/src/diff/mod.rs b/src/rust/lqos_bakery/src/diff/mod.rs index 23120f73..020a029d 100644 --- a/src/rust/lqos_bakery/src/diff/mod.rs +++ b/src/rust/lqos_bakery/src/diff/mod.rs @@ -1,5 +1,5 @@ mod circuits; mod sites; -pub(crate) use circuits::{CircuitDiffCategories, CircuitDiffResult, diff_circuits}; +pub(crate) use circuits::{CircuitDiffResult, diff_circuits}; pub(crate) use sites::{SiteDiffResult, diff_sites}; diff --git a/src/rust/lqos_bakery/src/lib.rs b/src/rust/lqos_bakery/src/lib.rs index a995c320..be1294c1 100644 --- a/src/rust/lqos_bakery/src/lib.rs +++ b/src/rust/lqos_bakery/src/lib.rs @@ -87,14 +87,14 @@ fn parse_ip_list(s: &str) -> Vec { .collect() } -fn parse_ip_and_prefix(ip: &str) -> (String, u32) { +/*fn parse_ip_and_prefix(ip: &str) -> (String, u32) { if let Some((addr, pfx)) = ip.split_once('/') { if let Ok(n) = pfx.parse::() { return (addr.to_string(), n); } } if ip.contains(':') { (ip.to_string(), 128) } else { (ip.to_string(), 32) } -} +}*/ fn tc_handle_from_major_minor(major: u16, minor: u16) -> TcHandle { TcHandle::from_u32(((major as u32) << 16) | (minor as u32)) @@ -226,6 +226,7 @@ fn bakery_main(rx: Receiver, tx: Sender) { } #[derive(Clone, Debug)] struct MappingVal { + #[allow(dead_code)] handle: TcHandle, cpu: u32, } -- knotmirror 0.0.1 From 773ff589963c319ffb8a9074d08ad0b81d255759 Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Thu, 30 Oct 2025 16:42:08 -0500 Subject: [PATCH 35/61] Feat: Support adding sqm ("fq_codel" or "cake") as an extra column to ShapedDevices.csv, and the qdisc is built as intended. --- src/LibreQoS.py | 2686 +++++++++-------- src/ShapedDevices.example.csv | 24 +- src/rust/lqos_bakery/src/commands.rs | 36 +- src/rust/lqos_bakery/src/diff/circuits.rs | 5 +- src/rust/lqos_bakery/src/lib.rs | 9 + src/rust/lqos_bakery/src/queue_math.rs | 44 + src/rust/lqos_bus/src/bus/request.rs | 2 + .../lqos_config/src/shaped_devices/mod.rs | 3 + .../src/shaped_devices/shaped_device.rs | 32 +- src/rust/lqos_python/src/lib.rs | 5 + src/rust/lqosd/src/main.rs | 13 + 11 files changed, 1512 insertions(+), 1347 deletions(-) diff --git a/src/LibreQoS.py b/src/LibreQoS.py index 86b36092..69b16f9d 100755 --- a/src/LibreQoS.py +++ b/src/LibreQoS.py @@ -22,12 +22,12 @@ import binpacking from deepdiff import DeepDiff from liblqos_python import is_lqosd_alive, clear_ip_mappings, delete_ip_mapping, validate_shaped_devices, \ - is_libre_already_running, create_lock_file, free_lock_file, add_ip_mapping, BatchedCommands, \ - check_config, sqm, upstream_bandwidth_capacity_download_mbps, upstream_bandwidth_capacity_upload_mbps, \ - interface_a, interface_b, enable_actual_shell_commands, use_bin_packing_to_balance_cpu, monitor_mode_only, \ - run_shell_commands_as_sudo, generated_pn_download_mbps, generated_pn_upload_mbps, queues_available_override, \ - on_a_stick, get_tree_weights, get_weights, is_network_flat, get_libreqos_directory, enable_insight_topology, \ - Bakery + is_libre_already_running, create_lock_file, free_lock_file, add_ip_mapping, BatchedCommands, \ + check_config, sqm, upstream_bandwidth_capacity_download_mbps, upstream_bandwidth_capacity_upload_mbps, \ + interface_a, interface_b, enable_actual_shell_commands, use_bin_packing_to_balance_cpu, monitor_mode_only, \ + run_shell_commands_as_sudo, generated_pn_download_mbps, generated_pn_upload_mbps, queues_available_override, \ + on_a_stick, get_tree_weights, get_weights, is_network_flat, get_libreqos_directory, enable_insight_topology, \ + Bakery R2Q = 10 #MAX_R2Q = 200_000 @@ -39,1358 +39,1392 @@ MIN_QUANTUM = 1522 # Setting to 0 disables padding (not recommended for production) # Higher values provide more room for growth but reduce total capacity try: - from ispConfig import CIRCUIT_PADDING + from ispConfig import CIRCUIT_PADDING except ImportError: - CIRCUIT_PADDING = 8 # Default value if not configured + CIRCUIT_PADDING = 8 # Default value if not configured def get_shaped_devices_path(): - base_dir = get_libreqos_directory() + base_dir = get_libreqos_directory() - if enable_insight_topology(): - insight_path = os.path.join(base_dir, "ShapedDevices.insight.csv") - if os.path.exists(insight_path): - return insight_path + if enable_insight_topology(): + insight_path = os.path.join(base_dir, "ShapedDevices.insight.csv") + if os.path.exists(insight_path): + return insight_path - # Either insight not enabled, or file doesn't exist - return os.path.join(base_dir, "ShapedDevices.csv") + # Either insight not enabled, or file doesn't exist + return os.path.join(base_dir, "ShapedDevices.csv") def get_network_json_path(): - base_dir = get_libreqos_directory() + base_dir = get_libreqos_directory() - if enable_insight_topology(): - insight_path = os.path.join(base_dir, "network.insight.json") - if os.path.exists(insight_path): - return insight_path + if enable_insight_topology(): + insight_path = os.path.join(base_dir, "network.insight.json") + if os.path.exists(insight_path): + return insight_path - # Either insight not enabled, or file doesn't exist - return os.path.join(base_dir, "network.json") + # Either insight not enabled, or file doesn't exist + return os.path.join(base_dir, "network.json") def calculateR2q(maxRateInMbps): - # So we've learned that r2q defaults to 10, and is used to calculate quantum. Quantum is rateInBytes/r2q by - # default. This default gives errors at high rates, and tc clamps the quantum to 200000. Setting a high quantum - # directly gives no errors. So we want to calculate r2q to default to 10, but not exceed 200000 for the highest - # specified rate (which will be the available bandwidth rate). - maxRateInBytesPerSecond = maxRateInMbps * 125000 - r2q = 10 - quantum = maxRateInBytesPerSecond / r2q - while quantum > MAX_R2Q: - r2q += 1 - quantum = maxRateInBytesPerSecond / r2q - global R2Q - R2Q = r2q + # So we've learned that r2q defaults to 10, and is used to calculate quantum. Quantum is rateInBytes/r2q by + # default. This default gives errors at high rates, and tc clamps the quantum to 200000. Setting a high quantum + # directly gives no errors. So we want to calculate r2q to default to 10, but not exceed 200000 for the highest + # specified rate (which will be the available bandwidth rate). + maxRateInBytesPerSecond = maxRateInMbps * 125000 + r2q = 10 + quantum = maxRateInBytesPerSecond / r2q + while quantum > MAX_R2Q: + r2q += 1 + quantum = maxRateInBytesPerSecond / r2q + global R2Q + R2Q = r2q def quantum(rateInMbps): - # Attempt to calculate an appropriate quantum for an HTB queue, given - # that `mq` does not appear to carry a valid `r2q` value to individual - # root nodes. - rateInBytesPerSecond = rateInMbps * 125000 - quantum = max(MIN_QUANTUM, int(rateInBytesPerSecond / R2Q)) - #print("R2Q=" + str(R2Q) + ", quantum: " + str(quantum)) - quantrumString = " quantum " + str(quantum) - return quantrumString + # Attempt to calculate an appropriate quantum for an HTB queue, given + # that `mq` does not appear to carry a valid `r2q` value to individual + # root nodes. + rateInBytesPerSecond = rateInMbps * 125000 + quantum = max(MIN_QUANTUM, int(rateInBytesPerSecond / R2Q)) + #print("R2Q=" + str(R2Q) + ", quantum: " + str(quantum)) + quantrumString = " quantum " + str(quantum) + return quantrumString def format_rate_for_tc(rate_mbps): - """ - Format a rate in Mbps for TC commands with smart unit selection. - - Rates >= 1000 Mbps use 'gbit' - - Rates >= 1 Mbps use 'mbit' - - Rates < 1 Mbps use 'kbit' - """ - if rate_mbps >= 1000: - return f"{rate_mbps/1000:.1f}gbit" - elif rate_mbps >= 1: - return f"{rate_mbps:.1f}mbit" - else: - return f"{rate_mbps*1000:.0f}kbit" + """ + Format a rate in Mbps for TC commands with smart unit selection. + - Rates >= 1000 Mbps use 'gbit' + - Rates >= 1 Mbps use 'mbit' + - Rates < 1 Mbps use 'kbit' + """ + if rate_mbps >= 1000: + return f"{rate_mbps/1000:.1f}gbit" + elif rate_mbps >= 1: + return f"{rate_mbps:.1f}mbit" + else: + return f"{rate_mbps*1000:.0f}kbit" def shell(command): - if enable_actual_shell_commands(): - if run_shell_commands_as_sudo(): - command = 'sudo ' + command - logging.info(command) - commands = command.split(' ') - proc = subprocess.Popen(commands, stdout=subprocess.PIPE) - for line in io.TextIOWrapper(proc.stdout, encoding="utf-8"): # or another encoding - if logging.DEBUG <= logging.root.level: - print(line) - if ("RTNETLINK answers" in line) or ("We have an error talking to the kernel" in line): - warnings.warn("Command: '" + command + "' resulted in " + line, stacklevel=2) - else: - logging.info(command) + if enable_actual_shell_commands(): + if run_shell_commands_as_sudo(): + command = 'sudo ' + command + logging.info(command) + commands = command.split(' ') + proc = subprocess.Popen(commands, stdout=subprocess.PIPE) + for line in io.TextIOWrapper(proc.stdout, encoding="utf-8"): # or another encoding + if logging.DEBUG <= logging.root.level: + print(line) + if ("RTNETLINK answers" in line) or ("We have an error talking to the kernel" in line): + warnings.warn("Command: '" + command + "' resulted in " + line, stacklevel=2) + else: + logging.info(command) def shellReturn(command): - returnableString = '' - if enable_actual_shell_commands(): - commands = command.split(' ') - proc = subprocess.Popen(commands, stdout=subprocess.PIPE) - for line in io.TextIOWrapper(proc.stdout, encoding="utf-8"): # or another encoding - returnableString = returnableString + line + '\n' - return returnableString + returnableString = '' + if enable_actual_shell_commands(): + commands = command.split(' ') + proc = subprocess.Popen(commands, stdout=subprocess.PIPE) + for line in io.TextIOWrapper(proc.stdout, encoding="utf-8"): # or another encoding + returnableString = returnableString + line + '\n' + return returnableString def checkIfFirstRunSinceBoot(): - if os.path.isfile("lastRun.txt"): - with open("lastRun.txt", 'r') as file: - lastRun = datetime.strptime(file.read(), "%d-%b-%Y (%H:%M:%S.%f)") - systemRunningSince = datetime.fromtimestamp(psutil.boot_time()) - if systemRunningSince > lastRun: - print("First time run since system boot.") - return True - else: - print("Not first time run since system boot.") - return False - else: - print("First time run since system boot.") - return True - + if os.path.isfile("lastRun.txt"): + with open("lastRun.txt", 'r') as file: + lastRun = datetime.strptime(file.read(), "%d-%b-%Y (%H:%M:%S.%f)") + systemRunningSince = datetime.fromtimestamp(psutil.boot_time()) + if systemRunningSince > lastRun: + print("First time run since system boot.") + return True + else: + print("Not first time run since system boot.") + return False + else: + print("First time run since system boot.") + return True + def clearPriorSettings(interfaceA, interfaceB): - if enable_actual_shell_commands(): - if 'mq' in shellReturn('tc qdisc show dev ' + interfaceA + ' root'): - print('MQ detected. Will delete and recreate mq qdisc.') - # Clear tc filter - if on_a_stick() == True: - shell('tc qdisc delete dev ' + interfaceA + ' root') - else: - shell('tc qdisc delete dev ' + interfaceA + ' root') - shell('tc qdisc delete dev ' + interfaceB + ' root') - + if enable_actual_shell_commands(): + if 'mq' in shellReturn('tc qdisc show dev ' + interfaceA + ' root'): + print('MQ detected. Will delete and recreate mq qdisc.') + # Clear tc filter + if on_a_stick() == True: + shell('tc qdisc delete dev ' + interfaceA + ' root') + else: + shell('tc qdisc delete dev ' + interfaceA + ' root') + shell('tc qdisc delete dev ' + interfaceB + ' root') + def tearDown(interfaceA, interfaceB): - # Full teardown of everything for exiting LibreQoS - if enable_actual_shell_commands(): - # Clear IP filters and remove xdp program from interfaces - # The bakery tracks and prunes mappings; avoid clearing everything here. - clearPriorSettings(interfaceA, interfaceB) + # Full teardown of everything for exiting LibreQoS + if enable_actual_shell_commands(): + # Clear IP filters and remove xdp program from interfaces + # The bakery tracks and prunes mappings; avoid clearing everything here. + clearPriorSettings(interfaceA, interfaceB) def findQueuesAvailable(interfaceName): - # Find queues and CPU cores available. Use min between those two as queuesAvailable - if enable_actual_shell_commands(): - if queues_available_override() == 0: - queuesAvailable = 0 - path = '/sys/class/net/' + interfaceName + '/queues/' - directory_contents = os.listdir(path) - for item in directory_contents: - if "tx-" in str(item): - queuesAvailable += 1 - print(f"Interface {interfaceName} NIC queues:\t\t\t" + str(queuesAvailable)) - else: - queuesAvailable = queues_available_override() - print(f"Interface {interfaceName} NIC queues (Override):\t\t\t" + str(queuesAvailable)) - cpuCount = multiprocessing.cpu_count() - print("CPU cores:\t\t\t" + str(cpuCount)) - if queuesAvailable < 2: - raise SystemError(f'Only 1 NIC rx/tx queue available for interface {interfaceName}. You will need to use a NIC with 2 or more rx/tx queues available.') - if cpuCount < 2: - raise SystemError('Only 1 CPU core available. You will need to use a CPU with 2 or more CPU cores.') - queuesAvailable = min(queuesAvailable,cpuCount) - print(f"queuesAvailable for interface {interfaceName} set to:\t" + str(queuesAvailable)) - else: - print("As enableActualShellCommands is False, CPU core / queue count has been set to 16") - logging.info(f"Interface {interfaceName} NIC queues:\t\t\t" + str(16)) - cpuCount = multiprocessing.cpu_count() - logging.info("CPU cores:\t\t\t" + str(16)) - logging.info(f"queuesAvailable for interface {interfaceName} set to:\t" + str(16)) - queuesAvailable = 16 - return queuesAvailable + # Find queues and CPU cores available. Use min between those two as queuesAvailable + if enable_actual_shell_commands(): + if queues_available_override() == 0: + queuesAvailable = 0 + path = '/sys/class/net/' + interfaceName + '/queues/' + directory_contents = os.listdir(path) + for item in directory_contents: + if "tx-" in str(item): + queuesAvailable += 1 + print(f"Interface {interfaceName} NIC queues:\t\t\t" + str(queuesAvailable)) + else: + queuesAvailable = queues_available_override() + print(f"Interface {interfaceName} NIC queues (Override):\t\t\t" + str(queuesAvailable)) + cpuCount = multiprocessing.cpu_count() + print("CPU cores:\t\t\t" + str(cpuCount)) + if queuesAvailable < 2: + raise SystemError(f'Only 1 NIC rx/tx queue available for interface {interfaceName}. You will need to use a NIC with 2 or more rx/tx queues available.') + if cpuCount < 2: + raise SystemError('Only 1 CPU core available. You will need to use a CPU with 2 or more CPU cores.') + queuesAvailable = min(queuesAvailable,cpuCount) + print(f"queuesAvailable for interface {interfaceName} set to:\t" + str(queuesAvailable)) + else: + print("As enableActualShellCommands is False, CPU core / queue count has been set to 16") + logging.info(f"Interface {interfaceName} NIC queues:\t\t\t" + str(16)) + cpuCount = multiprocessing.cpu_count() + logging.info("CPU cores:\t\t\t" + str(16)) + logging.info(f"queuesAvailable for interface {interfaceName} set to:\t" + str(16)) + queuesAvailable = 16 + return queuesAvailable def validateNetworkAndDevices(): - # Verify Network.json is valid json - networkValidatedOrNot = True - # Verify ShapedDevices.csv is valid - devicesValidatedOrNot = True # True by default, switches to false if ANY entry in ShapedDevices.csv fails validation - - # Verify that the Rust side of things can read the CSV file - rustValid = validate_shaped_devices() - if rustValid == "OK": - print("Rust validated ShapedDevices.csv") - else: - warnings.warn("Rust failed to validate ShapedDevices.csv", stacklevel=2) - warnings.warn(rustValid, stacklevel=2) - devicesValidatedOrNot = False - with open(get_network_json_path()) as file: - try: - data = json.load(file) # put JSON-data to a variable - if data != {}: - #Traverse - observedNodes = {} # Will not be used later - def traverseToVerifyValidity(data): - for elem in data: - if isinstance(elem, str): - if (isinstance(data[elem], dict)) and (elem != 'children'): - if elem not in observedNodes: - observedNodes[elem] = {'downloadBandwidthMbps': data[elem]['uploadBandwidthMbps'], 'downloadBandwidthMbps': data[elem]['uploadBandwidthMbps']} - if 'children' in data[elem]: - traverseToVerifyValidity(data[elem]['children']) - else: - warnings.warn("Non-unique Node name in network.json: " + elem, stacklevel=2) - networkValidatedOrNot = False - traverseToVerifyValidity(data) - if len(observedNodes) < 1: - warnings.warn("network.json had 0 valid nodes. Only {} is accepted for that scenario.", stacklevel=2) - networkValidatedOrNot = False - except json.decoder.JSONDecodeError: - warnings.warn("network.json is an invalid JSON file", stacklevel=2) # in case json is invalid - networkValidatedOrNot = False - rowNum = 2 - - # Handle non-utf8 encoding in ShapedDevices.csv - with open(get_shaped_devices_path(), 'rb') as f: - raw_bytes = f.read() - - # Handle BOM if present - if raw_bytes.startswith(b'\xef\xbb\xbf'): # UTF-8 BOM - raw_bytes = raw_bytes[3:] - text_content = raw_bytes.decode('utf-8') - elif raw_bytes.startswith(b'\xff\xfe'): # UTF-16 LE BOM - text_content = raw_bytes.decode('utf-16') - elif raw_bytes.startswith(b'\xfe\xff'): # UTF-16 BE BOM - text_content = raw_bytes.decode('utf-16') - else: - # Try UTF-8 first - try: - text_content = raw_bytes.decode('utf-8') - except UnicodeDecodeError: - # Detect encoding - detected = chardet.detect(raw_bytes) - encoding = detected['encoding'] or 'utf-8' - text_content = raw_bytes.decode(encoding, errors='replace') - - # Create a StringIO object to mimic a file - # And read from the sanitized byte stream - with io.StringIO(text_content) as csv_file: - csv_reader = csv.reader(csv_file, delimiter=',') - #Remove comments if any - commentsRemoved = [] - for row in csv_reader: - if not row[0].startswith('#'): - commentsRemoved.append(row) - #Remove header - commentsRemoved.pop(0) - seenTheseIPsAlready = [] - for row in commentsRemoved: - circuitID, circuitName, deviceID, deviceName, ParentNode, mac, ipv4_input, ipv6_input, downloadMin, uploadMin, downloadMax, uploadMax, comment = row - # Must have circuitID, it's a unique identifier required for stateful changes to queue structure - if circuitID == '': - warnings.warn("No Circuit ID provided in ShapedDevices.csv at row " + str(rowNum), stacklevel=2) - devicesValidatedOrNot = False - # Each entry in ShapedDevices.csv can have multiple IPv4s or IPv6s separated by commas. Split them up and parse each to ensure valid - ipv4_subnets_and_hosts = [] - ipv6_subnets_and_hosts = [] - if ipv4_input != "": - try: - ipv4_input = ipv4_input.replace(' ','') - if "," in ipv4_input: - ipv4_list = ipv4_input.split(',') - else: - ipv4_list = [ipv4_input] - for ipEntry in ipv4_list: - if ipEntry in seenTheseIPsAlready: - warnings.warn("Provided IPv4 '" + ipEntry + "' in ShapedDevices.csv at row " + str(rowNum) + " is duplicate.", stacklevel=2) - #devicesValidatedOrNot = False - seenTheseIPsAlready.append(ipEntry) - else: - if (type(ipaddress.ip_network(ipEntry)) is ipaddress.IPv4Network) or (type(ipaddress.ip_address(ipEntry)) is ipaddress.IPv4Address): - ipv4_subnets_and_hosts.extend(ipEntry) - else: - warnings.warn("Provided IPv4 '" + ipEntry + "' in ShapedDevices.csv at row " + str(rowNum) + " is not valid.", stacklevel=2) - devicesValidatedOrNot = False - seenTheseIPsAlready.append(ipEntry) - except: - warnings.warn("Provided IPv4 '" + ipv4_input + "' in ShapedDevices.csv at row " + str(rowNum) + " is not valid.", stacklevel=2) - devicesValidatedOrNot = False - if ipv6_input != "": - try: - ipv6_input = ipv6_input.replace(' ','') - if "," in ipv6_input: - ipv6_list = ipv6_input.split(',') - else: - ipv6_list = [ipv6_input] - for ipEntry in ipv6_list: - if ipEntry in seenTheseIPsAlready: - warnings.warn("Provided IPv6 '" + ipEntry + "' in ShapedDevices.csv at row " + str(rowNum) + " is duplicate.", stacklevel=2) - devicesValidatedOrNot = False - seenTheseIPsAlready.append(ipEntry) - else: - if (type(ipaddress.ip_network(ipEntry)) is ipaddress.IPv6Network) or (type(ipaddress.ip_address(ipEntry)) is ipaddress.IPv6Address): - ipv6_subnets_and_hosts.extend(ipEntry) - else: - warnings.warn("Provided IPv6 '" + ipEntry + "' in ShapedDevices.csv at row " + str(rowNum) + " is not valid.", stacklevel=2) - devicesValidatedOrNot = False - seenTheseIPsAlready.append(ipEntry) - except: - warnings.warn("Provided IPv6 '" + ipv6_input + "' in ShapedDevices.csv at row " + str(rowNum) + " is not valid.", stacklevel=2) - devicesValidatedOrNot = False - try: - a = float(downloadMin) - if a < 0.1: - warnings.warn("Provided downloadMin '" + downloadMin + "' in ShapedDevices.csv at row " + str(rowNum) + " is < 0.1 Mbps.", stacklevel=2) - devicesValidatedOrNot = False - except: - warnings.warn("Provided downloadMin '" + downloadMin + "' in ShapedDevices.csv at row " + str(rowNum) + " is not a valid number.", stacklevel=2) - devicesValidatedOrNot = False - try: - a = float(uploadMin) - if a < 0.1: - warnings.warn("Provided uploadMin '" + uploadMin + "' in ShapedDevices.csv at row " + str(rowNum) + " is < 0.1 Mbps.", stacklevel=2) - devicesValidatedOrNot = False - except: - warnings.warn("Provided uploadMin '" + uploadMin + "' in ShapedDevices.csv at row " + str(rowNum) + " is not a valid number.", stacklevel=2) - devicesValidatedOrNot = False - try: - a = float(downloadMax) - if a < 0.1: - warnings.warn("Provided downloadMax '" + downloadMax + "' in ShapedDevices.csv at row " + str(rowNum) + " is < 0.2 Mbps.", stacklevel=2) - devicesValidatedOrNot = False - except: - warnings.warn("Provided downloadMax '" + downloadMax + "' in ShapedDevices.csv at row " + str(rowNum) + " is not a valid number.", stacklevel=2) - devicesValidatedOrNot = False - try: - a = float(uploadMax) - if a < 0.1: - warnings.warn("Provided uploadMax '" + uploadMax + "' in ShapedDevices.csv at row " + str(rowNum) + " is < 0.2 Mbps.", stacklevel=2) - devicesValidatedOrNot = False - except: - warnings.warn("Provided uploadMax '" + uploadMax + "' in ShapedDevices.csv at row " + str(rowNum) + " is not a valid number.", stacklevel=2) - devicesValidatedOrNot = False - - try: - if float(downloadMin) > float(downloadMax): - warnings.warn("Provided downloadMin '" + downloadMin + "' in ShapedDevices.csv at row " + str(rowNum) + " is greater than downloadMax", stacklevel=2) - devicesValidatedOrNot = False - if float(uploadMin) > float(uploadMax): - warnings.warn("Provided uploadMin '" + uploadMin + "' in ShapedDevices.csv at row " + str(rowNum) + " is greater than uploadMax", stacklevel=2) - devicesValidatedOrNot = False - except: - devicesValidatedOrNot = False - - rowNum += 1 - if devicesValidatedOrNot == True: - print("ShapedDevices.csv passed validation") - else: - print("ShapedDevices.csv failed validation") - if networkValidatedOrNot == True: - print("network.json passed validation") - else: - print("network.json failed validation") - if (devicesValidatedOrNot == True) and (networkValidatedOrNot == True): - return True - else: - return False + # Verify Network.json is valid json + networkValidatedOrNot = True + # Verify ShapedDevices.csv is valid + devicesValidatedOrNot = True # True by default, switches to false if ANY entry in ShapedDevices.csv fails validation + + # Verify that the Rust side of things can read the CSV file + rustValid = validate_shaped_devices() + if rustValid == "OK": + print("Rust validated ShapedDevices.csv") + else: + warnings.warn("Rust failed to validate ShapedDevices.csv", stacklevel=2) + warnings.warn(rustValid, stacklevel=2) + devicesValidatedOrNot = False + with open(get_network_json_path()) as file: + try: + data = json.load(file) # put JSON-data to a variable + if data != {}: + #Traverse + observedNodes = {} # Will not be used later + def traverseToVerifyValidity(data): + for elem in data: + if isinstance(elem, str): + if (isinstance(data[elem], dict)) and (elem != 'children'): + if elem not in observedNodes: + observedNodes[elem] = {'downloadBandwidthMbps': data[elem]['uploadBandwidthMbps'], 'downloadBandwidthMbps': data[elem]['uploadBandwidthMbps']} + if 'children' in data[elem]: + traverseToVerifyValidity(data[elem]['children']) + else: + warnings.warn("Non-unique Node name in network.json: " + elem, stacklevel=2) + networkValidatedOrNot = False + traverseToVerifyValidity(data) + if len(observedNodes) < 1: + warnings.warn("network.json had 0 valid nodes. Only {} is accepted for that scenario.", stacklevel=2) + networkValidatedOrNot = False + except json.decoder.JSONDecodeError: + warnings.warn("network.json is an invalid JSON file", stacklevel=2) # in case json is invalid + networkValidatedOrNot = False + rowNum = 2 + + # Handle non-utf8 encoding in ShapedDevices.csv + with open(get_shaped_devices_path(), 'rb') as f: + raw_bytes = f.read() + + # Handle BOM if present + if raw_bytes.startswith(b'\xef\xbb\xbf'): # UTF-8 BOM + raw_bytes = raw_bytes[3:] + text_content = raw_bytes.decode('utf-8') + elif raw_bytes.startswith(b'\xff\xfe'): # UTF-16 LE BOM + text_content = raw_bytes.decode('utf-16') + elif raw_bytes.startswith(b'\xfe\xff'): # UTF-16 BE BOM + text_content = raw_bytes.decode('utf-16') + else: + # Try UTF-8 first + try: + text_content = raw_bytes.decode('utf-8') + except UnicodeDecodeError: + # Detect encoding + detected = chardet.detect(raw_bytes) + encoding = detected['encoding'] or 'utf-8' + text_content = raw_bytes.decode(encoding, errors='replace') + + # Create a StringIO object to mimic a file + # And read from the sanitized byte stream + with io.StringIO(text_content) as csv_file: + csv_reader = csv.reader(csv_file, delimiter=',') + #Remove comments if any + commentsRemoved = [] + for row in csv_reader: + if not row[0].startswith('#'): + commentsRemoved.append(row) + #Remove header + commentsRemoved.pop(0) + seenTheseIPsAlready = [] + for row in commentsRemoved: + # Accept optional 14th column 'sqm' but ignore here (validation focuses on core fields) + circuitID, circuitName, deviceID, deviceName, ParentNode, mac, ipv4_input, ipv6_input, downloadMin, uploadMin, downloadMax, uploadMax, comment = row[0:13] + # Must have circuitID, it's a unique identifier required for stateful changes to queue structure + if circuitID == '': + warnings.warn("No Circuit ID provided in ShapedDevices.csv at row " + str(rowNum), stacklevel=2) + devicesValidatedOrNot = False + # Each entry in ShapedDevices.csv can have multiple IPv4s or IPv6s separated by commas. Split them up and parse each to ensure valid + ipv4_subnets_and_hosts = [] + ipv6_subnets_and_hosts = [] + if ipv4_input != "": + try: + ipv4_input = ipv4_input.replace(' ','') + if "," in ipv4_input: + ipv4_list = ipv4_input.split(',') + else: + ipv4_list = [ipv4_input] + for ipEntry in ipv4_list: + if ipEntry in seenTheseIPsAlready: + warnings.warn("Provided IPv4 '" + ipEntry + "' in ShapedDevices.csv at row " + str(rowNum) + " is duplicate.", stacklevel=2) + #devicesValidatedOrNot = False + seenTheseIPsAlready.append(ipEntry) + else: + if (type(ipaddress.ip_network(ipEntry)) is ipaddress.IPv4Network) or (type(ipaddress.ip_address(ipEntry)) is ipaddress.IPv4Address): + ipv4_subnets_and_hosts.extend(ipEntry) + else: + warnings.warn("Provided IPv4 '" + ipEntry + "' in ShapedDevices.csv at row " + str(rowNum) + " is not valid.", stacklevel=2) + devicesValidatedOrNot = False + seenTheseIPsAlready.append(ipEntry) + except: + warnings.warn("Provided IPv4 '" + ipv4_input + "' in ShapedDevices.csv at row " + str(rowNum) + " is not valid.", stacklevel=2) + devicesValidatedOrNot = False + if ipv6_input != "": + try: + ipv6_input = ipv6_input.replace(' ','') + if "," in ipv6_input: + ipv6_list = ipv6_input.split(',') + else: + ipv6_list = [ipv6_input] + for ipEntry in ipv6_list: + if ipEntry in seenTheseIPsAlready: + warnings.warn("Provided IPv6 '" + ipEntry + "' in ShapedDevices.csv at row " + str(rowNum) + " is duplicate.", stacklevel=2) + devicesValidatedOrNot = False + seenTheseIPsAlready.append(ipEntry) + else: + if (type(ipaddress.ip_network(ipEntry)) is ipaddress.IPv6Network) or (type(ipaddress.ip_address(ipEntry)) is ipaddress.IPv6Address): + ipv6_subnets_and_hosts.extend(ipEntry) + else: + warnings.warn("Provided IPv6 '" + ipEntry + "' in ShapedDevices.csv at row " + str(rowNum) + " is not valid.", stacklevel=2) + devicesValidatedOrNot = False + seenTheseIPsAlready.append(ipEntry) + except: + warnings.warn("Provided IPv6 '" + ipv6_input + "' in ShapedDevices.csv at row " + str(rowNum) + " is not valid.", stacklevel=2) + devicesValidatedOrNot = False + try: + a = float(downloadMin) + if a < 0.1: + warnings.warn("Provided downloadMin '" + downloadMin + "' in ShapedDevices.csv at row " + str(rowNum) + " is < 0.1 Mbps.", stacklevel=2) + devicesValidatedOrNot = False + except: + warnings.warn("Provided downloadMin '" + downloadMin + "' in ShapedDevices.csv at row " + str(rowNum) + " is not a valid number.", stacklevel=2) + devicesValidatedOrNot = False + try: + a = float(uploadMin) + if a < 0.1: + warnings.warn("Provided uploadMin '" + uploadMin + "' in ShapedDevices.csv at row " + str(rowNum) + " is < 0.1 Mbps.", stacklevel=2) + devicesValidatedOrNot = False + except: + warnings.warn("Provided uploadMin '" + uploadMin + "' in ShapedDevices.csv at row " + str(rowNum) + " is not a valid number.", stacklevel=2) + devicesValidatedOrNot = False + try: + a = float(downloadMax) + if a < 0.1: + warnings.warn("Provided downloadMax '" + downloadMax + "' in ShapedDevices.csv at row " + str(rowNum) + " is < 0.2 Mbps.", stacklevel=2) + devicesValidatedOrNot = False + except: + warnings.warn("Provided downloadMax '" + downloadMax + "' in ShapedDevices.csv at row " + str(rowNum) + " is not a valid number.", stacklevel=2) + devicesValidatedOrNot = False + try: + a = float(uploadMax) + if a < 0.1: + warnings.warn("Provided uploadMax '" + uploadMax + "' in ShapedDevices.csv at row " + str(rowNum) + " is < 0.2 Mbps.", stacklevel=2) + devicesValidatedOrNot = False + except: + warnings.warn("Provided uploadMax '" + uploadMax + "' in ShapedDevices.csv at row " + str(rowNum) + " is not a valid number.", stacklevel=2) + devicesValidatedOrNot = False + + try: + if float(downloadMin) > float(downloadMax): + warnings.warn("Provided downloadMin '" + downloadMin + "' in ShapedDevices.csv at row " + str(rowNum) + " is greater than downloadMax", stacklevel=2) + devicesValidatedOrNot = False + if float(uploadMin) > float(uploadMax): + warnings.warn("Provided uploadMin '" + uploadMin + "' in ShapedDevices.csv at row " + str(rowNum) + " is greater than uploadMax", stacklevel=2) + devicesValidatedOrNot = False + except: + devicesValidatedOrNot = False + + rowNum += 1 + if devicesValidatedOrNot == True: + print("ShapedDevices.csv passed validation") + else: + print("ShapedDevices.csv failed validation") + if networkValidatedOrNot == True: + print("network.json passed validation") + else: + print("network.json failed validation") + if (devicesValidatedOrNot == True) and (networkValidatedOrNot == True): + return True + else: + return False def loadSubscriberCircuits(shapedDevicesFile): - # Load Subscriber Circuits & Devices - subscriberCircuits = [] - knownCircuitIDs = [] - counterForCircuitsWithoutParentNodes = 0 - dictForCircuitsWithoutParentNodes = {} - with open(shapedDevicesFile) as csv_file: - csv_reader = csv.reader(csv_file, delimiter=',') - # Remove comments if any - commentsRemoved = [] - for row in csv_reader: - if not row[0].startswith('#'): - commentsRemoved.append(row) - # Remove header - commentsRemoved.pop(0) - for row in commentsRemoved: - circuitID, circuitName, deviceID, deviceName, ParentNode, mac, ipv4_input, ipv6_input, downloadMin, uploadMin, downloadMax, uploadMax, comment = row - # If in monitorOnlyMode, override bandwidth rates to where no shaping will actually occur - if monitor_mode_only() == True: - downloadMin = 10000 - uploadMin = 10000 - downloadMax = 10000 - uploadMax = 10000 - ipv4_subnets_and_hosts = [] - # Each entry in ShapedDevices.csv can have multiple IPv4s or IPv6s separated by commas. Split them up and parse each - if ipv4_input != "": - ipv4_input = ipv4_input.replace(' ','') - if "," in ipv4_input: - ipv4_list = ipv4_input.split(',') - else: - ipv4_list = [ipv4_input] - for ipEntry in ipv4_list: - ipv4_subnets_and_hosts.append(ipEntry) - ipv6_subnets_and_hosts = [] - if ipv6_input != "": - ipv6_input = ipv6_input.replace(' ','') - if "," in ipv6_input: - ipv6_list = ipv6_input.split(',') - else: - ipv6_list = [ipv6_input] - for ipEntry in ipv6_list: - ipv6_subnets_and_hosts.append(ipEntry) - # If there is something in the circuit ID field - if circuitID != "": - # Seen circuit before - if circuitID in knownCircuitIDs: - for circuit in subscriberCircuits: - if circuit['circuitID'] == circuitID: - if circuit['ParentNode'] != "none": - if circuit['ParentNode'] != ParentNode: - errorMessageString = "Device " + deviceName + " with deviceID " + deviceID + " had different Parent Node from other devices of circuit ID #" + circuitID - raise ValueError(errorMessageString) - # Check if bandwidth parameters match other cdevices of this same circuit ID, but only check if monitorOnlyMode is Off - if monitor_mode_only() == False: - if ((circuit['minDownload'] != float(downloadMin)) - or (circuit['minUpload'] != float(uploadMin)) - or (circuit['maxDownload'] != float(downloadMax)) - or (circuit['maxUpload'] != float(uploadMax))): - warnings.warn("Device " + deviceName + " with ID " + deviceID + " had different bandwidth parameters than other devices on this circuit. Will instead use the bandwidth parameters defined by the first device added to its circuit.", stacklevel=2) - devicesListForCircuit = circuit['devices'] - thisDevice = { - "deviceID": deviceID, - "deviceName": deviceName, - "mac": mac, - "ipv4s": ipv4_subnets_and_hosts, - "ipv6s": ipv6_subnets_and_hosts, - "comment": comment - } - devicesListForCircuit.append(thisDevice) - circuit['devices'] = devicesListForCircuit - # Have not seen circuit before - else: - knownCircuitIDs.append(circuitID) - if ParentNode == "": - ParentNode = "none" - #ParentNode = ParentNode.strip() - deviceListForCircuit = [] - thisDevice = { - "deviceID": deviceID, - "deviceName": deviceName, - "mac": mac, - "ipv4s": ipv4_subnets_and_hosts, - "ipv6s": ipv6_subnets_and_hosts, - "comment": comment - } - deviceListForCircuit.append(thisDevice) - thisCircuit = { - "circuitID": circuitID, - "circuitName": circuitName, - "ParentNode": ParentNode, - "devices": deviceListForCircuit, - "minDownload": float(downloadMin), - "minUpload": float(uploadMin), - "maxDownload": float(downloadMax), - "maxUpload": float(uploadMax), - "classid": '', - "comment": comment - } - if thisCircuit['ParentNode'] == 'none': - thisCircuit['idForCircuitsWithoutParentNodes'] = counterForCircuitsWithoutParentNodes - dictForCircuitsWithoutParentNodes[counterForCircuitsWithoutParentNodes] = ((float(downloadMax))+(float(uploadMax))) - counterForCircuitsWithoutParentNodes += 1 - subscriberCircuits.append(thisCircuit) - # If there is nothing in the circuit ID field - else: - # Copy deviceName to circuitName if none defined already - if circuitName == "": - circuitName = deviceName - if ParentNode == "": - ParentNode = "none" - #ParentNode = ParentNode.strip() - deviceListForCircuit = [] - thisDevice = { - "deviceID": deviceID, - "deviceName": deviceName, - "mac": mac, - "ipv4s": ipv4_subnets_and_hosts, - "ipv6s": ipv6_subnets_and_hosts, - } - deviceListForCircuit.append(thisDevice) - thisCircuit = { - "circuitID": circuitID, - "circuitName": circuitName, - "ParentNode": ParentNode, - "devices": deviceListForCircuit, - "minDownload": float(downloadMin), - "minUpload": float(uploadMin), - "maxDownload": float(downloadMax), - "maxUpload": float(uploadMax), - "classid": '', - "comment": comment - } - if thisCircuit['ParentNode'] == 'none': - thisCircuit['idForCircuitsWithoutParentNodes'] = counterForCircuitsWithoutParentNodes - dictForCircuitsWithoutParentNodes[counterForCircuitsWithoutParentNodes] = ((float(downloadMax))+(float(uploadMax))) - counterForCircuitsWithoutParentNodes += 1 - subscriberCircuits.append(thisCircuit) - return (subscriberCircuits, dictForCircuitsWithoutParentNodes) + # Load Subscriber Circuits & Devices + subscriberCircuits = [] + knownCircuitIDs = [] + counterForCircuitsWithoutParentNodes = 0 + dictForCircuitsWithoutParentNodes = {} + with open(shapedDevicesFile) as csv_file: + csv_reader = csv.reader(csv_file, delimiter=',') + # Remove comments if any + commentsRemoved = [] + for row in csv_reader: + if not row[0].startswith('#'): + commentsRemoved.append(row) + # Remove header + commentsRemoved.pop(0) + for row in commentsRemoved: + # Optional per-circuit SQM override in last column + sqm_override_token = '' + if len(row) > 13: + sqm_override_token = row[13].strip().lower() + circuitID, circuitName, deviceID, deviceName, ParentNode, mac, ipv4_input, ipv6_input, downloadMin, uploadMin, downloadMax, uploadMax, comment = row[0:13] + # If in monitorOnlyMode, override bandwidth rates to where no shaping will actually occur + if monitor_mode_only() == True: + downloadMin = 10000 + uploadMin = 10000 + downloadMax = 10000 + uploadMax = 10000 + ipv4_subnets_and_hosts = [] + # Each entry in ShapedDevices.csv can have multiple IPv4s or IPv6s separated by commas. Split them up and parse each + if ipv4_input != "": + ipv4_input = ipv4_input.replace(' ','') + if "," in ipv4_input: + ipv4_list = ipv4_input.split(',') + else: + ipv4_list = [ipv4_input] + for ipEntry in ipv4_list: + ipv4_subnets_and_hosts.append(ipEntry) + ipv6_subnets_and_hosts = [] + if ipv6_input != "": + ipv6_input = ipv6_input.replace(' ','') + if "," in ipv6_input: + ipv6_list = ipv6_input.split(',') + else: + ipv6_list = [ipv6_input] + for ipEntry in ipv6_list: + ipv6_subnets_and_hosts.append(ipEntry) + # If there is something in the circuit ID field + if circuitID != "": + # Seen circuit before + if circuitID in knownCircuitIDs: + for circuit in subscriberCircuits: + if circuit['circuitID'] == circuitID: + if circuit['ParentNode'] != "none": + if circuit['ParentNode'] != ParentNode: + errorMessageString = "Device " + deviceName + " with deviceID " + deviceID + " had different Parent Node from other devices of circuit ID #" + circuitID + raise ValueError(errorMessageString) + # Check if bandwidth parameters match other cdevices of this same circuit ID, but only check if monitorOnlyMode is Off + if monitor_mode_only() == False: + if ((circuit['minDownload'] != float(downloadMin)) + or (circuit['minUpload'] != float(uploadMin)) + or (circuit['maxDownload'] != float(downloadMax)) + or (circuit['maxUpload'] != float(uploadMax))): + warnings.warn("Device " + deviceName + " with ID " + deviceID + " had different bandwidth parameters than other devices on this circuit. Will instead use the bandwidth parameters defined by the first device added to its circuit.", stacklevel=2) + # If this row specifies an SQM override, but the circuit already has a different one, warn and keep the first. + if sqm_override_token != '': + if 'sqm' in circuit: + if circuit['sqm'] != sqm_override_token: + warnings.warn("Device " + deviceName + " with ID " + deviceID + " had different SQM override than other devices on this circuit. Will instead use the SQM defined by the first device added to its circuit.", stacklevel=2) + else: + circuit['sqm'] = sqm_override_token + devicesListForCircuit = circuit['devices'] + thisDevice = { + "deviceID": deviceID, + "deviceName": deviceName, + "mac": mac, + "ipv4s": ipv4_subnets_and_hosts, + "ipv6s": ipv6_subnets_and_hosts, + "comment": comment + } + devicesListForCircuit.append(thisDevice) + circuit['devices'] = devicesListForCircuit + # Have not seen circuit before + else: + knownCircuitIDs.append(circuitID) + if ParentNode == "": + ParentNode = "none" + #ParentNode = ParentNode.strip() + deviceListForCircuit = [] + thisDevice = { + "deviceID": deviceID, + "deviceName": deviceName, + "mac": mac, + "ipv4s": ipv4_subnets_and_hosts, + "ipv6s": ipv6_subnets_and_hosts, + "comment": comment + } + deviceListForCircuit.append(thisDevice) + thisCircuit = { + "circuitID": circuitID, + "circuitName": circuitName, + "ParentNode": ParentNode, + "devices": deviceListForCircuit, + "minDownload": float(downloadMin), + "minUpload": float(uploadMin), + "maxDownload": float(downloadMax), + "maxUpload": float(uploadMax), + "classid": '', + "comment": comment + } + if sqm_override_token != '': + thisCircuit['sqm'] = sqm_override_token + if thisCircuit['ParentNode'] == 'none': + thisCircuit['idForCircuitsWithoutParentNodes'] = counterForCircuitsWithoutParentNodes + dictForCircuitsWithoutParentNodes[counterForCircuitsWithoutParentNodes] = ((float(downloadMax))+(float(uploadMax))) + counterForCircuitsWithoutParentNodes += 1 + subscriberCircuits.append(thisCircuit) + # If there is nothing in the circuit ID field + else: + # Copy deviceName to circuitName if none defined already + if circuitName == "": + circuitName = deviceName + if ParentNode == "": + ParentNode = "none" + #ParentNode = ParentNode.strip() + deviceListForCircuit = [] + thisDevice = { + "deviceID": deviceID, + "deviceName": deviceName, + "mac": mac, + "ipv4s": ipv4_subnets_and_hosts, + "ipv6s": ipv6_subnets_and_hosts, + } + deviceListForCircuit.append(thisDevice) + thisCircuit = { + "circuitID": circuitID, + "circuitName": circuitName, + "ParentNode": ParentNode, + "devices": deviceListForCircuit, + "minDownload": float(downloadMin), + "minUpload": float(uploadMin), + "maxDownload": float(downloadMax), + "maxUpload": float(uploadMax), + "classid": '', + "comment": comment + } + if sqm_override_token != '': + thisCircuit['sqm'] = sqm_override_token + if thisCircuit['ParentNode'] == 'none': + thisCircuit['idForCircuitsWithoutParentNodes'] = counterForCircuitsWithoutParentNodes + dictForCircuitsWithoutParentNodes[counterForCircuitsWithoutParentNodes] = ((float(downloadMax))+(float(uploadMax))) + counterForCircuitsWithoutParentNodes += 1 + subscriberCircuits.append(thisCircuit) + return (subscriberCircuits, dictForCircuitsWithoutParentNodes) def refreshShapers(): - - # Starting - print("refreshShapers starting at " + datetime.now().strftime("%d/%m/%Y %H:%M:%S")) - # Create a single batch of xdp update commands to execute together - ipMapBatch = BatchedCommands() - - # Warn user if enableActualShellCommands is False, because that would mean no actual commands are executing - if enable_actual_shell_commands() == False: - warnings.warn("enableActualShellCommands is set to False. None of the commands below will actually be executed. Simulated run.", stacklevel=2) - # Warn user if monitorOnlyMode is True, because that would mean no actual shaping is happening - if monitor_mode_only() == True: - warnings.warn("monitorOnlyMode is set to True. Shaping will not occur.", stacklevel=2) - - - # Check if first run since boot - isThisFirstRunSinceBoot = checkIfFirstRunSinceBoot() - - - # Files - shapedDevicesFile = get_shaped_devices_path() - networkJSONfile = get_network_json_path() - - - # Check validation - safeToRunRefresh = False - print("Validating input files '" + shapedDevicesFile + "' and '" + networkJSONfile + "'") - if (validateNetworkAndDevices() == True): - shutil.copyfile('ShapedDevices.csv', 'lastGoodConfig.csv') - shutil.copyfile('network.json', 'lastGoodConfig.json') - print("Backed up good config as lastGoodConfig.csv and lastGoodConfig.json") - safeToRunRefresh = True - else: - if (isThisFirstRunSinceBoot == False): - warnings.warn("Validation failed. Because this is not the first run since boot (queues already set up) - will now exit.", stacklevel=2) - safeToRunRefresh = False - else: - warnings.warn("Validation failed. However - because this is the first run since boot - will load queues from last good config", stacklevel=2) - shapedDevicesFile = 'lastGoodConfig.csv' - networkJSONfile = 'lastGoodConfig.json' - safeToRunRefresh = True - - if safeToRunRefresh == True: - - # Load Subscriber Circuits & Devices - subscriberCircuits, dictForCircuitsWithoutParentNodes = loadSubscriberCircuits(shapedDevicesFile) - - - # Load network hierarchy - with open(networkJSONfile, 'r') as j: - network = json.loads(j.read()) - - - # Pull rx/tx queues / CPU cores available - # Handling the case when the number of queues for interfaces are different - InterfaceAQueuesAvailable = findQueuesAvailable(interface_a()) - InterfaceBQueuesAvailable = findQueuesAvailable(interface_b()) - queuesAvailable = min(InterfaceAQueuesAvailable, InterfaceBQueuesAvailable) - stickOffset = 0 - if on_a_stick(): - print("On-a-stick override dividing queues") - # The idea here is that download use queues 0 - n/2, upload uses the other half - queuesAvailable = math.floor(queuesAvailable / 2) - stickOffset = queuesAvailable - - # If in monitorOnlyMode, override network.json bandwidth rates to where no shaping will actually occur - if monitor_mode_only() == True: - def overrideNetworkBandwidths(data): - for elem in data: - if 'children' in data[elem]: - overrideNetworkBandwidths(data[elem]['children']) - data[elem]['downloadBandwidthMbpsMin'] = 100000 - data[elem]['uploadBandwidthMbpsMin'] = 100000 - overrideNetworkBandwidths(network) - - # Generate Parent Nodes. Spread ShapedDevices.csv which lack defined ParentNode across these (balance across CPUs) - print("Generating parent nodes") - generatedPNs = [] - numberOfGeneratedPNs = queuesAvailable - # If in monitorOnlyMode, override bandwidth rates to where no shaping will actually occur - if monitor_mode_only() == True: - chosenDownloadMbps = 10000 - chosenUploadMbps = 10000 - else: - chosenDownloadMbps = generated_pn_download_mbps() - chosenUploadMbps = generated_pn_upload_mbps() - for x in range(numberOfGeneratedPNs): - genPNname = "Generated_PN_" + str(x+1) - network[genPNname] = { - "downloadBandwidthMbps": chosenDownloadMbps, - "uploadBandwidthMbps": chosenUploadMbps - } - generatedPNs.append(genPNname) - if use_bin_packing_to_balance_cpu(): - print("Using binpacking module to sort circuits by CPU core") - weights = get_weights() - if weights is not None and dictForCircuitsWithoutParentNodes is not None: - for circuitId in dictForCircuitsWithoutParentNodes: - for circuit in subscriberCircuits: - if 'idForCircuitsWithoutParentNodes' in circuit and circuit['idForCircuitsWithoutParentNodes'] == circuitId: - for w in weights: - if w.circuit_id == circuit['circuitID']: - dictForCircuitsWithoutParentNodes[circuitId] = w.weight - bins = binpacking.to_constant_bin_number(dictForCircuitsWithoutParentNodes, numberOfGeneratedPNs) - genPNcounter = 0 - for binItem in bins: - sumItem = 0 - logging.info(generatedPNs[genPNcounter] + " will contain " + str(len(binItem)) + " circuits") - for key in binItem.keys(): - for circuit in subscriberCircuits: - if circuit['ParentNode'] == 'none': - if circuit['idForCircuitsWithoutParentNodes'] == key: - circuit['ParentNode'] = generatedPNs[genPNcounter] - genPNcounter += 1 - if genPNcounter >= queuesAvailable: - genPNcounter = 0 - print("Finished binpacking") - else: - genPNcounter = 0 - for circuit in subscriberCircuits: - if circuit['ParentNode'] == 'none': - circuit['ParentNode'] = generatedPNs[genPNcounter] - genPNcounter += 1 - if genPNcounter >= queuesAvailable: - genPNcounter = 0 - print("Generated parent nodes created") - - # Find the bandwidth minimums for each node by combining mimimums of devices lower in that node's hierarchy - def findBandwidthMins(data, depth): - tabs = ' ' * depth - minDownload = 0 - minUpload = 0 - for elem in data: - for circuit in subscriberCircuits: - if elem == circuit['ParentNode']: - minDownload += circuit['minDownload'] - minUpload += circuit['minUpload'] - if 'children' in data[elem]: - minDL, minUL = findBandwidthMins(data[elem]['children'], depth+1) - minDownload += minDL - minUpload += minUL - if 'downloadBandwidthMbpsMin' in data[elem]: - data[elem]['downloadBandwidthMbpsMin'] = max(data[elem]['downloadBandwidthMbpsMin'], minDownload) - else: - data[elem]['downloadBandwidthMbpsMin'] = max(data[elem]['downloadBandwidthMbps'], minUpload) - if 'uploadBandwidthMbpsMin' in data[elem]: - data[elem]['uploadBandwidthMbpsMin'] = max(data[elem]['uploadBandwidthMbpsMin'], minUpload) - else: - data[elem]['uploadBandwidthMbpsMin'] = max(data[elem]['uploadBandwidthMbps'], minUpload) - return minDownload, minUpload - logging.info("Finding the bandwidth minimums for each node") - minDownload, minUpload = findBandwidthMins(network, 0) - logging.info("Found the bandwidth minimums for each node") - - # Child nodes inherit bandwidth maximums of parents. We apply this here to avoid bugs when compression is applied with flattenA(). - def inheritBandwidthMaxes(data, parentMaxDL, parentMaxUL, parentMinDL, parentMinUL): - for node in data: - if isinstance(node, str): - if (isinstance(data[node], dict)) and (node != 'children'): - # Cap based on this node's max bandwidth, or parent node's max bandwidth, whichever is lower - data[node]['downloadBandwidthMbps'] = min(int(data[node]['downloadBandwidthMbps']),int(parentMaxDL)) - data[node]['uploadBandwidthMbps'] = min(int(data[node]['uploadBandwidthMbps']),int(parentMaxUL)) - data[node]['downloadBandwidthMbpsMin'] = min(int(data[node]['downloadBandwidthMbpsMin']),int(data[node]['downloadBandwidthMbps']),int(parentMinDL)) - data[node]['uploadBandwidthMbpsMin'] = min(int(data[node]['uploadBandwidthMbpsMin']),int(data[node]['uploadBandwidthMbps']),int(parentMinUL)) - # Recursive call this function for children nodes attached to this node - if 'children' in data[node]: - # We need to keep tabs on the minor counter, because we can't have repeating class IDs. Here, we bring back the minor counter from the recursive function - inheritBandwidthMaxes(data[node]['children'], data[node]['downloadBandwidthMbps'], data[node]['uploadBandwidthMbps'], data[node]['downloadBandwidthMbpsMin'], data[node]['uploadBandwidthMbpsMin']) - #return data - # Here is the actual call to the recursive function - inheritBandwidthMaxes(network, parentMaxDL=upstream_bandwidth_capacity_download_mbps(), parentMaxUL=upstream_bandwidth_capacity_upload_mbps(), parentMinDL=upstream_bandwidth_capacity_download_mbps(), parentMinUL=upstream_bandwidth_capacity_upload_mbps()) - - # Compress network.json. HTB only supports 8 levels of HTB depth. Compress to 8 layers if beyond 8. - def flattenB(data): - newDict = {} - for node in data: - if isinstance(node, str): - if (isinstance(data[node], dict)) and (node != 'children'): - newDict[node] = dict(data[node]) - if 'children' in data[node]: - result = flattenB(data[node]['children']) - del newDict[node]['children'] - newDict.update(result) - return newDict - def flattenA(data, depth): - newDict = {} - for node in data: - if isinstance(node, str): - if (isinstance(data[node], dict)) and (node != 'children'): - newDict[node] = dict(data[node]) - if 'children' in data[node]: - result = flattenA(data[node]['children'], depth+2) - del newDict[node]['children'] - if depth <= 8: - newDict[node]['children'] = result - else: - flattened = flattenB(data[node]['children']) - if 'children' in newDict[node]: - newDict[node]['children'].update(flattened) - else: - newDict[node]['children'] = flattened - return newDict - network = flattenA(network, 1) - - # Group circuits by parent node. Reduces runtime for section below this one. - circuits_by_parent_node = {} - circuit_min_down_combined_by_parent_node = {} - circuit_min_up_combined_by_parent_node = {} - for circuit in subscriberCircuits: - #If a device from ShapedDevices.csv lists this node as its Parent Node, attach it as a leaf to this node HTB - if circuit['ParentNode'] not in circuits_by_parent_node: - circuits_by_parent_node[circuit['ParentNode']] = [] - temp = circuits_by_parent_node[circuit['ParentNode']] - temp.append(circuit) - circuits_by_parent_node[circuit['ParentNode']] = temp - if circuit['ParentNode'] not in circuit_min_down_combined_by_parent_node: - circuit_min_down_combined_by_parent_node[circuit['ParentNode']] = 0 - circuit_min_down_combined_by_parent_node[circuit['ParentNode']] += circuit['minDownload'] - if circuit['ParentNode'] not in circuit_min_up_combined_by_parent_node: - circuit_min_up_combined_by_parent_node[circuit['ParentNode']] = 0 - circuit_min_up_combined_by_parent_node[circuit['ParentNode']] += circuit['minUpload'] - - # Parse network structure and add devices from ShapedDevices.csv - print("Parsing network structure and tallying devices") - parentNodes = [] - minorByCPUpreloaded = {} - knownClassIDs = [] - nodes_requiring_min_squashing = {} - # Track minor counter by CPU. This way we can have > 32000 hosts (htb has u16 limit to minor handle) - # Minor numbers start at 3 to reserve 1 for root qdisc and 2 for default class - # With CIRCUIT_PADDING, we leave gaps between nodes to allow future circuit additions - # without disrupting existing ClassID assignments. This maintains stability across reloads. - for x in range(queuesAvailable): - minorByCPUpreloaded[x+1] = 3 - def traverseNetwork(data, depth, major, minorByCPU, queue, parentClassID, upParentClassID, parentMaxDL, parentMaxUL, parentMinDL, parentMinUL): - # ClassID Assignment Strategy: - # - Nodes and circuits are processed in alphabetical order for stability - # - Each node gets a unique minor number that increments sequentially - # - After processing all circuits for a node, we add CIRCUIT_PADDING to the minor counter - # - This creates gaps that allow adding new circuits without affecting other ClassIDs - # - Children are also sorted before recursive processing to ensure deterministic traversal - # For top-level binpacked keys (CpueQueueN), enforce numeric ordering of N - keys = list(data.keys()) - if depth == 0 and len(keys) > 0 and all(k.startswith("CpueQueue") for k in keys): - try: - keys.sort(key=lambda k: int(k.replace("CpueQueue", ""))) - except Exception: - keys = sorted(keys) - else: - keys = sorted(keys) - for node in keys: - #if data[node]['type'] == "virtual": - # print(node + " is a virtual node. Skipping.") - # if depth == 0: - # parentClassID = hex(major) + ':' - # upParentClassID = hex(major+stickOffset) + ':' - # data[node]['parentClassID'] = parentClassID - # data[node]['up_parentClassID'] = upParentClassID - # data[node]['classMajor'] = hex(major) - # data[node]['up_classMajor'] = hex(major + stickOffset) - # data[node]['classMinor'] = hex(minorByCPU[queue]) - # data[node]['cpuNum'] = hex(queue-1) - # data[node]['up_cpuNum'] = hex(queue-1+stickOffset) - # traverseNetwork(data[node]['children'], depth, major, minorByCPU, queue, parentClassID, upParentClassID, parentMaxDL, parentMaxUL) - # continue - circuitsForThisNetworkNode = [] - nodeClassID = hex(major) + ':' + hex(minorByCPU[queue]) - upNodeClassID = hex(major+stickOffset) + ':' + hex(minorByCPU[queue]) - data[node]['classid'] = nodeClassID - data[node]['up_classid'] = upNodeClassID - if depth == 0: - parentClassID = hex(major) + ':' - upParentClassID = hex(major+stickOffset) + ':' - data[node]['parentClassID'] = parentClassID - data[node]['up_parentClassID'] = upParentClassID - # If in monitorOnlyMode, override bandwidth rates to where no shaping will actually occur - if monitor_mode_only() == True: - data[node]['downloadBandwidthMbps'] = 100000 - data[node]['uploadBandwidthMbps'] = 100000 - data[node]['downloadBandwidthMbpsMin'] = 100000 - data[node]['uploadBandwidthMbpsMin'] = 100000 - # If not in monitorOnlyMode - else: - # Cap based on this node's max bandwidth, or parent node's max bandwidth, whichever is lower - data[node]['downloadBandwidthMbps'] = min(data[node]['downloadBandwidthMbps'],parentMaxDL) - data[node]['uploadBandwidthMbps'] = min(data[node]['uploadBandwidthMbps'],parentMaxUL) - data[node]['downloadBandwidthMbpsMin'] = min(data[node]['downloadBandwidthMbpsMin'], data[node]['downloadBandwidthMbps'], parentMinDL) - data[node]['uploadBandwidthMbpsMin'] = min(data[node]['uploadBandwidthMbpsMin'], data[node]['uploadBandwidthMbps'], parentMinUL) - # Calculations are done in findBandwidthMins() to determine optimal HTB rates (mins) and ceils (maxs) - data[node]['classMajor'] = hex(major) - data[node]['up_classMajor'] = hex(major + stickOffset) - data[node]['classMinor'] = hex(minorByCPU[queue]) - data[node]['cpuNum'] = hex(queue-1) - data[node]['up_cpuNum'] = hex(queue-1+stickOffset) - thisParentNode = { - "parentNodeName": node, - "classID": nodeClassID, - "maxDownload": data[node]['downloadBandwidthMbps'], - "maxUpload": data[node]['uploadBandwidthMbps'], - } - parentNodes.append(thisParentNode) - minorByCPU[queue] = minorByCPU[queue] + 1 - # Check for overflow - TC uses u16 for minor class ID (max 65535) - if minorByCPU[queue] > 0xFFFF: - logging.error(f"Minor class ID overflow on CPU {queue}: {minorByCPU[queue]} exceeds TC's u16 limit (65535). Consider increasing queue count or restructuring network hierarchy.") - raise ValueError(f"Minor class ID overflow on CPU {queue}: {minorByCPU[queue]} exceeds limit of 65535") - # If a device from ShapedDevices.csv lists this node as its Parent Node, attach it as a leaf to this node HTB - if node in circuits_by_parent_node: - # If mins of circuits combined exceed min of parent node - set to 1 - override_min_down = None - override_min_up = None - if monitor_mode_only() == False: - if (circuit_min_down_combined_by_parent_node[node] > data[node]['downloadBandwidthMbpsMin']) or (circuit_min_up_combined_by_parent_node[node] > data[node]['uploadBandwidthMbpsMin']): - override_min_down = 1 - override_min_up = 1 - logging.info("The combined minimums of circuits in Parent Node [" + node + "] exceeded that of the parent node. Reducing these circuits' minimums to 1 now.", stacklevel=2) - if ((override_min_down * len(circuits_by_parent_node[node])) > data[node]['downloadBandwidthMbpsMin']) or ((override_min_up * len(circuits_by_parent_node[node])) > data[node]['uploadBandwidthMbpsMin']): - logging.info("Even with this change, minimums will exceed the min rate of the parent node. Using 10 kbps as the minimum for these circuits instead.", stacklevel=2) - nodes_requiring_min_squashing[node] = True - # Sort circuits by name for stable ordering - sorted_circuits = sorted(circuits_by_parent_node[node], - key=lambda c: c.get('circuitName', c.get('circuitID', ''))) - for circuit in sorted_circuits: - if node == circuit['ParentNode']: - if monitor_mode_only() == False: - if circuit['maxDownload'] > data[node]['downloadBandwidthMbps']: - logging.info("downloadMax of Circuit ID [" + circuit['circuitID'] + "] exceeded that of its parent node. Reducing to that of its parent node now.", stacklevel=2) - if circuit['maxUpload'] > data[node]['uploadBandwidthMbps']: - logging.info("uploadMax of Circuit ID [" + circuit['circuitID'] + "] exceeded that of its parent node. Reducing to that of its parent node now.", stacklevel=2) - parentString = hex(major) + ':' - flowIDstring = hex(major) + ':' + hex(minorByCPU[queue]) - upFlowIDstring = hex(major + stickOffset) + ':' + hex(minorByCPU[queue]) - circuit['classid'] = flowIDstring - circuit['up_classid'] = upFlowIDstring - logging.info("Added up_classid to circuit: " + circuit['up_classid']) - # Create circuit dictionary to be added to network structure, eventually output as queuingStructure.json - maxDownload = min(circuit['maxDownload'],data[node]['downloadBandwidthMbps']) - maxUpload = min(circuit['maxUpload'],data[node]['uploadBandwidthMbps']) - if override_min_down: - circuit['minDownload'] = 1 - if override_min_up: - circuit['minUpload'] = 1 - minDownload = min(circuit['minDownload'],maxDownload) - minUpload = min(circuit['minUpload'],maxUpload) - thisNewCircuitItemForNetwork = { - 'maxDownload' : maxDownload, - 'maxUpload' : maxUpload, - 'minDownload' : minDownload, - 'minUpload' : minUpload, - "circuitID": circuit['circuitID'], - "circuitName": circuit['circuitName'], - "ParentNode": circuit['ParentNode'], - "devices": circuit['devices'], - "classid": flowIDstring, - "up_classid" : upFlowIDstring, - "classMajor": hex(major), - "up_classMajor" : hex(major + stickOffset), - "classMinor": hex(minorByCPU[queue]), - "comment": circuit['comment'] - } - # Generate TC commands to be executed later - thisNewCircuitItemForNetwork['devices'] = circuit['devices'] - circuitsForThisNetworkNode.append(thisNewCircuitItemForNetwork) - minorByCPU[queue] = minorByCPU[queue] + 1 - if len(circuitsForThisNetworkNode) > 0: - data[node]['circuits'] = circuitsForThisNetworkNode - - # Add padding for future circuit additions (applies to all nodes) - # This ensures space is reserved even for nodes without circuits - minorByCPU[queue] = minorByCPU[queue] + CIRCUIT_PADDING - - # Recursive call this function for children nodes attached to this node - if 'children' in data[node]: - # Sort children to ensure consistent traversal order - sorted_children = dict(sorted(data[node]['children'].items())) - # We need to keep tabs on the minor counter, because we can't have repeating class IDs. Here, we bring back the minor counter from the recursive function - minorByCPU[queue] = minorByCPU[queue] + 1 - # Check for overflow - TC uses u16 for minor class ID (max 65535) - if minorByCPU[queue] > 0xFFFF: - logging.error(f"Minor class ID overflow on CPU {queue}: {minorByCPU[queue]} exceeds TC's u16 limit (65535). Consider increasing queue count or restructuring network hierarchy.") - raise ValueError(f"Minor class ID overflow on CPU {queue}: {minorByCPU[queue]} exceeds limit of 65535") - minorByCPU = traverseNetwork(sorted_children, depth+1, major, minorByCPU, queue, nodeClassID, upNodeClassID, data[node]['downloadBandwidthMbps'], data[node]['uploadBandwidthMbps'], data[node]['downloadBandwidthMbpsMin'], data[node]['uploadBandwidthMbpsMin']) - # If top level node, increment to next queue / cpu core - if depth == 0: - if queue >= queuesAvailable: - queue = 1 - major = queue - else: - queue += 1 - major += 1 - return minorByCPU - - # If we're in binpacking mode, we need to sort the network structure a bit - bins = [] - if use_bin_packing_to_balance_cpu() and not is_network_flat(): - print("BinPacking is enabled, so we're going to sort your network.") - cpuBin = {} - weights = get_tree_weights() - # Stable tie-breaking: sort by (-weight, name) so equal weights have deterministic order - try: - weights = sorted(weights, key=lambda w: (-int(w.weight), str(w.name))) - except Exception: - pass - for w in weights: - cpuBin[w.name] = w.weight - bins = binpacking.to_constant_bin_number(cpuBin, queuesAvailable) - for x in range(queuesAvailable): - print("Bin " + str(x) + " = ", bins[x]) - binnedNetwork = {} - for cpu in range(queuesAvailable): - cpuKey = "CpueQueue" + str(cpu) - binnedNetwork[cpuKey] = { - 'downloadBandwidthMbps': generated_pn_download_mbps(), - 'uploadBandwidthMbps': generated_pn_upload_mbps(), - 'type': 'site', - 'downloadBandwidthMbpsMin': generated_pn_download_mbps(), - 'uploadBandwidthMbpsMin': generated_pn_upload_mbps(), - 'children': {}, - 'name': cpuKey - } - for node in network: - found = False - for bin in range(queuesAvailable): - if node in bins[bin]: - binnedNetwork["CpueQueue" + str(bin)]['children'][node] = network[node] - found = True - if found == False: - newQueueId = queuesAvailable-1 - binnedNetwork["CpueQueue" + str(newQueueId)]['children'][node] = network[node] - network = binnedNetwork - - # Here is the actual call to the recursive traverseNetwork() function. finalMinor is not used. - minorByCPU = traverseNetwork(network, 0, major=1, minorByCPU=minorByCPUpreloaded, queue=1, parentClassID=None, upParentClassID=None, parentMaxDL=upstream_bandwidth_capacity_download_mbps(), parentMaxUL=upstream_bandwidth_capacity_upload_mbps(), parentMinDL=upstream_bandwidth_capacity_download_mbps(), parentMinUL=upstream_bandwidth_capacity_upload_mbps()) - - bakery = Bakery() - bakery.start_batch() # Initializes the bakery transaction - linuxTCcommands = [] - devicesShaped = [] - # Root HTB Setup - # Create MQ qdisc for each CPU core / rx-tx queue. Generate commands to create corresponding HTB and leaf classes. Prepare commands for execution later - thisInterface = interface_a() - logging.info("# MQ Setup for " + thisInterface) - command = 'qdisc replace dev ' + thisInterface + ' root handle 7FFF: mq' - bakery.setup_mq(queuesAvailable, stickOffset) - linuxTCcommands.append(command) - maxBandwidth = max(upstream_bandwidth_capacity_upload_mbps(), upstream_bandwidth_capacity_download_mbps()) - calculateR2q(maxBandwidth) - for queue in range(queuesAvailable): - command = 'qdisc add dev ' + thisInterface + ' parent 7FFF:' + hex(queue+1) + ' handle ' + hex(queue+1) + ': htb default 2' - linuxTCcommands.append(command) - command = 'class add dev ' + thisInterface + ' parent ' + hex(queue+1) + ': classid ' + hex(queue+1) + ':1 htb rate '+ format_rate_for_tc(upstream_bandwidth_capacity_download_mbps()) + ' ceil ' + format_rate_for_tc(upstream_bandwidth_capacity_download_mbps()) + quantum(upstream_bandwidth_capacity_download_mbps()) - linuxTCcommands.append(command) - command = 'qdisc add dev ' + thisInterface + ' parent ' + hex(queue+1) + ':1 ' + sqm() - linuxTCcommands.append(command) - # Default class - traffic gets passed through this limiter with lower priority if it enters the top HTB without a specific class. - # Technically, that should not even happen. So don't expect much if any traffic in this default class. - # Only 1/4 of defaultClassCapacity is guaranteed (to prevent hitting ceiling of upstream), for the most part it serves as an "up to" ceiling. - command = 'class add dev ' + thisInterface + ' parent ' + hex(queue+1) + ':1 classid ' + hex(queue+1) + ':2 htb rate ' + format_rate_for_tc(round((upstream_bandwidth_capacity_download_mbps()-1)/4)) + ' ceil ' + format_rate_for_tc(upstream_bandwidth_capacity_download_mbps()-1) + ' prio 5' + quantum(upstream_bandwidth_capacity_download_mbps()) - linuxTCcommands.append(command) - command = 'qdisc add dev ' + thisInterface + ' parent ' + hex(queue+1) + ':2 ' + sqm() - linuxTCcommands.append(command) - - # Note the use of stickOffset, and not replacing the root queue if we're on a stick - thisInterface = interface_b() - logging.info("# MQ Setup for " + thisInterface) - if not on_a_stick(): - command = 'qdisc replace dev ' + thisInterface + ' root handle 7FFF: mq' - linuxTCcommands.append(command) - for queue in range(queuesAvailable): - command = 'qdisc add dev ' + thisInterface + ' parent 7FFF:' + hex(queue+stickOffset+1) + ' handle ' + hex(queue+stickOffset+1) + ': htb default 2' - linuxTCcommands.append(command) - command = 'class add dev ' + thisInterface + ' parent ' + hex(queue+stickOffset+1) + ': classid ' + hex(queue+stickOffset+1) + ':1 htb rate '+ format_rate_for_tc(upstream_bandwidth_capacity_upload_mbps()) + ' ceil ' + format_rate_for_tc(upstream_bandwidth_capacity_upload_mbps()) + quantum(upstream_bandwidth_capacity_upload_mbps()) - linuxTCcommands.append(command) - command = 'qdisc add dev ' + thisInterface + ' parent ' + hex(queue+stickOffset+1) + ':1 ' + sqm() - linuxTCcommands.append(command) - # Default class - traffic gets passed through this limiter with lower priority if it enters the top HTB without a specific class. - # Technically, that should not even happen. So don't expect much if any traffic in this default class. - # Only 1/4 of defaultClassCapacity is guarenteed (to prevent hitting ceiling of upstream), for the most part it serves as an "up to" ceiling. - command = 'class add dev ' + thisInterface + ' parent ' + hex(queue+stickOffset+1) + ':1 classid ' + hex(queue+stickOffset+1) + ':2 htb rate ' + format_rate_for_tc(round((upstream_bandwidth_capacity_upload_mbps()-1)/4)) + ' ceil ' + format_rate_for_tc(upstream_bandwidth_capacity_upload_mbps()-1) + ' prio 5' + quantum(upstream_bandwidth_capacity_upload_mbps()) - linuxTCcommands.append(command) - command = 'qdisc add dev ' + thisInterface + ' parent ' + hex(queue+stickOffset+1) + ':2 ' + sqm() - linuxTCcommands.append(command) - - - # Parse network structure. For each tier, generate commands to create corresponding HTB and leaf classes. Prepare commands for execution later - # Define lists for hash filters - print("Preparing TC commands") - def traverseNetwork(data): - - # Cake needs help handling rates lower than 5 Mbps - def sqmFixupRate(rate:int, sqm:str) -> str: - # If we aren't using cake, just return the sqm string - if not sqm.startswith("cake") or "rtt" in sqm: - return sqm - - # If we are using cake, we need to fixup the rate - # Based on: 1 MTU is 1500 bytes, or 12,000 bits. - # At 1 Mbps, (1,000 bits per ms) transmitting an MTU takes 12ms. Add 3ms for overhead, and we get 15ms. - # So 15ms divided by 5 (for 1%) multiplied by 100 yields 300ms. - # The same formula gives 180ms at 2Mbps - # 140ms at 3Mbps - # 120ms at 4Mbps - match rate: - case 1: return sqm + " rtt 300" - case 2: return sqm + " rtt 180" - case 3: return sqm + " rtt 140" - case 4: return sqm + " rtt 120" - case _: return sqm - - for node in sorted(data.keys()): - site_name = data[node]['name'] if 'name' in data[node] else node - bakery.add_site( - site_name, - data[node]['parentClassID'], - data[node]['up_parentClassID'], - int(data[node]['classMinor'], 16), - data[node]['downloadBandwidthMbpsMin'], - data[node]['uploadBandwidthMbpsMin'], - data[node]['downloadBandwidthMbps'], - data[node]['uploadBandwidthMbps'], - ) - command = 'class add dev ' + interface_a() + ' parent ' + data[node]['parentClassID'] + ' classid ' + data[node]['classMinor'] + ' htb rate '+ format_rate_for_tc(data[node]['downloadBandwidthMbpsMin']) + ' ceil '+ format_rate_for_tc(data[node]['downloadBandwidthMbps']) + ' prio 3' + quantum(data[node]['downloadBandwidthMbps']) - linuxTCcommands.append(command) - logging.info("Up ParentClassID: " + data[node]['up_parentClassID']) - logging.info("ClassMinor: " + data[node]['classMinor']) - command = 'class add dev ' + interface_b() + ' parent ' + data[node]['up_parentClassID'] + ' classid ' + data[node]['classMinor'] + ' htb rate '+ format_rate_for_tc(data[node]['uploadBandwidthMbpsMin']) + ' ceil '+ format_rate_for_tc(data[node]['uploadBandwidthMbps']) + ' prio 3' + quantum(data[node]['uploadBandwidthMbps']) - linuxTCcommands.append(command) - if 'circuits' in data[node]: - # Sort circuits by name for stable ordering - sorted_circuits = sorted(data[node]['circuits'], - key=lambda c: c.get('circuitName', c.get('circuitID', ''))) - for circuit in sorted_circuits: - # If circuit mins exceed node mins - handle low min rates of 1 to mean 10 kbps. - # Avoid changing minDownload or minUpload because they are used in queuingStructure.json, and must remain integers. - min_down = circuit['minDownload'] - min_up = circuit['minUpload'] - if node in nodes_requiring_min_squashing: - if min_down == 1: - min_down = 0.01 - if min_up == 1: - min_up = 0.01 - # Generate TC commands to be executed later - tcComment = " # CircuitID: " + circuit['circuitID'] + " DeviceIDs: " - for device in circuit['devices']: - tcComment = '' #tcComment + device['deviceID'] + ', ' - if 'devices' in circuit: - if 'comment' in circuit['devices'][0]: - tcComment = '' # tcComment + '| Comment: ' + circuit['devices'][0]['comment'] - tcComment = tcComment.replace("\n", "") - circuit_name = circuit['circuitID'] if 'circuitID' in circuit else "unknown" - # Collect all IP addresses for this circuit - ip_list = [] - for device in circuit['devices']: - if device['ipv4s']: - ip_list.extend(device['ipv4s']) - if device['ipv6s']: - ip_list.extend(device['ipv6s']) - # Concatenate IPs with comma separator - ip_addresses_str = ','.join(ip_list) - - bakery.add_circuit( - circuit_name, - data[node]['classid'], - data[node]['up_classid'], - int(circuit['classMinor'], 16), - min_down, - min_up, - circuit['maxDownload'], - circuit['maxUpload'], - int(circuit['classMajor'], 16), - int(circuit['up_classMajor'], 16), - ip_addresses_str, - ) - command = 'class add dev ' + interface_a() + ' parent ' + data[node]['classid'] + ' classid ' + circuit['classMinor'] + ' htb rate '+ format_rate_for_tc(min_down) + ' ceil '+ format_rate_for_tc(circuit['maxDownload']) + ' prio 3' + quantum(circuit['maxDownload']) + tcComment - linuxTCcommands.append(command) - # Only add CAKE / fq_codel qdisc if monitorOnlyMode is Off - if monitor_mode_only() == False: - # SQM Fixup for lower rates - useSqm = sqmFixupRate(circuit['maxDownload'], sqm()) - command = 'qdisc add dev ' + interface_a() + ' parent ' + circuit['classMajor'] + ':' + circuit['classMinor'] + ' ' + useSqm - linuxTCcommands.append(command) - command = 'class add dev ' + interface_b() + ' parent ' + data[node]['up_classid'] + ' classid ' + circuit['classMinor'] + ' htb rate '+ format_rate_for_tc(min_up) + ' ceil '+ format_rate_for_tc(circuit['maxUpload']) + ' prio 3' + quantum(circuit['maxUpload']) - linuxTCcommands.append(command) - # Only add CAKE / fq_codel qdisc if monitorOnlyMode is Off - if monitor_mode_only() == False: - # SQM Fixup for lower rates - useSqm = sqmFixupRate(circuit['maxUpload'], sqm()) - command = 'qdisc add dev ' + interface_b() + ' parent ' + circuit['up_classMajor'] + ':' + circuit['classMinor'] + ' ' + useSqm - linuxTCcommands.append(command) - pass - for device in circuit['devices']: - if device['ipv4s']: - for ipv4 in device['ipv4s']: - ipMapBatch.add_ip_mapping(str(ipv4), circuit['classid'], data[node]['cpuNum'], False) - #xdpCPUmapCommands.append('./bin/xdp_iphash_to_cpu_cmdline add --ip ' + str(ipv4) + ' --cpu ' + data[node]['cpuNum'] + ' --classid ' + circuit['classid']) - if on_a_stick(): - ipMapBatch.add_ip_mapping(str(ipv4), circuit['up_classid'], data[node]['up_cpuNum'], True) - #xdpCPUmapCommands.append('./bin/xdp_iphash_to_cpu_cmdline add --ip ' + str(ipv4) + ' --cpu ' + data[node]['up_cpuNum'] + ' --classid ' + circuit['up_classid'] + ' --upload 1') - if device['ipv6s']: - for ipv6 in device['ipv6s']: - ipMapBatch.add_ip_mapping(str(ipv6), circuit['classid'], data[node]['cpuNum'], False) - #xdpCPUmapCommands.append('./bin/xdp_iphash_to_cpu_cmdline add --ip ' + str(ipv6) + ' --cpu ' + data[node]['cpuNum'] + ' --classid ' + circuit['classid']) - if on_a_stick(): - ipMapBatch.add_ip_mapping(str(ipv6), circuit['up_classid'], data[node]['up_cpuNum'], True) - #xdpCPUmapCommands.append('./bin/xdp_iphash_to_cpu_cmdline add --ip ' + str(ipv6) + ' --cpu ' + data[node]['up_cpuNum'] + ' --classid ' + circuit['up_classid'] + ' --upload 1') - if device['deviceName'] not in devicesShaped: - devicesShaped.append(device['deviceName']) - # Recursive call this function for children nodes attached to this node - if 'children' in data[node]: - # Sort children to ensure consistent traversal order - sorted_children = dict(sorted(data[node]['children'].items())) - traverseNetwork(sorted_children) - # Here is the actual call to the recursive traverseNetwork() function. - traverseNetwork(network) - - # Save queuingStructure - queuingStructure = {} - queuingStructure['Network'] = network - queuingStructure['lastUsedClassIDCounterByCPU'] = minorByCPU - queuingStructure['generatedPNs'] = generatedPNs - with open('queuingStructure.json', 'w') as infile: - json.dump(queuingStructure, infile, indent=4) - - - # Record start time of actual filter reload - reloadStartTime = datetime.now() - - - # Clear Prior Settings - # We don't want to do this every time, with lqosd managing queues statefully. - # clearPriorSettings(interface_a(), interface_b()) - - - # Setup XDP and disable XPS regardless of whether it is first run or not (necessary to handle cases where systemctl stop was used) - xdpStartTime = datetime.now() - #if enable_actual_shell_commands(): - # The bakery will handle stale mapping cleanup; avoid clearing mappings here. - # Set up XDP-CPUMAP-TC - logging.info("# XDP Setup") - # Commented out - the daemon does this - #shell('./cpumap-pping/bin/xps_setup.sh -d ' + interfaceA + ' --default --disable') - #shell('./cpumap-pping/bin/xps_setup.sh -d ' + interfaceB + ' --default --disable') - #shell('./cpumap-pping/src/xdp_iphash_to_cpu --dev ' + interfaceA + ' --lan') - #shell('./cpumap-pping/src/xdp_iphash_to_cpu --dev ' + interfaceB + ' --wan') - #shell('./cpumap-pping/src/tc_classify --dev-egress ' + interfaceA) - #shell('./cpumap-pping/src/tc_classify --dev-egress ' + interfaceB) - xdpEndTime = datetime.now() - - - # Execute actual Linux TC commands - tcStartTime = datetime.now() - # print("Executing linux TC class/qdisc commands") - with open('linux_tc.txt', 'w') as f: - for command in linuxTCcommands: - logging.info(command) - f.write(f"{command}\n") - # if logging.DEBUG <= logging.root.level: - # # Do not --force in debug mode, so we can see any errors - # shell("/sbin/tc -b linux_tc.txt") - # else: - # shell("/sbin/tc -f -b linux_tc.txt") - bakery.commit() - tcEndTime = datetime.now() - # print("Executed " + str(len(linuxTCcommands)) + " linux TC class/qdisc commands") - - # Execute actual XDP-CPUMAP-TC filter commands - xdpFilterStartTime = datetime.now() - print("Executing XDP-CPUMAP-TC IP filter commands") - numXdpCommands = ipMapBatch.length() - if enable_actual_shell_commands(): - ipMapBatch.finish_ip_mappings() - ipMapBatch.submit() - #for command in xdpCPUmapCommands: - # logging.info(command) - # commands = command.split(' ') - # proc = subprocess.Popen(commands, stdout=subprocess.DEVNULL) - else: - ipMapBatch.log() - #for command in xdpCPUmapCommands: - # logging.info(command) - print("Executed " + str(numXdpCommands) + " XDP-CPUMAP-TC IP filter commands") - #print(xdpCPUmapCommands) - xdpFilterEndTime = datetime.now() - - - # Record end time of all reload commands - reloadEndTime = datetime.now() - - - # Recap - warn operator if devices were skipped - devicesSkipped = [] - for circuit in subscriberCircuits: - for device in circuit['devices']: - if device['deviceName'] not in devicesShaped: - devicesSkipped.append((device['deviceName'],device['deviceID'])) - if len(devicesSkipped) > 0: - warnings.warn('Some devices were not shaped. Please check to ensure they have a valid ParentNode listed in ShapedDevices.csv:', stacklevel=2) - print("Devices not shaped:") - for entry in devicesSkipped: - name, idNum = entry - print('DeviceID: ' + idNum + '\t DeviceName: ' + name) - - # Save ShapedDevices.csv as ShapedDevices.lastLoaded.csv - shutil.copyfile('ShapedDevices.csv', 'ShapedDevices.lastLoaded.csv') - - # Save for stats - with open('statsByCircuit.json', 'w') as f: - f.write(json.dumps(subscriberCircuits, indent=4)) - with open('statsByParentNode.json', 'w') as f: - f.write(json.dumps(parentNodes, indent=4)) - - - # Record time this run completed at - # filename = os.path.join(_here, 'lastRun.txt') - with open("lastRun.txt", 'w') as file: - file.write(datetime.now().strftime("%d-%b-%Y (%H:%M:%S.%f)")) - - - # Report reload time - reloadTimeSeconds = ((reloadEndTime - reloadStartTime).seconds) + (((reloadEndTime - reloadStartTime).microseconds) / 1000000) - tcTimeSeconds = ((tcEndTime - tcStartTime).seconds) + (((tcEndTime - tcStartTime).microseconds) / 1000000) - xdpSetupTimeSeconds = ((xdpEndTime - xdpStartTime).seconds) + (((xdpEndTime - xdpStartTime).microseconds) / 1000000) - xdpFilterTimeSeconds = ((xdpFilterEndTime - xdpFilterStartTime).seconds) + (((xdpFilterEndTime - xdpFilterStartTime).microseconds) / 1000000) - print("Queue and IP filter reload completed in " + "{:g}".format(round(reloadTimeSeconds,1)) + " seconds") - print("\tTC commands: \t" + "{:g}".format(round(tcTimeSeconds,1)) + " seconds") - print("\tXDP setup: \t " + "{:g}".format(round(xdpSetupTimeSeconds,1)) + " seconds") - print("\tXDP filters: \t " + "{:g}".format(round(xdpFilterTimeSeconds,4)) + " seconds") - - - # Done - print("refreshShapers completed on " + datetime.now().strftime("%d/%m/%Y %H:%M:%S")) + + # Starting + print("refreshShapers starting at " + datetime.now().strftime("%d/%m/%Y %H:%M:%S")) + # Create a single batch of xdp update commands to execute together + ipMapBatch = BatchedCommands() + + # Warn user if enableActualShellCommands is False, because that would mean no actual commands are executing + if enable_actual_shell_commands() == False: + warnings.warn("enableActualShellCommands is set to False. None of the commands below will actually be executed. Simulated run.", stacklevel=2) + # Warn user if monitorOnlyMode is True, because that would mean no actual shaping is happening + if monitor_mode_only() == True: + warnings.warn("monitorOnlyMode is set to True. Shaping will not occur.", stacklevel=2) + + + # Check if first run since boot + isThisFirstRunSinceBoot = checkIfFirstRunSinceBoot() + + + # Files + shapedDevicesFile = get_shaped_devices_path() + networkJSONfile = get_network_json_path() + + + # Check validation + safeToRunRefresh = False + print("Validating input files '" + shapedDevicesFile + "' and '" + networkJSONfile + "'") + if (validateNetworkAndDevices() == True): + shutil.copyfile('ShapedDevices.csv', 'lastGoodConfig.csv') + shutil.copyfile('network.json', 'lastGoodConfig.json') + print("Backed up good config as lastGoodConfig.csv and lastGoodConfig.json") + safeToRunRefresh = True + else: + if (isThisFirstRunSinceBoot == False): + warnings.warn("Validation failed. Because this is not the first run since boot (queues already set up) - will now exit.", stacklevel=2) + safeToRunRefresh = False + else: + warnings.warn("Validation failed. However - because this is the first run since boot - will load queues from last good config", stacklevel=2) + shapedDevicesFile = 'lastGoodConfig.csv' + networkJSONfile = 'lastGoodConfig.json' + safeToRunRefresh = True + + if safeToRunRefresh == True: + + # Load Subscriber Circuits & Devices + subscriberCircuits, dictForCircuitsWithoutParentNodes = loadSubscriberCircuits(shapedDevicesFile) + + + # Load network hierarchy + with open(networkJSONfile, 'r') as j: + network = json.loads(j.read()) + + + # Pull rx/tx queues / CPU cores available + # Handling the case when the number of queues for interfaces are different + InterfaceAQueuesAvailable = findQueuesAvailable(interface_a()) + InterfaceBQueuesAvailable = findQueuesAvailable(interface_b()) + queuesAvailable = min(InterfaceAQueuesAvailable, InterfaceBQueuesAvailable) + stickOffset = 0 + if on_a_stick(): + print("On-a-stick override dividing queues") + # The idea here is that download use queues 0 - n/2, upload uses the other half + queuesAvailable = math.floor(queuesAvailable / 2) + stickOffset = queuesAvailable + + # If in monitorOnlyMode, override network.json bandwidth rates to where no shaping will actually occur + if monitor_mode_only() == True: + def overrideNetworkBandwidths(data): + for elem in data: + if 'children' in data[elem]: + overrideNetworkBandwidths(data[elem]['children']) + data[elem]['downloadBandwidthMbpsMin'] = 100000 + data[elem]['uploadBandwidthMbpsMin'] = 100000 + overrideNetworkBandwidths(network) + + # Generate Parent Nodes. Spread ShapedDevices.csv which lack defined ParentNode across these (balance across CPUs) + print("Generating parent nodes") + generatedPNs = [] + numberOfGeneratedPNs = queuesAvailable + # If in monitorOnlyMode, override bandwidth rates to where no shaping will actually occur + if monitor_mode_only() == True: + chosenDownloadMbps = 10000 + chosenUploadMbps = 10000 + else: + chosenDownloadMbps = generated_pn_download_mbps() + chosenUploadMbps = generated_pn_upload_mbps() + for x in range(numberOfGeneratedPNs): + genPNname = "Generated_PN_" + str(x+1) + network[genPNname] = { + "downloadBandwidthMbps": chosenDownloadMbps, + "uploadBandwidthMbps": chosenUploadMbps + } + generatedPNs.append(genPNname) + if use_bin_packing_to_balance_cpu(): + print("Using binpacking module to sort circuits by CPU core") + weights = get_weights() + if weights is not None and dictForCircuitsWithoutParentNodes is not None: + for circuitId in dictForCircuitsWithoutParentNodes: + for circuit in subscriberCircuits: + if 'idForCircuitsWithoutParentNodes' in circuit and circuit['idForCircuitsWithoutParentNodes'] == circuitId: + for w in weights: + if w.circuit_id == circuit['circuitID']: + dictForCircuitsWithoutParentNodes[circuitId] = w.weight + bins = binpacking.to_constant_bin_number(dictForCircuitsWithoutParentNodes, numberOfGeneratedPNs) + genPNcounter = 0 + for binItem in bins: + sumItem = 0 + logging.info(generatedPNs[genPNcounter] + " will contain " + str(len(binItem)) + " circuits") + for key in binItem.keys(): + for circuit in subscriberCircuits: + if circuit['ParentNode'] == 'none': + if circuit['idForCircuitsWithoutParentNodes'] == key: + circuit['ParentNode'] = generatedPNs[genPNcounter] + genPNcounter += 1 + if genPNcounter >= queuesAvailable: + genPNcounter = 0 + print("Finished binpacking") + else: + genPNcounter = 0 + for circuit in subscriberCircuits: + if circuit['ParentNode'] == 'none': + circuit['ParentNode'] = generatedPNs[genPNcounter] + genPNcounter += 1 + if genPNcounter >= queuesAvailable: + genPNcounter = 0 + print("Generated parent nodes created") + + # Find the bandwidth minimums for each node by combining mimimums of devices lower in that node's hierarchy + def findBandwidthMins(data, depth): + tabs = ' ' * depth + minDownload = 0 + minUpload = 0 + for elem in data: + for circuit in subscriberCircuits: + if elem == circuit['ParentNode']: + minDownload += circuit['minDownload'] + minUpload += circuit['minUpload'] + if 'children' in data[elem]: + minDL, minUL = findBandwidthMins(data[elem]['children'], depth+1) + minDownload += minDL + minUpload += minUL + if 'downloadBandwidthMbpsMin' in data[elem]: + data[elem]['downloadBandwidthMbpsMin'] = max(data[elem]['downloadBandwidthMbpsMin'], minDownload) + else: + data[elem]['downloadBandwidthMbpsMin'] = max(data[elem]['downloadBandwidthMbps'], minUpload) + if 'uploadBandwidthMbpsMin' in data[elem]: + data[elem]['uploadBandwidthMbpsMin'] = max(data[elem]['uploadBandwidthMbpsMin'], minUpload) + else: + data[elem]['uploadBandwidthMbpsMin'] = max(data[elem]['uploadBandwidthMbps'], minUpload) + return minDownload, minUpload + logging.info("Finding the bandwidth minimums for each node") + minDownload, minUpload = findBandwidthMins(network, 0) + logging.info("Found the bandwidth minimums for each node") + + # Child nodes inherit bandwidth maximums of parents. We apply this here to avoid bugs when compression is applied with flattenA(). + def inheritBandwidthMaxes(data, parentMaxDL, parentMaxUL, parentMinDL, parentMinUL): + for node in data: + if isinstance(node, str): + if (isinstance(data[node], dict)) and (node != 'children'): + # Cap based on this node's max bandwidth, or parent node's max bandwidth, whichever is lower + data[node]['downloadBandwidthMbps'] = min(int(data[node]['downloadBandwidthMbps']),int(parentMaxDL)) + data[node]['uploadBandwidthMbps'] = min(int(data[node]['uploadBandwidthMbps']),int(parentMaxUL)) + data[node]['downloadBandwidthMbpsMin'] = min(int(data[node]['downloadBandwidthMbpsMin']),int(data[node]['downloadBandwidthMbps']),int(parentMinDL)) + data[node]['uploadBandwidthMbpsMin'] = min(int(data[node]['uploadBandwidthMbpsMin']),int(data[node]['uploadBandwidthMbps']),int(parentMinUL)) + # Recursive call this function for children nodes attached to this node + if 'children' in data[node]: + # We need to keep tabs on the minor counter, because we can't have repeating class IDs. Here, we bring back the minor counter from the recursive function + inheritBandwidthMaxes(data[node]['children'], data[node]['downloadBandwidthMbps'], data[node]['uploadBandwidthMbps'], data[node]['downloadBandwidthMbpsMin'], data[node]['uploadBandwidthMbpsMin']) + #return data + # Here is the actual call to the recursive function + inheritBandwidthMaxes(network, parentMaxDL=upstream_bandwidth_capacity_download_mbps(), parentMaxUL=upstream_bandwidth_capacity_upload_mbps(), parentMinDL=upstream_bandwidth_capacity_download_mbps(), parentMinUL=upstream_bandwidth_capacity_upload_mbps()) + + # Compress network.json. HTB only supports 8 levels of HTB depth. Compress to 8 layers if beyond 8. + def flattenB(data): + newDict = {} + for node in data: + if isinstance(node, str): + if (isinstance(data[node], dict)) and (node != 'children'): + newDict[node] = dict(data[node]) + if 'children' in data[node]: + result = flattenB(data[node]['children']) + del newDict[node]['children'] + newDict.update(result) + return newDict + def flattenA(data, depth): + newDict = {} + for node in data: + if isinstance(node, str): + if (isinstance(data[node], dict)) and (node != 'children'): + newDict[node] = dict(data[node]) + if 'children' in data[node]: + result = flattenA(data[node]['children'], depth+2) + del newDict[node]['children'] + if depth <= 8: + newDict[node]['children'] = result + else: + flattened = flattenB(data[node]['children']) + if 'children' in newDict[node]: + newDict[node]['children'].update(flattened) + else: + newDict[node]['children'] = flattened + return newDict + network = flattenA(network, 1) + + # Group circuits by parent node. Reduces runtime for section below this one. + circuits_by_parent_node = {} + circuit_min_down_combined_by_parent_node = {} + circuit_min_up_combined_by_parent_node = {} + for circuit in subscriberCircuits: + #If a device from ShapedDevices.csv lists this node as its Parent Node, attach it as a leaf to this node HTB + if circuit['ParentNode'] not in circuits_by_parent_node: + circuits_by_parent_node[circuit['ParentNode']] = [] + temp = circuits_by_parent_node[circuit['ParentNode']] + temp.append(circuit) + circuits_by_parent_node[circuit['ParentNode']] = temp + if circuit['ParentNode'] not in circuit_min_down_combined_by_parent_node: + circuit_min_down_combined_by_parent_node[circuit['ParentNode']] = 0 + circuit_min_down_combined_by_parent_node[circuit['ParentNode']] += circuit['minDownload'] + if circuit['ParentNode'] not in circuit_min_up_combined_by_parent_node: + circuit_min_up_combined_by_parent_node[circuit['ParentNode']] = 0 + circuit_min_up_combined_by_parent_node[circuit['ParentNode']] += circuit['minUpload'] + + # Parse network structure and add devices from ShapedDevices.csv + print("Parsing network structure and tallying devices") + parentNodes = [] + minorByCPUpreloaded = {} + knownClassIDs = [] + nodes_requiring_min_squashing = {} + # Track minor counter by CPU. This way we can have > 32000 hosts (htb has u16 limit to minor handle) + # Minor numbers start at 3 to reserve 1 for root qdisc and 2 for default class + # With CIRCUIT_PADDING, we leave gaps between nodes to allow future circuit additions + # without disrupting existing ClassID assignments. This maintains stability across reloads. + for x in range(queuesAvailable): + minorByCPUpreloaded[x+1] = 3 + def traverseNetwork(data, depth, major, minorByCPU, queue, parentClassID, upParentClassID, parentMaxDL, parentMaxUL, parentMinDL, parentMinUL): + # ClassID Assignment Strategy: + # - Nodes and circuits are processed in alphabetical order for stability + # - Each node gets a unique minor number that increments sequentially + # - After processing all circuits for a node, we add CIRCUIT_PADDING to the minor counter + # - This creates gaps that allow adding new circuits without affecting other ClassIDs + # - Children are also sorted before recursive processing to ensure deterministic traversal + # For top-level binpacked keys (CpueQueueN), enforce numeric ordering of N + keys = list(data.keys()) + if depth == 0 and len(keys) > 0 and all(k.startswith("CpueQueue") for k in keys): + try: + keys.sort(key=lambda k: int(k.replace("CpueQueue", ""))) + except Exception: + keys = sorted(keys) + else: + keys = sorted(keys) + for node in keys: + #if data[node]['type'] == "virtual": + # print(node + " is a virtual node. Skipping.") + # if depth == 0: + # parentClassID = hex(major) + ':' + # upParentClassID = hex(major+stickOffset) + ':' + # data[node]['parentClassID'] = parentClassID + # data[node]['up_parentClassID'] = upParentClassID + # data[node]['classMajor'] = hex(major) + # data[node]['up_classMajor'] = hex(major + stickOffset) + # data[node]['classMinor'] = hex(minorByCPU[queue]) + # data[node]['cpuNum'] = hex(queue-1) + # data[node]['up_cpuNum'] = hex(queue-1+stickOffset) + # traverseNetwork(data[node]['children'], depth, major, minorByCPU, queue, parentClassID, upParentClassID, parentMaxDL, parentMaxUL) + # continue + circuitsForThisNetworkNode = [] + nodeClassID = hex(major) + ':' + hex(minorByCPU[queue]) + upNodeClassID = hex(major+stickOffset) + ':' + hex(minorByCPU[queue]) + data[node]['classid'] = nodeClassID + data[node]['up_classid'] = upNodeClassID + if depth == 0: + parentClassID = hex(major) + ':' + upParentClassID = hex(major+stickOffset) + ':' + data[node]['parentClassID'] = parentClassID + data[node]['up_parentClassID'] = upParentClassID + # If in monitorOnlyMode, override bandwidth rates to where no shaping will actually occur + if monitor_mode_only() == True: + data[node]['downloadBandwidthMbps'] = 100000 + data[node]['uploadBandwidthMbps'] = 100000 + data[node]['downloadBandwidthMbpsMin'] = 100000 + data[node]['uploadBandwidthMbpsMin'] = 100000 + # If not in monitorOnlyMode + else: + # Cap based on this node's max bandwidth, or parent node's max bandwidth, whichever is lower + data[node]['downloadBandwidthMbps'] = min(data[node]['downloadBandwidthMbps'],parentMaxDL) + data[node]['uploadBandwidthMbps'] = min(data[node]['uploadBandwidthMbps'],parentMaxUL) + data[node]['downloadBandwidthMbpsMin'] = min(data[node]['downloadBandwidthMbpsMin'], data[node]['downloadBandwidthMbps'], parentMinDL) + data[node]['uploadBandwidthMbpsMin'] = min(data[node]['uploadBandwidthMbpsMin'], data[node]['uploadBandwidthMbps'], parentMinUL) + # Calculations are done in findBandwidthMins() to determine optimal HTB rates (mins) and ceils (maxs) + data[node]['classMajor'] = hex(major) + data[node]['up_classMajor'] = hex(major + stickOffset) + data[node]['classMinor'] = hex(minorByCPU[queue]) + data[node]['cpuNum'] = hex(queue-1) + data[node]['up_cpuNum'] = hex(queue-1+stickOffset) + thisParentNode = { + "parentNodeName": node, + "classID": nodeClassID, + "maxDownload": data[node]['downloadBandwidthMbps'], + "maxUpload": data[node]['uploadBandwidthMbps'], + } + parentNodes.append(thisParentNode) + minorByCPU[queue] = minorByCPU[queue] + 1 + # Check for overflow - TC uses u16 for minor class ID (max 65535) + if minorByCPU[queue] > 0xFFFF: + logging.error(f"Minor class ID overflow on CPU {queue}: {minorByCPU[queue]} exceeds TC's u16 limit (65535). Consider increasing queue count or restructuring network hierarchy.") + raise ValueError(f"Minor class ID overflow on CPU {queue}: {minorByCPU[queue]} exceeds limit of 65535") + # If a device from ShapedDevices.csv lists this node as its Parent Node, attach it as a leaf to this node HTB + if node in circuits_by_parent_node: + # If mins of circuits combined exceed min of parent node - set to 1 + override_min_down = None + override_min_up = None + if monitor_mode_only() == False: + if (circuit_min_down_combined_by_parent_node[node] > data[node]['downloadBandwidthMbpsMin']) or (circuit_min_up_combined_by_parent_node[node] > data[node]['uploadBandwidthMbpsMin']): + override_min_down = 1 + override_min_up = 1 + logging.info("The combined minimums of circuits in Parent Node [" + node + "] exceeded that of the parent node. Reducing these circuits' minimums to 1 now.", stacklevel=2) + if ((override_min_down * len(circuits_by_parent_node[node])) > data[node]['downloadBandwidthMbpsMin']) or ((override_min_up * len(circuits_by_parent_node[node])) > data[node]['uploadBandwidthMbpsMin']): + logging.info("Even with this change, minimums will exceed the min rate of the parent node. Using 10 kbps as the minimum for these circuits instead.", stacklevel=2) + nodes_requiring_min_squashing[node] = True + # Sort circuits by name for stable ordering + sorted_circuits = sorted(circuits_by_parent_node[node], + key=lambda c: c.get('circuitName', c.get('circuitID', ''))) + for circuit in sorted_circuits: + if node == circuit['ParentNode']: + if monitor_mode_only() == False: + if circuit['maxDownload'] > data[node]['downloadBandwidthMbps']: + logging.info("downloadMax of Circuit ID [" + circuit['circuitID'] + "] exceeded that of its parent node. Reducing to that of its parent node now.", stacklevel=2) + if circuit['maxUpload'] > data[node]['uploadBandwidthMbps']: + logging.info("uploadMax of Circuit ID [" + circuit['circuitID'] + "] exceeded that of its parent node. Reducing to that of its parent node now.", stacklevel=2) + parentString = hex(major) + ':' + flowIDstring = hex(major) + ':' + hex(minorByCPU[queue]) + upFlowIDstring = hex(major + stickOffset) + ':' + hex(minorByCPU[queue]) + circuit['classid'] = flowIDstring + circuit['up_classid'] = upFlowIDstring + logging.info("Added up_classid to circuit: " + circuit['up_classid']) + # Create circuit dictionary to be added to network structure, eventually output as queuingStructure.json + maxDownload = min(circuit['maxDownload'],data[node]['downloadBandwidthMbps']) + maxUpload = min(circuit['maxUpload'],data[node]['uploadBandwidthMbps']) + if override_min_down: + circuit['minDownload'] = 1 + if override_min_up: + circuit['minUpload'] = 1 + minDownload = min(circuit['minDownload'],maxDownload) + minUpload = min(circuit['minUpload'],maxUpload) + thisNewCircuitItemForNetwork = { + 'maxDownload' : maxDownload, + 'maxUpload' : maxUpload, + 'minDownload' : minDownload, + 'minUpload' : minUpload, + "circuitID": circuit['circuitID'], + "circuitName": circuit['circuitName'], + "ParentNode": circuit['ParentNode'], + "devices": circuit['devices'], + "classid": flowIDstring, + "up_classid" : upFlowIDstring, + "classMajor": hex(major), + "up_classMajor" : hex(major + stickOffset), + "classMinor": hex(minorByCPU[queue]), + "comment": circuit['comment'] + } + # Preserve optional per-circuit SQM override for downstream bakery call + if 'sqm' in circuit and circuit['sqm']: + thisNewCircuitItemForNetwork['sqm'] = circuit['sqm'] + # Generate TC commands to be executed later + thisNewCircuitItemForNetwork['devices'] = circuit['devices'] + circuitsForThisNetworkNode.append(thisNewCircuitItemForNetwork) + minorByCPU[queue] = minorByCPU[queue] + 1 + if len(circuitsForThisNetworkNode) > 0: + data[node]['circuits'] = circuitsForThisNetworkNode + + # Add padding for future circuit additions (applies to all nodes) + # This ensures space is reserved even for nodes without circuits + minorByCPU[queue] = minorByCPU[queue] + CIRCUIT_PADDING + + # Recursive call this function for children nodes attached to this node + if 'children' in data[node]: + # Sort children to ensure consistent traversal order + sorted_children = dict(sorted(data[node]['children'].items())) + # We need to keep tabs on the minor counter, because we can't have repeating class IDs. Here, we bring back the minor counter from the recursive function + minorByCPU[queue] = minorByCPU[queue] + 1 + # Check for overflow - TC uses u16 for minor class ID (max 65535) + if minorByCPU[queue] > 0xFFFF: + logging.error(f"Minor class ID overflow on CPU {queue}: {minorByCPU[queue]} exceeds TC's u16 limit (65535). Consider increasing queue count or restructuring network hierarchy.") + raise ValueError(f"Minor class ID overflow on CPU {queue}: {minorByCPU[queue]} exceeds limit of 65535") + minorByCPU = traverseNetwork(sorted_children, depth+1, major, minorByCPU, queue, nodeClassID, upNodeClassID, data[node]['downloadBandwidthMbps'], data[node]['uploadBandwidthMbps'], data[node]['downloadBandwidthMbpsMin'], data[node]['uploadBandwidthMbpsMin']) + # If top level node, increment to next queue / cpu core + if depth == 0: + if queue >= queuesAvailable: + queue = 1 + major = queue + else: + queue += 1 + major += 1 + return minorByCPU + + # If we're in binpacking mode, we need to sort the network structure a bit + bins = [] + if use_bin_packing_to_balance_cpu() and not is_network_flat(): + print("BinPacking is enabled, so we're going to sort your network.") + cpuBin = {} + weights = get_tree_weights() + # Stable tie-breaking: sort by (-weight, name) so equal weights have deterministic order + try: + weights = sorted(weights, key=lambda w: (-int(w.weight), str(w.name))) + except Exception: + pass + for w in weights: + cpuBin[w.name] = w.weight + bins = binpacking.to_constant_bin_number(cpuBin, queuesAvailable) + for x in range(queuesAvailable): + print("Bin " + str(x) + " = ", bins[x]) + binnedNetwork = {} + for cpu in range(queuesAvailable): + cpuKey = "CpueQueue" + str(cpu) + binnedNetwork[cpuKey] = { + 'downloadBandwidthMbps': generated_pn_download_mbps(), + 'uploadBandwidthMbps': generated_pn_upload_mbps(), + 'type': 'site', + 'downloadBandwidthMbpsMin': generated_pn_download_mbps(), + 'uploadBandwidthMbpsMin': generated_pn_upload_mbps(), + 'children': {}, + 'name': cpuKey + } + for node in network: + found = False + for bin in range(queuesAvailable): + if node in bins[bin]: + binnedNetwork["CpueQueue" + str(bin)]['children'][node] = network[node] + found = True + if found == False: + newQueueId = queuesAvailable-1 + binnedNetwork["CpueQueue" + str(newQueueId)]['children'][node] = network[node] + network = binnedNetwork + + # Here is the actual call to the recursive traverseNetwork() function. finalMinor is not used. + minorByCPU = traverseNetwork(network, 0, major=1, minorByCPU=minorByCPUpreloaded, queue=1, parentClassID=None, upParentClassID=None, parentMaxDL=upstream_bandwidth_capacity_download_mbps(), parentMaxUL=upstream_bandwidth_capacity_upload_mbps(), parentMinDL=upstream_bandwidth_capacity_download_mbps(), parentMinUL=upstream_bandwidth_capacity_upload_mbps()) + + bakery = Bakery() + bakery.start_batch() # Initializes the bakery transaction + linuxTCcommands = [] + devicesShaped = [] + # Root HTB Setup + # Create MQ qdisc for each CPU core / rx-tx queue. Generate commands to create corresponding HTB and leaf classes. Prepare commands for execution later + thisInterface = interface_a() + logging.info("# MQ Setup for " + thisInterface) + command = 'qdisc replace dev ' + thisInterface + ' root handle 7FFF: mq' + bakery.setup_mq(queuesAvailable, stickOffset) + linuxTCcommands.append(command) + maxBandwidth = max(upstream_bandwidth_capacity_upload_mbps(), upstream_bandwidth_capacity_download_mbps()) + calculateR2q(maxBandwidth) + for queue in range(queuesAvailable): + command = 'qdisc add dev ' + thisInterface + ' parent 7FFF:' + hex(queue+1) + ' handle ' + hex(queue+1) + ': htb default 2' + linuxTCcommands.append(command) + command = 'class add dev ' + thisInterface + ' parent ' + hex(queue+1) + ': classid ' + hex(queue+1) + ':1 htb rate '+ format_rate_for_tc(upstream_bandwidth_capacity_download_mbps()) + ' ceil ' + format_rate_for_tc(upstream_bandwidth_capacity_download_mbps()) + quantum(upstream_bandwidth_capacity_download_mbps()) + linuxTCcommands.append(command) + command = 'qdisc add dev ' + thisInterface + ' parent ' + hex(queue+1) + ':1 ' + sqm() + linuxTCcommands.append(command) + # Default class - traffic gets passed through this limiter with lower priority if it enters the top HTB without a specific class. + # Technically, that should not even happen. So don't expect much if any traffic in this default class. + # Only 1/4 of defaultClassCapacity is guaranteed (to prevent hitting ceiling of upstream), for the most part it serves as an "up to" ceiling. + command = 'class add dev ' + thisInterface + ' parent ' + hex(queue+1) + ':1 classid ' + hex(queue+1) + ':2 htb rate ' + format_rate_for_tc(round((upstream_bandwidth_capacity_download_mbps()-1)/4)) + ' ceil ' + format_rate_for_tc(upstream_bandwidth_capacity_download_mbps()-1) + ' prio 5' + quantum(upstream_bandwidth_capacity_download_mbps()) + linuxTCcommands.append(command) + command = 'qdisc add dev ' + thisInterface + ' parent ' + hex(queue+1) + ':2 ' + sqm() + linuxTCcommands.append(command) + + # Note the use of stickOffset, and not replacing the root queue if we're on a stick + thisInterface = interface_b() + logging.info("# MQ Setup for " + thisInterface) + if not on_a_stick(): + command = 'qdisc replace dev ' + thisInterface + ' root handle 7FFF: mq' + linuxTCcommands.append(command) + for queue in range(queuesAvailable): + command = 'qdisc add dev ' + thisInterface + ' parent 7FFF:' + hex(queue+stickOffset+1) + ' handle ' + hex(queue+stickOffset+1) + ': htb default 2' + linuxTCcommands.append(command) + command = 'class add dev ' + thisInterface + ' parent ' + hex(queue+stickOffset+1) + ': classid ' + hex(queue+stickOffset+1) + ':1 htb rate '+ format_rate_for_tc(upstream_bandwidth_capacity_upload_mbps()) + ' ceil ' + format_rate_for_tc(upstream_bandwidth_capacity_upload_mbps()) + quantum(upstream_bandwidth_capacity_upload_mbps()) + linuxTCcommands.append(command) + command = 'qdisc add dev ' + thisInterface + ' parent ' + hex(queue+stickOffset+1) + ':1 ' + sqm() + linuxTCcommands.append(command) + # Default class - traffic gets passed through this limiter with lower priority if it enters the top HTB without a specific class. + # Technically, that should not even happen. So don't expect much if any traffic in this default class. + # Only 1/4 of defaultClassCapacity is guarenteed (to prevent hitting ceiling of upstream), for the most part it serves as an "up to" ceiling. + command = 'class add dev ' + thisInterface + ' parent ' + hex(queue+stickOffset+1) + ':1 classid ' + hex(queue+stickOffset+1) + ':2 htb rate ' + format_rate_for_tc(round((upstream_bandwidth_capacity_upload_mbps()-1)/4)) + ' ceil ' + format_rate_for_tc(upstream_bandwidth_capacity_upload_mbps()-1) + ' prio 5' + quantum(upstream_bandwidth_capacity_upload_mbps()) + linuxTCcommands.append(command) + command = 'qdisc add dev ' + thisInterface + ' parent ' + hex(queue+stickOffset+1) + ':2 ' + sqm() + linuxTCcommands.append(command) + + + # Parse network structure. For each tier, generate commands to create corresponding HTB and leaf classes. Prepare commands for execution later + # Define lists for hash filters + print("Preparing TC commands") + def traverseNetwork(data): + + # Cake needs help handling rates lower than 5 Mbps + def sqmFixupRate(rate:int, sqm:str) -> str: + # If we aren't using cake, just return the sqm string + if not sqm.startswith("cake") or "rtt" in sqm: + return sqm + + # If we are using cake, we need to fixup the rate + # Based on: 1 MTU is 1500 bytes, or 12,000 bits. + # At 1 Mbps, (1,000 bits per ms) transmitting an MTU takes 12ms. Add 3ms for overhead, and we get 15ms. + # So 15ms divided by 5 (for 1%) multiplied by 100 yields 300ms. + # The same formula gives 180ms at 2Mbps + # 140ms at 3Mbps + # 120ms at 4Mbps + match rate: + case 1: return sqm + " rtt 300" + case 2: return sqm + " rtt 180" + case 3: return sqm + " rtt 140" + case 4: return sqm + " rtt 120" + case _: return sqm + + for node in sorted(data.keys()): + site_name = data[node]['name'] if 'name' in data[node] else node + bakery.add_site( + site_name, + data[node]['parentClassID'], + data[node]['up_parentClassID'], + int(data[node]['classMinor'], 16), + data[node]['downloadBandwidthMbpsMin'], + data[node]['uploadBandwidthMbpsMin'], + data[node]['downloadBandwidthMbps'], + data[node]['uploadBandwidthMbps'], + ) + command = 'class add dev ' + interface_a() + ' parent ' + data[node]['parentClassID'] + ' classid ' + data[node]['classMinor'] + ' htb rate '+ format_rate_for_tc(data[node]['downloadBandwidthMbpsMin']) + ' ceil '+ format_rate_for_tc(data[node]['downloadBandwidthMbps']) + ' prio 3' + quantum(data[node]['downloadBandwidthMbps']) + linuxTCcommands.append(command) + logging.info("Up ParentClassID: " + data[node]['up_parentClassID']) + logging.info("ClassMinor: " + data[node]['classMinor']) + command = 'class add dev ' + interface_b() + ' parent ' + data[node]['up_parentClassID'] + ' classid ' + data[node]['classMinor'] + ' htb rate '+ format_rate_for_tc(data[node]['uploadBandwidthMbpsMin']) + ' ceil '+ format_rate_for_tc(data[node]['uploadBandwidthMbps']) + ' prio 3' + quantum(data[node]['uploadBandwidthMbps']) + linuxTCcommands.append(command) + if 'circuits' in data[node]: + # Sort circuits by name for stable ordering + sorted_circuits = sorted(data[node]['circuits'], + key=lambda c: c.get('circuitName', c.get('circuitID', ''))) + for circuit in sorted_circuits: + # If circuit mins exceed node mins - handle low min rates of 1 to mean 10 kbps. + # Avoid changing minDownload or minUpload because they are used in queuingStructure.json, and must remain integers. + min_down = circuit['minDownload'] + min_up = circuit['minUpload'] + if node in nodes_requiring_min_squashing: + if min_down == 1: + min_down = 0.01 + if min_up == 1: + min_up = 0.01 + # Generate TC commands to be executed later + tcComment = " # CircuitID: " + circuit['circuitID'] + " DeviceIDs: " + for device in circuit['devices']: + tcComment = '' #tcComment + device['deviceID'] + ', ' + if 'devices' in circuit: + if 'comment' in circuit['devices'][0]: + tcComment = '' # tcComment + '| Comment: ' + circuit['devices'][0]['comment'] + tcComment = tcComment.replace("\n", "") + circuit_name = circuit['circuitID'] if 'circuitID' in circuit else "unknown" + # Collect all IP addresses for this circuit + ip_list = [] + for device in circuit['devices']: + if device['ipv4s']: + ip_list.extend(device['ipv4s']) + if device['ipv6s']: + ip_list.extend(device['ipv6s']) + # Concatenate IPs with comma separator + ip_addresses_str = ','.join(ip_list) + + sqm_override = circuit['sqm'] if 'sqm' in circuit else None + bakery.add_circuit( + circuit_name, + data[node]['classid'], + data[node]['up_classid'], + int(circuit['classMinor'], 16), + min_down, + min_up, + circuit['maxDownload'], + circuit['maxUpload'], + int(circuit['classMajor'], 16), + int(circuit['up_classMajor'], 16), + ip_addresses_str, + sqm_override, + ) + command = 'class add dev ' + interface_a() + ' parent ' + data[node]['classid'] + ' classid ' + circuit['classMinor'] + ' htb rate '+ format_rate_for_tc(min_down) + ' ceil '+ format_rate_for_tc(circuit['maxDownload']) + ' prio 3' + quantum(circuit['maxDownload']) + tcComment + linuxTCcommands.append(command) + # Only add CAKE / fq_codel qdisc if monitorOnlyMode is Off + if monitor_mode_only() == False: + # SQM Fixup for lower rates (and per-circuit override) + def effective_sqm_str(rate, override): + base = sqm() + if override is None or override == '': + return sqmFixupRate(rate, base) + ov = override.lower() + if ov == 'fq_codel': + return 'fq_codel' + if ov == 'cake': + cake_base = base if base.startswith('cake') else 'cake diffserv4' + return sqmFixupRate(rate, cake_base) + return sqmFixupRate(rate, base) + sqm_override = circuit['sqm'] if 'sqm' in circuit else None + useSqm = effective_sqm_str(circuit['maxDownload'], sqm_override) + command = 'qdisc add dev ' + interface_a() + ' parent ' + circuit['classMajor'] + ':' + circuit['classMinor'] + ' ' + useSqm + linuxTCcommands.append(command) + command = 'class add dev ' + interface_b() + ' parent ' + data[node]['up_classid'] + ' classid ' + circuit['classMinor'] + ' htb rate '+ format_rate_for_tc(min_up) + ' ceil '+ format_rate_for_tc(circuit['maxUpload']) + ' prio 3' + quantum(circuit['maxUpload']) + linuxTCcommands.append(command) + # Only add CAKE / fq_codel qdisc if monitorOnlyMode is Off + if monitor_mode_only() == False: + # SQM Fixup for lower rates (and per-circuit override) + sqm_override = circuit['sqm'] if 'sqm' in circuit else None + useSqm = effective_sqm_str(circuit['maxUpload'], sqm_override) + command = 'qdisc add dev ' + interface_b() + ' parent ' + circuit['up_classMajor'] + ':' + circuit['classMinor'] + ' ' + useSqm + linuxTCcommands.append(command) + pass + for device in circuit['devices']: + if device['ipv4s']: + for ipv4 in device['ipv4s']: + ipMapBatch.add_ip_mapping(str(ipv4), circuit['classid'], data[node]['cpuNum'], False) + #xdpCPUmapCommands.append('./bin/xdp_iphash_to_cpu_cmdline add --ip ' + str(ipv4) + ' --cpu ' + data[node]['cpuNum'] + ' --classid ' + circuit['classid']) + if on_a_stick(): + ipMapBatch.add_ip_mapping(str(ipv4), circuit['up_classid'], data[node]['up_cpuNum'], True) + #xdpCPUmapCommands.append('./bin/xdp_iphash_to_cpu_cmdline add --ip ' + str(ipv4) + ' --cpu ' + data[node]['up_cpuNum'] + ' --classid ' + circuit['up_classid'] + ' --upload 1') + if device['ipv6s']: + for ipv6 in device['ipv6s']: + ipMapBatch.add_ip_mapping(str(ipv6), circuit['classid'], data[node]['cpuNum'], False) + #xdpCPUmapCommands.append('./bin/xdp_iphash_to_cpu_cmdline add --ip ' + str(ipv6) + ' --cpu ' + data[node]['cpuNum'] + ' --classid ' + circuit['classid']) + if on_a_stick(): + ipMapBatch.add_ip_mapping(str(ipv6), circuit['up_classid'], data[node]['up_cpuNum'], True) + #xdpCPUmapCommands.append('./bin/xdp_iphash_to_cpu_cmdline add --ip ' + str(ipv6) + ' --cpu ' + data[node]['up_cpuNum'] + ' --classid ' + circuit['up_classid'] + ' --upload 1') + if device['deviceName'] not in devicesShaped: + devicesShaped.append(device['deviceName']) + # Recursive call this function for children nodes attached to this node + if 'children' in data[node]: + # Sort children to ensure consistent traversal order + sorted_children = dict(sorted(data[node]['children'].items())) + traverseNetwork(sorted_children) + # Here is the actual call to the recursive traverseNetwork() function. + traverseNetwork(network) + + # Save queuingStructure + queuingStructure = {} + queuingStructure['Network'] = network + queuingStructure['lastUsedClassIDCounterByCPU'] = minorByCPU + queuingStructure['generatedPNs'] = generatedPNs + with open('queuingStructure.json', 'w') as infile: + json.dump(queuingStructure, infile, indent=4) + + + # Record start time of actual filter reload + reloadStartTime = datetime.now() + + + # Clear Prior Settings + # We don't want to do this every time, with lqosd managing queues statefully. + # clearPriorSettings(interface_a(), interface_b()) + + + # Setup XDP and disable XPS regardless of whether it is first run or not (necessary to handle cases where systemctl stop was used) + xdpStartTime = datetime.now() + #if enable_actual_shell_commands(): + # The bakery will handle stale mapping cleanup; avoid clearing mappings here. + # Set up XDP-CPUMAP-TC + logging.info("# XDP Setup") + # Commented out - the daemon does this + #shell('./cpumap-pping/bin/xps_setup.sh -d ' + interfaceA + ' --default --disable') + #shell('./cpumap-pping/bin/xps_setup.sh -d ' + interfaceB + ' --default --disable') + #shell('./cpumap-pping/src/xdp_iphash_to_cpu --dev ' + interfaceA + ' --lan') + #shell('./cpumap-pping/src/xdp_iphash_to_cpu --dev ' + interfaceB + ' --wan') + #shell('./cpumap-pping/src/tc_classify --dev-egress ' + interfaceA) + #shell('./cpumap-pping/src/tc_classify --dev-egress ' + interfaceB) + xdpEndTime = datetime.now() + + + # Execute actual Linux TC commands + tcStartTime = datetime.now() + # print("Executing linux TC class/qdisc commands") + with open('linux_tc.txt', 'w') as f: + for command in linuxTCcommands: + logging.info(command) + f.write(f"{command}\n") + # if logging.DEBUG <= logging.root.level: + # # Do not --force in debug mode, so we can see any errors + # shell("/sbin/tc -b linux_tc.txt") + # else: + # shell("/sbin/tc -f -b linux_tc.txt") + bakery.commit() + tcEndTime = datetime.now() + # print("Executed " + str(len(linuxTCcommands)) + " linux TC class/qdisc commands") + + # Execute actual XDP-CPUMAP-TC filter commands + xdpFilterStartTime = datetime.now() + print("Executing XDP-CPUMAP-TC IP filter commands") + numXdpCommands = ipMapBatch.length() + if enable_actual_shell_commands(): + ipMapBatch.finish_ip_mappings() + ipMapBatch.submit() + #for command in xdpCPUmapCommands: + # logging.info(command) + # commands = command.split(' ') + # proc = subprocess.Popen(commands, stdout=subprocess.DEVNULL) + else: + ipMapBatch.log() + #for command in xdpCPUmapCommands: + # logging.info(command) + print("Executed " + str(numXdpCommands) + " XDP-CPUMAP-TC IP filter commands") + #print(xdpCPUmapCommands) + xdpFilterEndTime = datetime.now() + + + # Record end time of all reload commands + reloadEndTime = datetime.now() + + + # Recap - warn operator if devices were skipped + devicesSkipped = [] + for circuit in subscriberCircuits: + for device in circuit['devices']: + if device['deviceName'] not in devicesShaped: + devicesSkipped.append((device['deviceName'],device['deviceID'])) + if len(devicesSkipped) > 0: + warnings.warn('Some devices were not shaped. Please check to ensure they have a valid ParentNode listed in ShapedDevices.csv:', stacklevel=2) + print("Devices not shaped:") + for entry in devicesSkipped: + name, idNum = entry + print('DeviceID: ' + idNum + '\t DeviceName: ' + name) + + # Save ShapedDevices.csv as ShapedDevices.lastLoaded.csv + shutil.copyfile('ShapedDevices.csv', 'ShapedDevices.lastLoaded.csv') + + # Save for stats + with open('statsByCircuit.json', 'w') as f: + f.write(json.dumps(subscriberCircuits, indent=4)) + with open('statsByParentNode.json', 'w') as f: + f.write(json.dumps(parentNodes, indent=4)) + + + # Record time this run completed at + # filename = os.path.join(_here, 'lastRun.txt') + with open("lastRun.txt", 'w') as file: + file.write(datetime.now().strftime("%d-%b-%Y (%H:%M:%S.%f)")) + + + # Report reload time + reloadTimeSeconds = ((reloadEndTime - reloadStartTime).seconds) + (((reloadEndTime - reloadStartTime).microseconds) / 1000000) + tcTimeSeconds = ((tcEndTime - tcStartTime).seconds) + (((tcEndTime - tcStartTime).microseconds) / 1000000) + xdpSetupTimeSeconds = ((xdpEndTime - xdpStartTime).seconds) + (((xdpEndTime - xdpStartTime).microseconds) / 1000000) + xdpFilterTimeSeconds = ((xdpFilterEndTime - xdpFilterStartTime).seconds) + (((xdpFilterEndTime - xdpFilterStartTime).microseconds) / 1000000) + print("Queue and IP filter reload completed in " + "{:g}".format(round(reloadTimeSeconds,1)) + " seconds") + print("\tTC commands: \t" + "{:g}".format(round(tcTimeSeconds,1)) + " seconds") + print("\tXDP setup: \t " + "{:g}".format(round(xdpSetupTimeSeconds,1)) + " seconds") + print("\tXDP filters: \t " + "{:g}".format(round(xdpFilterTimeSeconds,4)) + " seconds") + + + # Done + print("refreshShapers completed on " + datetime.now().strftime("%d/%m/%Y %H:%M:%S")) def refreshShapersUpdateOnly(): - # Starting - print("refreshShapers starting at " + datetime.now().strftime("%d/%m/%Y %H:%M:%S")) - - - # Warn user if enableActualShellCommands is False, because that would mean no actual commands are executing - if enable_actual_shell_commands() == False: - warnings.warn("enableActualShellCommands is set to False. None of the commands below will actually be executed. Simulated run.", stacklevel=2) - - - # Files - shapedDevicesFile = 'ShapedDevices.csv' - networkJSONfile = 'network.json' - - - # Check validation - safeToRunRefresh = False - if (validateNetworkAndDevices() == True): - safeToRunRefresh = True - else: - warnings.warn("Validation failed. Will now exit.", stacklevel=2) - - if safeToRunRefresh == True: - networkChanged = False - devicesChanged = False - # Check for changes to network.json - if os.path.isfile('lastGoodConfig.json'): - with open('lastGoodConfig.json', 'r') as j: - originalNetwork = json.loads(j.read()) - with open('network.json', 'r') as j: - newestNetwork = json.loads(j.read()) - ddiff = DeepDiff(originalNetwork, newestNetwork, ignore_order=True) - if ddiff != {}: - networkChanged = True - - # Check for changes to ShapedDevices.csv - newlyUpdatedSubscriberCircuits, newlyUpdatedDictForCircuitsWithoutParentNodes = loadSubscriberCircuits('ShapedDevices.csv') - lastLoadedSubscriberCircuits, lastLoadedDictForCircuitsWithoutParentNodes = loadSubscriberCircuits('ShapedDevices.lastLoaded.csv') - - newlyUpdatedSubscriberCircuitsByID = {} - for circuit in newlyUpdatedSubscriberCircuits: - circuitid = circuit['circuitID'] - newlyUpdatedSubscriberCircuitsByID[circuitid] = circuit - - lastLoadedSubscriberCircuitsByID = {} - for circuit in lastLoadedSubscriberCircuits: - circuitid = circuit['circuitID'] - lastLoadedSubscriberCircuitsByID[circuitid] = circuit - - for circuitID, circuit in lastLoadedSubscriberCircuitsByID.items(): - if (circuitID in newlyUpdatedSubscriberCircuitsByID) and (circuitID in lastLoadedSubscriberCircuitsByID): - if newlyUpdatedSubscriberCircuitsByID[circuitID]['maxDownload'] != lastLoadedSubscriberCircuitsByID[circuitID]['maxDownload']: - devicesChanged = True - if newlyUpdatedSubscriberCircuitsByID[circuitID]['maxUpload'] != lastLoadedSubscriberCircuitsByID[circuitID]['maxUpload']: - devicesChanged = True - if newlyUpdatedSubscriberCircuitsByID[circuitID]['minDownload'] != lastLoadedSubscriberCircuitsByID[circuitID]['minDownload']: - devicesChanged = True - if newlyUpdatedSubscriberCircuitsByID[circuitID]['minUpload'] != lastLoadedSubscriberCircuitsByID[circuitID]['minUpload']: - devicesChanged = True - if newlyUpdatedSubscriberCircuitsByID[circuitID]['devices'] != lastLoadedSubscriberCircuitsByID[circuitID]['devices']: - devicesChanged = True - if newlyUpdatedSubscriberCircuitsByID[circuitID]['ParentNode'] != lastLoadedSubscriberCircuitsByID[circuitID]['ParentNode']: - devicesChanged = True - else: - devicesChanged = True - for circuitID, circuit in newlyUpdatedSubscriberCircuitsByID.items(): - if (circuitID not in lastLoadedSubscriberCircuitsByID): - devicesChanged = True - - - if devicesChanged or networkChanged: - print('Observed changes to ShapedDevices.csv or network.json. Applying full reload now') - refreshShapers() - else: - print('Observed no changes to ShapedDevices.csv or network.json. Leaving queues as is.') - - # Done - print("refreshShapersUpdateOnly completed on " + datetime.now().strftime("%d/%m/%Y %H:%M:%S")) + # Starting + print("refreshShapers starting at " + datetime.now().strftime("%d/%m/%Y %H:%M:%S")) + + + # Warn user if enableActualShellCommands is False, because that would mean no actual commands are executing + if enable_actual_shell_commands() == False: + warnings.warn("enableActualShellCommands is set to False. None of the commands below will actually be executed. Simulated run.", stacklevel=2) + + + # Files + shapedDevicesFile = 'ShapedDevices.csv' + networkJSONfile = 'network.json' + + + # Check validation + safeToRunRefresh = False + if (validateNetworkAndDevices() == True): + safeToRunRefresh = True + else: + warnings.warn("Validation failed. Will now exit.", stacklevel=2) + + if safeToRunRefresh == True: + networkChanged = False + devicesChanged = False + # Check for changes to network.json + if os.path.isfile('lastGoodConfig.json'): + with open('lastGoodConfig.json', 'r') as j: + originalNetwork = json.loads(j.read()) + with open('network.json', 'r') as j: + newestNetwork = json.loads(j.read()) + ddiff = DeepDiff(originalNetwork, newestNetwork, ignore_order=True) + if ddiff != {}: + networkChanged = True + + # Check for changes to ShapedDevices.csv + newlyUpdatedSubscriberCircuits, newlyUpdatedDictForCircuitsWithoutParentNodes = loadSubscriberCircuits('ShapedDevices.csv') + lastLoadedSubscriberCircuits, lastLoadedDictForCircuitsWithoutParentNodes = loadSubscriberCircuits('ShapedDevices.lastLoaded.csv') + + newlyUpdatedSubscriberCircuitsByID = {} + for circuit in newlyUpdatedSubscriberCircuits: + circuitid = circuit['circuitID'] + newlyUpdatedSubscriberCircuitsByID[circuitid] = circuit + + lastLoadedSubscriberCircuitsByID = {} + for circuit in lastLoadedSubscriberCircuits: + circuitid = circuit['circuitID'] + lastLoadedSubscriberCircuitsByID[circuitid] = circuit + + for circuitID, circuit in lastLoadedSubscriberCircuitsByID.items(): + if (circuitID in newlyUpdatedSubscriberCircuitsByID) and (circuitID in lastLoadedSubscriberCircuitsByID): + if newlyUpdatedSubscriberCircuitsByID[circuitID]['maxDownload'] != lastLoadedSubscriberCircuitsByID[circuitID]['maxDownload']: + devicesChanged = True + if newlyUpdatedSubscriberCircuitsByID[circuitID]['maxUpload'] != lastLoadedSubscriberCircuitsByID[circuitID]['maxUpload']: + devicesChanged = True + if newlyUpdatedSubscriberCircuitsByID[circuitID]['minDownload'] != lastLoadedSubscriberCircuitsByID[circuitID]['minDownload']: + devicesChanged = True + if newlyUpdatedSubscriberCircuitsByID[circuitID]['minUpload'] != lastLoadedSubscriberCircuitsByID[circuitID]['minUpload']: + devicesChanged = True + if newlyUpdatedSubscriberCircuitsByID[circuitID]['devices'] != lastLoadedSubscriberCircuitsByID[circuitID]['devices']: + devicesChanged = True + if newlyUpdatedSubscriberCircuitsByID[circuitID]['ParentNode'] != lastLoadedSubscriberCircuitsByID[circuitID]['ParentNode']: + devicesChanged = True + else: + devicesChanged = True + for circuitID, circuit in newlyUpdatedSubscriberCircuitsByID.items(): + if (circuitID not in lastLoadedSubscriberCircuitsByID): + devicesChanged = True + + + if devicesChanged or networkChanged: + print('Observed changes to ShapedDevices.csv or network.json. Applying full reload now') + refreshShapers() + else: + print('Observed no changes to ShapedDevices.csv or network.json. Leaving queues as is.') + + # Done + print("refreshShapersUpdateOnly completed on " + datetime.now().strftime("%d/%m/%Y %H:%M:%S")) if __name__ == '__main__': - # Check that the host lqosd is running - if is_lqosd_alive(): - print("lqosd is running") - else: - print("ERROR: lqosd is not running. Aborting") - os._exit(-1) - - # Check that the configuration file is usable - if check_config(): - print("Configuration from /etc/lqos.conf is usable") - else: - print("ERROR: Unable to load configuration from /etc/lqos.conf") - os.exit(-1) - - # Check that we aren't running LibreQoS.py more than once at a time - if is_libre_already_running(): - print("LibreQoS.py is already running in another process. Aborting.") - os._exit(-1) - - # We've got this far, so create a lock file - create_lock_file() - - parser = argparse.ArgumentParser() - parser.add_argument( - '-d', '--debug', - help="Print lots of debugging statements", - action="store_const", dest="loglevel", const=logging.DEBUG, - default=logging.WARNING, - ) - parser.add_argument( - '-v', '--verbose', - help="Be verbose", - action="store_const", dest="loglevel", const=logging.INFO, - ) - parser.add_argument( - '--updateonly', - help="Only update to reflect changes in ShapedDevices.csv (partial reload)", - action=argparse.BooleanOptionalAction, - ) - parser.add_argument( - '--validate', - help="Just validate network.json and ShapedDevices.csv", - action=argparse.BooleanOptionalAction, - ) - parser.add_argument( - '--clearrules', - help="Clear ip filters, qdiscs, and xdp setup if any", - action=argparse.BooleanOptionalAction, - ) - args = parser.parse_args() - logging.basicConfig(level=args.loglevel) - - if args.validate: - status = validateNetworkAndDevices() - elif args.clearrules: - tearDown(interface_a(), interface_b()) - elif args.updateonly: - # Single-interface updates don't work at all right now. - if on_a_stick(): - print("--updateonly is not supported for single-interface configurations") - os.exit(-1) - refreshShapersUpdateOnly() - else: - # Refresh and/or set up queues - refreshShapers() - - # Free the lock file - free_lock_file() + # Check that the host lqosd is running + if is_lqosd_alive(): + print("lqosd is running") + else: + print("ERROR: lqosd is not running. Aborting") + os._exit(-1) + + # Check that the configuration file is usable + if check_config(): + print("Configuration from /etc/lqos.conf is usable") + else: + print("ERROR: Unable to load configuration from /etc/lqos.conf") + os.exit(-1) + + # Check that we aren't running LibreQoS.py more than once at a time + if is_libre_already_running(): + print("LibreQoS.py is already running in another process. Aborting.") + os._exit(-1) + + # We've got this far, so create a lock file + create_lock_file() + + parser = argparse.ArgumentParser() + parser.add_argument( + '-d', '--debug', + help="Print lots of debugging statements", + action="store_const", dest="loglevel", const=logging.DEBUG, + default=logging.WARNING, + ) + parser.add_argument( + '-v', '--verbose', + help="Be verbose", + action="store_const", dest="loglevel", const=logging.INFO, + ) + parser.add_argument( + '--updateonly', + help="Only update to reflect changes in ShapedDevices.csv (partial reload)", + action=argparse.BooleanOptionalAction, + ) + parser.add_argument( + '--validate', + help="Just validate network.json and ShapedDevices.csv", + action=argparse.BooleanOptionalAction, + ) + parser.add_argument( + '--clearrules', + help="Clear ip filters, qdiscs, and xdp setup if any", + action=argparse.BooleanOptionalAction, + ) + args = parser.parse_args() + logging.basicConfig(level=args.loglevel) + + if args.validate: + status = validateNetworkAndDevices() + elif args.clearrules: + tearDown(interface_a(), interface_b()) + elif args.updateonly: + # Single-interface updates don't work at all right now. + if on_a_stick(): + print("--updateonly is not supported for single-interface configurations") + os.exit(-1) + refreshShapersUpdateOnly() + else: + # Refresh and/or set up queues + refreshShapers() + + # Free the lock file + free_lock_file() diff --git a/src/ShapedDevices.example.csv b/src/ShapedDevices.example.csv index c00eaa36..6ef04f3c 100644 --- a/src/ShapedDevices.example.csv +++ b/src/ShapedDevices.example.csv @@ -16,15 +16,15 @@ # # Backward Compatibility: Existing integer rates continue to work unchanged. # -Circuit ID,Circuit Name,Device ID,Device Name,Parent Node,MAC,IPv4,IPv6,Download Min Mbps,Upload Min Mbps,Download Max Mbps,Upload Max Mbps,Comment -1,"968 Circle St., Gurnee, IL 60031",1,Device 1,AP_A,,"100.64.0.1, 100.64.0.14",fdd7:b724:0:100::/56,1,1,155,20,Standard integer rates -2,"31 Marconi Street, Lake In The Hills, IL 60156",2,Device 2,AP_A,,100.64.0.2,fdd7:b724:0:200::/56,0.5,0.5,2.5,1.0,Fractional rate example - small plan -3,"255 NW. Newport Ave., Jamestown, NY 14701",3,Device 3,AP_9,,100.64.0.3,fdd7:b724:0:300::/56,1.25,0.75,10.5,5.25,Fractional rate example - medium plan -4,"8493 Campfire Street, Peabody, MA 01960",4,Device 4,AP_9,,100.64.0.4,fdd7:b724:0:400::/56,25.5,12.5,100.5,50.25,Fractional rate example - large plan -2794,"6 Littleton Drive, Ringgold, GA 30736",5,Device 5,AP_11,,100.64.0.5,fdd7:b724:0:500::/56,1,1,105,18,Standard integer rates -2794,"6 Littleton Drive, Ringgold, GA 30736",6,Device 6,AP_11,,100.64.0.6,fdd7:b724:0:600::/56,1,1,105,18,Standard integer rates -5,"93 Oklahoma Ave., Parsippany, NJ 07054",7,Device 7,AP_1,,100.64.0.7,fdd7:b724:0:700::/56,2.0,2.0,25.0,10.0,Mixed decimal rates -6,"74 Bishop Ave., Bakersfield, CA 93306",8,Device 8,AP_1,,100.64.0.8,fdd7:b724:0:800::/56,1,1,105,18,Standard integer rates -7,"9598 Peg Shop Drive, Lutherville Timonium, MD 21093",9,Device 9,AP_7,,100.64.0.9,fdd7:b724:0:900::/56,1,1,105,18,Standard integer rates -8,"115 Gartner Rd., Gettysburg, PA 17325",10,Device 10,AP_7,,100.64.0.10,fdd7:b724:0:a00::/56,0.1,0.1,1.5,1.0,Minimum rate example -9,"525 Birchpond St., Romulus, MI 48174",11,Device 11,Site_1,,100.64.0.11,fdd7:b724:0:b00::/56,1,1,105,18,Standard integer rates +Circuit ID,Circuit Name,Device ID,Device Name,Parent Node,MAC,IPv4,IPv6,Download Min Mbps,Upload Min Mbps,Download Max Mbps,Upload Max Mbps,Comment,sqm +1,"968 Circle St., Gurnee, IL 60031",1,Device 1,AP_A,,"100.64.0.1, 100.64.0.14",fdd7:b724:0:100::/56,1,1,155,20,Standard integer rates, +2,"31 Marconi Street, Lake In The Hills, IL 60156",2,Device 2,AP_A,,100.64.0.2,fdd7:b724:0:200::/56,0.5,0.5,2.5,1.0,Fractional rate example - small plan,fq_codel +3,"255 NW. Newport Ave., Jamestown, NY 14701",3,Device 3,AP_9,,100.64.0.3,fdd7:b724:0:300::/56,1.25,0.75,10.5,5.25,Fractional rate example - medium plan, +4,"8493 Campfire Street, Peabody, MA 01960",4,Device 4,AP_9,,100.64.0.4,fdd7:b724:0:400::/56,25.5,12.5,100.5,50.25,Fractional rate example - large plan,cake +2794,"6 Littleton Drive, Ringgold, GA 30736",5,Device 5,AP_11,,100.64.0.5,fdd7:b724:0:500::/56,1,1,105,18,Standard integer rates, +2794,"6 Littleton Drive, Ringgold, GA 30736",6,Device 6,AP_11,,100.64.0.6,fdd7:b724:0:600::/56,1,1,105,18,Standard integer rates, +5,"93 Oklahoma Ave., Parsippany, NJ 07054",7,Device 7,AP_1,,100.64.0.7,fdd7:b724:0:700::/56,2.0,2.0,25.0,10.0,Mixed decimal rates, +6,"74 Bishop Ave., Bakersfield, CA 93306",8,Device 8,AP_1,,100.64.0.8,fdd7:b724:0:800::/56,1,1,105,18,Standard integer rates, +7,"9598 Peg Shop Drive, Lutherville Timonium, MD 21093",9,Device 9,AP_7,,100.64.0.9,fdd7:b724:0:900::/56,1,1,105,18,Standard integer rates, +8,"115 Gartner Rd., Gettysburg, PA 17325",10,Device 10,AP_7,,100.64.0.10,fdd7:b724:0:a00::/56,0.1,0.1,1.5,1.0,Minimum rate example, +9,"525 Birchpond St., Romulus, MI 48174",11,Device 11,Site_1,,100.64.0.11,fdd7:b724:0:b00::/56,1,1,105,18,Standard integer rates, diff --git a/src/rust/lqos_bakery/src/commands.rs b/src/rust/lqos_bakery/src/commands.rs index e66e62ff..3e4414a7 100644 --- a/src/rust/lqos_bakery/src/commands.rs +++ b/src/rust/lqos_bakery/src/commands.rs @@ -1,13 +1,14 @@ use crate::MQ_CREATED; use crate::queue_math::{ format_rate_for_tc, format_rate_for_tc_f32, quantum, r2q, sqm_as_vec, sqm_rate_fixup, + sqm_tokens_for, }; use allocative::Allocative; use lqos_bus::TcHandle; use lqos_config::LazyQueueMode; use std::collections::HashSet; use std::sync::Arc; -use tracing::{info, warn}; +use tracing::{info, warn, debug}; #[derive(Debug, Clone, Copy, Allocative)] struct AddSiteParams { @@ -21,7 +22,7 @@ struct AddSiteParams { upload_bandwidth_max: f32, } -#[derive(Debug, Clone, Copy, Allocative)] +#[derive(Debug, Clone, Allocative)] struct AddCircuitParams { circuit_hash: i64, parent_class_id: TcHandle, @@ -33,6 +34,8 @@ struct AddCircuitParams { upload_bandwidth_max: f32, class_major: u16, up_class_major: u16, + // Optional per-circuit SQM override: "cake" or "fq_codel" + sqm_override: Option, } /// Execution Mode @@ -46,7 +49,7 @@ pub enum ExecutionMode { /// List of commands that the Bakery system can handle. #[derive(Debug, Clone, Allocative)] -pub enum BakeryCommands { + pub enum BakeryCommands { /// Notification that the bus socket is ready; bakery can seed mappings BusReady, /// Add or update an IP mapping (mirrors `MapIpToFlow` from the bus) @@ -149,6 +152,8 @@ pub enum BakeryCommands { up_class_major: u16, /// Concatenated list of all IPs for this circuit. ip_addresses: String, // Concatenated list of all IPs for this circuit + /// Optional per-circuit SQM override: "cake" or "fq_codel" + sqm_override: Option, }, /// Change a specific HTB class rate on-the-fly; optionally dry-run. StormGuardAdjustment { @@ -223,6 +228,7 @@ impl BakeryCommands { class_major, up_class_major, ip_addresses: _, + sqm_override, } => Self::add_circuit( execution_mode, config, @@ -237,6 +243,7 @@ impl BakeryCommands { upload_bandwidth_max: *upload_bandwidth_max, class_major: *class_major, up_class_major: *up_class_major, + sqm_override: sqm_override.clone(), }, ), _ => None, @@ -582,6 +589,17 @@ impl BakeryCommands { config: &Arc, params: AddCircuitParams, ) -> Option>> { + if let Some(ref s) = params.sqm_override { + if s.eq_ignore_ascii_case("fq_codel") { + debug!( + "Bakery: building AddCircuit with fq_codel override (circuit_hash={}, class_minor=0x{:x}, class_major=0x{:x}, up_class_major=0x{:x})", + params.circuit_hash, + params.class_minor, + params.class_major, + params.up_class_major + ); + } + } let do_htb; let do_sqm; @@ -674,7 +692,11 @@ impl BakeryCommands { "parent".to_string(), format!("0x{:x}:0x{:x}", params.class_major, params.class_minor), ]; - sqm_command.extend(sqm_rate_fixup(params.download_bandwidth_max, config)); + sqm_command.extend(sqm_tokens_for( + params.download_bandwidth_max, + config, + ¶ms.sqm_override, + )); result.push(sqm_command); } @@ -712,7 +734,11 @@ impl BakeryCommands { "parent".to_string(), format!("0x{:x}:0x{:x}", params.up_class_major, params.class_minor), ]; - sqm_command.extend(sqm_rate_fixup(params.upload_bandwidth_max, config)); + sqm_command.extend(sqm_tokens_for( + params.upload_bandwidth_max, + config, + ¶ms.sqm_override, + )); result.push(sqm_command); } diff --git a/src/rust/lqos_bakery/src/diff/circuits.rs b/src/rust/lqos_bakery/src/diff/circuits.rs index 8400cccf..c72c90ae 100644 --- a/src/rust/lqos_bakery/src/diff/circuits.rs +++ b/src/rust/lqos_bakery/src/diff/circuits.rs @@ -102,6 +102,7 @@ fn classify_circuit_change(a: &BakeryCommands, b: &BakeryCommands) -> CircuitCha class_major, up_class_major, ip_addresses, + sqm_override, .. } = a else { @@ -119,6 +120,7 @@ fn classify_circuit_change(a: &BakeryCommands, b: &BakeryCommands) -> CircuitCha class_major: other_class_major, up_class_major: other_up_class_major, ip_addresses: other_ip_addresses, + sqm_override: other_sqm_override, .. } = b else { @@ -139,7 +141,8 @@ fn classify_circuit_change(a: &BakeryCommands, b: &BakeryCommands) -> CircuitCha let speed = download_bandwidth_min != other_download_bandwidth_min || upload_bandwidth_min != other_upload_bandwidth_min || download_bandwidth_max != other_download_bandwidth_max - || upload_bandwidth_max != other_upload_bandwidth_max; + || upload_bandwidth_max != other_upload_bandwidth_max + || sqm_override != other_sqm_override; // treat SQM override changes as speed-level changes let ip = ip_addresses != other_ip_addresses; diff --git a/src/rust/lqos_bakery/src/lib.rs b/src/rust/lqos_bakery/src/lib.rs index be1294c1..bca43ce3 100644 --- a/src/rust/lqos_bakery/src/lib.rs +++ b/src/rust/lqos_bakery/src/lib.rs @@ -77,6 +77,8 @@ struct Migration { final_minor: u16, // IP list for remapping ips: Vec, + // Per-circuit SQM override ("cake" or "fq_codel"), if any + sqm_override: Option, stage: MigrationStage, } @@ -166,6 +168,7 @@ fn build_temp_add_cmd( class_major, up_class_major, ip_addresses, + sqm_override, .. } = base { @@ -181,6 +184,7 @@ fn build_temp_add_cmd( class_major: *class_major, up_class_major: *up_class_major, ip_addresses: ip_addresses.clone(), + sqm_override: sqm_override.clone(), }) } else { None @@ -538,6 +542,7 @@ fn bakery_main(rx: Receiver, tx: Sender) { class_major: mig.class_major, up_class_major: mig.up_class_major, ip_addresses: "".to_string(), + sqm_override: mig.sqm_override.clone(), }, mig.shadow_minor, mig.old_down_min, @@ -604,6 +609,7 @@ fn bakery_main(rx: Receiver, tx: Sender) { class_major: mig.class_major, up_class_major: mig.up_class_major, ip_addresses: "".to_string(), + sqm_override: mig.sqm_override.clone(), }, mig.old_minor, mig.old_down_min, @@ -678,6 +684,7 @@ fn bakery_main(rx: Receiver, tx: Sender) { class_major: mig.class_major, up_class_major: mig.up_class_major, ip_addresses: "".to_string(), + sqm_override: mig.sqm_override.clone(), }, mig.shadow_minor, mig.old_down_min, @@ -922,6 +929,7 @@ fn handle_commit_batch( class_major, up_class_major, ip_addresses, + sqm_override, } = cmd.as_ref() { let was_activated = live_circuits.contains_key(circuit_hash); @@ -956,6 +964,7 @@ fn handle_commit_batch( shadow_minor, final_minor: *class_minor, ips: parse_ip_list(ip_addresses), + sqm_override: sqm_override.clone(), stage: MigrationStage::PrepareShadow, }; migrations.insert(*circuit_hash, mig); diff --git a/src/rust/lqos_bakery/src/queue_math.rs b/src/rust/lqos_bakery/src/queue_math.rs index 5eecd2d0..fec5815c 100644 --- a/src/rust/lqos_bakery/src/queue_math.rs +++ b/src/rust/lqos_bakery/src/queue_math.rs @@ -107,3 +107,47 @@ pub(crate) fn sqm_rate_fixup(rate: f32, config: &Arc) -> Ve } result } + +/// Build SQM token vector for a circuit given an optional per-circuit override. +/// - None: use config default with cake low-rate RTT fixups (existing behavior) +/// - Some("fq_codel"): use fq_codel +/// - Some("cake"): use config default if it starts with "cake", otherwise fallback to +/// "cake diffserv4"; then apply low-rate RTT fixups. +pub(crate) fn sqm_tokens_for( + rate: f32, + config: &Arc, + override_opt: &Option, +) -> Vec { + match override_opt.as_deref() { + None => sqm_rate_fixup(rate, config), + Some("fq_codel") => vec!["fq_codel".to_string()], + Some("cake") => { + let default = &config.queues.default_sqm; + let mut base = if default.starts_with("cake") { + sqm_as_vec(config) + } else { + vec!["cake".to_string(), "diffserv4".to_string()] + }; + // If RTT already specified, leave as-is; otherwise apply low-rate fixups + let has_rtt = base.iter().any(|s| s == "rtt"); + if !has_rtt { + // Mirror the thresholds used in sqm_rate_fixup + if rate <= 1.0 { + base.push("rtt".to_string()); + base.push("300".to_string()); + } else if rate <= 2.0 { + base.push("rtt".to_string()); + base.push("180".to_string()); + } else if rate <= 3.0 { + base.push("rtt".to_string()); + base.push("140".to_string()); + } else if rate <= 4.0 { + base.push("rtt".to_string()); + base.push("120".to_string()); + } + } + base + } + Some(_) => sqm_rate_fixup(rate, config), // defensive fallback + } +} diff --git a/src/rust/lqos_bus/src/bus/request.rs b/src/rust/lqos_bus/src/bus/request.rs index 962bf614..c4d96641 100644 --- a/src/rust/lqos_bus/src/bus/request.rs +++ b/src/rust/lqos_bus/src/bus/request.rs @@ -284,6 +284,8 @@ pub enum BusRequest { up_class_major: u16, /// Concatenated list of IP addresses for the circuit ip_addresses: String, + /// Optional per-circuit SQM override: "cake" or "fq_codel" + sqm_override: Option, }, /// Get current Stormguard statistics diff --git a/src/rust/lqos_config/src/shaped_devices/mod.rs b/src/rust/lqos_config/src/shaped_devices/mod.rs index dc8301d8..56f3d733 100644 --- a/src/rust/lqos_config/src/shaped_devices/mod.rs +++ b/src/rust/lqos_config/src/shaped_devices/mod.rs @@ -133,6 +133,9 @@ impl ConfigShapedDevices { let mut reader = ReaderBuilder::new() .comment(Some(b'#')) .trim(csv::Trim::All) + // Allow optional trailing fields like per-circuit SQM override + // without forcing all rows to match header length. + .flexible(true) .from_reader(utf8_bytes.as_slice()); // Example: StringRecord(["1", "968 Circle St., Gurnee, IL 60031", "1", "Device 1", "", "", "192.168.101.2", "", "25", "5", "10000", "10000", ""]) diff --git a/src/rust/lqos_config/src/shaped_devices/shaped_device.rs b/src/rust/lqos_config/src/shaped_devices/shaped_device.rs index 6df79936..7ab00720 100644 --- a/src/rust/lqos_config/src/shaped_devices/shaped_device.rs +++ b/src/rust/lqos_config/src/shaped_devices/shaped_device.rs @@ -57,6 +57,12 @@ pub struct ShapedDevice { /// Generic comments field, does nothing. pub comment: String, + /// Optional per-circuit SQM override token. Strictly limited to + /// "cake" or "fq_codel" when present. Empty or missing means + /// "use global default". + #[serde(skip_serializing_if = "Option::is_none")] + pub sqm_override: Option, + /// Hash of the circuit ID, used for internal lookups. #[serde(skip)] pub circuit_hash: i64, @@ -75,7 +81,7 @@ impl ShapedDevice { /// /// This function parses a CSV record containing device configuration data and constructs /// a `ShapedDevice` with all necessary fields populated. The CSV record must contain - /// exactly 13 fields in the following order: + /// exactly 13 fields in the following order (optionally a 14th `sqm` field may be present): /// /// 1. Circuit ID /// 2. Circuit Name @@ -90,6 +96,7 @@ impl ShapedDevice { /// 11. Download Max Mbps /// 12. Upload Max Mbps /// 13. Comment + /// 14. sqm (optional; allowed values: "cake" or "fq_codel") /// /// # Arguments /// @@ -106,7 +113,8 @@ impl ShapedDevice { /// * The bandwidth values (min/max upload/download) cannot be parsed as unsigned integers /// * The CSV record doesn't contain the expected number of fields pub fn from_csv(record: &StringRecord) -> Result { - Ok(Self { + // Parse mandatory fields (first 13 entries) + let mut device = Self { circuit_id: record[0].to_string(), circuit_name: record[1].to_string(), device_id: record[2].to_string(), @@ -164,10 +172,28 @@ impl ShapedDevice { rate }, comment: record[12].to_string(), + sqm_override: None, circuit_hash: hash_to_i64(&record[0]), device_hash: hash_to_i64(&record[2]), parent_hash: hash_to_i64(&record[4]), - }) + }; + + // Optional 14th field: per-circuit SQM override token + if record.len() >= 14 { + let token = record[13].trim().to_lowercase(); + if !token.is_empty() { + match token.as_str() { + "cake" | "fq_codel" => device.sqm_override = Some(token), + other => { + return Err(ShapedDevicesError::CsvEntryParseError(format!( + "Invalid sqm override '{other}'. Allowed values: 'cake' or 'fq_codel'" + ))); + } + } + } + } + + Ok(device) } pub(crate) fn parse_cidr_v4(address: &str) -> Result<(Ipv4Addr, u32), ShapedDevicesError> { diff --git a/src/rust/lqos_python/src/lib.rs b/src/rust/lqos_python/src/lib.rs index 85f7cba7..308dd597 100644 --- a/src/rust/lqos_python/src/lib.rs +++ b/src/rust/lqos_python/src/lib.rs @@ -944,6 +944,7 @@ enum BakeryCommands { class_major: u16, up_class_major: u16, ip_addresses: String, + sqm_override: Option, }, } @@ -1028,6 +1029,7 @@ impl Bakery { class_major, up_class_major, ip_addresses, + sqm_override, } => { let command = BusRequest::BakeryAddCircuit { circuit_hash: *circuit_hash, @@ -1041,6 +1043,7 @@ impl Bakery { class_major: *class_major, up_class_major: *up_class_major, ip_addresses: ip_addresses.clone(), + sqm_override: sqm_override.clone(), }; requests.push(command); } @@ -1107,6 +1110,7 @@ impl Bakery { class_major: u16, up_class_major: u16, ip_addresses: String, + sqm_override: Option, ) -> PyResult<()> { let circuit_hash = lqos_utils::hash_to_i64(&circuit_name); //println!("Name: {circuit_name}, hash: {circuit_hash}"); @@ -1122,6 +1126,7 @@ impl Bakery { class_major, up_class_major, ip_addresses, + sqm_override, }; self.queue.push(command); Ok(()) diff --git a/src/rust/lqosd/src/main.rs b/src/rust/lqosd/src/main.rs index 9f5ffbc9..70255c70 100644 --- a/src/rust/lqosd/src/main.rs +++ b/src/rust/lqosd/src/main.rs @@ -574,7 +574,19 @@ fn handle_bus_requests(requests: &[BusRequest], responses: &mut Vec class_major, up_class_major, ip_addresses, + sqm_override, } => { + if let Some(s) = sqm_override.as_ref() { + if s.eq_ignore_ascii_case("fq_codel") { + tracing::info!( + "lqosd: Received BakeryAddCircuit with fq_codel override for circuit_hash={} (parent_class_id={}, up_parent_class_id={}, class_minor=0x{:x})", + circuit_hash, + parent_class_id.as_tc_string(), + up_parent_class_id.as_tc_string(), + class_minor + ); + } + } if let Some(sender) = lqos_bakery::BAKERY_SENDER.get() { let sender = sender.clone(); let _ = sender.send(lqos_bakery::BakeryCommands::AddCircuit { @@ -589,6 +601,7 @@ fn handle_bus_requests(requests: &[BusRequest], responses: &mut Vec class_major: class_major.clone(), up_class_major: up_class_major.clone(), ip_addresses: ip_addresses.clone(), + sqm_override: sqm_override.clone(), }); BusResponse::Ack } else { -- knotmirror 0.0.1 From 8e2b4eb6094ec2382df02e01fbed8a71e94be48a Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Fri, 31 Oct 2025 08:48:31 -0500 Subject: [PATCH 36/61] Feat: Track fq_codel stats, and display them in the web ui. --- src/rust/lqos_bus/src/bus/queue_data.rs | 4 ++ src/rust/lqos_queue_tracker/src/queue_diff.rs | 34 ++++++++++++- .../lqos_queue_tracker/src/queue_store.rs | 37 ++++++++++++-- .../src/queue_types/tc_fq_codel.rs | 48 +++++++++---------- .../src/node_manager/js_build/src/circuit.js | 17 ++++++- .../src/node_manager/static2/circuit.html | 2 +- 6 files changed, 111 insertions(+), 31 deletions(-) diff --git a/src/rust/lqos_bus/src/bus/queue_data.rs b/src/rust/lqos_bus/src/bus/queue_data.rs index 34014321..7c0fd683 100644 --- a/src/rust/lqos_bus/src/bus/queue_data.rs +++ b/src/rust/lqos_bus/src/bus/queue_data.rs @@ -15,6 +15,10 @@ pub struct QueueStoreTransit { //pub prev_upload: Option, pub current_download: CakeTransit, pub current_upload: CakeTransit, + /// Queue kind for downlink (e.g., "cake" or "fq_codel") + pub kind_down: String, + /// Queue kind for uplink (e.g., "cake" or "fq_codel") + pub kind_up: String, } #[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default, Allocative)] diff --git a/src/rust/lqos_queue_tracker/src/queue_diff.rs b/src/rust/lqos_queue_tracker/src/queue_diff.rs index 68d56a74..8e9c96a5 100644 --- a/src/rust/lqos_queue_tracker/src/queue_diff.rs +++ b/src/rust/lqos_queue_tracker/src/queue_diff.rs @@ -8,7 +8,7 @@ pub enum QueueDiff { None, // Mq, // Htb, - // FqCodel, + FqCodel(FqCodelDiff), Cake(CakeDiff), // ClsAct, } @@ -18,6 +18,13 @@ pub(crate) fn make_queue_diff( current: &QueueType, ) -> Result { match previous { + QueueType::FqCodel(..) => match current { + QueueType::FqCodel(..) => Ok(fq_codel_diff(previous, current)?), + _ => { + error!("Queue diffs are not implemented for FqCodel to {:?}", current); + Err(QueueDiffError::NotImplemented) + } + }, QueueType::Cake(..) => match current { QueueType::Cake(..) => Ok(cake_diff(previous, current)?), _ => { @@ -81,3 +88,28 @@ pub enum QueueDiffError { #[error("Not implemented")] NotImplemented, } +#[derive(Serialize, Clone, Debug)] +pub struct FqCodelDiff { + pub bytes: u64, + pub packets: u32, + pub backlog: u32, + pub flows: u16, + pub ddrops: u32, +} + +fn fq_codel_diff(previous: &QueueType, current: &QueueType) -> Result { + if let QueueType::FqCodel(prev) = previous { + if let QueueType::FqCodel(new) = current { + // Delta counters; backlog and flows are instantaneous + let diff = FqCodelDiff { + bytes: new.bytes.saturating_sub(prev.bytes), + packets: new.packets.saturating_sub(prev.packets), + backlog: new.backlog, + flows: new.options.flows, + ddrops: new.drop_overlimit.saturating_sub(prev.drop_overlimit), + }; + return Ok(QueueDiff::FqCodel(diff)); + } + } + Err(QueueDiffError::NotImplemented) +} diff --git a/src/rust/lqos_queue_tracker/src/queue_store.rs b/src/rust/lqos_queue_tracker/src/queue_store.rs index 7bfe9517..6c7e2c46 100644 --- a/src/rust/lqos_queue_tracker/src/queue_store.rs +++ b/src/rust/lqos_queue_tracker/src/queue_store.rs @@ -59,6 +59,17 @@ impl QueueStore { #[allow(clippy::from_over_into)] impl Into for QueueStore { fn into(self) -> QueueStoreTransit { + // Determine queue kinds for display + let kind_down = match &self.current_download { + QueueType::Cake(_) => "cake", + QueueType::FqCodel(_) => "fq_codel", + _ => "", + }; + let kind_up = match &self.current_upload { + QueueType::Cake(_) => "cake", + QueueType::FqCodel(_) => "fq_codel", + _ => "", + }; QueueStoreTransit { history: self .history @@ -71,6 +82,8 @@ impl Into for QueueStore { //prev_upload: self.prev_upload.map(|u| u.into()), current_download: self.current_download.into(), current_upload: self.current_upload.into(), + kind_down: kind_down.to_string(), + kind_up: kind_up.to_string(), } } } @@ -78,15 +91,31 @@ impl Into for QueueStore { #[allow(clippy::from_over_into)] impl Into for QueueDiff { fn into(self) -> CakeDiffTransit { - if let QueueDiff::Cake(c) = &self { - CakeDiffTransit { + match &self { + QueueDiff::Cake(c) => CakeDiffTransit { bytes: c.bytes, packets: c.packets, qlen: c.qlen, tins: c.tins.iter().cloned().map(|t| t.into()).collect(), + }, + QueueDiff::FqCodel(c) => { + // Map fq_codel stats into a Cake-like transit so the UI can render. + // Pad to 4 tins to match typical diffserv4 rendering assumptions in the UI. + let mut tins = Vec::with_capacity(4); + tins.push(CakeDiffTinTransit { + sent_bytes: c.bytes, + backlog_bytes: c.backlog, + drops: c.ddrops, + marks: 0, + base_delay_us: 0, + }); + // Add three zeroed tins for UI expectations + for _ in 0..3 { + tins.push(CakeDiffTinTransit::default()); + } + CakeDiffTransit { bytes: c.bytes, packets: c.packets, qlen: c.backlog, tins } } - } else { - CakeDiffTransit::default() + _ => CakeDiffTransit::default(), } } } diff --git a/src/rust/lqos_queue_tracker/src/queue_types/tc_fq_codel.rs b/src/rust/lqos_queue_tracker/src/queue_types/tc_fq_codel.rs index e6bc6cc8..f44cdca7 100644 --- a/src/rust/lqos_queue_tracker/src/queue_types/tc_fq_codel.rs +++ b/src/rust/lqos_queue_tracker/src/queue_types/tc_fq_codel.rs @@ -14,34 +14,34 @@ use tracing::info; #[derive(Default, Clone, Debug, Serialize)] pub struct TcFqCodel { - handle: TcHandle, + pub(crate) handle: TcHandle, pub(crate) parent: TcHandle, - options: TcFqCodelOptions, - bytes: u64, - packets: u32, // FIXME - for long term data we have to worry about wrapping - drops: u32, - overlimits: u32, - requeues: u32, - backlog: u32, - qlen: u32, - maxpacket: u16, - drop_overlimit: u32, - new_flow_count: u32, - ecn_mark: u32, - new_flows_len: u16, - old_flows_len: u16, + pub(crate) options: TcFqCodelOptions, + pub(crate) bytes: u64, + pub(crate) packets: u32, // FIXME - for long term data we have to worry about wrapping + pub(crate) drops: u32, + pub(crate) overlimits: u32, + pub(crate) requeues: u32, + pub(crate) backlog: u32, + pub(crate) qlen: u32, + pub(crate) maxpacket: u16, + pub(crate) drop_overlimit: u32, + pub(crate) new_flow_count: u32, + pub(crate) ecn_mark: u32, + pub(crate) new_flows_len: u16, + pub(crate) old_flows_len: u16, } #[derive(Default, Clone, Debug, Serialize)] -struct TcFqCodelOptions { - limit: u32, - flows: u16, - quantum: u16, - target: u64, // FIXME target and interval within fq_codel are scaled to ns >> 1024 - interval: u64, // tc scales them back up to us. Ideally ns would make sense throughout. - memory_limit: u32, - ecn: bool, - drop_batch: u16, // FIXME CE_threshold is presently missing from the parser +pub(crate) struct TcFqCodelOptions { + pub(crate) limit: u32, + pub(crate) flows: u16, + pub(crate) quantum: u16, + pub(crate) target: u64, // FIXME target and interval within fq_codel are scaled to ns >> 1024 + pub(crate) interval: u64, // tc scales them back up to us. Ideally ns would make sense throughout. + pub(crate) memory_limit: u32, + pub(crate) ecn: bool, + pub(crate) drop_batch: u16, // FIXME CE_threshold is presently missing from the parser } impl TcFqCodel { diff --git a/src/rust/lqosd/src/node_manager/js_build/src/circuit.js b/src/rust/lqosd/src/node_manager/js_build/src/circuit.js index 9210fe50..d30e89c8 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/circuit.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/circuit.js @@ -737,7 +737,7 @@ function subscribeToCake() { function showNoQueueMessage() { const cakeTab = document.getElementById("cake"); if (cakeTab && !hasReceivedData) { - cakeTab.innerHTML = '

Queue not loaded.

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

'; + cakeTab.innerHTML = '

Queue not loaded.

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

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