diff --git a/docs/v2.0/configuration-advanced.md b/docs/v2.0/configuration-advanced.md index c1070de8..8e3cf35e 100644 --- a/docs/v2.0/configuration-advanced.md +++ b/docs/v2.0/configuration-advanced.md @@ -108,8 +108,8 @@ In the WebUI, this lives at `Configuration -> Integration - Common` as `Queue Au How it works: - `queue_auto_virtualize_threshold_mbps` is the static queue-policy threshold used by `lqos_topology`. -- Integration roots default to static virtual nodes in the runtime tree. -- Site nodes above the threshold may also be virtualized automatically when they are acting as aggregation-only branches. +- `QueueAuto` only hides a node when it is a `Site`, has child branches, and its final effective node rate is at or above the threshold. +- That same threshold rule applies to top-level `QueueAuto` sites and non-top-level `QueueAuto` sites. - Nodes with directly attached circuits stay queue-visible by default. This static queue policy is now the primary way to avoid wasting HTB depth or creating artificial aggregate choke points. TreeGuard runtime link virtualization remains available, but is disabled by default. @@ -120,23 +120,20 @@ This static queue policy is now the primary way to avoid wasting HTB depth or cr ```{mermaid} flowchart TD - A[Node queue policy = QueueAuto] --> B{Is this a root node?} - B -->|Yes| C[Hide for queueing / promote children] - B -->|No| D{Is this a Site node?} + A[Node queue policy = QueueAuto] --> B{Is this a Site node?} + B -->|No| C[Keep queue-visible] + B -->|Yes| D{Does it have child branches?} D -->|No| E[Keep queue-visible] - D -->|Yes| F{Does it have child branches?} + D -->|Yes| F{Final effective node rate >= threshold?} F -->|No| G[Keep queue-visible] - F -->|Yes| H{Final effective node rate >= threshold?} - H -->|No| I[Keep queue-visible] - H -->|Yes| J[Mark static virtual for queueing] + F -->|Yes| H[Mark static virtual for queueing] ``` Current rule summary: -- Root nodes default to queue-hidden or static virtual behavior depending on policy. - Non-`Site` nodes stay queue-visible under `QueueAuto`. - A `Site` with no child branches stays queue-visible. -- A `Site` with child branches only becomes static virtual when its final effective node rate is at or above `queue_auto_virtualize_threshold_mbps`. +- A top-level or non-top-level `Site` with child branches only becomes static virtual when its final effective node rate is at or above `queue_auto_virtualize_threshold_mbps`. - The rate used for this decision is the recompiled runtime-effective rate, not an earlier raw attachment max. When a node becomes static virtual: diff --git a/src/rust/lqos_topology/src/lib.rs b/src/rust/lqos_topology/src/lib.rs index 7f494a89..c780574a 100644 --- a/src/rust/lqos_topology/src/lib.rs +++ b/src/rust/lqos_topology/src/lib.rs @@ -2380,9 +2380,6 @@ fn resolved_queue_visibility_policy( TopologyQueueVisibilityPolicy::QueueHiddenPromoteChildren } TopologyQueueVisibilityPolicy::QueueAuto => { - if ui_node.current_parent_node_id.is_none() { - return TopologyQueueVisibilityPolicy::QueueHiddenPromoteChildren; - } let Some(tree_node) = tree_node.and_then(Value::as_object) else { return TopologyQueueVisibilityPolicy::QueueVisible; }; @@ -5992,6 +5989,238 @@ mod tests { assert_eq!(aggregation.get("virtual").and_then(Value::as_bool), None); } + #[test] + fn queue_auto_top_level_site_below_threshold_stays_visible() { + let mut config = Config::default(); + config.uisp_integration.enable_uisp = true; + config.topology.queue_auto_virtualize_threshold_mbps = 5_000; + + let editor_state = TopologyEditorStateFile { + schema_version: 1, + source: "uisp/full2".to_string(), + generated_unix: None, + ingress_identity: None, + nodes: vec![ + TopologyEditorNode { + node_id: "site-root".to_string(), + node_name: "Root Aggregation".to_string(), + latitude: None, + longitude: None, + current_parent_node_id: None, + current_parent_node_name: None, + current_attachment_id: None, + current_attachment_name: None, + can_move: false, + allowed_parents: Vec::new(), + queue_visibility_policy: TopologyQueueVisibilityPolicy::QueueAuto, + preferred_attachment_id: None, + preferred_attachment_name: None, + effective_attachment_id: None, + effective_attachment_name: None, + }, + TopologyEditorNode { + node_id: "site-child".to_string(), + node_name: "Edge".to_string(), + latitude: None, + longitude: None, + current_parent_node_id: Some("site-root".to_string()), + current_parent_node_name: Some("Root Aggregation".to_string()), + current_attachment_id: None, + current_attachment_name: None, + can_move: false, + allowed_parents: Vec::new(), + queue_visibility_policy: TopologyQueueVisibilityPolicy::QueueVisible, + preferred_attachment_id: None, + preferred_attachment_name: None, + effective_attachment_id: None, + effective_attachment_name: None, + }, + ], + }; + + let canonical = json!({ + "Root Aggregation": { + "children": { + "Edge": { + "children": {}, + "downloadBandwidthMbps": 1000, + "id": "site-child", + "name": "Edge", + "type": "Site", + "uploadBandwidthMbps": 1000 + } + }, + "downloadBandwidthMbps": 2350, + "id": "site-root", + "name": "Root Aggregation", + "type": "Site", + "uploadBandwidthMbps": 2350 + } + }); + + let effective = TopologyEffectiveStateFile { + schema_version: 1, + generated_unix: None, + canonical_generated_unix: None, + health_generated_unix: None, + nodes: vec![ + TopologyEffectiveNodeState { + node_id: "site-root".to_string(), + logical_parent_node_id: String::new(), + preferred_attachment_id: None, + effective_attachment_id: None, + fallback_reason: None, + all_attachments_suppressed: false, + attachments: vec![], + }, + TopologyEffectiveNodeState { + node_id: "site-child".to_string(), + logical_parent_node_id: "site-root".to_string(), + preferred_attachment_id: None, + effective_attachment_id: None, + fallback_reason: None, + all_attachments_suppressed: false, + attachments: vec![], + }, + ], + }; + + let effective_network = apply_effective_topology_to_network_json( + &config, + &canonical, + &editor_state, + &effective, + ); + let root = effective_network + .as_object() + .expect("effective export should remain an object tree"); + let root_node = root + .get("Root Aggregation") + .and_then(Value::as_object) + .expect("root node should remain exported"); + assert_eq!(root_node.get("virtual").and_then(Value::as_bool), None); + let children = root_node["children"] + .as_object() + .expect("root node should retain its logical children"); + assert!(children.get("Edge").is_some()); + } + + #[test] + fn queue_auto_top_level_site_above_threshold_becomes_virtual() { + let mut config = Config::default(); + config.uisp_integration.enable_uisp = true; + config.topology.queue_auto_virtualize_threshold_mbps = 5_000; + + let editor_state = TopologyEditorStateFile { + schema_version: 1, + source: "uisp/full2".to_string(), + generated_unix: None, + ingress_identity: None, + nodes: vec![ + TopologyEditorNode { + node_id: "site-root".to_string(), + node_name: "Root Aggregation".to_string(), + latitude: None, + longitude: None, + current_parent_node_id: None, + current_parent_node_name: None, + current_attachment_id: None, + current_attachment_name: None, + can_move: false, + allowed_parents: Vec::new(), + queue_visibility_policy: TopologyQueueVisibilityPolicy::QueueAuto, + preferred_attachment_id: None, + preferred_attachment_name: None, + effective_attachment_id: None, + effective_attachment_name: None, + }, + TopologyEditorNode { + node_id: "site-child".to_string(), + node_name: "Edge".to_string(), + latitude: None, + longitude: None, + current_parent_node_id: Some("site-root".to_string()), + current_parent_node_name: Some("Root Aggregation".to_string()), + current_attachment_id: None, + current_attachment_name: None, + can_move: false, + allowed_parents: Vec::new(), + queue_visibility_policy: TopologyQueueVisibilityPolicy::QueueVisible, + preferred_attachment_id: None, + preferred_attachment_name: None, + effective_attachment_id: None, + effective_attachment_name: None, + }, + ], + }; + + let canonical = json!({ + "Root Aggregation": { + "children": { + "Edge": { + "children": {}, + "downloadBandwidthMbps": 1000, + "id": "site-child", + "name": "Edge", + "type": "Site", + "uploadBandwidthMbps": 1000 + } + }, + "downloadBandwidthMbps": 7000, + "id": "site-root", + "name": "Root Aggregation", + "type": "Site", + "uploadBandwidthMbps": 7000 + } + }); + + let effective = TopologyEffectiveStateFile { + schema_version: 1, + generated_unix: None, + canonical_generated_unix: None, + health_generated_unix: None, + nodes: vec![ + TopologyEffectiveNodeState { + node_id: "site-root".to_string(), + logical_parent_node_id: String::new(), + preferred_attachment_id: None, + effective_attachment_id: None, + fallback_reason: None, + all_attachments_suppressed: false, + attachments: vec![], + }, + TopologyEffectiveNodeState { + node_id: "site-child".to_string(), + logical_parent_node_id: "site-root".to_string(), + preferred_attachment_id: None, + effective_attachment_id: None, + fallback_reason: None, + all_attachments_suppressed: false, + attachments: vec![], + }, + ], + }; + + let effective_network = apply_effective_topology_to_network_json( + &config, + &canonical, + &editor_state, + &effective, + ); + let root = effective_network + .as_object() + .expect("effective export should remain an object tree"); + let root_node = root + .get("Root Aggregation") + .and_then(Value::as_object) + .expect("root node should remain exported"); + assert_eq!(root_node.get("virtual").and_then(Value::as_bool), Some(true)); + let children = root_node["children"] + .as_object() + .expect("root node should retain its logical children"); + assert!(children.get("Edge").is_some()); + } + #[test] fn runtime_squashing_respects_do_not_squash_sites() { let mut config = Config::default(); -- knotmirror 0.0.1 From 6df518a4096d2cc45c351e72890a80e8416ddc96 Mon Sep 17 00:00:00 2001 From: Name <2718612@2178972821991.net> Date: Sat, 18 Apr 2026 23:26:16 -0600 Subject: [PATCH 02/51] changes --- .../src/node_manager/js_build/src/template.js | 36 +++++++++++++++---- 1 file changed, 30 insertions(+), 6 deletions(-) diff --git a/src/rust/lqosd/src/node_manager/js_build/src/template.js b/src/rust/lqosd/src/node_manager/js_build/src/template.js index d90a7d05..233be5f3 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/template.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/template.js @@ -119,9 +119,31 @@ function schedulerRelativeTime(updatedUnix) { return `Updated ${deltaDays}d ago`; } +function schedulerErrorText(data) { + const error = data?.error; + if (!error) return ""; + return String(error).trim(); +} + +function schedulerLooksRecovered(data) { + const progress = data?.progress || null; + if (!data?.available || !progress || progress.active) { + return false; + } + return String(progress.phase || "").trim() === "ready"; +} + +function schedulerHasLiveError(data) { + const errorText = schedulerErrorText(data); + if (!errorText) { + return false; + } + return !schedulerLooksRecovered(data); +} + function schedulerStateDescriptor(data) { const progress = data?.progress || null; - const hasError = !!(data?.error && String(data.error).trim().length > 0); + const hasError = schedulerHasLiveError(data); const available = !!data?.available; const active = !!progress?.active; const setupRequired = !!data?.setup_required; @@ -231,6 +253,8 @@ function schedulerActivityItems(output, error, data) { function renderSchedulerDetails(data) { const progress = data?.progress || null; const descriptor = schedulerStateDescriptor(data); + const liveError = schedulerHasLiveError(data) ? schedulerErrorText(data) : ""; + const historicalError = !liveError ? schedulerErrorText(data) : ""; const percent = progress ? schedulerProgressPercent(progress) : (data?.available ? 100 : 0); const phaseLabel = progress?.phase_label || progress?.phase || descriptor.title; const stepCount = Number(progress?.step_count); @@ -242,8 +266,8 @@ function renderSchedulerDetails(data) { ? schedulerRelativeTime(progress.updated_unix) : "Update time unavailable"; const availabilityText = data?.setup_required ? "Setup Required" : (data?.available ? "Healthy" : "Unavailable"); - const recentResult = schedulerSetupMessage(data) || summarizeSchedulerOutput(data?.output, data?.error); - const activity = schedulerActivityItems(data?.output, data?.error, data); + const recentResult = schedulerSetupMessage(data) || summarizeSchedulerOutput(data?.output, historicalError || liveError); + const activity = schedulerActivityItems(data?.output, historicalError || liveError, data); const progressMeta = data?.setup_required ? "Complete runtime setup to enable scheduler work" : progress?.active @@ -254,8 +278,8 @@ function renderSchedulerDetails(data) { const setupAlert = data?.setup_required ? `` : ""; - const alertMarkup = data?.error - ? `` + const alertMarkup = liveError + ? `` : ""; const activityMarkup = activity.length ? activity.map(line => ` @@ -413,7 +437,7 @@ function loadSchedulerStatus(force = false) { return; } const data = msg.data; - const hasError = !!(data.error && String(data.error).trim().length > 0); + const hasError = schedulerHasLiveError(data); const isHealthy = !!data.available && !hasError; const progress = data.progress || null; const progressActive = !!(progress && progress.active); -- knotmirror 0.0.1 From d2c4a7e6a460a684468e766ab92425c80c236044 Mon Sep 17 00:00:00 2001 From: Name <2718612@2178972821991.net> Date: Sun, 19 Apr 2026 00:02:03 -0600 Subject: [PATCH 03/51] changes --- docs-es/v2.0/troubleshooting-es.md | 11 ++ docs/v2.0/troubleshooting.md | 13 +- src/LibreQoS.py | 71 ++++++-- .../lqos_config/src/etc/v15/top_config.rs | 4 +- src/rust/lqos_network_devices/src/state.rs | 4 +- src/rust/lqos_topology/src/lib.rs | 110 ++++++++++-- src/scheduler.py | 167 ++++++++++++++++++ src/test_libreqos_shaping_inputs.py | 37 +++- src/test_scheduler.py | 108 ++++++++++- 9 files changed, 485 insertions(+), 40 deletions(-) diff --git a/docs-es/v2.0/troubleshooting-es.md b/docs-es/v2.0/troubleshooting-es.md index 29dc1f17..14f95604 100644 --- a/docs-es/v2.0/troubleshooting-es.md +++ b/docs-es/v2.0/troubleshooting-es.md @@ -134,6 +134,17 @@ sudo systemctl restart lqosd lqos_scheduler Si oscila entre ready/error, valide credenciales y timeouts de integración en `/etc/lqos.conf`. +Si el shaping de arranque comienza antes de que topology runtime publique la generación actual de `shaping_inputs.json`, las versiones actuales mantienen el scheduler en un estado de espera de arranque y reintentan el shaping inicial cada pocos segundos. Un mensaje breve como `still building outputs for the current source generation` justo después de reiniciar normalmente significa que LibreQoS todavía está terminando el ciclo de importación y publicación de runtime, no que el shaping quede detenido hasta la siguiente actualización de 30 minutos. + +Si el arranque del scheduler permanece demasiado tiempo en esa espera, o entra en estado degradado con un mensaje indicando que topology runtime falló para la generación actual, revise: + +```bash +cat /opt/libreqos/state/topology/topology_runtime_status.json +ls -lh /opt/libreqos/state/topology/topology_effective_state.json /opt/libreqos/state/topology/network.effective.json /opt/libreqos/state/shaping/shaping_inputs.json +journalctl -u lqos_scheduler --since "30 minutes ago" +journalctl -u lqosd --since "30 minutes ago" +``` + ### RTNETLINK answers: Invalid argument Suele indicar que no se pudo agregar correctamente qdisc MQ en la NIC (colas RX/TX insuficientes). Verifique [NICs recomendadas](requirements-es.md). diff --git a/docs/v2.0/troubleshooting.md b/docs/v2.0/troubleshooting.md index c4c5ee96..127b479f 100644 --- a/docs/v2.0/troubleshooting.md +++ b/docs/v2.0/troubleshooting.md @@ -154,19 +154,18 @@ ldd /opt/libreqos/src/liblqos_python.so Routine package upgrades now keep `lqosd` in charge of the main WebUI when `/etc/lqos.conf` already exists. Current packages no longer start the dedicated `lqos_setup` web service during a normal upgrade just because newer first-run checks are incomplete. If the upgraded host still needs a first admin user or a topology source, finish that work in the normal WebUI (`first-run.html` or `Complete Setup`) instead of expecting `lqos_setup` to take over port `9123`. -If startup shaping fails because `shaping_inputs.json` is missing or stale, current builds leave the scheduler running in a degraded state and wait for the next scheduled full refresh to recover. The high-frequency topology refresh tick stays disabled until one shaping pass completes successfully, so repeated 3-second refresh attempts should not continue hammering a fresh install that has not produced runtime topology inputs yet. +If startup shaping begins before topology runtime has finished publishing the current generation of `shaping_inputs.json`, current builds keep the scheduler in a startup wait state and retry the initial shaping pass every few seconds. A short `still building outputs for the current source generation` message right after restart now usually means LibreQoS is still finishing the import/runtime publish cycle, not that shaping is stuck until the next 30-minute refresh. -If scheduler startup is degraded with a message about topology runtime still building, that usually means LibreQoS is still finishing an import or refreshing shaping data. Give the current cycle a little time to complete, then recheck Scheduler Status before changing unrelated settings. - -If scheduler startup is degraded with a message that topology runtime failed for the current generation, inspect: +If scheduler startup stays in that wait state for an unusually long time, or degrades with a message that topology runtime failed for the current generation, inspect: ```bash -cat /opt/libreqos/src/topology_runtime_status.json -ls -lh /opt/libreqos/src/topology_effective_state.json /opt/libreqos/src/network.effective.json /opt/libreqos/src/shaping_inputs.json +cat /opt/libreqos/state/topology/topology_runtime_status.json +ls -lh /opt/libreqos/state/topology/topology_effective_state.json /opt/libreqos/state/topology/network.effective.json /opt/libreqos/state/shaping/shaping_inputs.json journalctl -u lqos_scheduler --since "30 minutes ago" +journalctl -u lqosd --since "30 minutes ago" ``` -If Topology Manager changes or imports seem stuck on older data, check whether LibreQoS set older snapshots aside under `/opt/libreqos/src/.topology_stale/`, then review recent scheduler logs before retrying. +If Topology Manager changes or imports seem stuck on older data, check whether LibreQoS set older snapshots aside under `/opt/libreqos/src/.topology_stale/`, then review recent scheduler and `lqosd` logs before retrying. If Insight topology looks wrong, review the current troubleshooting snapshot that `lqosd` is preparing for Insight: diff --git a/src/LibreQoS.py b/src/LibreQoS.py index 381f6bc6..3a308d40 100755 --- a/src/LibreQoS.py +++ b/src/LibreQoS.py @@ -345,6 +345,46 @@ def _attachment_lookup_candidates(node_key, node_data): return candidates +def _circuit_attachment_name_candidates(circuit): + candidates = [] + for candidate_name in ( + circuit.get('ParentNode', ''), + circuit.get('effectiveParentNodeName', ''), + ): + candidate = str(candidate_name or '').strip() + if candidate and candidate != 'none' and candidate not in candidates: + candidates.append(candidate) + + if circuit.get('parentResolvedByShapingInputs') is not True: + logical_parent = str(circuit.get('logicalParentNode', '') or '').strip() + if logical_parent and logical_parent != 'none' and logical_parent not in candidates: + candidates.append(logical_parent) + + return candidates + + +def _validate_planned_circuit_attachment(node_name, node_data, circuit, planned_identity): + site_major = _parse_int_token(node_data.get('classMajor')) + site_up_major = _parse_int_token(node_data.get('up_classMajor')) + planned_major = _parse_int_token(planned_identity.get('class_major')) + planned_up_major = _parse_int_token(planned_identity.get('up_class_major')) + if None in (site_major, site_up_major, planned_major, planned_up_major): + raise ValueError( + f"Incomplete class identity while attaching circuit '{circuit.get('circuitID', '')}' to parent '{node_name}'" + ) + if site_major != planned_major or site_up_major != planned_up_major: + raise ValueError( + "Planned circuit class majors do not match the selected parent node: " + f"circuit='{circuit.get('circuitID', '')}', parent='{node_name}', " + f"parentMajor={hex(site_major)}, parentUpMajor={hex(site_up_major)}, " + f"plannedMajor={hex(planned_major)}, plannedUpMajor={hex(planned_up_major)}, " + f"ParentNode='{circuit.get('ParentNode', '')}', " + f"logicalParentNode='{circuit.get('logicalParentNode', '')}', " + f"resolutionSource='{circuit.get('parentResolutionSource', '')}'" + ) + return planned_major, planned_up_major + + def _current_topology_source_generation(): try: generation = calculate_topology_source_generation() @@ -461,6 +501,7 @@ def loadSubscriberCircuitsFromShapingInputs(shapingInputsPath): "circuitID": circuitID, "circuitName": str(circuit.get('circuit_name', '') or ''), "ParentNode": parent_node if parent_node != '' else 'none', + "effectiveParentNodeName": parent_node, "ParentNodeID": parent_node_id, "AnchorNodeID": anchor_node_id, "devices": devices, @@ -1770,13 +1811,8 @@ def refreshShapers(): if parent_id: circuits_by_parent_id.setdefault(parent_id, []).append(circuit) - for parent_name in { - str(circuit.get('ParentNode', '') or '').strip(), - str(circuit.get('effectiveParentNodeName', '') or '').strip(), - str(circuit.get('logicalParentNode', '') or '').strip(), - }: - if parent_name: - circuits_by_parent_name.setdefault(parent_name, []).append(circuit) + for parent_name in _circuit_attachment_name_candidates(circuit): + circuits_by_parent_name.setdefault(parent_name, []).append(circuit) # Parse network structure and add devices from ShapedDevices.csv print("Parsing network structure and tallying devices") @@ -2184,8 +2220,9 @@ def refreshShapers(): for node in sorted_node_keys(data, depth): node_data = data[node] queue_token = _parse_int_token(node_data.get('cpuNum')) - major = _parse_int_token(node_data.get('classMajor')) - if queue_token is None or major is None: + site_major = _parse_int_token(node_data.get('classMajor')) + site_up_major = _parse_int_token(node_data.get('up_classMajor')) + if queue_token is None or site_major is None or site_up_major is None: continue queue = queue_token + 1 circuitsForThisNetworkNode = [] @@ -2236,11 +2273,15 @@ def refreshShapers(): if planned_identity is None: raise ValueError(f"Missing planned circuit identity for {planner_key}") candidate_minor = int(planned_identity["class_minor"]) - major = int(planned_identity["class_major"]) - up_major = int(planned_identity["up_class_major"]) + planned_major, planned_up_major = _validate_planned_circuit_attachment( + node, + node_data, + circuit, + planned_identity, + ) ensure_minor_capacity(queue, candidate_minor) - flowIDstring = hex(major) + ':' + hex(candidate_minor) - upFlowIDstring = hex(up_major) + ':' + hex(candidate_minor) + flowIDstring = hex(planned_major) + ':' + hex(candidate_minor) + upFlowIDstring = hex(planned_up_major) + ':' + hex(candidate_minor) circuit['classid'] = flowIDstring circuit['up_classid'] = upFlowIDstring attached_circuit_ids.add(circuit_id) @@ -2268,8 +2309,8 @@ def refreshShapers(): "devices": circuit['devices'], "classid": flowIDstring, "up_classid": upFlowIDstring, - "classMajor": hex(major), - "up_classMajor": hex(up_major), + "classMajor": hex(planned_major), + "up_classMajor": hex(planned_up_major), "classMinor": hex(candidate_minor), "comment": circuit['comment'], } 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 a5a0cfcf..3d942b45 100644 --- a/src/rust/lqos_config/src/etc/v15/top_config.rs +++ b/src/rust/lqos_config/src/etc/v15/top_config.rs @@ -597,7 +597,9 @@ mod test { raw.lines() .filter(|line| { let trimmed = line.trim_start(); - !keys.iter().any(|key| trimmed.starts_with(&format!("{key} ="))) + !keys + .iter() + .any(|key| trimmed.starts_with(&format!("{key} ="))) }) .collect::>() .join("\n") diff --git a/src/rust/lqos_network_devices/src/state.rs b/src/rust/lqos_network_devices/src/state.rs index 7a82977d..44f16738 100644 --- a/src/rust/lqos_network_devices/src/state.rs +++ b/src/rust/lqos_network_devices/src/state.rs @@ -132,9 +132,7 @@ mod tests { use super::network_json_with_carried_runtime_state; use lqos_config::NetworkJsonNode; use lqos_utils::{ - qoq_heatmap::TemporalQoqHeatmap, - rtt::RttBuffer, - temporal_heatmap::TemporalHeatmap, + qoq_heatmap::TemporalQoqHeatmap, rtt::RttBuffer, temporal_heatmap::TemporalHeatmap, units::DownUpOrder, }; diff --git a/src/rust/lqos_topology/src/lib.rs b/src/rust/lqos_topology/src/lib.rs index c780574a..03c72d37 100644 --- a/src/rust/lqos_topology/src/lib.rs +++ b/src/rust/lqos_topology/src/lib.rs @@ -23,7 +23,7 @@ use lqos_overrides::{ }; use lqos_topology_compile::{TopologyCompiledShapingFile, TopologyImportFile}; use serde_json::{Map, Value}; -use std::collections::{BTreeMap, HashMap, HashSet}; +use std::collections::{BTreeMap, HashMap, HashSet, hash_map::Entry}; use std::fs::{File, OpenOptions}; use std::io::Write; use std::net::IpAddr; @@ -106,7 +106,12 @@ fn optional_non_empty_owned(raw: Option) -> Option { raw.and_then(|value| optional_non_empty(&value)) } -fn collect_exported_effective_nodes(value: &Value, by_id: &mut HashMap) { +fn collect_exported_effective_nodes( + value: &Value, + by_id: &mut HashMap, + unique_names: &mut HashMap>, + ambiguous_names: &mut HashSet, +) { let Some(nodes) = value.as_object() else { return; }; @@ -124,11 +129,24 @@ fn collect_exported_effective_nodes(value: &Value, by_id: &mut HashMap { + entry.insert(node_id); + } + Entry::Occupied(entry) => { + let (duplicate_name, _) = entry.remove_entry(); + ambiguous_names.insert(duplicate_name); + } + } + } } if let Some(children) = map.get("children") { - collect_exported_effective_nodes(children, by_id); + collect_exported_effective_nodes(children, by_id, unique_names, ambiguous_names); } } } @@ -217,6 +235,7 @@ fn resolve_legacy_parent_from_effective_tree( parent_node: &str, parent_node_id: Option<&str>, exported_effective_nodes: &HashMap, + exported_effective_names: &HashMap>, exported_effective_aliases: &HashMap, queue_aliases_by_id: &HashMap, queue_aliases_by_name: &HashMap, @@ -235,11 +254,12 @@ fn resolve_legacy_parent_from_effective_tree( return Some(resolved); } if let Some(parent_name) = trimmed_name.as_deref() - && let Some(parent_id) = exported_effective_nodes - .iter() - .find_map(|(node_id, node_name)| (node_name == parent_name).then(|| node_id.clone())) + && let Some(parent_id) = exported_effective_names.get(parent_name) { - return Some((parent_id, parent_name.to_string())); + return Some(( + parent_id.clone().unwrap_or_default(), + parent_name.to_string(), + )); } if let Some(parent_name) = trimmed_name.as_deref() && let Some(resolved) = queue_aliases_by_name.get(parent_name).cloned() @@ -496,10 +516,17 @@ fn build_shaping_inputs( .map(|node| (node.node_id.as_str(), node)) .collect::>(); let mut exported_effective_nodes = HashMap::::new(); + let mut exported_effective_names = HashMap::>::new(); let mut exported_effective_aliases = HashMap::::new(); + let mut ambiguous_exported_effective_names = HashSet::::new(); let attachment_owner_by_attachment_id = build_attachment_owner_map(&artifacts.ui_state); if let Some(effective_network) = artifacts.effective_network.as_ref() { - collect_exported_effective_nodes(effective_network, &mut exported_effective_nodes); + collect_exported_effective_nodes( + effective_network, + &mut exported_effective_nodes, + &mut exported_effective_names, + &mut ambiguous_exported_effective_names, + ); collect_exported_effective_aliases(effective_network, &mut exported_effective_aliases); } let (queue_aliases_by_id, queue_aliases_by_name) = build_effective_queue_aliases( @@ -627,6 +654,7 @@ fn build_shaping_inputs( &device.parent_node, device.parent_node_id.as_deref(), &exported_effective_nodes, + &exported_effective_names, &exported_effective_aliases, &queue_aliases_by_id, &queue_aliases_by_name, @@ -4757,6 +4785,63 @@ mod tests { ); } + #[test] + fn shaping_inputs_resolve_legacy_parent_by_unique_effective_name_without_id() { + let lqos_directory = unique_temp_dir("lqos-topology-legacy-parent-name-only"); + let config = Config { + lqos_directory: lqos_directory.to_string_lossy().to_string(), + state_directory: None, + ..Config::default() + }; + fs::write( + lqos_directory.join("ShapedDevices.csv"), + concat!( + "Circuit ID,Circuit Name,Device ID,Device Name,Parent Node,Parent Node ID,Anchor Node ID,MAC,IPv4,IPv6,Download Min Mbps,Upload Min Mbps,Download Max Mbps,Upload Max Mbps,Comment\n", + "\"circuit-1\",\"Circuit 1\",\"device-1\",\"Device 1\",\"Tower 1\",\"\",\"\",\"aa:bb:cc:dd:ee:ff\",\"192.0.2.10/32\",\"\",\"10\",\"10\",\"100\",\"100\",\"\"\n", + ), + ) + .expect("ShapedDevices.csv should write"); + + let artifacts = EffectiveTopologyArtifacts { + effective: TopologyEffectiveStateFile { + schema_version: 1, + generated_unix: Some(1), + canonical_generated_unix: Some(1), + health_generated_unix: Some(1), + nodes: Vec::new(), + }, + ui_state: TopologyEditorStateFile { + schema_version: 1, + source: "test".to_string(), + generated_unix: Some(1), + ingress_identity: None, + nodes: Vec::new(), + }, + effective_network: Some(json!({ + "Tower 1": { + "children": {} + } + })), + }; + + let shaping_inputs = build_shaping_inputs(&config, &artifacts) + .expect("shaping inputs should build") + .expect("shaping inputs should exist"); + let circuit = shaping_inputs + .circuits + .iter() + .find(|circuit| circuit.circuit_id == "circuit-1") + .expect("expected circuit"); + + assert_eq!(circuit.effective_parent_node_id, ""); + assert_eq!(circuit.effective_parent_node_name, "Tower 1"); + assert_eq!( + circuit.resolution_source, + lqos_config::TopologyShapingResolutionSource::LegacyParent + ); + assert!(shaping_inputs.warnings.is_empty()); + } + #[test] fn shaping_inputs_skip_virtual_effective_nodes_when_resolving_physical_parent() { let lqos_directory = unique_temp_dir("lqos-topology-legacy-parent-virtual"); @@ -6214,7 +6299,10 @@ mod tests { .get("Root Aggregation") .and_then(Value::as_object) .expect("root node should remain exported"); - assert_eq!(root_node.get("virtual").and_then(Value::as_bool), Some(true)); + assert_eq!( + root_node.get("virtual").and_then(Value::as_bool), + Some(true) + ); let children = root_node["children"] .as_object() .expect("root node should retain its logical children"); diff --git a/src/scheduler.py b/src/scheduler.py index dd2aaa47..b966be7b 100644 --- a/src/scheduler.py +++ b/src/scheduler.py @@ -33,9 +33,14 @@ shaping_runtime_hash = 0 INTEGRATION_FAILURE_PREVIEW_LINES = 30 INTEGRATION_FAILURE_PREVIEW_CHARS = 4000 TOPOLOGY_RUNTIME_REFRESH_SECONDS = 3 +STARTUP_TOPOLOGY_RUNTIME_MAX_WAIT_SECONDS = 120 SCHEDULER_STARTUP_STEP_COUNT = 5 SCHEDULER_REFRESH_STEP_COUNT = 4 scheduler_status_bus_enabled = True +startup_topology_runtime_pending = False +startup_topology_runtime_generation = None +startup_topology_runtime_started_monotonic = None +startup_topology_runtime_last_report_state = None def configure_scheduler_stdio(): @@ -1004,6 +1009,10 @@ def importAndShapeFullReload(): importFromCRM() publish_scheduler_progress(True, "starting_topology_runtime", "Starting topology runtime", 4, SCHEDULER_STARTUP_STEP_COUNT) if not ensure_topology_runtime_process(wait_for_outputs=True): + ready, detail, generation = topology_runtime_readiness_detail() + if not ready and _topology_runtime_not_ready_is_transient(detail): + _begin_startup_topology_runtime_wait(generation) + return False report_topology_runtime_not_ready( "Scheduler startup shaping refresh deferred", phase_label="Scheduler waiting for topology runtime", @@ -1174,6 +1183,160 @@ def report_topology_runtime_not_ready(context: str, *, phase_label: str, step_co ) +def _reset_startup_topology_runtime_wait(): + global startup_topology_runtime_pending + global startup_topology_runtime_generation + global startup_topology_runtime_started_monotonic + global startup_topology_runtime_last_report_state + + startup_topology_runtime_pending = False + startup_topology_runtime_generation = None + startup_topology_runtime_started_monotonic = None + startup_topology_runtime_last_report_state = None + + +def _topology_runtime_not_ready_is_transient(detail: str) -> bool: + detail_text = str(detail or "").strip() + if detail_text.startswith("Topology runtime failed for the current source generation:"): + return False + return True + + +def _publish_startup_topology_runtime_wait(generation: str | None): + global startup_topology_runtime_last_report_state + + generation_token = str(generation or "").strip() or "unknown" + state = ("waiting", generation_token) + if startup_topology_runtime_last_report_state == state: + return + startup_topology_runtime_last_report_state = state + if generation_token != "unknown": + print( + "Scheduler startup waiting for topology runtime outputs for " + f"generation {generation_token[:12]}." + ) + else: + print("Scheduler startup waiting for topology runtime outputs.") + publish_scheduler_progress( + True, + "waiting_for_topology_runtime", + "Waiting for topology runtime", + 4, + SCHEDULER_STARTUP_STEP_COUNT, + percent=80, + ) + + +def _begin_startup_topology_runtime_wait(generation: str | None): + global startup_topology_runtime_pending + global startup_topology_runtime_generation + global startup_topology_runtime_started_monotonic + global startup_topology_runtime_last_report_state + + generation_token = str(generation or "").strip() or None + now = time.monotonic() + if ( + not startup_topology_runtime_pending + or startup_topology_runtime_generation != generation_token + ): + startup_topology_runtime_pending = True + startup_topology_runtime_generation = generation_token + startup_topology_runtime_started_monotonic = now + startup_topology_runtime_last_report_state = None + _publish_startup_topology_runtime_wait(generation_token) + + +def _continue_startup_topology_runtime_wait(): + global shaping_runtime_hash + global startup_topology_runtime_generation + global startup_topology_runtime_started_monotonic + global startup_topology_runtime_last_report_state + + ready, detail, generation = topology_runtime_readiness_detail() + generation_token = str(generation or "").strip() or None + now = time.monotonic() + + if generation_token != startup_topology_runtime_generation: + startup_topology_runtime_generation = generation_token + startup_topology_runtime_started_monotonic = now + startup_topology_runtime_last_report_state = None + + if ready: + publish_scheduler_progress( + True, + "initial_shaping_reload", + "Refreshing shaper state", + 5, + SCHEDULER_STARTUP_STEP_COUNT, + ) + try: + if not enable_insight_topology(): + refreshShapers() + shaping_runtime_hash = calculate_shaping_runtime_hash() + except ValidationFailure as e: + _reset_startup_topology_runtime_wait() + report_scheduler_validation_failure( + "Scheduler startup shaping refresh blocked by validation", + e, + startup=True, + step_count=SCHEDULER_STARTUP_STEP_COUNT, + ) + shaping_runtime_hash = 0 + return + except Exception as e: + _reset_startup_topology_runtime_wait() + report_scheduler_runtime_failure( + "Scheduler startup shaping refresh failed", + e, + startup=True, + ) + shaping_runtime_hash = 0 + return + + _reset_startup_topology_runtime_wait() + if shaping_runtime_hash != 0: + clear_scheduler_error() + publish_scheduler_progress( + False, + "ready", + "Scheduler ready", + SCHEDULER_STARTUP_STEP_COUNT, + SCHEDULER_STARTUP_STEP_COUNT, + percent=100, + ) + return + + report_scheduler_runtime_failure( + "Scheduler startup shaping refresh failed", + RuntimeError("Shaping runtime hash was not published after startup refresh."), + startup=True, + ) + return + + started = startup_topology_runtime_started_monotonic + if started is None: + startup_topology_runtime_started_monotonic = now + started = now + elapsed = max(0.0, now - started) + + if ( + _topology_runtime_not_ready_is_transient(detail) + and elapsed < STARTUP_TOPOLOGY_RUNTIME_MAX_WAIT_SECONDS + ): + _publish_startup_topology_runtime_wait(generation_token) + return + + state = ("degraded", str(detail or "").strip(), generation_token or "") + if startup_topology_runtime_last_report_state == state: + return + startup_topology_runtime_last_report_state = state + report_topology_runtime_not_ready( + "Scheduler startup shaping refresh deferred", + phase_label="Scheduler waiting for topology runtime", + step_count=SCHEDULER_STARTUP_STEP_COUNT, + ) + + def wait_for_topology_runtime_ready(timeout_seconds=8.0): deadline = time.monotonic() + timeout_seconds while time.monotonic() < deadline: @@ -1193,6 +1356,10 @@ def ensure_topology_runtime_process(wait_for_outputs=False): def topology_runtime_refresh_tick(): global shaping_runtime_hash + if startup_topology_runtime_pending: + _continue_startup_topology_runtime_wait() + return + if shaping_runtime_hash == 0: return diff --git a/src/test_libreqos_shaping_inputs.py b/src/test_libreqos_shaping_inputs.py index 8c03b1cd..57531a3c 100644 --- a/src/test_libreqos_shaping_inputs.py +++ b/src/test_libreqos_shaping_inputs.py @@ -9,7 +9,7 @@ import types import unittest from unittest.mock import patch -_STUBBED_MODULES = ("pythonCheck", "liblqos_python", "LibreQoS") +_STUBBED_MODULES = ("pythonCheck", "liblqos_python", "deepdiff", "LibreQoS") _ORIGINAL_MODULES = {name: sys.modules.get(name) for name in _STUBBED_MODULES} LibreQoS = None @@ -19,6 +19,10 @@ def install_libreqos_stubs(): python_check.checkPythonVersion = lambda: None sys.modules["pythonCheck"] = python_check + deepdiff = types.ModuleType("deepdiff") + deepdiff.DeepDiff = lambda *_args, **_kwargs: {} + sys.modules["deepdiff"] = deepdiff + lqlib = types.ModuleType("liblqos_python") lqlib.is_lqosd_alive = lambda: True lqlib.clear_ip_mappings = lambda: None @@ -96,6 +100,37 @@ class TestLibreQoSShapingInputs(unittest.TestCase): candidates = LibreQoS._attachment_lookup_candidates("Generated_PN_1", {}) self.assertEqual(candidates, ["Generated_PN_1"]) + def test_runtime_resolved_circuit_attachment_candidates_ignore_logical_parent(self): + candidates = LibreQoS._circuit_attachment_name_candidates( + { + "ParentNode": "Generated_PN_2", + "effectiveParentNodeName": "Generated_PN_2", + "logicalParentNode": "Globe", + "parentResolvedByShapingInputs": True, + } + ) + self.assertEqual(candidates, ["Generated_PN_2"]) + + def test_validate_planned_circuit_attachment_rejects_major_mismatch(self): + with self.assertRaisesRegex(ValueError, "Planned circuit class majors do not match"): + LibreQoS._validate_planned_circuit_attachment( + "Globe", + { + "classMajor": "0x1", + "up_classMajor": "0x11", + }, + { + "circuitID": "circuit-1", + "ParentNode": "Generated_PN_4", + "logicalParentNode": "Globe", + "parentResolutionSource": "runtime_fallback", + }, + { + "class_major": 4, + "up_class_major": 20, + }, + ) + def test_shaping_inputs_freshness_tracks_circuit_anchors(self): with tempfile.TemporaryDirectory() as temp_dir: shaping_inputs = os.path.join(temp_dir, "shaping_inputs.json") diff --git a/src/test_scheduler.py b/src/test_scheduler.py index 15967c04..c9cbe0a3 100644 --- a/src/test_scheduler.py +++ b/src/test_scheduler.py @@ -194,6 +194,8 @@ class TestSchedulerAffinity(unittest.TestCase): class TestSchedulerErrorReporting(unittest.TestCase): def setUp(self): scheduler.set_scheduler_status_bus_enabled(True) + scheduler._reset_startup_topology_runtime_wait() + scheduler.shaping_runtime_hash = 0 def test_python_integration_output_does_not_set_scheduler_error(self): result = types.SimpleNamespace(returncode=0, stdout="normal info\n", stderr="") @@ -416,6 +418,94 @@ class TestSchedulerLogging(unittest.TestCase): mock_ensure.assert_not_called() mock_hash.assert_not_called() + def test_topology_runtime_refresh_tick_waits_for_startup_runtime_outputs(self): + scheduler.startup_topology_runtime_pending = True + scheduler.startup_topology_runtime_generation = "generation-1" + scheduler.startup_topology_runtime_started_monotonic = scheduler.time.monotonic() + + with patch.object( + scheduler, + "topology_runtime_readiness_detail", + return_value=( + False, + "Topology runtime is still building outputs for the current source generation.", + "generation-1", + ), + ): + with patch.object(scheduler, "publish_scheduler_progress") as mock_progress: + with patch.object(scheduler, "refreshShapers") as mock_refresh: + with patch.object(scheduler, "scheduler_error") as mock_scheduler_error: + with patch("builtins.print"): + scheduler.topology_runtime_refresh_tick() + + mock_refresh.assert_not_called() + mock_scheduler_error.assert_not_called() + self.assertTrue(scheduler.startup_topology_runtime_pending) + self.assertTrue( + any( + call.args[:3] == ( + True, + "waiting_for_topology_runtime", + "Waiting for topology runtime", + ) + for call in mock_progress.call_args_list + ) + ) + + def test_topology_runtime_refresh_tick_completes_startup_when_runtime_ready(self): + scheduler.startup_topology_runtime_pending = True + scheduler.startup_topology_runtime_generation = "generation-1" + scheduler.startup_topology_runtime_started_monotonic = scheduler.time.monotonic() + + with patch.object( + scheduler, + "topology_runtime_readiness_detail", + return_value=(True, "", "generation-1"), + ): + with patch.object(scheduler, "refreshShapers") as mock_refresh: + with patch.object(scheduler, "calculate_shaping_runtime_hash", return_value=9): + with patch.object(scheduler, "publish_scheduler_progress") as mock_progress: + with patch.object(scheduler, "clear_scheduler_error") as mock_clear_error: + with patch("builtins.print"): + scheduler.topology_runtime_refresh_tick() + + mock_refresh.assert_called_once() + mock_clear_error.assert_called_once() + self.assertEqual(scheduler.shaping_runtime_hash, 9) + self.assertFalse(scheduler.startup_topology_runtime_pending) + self.assertTrue( + any( + call.args[:3] == ( + False, + "ready", + "Scheduler ready", + ) + for call in mock_progress.call_args_list + ) + ) + + def test_topology_runtime_refresh_tick_completes_startup_without_refresh_for_insight_topology(self): + scheduler.startup_topology_runtime_pending = True + scheduler.startup_topology_runtime_generation = "generation-1" + scheduler.startup_topology_runtime_started_monotonic = scheduler.time.monotonic() + + with patch.object( + scheduler, + "topology_runtime_readiness_detail", + return_value=(True, "", "generation-1"), + ): + with patch.object(scheduler, "enable_insight_topology", return_value=True): + with patch.object(scheduler, "refreshShapers") as mock_refresh: + with patch.object(scheduler, "calculate_shaping_runtime_hash", return_value=9): + with patch.object(scheduler, "publish_scheduler_progress"): + with patch.object(scheduler, "clear_scheduler_error"): + with patch("builtins.print"): + scheduler.topology_runtime_refresh_tick() + + mock_refresh.assert_not_called() + self.assertEqual(scheduler.shaping_runtime_hash, 9) + self.assertFalse(scheduler.startup_topology_runtime_pending) + def test_import_and_shape_full_reload_reenables_status_bus_after_success(self): scheduler.set_scheduler_status_bus_enabled(False) @@ -432,9 +522,18 @@ class TestSchedulerLogging(unittest.TestCase): def test_import_and_shape_full_reload_returns_false_when_topology_runtime_not_ready(self): with patch.object(scheduler, "importFromCRM"): with patch.object(scheduler, "ensure_topology_runtime_process", return_value=False): - with patch.object(scheduler, "report_topology_runtime_not_ready"): + with patch.object( + scheduler, + "topology_runtime_readiness_detail", + return_value=( + False, + "Topology runtime is still building outputs for the current source generation.", + "generation-1", + ), + ): with patch.object(scheduler, "publish_scheduler_progress"): self.assertFalse(scheduler.importAndShapeFullReload()) + self.assertTrue(scheduler.startup_topology_runtime_pending) def test_run_scheduler_main_reports_validation_failure_without_ready(self): fake_ads = Mock() @@ -662,6 +761,10 @@ class TestTopologyRuntimeReadiness(unittest.TestCase): class TestTopologyRuntimeGating(unittest.TestCase): + def setUp(self): + scheduler._reset_startup_topology_runtime_wait() + scheduler.shaping_runtime_hash = 0 + def test_full_reload_skips_refresh_when_topology_runtime_not_ready(self): with patch.object(scheduler, "importFromCRM"): with patch.object(scheduler, "ensure_topology_runtime_process", return_value=False): @@ -671,7 +774,8 @@ class TestTopologyRuntimeGating(unittest.TestCase): scheduler.importAndShapeFullReload() mock_refresh.assert_not_called() - mock_report.assert_called_once() + mock_report.assert_not_called() + self.assertTrue(scheduler.startup_topology_runtime_pending) def test_partial_reload_skips_refresh_when_topology_runtime_not_ready(self): with patch.object(scheduler, "importFromCRM"): -- knotmirror 0.0.1 From 980c4700c83321c1dc80f58a39f2f993b06efd40 Mon Sep 17 00:00:00 2001 From: Name <2718612@2178972821991.net> Date: Sun, 19 Apr 2026 09:18:37 -0600 Subject: [PATCH 04/51] changes --- docs-es/v2.0/troubleshooting-es.md | 1 + docs/v2.0/troubleshooting.md | 1 + .../src/node_manager/js_build/src/template.js | 156 +++++++++++++++--- .../src/node_manager/local_api/scheduler.rs | 83 +++++++++- src/rust/lqosd/src/tool_status.rs | 10 ++ 5 files changed, 224 insertions(+), 27 deletions(-) diff --git a/docs-es/v2.0/troubleshooting-es.md b/docs-es/v2.0/troubleshooting-es.md index 14f95604..b2befc84 100644 --- a/docs-es/v2.0/troubleshooting-es.md +++ b/docs-es/v2.0/troubleshooting-es.md @@ -117,6 +117,7 @@ Si el scheduler falla inmediatamente después de un reinicio con un mensaje como ### El estado del scheduler en WebUI aparece no saludable Versiones recientes muestran estado/readiness del scheduler en WebUI. +Si el modal del scheduler indica que se agotó el tiempo al cargar detalles, las versiones actuales mantienen visible la última instantánea buena del scheduler con su antigüedad en lugar de convertir ese problema de transporte en un error del scheduler. Trate primero esa advertencia como un problema de comunicación entre WebUI y `lqosd`, y confirme la salud real del scheduler en los logs antes de asumir que falló el shaping. Si aparece caído/desactualizado: diff --git a/docs/v2.0/troubleshooting.md b/docs/v2.0/troubleshooting.md index 127b479f..9c341feb 100644 --- a/docs/v2.0/troubleshooting.md +++ b/docs/v2.0/troubleshooting.md @@ -184,6 +184,7 @@ If an integration subprocess fails, current builds keep the scheduler alive, pub Recent builds expose scheduler readiness/state in the WebUI (Node Manager). If the scheduler is still starting, the sidebar now reports the current startup phase and a coarse progress ring rather than only a spinner. Current builds also treat scheduler progress, output, and error bus messages as proof that the scheduler is alive, so the sidebar should not stay stuck on `Scheduler available: false` while the scheduler is actively reporting work. +If the scheduler modal says scheduler details timed out, current builds keep showing the last good scheduler snapshot with its age instead of turning that transport problem into a scheduler error. Treat that warning as a WebUI or `lqosd` communication issue first, then confirm scheduler health in the service logs before assuming shaping failed. If scheduler status appears down/stale: 1. Verify both services: diff --git a/src/rust/lqosd/src/node_manager/js_build/src/template.js b/src/rust/lqosd/src/node_manager/js_build/src/template.js index 233be5f3..af9c347a 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/template.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/template.js @@ -35,9 +35,11 @@ const SCHEDULER_MODAL_ACTIVE_POLL_MS = 1000; let schedulerStatusPollTimer = null; let schedulerStatusRequestInFlight = false; let schedulerStatusFirstRequestedAt = null; +let cachedSchedulerStatusData = null; let schedulerModalPollTimer = null; let schedulerModalRequestInFlight = false; let schedulerModalInstance = null; +let cachedSchedulerDetailsData = null; let cachedQueueModeConfig = null; function listenOnceWithTimeout(eventName, timeoutMs, handler, onTimeout) { @@ -125,6 +127,42 @@ function schedulerErrorText(data) { return String(error).trim(); } +function schedulerSnapshotUpdatedUnix(data) { + const progressUpdatedUnix = Number(data?.progress?.updated_unix); + if (Number.isFinite(progressUpdatedUnix) && progressUpdatedUnix > 0) { + return progressUpdatedUnix; + } + const statusUpdatedUnix = Number(data?.updated_unix); + if (Number.isFinite(statusUpdatedUnix) && statusUpdatedUnix > 0) { + return statusUpdatedUnix; + } + return null; +} + +function schedulerUpdatedText(data) { + const updatedUnix = schedulerSnapshotUpdatedUnix(data); + if (!updatedUnix) { + return "Update time unavailable"; + } + return schedulerRelativeTime(updatedUnix); +} + +function schedulerTransportWarningText(message, data) { + const updatedText = schedulerUpdatedText(data); + if (updatedText === "Update time unavailable") { + return `${message} Retrying in the background.`; + } + return `${message} Showing cached scheduler data. ${updatedText}.`; +} + +function schedulerStaleStatusLabel(data) { + const updatedText = schedulerUpdatedText(data); + if (updatedText === "Update time unavailable") { + return "Scheduler status is stale"; + } + return `Scheduler status is stale. ${updatedText}.`; +} + function schedulerLooksRecovered(data) { const progress = data?.progress || null; if (!data?.available || !progress || progress.active) { @@ -170,6 +208,17 @@ function schedulerStateDescriptor(data) { icon: "fa-list-check", }; } + if (data?.stale) { + return { + tone: "warning", + badgeClass: "text-bg-warning", + label: "Stale", + title: "Scheduler status is stale", + subtitle: "Showing the last scheduler snapshot older than five minutes", + ringTone: "tone-warning", + icon: "fa-clock", + }; + } if (active) { return { tone: "info", @@ -250,7 +299,7 @@ function schedulerActivityItems(output, error, data) { .reverse(); } -function renderSchedulerDetails(data) { +function renderSchedulerDetails(data, options = {}) { const progress = data?.progress || null; const descriptor = schedulerStateDescriptor(data); const liveError = schedulerHasLiveError(data) ? schedulerErrorText(data) : ""; @@ -262,22 +311,30 @@ function renderSchedulerDetails(data) { const stepText = Number.isFinite(stepIndex) && Number.isFinite(stepCount) && stepCount > 0 ? `Step ${stepIndex} of ${stepCount}` : "No active step reported"; - const updatedText = progress?.updated_unix - ? schedulerRelativeTime(progress.updated_unix) - : "Update time unavailable"; - const availabilityText = data?.setup_required ? "Setup Required" : (data?.available ? "Healthy" : "Unavailable"); + const updatedText = schedulerUpdatedText(data); + const availabilityText = data?.setup_required + ? "Setup Required" + : data?.stale + ? "Stale" + : (data?.available ? "Healthy" : "Unavailable"); const recentResult = schedulerSetupMessage(data) || summarizeSchedulerOutput(data?.output, historicalError || liveError); const activity = schedulerActivityItems(data?.output, historicalError || liveError, data); - const progressMeta = data?.setup_required - ? "Complete runtime setup to enable scheduler work" - : progress?.active - ? `${percent}% complete` - : descriptor.label === "Idle" - ? "Last run complete" - : "Waiting for activity"; + let progressMeta = "Waiting for activity"; + if (options.transportWarning) { + progressMeta = "Showing cached scheduler details while the UI reconnects"; + } else if (data?.setup_required) { + progressMeta = "Complete runtime setup to enable scheduler work"; + } else if (progress?.active) { + progressMeta = `${percent}% complete`; + } else if (descriptor.label === "Idle") { + progressMeta = "Last run complete"; + } const setupAlert = data?.setup_required ? `` : ""; + const transportWarningMarkup = options.transportWarning + ? `` + : ""; const alertMarkup = liveError ? `` : ""; @@ -304,6 +361,7 @@ function renderSchedulerDetails(data) { ${setupAlert} + ${transportWarningMarkup} ${alertMarkup}
@@ -360,7 +418,7 @@ function updateSchedulerModalBody(contentHtml) { } } -function renderSchedulerStatus(container, state, progress) { +function renderSchedulerStatus(container, state, progress, labelOverride = null) { if (!container) return; let color = "text-secondary"; @@ -388,11 +446,18 @@ function renderSchedulerStatus(container, state, progress) { color = "text-danger"; label = "Scheduler has an internal error"; indicator = schedulerRingMarkup(100, "tone-danger", "fa-triangle-exclamation"); + } else if (state === "stale") { + color = "text-warning"; + label = "Scheduler status is stale"; + indicator = schedulerRingMarkup(100, "tone-warning", "fa-clock"); } else if (state === "setup") { color = "text-warning"; label = "Scheduler needs topology setup"; indicator = schedulerRingMarkup(100, "tone-warning", "fa-list-check"); } + if (labelOverride) { + label = labelOverride; + } container.innerHTML = `
`); } -function renderSchedulerModalError(message) { - updateSchedulerModalBody(` - `); -} - function ensureSchedulerModalLifecycle() { const modalEl = document.getElementById('schedulerModal'); if (!modalEl || modalEl.dataset.schedulerLiveBound === "1") { @@ -567,10 +649,24 @@ function refreshSchedulerModalDetails(showLoading = false) { return; } if (!msg || !msg.data) { - renderSchedulerModalError("Failed to load scheduler details"); + if (cachedSchedulerDetailsData) { + updateSchedulerModalBody(renderSchedulerDetails(cachedSchedulerDetailsData, { + transportWarning: schedulerTransportWarningText( + "Scheduler details response was empty.", + cachedSchedulerDetailsData + ), + })); + } else { + updateSchedulerModalBody(` + `); + } scheduleNextSchedulerModalPoll(SCHEDULER_MODAL_IDLE_POLL_MS); return; } + cachedSchedulerDetailsData = msg.data; + cachedSchedulerStatusData = msg.data; updateSchedulerModalBody(renderSchedulerDetails(msg.data)); scheduleNextSchedulerModalPoll(schedulerModalPollDelay(msg.data)); }, () => { @@ -579,7 +675,19 @@ function refreshSchedulerModalDetails(showLoading = false) { stopSchedulerModalPolling(); return; } - renderSchedulerModalError("Timed out while loading scheduler details"); + if (cachedSchedulerDetailsData) { + updateSchedulerModalBody(renderSchedulerDetails(cachedSchedulerDetailsData, { + transportWarning: schedulerTransportWarningText( + "Scheduler details refresh timed out.", + cachedSchedulerDetailsData + ), + })); + } else { + updateSchedulerModalBody(` + `); + } scheduleNextSchedulerModalPoll(SCHEDULER_MODAL_IDLE_POLL_MS); }); wsClient.send({ SchedulerDetails: {} }); diff --git a/src/rust/lqosd/src/node_manager/local_api/scheduler.rs b/src/rust/lqosd/src/node_manager/local_api/scheduler.rs index 377307bc..33062255 100644 --- a/src/rust/lqosd/src/node_manager/local_api/scheduler.rs +++ b/src/rust/lqosd/src/node_manager/local_api/scheduler.rs @@ -4,8 +4,8 @@ use lqos_bus::SchedulerProgressReport; use crate::node_manager::runtime_onboarding::runtime_onboarding_state; use crate::tool_status::{ - is_scheduler_available, scheduler_error_message, scheduler_output_message, - scheduler_progress_state, + is_scheduler_available, scheduler_error_message, scheduler_last_seen_unix, + scheduler_output_message, scheduler_progress_state, }; // Remove ANSI escape sequences (basic CSI/OSC handling) for browser display @@ -64,23 +64,45 @@ fn strip_ansi(input: &str) -> String { out } +/// Snapshot of scheduler availability for the node-manager widget. #[derive(Serialize, Debug, Clone)] pub struct SchedulerStatus { + /// Whether the scheduler has reported in within the last five minutes. pub available: bool, + /// The latest scheduler error, if one was reported. pub error: Option, + /// The scheduler's last reported progress snapshot, if any. pub progress: Option, + /// The best-known Unix timestamp for this scheduler snapshot. + pub updated_unix: Option, + /// Whether this snapshot is older than the scheduler availability window. + pub stale: bool, + /// Whether initial runtime onboarding is blocking scheduler activity. pub setup_required: bool, + /// Operator-facing onboarding guidance when `setup_required` is true. pub setup_message: Option, } +/// Detailed scheduler snapshot for the scheduler modal. #[derive(Serialize, Debug, Clone)] pub struct SchedulerDetails { + /// Whether the scheduler has reported in within the last five minutes. pub available: bool, + /// The latest scheduler error, if one was reported. pub error: Option, + /// The latest non-error scheduler output line, if any. pub output: Option, + /// The scheduler's last reported progress snapshot, if any. pub progress: Option, + /// The best-known Unix timestamp for this scheduler snapshot. + pub updated_unix: Option, + /// Whether this snapshot is older than the scheduler availability window. + pub stale: bool, + /// Whether initial runtime onboarding is blocking scheduler activity. pub setup_required: bool, + /// Operator-facing onboarding guidance when `setup_required` is true. pub setup_message: Option, + /// Human-readable raw details for the operator debug view. pub details: String, } @@ -106,6 +128,19 @@ fn scheduler_output() -> Option { }) } +fn scheduler_updated_unix(progress: Option<&SchedulerProgressReport>) -> Option { + let progress_updated = progress.and_then(|report| report.updated_unix); + match (progress_updated, scheduler_last_seen_unix()) { + (Some(progress_updated), Some(last_seen_updated)) => { + Some(progress_updated.max(last_seen_updated)) + } + (Some(progress_updated), None) => Some(progress_updated), + (None, Some(last_seen_updated)) => Some(last_seen_updated), + (None, None) => None, + } +} + +/// Builds the lightweight scheduler status snapshot for node-manager consumers. pub fn scheduler_status_data() -> SchedulerStatus { let onboarding = runtime_onboarding_state(); if onboarding.required { @@ -113,6 +148,8 @@ pub fn scheduler_status_data() -> SchedulerStatus { available: false, error: None, progress: None, + updated_unix: None, + stale: false, setup_required: true, setup_message: Some(onboarding.summary), }; @@ -121,15 +158,19 @@ pub fn scheduler_status_data() -> SchedulerStatus { let available = is_scheduler_available(); let error = scheduler_error(); let progress = scheduler_progress_state(); + let updated_unix = scheduler_updated_unix(progress.as_ref()); SchedulerStatus { available, error, progress, + updated_unix, + stale: updated_unix.is_some() && !available, setup_required: false, setup_message: None, } } +/// Builds the detailed scheduler snapshot for the scheduler modal. pub fn scheduler_details_data() -> SchedulerDetails { let status = scheduler_status_data(); let output = scheduler_output(); @@ -148,6 +189,8 @@ pub fn scheduler_details_data() -> SchedulerDetails { error: None, output: None, progress: None, + updated_unix: None, + stale: false, setup_required: true, setup_message: Some(message), details: body, @@ -155,6 +198,12 @@ pub fn scheduler_details_data() -> SchedulerDetails { } body.push_str(&format!("Scheduler available: {}\n\n", status.available)); + if let Some(updated_unix) = status.updated_unix { + body.push_str(&format!("Last updated Unix: {updated_unix}\n")); + } else { + body.push_str("Last updated Unix: unavailable\n"); + } + body.push_str(&format!("Snapshot stale: {}\n\n", status.stale)); match status.progress.as_ref() { Some(progress) => { body.push_str("Current progress:\n"); @@ -203,6 +252,8 @@ pub fn scheduler_details_data() -> SchedulerDetails { error: status.error, output, progress: status.progress, + updated_unix: status.updated_unix, + stale: status.stale, setup_required: false, setup_message: None, details: body, @@ -214,7 +265,8 @@ mod tests { use super::{scheduler_details_data, scheduler_status_data}; use crate::test_support::runtime_config_test_lock; use crate::tool_status::{ - scheduler_error, scheduler_output, scheduler_progress, scheduler_seen, + scheduler_error, scheduler_last_seen_unix, scheduler_output, scheduler_progress, + scheduler_seen, }; use lqos_bus::SchedulerProgressReport; use std::ffi::OsString; @@ -324,6 +376,9 @@ mod tests { let status = scheduler_status_data(); let details = scheduler_details_data(); + let expected_updated_unix = scheduler_last_seen_unix() + .map(|last_seen_unix| last_seen_unix.max(1_234_567_890)) + .expect("scheduler last seen should be set"); assert!(status.available); assert_eq!( @@ -337,6 +392,8 @@ mod tests { .map(|progress| progress.phase.as_str()), Some("validation_failed") ); + assert_eq!(status.updated_unix, Some(expected_updated_unix)); + assert!(!status.stale); assert!(!status.setup_required); assert!(details.available); @@ -348,7 +405,27 @@ mod tests { details.output.as_deref(), Some("Scheduled shaping refresh blocked by validation: duplicate IPv4") ); + assert_eq!(details.updated_unix, Some(expected_updated_unix)); + assert!(!details.stale); assert!(details.details.contains("Reported error:")); + assert!(details.details.contains("Snapshot stale: false")); assert!(details.details.contains("Scheduler validation failed")); } + + #[test] + fn scheduler_status_uses_last_seen_when_progress_timestamp_is_missing() { + let _context = SchedulerStatusTestContext::new("last-seen-fallback"); + scheduler_seen(); + + let status = scheduler_status_data(); + let details = scheduler_details_data(); + let last_seen_unix = scheduler_last_seen_unix().expect("scheduler last seen should be set"); + + assert_eq!(status.updated_unix, Some(last_seen_unix)); + assert!(!status.stale); + assert_eq!(details.updated_unix, Some(last_seen_unix)); + assert!(details + .details + .contains(&format!("Last updated Unix: {last_seen_unix}"))); + } } diff --git a/src/rust/lqosd/src/tool_status.rs b/src/rust/lqosd/src/tool_status.rs index 3c15ac58..7528b55e 100644 --- a/src/rust/lqosd/src/tool_status.rs +++ b/src/rust/lqosd/src/tool_status.rs @@ -83,6 +83,16 @@ pub fn is_scheduler_available() -> bool { now.saturating_sub(last) < 300 } +/// Returns the Unix timestamp of the scheduler's last heartbeat, if one has been seen. +pub fn scheduler_last_seen_unix() -> Option { + let last = SCHEDULER_LAST_SEEN.load(Ordering::Relaxed); + if last == 0 { + None + } else { + Some(last) + } +} + /// Returns the current scheduler error message, if any. pub fn scheduler_error_message() -> Option { let guard: parking_lot::lock_api::MutexGuard<'_, parking_lot::RawMutex, Option> = -- knotmirror 0.0.1 From cad701a8e0e31caa98353e6b02856e752c54bc26 Mon Sep 17 00:00:00 2001 From: Name <2718612@2178972821991.net> Date: Sun, 19 Apr 2026 09:41:58 -0600 Subject: [PATCH 05/51] changes --- .../lqosd/src/lts2_sys/control_channel.rs | 167 ++++++++++++------ .../src/node_manager/local_api/scheduler.rs | 8 +- src/rust/lqosd/src/tool_status.rs | 6 +- 3 files changed, 116 insertions(+), 65 deletions(-) diff --git a/src/rust/lqosd/src/lts2_sys/control_channel.rs b/src/rust/lqosd/src/lts2_sys/control_channel.rs index 24154ad8..61d70af2 100644 --- a/src/rust/lqosd/src/lts2_sys/control_channel.rs +++ b/src/rust/lqosd/src/lts2_sys/control_channel.rs @@ -1,5 +1,5 @@ use anyhow::{Result, bail}; -use futures_util::{StreamExt, sink::SinkExt}; +use futures_util::{StreamExt, sink::SinkExt, stream::SplitSink}; use serde::{Deserialize, Serialize}; use std::{collections::HashMap, time::Duration}; use tokio::net::TcpStream; @@ -23,6 +23,11 @@ pub use messages::{ }; const SHAPER_VERSION_STRING: &str = include_str!("../../../../VERSION_STRING"); +const CONTROL_CHANNEL_QUEUE_DEPTH: usize = 256; +const CONNECTION_COMMAND_QUEUE_DEPTH: usize = 1024; +const SOCKET_SENDER_QUEUE_DEPTH: usize = 32; + +type ControlSocketWriter = SplitSink>, Message>; fn current_shaper_version() -> Option { let version = SHAPER_VERSION_STRING.trim(); @@ -133,7 +138,7 @@ pub struct ControlChannelBuilder { pub fn init_control_channel() -> Result { // Doing this two-step: make the channel here and then spawn the task - let (tx, rx) = tokio::sync::mpsc::channel(256); + let (tx, rx) = tokio::sync::mpsc::channel(CONTROL_CHANNEL_QUEUE_DEPTH); Ok(ControlChannelBuilder { tx, rx }) } @@ -148,7 +153,7 @@ pub async fn start_control_channel(builder: ControlChannelBuilder) -> Result<()> async fn control_channel_loop(mut builder: ControlChannelBuilder) -> Result<()> { // Handle the persistent channel to Insight here - let (tx, rx) = tokio::sync::mpsc::channel::(1024); + let (tx, rx) = tokio::sync::mpsc::channel::(CONNECTION_COMMAND_QUEUE_DEPTH); tokio::spawn(persistent_connection(rx)); while let Some(cmd) = builder.rx.recv().await { @@ -273,6 +278,72 @@ const TCP_TIMEOUT: Duration = Duration::from_secs(30); // Prevent unbounded growth while waiting for Welcome const MAX_PENDING_CHATBOT_MESSAGES: usize = 256; +fn encode_ws_binary( + message: &messages::WsMessage, + label: &'static str, +) -> std::result::Result { + let Ok((_, _, bytes)) = message.to_bytes() else { + error!("Failed to serialize {label} message"); + return Err(()); + }; + Ok(Message::Binary(bytes)) +} + +async fn send_ws_message_now( + write: &mut ControlSocketWriter, + message: Message, + label: &'static str, +) -> std::result::Result<(), ()> { + let Ok(Ok(_)) = timeout(TCP_TIMEOUT, write.send(message)).await else { + error!("Failed to send {label} message"); + return Err(()); + }; + Ok(()) +} + +async fn send_ingest_batch( + write: &mut ControlSocketWriter, + serial: usize, + chunks: Vec>, +) -> std::result::Result { + let n_chunks = chunks.len(); + let byte_count = chunks.iter().map(|chunk| chunk.len()).sum::(); + + let begin = messages::WsMessage::BeginIngest { + unique_id: serial as u64, + n_chunks: n_chunks as u64, + }; + send_ws_message_now( + write, + encode_ws_binary(&begin, "BeginIngest")?, + "BeginIngest", + ) + .await?; + + for (chunk_index, chunk) in chunks.into_iter().enumerate() { + let ingest_chunk = messages::WsMessage::IngestChunk { + unique_id: serial as u64, + chunk: chunk_index as u64, + n_chunks: n_chunks as u64, + data: chunk, + }; + send_ws_message_now( + write, + encode_ws_binary(&ingest_chunk, "IngestChunk")?, + "IngestChunk", + ) + .await?; + } + + let end = messages::WsMessage::EndIngest { + unique_id: serial as u64, + n_chunks: n_chunks as u64, + }; + send_ws_message_now(write, encode_ws_binary(&end, "EndIngest")?, "EndIngest").await?; + + Ok(byte_count) +} + async fn persistent_connection( mut rx: tokio::sync::mpsc::Receiver, ) -> std::result::Result<(), String> { @@ -303,7 +374,7 @@ async fn persistent_connection( // Split the socket let (mut write, mut read) = socket.split(); let (socket_sender_tx, mut socket_sender_rx) = - tokio::sync::mpsc::channel::(32); + tokio::sync::mpsc::channel::(SOCKET_SENDER_QUEUE_DEPTH); let mut ping_interval = tokio::time::interval(Duration::from_secs(10)); let mut license_interval = tokio::time::interval(Duration::from_secs(60 * 15)); // 15 minutes let mut pending_history: HashMap< @@ -363,61 +434,11 @@ async fn persistent_connection( info!("Not permitted to send chunks yet"); continue 'message_pump; } - let n_chunks = chunks.len(); - let byte_count = chunks.iter().map(|c| c.len()).sum::(); - - // Send BeginIngest - let Ok((_, _, bytes)) = messages::WsMessage::BeginIngest { unique_id: serial as u64, n_chunks: n_chunks as u64 }.to_bytes() else { - error!("Failed to serialize BeginIngest message"); - break 'message_pump; - }; - if let Err(e) = socket_sender_tx.try_send(Message::Binary(bytes)) { - match e { - TrySendError::Full(_) => { - warn!("Send unavailable: BeginIngest queue full; dropping message"); - } - TrySendError::Closed(_) => { - error!("Failed to send BeginIngest message: channel closed"); - break 'message_pump; - } - } - } - - // Submit Each Chunk - for (i, chunk) in chunks.into_iter().enumerate() { - let Ok((_, _, bytes)) = messages::WsMessage::IngestChunk { unique_id: serial as u64, chunk: i as u64, n_chunks: n_chunks as u64, data: chunk }.to_bytes() else { - error!("Failed to serialize IngestChunk message"); - break 'message_pump; - }; - if let Err(e) = socket_sender_tx.try_send(Message::Binary(bytes)) { - match e { - TrySendError::Full(_) => { - warn!("Send unavailable: IngestChunk queue full; dropping chunk"); - } - TrySendError::Closed(_) => { - error!("Failed to send IngestChunk message: channel closed"); - break 'message_pump; - } - } - } - } - - // Send EndIngest - let Ok((_, _, bytes)) = messages::WsMessage::EndIngest { unique_id: serial as u64, n_chunks: n_chunks as u64 }.to_bytes() else { - error!("Failed to serialize EndIngest message"); + let Ok(byte_count) = + send_ingest_batch(&mut write, serial, chunks).await + else { break 'message_pump; }; - if let Err(e) = socket_sender_tx.try_send(Message::Binary(bytes)) { - match e { - TrySendError::Full(_) => { - warn!("Send unavailable: EndIngest queue full; dropping message"); - } - TrySendError::Closed(_) => { - error!("Failed to send EndIngest message: channel closed"); - break 'message_pump; - } - } - } debug!("Submitted {} bytes for ingestion", byte_count); } Some(ConnectionCommand::FetchHistory { request, responder }) => { @@ -1148,6 +1169,38 @@ async fn persistent_connection( } } +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn encode_ws_binary_round_trips_begin_ingest() { + let encoded = encode_ws_binary( + &messages::WsMessage::BeginIngest { + unique_id: 42, + n_chunks: 7, + }, + "BeginIngest", + ) + .expect("BeginIngest should encode"); + + let Message::Binary(bytes) = encoded else { + panic!("BeginIngest should encode to a binary websocket frame"); + }; + + match messages::WsMessage::from_bytes(&bytes).expect("BeginIngest should decode") { + messages::WsMessage::BeginIngest { + unique_id, + n_chunks, + } => { + assert_eq!(unique_id, 42); + assert_eq!(n_chunks, 7); + } + other => panic!("unexpected decoded message: {other:?}"), + } + } +} + async fn connect() -> anyhow::Result>> { let remote_host = crate::lts2_sys::lts2_client::get_remote_host(); let target = format!("wss://{}:443/shaper_gateway/ws", &remote_host); diff --git a/src/rust/lqosd/src/node_manager/local_api/scheduler.rs b/src/rust/lqosd/src/node_manager/local_api/scheduler.rs index 33062255..a9617019 100644 --- a/src/rust/lqosd/src/node_manager/local_api/scheduler.rs +++ b/src/rust/lqosd/src/node_manager/local_api/scheduler.rs @@ -424,8 +424,10 @@ mod tests { assert_eq!(status.updated_unix, Some(last_seen_unix)); assert!(!status.stale); assert_eq!(details.updated_unix, Some(last_seen_unix)); - assert!(details - .details - .contains(&format!("Last updated Unix: {last_seen_unix}"))); + assert!( + details + .details + .contains(&format!("Last updated Unix: {last_seen_unix}")) + ); } } diff --git a/src/rust/lqosd/src/tool_status.rs b/src/rust/lqosd/src/tool_status.rs index 7528b55e..dfe659ec 100644 --- a/src/rust/lqosd/src/tool_status.rs +++ b/src/rust/lqosd/src/tool_status.rs @@ -86,11 +86,7 @@ pub fn is_scheduler_available() -> bool { /// Returns the Unix timestamp of the scheduler's last heartbeat, if one has been seen. pub fn scheduler_last_seen_unix() -> Option { let last = SCHEDULER_LAST_SEEN.load(Ordering::Relaxed); - if last == 0 { - None - } else { - Some(last) - } + if last == 0 { None } else { Some(last) } } /// Returns the current scheduler error message, if any. -- knotmirror 0.0.1 From 6ef3abe39330764dc8d98f4b12eb7e4371e01937 Mon Sep 17 00:00:00 2001 From: Name <2718612@2178972821991.net> Date: Sun, 19 Apr 2026 14:13:18 -0600 Subject: [PATCH 06/51] changes --- docs-es/v2.0/troubleshooting-es.md | 4 + docs/v2.0/troubleshooting.md | 4 + src/scheduler.py | 169 +++++++++++++++++++++++++++++ src/test_scheduler.py | 120 +++++++++++++++++++- 4 files changed, 292 insertions(+), 5 deletions(-) diff --git a/docs-es/v2.0/troubleshooting-es.md b/docs-es/v2.0/troubleshooting-es.md index b2befc84..16f6b3d5 100644 --- a/docs-es/v2.0/troubleshooting-es.md +++ b/docs-es/v2.0/troubleshooting-es.md @@ -137,6 +137,8 @@ Si oscila entre ready/error, valide credenciales y timeouts de integración en ` Si el shaping de arranque comienza antes de que topology runtime publique la generación actual de `shaping_inputs.json`, las versiones actuales mantienen el scheduler en un estado de espera de arranque y reintentan el shaping inicial cada pocos segundos. Un mensaje breve como `still building outputs for the current source generation` justo después de reiniciar normalmente significa que LibreQoS todavía está terminando el ciclo de importación y publicación de runtime, no que el shaping quede detenido hasta la siguiente actualización de 30 minutos. +Si una actualización programada de integración cae mientras topology runtime todavía está publicando salidas para la nueva generación de fuente, las versiones actuales mantienen el scheduler en estado de espera para esa generación y reintentan automáticamente el shaping programado en cuanto topology runtime termina. Trate `Scheduled shaping refresh deferred` como una espera transitoria solo cuando el mensaje indique que topology runtime todavía está construyendo salidas para la generación actual. Si en cambio indica que topology runtime falló para la generación actual, revise directamente esa falla de runtime. + Si el arranque del scheduler permanece demasiado tiempo en esa espera, o entra en estado degradado con un mensaje indicando que topology runtime falló para la generación actual, revise: ```bash @@ -146,6 +148,8 @@ journalctl -u lqos_scheduler --since "30 minutes ago" journalctl -u lqosd --since "30 minutes ago" ``` +Si `journalctl -u lqosd` muestra advertencias repetidas como `BeginIngest queue full`, `IngestChunk queue full` o `EndIngest queue full` durante el arranque o justo después de una importación de topología, los builds anteriores estaban descartando tramas de ingesta hacia Insight porque la cola local del canal de control era demasiado pequeña para ráfagas grandes. Los builds actuales aplican backpressure sobre el socket de Insight para esos lotes de ingesta, por lo que esas advertencias ya no deberían aparecer durante ráfagas cortas de arranque o importación. Si siguen apareciendo después de actualizar, revise primero la presión de CPU de `lqosd` y la conectividad reciente del canal de control antes de asumir que el shaping está fallando. + ### RTNETLINK answers: Invalid argument Suele indicar que no se pudo agregar correctamente qdisc MQ en la NIC (colas RX/TX insuficientes). Verifique [NICs recomendadas](requirements-es.md). diff --git a/docs/v2.0/troubleshooting.md b/docs/v2.0/troubleshooting.md index 9c341feb..527bd19a 100644 --- a/docs/v2.0/troubleshooting.md +++ b/docs/v2.0/troubleshooting.md @@ -156,6 +156,8 @@ Routine package upgrades now keep `lqosd` in charge of the main WebUI when `/etc If startup shaping begins before topology runtime has finished publishing the current generation of `shaping_inputs.json`, current builds keep the scheduler in a startup wait state and retry the initial shaping pass every few seconds. A short `still building outputs for the current source generation` message right after restart now usually means LibreQoS is still finishing the import/runtime publish cycle, not that shaping is stuck until the next 30-minute refresh. +If a scheduled integration refresh lands while topology runtime is still publishing outputs for the new source generation, current builds keep the scheduler in a waiting state for that generation and retry the scheduled shaping refresh automatically as soon as topology runtime finishes. Treat `Scheduled shaping refresh deferred` as a transient wait only when the message says topology runtime is still building outputs for the current generation. If the message instead says topology runtime failed for the current generation, investigate that runtime failure directly. + If scheduler startup stays in that wait state for an unusually long time, or degrades with a message that topology runtime failed for the current generation, inspect: ```bash @@ -175,6 +177,8 @@ cat /opt/libreqos/src/network.insight.debug.json Treat `network.insight.debug.json` as a troubleshooting snapshot only; do not edit it. +If `journalctl -u lqosd` shows repeated `BeginIngest queue full`, `IngestChunk queue full`, or `EndIngest queue full` warnings during startup or immediately after a topology import, older builds were dropping Insight ingest frames because the node's outbound control-channel queue was too small for burst uploads. Current builds apply backpressure on the Insight socket for ingest batches instead, so those warnings should no longer be expected during short import/startup bursts. If they still appear after upgrading, inspect recent `lqosd` CPU pressure and control-channel connectivity before assuming shaping itself is unhealthy. + If specific APs or switches appear multiple times with suffixed names such as `... [AP deadbeef]`, check whether UISP is returning duplicate rows for the same device ID. Current builds defensively deduplicate raw UISP devices by `identification.id` before topology graph construction, and skip any residual duplicate device IDs during graph assembly. If an integration subprocess fails, current builds keep the scheduler alive, publish a shortened output preview to the scheduler status/error surfaces, and save the full captured output to a timestamped file under `/tmp` such as `lqos_scheduler_uisp_integration_YYYYMMDD_HHMMSS.log`. diff --git a/src/scheduler.py b/src/scheduler.py index b966be7b..12e18959 100644 --- a/src/scheduler.py +++ b/src/scheduler.py @@ -34,6 +34,7 @@ INTEGRATION_FAILURE_PREVIEW_LINES = 30 INTEGRATION_FAILURE_PREVIEW_CHARS = 4000 TOPOLOGY_RUNTIME_REFRESH_SECONDS = 3 STARTUP_TOPOLOGY_RUNTIME_MAX_WAIT_SECONDS = 120 +PARTIAL_TOPOLOGY_RUNTIME_MAX_WAIT_SECONDS = 120 SCHEDULER_STARTUP_STEP_COUNT = 5 SCHEDULER_REFRESH_STEP_COUNT = 4 scheduler_status_bus_enabled = True @@ -41,6 +42,10 @@ startup_topology_runtime_pending = False startup_topology_runtime_generation = None startup_topology_runtime_started_monotonic = None startup_topology_runtime_last_report_state = None +partial_topology_runtime_pending = False +partial_topology_runtime_generation = None +partial_topology_runtime_started_monotonic = None +partial_topology_runtime_last_report_state = None def configure_scheduler_stdio(): @@ -1045,6 +1050,10 @@ def importAndShapePartialReload(): ) publish_scheduler_progress(True, "partial_topology_runtime", "Refreshing topology runtime", 3, SCHEDULER_REFRESH_STEP_COUNT) if not ensure_topology_runtime_process(wait_for_outputs=True): + ready, detail, generation = topology_runtime_readiness_detail() + if not ready and _topology_runtime_not_ready_is_transient(detail): + _begin_partial_topology_runtime_wait(generation) + return report_topology_runtime_not_ready( "Scheduled shaping refresh deferred", phase_label="Scheduler waiting for topology runtime", @@ -1195,6 +1204,18 @@ def _reset_startup_topology_runtime_wait(): startup_topology_runtime_last_report_state = None +def _reset_partial_topology_runtime_wait(): + global partial_topology_runtime_pending + global partial_topology_runtime_generation + global partial_topology_runtime_started_monotonic + global partial_topology_runtime_last_report_state + + partial_topology_runtime_pending = False + partial_topology_runtime_generation = None + partial_topology_runtime_started_monotonic = None + partial_topology_runtime_last_report_state = None + + def _topology_runtime_not_ready_is_transient(detail: str) -> bool: detail_text = str(detail or "").strip() if detail_text.startswith("Topology runtime failed for the current source generation:"): @@ -1246,6 +1267,50 @@ def _begin_startup_topology_runtime_wait(generation: str | None): _publish_startup_topology_runtime_wait(generation_token) +def _publish_partial_topology_runtime_wait(generation: str | None): + global partial_topology_runtime_last_report_state + + generation_token = str(generation or "").strip() or "unknown" + state = ("waiting", generation_token) + if partial_topology_runtime_last_report_state == state: + return + partial_topology_runtime_last_report_state = state + if generation_token != "unknown": + print( + "Scheduled shaping refresh waiting for topology runtime outputs for " + f"generation {generation_token[:12]}." + ) + else: + print("Scheduled shaping refresh waiting for topology runtime outputs.") + publish_scheduler_progress( + True, + "waiting_for_topology_runtime", + "Waiting for topology runtime", + 3, + SCHEDULER_REFRESH_STEP_COUNT, + percent=75, + ) + + +def _begin_partial_topology_runtime_wait(generation: str | None): + global partial_topology_runtime_pending + global partial_topology_runtime_generation + global partial_topology_runtime_started_monotonic + global partial_topology_runtime_last_report_state + + generation_token = str(generation or "").strip() or None + now = time.monotonic() + if ( + not partial_topology_runtime_pending + or partial_topology_runtime_generation != generation_token + ): + partial_topology_runtime_pending = True + partial_topology_runtime_generation = generation_token + partial_topology_runtime_started_monotonic = now + partial_topology_runtime_last_report_state = None + _publish_partial_topology_runtime_wait(generation_token) + + def _continue_startup_topology_runtime_wait(): global shaping_runtime_hash global startup_topology_runtime_generation @@ -1337,6 +1402,106 @@ def _continue_startup_topology_runtime_wait(): ) +def _continue_partial_topology_runtime_wait(): + global shaping_runtime_hash + global partial_topology_runtime_generation + global partial_topology_runtime_started_monotonic + global partial_topology_runtime_last_report_state + + ready, detail, generation = topology_runtime_readiness_detail() + generation_token = str(generation or "").strip() or None + now = time.monotonic() + + if generation_token != partial_topology_runtime_generation: + partial_topology_runtime_generation = generation_token + partial_topology_runtime_started_monotonic = now + partial_topology_runtime_last_report_state = None + + if ready: + publish_scheduler_progress( + True, + "partial_runtime_hash", + "Checking shaping inputs", + 4, + SCHEDULER_REFRESH_STEP_COUNT, + ) + new_hash = calculate_shaping_runtime_hash() + if new_hash == 0: + _reset_partial_topology_runtime_wait() + report_scheduler_runtime_failure( + "Scheduled shaping refresh failed", + RuntimeError( + "Shaping runtime hash was not published after topology runtime became ready." + ), + ) + return + if new_hash != shaping_runtime_hash: + publish_scheduler_progress( + True, + "partial_reload", + "Applying incremental shaper refresh", + 4, + SCHEDULER_REFRESH_STEP_COUNT, + ) + try: + refreshShapers() + except ValidationFailure as e: + _reset_partial_topology_runtime_wait() + report_scheduler_validation_failure( + "Scheduled shaping refresh blocked by validation", + e, + ) + return + except Exception as e: + _reset_partial_topology_runtime_wait() + report_scheduler_runtime_failure("Scheduled shaping refresh failed", e) + return + shaping_runtime_hash = calculate_shaping_runtime_hash() + if shaping_runtime_hash == 0: + _reset_partial_topology_runtime_wait() + report_scheduler_runtime_failure( + "Scheduled shaping refresh failed", + RuntimeError( + "Shaping runtime hash was not published after scheduled refresh." + ), + ) + return + _reset_partial_topology_runtime_wait() + clear_scheduler_error() + publish_scheduler_progress( + False, + "ready", + "Scheduler ready", + SCHEDULER_REFRESH_STEP_COUNT, + SCHEDULER_REFRESH_STEP_COUNT, + percent=100, + ) + return + + started = partial_topology_runtime_started_monotonic + if started is None: + partial_topology_runtime_started_monotonic = now + started = now + elapsed = max(0.0, now - started) + + if ( + _topology_runtime_not_ready_is_transient(detail) + and elapsed < PARTIAL_TOPOLOGY_RUNTIME_MAX_WAIT_SECONDS + ): + _publish_partial_topology_runtime_wait(generation_token) + return + + state = ("degraded", str(detail or "").strip(), generation_token or "") + if partial_topology_runtime_last_report_state == state: + return + partial_topology_runtime_last_report_state = state + report_topology_runtime_not_ready( + "Scheduled shaping refresh deferred", + phase_label="Scheduler waiting for topology runtime", + step_count=SCHEDULER_REFRESH_STEP_COUNT, + ) + + def wait_for_topology_runtime_ready(timeout_seconds=8.0): deadline = time.monotonic() + timeout_seconds while time.monotonic() < deadline: @@ -1360,6 +1525,10 @@ def topology_runtime_refresh_tick(): _continue_startup_topology_runtime_wait() return + if partial_topology_runtime_pending: + _continue_partial_topology_runtime_wait() + return + if shaping_runtime_hash == 0: return diff --git a/src/test_scheduler.py b/src/test_scheduler.py index c9cbe0a3..e69deb3f 100644 --- a/src/test_scheduler.py +++ b/src/test_scheduler.py @@ -195,6 +195,7 @@ class TestSchedulerErrorReporting(unittest.TestCase): def setUp(self): scheduler.set_scheduler_status_bus_enabled(True) scheduler._reset_startup_topology_runtime_wait() + scheduler._reset_partial_topology_runtime_wait() scheduler.shaping_runtime_hash = 0 def test_python_integration_output_does_not_set_scheduler_error(self): @@ -294,6 +295,12 @@ class TestSchedulerErrorReporting(unittest.TestCase): class TestSchedulerLogging(unittest.TestCase): + def setUp(self): + scheduler.set_scheduler_status_bus_enabled(True) + scheduler._reset_startup_topology_runtime_wait() + scheduler._reset_partial_topology_runtime_wait() + scheduler.shaping_runtime_hash = 0 + def test_configure_scheduler_stdio_enables_line_buffering_when_supported(self): class FakeStream: def __init__(self): @@ -452,6 +459,41 @@ class TestSchedulerLogging(unittest.TestCase): ) ) + def test_topology_runtime_refresh_tick_waits_for_partial_runtime_outputs(self): + scheduler.partial_topology_runtime_pending = True + scheduler.partial_topology_runtime_generation = "generation-1" + scheduler.partial_topology_runtime_started_monotonic = scheduler.time.monotonic() + scheduler.shaping_runtime_hash = 4 + + with patch.object( + scheduler, + "topology_runtime_readiness_detail", + return_value=( + False, + "Topology runtime is still building outputs for the current source generation.", + "generation-1", + ), + ): + with patch.object(scheduler, "publish_scheduler_progress") as mock_progress: + with patch.object(scheduler, "refreshShapers") as mock_refresh: + with patch.object(scheduler, "scheduler_error") as mock_scheduler_error: + with patch("builtins.print"): + scheduler.topology_runtime_refresh_tick() + + mock_refresh.assert_not_called() + mock_scheduler_error.assert_not_called() + self.assertTrue(scheduler.partial_topology_runtime_pending) + self.assertTrue( + any( + call.args[:3] == ( + True, + "waiting_for_topology_runtime", + "Waiting for topology runtime", + ) + for call in mock_progress.call_args_list + ) + ) + def test_topology_runtime_refresh_tick_completes_startup_when_runtime_ready(self): scheduler.startup_topology_runtime_pending = True scheduler.startup_topology_runtime_generation = "generation-1" @@ -506,6 +548,43 @@ class TestSchedulerLogging(unittest.TestCase): self.assertEqual(scheduler.shaping_runtime_hash, 9) self.assertFalse(scheduler.startup_topology_runtime_pending) + def test_topology_runtime_refresh_tick_completes_partial_wait_when_runtime_ready(self): + scheduler.partial_topology_runtime_pending = True + scheduler.partial_topology_runtime_generation = "generation-1" + scheduler.partial_topology_runtime_started_monotonic = scheduler.time.monotonic() + scheduler.shaping_runtime_hash = 1 + + with patch.object( + scheduler, + "topology_runtime_readiness_detail", + return_value=(True, "", "generation-1"), + ): + with patch.object(scheduler, "refreshShapers") as mock_refresh: + with patch.object( + scheduler, + "calculate_shaping_runtime_hash", + side_effect=[9, 9], + ): + with patch.object(scheduler, "publish_scheduler_progress") as mock_progress: + with patch.object(scheduler, "clear_scheduler_error") as mock_clear_error: + with patch("builtins.print"): + scheduler.topology_runtime_refresh_tick() + + mock_refresh.assert_called_once() + mock_clear_error.assert_called_once() + self.assertEqual(scheduler.shaping_runtime_hash, 9) + self.assertFalse(scheduler.partial_topology_runtime_pending) + self.assertTrue( + any( + call.args[:3] == ( + False, + "ready", + "Scheduler ready", + ) + for call in mock_progress.call_args_list + ) + ) + def test_import_and_shape_full_reload_reenables_status_bus_after_success(self): scheduler.set_scheduler_status_bus_enabled(False) @@ -763,6 +842,7 @@ class TestTopologyRuntimeReadiness(unittest.TestCase): class TestTopologyRuntimeGating(unittest.TestCase): def setUp(self): scheduler._reset_startup_topology_runtime_wait() + scheduler._reset_partial_topology_runtime_wait() scheduler.shaping_runtime_hash = 0 def test_full_reload_skips_refresh_when_topology_runtime_not_ready(self): @@ -777,13 +857,43 @@ class TestTopologyRuntimeGating(unittest.TestCase): mock_report.assert_not_called() self.assertTrue(scheduler.startup_topology_runtime_pending) - def test_partial_reload_skips_refresh_when_topology_runtime_not_ready(self): + def test_partial_reload_waits_when_topology_runtime_not_ready(self): with patch.object(scheduler, "importFromCRM"): with patch.object(scheduler, "ensure_topology_runtime_process", return_value=False): - with patch.object(scheduler, "report_topology_runtime_not_ready") as mock_report: - with patch.object(scheduler, "refreshShapers") as mock_refresh: - with patch.object(scheduler, "publish_scheduler_progress"): - scheduler.importAndShapePartialReload() + with patch.object( + scheduler, + "topology_runtime_readiness_detail", + return_value=( + False, + "Topology runtime is still building outputs for the current source generation.", + "generation-1", + ), + ): + with patch.object(scheduler, "report_topology_runtime_not_ready") as mock_report: + with patch.object(scheduler, "refreshShapers") as mock_refresh: + with patch.object(scheduler, "publish_scheduler_progress"): + scheduler.importAndShapePartialReload() + + mock_refresh.assert_not_called() + mock_report.assert_not_called() + self.assertTrue(scheduler.partial_topology_runtime_pending) + + def test_partial_reload_reports_runtime_failure_when_topology_runtime_failed(self): + with patch.object(scheduler, "importFromCRM"): + with patch.object(scheduler, "ensure_topology_runtime_process", return_value=False): + with patch.object( + scheduler, + "topology_runtime_readiness_detail", + return_value=( + False, + "Topology runtime failed for the current source generation: publish failed", + "generation-1", + ), + ): + with patch.object(scheduler, "report_topology_runtime_not_ready") as mock_report: + with patch.object(scheduler, "refreshShapers") as mock_refresh: + with patch.object(scheduler, "publish_scheduler_progress"): + scheduler.importAndShapePartialReload() mock_refresh.assert_not_called() mock_report.assert_called_once() -- knotmirror 0.0.1 From ab7c9531ae6529ec7f52eb0f46985b62de000925 Mon Sep 17 00:00:00 2001 From: Name <2718612@2178972821991.net> Date: Sun, 19 Apr 2026 14:58:25 -0600 Subject: [PATCH 07/51] changes --- .../src/node_manager/js_build/src/circuit.js | 138 +++++++++++++++++- .../src/node_manager/static2/node_manager.css | 68 +++++++++ 2 files changed, 204 insertions(+), 2 deletions(-) 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 7a6f5c85..2e93c16c 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 @@ -1580,6 +1580,38 @@ let topAsnSortColumn = 'rate'; let topAsnSortDirection = 'desc'; let trafficCurrentPage = 1; let trafficPageSize = DEFAULT_TRAFFIC_PAGE_SIZE; +const TOP_ASN_TABLE_COLUMNS = [ + { group: "attribution" }, + { group: "attribution" }, + { group: "rates", numeric: true }, + { group: "rates", numeric: true }, + { group: "quality", numeric: true }, + { group: "quality", numeric: true }, + { group: "quality", numeric: true }, + { group: "quality", numeric: true }, + { group: "quality", numeric: true }, + { group: "quality", numeric: true }, + { group: "flows", numeric: true }, +]; +const TRAFFIC_TABLE_COLUMNS = [ + { group: "identity" }, + { group: "rates", numeric: true }, + { group: "rates", numeric: true }, + { group: "volume", numeric: true }, + { group: "volume", numeric: true }, + { group: "volume", numeric: true }, + { group: "volume", numeric: true }, + { group: "quality", numeric: true }, + { group: "quality", numeric: true }, + { group: "quality", numeric: true }, + { group: "quality", numeric: true }, + { group: "quality", numeric: true }, + { group: "quality", numeric: true }, + { group: "attribution" }, + { group: "attribution" }, + { group: "attribution" }, + { group: "actions", action: true }, +]; function formatQooScore(score0to100, fallback = "-") { if (score0to100 === null || score0to100 === undefined) { @@ -1630,6 +1662,106 @@ function truncatedTrafficCell(text, cellClass) { return td; } +function applyCircuitTableCellChrome(cell, columns, startIndex, endIndex) { + const descriptor = columns[startIndex]; + if (!descriptor) { + return; + } + + const group = String(descriptor.group || "default"); + cell.classList.add("lqos-circuit-table-cell", `lqos-circuit-colgroup-${group}`); + if (descriptor.numeric) { + cell.classList.add("lqos-circuit-cell-numeric"); + } + if (descriptor.action) { + cell.classList.add("lqos-circuit-cell-action"); + } + + if (startIndex > 0 && columns[startIndex - 1]?.group !== group) { + cell.classList.add("lqos-circuit-col-start"); + } + if (endIndex < columns.length - 1 && columns[endIndex + 1]?.group !== group) { + cell.classList.add("lqos-circuit-col-end"); + } + + cell.dataset.columnStart = String(startIndex); + cell.dataset.columnEnd = String(endIndex); +} + +function annotateCircuitDataTable(table, columns) { + const headRow = table.tHead?.rows?.[0]; + if (headRow) { + let columnIndex = 0; + Array.from(headRow.cells).forEach((cell) => { + const span = Math.max(1, Number(cell.colSpan) || 1); + const startIndex = columnIndex; + const endIndex = Math.min(columns.length - 1, startIndex + span - 1); + applyCircuitTableCellChrome(cell, columns, startIndex, endIndex); + columnIndex += span; + }); + } + + Array.from(table.tBodies).forEach((tbody) => { + Array.from(tbody.rows).forEach((row) => { + if (row.cells.length !== columns.length) { + return; + } + Array.from(row.cells).forEach((cell, index) => { + applyCircuitTableCellChrome(cell, columns, index, index); + }); + }); + }); + + wireCircuitDataTableHover(table); +} + +function wireCircuitDataTableHover(table) { + let activeStart = null; + let activeEnd = null; + + const paintRange = (start, end) => { + Array.from(table.querySelectorAll("[data-column-start][data-column-end]")).forEach((cell) => { + const cellStart = Number.parseInt(cell.dataset.columnStart || "", 10); + const cellEnd = Number.parseInt(cell.dataset.columnEnd || "", 10); + const shouldHighlight = Number.isFinite(cellStart) + && Number.isFinite(cellEnd) + && cellStart <= end + && cellEnd >= start; + cell.classList.toggle("is-column-hover", shouldHighlight); + }); + }; + + const clearRange = () => { + activeStart = null; + activeEnd = null; + Array.from(table.querySelectorAll(".is-column-hover")).forEach((cell) => { + cell.classList.remove("is-column-hover"); + }); + }; + + table.addEventListener("pointerover", (event) => { + const cell = event.target.closest("th, td"); + if (!cell || !table.contains(cell)) { + return; + } + const start = Number.parseInt(cell.dataset.columnStart || "", 10); + const end = Number.parseInt(cell.dataset.columnEnd || "", 10); + if (!Number.isFinite(start) || !Number.isFinite(end)) { + return; + } + if (activeStart === start && activeEnd === end) { + return; + } + activeStart = start; + activeEnd = end; + paintRange(start, end); + }); + + table.addEventListener("pointerleave", () => { + clearRange(); + }); +} + function visibleTrafficRows() { return Array.isArray(latestTrafficPage?.rows) ? latestTrafficPage.rows : []; } @@ -1735,7 +1867,7 @@ function renderTopAsnTab() { tableWrap.classList.add("lqos-table-wrap"); const table = document.createElement("table"); - table.classList.add("lqos-table", "lqos-table-tight", "lqos-circuit-traffic-table"); + table.classList.add("lqos-table", "lqos-table-tight", "lqos-circuit-traffic-table", "lqos-circuit-data-table"); const thead = document.createElement("thead", "small"); thead.style.fontSize = "0.8em"; @@ -1797,6 +1929,7 @@ function renderTopAsnTab() { } table.appendChild(tbody); + annotateCircuitDataTable(table, TOP_ASN_TABLE_COLUMNS); tableWrap.appendChild(table); clearDiv(target); target.appendChild(tableWrap); @@ -1818,7 +1951,7 @@ function renderTrafficTab() { tableWrap.classList.add("lqos-table-wrap"); let table = document.createElement("table"); - table.classList.add("lqos-table", "lqos-table-tight", "lqos-circuit-traffic-table"); + table.classList.add("lqos-table", "lqos-table-tight", "lqos-circuit-traffic-table", "lqos-circuit-data-table"); let thead = document.createElement("thead", "small"); thead.style.fontSize = "0.8em"; @@ -1903,6 +2036,7 @@ function renderTrafficTab() { } table.appendChild(tbody); + annotateCircuitDataTable(table, TRAFFIC_TABLE_COLUMNS); tableWrap.appendChild(table); clearDiv(target); target.appendChild(tableWrap); diff --git a/src/rust/lqosd/src/node_manager/static2/node_manager.css b/src/rust/lqosd/src/node_manager/static2/node_manager.css index 4ec8c8c1..8d0aa92c 100644 --- a/src/rust/lqosd/src/node_manager/static2/node_manager.css +++ b/src/rust/lqosd/src/node_manager/static2/node_manager.css @@ -1567,6 +1567,74 @@ h5 { max-width: 100%; } +.lqos-circuit-data-table th, +.lqos-circuit-data-table td { + --lqos-circuit-group-tint: transparent; + --lqos-circuit-hover-tint: transparent; + background-image: + linear-gradient(var(--lqos-circuit-hover-tint), var(--lqos-circuit-hover-tint)), + linear-gradient(var(--lqos-circuit-group-tint), var(--lqos-circuit-group-tint)); + background-clip: padding-box; + transition: + background-color 140ms ease, + border-color 140ms ease, + box-shadow 140ms ease; +} + +.lqos-circuit-data-table thead th + th, +.lqos-circuit-data-table tbody td + td { + border-left: 1px solid color-mix(in srgb, var(--lqos-border) 42%, transparent); +} + +.lqos-circuit-data-table .lqos-circuit-col-start { + border-left-color: color-mix(in srgb, var(--lqos-border) 92%, transparent); +} + +.lqos-circuit-data-table .lqos-circuit-colgroup-identity, +.lqos-circuit-data-table .lqos-circuit-colgroup-actions { + --lqos-circuit-group-tint: color-mix(in srgb, var(--lqos-surface) 14%, transparent); +} + +.lqos-circuit-data-table .lqos-circuit-colgroup-rates { + --lqos-circuit-group-tint: color-mix(in srgb, var(--bs-info) 7%, transparent); +} + +.lqos-circuit-data-table .lqos-circuit-colgroup-volume { + --lqos-circuit-group-tint: color-mix(in srgb, #d39f37 7%, transparent); +} + +.lqos-circuit-data-table .lqos-circuit-colgroup-quality { + --lqos-circuit-group-tint: color-mix(in srgb, #2b8a57 7%, transparent); +} + +.lqos-circuit-data-table .lqos-circuit-colgroup-attribution, +.lqos-circuit-data-table .lqos-circuit-colgroup-flows { + --lqos-circuit-group-tint: color-mix(in srgb, var(--bs-secondary-color) 8%, transparent); +} + +.lqos-circuit-data-table .lqos-circuit-cell-numeric { + text-align: right; + font-variant-numeric: tabular-nums; +} + +.lqos-circuit-data-table .lqos-circuit-cell-action { + text-align: center; +} + +.lqos-circuit-data-table .is-column-hover { + --lqos-circuit-hover-tint: rgba(255, 255, 255, 0.035); + box-shadow: + inset 0 1px 0 rgba(255, 255, 255, 0.05), + inset 0 0 0 1px color-mix(in srgb, var(--lqos-border) 70%, transparent); +} + +[data-bs-theme="light"] .lqos-circuit-data-table .is-column-hover { + --lqos-circuit-hover-tint: rgba(17, 29, 45, 0.045); + box-shadow: + inset 0 1px 0 rgba(255, 255, 255, 0.28), + inset 0 0 0 1px color-mix(in srgb, var(--lqos-border) 74%, transparent); +} + .lqos-tree-stack { display: flex; flex-direction: column; -- knotmirror 0.0.1 From 392f122cd3485a472af2c3803887baf471b12401 Mon Sep 17 00:00:00 2001 From: rchac Date: Sun, 19 Apr 2026 20:28:56 -0600 Subject: [PATCH 08/51] changes --- src/scheduler.py | 40 ++++++++++- src/test_scheduler.py | 153 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 191 insertions(+), 2 deletions(-) diff --git a/src/scheduler.py b/src/scheduler.py index 12e18959..2a0bcea0 100644 --- a/src/scheduler.py +++ b/src/scheduler.py @@ -4,7 +4,7 @@ import csv import io import json import chardet -from LibreQoS import ValidationFailure, refreshShapers, refreshShapersUpdateOnly +from LibreQoS import RefreshFailure, ValidationFailure, refreshShapers, refreshShapersUpdateOnly import subprocess import sys import tempfile @@ -1026,7 +1026,12 @@ def importAndShapeFullReload(): return False publish_scheduler_progress(True, "initial_shaping_reload", "Refreshing shaper state", 5, SCHEDULER_STARTUP_STEP_COUNT) if not enable_insight_topology(): - refreshShapers() + try: + refreshShapers() + except Exception as e: + if _defer_stale_shaping_inputs_failure(e, startup=True): + return False + raise shaping_runtime_hash = calculate_shaping_runtime_hash() else: shaping_runtime_hash = calculate_shaping_runtime_hash() @@ -1072,6 +1077,8 @@ def importAndShapePartialReload(): report_scheduler_validation_failure("Scheduled shaping refresh blocked by validation", e) return except Exception as e: + if _defer_stale_shaping_inputs_failure(e, startup=False): + return report_scheduler_runtime_failure("Scheduled shaping refresh failed", e) return shaping_runtime_hash = calculate_shaping_runtime_hash() @@ -1223,6 +1230,29 @@ def _topology_runtime_not_ready_is_transient(detail: str) -> bool: return True +def _is_transient_stale_shaping_inputs_failure(exc: Exception) -> bool: + if not isinstance(exc, RefreshFailure): + return False + detail = str(exc or "").strip() + return detail.startswith("Missing or stale shaping_inputs.json.") + + +def _defer_stale_shaping_inputs_failure(exc: Exception, *, startup: bool) -> bool: + if not _is_transient_stale_shaping_inputs_failure(exc): + return False + + ready, detail, generation = topology_runtime_readiness_detail() + if detail and not _topology_runtime_not_ready_is_transient(detail): + return False + + clear_scheduler_error() + if startup: + _begin_startup_topology_runtime_wait(generation if not ready else current_topology_source_generation()) + else: + _begin_partial_topology_runtime_wait(generation if not ready else current_topology_source_generation()) + return True + + def _publish_startup_topology_runtime_wait(generation: str | None): global startup_topology_runtime_last_report_state @@ -1349,6 +1379,8 @@ def _continue_startup_topology_runtime_wait(): shaping_runtime_hash = 0 return except Exception as e: + if _defer_stale_shaping_inputs_failure(e, startup=True): + return _reset_startup_topology_runtime_wait() report_scheduler_runtime_failure( "Scheduler startup shaping refresh failed", @@ -1453,6 +1485,8 @@ def _continue_partial_topology_runtime_wait(): ) return except Exception as e: + if _defer_stale_shaping_inputs_failure(e, startup=False): + return _reset_partial_topology_runtime_wait() report_scheduler_runtime_failure("Scheduled shaping refresh failed", e) return @@ -1546,6 +1580,8 @@ def topology_runtime_refresh_tick(): report_scheduler_validation_failure("Topology runtime refresh blocked by validation", e) return except Exception as e: + if _defer_stale_shaping_inputs_failure(e, startup=False): + return report_scheduler_runtime_failure("Topology runtime refresh failed", e) return shaping_runtime_hash = calculate_shaping_runtime_hash() diff --git a/src/test_scheduler.py b/src/test_scheduler.py index e69deb3f..7c43ae5f 100644 --- a/src/test_scheduler.py +++ b/src/test_scheduler.py @@ -22,8 +22,11 @@ scheduler = None def install_scheduler_stubs(): libre = types.ModuleType("LibreQoS") + class RefreshFailure(Exception): + pass class ValidationFailure(Exception): pass + libre.RefreshFailure = RefreshFailure libre.ValidationFailure = ValidationFailure libre.refreshShapers = Mock() libre.refreshShapersUpdateOnly = Mock() @@ -377,6 +380,55 @@ class TestSchedulerLogging(unittest.TestCase): "Topology runtime refresh failed: bad runtime" ) + def test_topology_runtime_refresh_tick_waits_for_stale_shaping_inputs(self): + stale_exc = scheduler.RefreshFailure( + "Missing or stale shaping_inputs.json. Run topology runtime before shaping." + ) + + with patch.object(scheduler, "ensure_topology_runtime_process"): + with patch.object( + scheduler, + "topology_runtime_readiness_detail", + return_value=(True, "", "generation-1"), + ): + with patch.object( + scheduler, + "current_topology_source_generation", + return_value="generation-1", + ): + with patch.object(scheduler, "calculate_shaping_runtime_hash", return_value=5): + with patch.object( + scheduler, + "refreshShapers", + side_effect=stale_exc, + ): + with patch.object(scheduler, "clear_scheduler_error") as mock_clear_error: + with patch.object( + scheduler, + "report_scheduler_runtime_failure", + ) as mock_report: + with patch.object( + scheduler, + "publish_scheduler_progress", + ) as mock_progress: + with patch("builtins.print"): + scheduler.shaping_runtime_hash = 1 + scheduler.topology_runtime_refresh_tick() + + mock_clear_error.assert_called_once() + mock_report.assert_not_called() + self.assertTrue(scheduler.partial_topology_runtime_pending) + self.assertTrue( + any( + call.args[:3] == ( + True, + "waiting_for_topology_runtime", + "Waiting for topology runtime", + ) + for call in mock_progress.call_args_list + ) + ) + def test_topology_runtime_refresh_tick_reports_validation_failure(self): validation_exc = scheduler.ValidationFailure("Validation failed. Will now exit.") @@ -689,6 +741,59 @@ class TestSchedulerLogging(unittest.TestCase): ) ) + def test_partial_reload_waits_for_stale_shaping_inputs(self): + stale_exc = scheduler.RefreshFailure( + "Missing or stale shaping_inputs.json. Run topology runtime before shaping." + ) + + with patch.object(scheduler, "importFromCRM"): + with patch.object(scheduler, "ensure_topology_runtime_process", return_value=True): + with patch.object(scheduler, "calculate_shaping_runtime_hash", return_value=2): + with patch.object(scheduler, "shaping_runtime_hash", 1): + with patch.object( + scheduler, + "topology_runtime_readiness_detail", + return_value=(True, "", "generation-1"), + ): + with patch.object( + scheduler, + "current_topology_source_generation", + return_value="generation-1", + ): + with patch.object( + scheduler, + "refreshShapers", + side_effect=stale_exc, + ): + with patch.object( + scheduler, + "clear_scheduler_error", + ) as mock_clear_error: + with patch.object( + scheduler, + "report_scheduler_runtime_failure", + ) as mock_report: + with patch.object( + scheduler, + "publish_scheduler_progress", + ) as mock_progress: + with patch("builtins.print"): + scheduler.importAndShapePartialReload() + + mock_clear_error.assert_called_once() + mock_report.assert_not_called() + self.assertTrue(scheduler.partial_topology_runtime_pending) + self.assertTrue( + any( + call.args[:3] == ( + True, + "waiting_for_topology_runtime", + "Waiting for topology runtime", + ) + for call in mock_progress.call_args_list + ) + ) + class TestTopologyRuntimeReadiness(unittest.TestCase): def test_missing_status_is_not_ready(self): @@ -898,6 +1003,54 @@ class TestTopologyRuntimeGating(unittest.TestCase): mock_refresh.assert_not_called() mock_report.assert_called_once() + def test_full_reload_waits_for_stale_shaping_inputs(self): + stale_exc = scheduler.RefreshFailure( + "Missing or stale shaping_inputs.json. Run topology runtime before shaping." + ) + + with patch.object(scheduler, "importFromCRM"): + with patch.object(scheduler, "ensure_topology_runtime_process", return_value=True): + with patch.object(scheduler, "enable_insight_topology", return_value=False): + with patch.object( + scheduler, + "topology_runtime_readiness_detail", + return_value=(True, "", "generation-1"), + ): + with patch.object( + scheduler, + "current_topology_source_generation", + return_value="generation-1", + ): + with patch.object( + scheduler, + "refreshShapers", + side_effect=stale_exc, + ): + with patch.object( + scheduler, + "clear_scheduler_error", + ) as mock_clear_error: + with patch.object( + scheduler, + "publish_scheduler_progress", + ) as mock_progress: + with patch("builtins.print"): + ready = scheduler.importAndShapeFullReload() + + self.assertFalse(ready) + mock_clear_error.assert_called_once() + self.assertTrue(scheduler.startup_topology_runtime_pending) + self.assertTrue( + any( + call.args[:3] == ( + True, + "waiting_for_topology_runtime", + "Waiting for topology runtime", + ) + for call in mock_progress.call_args_list + ) + ) + class TestSchedulerOverrideMerge(unittest.TestCase): def test_merge_rows_replaces_matching_device_id(self): -- knotmirror 0.0.1 From 1d6dd5cacc23643b0b6126c6e76cba361dcdfe71 Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Mon, 20 Apr 2026 10:54:30 -0500 Subject: [PATCH 09/51] Fix dynamic circuit saves and improve dynamic inventory view --- .../src/etc/v15/dynamic_circuits.rs | 46 +++ src/rust/lqosd/src/main.rs | 18 +- .../js_build/src/config/config_helper.js | 83 +++-- .../js_build/src/shaped-devices.js | 331 +++++++++++++++--- .../src/node_manager/local_api/config.rs | 21 +- .../local_api/shaped_devices_page.rs | 140 +++++++- .../src/node_manager/static2/node_manager.css | 35 ++ src/rust/lqosd/src/node_manager/ws.rs | 3 +- 8 files changed, 585 insertions(+), 92 deletions(-) diff --git a/src/rust/lqos_config/src/etc/v15/dynamic_circuits.rs b/src/rust/lqos_config/src/etc/v15/dynamic_circuits.rs index f725db28..0a0b3565 100644 --- a/src/rust/lqos_config/src/etc/v15/dynamic_circuits.rs +++ b/src/rust/lqos_config/src/etc/v15/dynamic_circuits.rs @@ -207,4 +207,50 @@ mod tests { 1 ); } + + #[test] + fn config_roundtrips_with_multiple_dynamic_circuit_ranges() { + let mut config = Config::default(); + + let ipv4_rule = DynamicCircuitRangeRule { + name: "IPv4 default".to_string(), + ip_range: "0.0.0.0/0" + .parse() + .expect("default ipv4 network should parse"), + download_min_mbps: 10.0, + upload_min_mbps: 10.0, + download_max_mbps: 100.0, + upload_max_mbps: 100.0, + attach_to: "Tower-A".to_string(), + }; + let ipv6_rule = DynamicCircuitRangeRule { + name: "IPv6 subscribers".to_string(), + ip_range: "2001:db8::/48" + .parse() + .expect("default ipv6 network should parse"), + download_min_mbps: 25.0, + upload_min_mbps: 5.0, + download_max_mbps: 250.0, + upload_max_mbps: 50.0, + attach_to: String::new(), + }; + + config.dynamic_circuits = Some(DynamicCircuitsConfig { + enabled: true, + ttl_seconds: 300, + enable_unknown_ip_promotion: true, + ranges: vec![ipv4_rule.clone(), ipv6_rule.clone()], + }); + + let raw = toml::to_string_pretty(&config).expect("config should serialize to TOML"); + let parsed = Config::load_from_string(&raw).expect("config should deserialize"); + let ranges = &parsed + .dynamic_circuits + .as_ref() + .expect("dynamic circuits should deserialize") + .ranges; + assert_eq!(ranges.len(), 2); + assert_eq!(ranges[0], ipv4_rule); + assert_eq!(ranges[1], ipv6_rule); + } } diff --git a/src/rust/lqosd/src/main.rs b/src/rust/lqosd/src/main.rs index 9bc37563..1bd0c6da 100644 --- a/src/rust/lqosd/src/main.rs +++ b/src/rust/lqosd/src/main.rs @@ -616,16 +616,18 @@ fn handle_bus_requests(requests: &[BusRequest], responses: &mut Vec lqos_bus::BusResponse::Ack } BusRequest::UpdateLqosDTuning(..) => tuning::tune_lqosd_from_bus(req), - BusRequest::UpdateLqosdConfig(config) => { - let result = lqos_config::update_config(config); - if result.is_err() { - error!("Error updating config: {:?}", result); + BusRequest::UpdateLqosdConfig(config) => match lqos_config::update_config(config) { + Ok(()) => { + if let Ok(cfg) = lqos_config::load_config() { + let _ = stick::recompute_stick_offset(&cfg); + } + BusResponse::Ack } - if let Ok(cfg) = lqos_config::load_config() { - let _ = stick::recompute_stick_offset(&cfg); + Err(err) => { + error!("Error updating config: {err:?}"); + BusResponse::Fail(err.to_string()) } - BusResponse::Ack - } + }, BusRequest::CreateDynamicCircuit { shaped_device } => { crate::dynamic_circuits::create_dynamic_circuit((**shaped_device).clone()) } 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 cd677401..536cfe1c 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 @@ -2,27 +2,39 @@ import { get_ws_client } from "../pubsub/ws"; const wsClient = get_ws_client(); const secretBindings = []; +const CONFIG_SAVE_TIMEOUT_MS = 10000; -export function sendWsRequest(responseEvent, request, onComplete, onError) { +export function sendWsRequest(responseEvent, request, onComplete, onError, options = {}) { let done = false; - const responseHandler = (msg) => { + let timeoutId = null; + const finish = (callback, msg) => { if (done) return; done = true; + if (timeoutId !== null) { + clearTimeout(timeoutId); + timeoutId = null; + } wsClient.off(responseEvent, responseHandler); wsClient.off("Error", errorHandler); - onComplete(msg); + if (callback) { + callback(msg); + } + }; + const responseHandler = (msg) => { + finish(onComplete, msg); }; const errorHandler = (msg) => { - if (done) return; - done = true; - wsClient.off(responseEvent, responseHandler); - wsClient.off("Error", errorHandler); - if (onError) { - onError(msg); - } + finish(onError, msg); }; wsClient.on(responseEvent, responseHandler); wsClient.on("Error", errorHandler); + if (Number.isFinite(options.timeoutMs) && options.timeoutMs > 0) { + timeoutId = setTimeout(() => { + finish(onError, { + message: options.timeoutMessage || `Timed out waiting for ${responseEvent}`, + }); + }, options.timeoutMs); + } wsClient.send(request); } @@ -144,6 +156,17 @@ export function loadConfig(onComplete, onError) { export function saveConfig(onComplete, onError) { const clearSecrets = window.configSecretClears || {}; + const reportError = (msg) => { + const errorMsg = (msg && msg.message) ? msg.message : "Request failed"; + const detail = (msg && typeof msg === "object") + ? { ...msg, message: errorMsg } + : { message: errorMsg }; + if (onError) { + onError(detail); + } else { + alert("Error saving configuration: " + errorMsg); + } + }; sendWsRequest( "UpdateConfigResult", { @@ -153,29 +176,29 @@ export function saveConfig(onComplete, onError) { }, }, (msg) => { - if (msg && msg.ok) { - secretBindings.forEach((binding) => { - const sectionState = secretFieldMap(window.configSecretState || {}, binding.section); - const inputValue = binding.input.value.trim(); - sectionState[binding.field] = clearSecrets?.[binding.section]?.[binding.field] - ? false - : (inputValue.length > 0 || sectionState[binding.field]); - if (window.config?.[binding.section] && typeof window.config[binding.section] === "object") { - window.config[binding.section][binding.field] = ""; - } - binding.input.value = ""; - setSecretClear(binding.section, binding.field, false); - binding.updateStatus(); - }); + if (!msg || !msg.ok) { + reportError(msg); + return; } + secretBindings.forEach((binding) => { + const sectionState = secretFieldMap(window.configSecretState || {}, binding.section); + const inputValue = binding.input.value.trim(); + sectionState[binding.field] = clearSecrets?.[binding.section]?.[binding.field] + ? false + : (inputValue.length > 0 || sectionState[binding.field]); + if (window.config?.[binding.section] && typeof window.config[binding.section] === "object") { + window.config[binding.section][binding.field] = ""; + } + binding.input.value = ""; + setSecretClear(binding.section, binding.field, false); + binding.updateStatus(); + }); if (onComplete) onComplete(msg); }, - (msg) => { - if (onError) { - onError(msg); - } else { - alert("That didn't work"); - } + reportError, + { + timeoutMs: CONFIG_SAVE_TIMEOUT_MS, + timeoutMessage: "Timed out waiting for the config save result. The websocket may have disconnected.", }, ); } diff --git a/src/rust/lqosd/src/node_manager/js_build/src/shaped-devices.js b/src/rust/lqosd/src/node_manager/js_build/src/shaped-devices.js index f485de9b..bb82c4aa 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/shaped-devices.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/shaped-devices.js @@ -21,6 +21,8 @@ let totalRows = 0; let totalCircuits = 0; let circuitMetricsWatchSignature = null; const wsClient = get_ws_client(); +const DYNAMIC_VIEW_MODE_STORAGE_KEY = "lqosShapedDevicesDynamicViewMode"; +let dynamicViewMode = loadDynamicViewMode(); const QOO_TOOLTIP_HTML = "
Quality of Outcome (QoO)
" + @@ -75,6 +77,38 @@ function formatPlanValue(value) { return formatted; } +function normalizeDynamicViewMode(mode) { + return mode === "list" ? "list" : "cards"; +} + +function loadDynamicViewMode() { + try { + if (window.localStorage) { + return normalizeDynamicViewMode(window.localStorage.getItem(DYNAMIC_VIEW_MODE_STORAGE_KEY)); + } + } catch (_error) { + // Ignore storage failures and fall back to the default cards view. + } + return "cards"; +} + +function persistDynamicViewMode(mode) { + try { + if (window.localStorage) { + window.localStorage.setItem( + DYNAMIC_VIEW_MODE_STORAGE_KEY, + normalizeDynamicViewMode(mode), + ); + } + } catch (_error) { + // Ignore storage failures and keep the current in-memory preference. + } +} + +function isDynamicListView() { + return shapedDevicesKind === "Dynamic" && dynamicViewMode === "list"; +} + function countCircuits() { return totalCircuits; } @@ -125,6 +159,16 @@ function setShapedDevicesKind(kind) { requestShapedDevicesPage(); } +function setDynamicViewMode(mode) { + const normalized = normalizeDynamicViewMode(mode); + if (dynamicViewMode === normalized) { + return; + } + dynamicViewMode = normalized; + persistDynamicViewMode(dynamicViewMode); + renderDevices(); +} + function filterDevices() { page = 0; requestShapedDevicesPage(); @@ -304,45 +348,110 @@ function metricTableRow(labelEl, downEl, upEl) { return tr; } -function buildDeviceCard(device) { - const card = document.createElement("div"); - card.classList.add("executive-card", "h-100"); - - // Header - const header = document.createElement("div"); - header.classList.add("d-flex", "justify-content-between", "align-items-start", "gap-2"); - - const titleWrap = document.createElement("div"); - titleWrap.style.minWidth = "0"; +function buildDeviceIdentity(device, options = {}) { + const { + circuitClasses = [], + deviceClasses = [], + } = options; + const wrapper = document.createElement("div"); + wrapper.style.minWidth = "0"; if (device.circuit_id) { const circuitLink = document.createElement("a"); circuitLink.href = "circuit.html?id=" + encodeURI(device.circuit_id); - circuitLink.classList.add("redactable", "fw-semibold", "text-decoration-none"); + circuitClasses.forEach((className) => circuitLink.classList.add(className)); circuitLink.innerText = device.circuit_name || "(Unknown circuit)"; - titleWrap.appendChild(circuitLink); - - const deviceLink = document.createElement("a"); - deviceLink.href = "circuit.html?id=" + encodeURI(device.circuit_id); - deviceLink.classList.add("redactable", "d-block", "small", "text-body-secondary", "text-decoration-none"); - deviceLink.innerText = device.device_name || ""; - titleWrap.appendChild(deviceLink); + wrapper.appendChild(circuitLink); + + if (device.device_name) { + const deviceLink = document.createElement("a"); + deviceLink.href = "circuit.html?id=" + encodeURI(device.circuit_id); + deviceClasses.forEach((className) => deviceLink.classList.add(className)); + deviceLink.innerText = device.device_name; + wrapper.appendChild(deviceLink); + } } else { const circuitName = document.createElement("div"); - circuitName.classList.add("fw-semibold", "redactable"); + circuitClasses.forEach((className) => circuitName.classList.add(className)); circuitName.innerText = device.circuit_name || "(Unknown circuit)"; - titleWrap.appendChild(circuitName); + wrapper.appendChild(circuitName); - const deviceName = document.createElement("div"); - deviceName.classList.add("small", "text-body-secondary", "redactable"); - deviceName.innerText = device.device_name || ""; - titleWrap.appendChild(deviceName); + if (device.device_name) { + const deviceName = document.createElement("div"); + deviceClasses.forEach((className) => deviceName.classList.add(className)); + deviceName.innerText = device.device_name; + wrapper.appendChild(deviceName); + } } - const planBadge = document.createElement("span"); - planBadge.classList.add("badge", "text-bg-secondary", "exec-badge", "ms-auto"); - planBadge.innerText = + return wrapper; +} + +function buildPlanBadge(device, extraClasses = []) { + const badge = document.createElement("span"); + badge.classList.add("badge", "text-bg-secondary", "exec-badge", ...extraClasses); + badge.innerText = formatPlanValue(device.download_max_mbps) + " / " + formatPlanValue(device.upload_max_mbps) + " Mbps"; + return badge; +} + +function buildMetricValueEl() { + const span = document.createElement("span"); + span.innerHTML = "-"; + return span; +} + +function buildMetricPairCell(circuitId, downMetricName, upMetricName) { + const wrapper = document.createElement("div"); + wrapper.classList.add("lqos-direction-metric"); + + const addLine = (label, metricName) => { + const line = document.createElement("div"); + line.classList.add("lqos-direction-metric-line"); + + const labelEl = document.createElement("span"); + labelEl.classList.add("lqos-direction-metric-label"); + labelEl.innerText = label; + line.appendChild(labelEl); + + const valueEl = buildMetricValueEl(); + line.appendChild(valueEl); + wrapper.appendChild(line); + registerMetricEl(circuitId, metricName, valueEl); + }; + + addLine("DL", downMetricName); + addLine("UL", upMetricName); + + return wrapper; +} + +function appendListCell(row, content, classNames = []) { + const td = document.createElement("td"); + classNames.forEach((className) => td.classList.add(className)); + if (typeof content === "string") { + td.innerText = content; + } else if (content) { + td.appendChild(content); + } + row.appendChild(td); + return td; +} + +function buildDeviceCard(device) { + const card = document.createElement("div"); + card.classList.add("executive-card", "h-100"); + + // Header + const header = document.createElement("div"); + header.classList.add("d-flex", "justify-content-between", "align-items-start", "gap-2"); + + const titleWrap = buildDeviceIdentity(device, { + circuitClasses: ["redactable", "fw-semibold", "text-decoration-none"], + deviceClasses: ["redactable", "d-block", "small", "text-body-secondary", "text-decoration-none"], + }); + + const planBadge = buildPlanBadge(device, ["ms-auto"]); header.appendChild(titleWrap); header.appendChild(planBadge); @@ -446,19 +555,57 @@ function buildDeviceCard(device) { return card; } +function buildDeviceListRow(device) { + const row = document.createElement("tr"); + row.classList.add("align-middle"); + + const identity = buildDeviceIdentity(device, { + circuitClasses: ["redactable", "fw-semibold", "text-decoration-none"], + deviceClasses: ["redactable", "d-block", "small", "text-body-secondary", "text-decoration-none"], + }); + appendListCell(row, identity); + + const parent = document.createElement("div"); + parent.classList.add("small", "redactable"); + parent.innerText = device.parent_node || "-"; + appendListCell(row, parent); + + appendListCell(row, buildPlanBadge(device)); + appendListCell(row, buildMetricPairCell(device.circuit_id, "tpDown", "tpUp"), ["text-nowrap"]); + appendListCell(row, buildMetricPairCell(device.circuit_id, "rttDown", "rttUp"), ["text-nowrap"]); + appendListCell(row, buildMetricPairCell(device.circuit_id, "qooDown", "qooUp"), ["text-nowrap"]); + appendListCell(row, buildMetricPairCell(device.circuit_id, "reXmitDown", "reXmitUp"), ["text-nowrap"]); + + const lastSeenValue = document.createElement("span"); + lastSeenValue.innerText = "-"; + appendListCell(row, lastSeenValue, ["text-nowrap"]); + registerMetricEl(device.circuit_id, "lastSeen", lastSeenValue); + + appendListCell(row, buildIpListEl(device), ["text-nowrap"]); + + return row; +} + function ensureLayout() { const target = document.getElementById("deviceTable"); if (!target) return null; let toolbar = document.getElementById("sdToolbar"); let grid = document.getElementById("sdCardsGrid"); - if (toolbar && grid) { + let listWrap = document.getElementById("sdListWrap"); + let listBody = document.getElementById("sdListBody"); + if (toolbar && grid && listWrap && listBody) { return { target, toolbar, grid, + listWrap, + listBody, searchInput: document.getElementById("sdSearch"), perPageSelect: document.getElementById("sdPerPage"), + viewToggleWrap: document.getElementById("sdViewToggleWrap"), + viewCardsButton: document.getElementById("sdViewCards"), + viewListButton: document.getElementById("sdViewList"), prevButton: document.getElementById("sdPrevPage"), nextButton: document.getElementById("sdNextPage"), pageCounter: document.getElementById("sdPageCounter"), @@ -529,6 +676,41 @@ function ensureLayout() { perPageWrap.appendChild(perPageSelect); toolbar.appendChild(perPageWrap); + const viewToggleWrap = document.createElement("div"); + viewToggleWrap.id = "sdViewToggleWrap"; + viewToggleWrap.classList.add("d-none", "d-flex", "align-items-center", "gap-1"); + const viewLabel = document.createElement("span"); + viewLabel.classList.add("small", "text-body-secondary"); + viewLabel.innerText = "View"; + const viewToggle = document.createElement("div"); + viewToggle.classList.add("btn-group", "btn-group-sm", "lqos-shaped-devices-view-toggle"); + viewToggle.setAttribute("role", "group"); + viewToggle.setAttribute("aria-label", "Dynamic circuits view"); + + const viewCards = document.createElement("button"); + viewCards.id = "sdViewCards"; + viewCards.type = "button"; + viewCards.classList.add("btn", "btn-outline-secondary"); + viewCards.innerHTML = "Cards"; + viewCards.onclick = () => { + setDynamicViewMode("cards"); + }; + + const viewList = document.createElement("button"); + viewList.id = "sdViewList"; + viewList.type = "button"; + viewList.classList.add("btn", "btn-outline-secondary"); + viewList.innerHTML = "List"; + viewList.onclick = () => { + setDynamicViewMode("list"); + }; + + viewToggle.appendChild(viewCards); + viewToggle.appendChild(viewList); + viewToggleWrap.appendChild(viewLabel); + viewToggleWrap.appendChild(viewToggle); + toolbar.appendChild(viewToggleWrap); + const pagerWrap = document.createElement("div"); pagerWrap.classList.add("d-flex", "align-items-center", "gap-2"); const pager = document.createElement("div"); @@ -580,12 +762,50 @@ function ensureLayout() { grid.classList.add("row", "row-cols-1", "row-cols-md-2", "row-cols-xl-3", "g-3"); target.appendChild(grid); + listWrap = document.createElement("div"); + listWrap.id = "sdListWrap"; + listWrap.classList.add("table-responsive", "lqos-table-wrap", "d-none"); + + const listTable = document.createElement("table"); + listTable.classList.add("lqos-table", "lqos-table-tight", "mb-0", "lqos-shaped-devices-list-table"); + + const listHead = document.createElement("thead"); + const listHeadRow = document.createElement("tr"); + [ + "Circuit", + "Parent", + "Plan", + "Throughput", + "RTT", + "QoO", + "Retransmits", + "Last Seen", + "IPs", + ].forEach((label) => { + const th = document.createElement("th"); + th.innerText = label; + listHeadRow.appendChild(th); + }); + listHead.appendChild(listHeadRow); + listTable.appendChild(listHead); + + listBody = document.createElement("tbody"); + listBody.id = "sdListBody"; + listTable.appendChild(listBody); + listWrap.appendChild(listTable); + target.appendChild(listWrap); + return { target, toolbar, grid, + listWrap, + listBody, searchInput, perPageSelect, + viewToggleWrap, + viewCardsButton: viewCards, + viewListButton: viewList, prevButton: prev, nextButton: next, pageCounter, @@ -656,19 +876,36 @@ async function requestShapedDevicesPage() { current.up = Math.max(toNumber(current.up, 0), toNumber(device.upload_max_mbps, 0)); planByCircuitId.set(device.circuit_id, current); }); - renderCards(); + renderDevices(); requestCircuitMetricsWatch(true); renderCounts(); } catch (_error) { shapedDevices = []; totalRows = 0; totalCircuits = 0; - renderCards(); + renderDevices(); renderCounts(); } } -function renderCards() { +function updateViewToggle(layout) { + const showToggle = shapedDevicesKind === "Dynamic"; + if (layout.viewToggleWrap) { + layout.viewToggleWrap.classList.toggle("d-none", !showToggle); + layout.viewToggleWrap.classList.toggle("d-flex", showToggle); + } + const cardsActive = !isDynamicListView(); + if (layout.viewCardsButton) { + layout.viewCardsButton.classList.toggle("active", cardsActive); + layout.viewCardsButton.setAttribute("aria-pressed", cardsActive.toString()); + } + if (layout.viewListButton) { + layout.viewListButton.classList.toggle("active", !cardsActive); + layout.viewListButton.setAttribute("aria-pressed", (!cardsActive).toString()); + } +} + +function renderDevices() { const layout = ensureLayout(); if (!layout) return; @@ -679,6 +916,7 @@ function renderCards() { if (layout.perPageSelect && String(devicesPerPage) !== layout.perPageSelect.value) { layout.perPageSelect.value = String(devicesPerPage); } + updateViewToggle(layout); if (layout.prevButton) layout.prevButton.disabled = page <= 0; if (layout.nextButton) layout.nextButton.disabled = page >= totalPages - 1; if (layout.pageCounter) layout.pageCounter.innerText = "Page " + (page + 1) + " / " + totalPages; @@ -688,21 +926,36 @@ function renderCards() { } else { const start = page * devicesPerPage + 1; const end = Math.min((page + 1) * devicesPerPage, totalRows); - layout.summary.innerText = "Showing " + start + "–" + end + " of " + totalRows; + let summary = "Showing " + start + "–" + end + " of " + totalRows; + if (shapedDevicesKind === "Dynamic") { + summary += " (highest throughput first)"; + } + layout.summary.innerText = summary; } } metricElsByCircuitId = new Map(); clearDiv(layout.grid); + clearDiv(layout.listBody); - shapedDevices.forEach((device) => { - const col = document.createElement("div"); - col.classList.add("col"); - col.appendChild(buildDeviceCard(device)); - layout.grid.appendChild(col); - }); + const showList = isDynamicListView(); + layout.grid.classList.toggle("d-none", showList); + layout.listWrap.classList.toggle("d-none", !showList); + + if (showList) { + shapedDevices.forEach((device) => { + layout.listBody.appendChild(buildDeviceListRow(device)); + }); + } else { + shapedDevices.forEach((device) => { + const col = document.createElement("div"); + col.classList.add("col"); + col.appendChild(buildDeviceCard(device)); + layout.grid.appendChild(col); + }); + } - // Fill visible cards from cached live data immediately. + // Fill visible metrics from cached live data immediately. metricElsByCircuitId.forEach((_metrics, circuitId) => { const latest = latestByCircuitId.get(circuitId); if (latest) { diff --git a/src/rust/lqosd/src/node_manager/local_api/config.rs b/src/rust/lqosd/src/node_manager/local_api/config.rs index f72a85a6..93b40394 100644 --- a/src/rust/lqosd/src/node_manager/local_api/config.rs +++ b/src/rust/lqosd/src/node_manager/local_api/config.rs @@ -7,7 +7,7 @@ use axum::body::Bytes; use axum::http::StatusCode; use axum::http::header; use default_net::get_interfaces; -use lqos_bus::{BusRequest, bus_request}; +use lqos_bus::{BusRequest, BusResponse, bus_request}; use lqos_config::{Config, ConfigShapedDevices, ShapedDevice, UserRole, WebUser, WebUsers}; use lqos_utils::hash_to_i64; use serde::{Deserialize, Serialize}; @@ -793,16 +793,23 @@ pub async fn update_lqosd_config_data( login: LoginResult, mut config: Config, clear_secrets: ConfigSecretClearRequest, -) -> Result<(), StatusCode> { +) -> Result<(), String> { if login != LoginResult::Admin { - return Err(StatusCode::FORBIDDEN); + return Err("Unauthorized".to_string()); } - let existing = lqos_config::load_config().map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + let existing = + lqos_config::load_config().map_err(|_| "Unable to load the current config".to_string())?; apply_secret_updates(existing.as_ref(), &mut config, &clear_secrets); - bus_request(vec![BusRequest::UpdateLqosdConfig(Box::new(config))]) + let mut responses = bus_request(vec![BusRequest::UpdateLqosdConfig(Box::new(config))]) .await - .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; - Ok(()) + .map_err(|err| format!("Unable to update config: {err}"))?; + + match responses.pop() { + Some(BusResponse::Ack) => Ok(()), + Some(BusResponse::Fail(message)) => Err(message), + Some(other) => Err(format!("Unexpected config update response: {other:?}")), + None => Err("No response received for config update".to_string()), + } } /// Persists both `network.json` and `ShapedDevices.csv` for administrative diff --git a/src/rust/lqosd/src/node_manager/local_api/shaped_devices_page.rs b/src/rust/lqosd/src/node_manager/local_api/shaped_devices_page.rs index dc21a98f..5ed297da 100644 --- a/src/rust/lqosd/src/node_manager/local_api/shaped_devices_page.rs +++ b/src/rust/lqosd/src/node_manager/local_api/shaped_devices_page.rs @@ -1,5 +1,9 @@ +use crate::shaped_devices_tracker::circuit_live::{ + CircuitLiveRollup, CircuitLiveSnapshot, fresh_circuit_live_snapshot, +}; use lqos_config::ShapedDevice; use serde::{Deserialize, Deserializer, Serialize}; +use std::cmp::Ordering; use std::collections::HashSet; const DEFAULT_SHAPED_DEVICES_PAGE_SIZE: usize = 24; @@ -57,7 +61,49 @@ fn normalized_page_size(query: &ShapedDevicesPageQuery) -> usize { .clamp(1, MAX_SHAPED_DEVICES_PAGE_SIZE) } +fn alphabetic_inventory_order(left: &ShapedDevice, right: &ShapedDevice) -> Ordering { + left.circuit_name + .cmp(&right.circuit_name) + .then_with(|| left.device_name.cmp(&right.device_name)) + .then_with(|| left.device_id.cmp(&right.device_id)) +} + +fn live_sort_rank(snapshot: &CircuitLiveSnapshot, device: &ShapedDevice) -> (u64, u64, u64, u64) { + let live = snapshot.by_circuit_id.get(&device.circuit_id); + let bytes_per_second = live + .map(|row: &CircuitLiveRollup| row.bytes_per_second) + .unwrap_or_default(); + let total_bytes_per_second = bytes_per_second.down.saturating_add(bytes_per_second.up); + let last_seen_nanos = live.map(|row| row.last_seen_nanos).unwrap_or(u64::MAX); + ( + total_bytes_per_second, + bytes_per_second.down, + bytes_per_second.up, + last_seen_nanos, + ) +} + +fn dynamic_inventory_order( + snapshot: &CircuitLiveSnapshot, + left: &ShapedDevice, + right: &ShapedDevice, +) -> Ordering { + let left_rank = live_sort_rank(snapshot, left); + let right_rank = live_sort_rank(snapshot, right); + right_rank + .0 + .cmp(&left_rank.0) + .then_with(|| right_rank.1.cmp(&left_rank.1)) + .then_with(|| right_rank.2.cmp(&left_rank.2)) + .then_with(|| left_rank.3.cmp(&right_rank.3)) + .then_with(|| alphabetic_inventory_order(left, right)) +} + /// Returns one filtered, sorted page of shaped-device rows. +/// +/// Static inventory rows are ordered alphabetically. Dynamic inventory rows are +/// ordered by current observed throughput before pagination so the busiest +/// circuits stay at the top of the page. pub fn shaped_devices_page(query: ShapedDevicesPageQuery) -> ShapedDevicesPage { let page = query.page.unwrap_or(0); let page_size = normalized_page_size(&query); @@ -103,12 +149,13 @@ pub fn shaped_devices_page(query: ShapedDevicesPageQuery) -> ShapedDevicesPage { .cloned() .collect(), }; - filtered.sort_by(|left, right| { - left.circuit_name - .cmp(&right.circuit_name) - .then_with(|| left.device_name.cmp(&right.device_name)) - .then_with(|| left.device_id.cmp(&right.device_id)) - }); + match kind { + ShapedDevicesPageKind::Static => filtered.sort_by(alphabetic_inventory_order), + ShapedDevicesPageKind::Dynamic => { + let snapshot = fresh_circuit_live_snapshot(); + filtered.sort_by(|left, right| dynamic_inventory_order(snapshot.as_ref(), left, right)); + } + } let total_rows = filtered.len(); let total_circuits = filtered @@ -140,3 +187,84 @@ pub fn shaped_devices_page(query: ShapedDevicesPageQuery) -> ShapedDevicesPage { rows, } } + +#[cfg(test)] +mod tests { + use super::*; + use fxhash::FxHashMap; + use lqos_utils::units::DownUpOrder; + + fn test_device(circuit_id: &str, circuit_name: &str, device_name: &str) -> ShapedDevice { + ShapedDevice { + circuit_id: circuit_id.to_string(), + circuit_name: circuit_name.to_string(), + device_id: format!("{circuit_id}-device"), + device_name: device_name.to_string(), + ..Default::default() + } + } + + fn test_snapshot(entries: &[(&str, u64, u64, u64)]) -> CircuitLiveSnapshot { + let mut by_circuit_id = FxHashMap::default(); + for (circuit_id, down, up, last_seen_nanos) in entries { + by_circuit_id.insert( + (*circuit_id).to_string(), + CircuitLiveRollup { + circuit_id: (*circuit_id).to_string(), + circuit_name: String::new(), + parent_node: String::new(), + device_names: Vec::new(), + ip_addrs: Vec::new(), + plan_mbps: DownUpOrder::default(), + bytes_per_second: DownUpOrder::new(*down, *up), + rtt_current_p50_nanos: DownUpOrder::default(), + qoo: DownUpOrder::default(), + tcp_retransmit_sample: DownUpOrder::default(), + last_seen_nanos: *last_seen_nanos, + }, + ); + } + CircuitLiveSnapshot { by_circuit_id } + } + + #[test] + fn dynamic_inventory_order_prefers_higher_combined_throughput() { + let snapshot = test_snapshot(&[ + ("slow", 10, 20, 3_000), + ("fast", 40, 90, 2_000), + ("idle", 0, 0, u64::MAX), + ]); + let mut rows = vec![ + test_device("slow", "Slow Circuit", "Slow Device"), + test_device("idle", "Idle Circuit", "Idle Device"), + test_device("fast", "Fast Circuit", "Fast Device"), + ]; + + rows.sort_by(|left, right| dynamic_inventory_order(&snapshot, left, right)); + + assert_eq!( + rows.iter() + .map(|row| row.circuit_id.as_str()) + .collect::>(), + vec!["fast", "slow", "idle"] + ); + } + + #[test] + fn dynamic_inventory_order_uses_alphabetic_tie_breakers() { + let snapshot = test_snapshot(&[("alpha", 25, 25, 100), ("beta", 25, 25, 100)]); + let mut rows = vec![ + test_device("beta", "Beta Circuit", "Second Device"), + test_device("alpha", "Alpha Circuit", "First Device"), + ]; + + rows.sort_by(|left, right| dynamic_inventory_order(&snapshot, left, right)); + + assert_eq!( + rows.iter() + .map(|row| row.circuit_id.as_str()) + .collect::>(), + vec!["alpha", "beta"] + ); + } +} diff --git a/src/rust/lqosd/src/node_manager/static2/node_manager.css b/src/rust/lqosd/src/node_manager/static2/node_manager.css index 8d0aa92c..dd83d134 100644 --- a/src/rust/lqosd/src/node_manager/static2/node_manager.css +++ b/src/rust/lqosd/src/node_manager/static2/node_manager.css @@ -2501,6 +2501,41 @@ table tr td a { background: var(--lqos-surface-solid); box-shadow: var(--lqos-shadow-sm); } +.lqos-shaped-devices-view-toggle .btn { + border-color: color-mix(in srgb, var(--lqos-border) 80%, transparent); +} +.lqos-shaped-devices-view-toggle .btn.active, +.lqos-shaped-devices-view-toggle .btn:active { + color: var(--bs-emphasis-color); + border-color: color-mix(in srgb, var(--lqos-border) 72%, transparent); + background: color-mix(in srgb, var(--lqos-surface) 86%, transparent); + box-shadow: + inset 0 1px 0 rgba(255, 255, 255, 0.08), + 0 0 0 1px color-mix(in srgb, var(--lqos-border) 30%, transparent); +} +.lqos-shaped-devices-list-table td { + vertical-align: middle; +} +.lqos-shaped-devices-list-table td .badge { + white-space: nowrap; +} +.lqos-direction-metric { + display: flex; + flex-direction: column; + gap: 0.15rem; + min-width: 7rem; +} +.lqos-direction-metric-line { + display: flex; + align-items: center; + justify-content: space-between; + gap: 0.75rem; +} +.lqos-direction-metric-label { + font-size: 0.74rem; + font-weight: 600; + color: var(--bs-secondary-color); +} .exec-icon { display: inline-flex; align-items: center; diff --git a/src/rust/lqosd/src/node_manager/ws.rs b/src/rust/lqosd/src/node_manager/ws.rs index 65bc0c31..4e359bd8 100644 --- a/src/rust/lqosd/src/node_manager/ws.rs +++ b/src/rust/lqosd/src/node_manager/ws.rs @@ -1579,8 +1579,7 @@ async fn receive_channel_message( config::update_lqosd_config_data(*request_state.login, cfg, clear_secrets).await; let (ok, message) = match result { Ok(()) => (true, "Ok".to_string()), - Err(StatusCode::FORBIDDEN) => (false, "Unauthorized".to_string()), - Err(_) => (false, "Error".to_string()), + Err(message) => (false, message), }; let response = WsResponse::UpdateConfigResult { ok, message }; if send_ws_response(&tx, response).await { -- knotmirror 0.0.1 From c2262649fd0c11997e6d3811311d58bd89af038f Mon Sep 17 00:00:00 2001 From: rchac Date: Mon, 20 Apr 2026 21:30:07 -0600 Subject: [PATCH 10/51] changes --- .../src/node_manager/js_build/src/template.js | 43 +++++++++++ src/scheduler.py | 24 +++++- src/test_scheduler.py | 77 +++++++++++++++++++ 3 files changed, 143 insertions(+), 1 deletion(-) diff --git a/src/rust/lqosd/src/node_manager/js_build/src/template.js b/src/rust/lqosd/src/node_manager/js_build/src/template.js index af9c347a..5f26f50b 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/template.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/template.js @@ -179,12 +179,21 @@ function schedulerHasLiveError(data) { return !schedulerLooksRecovered(data); } +function schedulerWaitsForTopologyRuntime(data) { + const progress = data?.progress || null; + if (!progress) { + return false; + } + return String(progress.phase || "").trim() === "waiting_for_topology_runtime"; +} + function schedulerStateDescriptor(data) { const progress = data?.progress || null; const hasError = schedulerHasLiveError(data); const available = !!data?.available; const active = !!progress?.active; const setupRequired = !!data?.setup_required; + const topologyRuntimeWait = schedulerWaitsForTopologyRuntime(data); if (hasError) { return { @@ -219,6 +228,17 @@ function schedulerStateDescriptor(data) { icon: "fa-clock", }; } + if (topologyRuntimeWait) { + return { + tone: "warning", + badgeClass: "text-bg-warning", + label: "Deferred", + title: progress?.phase_label || "Waiting for topology runtime", + subtitle: "Scheduler is waiting for topology runtime outputs", + ringTone: "tone-warning", + icon: "fa-hourglass-half", + }; + } if (active) { return { tone: "info", @@ -316,6 +336,8 @@ function renderSchedulerDetails(data, options = {}) { ? "Setup Required" : data?.stale ? "Stale" + : schedulerWaitsForTopologyRuntime(data) + ? "Deferred" : (data?.available ? "Healthy" : "Unavailable"); const recentResult = schedulerSetupMessage(data) || summarizeSchedulerOutput(data?.output, historicalError || liveError); const activity = schedulerActivityItems(data?.output, historicalError || liveError, data); @@ -324,6 +346,8 @@ function renderSchedulerDetails(data, options = {}) { progressMeta = "Showing cached scheduler details while the UI reconnects"; } else if (data?.setup_required) { progressMeta = "Complete runtime setup to enable scheduler work"; + } else if (schedulerWaitsForTopologyRuntime(data)) { + progressMeta = "The next shaping update is waiting for topology runtime outputs"; } else if (progress?.active) { progressMeta = `${percent}% complete`; } else if (descriptor.label === "Idle") { @@ -450,6 +474,14 @@ function renderSchedulerStatus(container, state, progress, labelOverride = null) color = "text-warning"; label = "Scheduler status is stale"; indicator = schedulerRingMarkup(100, "tone-warning", "fa-clock"); + } else if (state === "deferred") { + color = "text-warning"; + label = labelOverride || "Scheduler is waiting for topology runtime"; + indicator = schedulerRingMarkup( + schedulerProgressPercent(progress), + "tone-warning", + "fa-hourglass-half" + ); } else if (state === "setup") { color = "text-warning"; label = "Scheduler needs topology setup"; @@ -538,6 +570,17 @@ function loadSchedulerStatus(force = false) { return; } + if (schedulerWaitsForTopologyRuntime(data)) { + renderSchedulerStatus( + container, + "deferred", + progress, + progress?.phase_label || "Scheduler is waiting for topology runtime" + ); + scheduleNextSchedulerStatusPoll(); + return; + } + if (progressActive) { renderSchedulerStatus(container, "progress", progress); scheduleNextSchedulerStatusPoll(); diff --git a/src/scheduler.py b/src/scheduler.py index 2a0bcea0..08757f54 100644 --- a/src/scheduler.py +++ b/src/scheduler.py @@ -1021,6 +1021,7 @@ def importAndShapeFullReload(): report_topology_runtime_not_ready( "Scheduler startup shaping refresh deferred", phase_label="Scheduler waiting for topology runtime", + step_index=4, step_count=SCHEDULER_STARTUP_STEP_COUNT, ) return False @@ -1062,6 +1063,7 @@ def importAndShapePartialReload(): report_topology_runtime_not_ready( "Scheduled shaping refresh deferred", phase_label="Scheduler waiting for topology runtime", + step_index=3, step_count=SCHEDULER_REFRESH_STEP_COUNT, ) return @@ -1180,7 +1182,13 @@ def topology_runtime_readiness_detail(): return (True, "", current_generation) -def report_topology_runtime_not_ready(context: str, *, phase_label: str, step_count: int): +def report_topology_runtime_not_ready( + context: str, + *, + phase_label: str, + step_index: int, + step_count: int, +): ready, detail, generation = topology_runtime_readiness_detail() if ready: return @@ -1188,7 +1196,19 @@ def report_topology_runtime_not_ready(context: str, *, phase_label: str, step_co if generation: message += f" Generation {generation[:12]}." print(message) + if _topology_runtime_not_ready_is_transient(detail): + clear_scheduler_error() + scheduler_output(message) + publish_scheduler_progress( + False, + "waiting_for_topology_runtime", + phase_label, + step_index, + step_count, + ) + return scheduler_error(message) + scheduler_output(message) publish_scheduler_progress( False, "degraded", @@ -1430,6 +1450,7 @@ def _continue_startup_topology_runtime_wait(): report_topology_runtime_not_ready( "Scheduler startup shaping refresh deferred", phase_label="Scheduler waiting for topology runtime", + step_index=4, step_count=SCHEDULER_STARTUP_STEP_COUNT, ) @@ -1532,6 +1553,7 @@ def _continue_partial_topology_runtime_wait(): report_topology_runtime_not_ready( "Scheduled shaping refresh deferred", phase_label="Scheduler waiting for topology runtime", + step_index=3, step_count=SCHEDULER_REFRESH_STEP_COUNT, ) diff --git a/src/test_scheduler.py b/src/test_scheduler.py index 7c43ae5f..4b8d74b3 100644 --- a/src/test_scheduler.py +++ b/src/test_scheduler.py @@ -511,6 +511,83 @@ class TestSchedulerLogging(unittest.TestCase): ) ) + def test_transient_topology_runtime_deferred_wait_does_not_raise_scheduler_error(self): + with patch.object( + scheduler, + "topology_runtime_readiness_detail", + return_value=( + False, + "Topology runtime is still building outputs for the current source generation.", + "generation-1", + ), + ): + with patch.object(scheduler, "clear_scheduler_error") as mock_clear_error: + with patch.object(scheduler, "scheduler_error") as mock_scheduler_error: + with patch.object(scheduler, "scheduler_output") as mock_scheduler_output: + with patch.object( + scheduler, + "publish_scheduler_progress", + ) as mock_progress: + with patch("builtins.print"): + scheduler.report_topology_runtime_not_ready( + "Scheduled shaping refresh deferred", + phase_label="Scheduler waiting for topology runtime", + step_index=3, + step_count=scheduler.SCHEDULER_REFRESH_STEP_COUNT, + ) + + mock_clear_error.assert_called_once() + mock_scheduler_error.assert_not_called() + mock_scheduler_output.assert_called_once() + mock_progress.assert_called_once_with( + False, + "waiting_for_topology_runtime", + "Scheduler waiting for topology runtime", + 3, + scheduler.SCHEDULER_REFRESH_STEP_COUNT, + ) + + def test_failed_topology_runtime_deferred_wait_reports_scheduler_error(self): + with patch.object( + scheduler, + "topology_runtime_readiness_detail", + return_value=( + False, + "Topology runtime failed for the current source generation: publish failed", + "generation-1", + ), + ): + with patch.object(scheduler, "clear_scheduler_error") as mock_clear_error: + with patch.object(scheduler, "scheduler_error") as mock_scheduler_error: + with patch.object(scheduler, "scheduler_output") as mock_scheduler_output: + with patch.object( + scheduler, + "publish_scheduler_progress", + ) as mock_progress: + with patch("builtins.print"): + scheduler.report_topology_runtime_not_ready( + "Scheduled shaping refresh deferred", + phase_label="Scheduler waiting for topology runtime", + step_index=3, + step_count=scheduler.SCHEDULER_REFRESH_STEP_COUNT, + ) + + mock_clear_error.assert_not_called() + mock_scheduler_error.assert_called_once_with( + "Scheduled shaping refresh deferred: Topology runtime failed for the current source generation: publish failed Generation generation-1." + ) + mock_scheduler_output.assert_called_once_with( + "Scheduled shaping refresh deferred: Topology runtime failed for the current source generation: publish failed Generation generation-1." + ) + mock_progress.assert_called_once_with( + False, + "degraded", + "Scheduler waiting for topology runtime", + scheduler.SCHEDULER_REFRESH_STEP_COUNT, + scheduler.SCHEDULER_REFRESH_STEP_COUNT, + percent=100, + ) + def test_topology_runtime_refresh_tick_waits_for_partial_runtime_outputs(self): scheduler.partial_topology_runtime_pending = True scheduler.partial_topology_runtime_generation = "generation-1" -- knotmirror 0.0.1 From 823450f1d256791327d4f1c68c57430e559c8cfa Mon Sep 17 00:00:00 2001 From: rchac Date: Tue, 21 Apr 2026 22:14:20 +0000 Subject: [PATCH 11/51] changes --- docs-es/v2.0/integrations-sonar-es.md | 1 + docs-es/v2.0/troubleshooting-es.md | 1 + docs/v2.0/integrations-sonar.md | 2 +- docs/v2.0/troubleshooting.md | 2 +- src/integrationCommon.py | 45 +++++++- src/integrationSonar.py | 68 ++++++++++++- src/rust/lqos_python/src/device_weights.rs | 2 +- src/rust/lqos_python/src/lib.rs | 2 + src/scheduler.py | 53 ++++++++-- src/testGraph.py | 39 +++++++ src/test_integration_sonar.py | 113 ++++++++++++++++++++- src/test_scheduler.py | 28 +++++ 12 files changed, 340 insertions(+), 16 deletions(-) diff --git a/docs-es/v2.0/integrations-sonar-es.md b/docs-es/v2.0/integrations-sonar-es.md index 284a56c2..17c9baa3 100644 --- a/docs-es/v2.0/integrations-sonar-es.md +++ b/docs-es/v2.0/integrations-sonar-es.md @@ -14,6 +14,7 @@ Use esta integración cuando Sonar sea su fuente de verdad CRM/NMS. - La integración refresca automáticamente los datos importados y de shaping que LibreQoS usa con Sonar. - `network.json` queda para despliegues DIY o manuales. +- La integración importa IPs desde equipos de inventario, cuentas Radius e IPs asignadas directamente a la cuenta Sonar. Las IPs de Radius y de cuenta se agregan como dispositivos suplementarios de shaping y se deduplican contra las IPs de inventario. - Use la WebUI para confirmar que la importación terminó correctamente. ## Referencia completa diff --git a/docs-es/v2.0/troubleshooting-es.md b/docs-es/v2.0/troubleshooting-es.md index 16f6b3d5..db4a348d 100644 --- a/docs-es/v2.0/troubleshooting-es.md +++ b/docs-es/v2.0/troubleshooting-es.md @@ -118,6 +118,7 @@ Si el scheduler falla inmediatamente después de un reinicio con un mensaje como Versiones recientes muestran estado/readiness del scheduler en WebUI. Si el modal del scheduler indica que se agotó el tiempo al cargar detalles, las versiones actuales mantienen visible la última instantánea buena del scheduler con su antigüedad en lugar de convertir ese problema de transporte en un error del scheduler. Trate primero esa advertencia como un problema de comunicación entre WebUI y `lqosd`, y confirme la salud real del scheduler en los logs antes de asumir que falló el shaping. +Si falla un subproceso de integración pero el shaping puede continuar con la última topología válida, el scheduler puede seguir mostrando estado ready, pero el último error de integración permanece visible en el estado del scheduler hasta la siguiente integración exitosa. Si aparece caído/desactualizado: diff --git a/docs/v2.0/integrations-sonar.md b/docs/v2.0/integrations-sonar.md index 12184f46..a032aff8 100644 --- a/docs/v2.0/integrations-sonar.md +++ b/docs/v2.0/integrations-sonar.md @@ -7,7 +7,7 @@ Current behavior notes: - Current builds page through Sonar GraphQL results instead of relying on a small first-page sample. - Paginated Sonar GraphQL requests now use a split connect/read timeout and retry transient read timeouts before failing the import. - Emitted Sonar identities are namespaced (for example `sonar:account:` and `sonar:device:`) so they remain stable across overrides and downstream tooling. -- Account device discovery now preserves inventory-item IP handling and also imports Radius account IP assignments when they exist. Inventory-backed MACs are still used for AP mapping; Radius-only IPs are added as supplemental shaping devices and overlapping subnets are de-duplicated. +- Account device discovery now preserves inventory-item IP handling and also imports Radius account and account-level IP assignments when they exist. Inventory-backed MACs are still used for AP mapping; Radius-only and account-level IPs are added as supplemental shaping devices and overlapping subnets are de-duplicated. - Sonar `child_accounts` are also imported when they expose their own service and usable IP data. If a child account lacks its own address, LibreQoS falls back to the parent account address so the child can still be emitted as its own circuit. - Sonar settings now support ISP-specific recurring-service fallback rates plus a recurring-service exclusion list. LibreQoS still prefers active `DATA` services first; recurring mappings are only used when an account has no usable `DATA` service. - If Sonar returns non-JSON content or GraphQL errors, the integration now raises a more specific error message showing the endpoint and a short response preview. diff --git a/docs/v2.0/troubleshooting.md b/docs/v2.0/troubleshooting.md index 527bd19a..609287fe 100644 --- a/docs/v2.0/troubleshooting.md +++ b/docs/v2.0/troubleshooting.md @@ -181,7 +181,7 @@ If `journalctl -u lqosd` shows repeated `BeginIngest queue full`, `IngestChunk q If specific APs or switches appear multiple times with suffixed names such as `... [AP deadbeef]`, check whether UISP is returning duplicate rows for the same device ID. Current builds defensively deduplicate raw UISP devices by `identification.id` before topology graph construction, and skip any residual duplicate device IDs during graph assembly. -If an integration subprocess fails, current builds keep the scheduler alive, publish a shortened output preview to the scheduler status/error surfaces, and save the full captured output to a timestamped file under `/tmp` such as `lqos_scheduler_uisp_integration_YYYYMMDD_HHMMSS.log`. +If an integration subprocess fails, current builds keep the scheduler alive, publish a shortened output preview to the scheduler status/error surfaces, and save the full captured output to a timestamped file under `/tmp` such as `lqos_scheduler_uisp_integration_YYYYMMDD_HHMMSS.log`. If shaping can continue from the last-known-good topology, the scheduler may still report ready, but the latest integration failure remains visible in scheduler status until the next successful integration run. ### Scheduler status in WebUI looks unhealthy diff --git a/src/integrationCommon.py b/src/integrationCommon.py index 754b754b..6d52b4bf 100644 --- a/src/integrationCommon.py +++ b/src/integrationCommon.py @@ -1,7 +1,7 @@ # Optimized version of integrationCommon.py for better performance with large datasets # Provides common functionality shared between integrations. -from typing import List, Any, Dict, Set +from typing import List, Any, Dict, Set, Tuple from liblqos_python import allowed_subnets, ignore_subnets, generated_pn_download_mbps, generated_pn_upload_mbps, \ circuit_name_use_address, upstream_bandwidth_capacity_download_mbps, upstream_bandwidth_capacity_upload_mbps, \ find_ipv6_using_mikrotik, exclude_sites, bandwidth_overhead_factor, committed_bandwidth_multiplier, \ @@ -32,6 +32,46 @@ def _state_directory(): def _state_path(category, filename): return os.path.join(_state_directory(), category, filename) +def _normalize_exception_cpes(raw_exception_cpes) -> Tuple[Dict[str, str], List[str]]: + normalized = {} + errors = [] + if raw_exception_cpes is None: + return normalized, errors + if isinstance(raw_exception_cpes, dict): + for cpe, parent in raw_exception_cpes.items(): + cpe = str(cpe).strip() + parent = str(parent).strip() + if cpe and parent: + normalized[cpe] = parent + return normalized, errors + if not isinstance(raw_exception_cpes, (list, tuple, set)): + errors.append( + f"exception_cpes ignored: expected dict or list, got {type(raw_exception_cpes).__name__}" + ) + return normalized, errors + for entry in raw_exception_cpes: + cpe = None + parent = None + if isinstance(entry, str): + if ":" in entry: + cpe, parent = entry.split(":", 1) + else: + errors.append(f"exception_cpes entry ignored: {entry!r} is missing ':'") + continue + elif isinstance(entry, dict): + cpe = entry.get("cpe") + parent = entry.get("parent") + else: + cpe = getattr(entry, "cpe", None) + parent = getattr(entry, "parent", None) + cpe = str(cpe or "").strip() + parent = str(parent or "").strip() + if not cpe or not parent: + errors.append(f"exception_cpes entry ignored: {entry!r} is missing cpe or parent") + continue + normalized[cpe] = parent + return normalized, errors + def isInAllowedSubnets(inputIP): # Check whether an IP address occurs inside the allowedSubnets list isAllowed = False @@ -203,8 +243,9 @@ class NetworkGraph: parentId="", displayName="Shaper Root") ] self.excludeSites = exclude_sites() - self.exceptionCPEs = exception_cpes() self.errors: List[str] = [] + self.exceptionCPEs, exception_cpe_errors = _normalize_exception_cpes(exception_cpes()) + self.errors.extend(exception_cpe_errors) # Initialize optimization structures self._id_to_index = {"FakeRoot": 0} diff --git a/src/integrationSonar.py b/src/integrationSonar.py index 28072ff3..b87990af 100644 --- a/src/integrationSonar.py +++ b/src/integrationSonar.py @@ -65,6 +65,10 @@ def sonarRadiusAccountDeviceNodeId(radius_account_id): return f"sonar:radius-account:{radius_account_id}" +def sonarAccountIpAssignmentDeviceNodeId(account_id): + return f"sonar:account-ip-assignments:{account_id}" + + def sonarSession(): global _SONAR_SESSION if _SONAR_SESSION is None: @@ -236,6 +240,15 @@ def findRadiusAccountIPs(radius_account): return dedupeSubnets(ips) +def findAccountIPs(account): + ips = [] + for ip in account.get('ip_assignments', {}).get('entities', []): + subnet = ip.get('subnet') + if subnet: + ips.append(subnet) + return dedupeSubnets(ips) + + def recurringServiceRateRules(): rules = {} for enabled, service_name, download_mbps, upload_mbps in sonar_recurring_service_rates(): @@ -413,7 +426,8 @@ def buildAccountDevices(account): 'raw_id': item['id'], 'name': item['inventory_model']['name'], 'ips': ips, - 'mac': findPrimaryMac(item) + 'mac': findPrimaryMac(item), + 'source': 'inventory_item', }) for radius_account in account.get('radius_accounts', {}).get('entities', []): @@ -429,7 +443,23 @@ def buildAccountDevices(account): 'raw_id': radius_account['id'], 'name': f"Radius Account {radius_account['id']}", 'ips': radius_ips, - 'mac': '' + 'mac': '', + 'source': 'radius_account', + }) + + account_ips = [ + subnet for subnet in findAccountIPs(account) + if subnet not in known_ip_subnets + ] + if account_ips: + known_ip_subnets.update(account_ips) + devices.append({ + 'id': sonarAccountIpAssignmentDeviceNodeId(account['id']), + 'raw_id': account['id'], + 'name': 'Account IP Assignments', + 'ips': account_ips, + 'mac': '', + 'source': 'account_ip_assignments', }) return devices @@ -520,6 +550,11 @@ def getAccounts(sonar_active_status_ids): account_status_id id name + ip_assignments { + entities { + subnet + } + } account_services (reverse_relation_filters: [$data]) { entities { service { @@ -580,6 +615,11 @@ def getAccounts(sonar_active_status_ids): entities { id name + ip_assignments { + entities { + subnet + } + } account_services (reverse_relation_filters: [$data]) { entities { service { @@ -729,6 +769,28 @@ def buildMacToApMap(aps): mac_to_ap[cpe_mac] = ap['id'] return mac_to_ap + +def sonarImportSummary(sites, aps, accounts): + total_devices = 0 + devices_with_ips = 0 + account_level_ip_devices = 0 + accounts_with_parent = 0 + for account in accounts: + if account.get('parent'): + accounts_with_parent += 1 + for device in account.get('devices', []): + total_devices += 1 + if len(device.get('ips') or []) > 0: + devices_with_ips += 1 + if device.get('source') == 'account_ip_assignments': + account_level_ip_devices += 1 + return ( + f"Sonar import summary: sites={len(sites)} aps={len(aps)} " + f"accounts={len(accounts)} accounts_with_ap_parent={accounts_with_parent} " + f"devices={total_devices} devices_with_ips={devices_with_ips} " + f"account_level_ip_devices={account_level_ip_devices}" + ) + def createShaper(): net = NetworkGraph() @@ -757,6 +819,8 @@ def createShaper(): if account['parent']: break + print(sonarImportSummary(sites, aps, accounts)) + for site in sites: net.addRawNode(NetworkNode(id=site['id'], displayName=site['name'], parentId="", type=NodeType.site, networkJsonId=f"sonar:site:{site['raw_id']}")) diff --git a/src/rust/lqos_python/src/device_weights.rs b/src/rust/lqos_python/src/device_weights.rs index 51c00b7e..770975ae 100644 --- a/src/rust/lqos_python/src/device_weights.rs +++ b/src/rust/lqos_python/src/device_weights.rs @@ -238,6 +238,6 @@ pub(crate) fn calculate_tree_weights() -> Result> { }); }); - result.sort_by(|a, b| b.weight.cmp(&a.weight)); + result.sort_by_key(|entry| std::cmp::Reverse(entry.weight)); Ok(result) } diff --git a/src/rust/lqos_python/src/lib.rs b/src/rust/lqos_python/src/lib.rs index fa165bac..6984888d 100644 --- a/src/rust/lqos_python/src/lib.rs +++ b/src/rust/lqos_python/src/lib.rs @@ -2240,8 +2240,10 @@ fn committed_bandwidth_multiplier() -> PyResult { /// A UISP exception CPE entry paired with its forced parent. pub struct PyExceptionCpe { /// Child CPE site or device identifier. + #[pyo3(get)] pub cpe: String, /// Parent identifier assigned to the exception CPE. + #[pyo3(get)] pub parent: String, } diff --git a/src/scheduler.py b/src/scheduler.py index 08757f54..3bcaf56e 100644 --- a/src/scheduler.py +++ b/src/scheduler.py @@ -46,6 +46,7 @@ partial_topology_runtime_pending = False partial_topology_runtime_generation = None partial_topology_runtime_started_monotonic = None partial_topology_runtime_last_report_state = None +last_integration_failure_message = "" def configure_scheduler_stdio(): @@ -128,6 +129,37 @@ def clear_scheduler_output(): scheduler_output("") +def remember_integration_failure(message: str): + global last_integration_failure_message + last_integration_failure_message = str(message or "").strip() + + +def clear_integration_failure(): + global last_integration_failure_message + last_integration_failure_message = "" + + +def clear_scheduler_error_unless_integration_failed(): + if not last_integration_failure_message: + clear_scheduler_error() + + +def publish_ready_progress(active: bool, phase: str, phase_label: str, step_index: int, step_count: int, *, percent=None): + publish_scheduler_progress( + active, + phase, + phase_label, + step_index, + step_count, + percent=percent, + ) + if last_integration_failure_message: + scheduler_error( + "Scheduler ready using last-known-good topology; latest integration import failed.\n" + + last_integration_failure_message + ) + + def _scheduler_progress_percent(step_index: int, step_count: int, *, active: bool) -> int: if step_count <= 0: return 0 @@ -242,6 +274,7 @@ def _write_integration_output_artifact(label, output): def _publish_integration_result(label, result): output = ((result.stdout or "") + (result.stderr or "")).replace("\r\n", "\n").strip() if result.returncode == 0: + clear_integration_failure() line_count = len(_integration_output_lines(output)) summary = ( f"{label} completed successfully." @@ -264,6 +297,7 @@ def _publish_integration_result(label, result): if artifact is not None: message += f"\nFull output saved to {artifact}" print(message) + remember_integration_failure(message) scheduler_error(message) @@ -385,6 +419,7 @@ def run_python_integration(module_name: str, func_name: str, label: str = ""): except Exception as e: err = f"Failed to invoke integration {label or (module_name + '.' + func_name)}: {e}" print(err) + remember_integration_failure(err) scheduler_error(err) def importFromCRM( @@ -397,6 +432,7 @@ def importFromCRM( overrides_label="Applying overrides", overrides_step=3, ): + clear_integration_failure() clear_scheduler_error() clear_scheduler_output() publish_scheduler_progress( @@ -422,6 +458,7 @@ def importFromCRM( except Exception as e: error_msg = f"Failed to run UISP integration: {str(e)}" print(error_msg) + remember_integration_failure(error_msg) scheduler_error(error_msg) elif automatic_import_splynx(): run_python_integration("integrationSplynx", "importFromSplynx", label="Splynx") @@ -1086,7 +1123,7 @@ def importAndShapePartialReload(): shaping_runtime_hash = calculate_shaping_runtime_hash() if shaping_runtime_hash != 0: set_scheduler_status_bus_enabled(True) - publish_scheduler_progress(False, "ready", "Scheduler ready", SCHEDULER_REFRESH_STEP_COUNT, SCHEDULER_REFRESH_STEP_COUNT, percent=100) + publish_ready_progress(False, "ready", "Scheduler ready", SCHEDULER_REFRESH_STEP_COUNT, SCHEDULER_REFRESH_STEP_COUNT, percent=100) def topology_runtime_status_path(): @@ -1197,7 +1234,7 @@ def report_topology_runtime_not_ready( message += f" Generation {generation[:12]}." print(message) if _topology_runtime_not_ready_is_transient(detail): - clear_scheduler_error() + clear_scheduler_error_unless_integration_failed() scheduler_output(message) publish_scheduler_progress( False, @@ -1265,7 +1302,7 @@ def _defer_stale_shaping_inputs_failure(exc: Exception, *, startup: bool) -> boo if detail and not _topology_runtime_not_ready_is_transient(detail): return False - clear_scheduler_error() + clear_scheduler_error_unless_integration_failed() if startup: _begin_startup_topology_runtime_wait(generation if not ready else current_topology_source_generation()) else: @@ -1412,8 +1449,8 @@ def _continue_startup_topology_runtime_wait(): _reset_startup_topology_runtime_wait() if shaping_runtime_hash != 0: - clear_scheduler_error() - publish_scheduler_progress( + clear_scheduler_error_unless_integration_failed() + publish_ready_progress( False, "ready", "Scheduler ready", @@ -1522,8 +1559,8 @@ def _continue_partial_topology_runtime_wait(): ) return _reset_partial_topology_runtime_wait() - clear_scheduler_error() - publish_scheduler_progress( + clear_scheduler_error_unless_integration_failed() + publish_ready_progress( False, "ready", "Scheduler ready", @@ -1629,7 +1666,7 @@ def run_scheduler_main(): try: startup_ready = importAndShapeFullReload() if startup_ready: - publish_scheduler_progress(False, "ready", "Scheduler ready", SCHEDULER_STARTUP_STEP_COUNT, SCHEDULER_STARTUP_STEP_COUNT, percent=100) + publish_ready_progress(False, "ready", "Scheduler ready", SCHEDULER_STARTUP_STEP_COUNT, SCHEDULER_STARTUP_STEP_COUNT, percent=100) except ValidationFailure as e: report_scheduler_validation_failure( "Scheduler startup shaping refresh blocked by validation", diff --git a/src/testGraph.py b/src/testGraph.py index d35810ec..a4a33e94 100644 --- a/src/testGraph.py +++ b/src/testGraph.py @@ -493,6 +493,45 @@ class TestGraph(unittest.TestCase): net.prepareTree() self.assertEqual(net.nodes[2].parentIndex, 1) + def test_empty_exception_cpes_list_does_not_crash(self): + import integrationCommon + from integrationCommon import NetworkGraph, NetworkNode, NodeType + + original_exception_cpes = integrationCommon.exception_cpes + try: + integrationCommon.exception_cpes = lambda: [] + net = NetworkGraph() + net.addRawNode(NetworkNode("Site_1", "Site_1", "", NodeType.site, 1000, 1000)) + finally: + integrationCommon.exception_cpes = original_exception_cpes + + self.assertEqual(net.nodes[1].displayName, "Site_1") + + def test_exception_cpes_list_entries_are_normalized(self): + from integrationCommon import NetworkGraph, NetworkNode, NodeType, _normalize_exception_cpes + + class ExceptionCpe: + cpe = "Site_3" + parent = "Site_1" + + normalized, errors = _normalize_exception_cpes([ + "Site_2:Site_1", + {"cpe": "Site_4", "parent": "Site_1"}, + ExceptionCpe(), + ]) + + self.assertEqual(errors, []) + self.assertEqual(normalized["Site_2"], "Site_1") + self.assertEqual(normalized["Site_3"], "Site_1") + self.assertEqual(normalized["Site_4"], "Site_1") + + net = NetworkGraph() + net.exceptionCPEs = normalized + net.addRawNode(NetworkNode("Site_1", "Site_1", "", NodeType.site, 1000, 1000)) + net.addRawNode(NetworkNode("Site_2", "Site_2", "", NodeType.site, 500, 500)) + + self.assertEqual(net.nodes[2].parentId, "Site_1") + def test_native_topology_editor_uses_nearest_real_infrastructure_parent(self): from integrationCommon import NetworkGraph, NetworkNode, NodeType diff --git a/src/test_integration_sonar.py b/src/test_integration_sonar.py index cb1c2268..6d29a77f 100644 --- a/src/test_integration_sonar.py +++ b/src/test_integration_sonar.py @@ -29,6 +29,9 @@ def install_sonar_stubs(): lqlib.sonar_active_status_ids = lambda: [] lqlib.sonar_recurring_service_rates = lambda: [] lqlib.sonar_recurring_excluded_service_names = lambda: [] + lqlib.sonar_strategy = lambda: "full" + lqlib.write_compiled_topology_from_python_graph_payload = lambda *_args, **_kwargs: None + lqlib.get_libreqos_directory = lambda: "" sys.modules["liblqos_python"] = lqlib @@ -59,8 +62,13 @@ def inventory_item(item_id, name, ips=None, mac=""): } -def sonar_account(address_items=None, radius_accounts=None): +def sonar_account(address_items=None, radius_accounts=None, account_ips=None): return { + "id": 1, + "name": "Account 1", + "ip_assignments": { + "entities": [{"subnet": subnet} for subnet in (account_ips or [])] + }, "addresses": { "entities": [ { @@ -147,6 +155,53 @@ class TestIntegrationSonarDevices(unittest.TestCase): self.assertEqual(devices[1]["id"], "sonar:radius-account:88") self.assertEqual(devices[1]["ips"], ["100.64.3.31/32"]) + def test_account_level_ips_emit_stable_account_ip_device(self): + devices = integrationSonar.buildAccountDevices( + sonar_account( + address_items=[ + inventory_item( + 42, + "ONU", + ips=[], + mac="AA:BB:CC:DD:EE:03", + ) + ], + account_ips=["100.64.8.80", "100.64.8.81"], + ) + ) + + self.assertEqual(len(devices), 2) + self.assertEqual(devices[0]["id"], "sonar:device:42") + self.assertEqual(devices[0]["mac"], "AA:BB:CC:DD:EE:03") + self.assertEqual(devices[0]["ips"], []) + self.assertEqual(devices[1]["id"], "sonar:account-ip-assignments:1") + self.assertEqual(devices[1]["name"], "Account IP Assignments") + self.assertEqual(devices[1]["ips"], ["100.64.8.80", "100.64.8.81"]) + self.assertEqual(devices[1]["mac"], "") + self.assertEqual(devices[1]["source"], "account_ip_assignments") + + def test_account_level_ips_are_deduped_against_inventory_and_radius_ips(self): + devices = integrationSonar.buildAccountDevices( + sonar_account( + address_items=[ + inventory_item( + 42, + "ONU", + ips=["100.64.9.90"], + mac="AA:BB:CC:DD:EE:09", + ) + ], + radius_accounts=[ + radius_account(99, ["100.64.9.91"]) + ], + account_ips=["100.64.9.90", "100.64.9.91", "100.64.9.92"], + ) + ) + + self.assertEqual(len(devices), 3) + self.assertEqual(devices[2]["id"], "sonar:account-ip-assignments:1") + self.assertEqual(devices[2]["ips"], ["100.64.9.92"]) + def test_inventory_mac_devices_are_preserved_when_radius_supplies_ips(self): devices = integrationSonar.buildAccountDevices( sonar_account( @@ -195,6 +250,31 @@ class TestIntegrationSonarDevices(unittest.TestCase): self.assertEqual(record["address"], "Parent Address") self.assertEqual(record["id"], "sonar:account:500") + def test_child_account_imports_account_level_ips(self): + child = sonar_account( + address_items=[], + account_ips=["100.64.10.10"], + ) + child["addresses"] = {"entities": []} + child["id"] = 501 + child["name"] = "Suite 501" + child["account_services"] = { + "entities": [{ + "service": { + "data_service_detail": { + "download_speed_kilobits_per_second": 100000, + "upload_speed_kilobits_per_second": 20000, + } + } + }] + } + + record = integrationSonar.buildAccountRecord(child, fallback_address="Parent Address") + + self.assertIsNotNone(record) + self.assertEqual(record["devices"][0]["id"], "sonar:account-ip-assignments:501") + self.assertEqual(record["devices"][0]["ips"], ["100.64.10.10"]) + def test_child_accounts_are_added_without_duplicate_top_level_records(self): top_level = sonar_account( address_items=[ @@ -338,6 +418,37 @@ class TestIntegrationSonarDevices(unittest.TestCase): self.assertIsNone(record) + def test_import_summary_counts_account_level_ip_devices(self): + account = { + "parent": "ap_1", + "devices": [ + { + "id": "sonar:device:42", + "ips": [], + "source": "inventory_item", + }, + { + "id": "sonar:account-ip-assignments:1", + "ips": ["100.64.11.11"], + "source": "account_ip_assignments", + }, + ], + } + + summary = integrationSonar.sonarImportSummary( + sites=[{"id": "site_1"}], + aps=[{"id": "ap_1"}], + accounts=[account], + ) + + self.assertIn("sites=1", summary) + self.assertIn("aps=1", summary) + self.assertIn("accounts=1", summary) + self.assertIn("accounts_with_ap_parent=1", summary) + self.assertIn("devices=2", summary) + self.assertIn("devices_with_ips=1", summary) + self.assertIn("account_level_ip_devices=1", summary) + class FakeResponse: def __init__(self, payload): diff --git a/src/test_scheduler.py b/src/test_scheduler.py index 4b8d74b3..824d4005 100644 --- a/src/test_scheduler.py +++ b/src/test_scheduler.py @@ -199,6 +199,7 @@ class TestSchedulerErrorReporting(unittest.TestCase): scheduler.set_scheduler_status_bus_enabled(True) scheduler._reset_startup_topology_runtime_wait() scheduler._reset_partial_topology_runtime_wait() + scheduler.clear_integration_failure() scheduler.shaping_runtime_hash = 0 def test_python_integration_output_does_not_set_scheduler_error(self): @@ -296,12 +297,38 @@ class TestSchedulerErrorReporting(unittest.TestCase): ) self.assertEqual(mock_scheduler_output.call_args_list, [(( "",),)]) + def test_ready_progress_keeps_latest_integration_failure_visible(self): + scheduler.remember_integration_failure("Sonar exited with code 1. Continuing.") + + with patch.object(scheduler, "publish_scheduler_progress") as mock_progress: + with patch.object(scheduler, "scheduler_error") as mock_scheduler_error: + scheduler.publish_ready_progress( + False, + "ready", + "Scheduler ready", + scheduler.SCHEDULER_REFRESH_STEP_COUNT, + scheduler.SCHEDULER_REFRESH_STEP_COUNT, + percent=100, + ) + + mock_progress.assert_called_once() + mock_scheduler_error.assert_called_once() + self.assertIn( + "Scheduler ready using last-known-good topology; latest integration import failed.", + mock_scheduler_error.call_args.args[0], + ) + self.assertIn( + "Sonar exited with code 1. Continuing.", + mock_scheduler_error.call_args.args[0], + ) + class TestSchedulerLogging(unittest.TestCase): def setUp(self): scheduler.set_scheduler_status_bus_enabled(True) scheduler._reset_startup_topology_runtime_wait() scheduler._reset_partial_topology_runtime_wait() + scheduler.clear_integration_failure() scheduler.shaping_runtime_hash = 0 def test_configure_scheduler_stdio_enables_line_buffering_when_supported(self): @@ -1025,6 +1052,7 @@ class TestTopologyRuntimeGating(unittest.TestCase): def setUp(self): scheduler._reset_startup_topology_runtime_wait() scheduler._reset_partial_topology_runtime_wait() + scheduler.clear_integration_failure() scheduler.shaping_runtime_hash = 0 def test_full_reload_skips_refresh_when_topology_runtime_not_ready(self): -- knotmirror 0.0.1 From 86f758d79a29110a7e9948e1dc723ca71327f820 Mon Sep 17 00:00:00 2001 From: rchac Date: Tue, 21 Apr 2026 22:50:26 +0000 Subject: [PATCH 12/51] changes --- docs-es/v2.0/integrations-sonar-es.md | 1 + docs/v2.0/integrations-sonar.md | 1 + src/integrationSonar.py | 29 ++++++++++++++++++++++++++- src/test_integration_sonar.py | 15 +++++++++++++- 4 files changed, 44 insertions(+), 2 deletions(-) diff --git a/docs-es/v2.0/integrations-sonar-es.md b/docs-es/v2.0/integrations-sonar-es.md index 17c9baa3..85fdaf27 100644 --- a/docs-es/v2.0/integrations-sonar-es.md +++ b/docs-es/v2.0/integrations-sonar-es.md @@ -15,6 +15,7 @@ Use esta integración cuando Sonar sea su fuente de verdad CRM/NMS. - La integración refresca automáticamente los datos importados y de shaping que LibreQoS usa con Sonar. - `network.json` queda para despliegues DIY o manuales. - La integración importa IPs desde equipos de inventario, cuentas Radius e IPs asignadas directamente a la cuenta Sonar. Las IPs de Radius y de cuenta se agregan como dispositivos suplementarios de shaping y se deduplican contra las IPs de inventario. +- Las asignaciones IPv4 e IPv6 se separan en los campos correctos de LibreQoS. Los prefijos IPv6 de Sonar, como redes delegadas `/56`, se importan como asignaciones IPv6. - Use la WebUI para confirmar que la importación terminó correctamente. ## Referencia completa diff --git a/docs/v2.0/integrations-sonar.md b/docs/v2.0/integrations-sonar.md index a032aff8..24766596 100644 --- a/docs/v2.0/integrations-sonar.md +++ b/docs/v2.0/integrations-sonar.md @@ -8,6 +8,7 @@ Current behavior notes: - Paginated Sonar GraphQL requests now use a split connect/read timeout and retry transient read timeouts before failing the import. - Emitted Sonar identities are namespaced (for example `sonar:account:` and `sonar:device:`) so they remain stable across overrides and downstream tooling. - Account device discovery now preserves inventory-item IP handling and also imports Radius account and account-level IP assignments when they exist. Inventory-backed MACs are still used for AP mapping; Radius-only and account-level IPs are added as supplemental shaping devices and overlapping subnets are de-duplicated. +- IPv4 and IPv6 assignments are split into the correct LibreQoS fields. Sonar IPv6 prefixes such as delegated `/56` networks are imported as IPv6 assignments, not IPv4 device entries. - Sonar `child_accounts` are also imported when they expose their own service and usable IP data. If a child account lacks its own address, LibreQoS falls back to the parent account address so the child can still be emitted as its own circuit. - Sonar settings now support ISP-specific recurring-service fallback rates plus a recurring-service exclusion list. LibreQoS still prefers active `DATA` services first; recurring mappings are only used when an account has no usable `DATA` service. - If Sonar returns non-JSON content or GraphQL errors, the integration now raises a more specific error message showing the endpoint and a short response preview. diff --git a/src/integrationSonar.py b/src/integrationSonar.py index b87990af..4fba6110 100644 --- a/src/integrationSonar.py +++ b/src/integrationSonar.py @@ -1,5 +1,6 @@ from pythonCheck import checkPythonVersion checkPythonVersion() +import ipaddress import requests import subprocess import time @@ -227,6 +228,23 @@ def dedupeSubnets(subnets): return deduped +def splitIpVersions(subnets): + ipv4 = [] + ipv6 = [] + invalid = [] + for subnet in subnets or []: + try: + network = ipaddress.ip_network(subnet, strict=False) + except ValueError: + invalid.append(subnet) + continue + if network.version == 4: + ipv4.append(subnet) + else: + ipv6.append(subnet) + return ipv4, ipv6, invalid + + def normalizeServiceName(name): return (name or "").strip().casefold() @@ -773,6 +791,8 @@ def buildMacToApMap(aps): def sonarImportSummary(sites, aps, accounts): total_devices = 0 devices_with_ips = 0 + ipv4_assignments = 0 + ipv6_assignments = 0 account_level_ip_devices = 0 accounts_with_parent = 0 for account in accounts: @@ -782,12 +802,16 @@ def sonarImportSummary(sites, aps, accounts): total_devices += 1 if len(device.get('ips') or []) > 0: devices_with_ips += 1 + ipv4, ipv6, _invalid = splitIpVersions(device.get('ips', [])) + ipv4_assignments += len(ipv4) + ipv6_assignments += len(ipv6) if device.get('source') == 'account_ip_assignments': account_level_ip_devices += 1 return ( f"Sonar import summary: sites={len(sites)} aps={len(aps)} " f"accounts={len(accounts)} accounts_with_ap_parent={accounts_with_parent} " f"devices={total_devices} devices_with_ips={devices_with_ips} " + f"ipv4_assignments={ipv4_assignments} ipv6_assignments={ipv6_assignments} " f"account_level_ip_devices={account_level_ip_devices}" ) @@ -836,7 +860,10 @@ def createShaper(): net.addRawNode(customer) for device in account['devices']: - libre_device = NetworkNode(id=device['id'], displayName=device['name'],parentId=account['id'],type=NodeType.device, ipv4=device['ips'],ipv6=[],mac=device['mac']) + ipv4, ipv6, invalid_ips = splitIpVersions(device.get('ips', [])) + if invalid_ips: + print(f"Skipping invalid Sonar IP assignment(s) for {device['id']}: {invalid_ips}") + libre_device = NetworkNode(id=device['id'], displayName=device['name'],parentId=account['id'],type=NodeType.device, ipv4=ipv4,ipv6=ipv6,mac=device['mac']) net.addRawNode(libre_device) net.prepareTree() diff --git a/src/test_integration_sonar.py b/src/test_integration_sonar.py index 6d29a77f..aff493a8 100644 --- a/src/test_integration_sonar.py +++ b/src/test_integration_sonar.py @@ -180,6 +180,17 @@ class TestIntegrationSonarDevices(unittest.TestCase): self.assertEqual(devices[1]["mac"], "") self.assertEqual(devices[1]["source"], "account_ip_assignments") + def test_split_ip_versions_preserves_ipv6_prefixes(self): + ipv4, ipv6, invalid = integrationSonar.splitIpVersions([ + "100.64.8.80", + "2605:40c1:300::/56", + "not an ip", + ]) + + self.assertEqual(ipv4, ["100.64.8.80"]) + self.assertEqual(ipv6, ["2605:40c1:300::/56"]) + self.assertEqual(invalid, ["not an ip"]) + def test_account_level_ips_are_deduped_against_inventory_and_radius_ips(self): devices = integrationSonar.buildAccountDevices( sonar_account( @@ -429,7 +440,7 @@ class TestIntegrationSonarDevices(unittest.TestCase): }, { "id": "sonar:account-ip-assignments:1", - "ips": ["100.64.11.11"], + "ips": ["100.64.11.11", "2605:40c1:300::/56"], "source": "account_ip_assignments", }, ], @@ -447,6 +458,8 @@ class TestIntegrationSonarDevices(unittest.TestCase): self.assertIn("accounts_with_ap_parent=1", summary) self.assertIn("devices=2", summary) self.assertIn("devices_with_ips=1", summary) + self.assertIn("ipv4_assignments=1", summary) + self.assertIn("ipv6_assignments=1", summary) self.assertIn("account_level_ip_devices=1", summary) -- knotmirror 0.0.1 From 75dd8e0afb9a9a861cd2b88891f258ce77cd9898 Mon Sep 17 00:00:00 2001 From: Name <2718612@2178972821991.net> Date: Wed, 22 Apr 2026 12:48:14 -0600 Subject: [PATCH 13/51] changes --- src/rust/lqos_python/src/lib.rs | 27 +++++++++++----- src/scheduler.py | 41 +++++++++++++----------- src/test_scheduler.py | 55 +++++++++++++++++++++++++++++++++ 3 files changed, 97 insertions(+), 26 deletions(-) diff --git a/src/rust/lqos_python/src/lib.rs b/src/rust/lqos_python/src/lib.rs index fa165bac..4d27d4c9 100644 --- a/src/rust/lqos_python/src/lib.rs +++ b/src/rust/lqos_python/src/lib.rs @@ -3565,12 +3565,26 @@ impl Bakery { estimated_memory_bytes: detail.estimated_memory_bytes, }) .collect::>(); + let qdisc_counts_fit = estimate + .interfaces + .values() + .all(|count| *count <= estimate.safe_budget); + let preflight_status = match (qdisc_counts_fit, estimate.memory_ok) { + (true, true) => "fits preflight", + (false, true) => "exceeds qdisc-count preflight", + (true, false) => "passed qdisc-count preflight but failed memory preflight", + (false, false) => "exceeds qdisc-count preflight and failed memory preflight", + }; let memory_summary = if let Some(snapshot) = estimate.memory_snapshot.as_ref() { + let memory_floor = lqos_bakery::BAKERY_MEMORY_GUARD_MIN_AVAILABLE_BYTES; + let required_available_bytes = + memory_floor.saturating_add(estimate.estimated_total_memory_bytes); format!( - "estimated qdisc memory {} bytes with {} bytes currently available and safety floor {} bytes", + "estimated qdisc memory {} bytes; available memory {} bytes; required minimum {} bytes (safety floor {} bytes plus estimate)", estimate.estimated_total_memory_bytes, snapshot.available_bytes, - lqos_bakery::BAKERY_MEMORY_GUARD_MIN_AVAILABLE_BYTES + required_available_bytes, + memory_floor ) } else { format!( @@ -3580,8 +3594,7 @@ impl Bakery { }; let summary = if interface_reports.is_empty() { format!( - "Planned queue model {} preflight. No shaping interfaces were queued; {memory_summary}.", - if is_ok { "fits" } else { "exceeds" }, + "Planned queue model {preflight_status}. No shaping interfaces were queued; {memory_summary}.", ) } else { let interface_summary = interface_reports @@ -3603,10 +3616,8 @@ impl Bakery { .collect::>() .join(", "); format!( - "Planned queue model {} preflight. {interface_summary}; safe budget {}, kernel limit {}; {memory_summary}.", - if is_ok { "fits" } else { "exceeds" }, - estimate.safe_budget, - estimate.hard_limit, + "Planned queue model {preflight_status}. {interface_summary}; safe budget {}, kernel limit {}; {memory_summary}.", + estimate.safe_budget, estimate.hard_limit, ) }; let _ = run_query(vec![BusRequest::BakeryReportPreflight { diff --git a/src/scheduler.py b/src/scheduler.py index 12e18959..9faf5cb5 100644 --- a/src/scheduler.py +++ b/src/scheduler.py @@ -152,6 +152,17 @@ def publish_scheduler_progress(active: bool, phase: str, phase_label: str, step_ print(f"Failed to publish scheduler progress: {e}") +def publish_scheduler_ready(step_count: int): + publish_scheduler_progress( + False, + "ready", + "Scheduler ready", + step_count, + step_count, + percent=100, + ) + + def report_scheduler_runtime_failure(context: str, exc: Exception, *, startup: bool = False): message = f"{context}: {exc}" print(message) @@ -1077,7 +1088,7 @@ def importAndShapePartialReload(): shaping_runtime_hash = calculate_shaping_runtime_hash() if shaping_runtime_hash != 0: set_scheduler_status_bus_enabled(True) - publish_scheduler_progress(False, "ready", "Scheduler ready", SCHEDULER_REFRESH_STEP_COUNT, SCHEDULER_REFRESH_STEP_COUNT, percent=100) + publish_scheduler_ready(SCHEDULER_REFRESH_STEP_COUNT) def topology_runtime_status_path(): @@ -1361,14 +1372,7 @@ def _continue_startup_topology_runtime_wait(): _reset_startup_topology_runtime_wait() if shaping_runtime_hash != 0: clear_scheduler_error() - publish_scheduler_progress( - False, - "ready", - "Scheduler ready", - SCHEDULER_STARTUP_STEP_COUNT, - SCHEDULER_STARTUP_STEP_COUNT, - percent=100, - ) + publish_scheduler_ready(SCHEDULER_STARTUP_STEP_COUNT) return report_scheduler_runtime_failure( @@ -1468,14 +1472,7 @@ def _continue_partial_topology_runtime_wait(): return _reset_partial_topology_runtime_wait() clear_scheduler_error() - publish_scheduler_progress( - False, - "ready", - "Scheduler ready", - SCHEDULER_REFRESH_STEP_COUNT, - SCHEDULER_REFRESH_STEP_COUNT, - percent=100, - ) + publish_scheduler_ready(SCHEDULER_REFRESH_STEP_COUNT) return started = partial_topology_runtime_started_monotonic @@ -1549,6 +1546,14 @@ def topology_runtime_refresh_tick(): report_scheduler_runtime_failure("Topology runtime refresh failed", e) return shaping_runtime_hash = calculate_shaping_runtime_hash() + if shaping_runtime_hash == 0: + report_scheduler_runtime_failure( + "Topology runtime refresh failed", + RuntimeError("Shaping runtime hash was not published after topology runtime refresh."), + ) + return + clear_scheduler_error() + publish_scheduler_ready(SCHEDULER_REFRESH_STEP_COUNT) def not_dead_yet(): @@ -1571,7 +1576,7 @@ def run_scheduler_main(): try: startup_ready = importAndShapeFullReload() if startup_ready: - publish_scheduler_progress(False, "ready", "Scheduler ready", SCHEDULER_STARTUP_STEP_COUNT, SCHEDULER_STARTUP_STEP_COUNT, percent=100) + publish_scheduler_ready(SCHEDULER_STARTUP_STEP_COUNT) except ValidationFailure as e: report_scheduler_validation_failure( "Scheduler startup shaping refresh blocked by validation", diff --git a/src/test_scheduler.py b/src/test_scheduler.py index e69deb3f..b9f69ffe 100644 --- a/src/test_scheduler.py +++ b/src/test_scheduler.py @@ -416,6 +416,61 @@ class TestSchedulerLogging(unittest.TestCase): ) ) + def test_topology_runtime_refresh_tick_clears_error_after_success(self): + with patch.object(scheduler, "ensure_topology_runtime_process"): + with patch.object( + scheduler, + "topology_runtime_readiness_detail", + return_value=(True, "", "generation-1"), + ): + with patch.object( + scheduler, + "calculate_shaping_runtime_hash", + side_effect=[5, 5], + ): + with patch.object(scheduler, "refreshShapers") as mock_refresh: + with patch.object(scheduler, "clear_scheduler_error") as mock_clear_error: + with patch.object(scheduler, "publish_scheduler_progress") as mock_progress: + scheduler.shaping_runtime_hash = 1 + scheduler.topology_runtime_refresh_tick() + + mock_refresh.assert_called_once() + mock_clear_error.assert_called_once() + self.assertEqual(scheduler.shaping_runtime_hash, 5) + self.assertTrue( + any( + call.args[:3] == ( + False, + "ready", + "Scheduler ready", + ) + for call in mock_progress.call_args_list + ) + ) + + def test_topology_runtime_refresh_tick_reports_missing_hash_after_success(self): + with patch.object(scheduler, "ensure_topology_runtime_process"): + with patch.object( + scheduler, + "topology_runtime_readiness_detail", + return_value=(True, "", "generation-1"), + ): + with patch.object( + scheduler, + "calculate_shaping_runtime_hash", + side_effect=[5, 0], + ): + with patch.object(scheduler, "refreshShapers"): + with patch.object(scheduler, "scheduler_error") as mock_scheduler_error: + with patch.object(scheduler, "clear_scheduler_error") as mock_clear_error: + scheduler.shaping_runtime_hash = 1 + scheduler.topology_runtime_refresh_tick() + + mock_clear_error.assert_not_called() + mock_scheduler_error.assert_called_once_with( + "Topology runtime refresh failed: Shaping runtime hash was not published after topology runtime refresh." + ) + def test_topology_runtime_refresh_tick_skips_until_initial_shaping_succeeds(self): with patch.object(scheduler, "ensure_topology_runtime_process") as mock_ensure: with patch.object(scheduler, "calculate_shaping_runtime_hash") as mock_hash: -- knotmirror 0.0.1 From 0f58178203d3f05a1d66f5b60a818b3c79f864e2 Mon Sep 17 00:00:00 2001 From: rchac Date: Wed, 22 Apr 2026 23:10:12 +0000 Subject: [PATCH 14/51] changes --- docs-es/v2.0/integrations-splynx-es.md | 2 + docs/v2.0/integrations-splynx.md | 4 +- src/integrationCommon.py | 4 +- src/integrationSplynx.py | 45 +- .../lqos_config/src/topology_runtime_state.rs | 2 +- .../src/runtime_inputs.rs | 27 +- src/rust/lqos_network_devices/src/tests.rs | 31 +- src/rust/lqos_topology/src/lib.rs | 392 ++++++++++++++++-- src/rust/lqos_topology/src/runtime.rs | 11 +- .../lqos_topology_compile/src/compile_mode.rs | 176 +------- src/test_integration_splynx.py | 39 +- 11 files changed, 469 insertions(+), 264 deletions(-) diff --git a/docs-es/v2.0/integrations-splynx-es.md b/docs-es/v2.0/integrations-splynx-es.md index 65a09651..8f40e100 100644 --- a/docs-es/v2.0/integrations-splynx-es.md +++ b/docs-es/v2.0/integrations-splynx-es.md @@ -26,6 +26,8 @@ Después, ejecute una sincronización manual y valide salidas antes de aumentar - `network.json` queda para despliegues DIY o manuales. - Use la WebUI para confirmar que la importación y la profundidad del árbol son las esperadas. - Use WebUI para ajustes operativos diarios. +- Cuando Splynx no puede inferir el padre de un circuito desde `access_device` o los metadatos del router, LibreQoS deja ese circuito sin padre para shaping en lugar de adjuntarlo a un sitio o AP sintético. Corrija el padre en Splynx o Topology Manager si debe aparecer bajo un sitio o AP real. +- En modo `ap_site`, LibreQoS trata los Network Sites de Splynx como contenedores de sitio y las filas de monitoreo con `access_device = 1` como AP o nodos de acceso. Los contenedores de sitio grandes pueden virtualizarse automáticamente cuando superan `queue_auto_virtualize_threshold_mbps`, tienen ramas de cola hijas y no tienen circuitos conectados directamente al ID del sitio. Defina una anulación virtual del nodo en `false` cuando un sitio específico deba permanecer como cola física. ## Validación en 5 minutos después de cambios Splynx diff --git a/docs/v2.0/integrations-splynx.md b/docs/v2.0/integrations-splynx.md index 1066a671..b029d36b 100644 --- a/docs/v2.0/integrations-splynx.md +++ b/docs/v2.0/integrations-splynx.md @@ -24,7 +24,9 @@ LibreQoS supports multiple topology strategies for Splynx integration to balance | `ap_site` | Two layers: Site → AP → Clients | Medium | **Default**. Best balance of structure and operator clarity | | `full` | Complete monitoring-parent topology mapping | Highest | Preserves the richer Splynx monitoring hierarchy instead of flattening to Network Sites | -When Splynx `full` cannot infer a circuit parent from `access_device` or router metadata, LibreQoS now groups those circuits under a single generated `LibreQoS Unattached [Site]` node instead of leaving them fully unresolved at runtime. +When Splynx cannot infer a circuit parent from `access_device` or router metadata, LibreQoS leaves the circuit unparented for shaping instead of attaching it to a synthetic site or AP. Fix the parent in Splynx or Topology Manager if the circuit should appear under a real site or AP. + +In `ap_site` mode, LibreQoS treats Splynx Network Sites as site containers and monitoring rows with `access_device = 1` as AP/access nodes. Large site containers can be virtualized automatically when they exceed `queue_auto_virtualize_threshold_mbps`, have child queue branches, and have no circuits directly attached to the site node ID. Set a node virtual override to `false` when a specific site must remain as a physical queue. Configure the shared topology mode in `/etc/lqos.conf` under the `[topology]` section: diff --git a/src/integrationCommon.py b/src/integrationCommon.py index 6d52b4bf..0570c074 100644 --- a/src/integrationCommon.py +++ b/src/integrationCommon.py @@ -776,8 +776,8 @@ class NetworkGraph: device["mac"], ipv4, ipv6, - int(1), - int(1), + max(1.0, round(float(circuit["download"]*0.98), 2)), + max(1.0, round(float(circuit["upload"])*0.98, 2)), max(1.0, round(float(circuit["download"]), 2)), max(1.0, round(float(circuit["upload"]), 2)), "" diff --git a/src/integrationSplynx.py b/src/integrationSplynx.py index 95dd5bf2..e3f00c92 100644 --- a/src/integrationSplynx.py +++ b/src/integrationSplynx.py @@ -90,36 +90,6 @@ def normalize_splynx_graph_id(value): return str(value) -def splynx_generated_unattached_site_id(): - """ - Stable raw graph ID for Splynx full-mode circuits with no inferred parent. - """ - return "splynx_generated_unattached_site" - - -def splynx_generated_unattached_site_network_id(): - """ - Stable exported topology ID for Splynx full-mode fallback grouping. - """ - return "libreqos:generated:splynx:site:unattached" - - -def splynx_generated_unattached_site_name(): - """ - Display name for the explicit Splynx full-mode fallback site. - """ - return "LibreQoS Unattached [Site]" - - -def splynx_generated_unattached_parent_id(strategy_name: str): - """ - Only full mode should materialize a stable generated site for unresolved parents. - Other modes handle unresolved circuits through their own compiler/runtime fallbacks. - """ - if strategy_name == "full": - return splynx_generated_unattached_site_id() - return None - def supplement_existing_devices_with_online_ips(net, allServices, service_ids_handled, customersOnline, cust_id_to_name, allocated_ipv4s, allocated_ipv6s, device_by_service_id=None): """ For services already handled (devices created from static IPs), supplement missing @@ -424,19 +394,6 @@ def run_splynx_pipeline(strategy_name: str): # ap_site and full print("Creating site and AP infrastructure") createInfrastructureNodes(net, monitoring, hardware_name, hardware_parent, hardware_type, siteBandwidth, hardware_name_extended) - if strategy_name == 'full': - net.addRawNode( - NetworkNode( - id=splynx_generated_unattached_site_id(), - displayName=splynx_generated_unattached_site_name(), - type=NodeType.site, - parentId=None, - download=10000, - upload=10000, - address=splynx_generated_unattached_site_name(), - networkJsonId=splynx_generated_unattached_site_network_id(), - ) - ) # Parent selector per strategy def select_parent(serviceItem): @@ -450,7 +407,7 @@ def run_splynx_pipeline(strategy_name: str): return None if strategy_name == 'ap_only': return parent_node_id if (parent_node_id in ap_nodes) else None - return parent_node_id or splynx_generated_unattached_parent_id(strategy_name) + return parent_node_id # Run pipeline build_infrastructure() diff --git a/src/rust/lqos_config/src/topology_runtime_state.rs b/src/rust/lqos_config/src/topology_runtime_state.rs index 3bdb1e64..3e1c8954 100644 --- a/src/rust/lqos_config/src/topology_runtime_state.rs +++ b/src/rust/lqos_config/src/topology_runtime_state.rs @@ -694,7 +694,7 @@ fn normalized_json_value_for_generation(value: &Value) -> Value { match value { Value::Object(map) => { let mut entries = map.iter().collect::>(); - entries.sort_unstable_by(|(left_key, _), (right_key, _)| left_key.cmp(right_key)); + entries.sort_unstable_by_key(|(key, _)| *key); let mut normalized = serde_json::Map::with_capacity(entries.len()); for (key, child) in entries { normalized.insert(key.clone(), normalized_json_value_for_generation(child)); diff --git a/src/rust/lqos_network_devices/src/runtime_inputs.rs b/src/rust/lqos_network_devices/src/runtime_inputs.rs index 714878a5..3e1f302b 100644 --- a/src/rust/lqos_network_devices/src/runtime_inputs.rs +++ b/src/rust/lqos_network_devices/src/runtime_inputs.rs @@ -5,7 +5,10 @@ //! into the shaped-device snapshot used by `lqosd`. use anyhow::Result; -use lqos_config::{Config, ConfigShapedDevices, ShapedDevice, TopologyShapingInputsFile}; +use lqos_config::{ + Config, ConfigShapedDevices, ShapedDevice, TopologyShapingInputsFile, + TopologyShapingResolutionSource, +}; use std::net::{Ipv4Addr, Ipv6Addr}; use tracing::debug; @@ -58,6 +61,22 @@ fn parse_ipv6_list(values: &[String]) -> Vec<(Ipv6Addr, u32)> { .collect() } +fn runtime_parent_for_circuit( + circuit: &lqos_config::TopologyShapingCircuitInput, +) -> (String, Option) { + if circuit.resolution_source == TopologyShapingResolutionSource::RuntimeFallback { + return (String::new(), None); + } + + let parent_node = optional_trimmed_string(&circuit.effective_parent_node_name) + .or_else(|| circuit.logical_parent_node_name.clone()) + .unwrap_or_default(); + let parent_node_id = optional_trimmed_string(&circuit.effective_parent_node_id) + .or_else(|| circuit.logical_parent_node_id.clone()); + + (parent_node, parent_node_id) +} + /// Loads the currently active runtime shaping inputs when available. pub(crate) fn load_ready_runtime_shaping_inputs( config: &Config, @@ -80,11 +99,7 @@ pub(crate) fn shaped_devices_from_runtime_inputs( ) -> ConfigShapedDevices { let mut devices = Vec::new(); for circuit in &shaping_inputs.circuits { - let parent_node = optional_trimmed_string(&circuit.effective_parent_node_name) - .or_else(|| circuit.logical_parent_node_name.clone()) - .unwrap_or_default(); - let parent_node_id = optional_trimmed_string(&circuit.effective_parent_node_id) - .or_else(|| circuit.logical_parent_node_id.clone()); + let (parent_node, parent_node_id) = runtime_parent_for_circuit(circuit); for device in &circuit.devices { devices.push(ShapedDevice { circuit_id: circuit.circuit_id.clone(), diff --git a/src/rust/lqos_network_devices/src/tests.rs b/src/rust/lqos_network_devices/src/tests.rs index d51828ab..2d71ade6 100644 --- a/src/rust/lqos_network_devices/src/tests.rs +++ b/src/rust/lqos_network_devices/src/tests.rs @@ -5,7 +5,7 @@ use crate::{ use lqos_config::{ CircuitAnchorsFile, Config, ConfigShapedDevices, NetworkJsonNode, ShapedDevice, TOPOLOGY_RUNTIME_STATUS_FILENAME, TopologyShapingCircuitInput, TopologyShapingDeviceInput, - TopologyShapingInputsFile, + TopologyShapingInputsFile, TopologyShapingResolutionSource, }; use lqos_topology_compile::{ImportedTopologyBundle, TopologyImportFile}; use lqos_utils::rtt::RttBuffer; @@ -337,6 +337,35 @@ fn runtime_inputs_build_shaped_devices_from_effective_parent_data() { assert_eq!(shaped.devices[0].circuit_id, "circuit-1"); } +#[test] +fn runtime_inputs_leave_runtime_fallback_circuits_unparented() { + let _guard = TEST_LOCK.lock(); + + let shaping_inputs = TopologyShapingInputsFile { + circuits: vec![TopologyShapingCircuitInput { + circuit_id: "circuit-1".to_string(), + circuit_name: "Circuit Alpha".to_string(), + logical_parent_node_name: Some("LibreQoS Unattached [Site]".to_string()), + logical_parent_node_id: Some("libreqos:generated:splynx:site:unattached".to_string()), + resolution_source: TopologyShapingResolutionSource::RuntimeFallback, + devices: vec![TopologyShapingDeviceInput { + device_id: "device-1".to_string(), + device_name: "Device Alpha".to_string(), + ipv4: vec!["192.168.1.10/32".to_string()], + ..TopologyShapingDeviceInput::default() + }], + ..TopologyShapingCircuitInput::default() + }], + ..TopologyShapingInputsFile::default() + }; + + let shaped = runtime_inputs::shaped_devices_from_runtime_inputs(&shaping_inputs); + assert_eq!(shaped.devices.len(), 1); + assert_eq!(shaped.devices[0].parent_node, ""); + assert_eq!(shaped.devices[0].parent_node_id, None); + assert_eq!(shaped.devices[0].circuit_id, "circuit-1"); +} + #[test] fn load_shaped_devices_uses_topology_import_when_runtime_inputs_are_empty() { let _guard = TEST_LOCK.lock(); diff --git a/src/rust/lqos_topology/src/lib.rs b/src/rust/lqos_topology/src/lib.rs index 03c72d37..17ef7764 100644 --- a/src/rust/lqos_topology/src/lib.rs +++ b/src/rust/lqos_topology/src/lib.rs @@ -19,7 +19,8 @@ use lqos_config::{ topology_runtime_status_path, topology_shaping_inputs_path, }; use lqos_overrides::{ - CircuitAdjustment, OverrideStore, TopologyAttachmentMode, TopologyOverridesFile, + CircuitAdjustment, NetworkAdjustment, OverrideStore, TopologyAttachmentMode, + TopologyOverridesFile, }; use lqos_topology_compile::{TopologyCompiledShapingFile, TopologyImportFile}; use serde_json::{Map, Value}; @@ -985,6 +986,88 @@ fn load_runtime_shaping_overrides(config: &Config) -> Result, + forced_visible_node_names: HashSet, +} + +fn insert_optional_node_id(target: &mut HashSet, value: Option<&str>) { + if let Some(node_id) = value.map(str::trim).filter(|value| !value.is_empty()) { + target.insert(node_id.to_string()); + } +} + +fn collect_direct_circuit_node_ids( + shaped_devices: &ConfigShapedDevices, + circuit_anchors: &[CircuitAnchor], +) -> HashSet { + let mut direct_node_ids = HashSet::new(); + for device in &shaped_devices.devices { + insert_optional_node_id(&mut direct_node_ids, device.parent_node_id.as_deref()); + insert_optional_node_id(&mut direct_node_ids, device.anchor_node_id.as_deref()); + } + for anchor in circuit_anchors { + insert_optional_node_id(&mut direct_node_ids, Some(anchor.anchor_node_id.as_str())); + } + direct_node_ids +} + +fn forced_visible_node_names(overrides: &lqos_overrides::OverrideFile) -> HashSet { + overrides + .network_adjustments() + .iter() + .filter_map(|adjustment| match adjustment { + NetworkAdjustment::SetNodeVirtual { + node_name, + virtual_node: false, + } => Some(node_name.trim()), + _ => None, + }) + .filter(|node_name| !node_name.is_empty()) + .map(ToOwned::to_owned) + .collect() +} + +fn load_queue_virtualization_context(config: &Config) -> Result { + let runtime_overrides = load_runtime_shaping_overrides(config)?; + let direct_circuit_node_ids = if topology_import_ingress_enabled(config) { + let Some((mut shaped_devices, circuit_anchors)) = + load_integration_shaping_artifacts(config)? + else { + return Ok(QueueVirtualizationContext { + forced_visible_node_names: forced_visible_node_names(&runtime_overrides), + ..QueueVirtualizationContext::default() + }); + }; + let runtime_devices = apply_runtime_shaped_device_overrides( + std::mem::take(&mut shaped_devices.devices), + &runtime_overrides, + ); + shaped_devices.replace_with_new_data(runtime_devices); + collect_direct_circuit_node_ids(&shaped_devices, &circuit_anchors) + } else { + let shaped_devices_path = ConfigShapedDevices::path_for_config(config); + if !shaped_devices_path.exists() { + HashSet::new() + } else { + let shaped_devices_mtime = std::fs::metadata(&shaped_devices_path) + .ok() + .and_then(|metadata| metadata.modified().ok()); + let shaped_devices = ConfigShapedDevices::load_for_config(config).with_context( + || "Unable to load ShapedDevices.csv while preparing queue virtualization", + )?; + let circuit_anchors = load_circuit_anchors(config, shaped_devices_mtime); + collect_direct_circuit_node_ids(&shaped_devices, &circuit_anchors) + } + }; + + Ok(QueueVirtualizationContext { + direct_circuit_node_ids, + forced_visible_node_names: forced_visible_node_names(&runtime_overrides), + }) +} + fn apply_runtime_shaped_device_overrides( base_devices: Vec, overrides: &lqos_overrides::OverrideFile, @@ -1161,8 +1244,41 @@ pub fn build_effective_topology_artifacts_from_canonical( health: &TopologyAttachmentHealthStateFile, ) -> std::result::Result> { let prepared = prepared_runtime_topology_editor_state(&canonical.to_editor_state(), overrides); + let virtualization = QueueVirtualizationContext::default(); + build_effective_topology_artifacts_from_prepared( + config, + canonical, + &prepared, + overrides, + health, + &virtualization, + ) +} + +/// Builds validated effective-topology artifacts with runtime queue-virtualization guards. +/// +/// Side effects: reads shaping artifacts and effective override layers so automatic +/// virtualization can avoid nodes that have direct circuit attachments or explicit +/// visible overrides. +pub fn build_effective_topology_artifacts_from_canonical_with_runtime_queue_context( + config: &Config, + canonical: &TopologyCanonicalStateFile, + overrides: &TopologyOverridesFile, + health: &TopologyAttachmentHealthStateFile, +) -> std::result::Result> { + let prepared = prepared_runtime_topology_editor_state(&canonical.to_editor_state(), overrides); + let virtualization = load_queue_virtualization_context(config).map_err(|err| { + vec![format!( + "Unable to load queue virtualization context: {err:#}" + )] + })?; build_effective_topology_artifacts_from_prepared( - config, canonical, &prepared, overrides, health, + config, + canonical, + &prepared, + overrides, + health, + &virtualization, ) } @@ -1192,6 +1308,7 @@ fn build_effective_topology_artifacts_from_prepared( prepared: &TopologyEditorStateFile, overrides: &TopologyOverridesFile, health: &TopologyAttachmentHealthStateFile, + virtualization: &QueueVirtualizationContext, ) -> std::result::Result> { let effective = compute_effective_state_from_prepared(config, prepared, overrides, health); let ui_state = @@ -1206,7 +1323,13 @@ fn build_effective_topology_artifacts_from_prepared( Some(runtime_flat_bucket_network(config)) } else { canonical_network.as_object().map(|_| { - apply_effective_topology_to_canonical_state(config, canonical, &ui_state, &effective) + apply_effective_topology_to_canonical_state( + config, + canonical, + &ui_state, + &effective, + virtualization, + ) }) }; @@ -1217,6 +1340,7 @@ fn build_effective_topology_artifacts_from_prepared( &ui_state, &effective, effective_network, + virtualization, )?; } @@ -2401,41 +2525,74 @@ fn resolved_queue_visibility_policy( ui_node: &TopologyEditorNode, tree_node: Option<&Value>, child_branch_counts: &HashMap, + virtualization: &QueueVirtualizationContext, ) -> TopologyQueueVisibilityPolicy { match ui_node.queue_visibility_policy { - TopologyQueueVisibilityPolicy::QueueVisible => TopologyQueueVisibilityPolicy::QueueVisible, + TopologyQueueVisibilityPolicy::QueueVisible => resolved_auto_queue_visibility_policy( + config, + ui_node, + tree_node, + child_branch_counts, + virtualization, + ), TopologyQueueVisibilityPolicy::QueueHiddenPromoteChildren => { TopologyQueueVisibilityPolicy::QueueHiddenPromoteChildren } - TopologyQueueVisibilityPolicy::QueueAuto => { - let Some(tree_node) = tree_node.and_then(Value::as_object) else { - return TopologyQueueVisibilityPolicy::QueueVisible; - }; - let is_site = tree_node - .get("type") - .and_then(Value::as_str) - .is_some_and(|kind| kind.eq_ignore_ascii_case("site")); - if !is_site { - return TopologyQueueVisibilityPolicy::QueueVisible; - } - if child_branch_counts - .get(ui_node.node_id.as_str()) - .copied() - .unwrap_or_default() - == 0 - { - return TopologyQueueVisibilityPolicy::QueueVisible; - } - let threshold = config.topology.queue_auto_virtualize_threshold_mbps; - if threshold == 0 { - return TopologyQueueVisibilityPolicy::QueueVisible; - } - if node_capacity_mbps(tree_node) >= threshold { - TopologyQueueVisibilityPolicy::QueueHiddenPromoteChildren - } else { - TopologyQueueVisibilityPolicy::QueueVisible - } - } + TopologyQueueVisibilityPolicy::QueueAuto => resolved_auto_queue_visibility_policy( + config, + ui_node, + tree_node, + child_branch_counts, + virtualization, + ), + } +} + +fn resolved_auto_queue_visibility_policy( + config: &Config, + ui_node: &TopologyEditorNode, + tree_node: Option<&Value>, + child_branch_counts: &HashMap, + virtualization: &QueueVirtualizationContext, +) -> TopologyQueueVisibilityPolicy { + if virtualization + .forced_visible_node_names + .contains(ui_node.node_name.as_str()) + { + return TopologyQueueVisibilityPolicy::QueueVisible; + } + if virtualization + .direct_circuit_node_ids + .contains(ui_node.node_id.as_str()) + { + return TopologyQueueVisibilityPolicy::QueueVisible; + } + let Some(tree_node) = tree_node.and_then(Value::as_object) else { + return TopologyQueueVisibilityPolicy::QueueVisible; + }; + let is_site = tree_node + .get("type") + .and_then(Value::as_str) + .is_some_and(|kind| kind.eq_ignore_ascii_case("site")); + if !is_site { + return TopologyQueueVisibilityPolicy::QueueVisible; + } + if child_branch_counts + .get(ui_node.node_id.as_str()) + .copied() + .unwrap_or_default() + == 0 + { + return TopologyQueueVisibilityPolicy::QueueVisible; + } + let threshold = config.topology.queue_auto_virtualize_threshold_mbps; + if threshold == 0 { + return TopologyQueueVisibilityPolicy::QueueVisible; + } + if node_capacity_mbps(tree_node) >= threshold { + TopologyQueueVisibilityPolicy::QueueHiddenPromoteChildren + } else { + TopologyQueueVisibilityPolicy::QueueVisible } } @@ -2638,6 +2795,7 @@ fn apply_queue_hidden_node_virtualization( config: &Config, ui_state: &TopologyEditorStateFile, root: &mut Map, + virtualization: &QueueVirtualizationContext, ) { let ui_by_id = ui_state .nodes @@ -2655,6 +2813,7 @@ fn apply_queue_hidden_node_virtualization( ui_node, find_node_by_id(root, &hidden_node_id), &child_branch_counts, + virtualization, ); if resolved_policy != TopologyQueueVisibilityPolicy::QueueHiddenPromoteChildren { continue; @@ -3870,6 +4029,7 @@ fn validate_effective_topology_network_from_canonical( ui_state: &TopologyEditorStateFile, effective: &TopologyEffectiveStateFile, effective_network: &Value, + virtualization: &QueueVirtualizationContext, ) -> Result<(), Vec> { let mut errors = Vec::new(); validate_effective_node_identity_consistency(ui_state, effective, &mut errors); @@ -3897,6 +4057,7 @@ fn validate_effective_topology_network_from_canonical( node, queue_policy_root.and_then(|root| find_node_by_id(root, &node.node_id)), &child_branch_counts, + virtualization, ) == TopologyQueueVisibilityPolicy::QueueHiddenPromoteChildren { continue; @@ -3944,6 +4105,7 @@ pub fn validate_effective_topology_network( ui_state, effective, effective_network, + &QueueVirtualizationContext::default(), ) } @@ -3955,11 +4117,12 @@ fn apply_effective_topology_to_network_json_from_canonical( canonical: &TopologyCanonicalStateFile, ui_state: &TopologyEditorStateFile, effective: &TopologyEffectiveStateFile, + virtualization: &QueueVirtualizationContext, ) -> Value { let mut out = apply_effective_topology_reparenting_only(canonical_network, ui_state, effective); if let Some(root) = out.as_object_mut() { recompile_effective_network_bandwidths(root, canonical, ui_state, effective); - apply_queue_hidden_node_virtualization(config, ui_state, root); + apply_queue_hidden_node_virtualization(config, ui_state, root, virtualization); apply_runtime_squashing(config, ui_state, effective, root); } out @@ -3988,6 +4151,7 @@ pub fn apply_effective_topology_to_network_json( &canonical_state, ui_state, effective, + &QueueVirtualizationContext::default(), ) } @@ -3996,6 +4160,7 @@ fn apply_effective_topology_to_canonical_state( canonical: &TopologyCanonicalStateFile, ui_state: &TopologyEditorStateFile, effective: &TopologyEffectiveStateFile, + virtualization: &QueueVirtualizationContext, ) -> Value { let canonical_network = if canonical.ingress_kind == TopologyCanonicalIngressKind::NativeIntegration { @@ -4009,14 +4174,16 @@ fn apply_effective_topology_to_canonical_state( canonical, ui_state, effective, + virtualization, ) } #[cfg(test)] mod tests { use super::{ - EffectiveTopologyArtifacts, apply_effective_topology_to_canonical_state, - apply_effective_topology_to_network_json, auto_attachment_option, + EffectiveTopologyArtifacts, QueueVirtualizationContext, + apply_effective_topology_to_canonical_state, apply_effective_topology_to_network_json, + apply_effective_topology_to_network_json_from_canonical, auto_attachment_option, build_effective_topology_artifacts, build_effective_topology_artifacts_from_canonical, build_shaping_inputs, compute_effective_state, publish_effective_topology_artifacts, publish_topology_runtime_error_status, validate_effective_topology_network, @@ -4033,6 +4200,7 @@ mod tests { }; use lqos_overrides::{TopologyAttachmentMode, TopologyOverridesFile}; use serde_json::{Value, json}; + use std::collections::HashSet; use std::fs; use std::path::PathBuf; use std::time::{SystemTime, UNIX_EPOCH}; @@ -4059,6 +4227,81 @@ mod tests { .unwrap_or_else(|_| panic!("{label} should write")); } + fn site_with_ap_fixture() -> ( + Config, + TopologyCanonicalStateFile, + TopologyEditorStateFile, + TopologyEffectiveStateFile, + ) { + let mut config = Config::default(); + config.topology.queue_auto_virtualize_threshold_mbps = 5_000; + let editor_state = TopologyEditorStateFile { + schema_version: 1, + source: "splynx/ap_site".to_string(), + generated_unix: None, + ingress_identity: None, + nodes: vec![ + TopologyEditorNode { + node_id: "site-agg".to_string(), + node_name: "Aggregation".to_string(), + queue_visibility_policy: TopologyQueueVisibilityPolicy::QueueVisible, + ..TopologyEditorNode::default() + }, + TopologyEditorNode { + node_id: "ap-1".to_string(), + node_name: "AP One".to_string(), + current_parent_node_id: Some("site-agg".to_string()), + current_parent_node_name: Some("Aggregation".to_string()), + queue_visibility_policy: TopologyQueueVisibilityPolicy::QueueVisible, + ..TopologyEditorNode::default() + }, + ], + }; + let network = json!({ + "Aggregation": { + "children": { + "AP One": { + "children": {}, + "downloadBandwidthMbps": 1000, + "id": "ap-1", + "name": "AP One", + "type": "AP", + "uploadBandwidthMbps": 1000 + } + }, + "downloadBandwidthMbps": 7000, + "id": "site-agg", + "name": "Aggregation", + "type": "Site", + "uploadBandwidthMbps": 7000 + } + }); + let canonical = TopologyCanonicalStateFile::from_editor_and_network( + &editor_state, + &network, + TopologyCanonicalIngressKind::NativeIntegration, + ); + let effective = TopologyEffectiveStateFile { + schema_version: 1, + generated_unix: None, + canonical_generated_unix: None, + health_generated_unix: None, + nodes: vec![ + TopologyEffectiveNodeState { + node_id: "site-agg".to_string(), + logical_parent_node_id: String::new(), + ..TopologyEffectiveNodeState::default() + }, + TopologyEffectiveNodeState { + node_id: "ap-1".to_string(), + logical_parent_node_id: "site-agg".to_string(), + ..TopologyEffectiveNodeState::default() + }, + ], + }; + (config, canonical, editor_state, effective) + } + fn runtime_tree_max_depth(value: &Value) -> usize { fn recurse(node: &Value, depth: usize) -> usize { let Some(map) = node.as_object() else { @@ -5571,6 +5814,7 @@ mod tests { }], }], }, + &QueueVirtualizationContext::default(), ); let root_children = squashed @@ -5740,6 +5984,7 @@ mod tests { &canonical, &editor_state, &effective, + &QueueVirtualizationContext::default(), ); let root = effective_network .as_object() @@ -5756,6 +6001,81 @@ mod tests { assert!(west_children.get("Tuscany Ridge").is_some()); } + #[test] + fn large_visible_site_without_direct_circuits_auto_virtualizes() { + let (config, canonical, editor_state, effective) = site_with_ap_fixture(); + + let effective_network = apply_effective_topology_to_canonical_state( + &config, + &canonical, + &editor_state, + &effective, + &QueueVirtualizationContext::default(), + ); + let root = effective_network + .as_object() + .expect("effective export should remain an object tree"); + let site = root["Aggregation"] + .as_object() + .expect("Aggregation should remain exported"); + + assert_eq!(site.get("virtual").and_then(Value::as_bool), Some(true)); + } + + #[test] + fn large_site_with_direct_circuit_stays_visible() { + let (config, canonical, editor_state, effective) = site_with_ap_fixture(); + let virtualization = QueueVirtualizationContext { + direct_circuit_node_ids: HashSet::from(["site-agg".to_string()]), + forced_visible_node_names: HashSet::new(), + }; + + let canonical_network = canonical.insight_topology_network_json(); + let effective_network = apply_effective_topology_to_network_json_from_canonical( + &config, + &canonical_network, + &canonical, + &editor_state, + &effective, + &virtualization, + ); + let root = effective_network + .as_object() + .expect("effective export should remain an object tree"); + let site = root["Aggregation"] + .as_object() + .expect("Aggregation should remain exported"); + + assert_eq!(site.get("virtual").and_then(Value::as_bool), None); + } + + #[test] + fn large_site_with_force_visible_override_stays_visible() { + let (config, canonical, editor_state, effective) = site_with_ap_fixture(); + let virtualization = QueueVirtualizationContext { + direct_circuit_node_ids: HashSet::new(), + forced_visible_node_names: HashSet::from(["Aggregation".to_string()]), + }; + + let canonical_network = canonical.insight_topology_network_json(); + let effective_network = apply_effective_topology_to_network_json_from_canonical( + &config, + &canonical_network, + &canonical, + &editor_state, + &effective, + &virtualization, + ); + let root = effective_network + .as_object() + .expect("effective export should remain an object tree"); + let site = root["Aggregation"] + .as_object() + .expect("Aggregation should remain exported"); + + assert_eq!(site.get("virtual").and_then(Value::as_bool), None); + } + #[test] fn queue_auto_marks_large_site_virtual_without_treeguard() { let mut config = Config::default(); diff --git a/src/rust/lqos_topology/src/runtime.rs b/src/rust/lqos_topology/src/runtime.rs index 8aa42ebc..1a8b763d 100644 --- a/src/rust/lqos_topology/src/runtime.rs +++ b/src/rust/lqos_topology/src/runtime.rs @@ -13,10 +13,11 @@ use std::time::{Duration, SystemTime, UNIX_EPOCH}; use tracing::{info, warn}; use crate::{ - AttachmentProbeSpec, build_effective_topology_artifacts_from_canonical, is_health_state_fresh, - load_canonical_topology_state, prepare_runtime_topology_editor_state_from_canonical, - probe_specs_from_state, publish_effective_topology_artifacts, - publish_topology_runtime_error_status, + AttachmentProbeSpec, + build_effective_topology_artifacts_from_canonical_with_runtime_queue_context, + is_health_state_fresh, load_canonical_topology_state, + prepare_runtime_topology_editor_state_from_canonical, probe_specs_from_state, + publish_effective_topology_artifacts, publish_topology_runtime_error_status, }; const TOPOLOGY_PROBE_MAX_AGE_MS: u64 = 250; @@ -343,7 +344,7 @@ async fn run_round( refresh_health_state(config.as_ref(), health_state, &specs, &HashMap::new())?; } - let artifacts = build_effective_topology_artifacts_from_canonical( + let artifacts = build_effective_topology_artifacts_from_canonical_with_runtime_queue_context( config.as_ref(), &canonical, &overrides, diff --git a/src/rust/lqos_topology_compile/src/compile_mode.rs b/src/rust/lqos_topology_compile/src/compile_mode.rs index 3b9898ba..6432247c 100644 --- a/src/rust/lqos_topology_compile/src/compile_mode.rs +++ b/src/rust/lqos_topology_compile/src/compile_mode.rs @@ -50,11 +50,6 @@ struct CircuitProjection { node_name: String, } -const GENERATED_UNATTACHED_SITE_ID: &str = "libreqos:generated:site:unattached"; -const GENERATED_UNATTACHED_SITE_NAME: &str = "LibreQoS Unattached [Site]"; -const GENERATED_UNATTACHED_AP_ID: &str = "libreqos:generated:ap:unattached"; -const GENERATED_UNATTACHED_AP_NAME: &str = "LibreQoS Unattached [AP]"; - fn empty_parent_candidates(source: &str) -> TopologyParentCandidatesFile { TopologyParentCandidatesFile { source: source.to_string(), @@ -330,85 +325,6 @@ where circuits } -fn unresolved_circuits( - imported: &ImportedTopologyBundle, - projection: &HashMap, -) -> Vec<(String, String)> { - let mut unresolved = Vec::new(); - let mut seen = HashSet::new(); - for device in &imported.shaped_devices.devices { - if projection.contains_key(&device.circuit_id) || !seen.insert(device.circuit_id.clone()) { - continue; - } - unresolved.push((device.circuit_id.clone(), device.circuit_name.clone())); - } - unresolved -} - -fn generated_ap_node() -> ExportedNode { - ExportedNode { - id: GENERATED_UNATTACHED_AP_ID.to_string(), - name: GENERATED_UNATTACHED_AP_NAME.to_string(), - kind: "AP".to_string(), - parent_id: None, - download_mbps: None, - upload_mbps: None, - } -} - -fn generated_site_node() -> ExportedNode { - ExportedNode { - id: GENERATED_UNATTACHED_SITE_ID.to_string(), - name: GENERATED_UNATTACHED_SITE_NAME.to_string(), - kind: "Site".to_string(), - parent_id: None, - download_mbps: None, - upload_mbps: None, - } -} - -fn exported_unattached_fallback_node( - nodes_by_id: &HashMap, -) -> Option { - let mut preferred_site = None; - let mut preferred_ap = None; - for node in nodes_by_id.values() { - let id = node.id.to_ascii_lowercase(); - let name = node.name.to_ascii_lowercase(); - let is_unattached = id.contains("unattach") - || name.contains("unattach") - || id.contains("orphan") - || name.contains("orphan"); - if !is_unattached { - continue; - } - if node.kind.eq_ignore_ascii_case("site") { - preferred_site = Some(node.clone()); - break; - } - if preferred_ap.is_none() && node.kind.eq_ignore_ascii_case("ap") { - preferred_ap = Some(node.clone()); - } - } - preferred_site.or(preferred_ap) -} - -fn attach_unresolved_to_projection( - projection: &mut HashMap, - unresolved: Vec<(String, String)>, - fallback_node: &ExportedNode, -) { - for (circuit_id, _circuit_name) in unresolved { - projection.insert( - circuit_id, - CircuitProjection { - node_id: fallback_node.id.clone(), - node_name: fallback_node.name.clone(), - }, - ); - } -} - fn set_number(map: &mut Map, key: &str, value: Option, fallback: u64) { map.insert( key.to_string(), @@ -706,8 +622,6 @@ fn compile_full_like( ) -> Result { let source = compiled_source(&imported.source, mode); let ingress_identity = compiled_ingress_identity(&imported, mode); - let (exported_nodes_by_id, _) = exported_index(&imported.compatibility_network_json); - let unresolved_fallback = exported_unattached_fallback_node(&exported_nodes_by_id); let mut editor = sanitized_editor_state(&source, imported.generated_unix, &imported); editor.ingress_identity = ingress_identity.clone(); let mut canonical = TopologyCanonicalStateFile::from_editor_and_network( @@ -723,18 +637,6 @@ fn compile_full_like( .unwrap_or_else(|| empty_parent_candidates(&source)); parent_candidates.source = source.clone(); parent_candidates.ingress_identity = ingress_identity.clone(); - let mut shaped_devices = imported.shaped_devices.devices; - if let Some(fallback) = unresolved_fallback { - for device in &mut shaped_devices { - let missing_parent = device.parent_node.trim().is_empty() - && device.parent_node_id.is_none() - && device.anchor_node_id.is_none(); - if missing_parent { - device.parent_node = fallback.name.clone(); - device.parent_node_id = Some(fallback.id.clone()); - } - } - } Ok(CompiledTopologyBundle { source: source.clone(), generated_unix: imported.generated_unix, @@ -743,7 +645,7 @@ fn compile_full_like( editor, parent_candidates, compatibility_network_json: imported.compatibility_network_json, - shaped_devices: make_shaped_devices(shaped_devices), + shaped_devices: make_shaped_devices(imported.shaped_devices.devices), circuit_anchors: CircuitAnchorsFile { schema_version: imported.circuit_anchors.schema_version, source, @@ -767,10 +669,9 @@ fn compile_flat(imported: ImportedTopologyBundle) -> CompiledTopologyBundle { fn compile_ap_only(imported: ImportedTopologyBundle) -> Result { let source = compiled_source(&imported.source, TopologyCompileMode::ApOnly); - let mut projection = circuit_projection_map(&imported, |nodes_by_id, node_id| { + let projection = circuit_projection_map(&imported, |nodes_by_id, node_id| { nearest_kind(nodes_by_id, node_id, "AP") }); - let unresolved = unresolved_circuits(&imported, &projection); let (nodes_by_id, _) = native_projection_index(&imported); let mut root = BTreeMap::::new(); let mut seen = HashSet::new(); @@ -783,11 +684,6 @@ fn compile_ap_only(imported: ImportedTopologyBundle) -> Result Result Result { let source = compiled_source(&imported.source, TopologyCompileMode::ApSite); - let mut projection = circuit_projection_map(&imported, |nodes_by_id, node_id| { + let projection = circuit_projection_map(&imported, |nodes_by_id, node_id| { nearest_kind(nodes_by_id, node_id, "AP") }); - let unresolved = unresolved_circuits(&imported, &projection); let (nodes_by_id, _) = native_projection_index(&imported); let mut groups = BTreeMap::)>::new(); let mut synthetic_counter = 0usize; @@ -835,21 +730,6 @@ fn compile_ap_site(imported: ImportedTopologyBundle) -> Result::new(); for (_site_id, (site, children)) in groups { root.insert( @@ -892,10 +772,7 @@ pub fn compile_topology( #[cfg(test)] mod tests { - use super::{ - GENERATED_UNATTACHED_AP_ID, GENERATED_UNATTACHED_AP_NAME, GENERATED_UNATTACHED_SITE_NAME, - TopologyCompileMode, compile_topology, - }; + use super::{TopologyCompileMode, compile_topology}; use crate::bundle::ImportedTopologyBundle; use lqos_config::{ CircuitAnchor, CircuitAnchorsFile, ConfigShapedDevices, ShapedDevice, @@ -1044,22 +921,24 @@ mod tests { } #[test] - fn ap_only_drops_unresolved_orphan_parents() { + fn ap_only_leaves_unresolved_orphan_parents_unattached() { let compiled = compile_topology(imported_bundle(), TopologyCompileMode::ApOnly) .expect("ap_only compilation should succeed"); - assert_eq!(compiled.circuit_anchors.anchors.len(), 3); - assert!(compiled.compatibility_network_json[GENERATED_UNATTACHED_AP_NAME].is_object()); + assert_eq!(compiled.circuit_anchors.anchors.len(), 2); + assert!( + compiled + .compatibility_network_json + .get("LibreQoS Unattached [AP]") + .is_none() + ); let device = compiled .shaped_devices .devices .iter() .find(|device| device.circuit_id == "circuit-3") .expect("unresolved circuit should still be emitted"); - assert_eq!( - device.parent_node_id.as_deref(), - Some(GENERATED_UNATTACHED_AP_ID) - ); - assert_eq!(device.parent_node, GENERATED_UNATTACHED_AP_NAME); + assert!(device.parent_node.is_empty()); + assert!(device.parent_node_id.is_none()); } #[test] @@ -1079,27 +958,15 @@ mod tests { .expect("site should have children"); assert!(children.get("AP North").is_some()); assert!(children.get("AP South").is_some()); - let fallback_site = root[GENERATED_UNATTACHED_SITE_NAME] - .as_object() - .expect("fallback site should be present for unresolved circuits"); - let fallback_children = fallback_site["children"] - .as_object() - .expect("fallback site should have children"); - assert!( - fallback_children - .get(GENERATED_UNATTACHED_AP_NAME) - .is_some() - ); + assert!(root.get("LibreQoS Unattached [Site]").is_none()); let device = compiled .shaped_devices .devices .iter() .find(|device| device.circuit_id == "circuit-3") .expect("unresolved circuit should still be emitted"); - assert_eq!( - device.parent_node_id.as_deref(), - Some(GENERATED_UNATTACHED_AP_ID) - ); + assert!(device.parent_node.is_empty()); + assert!(device.parent_node_id.is_none()); } #[test] @@ -1359,7 +1226,7 @@ mod tests { } #[test] - fn full_mode_assigns_blank_parent_circuits_to_exported_unattached_site() { + fn full_mode_leaves_blank_parent_circuits_unattached() { let mut imported = imported_bundle(); imported.compatibility_network_json = json!({ "Site Alpha": { @@ -1411,11 +1278,8 @@ mod tests { .find(|device| device.circuit_id == "circuit-3") .expect("unresolved circuit should still be emitted"); - assert_eq!(device.parent_node, "LibreQoS Unattached [Site]"); - assert_eq!( - device.parent_node_id.as_deref(), - Some("libreqos:generated:splynx:site:unattached") - ); + assert!(device.parent_node.is_empty()); + assert!(device.parent_node_id.is_none()); } #[test] diff --git a/src/test_integration_splynx.py b/src/test_integration_splynx.py index 8ad53fc3..69b92da5 100644 --- a/src/test_integration_splynx.py +++ b/src/test_integration_splynx.py @@ -1,4 +1,6 @@ import importlib +import csv +import io import sys import types import unittest @@ -22,6 +24,7 @@ def install_splynx_stubs(): lqlib.exception_cpes = lambda: [] lqlib.promote_to_root_list = lambda: [] lqlib.client_bandwidth_multiplier = lambda: 1.0 + lqlib.get_libreqos_directory = lambda: "/opt/libreqos/src" lqlib.write_compiled_topology_from_python_graph_payload = lambda *_args, **_kwargs: None lqlib.splynx_api_key = lambda: "" lqlib.splynx_api_secret = lambda: "" @@ -128,20 +131,32 @@ class TestIntegrationSplynxStableIds(unittest.TestCase): ) ) - def test_full_mode_uses_stable_generated_unattached_site(self): - self.assertEqual( - integrationSplynx.splynx_generated_unattached_parent_id("full"), - "splynx_generated_unattached_site", - ) - self.assertEqual( - integrationSplynx.splynx_generated_unattached_site_network_id(), - "libreqos:generated:splynx:site:unattached", + def test_unresolved_splynx_parent_exports_empty_parent_node(self): + net = integrationCommon.NetworkGraph() + integrationSplynx.createClientAndDevice( + net, + serviceItem={ + "id": 93, + "customer_id": 29547, + "tariff_id": 32, + "mac": "2CC81BBDC9AB", + }, + cust_id_to_name={29547: "Charles Massey and Alex Soto"}, + downloadForTariffID={32: 330.0}, + uploadForTariffID={32: 330.0}, + parent_node_id=None, + ipv4_list=["66.185.224.210"], + ipv6_list=[], ) - def test_non_full_modes_do_not_force_generated_unattached_site(self): - self.assertIsNone(integrationSplynx.splynx_generated_unattached_parent_id("ap_site")) - self.assertIsNone(integrationSplynx.splynx_generated_unattached_parent_id("ap_only")) - self.assertIsNone(integrationSplynx.splynx_generated_unattached_parent_id("flat")) + net.prepareTree() + shaped_devices_csv, circuit_anchors = net.buildShapedDevicesArtifacts() + rows = list(csv.DictReader(io.StringIO(shaped_devices_csv))) + + self.assertEqual(len(rows), 1) + self.assertEqual(rows[0]["Parent Node"], "") + self.assertEqual(rows[0]["Parent Node ID"], "") + self.assertEqual(circuit_anchors["anchors"], []) def test_create_infrastructure_nodes_normalizes_parent_ids(self): net = integrationCommon.NetworkGraph() -- knotmirror 0.0.1 From 837b1082ae59fc04640748edc4d4df5ae088f721 Mon Sep 17 00:00:00 2001 From: rchac Date: Thu, 23 Apr 2026 03:04:06 +0000 Subject: [PATCH 15/51] changes --- docs-es/v2.0/configuration-es.md | 2 + docs-es/v2.0/integrations-reference-es.md | 2 +- docs/v2.0/configuration.md | 2 + docs/v2.0/integrations-reference.md | 2 +- .../src/topology_canonical_state.rs | 182 +++++++++++++++++- src/rust/lqosd/src/main.rs | 2 +- .../js_build/src/config_stormguard.js | 68 +++---- .../js_build/src/config_treeguard.js | 57 +++--- .../src/node_manager/local_api/config.rs | 12 +- .../node_manager/local_api/executive_cache.rs | 2 +- .../ws/single_user_channels/ping_monitor.rs | 2 +- .../src/node_manager/ws/ticker/asn_top.rs | 4 +- .../node_manager/ws/ticker/tree_summary_l2.rs | 2 +- .../flow_data/flow_analysis/finished_flows.rs | 4 +- src/rust/lqosd/src/throughput_tracker/mod.rs | 6 +- 15 files changed, 251 insertions(+), 98 deletions(-) diff --git a/docs-es/v2.0/configuration-es.md b/docs-es/v2.0/configuration-es.md index d64032ae..c96476a3 100644 --- a/docs-es/v2.0/configuration-es.md +++ b/docs-es/v2.0/configuration-es.md @@ -31,6 +31,8 @@ La mayoría de los cambios operativos diarios se hacen en la WebUI (`http://tu_i Las versiones actuales usan una disposición coherente en las páginas General, RTT, Queues, TreeGuard, Network Mode, Integration Defaults, Network Layout, Insight, páginas de integración por proveedor, IP Ranges, Flow Tracking y Shaped Devices. Integration Defaults también incluye la política compartida de margen para puertos Ethernet usada por integraciones que pueden detectar la velocidad negociada hacia el suscriptor. +Las páginas de configuración que ofrecen selectores de topología usan la topología activa en tiempo de ejecución, por lo que los despliegues gestionados por una integración no necesitan un `network.json` mantenido manualmente para esas listas. + ### Dónde en la WebUI - Ajustes generales: `Configuration -> General` diff --git a/docs-es/v2.0/integrations-reference-es.md b/docs-es/v2.0/integrations-reference-es.md index d0c7a91c..60b472ef 100644 --- a/docs-es/v2.0/integrations-reference-es.md +++ b/docs-es/v2.0/integrations-reference-es.md @@ -338,7 +338,7 @@ Las integraciones incluidas no sobrescriben `network.json`; conserve `network.js ShapedDevices.csv será sobrescrito cada vez que se ejecute la integración de UISP. -Si UISP expone un sitio y un AP con el mismo nombre visible dentro de la misma topología, las compilaciones actuales conservan el nombre del sitio en `network.json` y diferencian el nombre exportado del AP para que la rama del sitio no desaparezca del árbol. +Si UISP expone nombres visibles duplicados, las compilaciones actuales conservan los IDs estables de UISP y diferencian los nombres duplicados exportados de dispositivos/AP con un sufijo de ID corto, como `Nanoswitch [7c57e383]`. En colisiones de nombre entre sitio y AP, el sitio conserva el nombre simple y el lado AP recibe el sufijo para que una rama no oculte otra en el árbol heredado. Las integraciones incluidas no sobrescriben `network.json`; conserve `network.json` como entrada DIY/manual operada por el usuario. diff --git a/docs/v2.0/configuration.md b/docs/v2.0/configuration.md index 55d42d5b..cd82d450 100644 --- a/docs/v2.0/configuration.md +++ b/docs/v2.0/configuration.md @@ -31,6 +31,8 @@ Most day-to-day LibreQoS configuration happens in WebUI (`http://your_shaper_ip: Current builds use a consistent configuration layout across the General, RTT, Queues, TreeGuard, Network Mode, Integration Defaults, Network Layout, Insight, provider integration, IP Ranges, Flow Tracking, and Shaped Devices pages. Integration Defaults also includes the shared Ethernet port headroom policy used by integrations that can detect negotiated subscriber-facing port speeds. +Configuration pages that offer topology selectors use the active runtime topology, so integration-backed deployments do not need a hand-managed `network.json` for those lists. + ### Where In WebUI - General settings: `Configuration -> General` diff --git a/docs/v2.0/integrations-reference.md b/docs/v2.0/integrations-reference.md index 927542e7..2fd00ebe 100644 --- a/docs/v2.0/integrations-reference.md +++ b/docs/v2.0/integrations-reference.md @@ -338,7 +338,7 @@ Built-in integrations do not overwrite an existing `network.json`; keep DIY `net ShapedDevices.csv will be overwritten every time the UISP integration is run. -If UISP exposes a site and an AP with the same visible name in the same topology, current builds keep the site name stable in `network.json` and disambiguate the AP name during export so the site branch is not dropped from the tree. +If UISP exposes duplicate visible node names, current builds keep the stable UISP IDs and disambiguate exported duplicate device/AP names with a short ID suffix such as `Nanoswitch [7c57e383]`. For site/AP name collisions, the site keeps the plain name and the AP side is suffixed so one branch does not hide another in the legacy network tree. Built-in integrations do not overwrite `network.json`; keep DIY `network.json` operator-owned. diff --git a/src/rust/lqos_config/src/topology_canonical_state.rs b/src/rust/lqos_config/src/topology_canonical_state.rs index 7fff434b..5ddd5bdc 100644 --- a/src/rust/lqos_config/src/topology_canonical_state.rs +++ b/src/rust/lqos_config/src/topology_canonical_state.rs @@ -439,9 +439,9 @@ fn normalized_insight_node_kind(kind: &str) -> String { } } -fn short_node_suffix(node_id: &str) -> &str { +fn short_node_suffix(node_id: &str) -> String { let short = node_id.rsplit(':').next().unwrap_or(node_id); - &short[..short.len().min(8)] + short.chars().take(8).collect() } fn unique_export_name(name: &str, node_id: &str, used_names: &mut HashSet) -> String { @@ -459,6 +459,87 @@ fn unique_export_name(name: &str, node_id: &str, used_names: &mut HashSet) -> String { + let short = format!("{name} [{}]", short_node_suffix(node_id)); + if used_names.insert(short.clone()) { + return short; + } + + let fallback = format!("{name} [{node_id}]"); + used_names.insert(fallback.clone()); + fallback +} + +fn globally_unique_export_names( + nodes: &[TopologyCanonicalNode], + base_names_by_id: &HashMap, +) -> HashMap { + let mut node_ids_by_name = HashMap::<&str, HashSet<&str>>::new(); + let mut site_name_owner_by_base = HashMap::<&str, Option<&str>>::new(); + for node in nodes { + let Some(base_name) = base_names_by_id.get(&node.node_id) else { + continue; + }; + node_ids_by_name + .entry(base_name.as_str()) + .or_default() + .insert(node.node_id.as_str()); + if normalized_insight_node_kind(&node.node_kind) == "Site" { + match site_name_owner_by_base.entry(base_name.as_str()) { + std::collections::hash_map::Entry::Vacant(entry) => { + entry.insert(Some(node.node_id.as_str())); + } + std::collections::hash_map::Entry::Occupied(mut entry) => { + if *entry.get() != Some(node.node_id.as_str()) { + entry.insert(None); + } + } + } + } + } + + let mut ordered_nodes = nodes.iter().collect::>(); + ordered_nodes.sort_unstable_by(|left, right| { + let left_name = base_names_by_id + .get(&left.node_id) + .map(String::as_str) + .unwrap_or(left.node_name.as_str()); + let right_name = base_names_by_id + .get(&right.node_id) + .map(String::as_str) + .unwrap_or(right.node_name.as_str()); + left_name + .cmp(right_name) + .then_with(|| left.node_id.cmp(&right.node_id)) + }); + + let mut used_names = HashSet::new(); + let mut assigned_node_ids = HashSet::new(); + let mut export_names = HashMap::new(); + for node in ordered_nodes { + if !assigned_node_ids.insert(node.node_id.as_str()) { + continue; + } + let base_name = base_names_by_id + .get(&node.node_id) + .map(String::as_str) + .unwrap_or(node.node_name.as_str()); + let duplicate_count = node_ids_by_name + .get(base_name) + .map(HashSet::len) + .unwrap_or_default(); + let plain_site_owner = site_name_owner_by_base.get(base_name).copied().flatten(); + let export_name = if duplicate_count > 1 && plain_site_owner != Some(node.node_id.as_str()) + { + duplicate_export_name(base_name, &node.node_id, &mut used_names) + } else { + unique_export_name(base_name, &node.node_id, &mut used_names) + }; + export_names.insert(node.node_id.clone(), export_name); + } + export_names +} + fn build_insight_logical_entry_json( entry_id: &str, entries: &HashMap, @@ -980,14 +1061,24 @@ impl TopologyCanonicalStateFile { build_network_node_index(network_map, &mut by_id, &mut by_name); } - let mut entries = HashMap::::new(); + let mut base_names_by_id = HashMap::::new(); for node in &self.nodes { - let (download_mbps, upload_mbps) = canonical_node_rates(node); let export_name = by_id .get(&node.node_id) .or_else(|| by_name.get(&node.node_name)) .map(|snapshot| snapshot.export_name.clone()) .unwrap_or_else(|| node.node_name.clone()); + base_names_by_id.insert(node.node_id.clone(), export_name); + } + let export_names_by_id = globally_unique_export_names(&self.nodes, &base_names_by_id); + + let mut entries = HashMap::::new(); + for node in &self.nodes { + let (download_mbps, upload_mbps) = canonical_node_rates(node); + let export_name = export_names_by_id + .get(&node.node_id) + .cloned() + .unwrap_or_else(|| node.node_name.clone()); entries.insert( node.node_id.clone(), InsightLogicalNodeEntry { @@ -1338,6 +1429,89 @@ mod tests { ); } + #[test] + fn native_integration_export_suffixes_duplicate_node_names() { + let canonical = TopologyCanonicalStateFile { + schema_version: 1, + source: "uisp/ap_site".to_string(), + generated_unix: Some(123), + ingress_identity: None, + ingress_kind: TopologyCanonicalIngressKind::NativeIntegration, + nodes: vec![ + TopologyCanonicalNode { + node_id: "uisp:site:site-a".to_string(), + node_name: "Site A".to_string(), + node_kind: "Site".to_string(), + rate_input: super::TopologyCanonicalRateInput { + intrinsic_download_mbps: Some(1000), + intrinsic_upload_mbps: Some(1000), + ..Default::default() + }, + ..Default::default() + }, + TopologyCanonicalNode { + node_id: "uisp:site:site-b".to_string(), + node_name: "Site B".to_string(), + node_kind: "Site".to_string(), + rate_input: super::TopologyCanonicalRateInput { + intrinsic_download_mbps: Some(1000), + intrinsic_upload_mbps: Some(1000), + ..Default::default() + }, + ..Default::default() + }, + TopologyCanonicalNode { + node_id: "uisp:device:7c57e383-d0c4-47ac-af78-7b626a20d0a3".to_string(), + node_name: "Nanoswitch".to_string(), + node_kind: "AP".to_string(), + current_parent_node_id: Some("uisp:site:site-a".to_string()), + current_parent_node_name: Some("Site A".to_string()), + rate_input: super::TopologyCanonicalRateInput { + intrinsic_download_mbps: Some(95), + intrinsic_upload_mbps: Some(33), + ..Default::default() + }, + ..Default::default() + }, + TopologyCanonicalNode { + node_id: "uisp:device:01557d07-8a17-4263-98fb-80606c7dc613".to_string(), + node_name: "Nanoswitch".to_string(), + node_kind: "AP".to_string(), + current_parent_node_id: Some("uisp:site:site-b".to_string()), + current_parent_node_name: Some("Site B".to_string()), + rate_input: super::TopologyCanonicalRateInput { + intrinsic_download_mbps: Some(47), + intrinsic_upload_mbps: Some(28), + ..Default::default() + }, + ..Default::default() + }, + ], + compatibility_network_json: json!({}), + }; + + let logical = canonical.insight_topology_network_json(); + let site_a_children = logical["Site A"]["children"] + .as_object() + .expect("Site A should have child map"); + let site_b_children = logical["Site B"]["children"] + .as_object() + .expect("Site B should have child map"); + + assert!(site_a_children.get("Nanoswitch").is_none()); + assert!(site_b_children.get("Nanoswitch").is_none()); + assert!(site_a_children.get("Nanoswitch [7c57e383]").is_some()); + assert!(site_b_children.get("Nanoswitch [01557d07]").is_some()); + assert_eq!( + site_a_children["Nanoswitch [7c57e383]"]["name"].as_str(), + Some("Nanoswitch [7c57e383]") + ); + assert_eq!( + site_b_children["Nanoswitch [01557d07]"]["name"].as_str(), + Some("Nanoswitch [01557d07]") + ); + } + #[test] fn legacy_network_json_import_is_read_only_with_imported_rate_inputs() { let canonical = TopologyCanonicalStateFile::from_legacy_network_json(&json!({ diff --git a/src/rust/lqosd/src/main.rs b/src/rust/lqosd/src/main.rs index 1bd0c6da..de540d0f 100644 --- a/src/rust/lqosd/src/main.rs +++ b/src/rust/lqosd/src/main.rs @@ -1353,7 +1353,7 @@ fn tree_summary_l2_data() -> Vec<(usize, Vec<(usize, lqos_config::NetworkJsonTra } } - candidates.sort_by(|a, b| b.3.cmp(&a.3)); + candidates.sort_by_key(|candidate| std::cmp::Reverse(candidate.3)); let n: usize = 10; if candidates.len() > n { candidates.truncate(n); diff --git a/src/rust/lqosd/src/node_manager/js_build/src/config_stormguard.js b/src/rust/lqosd/src/node_manager/js_build/src/config_stormguard.js index 5d6a7ce4..40d60cc8 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/config_stormguard.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/config_stormguard.js @@ -1,11 +1,11 @@ import { loadConfig, - loadNetworkJson, + loadNodeDirectory, renderConfigMenu, saveConfig, } from "./config/config_helper"; -let networkData = null; +let siteRows = []; let selectedTargets = []; let excludedSites = []; @@ -75,26 +75,31 @@ function updateStrategyUi() { } } -// Load network.json for site dropdown +function nodeType(entry) { + return (entry?.node_type || "").toString().trim().toLowerCase(); +} + +function displayName(entry) { + return (entry?.node_name || "").toString().trim(); +} + +// Load the active runtime node directory for site dropdowns. function loadNetworkData() { return new Promise((resolve, reject) => { - loadNetworkJson( + loadNodeDirectory( (data) => { - // Check if we got the "Not done yet" response - if (typeof data === 'string' && data === 'Not done yet') { - console.error('Network.json file not found on server'); - alert('Network configuration not found. Please ensure network.json exists.'); - resolve(); - return; - } - networkData = data; - console.log('Network data loaded:', networkData); + const rows = Array.isArray(data) ? data : []; + const siteCandidates = rows.filter((entry) => nodeType(entry) === "site"); + const sourceRows = siteCandidates.length > 0 ? siteCandidates : rows; + siteRows = sourceRows + .filter((entry) => displayName(entry).length > 0); + siteRows.sort((a, b) => displayName(a).localeCompare(displayName(b))); populateSiteSelectors(); resolve(); }, (err) => { - console.error('Error loading network data:', err); - alert('Failed to load network sites. Please refresh the page.'); + console.error('Error loading node directory:', err); + alert('Topology data is not ready yet. Run the integration or scheduler refresh and try again.'); reject(err); }, ); @@ -105,32 +110,13 @@ function setSelectorOptions(selectorId) { const selector = document.getElementById(selectorId); selector.innerHTML = ''; - function iterate(data, level = 0) { - if (typeof data !== 'object' || data === null) { - return; - } - - for (const [key, value] of Object.entries(data)) { - const option = document.createElement('option'); - option.value = key; - - let prefix = ''; - for (let i = 0; i < level; i++) { - prefix += '- '; - } - option.textContent = prefix + key; - - selector.appendChild(option); - - if (value && typeof value === 'object' && value.children != null) { - iterate(value.children, level + 1); - } - } - } - - if (networkData) { - iterate(networkData); - } + siteRows.forEach((entry) => { + const name = displayName(entry); + const option = document.createElement('option'); + option.value = name; + option.textContent = name; + selector.appendChild(option); + }); } function populateSiteSelectors() { diff --git a/src/rust/lqosd/src/node_manager/js_build/src/config_treeguard.js b/src/rust/lqosd/src/node_manager/js_build/src/config_treeguard.js index 61a48e27..f5d40413 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/config_treeguard.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/config_treeguard.js @@ -1,13 +1,13 @@ import { loadAllCircuitDirectoryRows, loadConfig, - loadNetworkJson, + loadNodeDirectory, renderConfigMenu, saveConfig, } from "./config/config_helper"; import {defaultTreeguardConfig, ensureTreeguardConfig} from "./config/treeguard_defaults"; -let networkData = null; +let nodeRows = []; let circuitRows = null; let selectedNodes = []; let selectedCircuits = []; @@ -98,21 +98,22 @@ function updateCircuitsEnrollmentUi() { function loadNetworkData() { return new Promise((resolve, reject) => { - loadNetworkJson( + loadNodeDirectory( (data) => { - if (typeof data === "string" && data === "Not done yet") { - console.error("Network.json file not found on server"); - alert("Network configuration not found. Please ensure network.json exists."); - resolve(); - return; - } - networkData = data; + nodeRows = Array.isArray(data) + ? data.filter((entry) => (entry?.node_name || "").toString().trim().length > 0) + : []; + nodeRows.sort((a, b) => { + const left = (a?.node_name || "").toString(); + const right = (b?.node_name || "").toString(); + return left.localeCompare(right); + }); populateNodeSelector(); resolve(); }, (err) => { - console.error("Error loading network data:", err); - alert("Failed to load network nodes. You can still add nodes manually."); + console.error("Error loading node directory:", err); + alert("Topology data is not ready yet. Run the integration or scheduler refresh and try again. You can still add nodes manually."); reject(err); }, ); @@ -145,31 +146,17 @@ function populateNodeSelector() { const selector = document.getElementById("nodeSelector"); selector.innerHTML = ''; - function iterate(data, level = 0) { - if (typeof data !== "object" || data === null) { + nodeRows.forEach((entry) => { + const name = (entry?.node_name || "").toString().trim(); + if (!name) { return; } - - for (const [key, value] of Object.entries(data)) { - const option = document.createElement("option"); - option.value = key; - - let prefix = ""; - for (let i = 0; i < level; i++) { - prefix += "- "; - } - option.textContent = prefix + key; - selector.appendChild(option); - - if (value && typeof value === "object" && value.children != null) { - iterate(value.children, level + 1); - } - } - } - - if (networkData) { - iterate(networkData); - } + const type = (entry?.node_type || "").toString().trim(); + const option = document.createElement("option"); + option.value = name; + option.textContent = type ? `${name} (${type})` : name; + selector.appendChild(option); + }); } function populateCircuitSelector() { diff --git a/src/rust/lqosd/src/node_manager/local_api/config.rs b/src/rust/lqosd/src/node_manager/local_api/config.rs index 93b40394..a024764b 100644 --- a/src/rust/lqosd/src/node_manager/local_api/config.rs +++ b/src/rust/lqosd/src/node_manager/local_api/config.rs @@ -8,7 +8,9 @@ use axum::http::StatusCode; use axum::http::header; use default_net::get_interfaces; use lqos_bus::{BusRequest, BusResponse, bus_request}; -use lqos_config::{Config, ConfigShapedDevices, ShapedDevice, UserRole, WebUser, WebUsers}; +use lqos_config::{ + Config, ConfigShapedDevices, NetworkJson, ShapedDevice, UserRole, WebUser, WebUsers, +}; use lqos_utils::hash_to_i64; use serde::{Deserialize, Serialize}; use serde_json::Value; @@ -524,10 +526,10 @@ pub fn list_nics_data(login: LoginResult) -> Result Value { if let Ok(config) = lqos_config::load_config() { - let path = std::path::Path::new(&config.lqos_directory).join("network.json"); - if path.exists() { - let raw = std::fs::read_to_string(path).expect("Unable to read network json"); - let json: Value = serde_json::from_str(&raw).expect("Unable to read network json"); + let path = NetworkJson::path_for_config(config.as_ref()); + if let Ok(raw) = std::fs::read_to_string(path) + && let Ok(json) = serde_json::from_str(&raw) + { return json; } } diff --git a/src/rust/lqosd/src/node_manager/local_api/executive_cache.rs b/src/rust/lqosd/src/node_manager/local_api/executive_cache.rs index 5c9495b0..d09a307b 100644 --- a/src/rust/lqosd/src/node_manager/local_api/executive_cache.rs +++ b/src/rust/lqosd/src/node_manager/local_api/executive_cache.rs @@ -352,7 +352,7 @@ fn build_top_asn_rows(entities: &[ExecutiveEntitySnapshot]) -> Vec>(); - rows.sort_by(|left, right| right.total_bytes_15m.cmp(&left.total_bytes_15m)); + rows.sort_by_key(|row| std::cmp::Reverse(row.total_bytes_15m)); rows.truncate(EXECUTIVE_TOP_LIMIT); rows } diff --git a/src/rust/lqosd/src/node_manager/ws/single_user_channels/ping_monitor.rs b/src/rust/lqosd/src/node_manager/ws/single_user_channels/ping_monitor.rs index ad249d91..69133f21 100644 --- a/src/rust/lqosd/src/node_manager/ws/single_user_channels/ping_monitor.rs +++ b/src/rust/lqosd/src/node_manager/ws/single_user_channels/ping_monitor.rs @@ -32,7 +32,7 @@ pub(super) async fn ping_monitor( } }; - for ((ip, label), observation) in ip_addresses.iter().zip(observations.into_iter()) { + for ((ip, label), observation) in ip_addresses.iter().zip(observations) { if observation.reachable { let ping_time = observation .rtt_ms diff --git a/src/rust/lqosd/src/node_manager/ws/ticker/asn_top.rs b/src/rust/lqosd/src/node_manager/ws/ticker/asn_top.rs index a367e76d..30c2e46e 100644 --- a/src/rust/lqosd/src/node_manager/ws/ticker/asn_top.rs +++ b/src/rust/lqosd/src/node_manager/ws/ticker/asn_top.rs @@ -72,7 +72,7 @@ pub async fn asn_top( }, }) .collect(); - down_rows.sort_by(|a, b| b.value.cmp(&a.value)); + down_rows.sort_by_key(|row| std::cmp::Reverse(row.value)); down_rows.truncate(9); let mut up_rows: Vec = map @@ -88,7 +88,7 @@ pub async fn asn_top( }, }) .collect(); - up_rows.sort_by(|a, b| b.value.cmp(&a.value)); + up_rows.sort_by_key(|row| std::cmp::Reverse(row.value)); up_rows.truncate(9); // Publish to channels as needed diff --git a/src/rust/lqosd/src/node_manager/ws/ticker/tree_summary_l2.rs b/src/rust/lqosd/src/node_manager/ws/ticker/tree_summary_l2.rs index b6fcbcd7..6b86cb7a 100644 --- a/src/rust/lqosd/src/node_manager/ws/ticker/tree_summary_l2.rs +++ b/src/rust/lqosd/src/node_manager/ws/ticker/tree_summary_l2.rs @@ -44,7 +44,7 @@ pub async fn tree_summary_l2(channels: Arc) { } // Sort by total throughput descending and cap to N - candidates.sort_by(|a, b| b.3.cmp(&a.3)); + candidates.sort_by_key(|candidate| std::cmp::Reverse(candidate.3)); let n: usize = 10; if candidates.len() > n { candidates.truncate(n); diff --git a/src/rust/lqosd/src/throughput_tracker/flow_data/flow_analysis/finished_flows.rs b/src/rust/lqosd/src/throughput_tracker/flow_data/flow_analysis/finished_flows.rs index 6070720e..a708faaa 100644 --- a/src/rust/lqosd/src/throughput_tracker/flow_data/flow_analysis/finished_flows.rs +++ b/src/rust/lqosd/src/throughput_tracker/flow_data/flow_analysis/finished_flows.rs @@ -166,7 +166,7 @@ impl TimeBuffer { } // Sort by bytes downloaded descending - country_summary.sort_by(|a, b| b.1.down.cmp(&a.1.down)); + country_summary.sort_by_key(|row| std::cmp::Reverse(row.1.down)); country_summary } @@ -268,7 +268,7 @@ impl TimeBuffer { let mut results = results .into_iter() .collect::)>>(); - results.sort_by(|a, b| b.1.down.cmp(&a.1.down)); + results.sort_by_key(|row| std::cmp::Reverse(row.1.down)); // Keep only the top 10 results.truncate(10); results diff --git a/src/rust/lqosd/src/throughput_tracker/mod.rs b/src/rust/lqosd/src/throughput_tracker/mod.rs index 39138aec..f19c4f2f 100644 --- a/src/rust/lqosd/src/throughput_tracker/mod.rs +++ b/src/rust/lqosd/src/throughput_tracker/mod.rs @@ -446,7 +446,7 @@ pub fn top_n(start: u32, end: u32) -> BusResponse { }) .collect() }; - full_list.sort_by(|a, b| b.1.down.cmp(&a.1.down)); + full_list.sort_by_key(|row| std::cmp::Reverse(row.1.down)); let result = full_list .iter() //.skip(start as usize) @@ -493,7 +493,7 @@ pub fn top_n_up(start: u32, end: u32) -> BusResponse { }) .collect() }; - full_list.sort_by(|a, b| b.1.up.cmp(&a.1.up)); + full_list.sort_by_key(|row| std::cmp::Reverse(row.1.up)); let result = full_list .iter() //.skip(start as usize) @@ -1064,7 +1064,7 @@ pub fn all_unknown_ips() -> BusResponse { }) .collect() }; - full_list.sort_by(|a, b| b.5.cmp(&a.5)); + full_list.sort_by_key(|row| std::cmp::Reverse(row.5)); let result = full_list .iter() .map( -- knotmirror 0.0.1 From abe8d9e2f2249549e6f06a2e6cbb7e224427045a Mon Sep 17 00:00:00 2001 From: Name <2718612@2178972821991.net> Date: Thu, 23 Apr 2026 08:59:21 -0600 Subject: [PATCH 16/51] changes --- src/lqos.example | 2 + src/rust/lqos_config/src/etc/migration.rs | 2 + src/rust/lqos_config/src/etc/v15/example.toml | 2 + .../src/etc/v15/integration_common.rs | 42 +++++++++++++++++++ .../js_build/src/config/config_helper.js | 8 ++++ .../js_build/src/config_integration.js | 3 ++ 6 files changed, 59 insertions(+) diff --git a/src/lqos.example b/src/lqos.example index 547e0ddb..f4a08ea4 100644 --- a/src/lqos.example +++ b/src/lqos.example @@ -70,6 +70,8 @@ do_not_track_subnets = [ "192.168.66.0/24" ] [integration_common] circuit_name_as_address = false +# Deprecated compatibility key for older lqos_api binaries. LibreQoS ignores the value. +always_overwrite_network_json = true queue_refresh_interval_mins = 30 use_mikrotik_ipv6 = false diff --git a/src/rust/lqos_config/src/etc/migration.rs b/src/rust/lqos_config/src/etc/migration.rs index 9686a1ef..3a4a8fb8 100644 --- a/src/rust/lqos_config/src/etc/migration.rs +++ b/src/rust/lqos_config/src/etc/migration.rs @@ -255,6 +255,8 @@ fn migrate_integration_common( new_config: &mut Config, ) -> Result<(), MigrationError> { new_config.integration_common.circuit_name_as_address = python_config.circuit_name_use_address; + new_config.integration_common.always_overwrite_network_json = + python_config.overwrite_network_jsonalways; new_config.integration_common.queue_refresh_interval_mins = python_config.queue_refresh_interval_mins as u32; new_config.integration_common.use_mikrotik_ipv6 = python_config.find_ipv6using_mikrotik_api; diff --git a/src/rust/lqos_config/src/etc/v15/example.toml b/src/rust/lqos_config/src/etc/v15/example.toml index 730f272d..8e2ad841 100644 --- a/src/rust/lqos_config/src/etc/v15/example.toml +++ b/src/rust/lqos_config/src/etc/v15/example.toml @@ -101,6 +101,8 @@ allow_subnets = [ "172.16.0.0/12", "10.0.0.0/8", "100.64.0.0/16", "192.168.0.0/1 [integration_common] circuit_name_as_address = false +# Deprecated compatibility key for older lqos_api binaries. LibreQoS ignores the value. +always_overwrite_network_json = true queue_refresh_interval_mins = 30 use_mikrotik_ipv6 = false ethernet_port_limits_enabled = true diff --git a/src/rust/lqos_config/src/etc/v15/integration_common.rs b/src/rust/lqos_config/src/etc/v15/integration_common.rs index 06867725..7ae9ec5f 100644 --- a/src/rust/lqos_config/src/etc/v15/integration_common.rs +++ b/src/rust/lqos_config/src/etc/v15/integration_common.rs @@ -7,6 +7,10 @@ fn default_ethernet_port_limits_enabled() -> bool { true } +fn default_always_overwrite_network_json() -> bool { + true +} + fn default_attachment_health_enabled() -> bool { true } @@ -78,6 +82,14 @@ pub struct IntegrationConfig { /// Replace names with addresses? pub circuit_name_as_address: bool, + /// Deprecated compatibility field for older sidecar services. + /// + /// LibreQoS no longer uses this value to decide whether integrations may + /// replace `network.json`, but older `lqos_api` binaries still require the + /// key to exist when parsing `/etc/lqos.conf`. + #[serde(default = "default_always_overwrite_network_json")] + pub always_overwrite_network_json: bool, + /// Queue refresh interval in minutes pub queue_refresh_interval_mins: u32, @@ -110,6 +122,7 @@ impl Default for IntegrationConfig { fn default() -> Self { Self { circuit_name_as_address: false, + always_overwrite_network_json: true, queue_refresh_interval_mins: 30, use_mikrotik_ipv6: false, promote_to_root: None, @@ -120,3 +133,32 @@ impl Default for IntegrationConfig { } } } + +#[cfg(test)] +mod tests { + use super::IntegrationConfig; + + #[test] + fn missing_legacy_overwrite_key_defaults_to_true() { + let config: IntegrationConfig = toml::from_str( + r#" +circuit_name_as_address = false +queue_refresh_interval_mins = 30 +"#, + ) + .expect("integration config without legacy key should deserialize"); + + assert!(config.always_overwrite_network_json); + } + + #[test] + fn serialized_config_includes_legacy_overwrite_key() { + let serialized = + toml::to_string(&IntegrationConfig::default()).expect("config should serialize"); + + assert!( + serialized.contains("always_overwrite_network_json = true"), + "serialized config should keep legacy key for older lqos_api binaries" + ); + } +} 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 536cfe1c..d35fab49 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 @@ -46,6 +46,9 @@ function ensureOptionalConfigSections(config) { if (!config.splynx_integration || typeof config.splynx_integration !== "object") { config.splynx_integration = {}; } + if (!config.integration_common || typeof config.integration_common !== "object") { + config.integration_common = {}; + } if (!config.topology || typeof config.topology !== "object") { config.topology = {}; } @@ -78,6 +81,11 @@ function ensureOptionalConfigSections(config) { splynx.strategy = "ap_site"; } + const integration = config.integration_common; + if (typeof integration.always_overwrite_network_json !== "boolean") { + integration.always_overwrite_network_json = true; + } + const topology = config.topology; const normalizeMode = (mode) => { if (typeof mode !== "string") { diff --git a/src/rust/lqosd/src/node_manager/js_build/src/config_integration.js b/src/rust/lqosd/src/node_manager/js_build/src/config_integration.js index cf86a2bc..a09b1fe4 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/config_integration.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/config_integration.js @@ -54,6 +54,9 @@ function validateConfig() { function updateConfig() { // Update only the integration_common section window.config.integration_common = { + ...(window.config.integration_common || {}), + always_overwrite_network_json: + window.config.integration_common?.always_overwrite_network_json ?? true, circuit_name_as_address: document.getElementById("circuitNameAsAddress").checked, use_mikrotik_ipv6: document.getElementById("useMikrotikIpv6").checked, queue_refresh_interval_mins: parseInt(document.getElementById("queueRefreshInterval").value), -- knotmirror 0.0.1 From 4ba7240f0457f69cd82496abd7ef9f0433725b5a Mon Sep 17 00:00:00 2001 From: Name <2718612@2178972821991.net> Date: Thu, 23 Apr 2026 09:13:14 -0600 Subject: [PATCH 17/51] changes --- docs-es/v2.0/api-es.md | 5 ++ docs/v2.0/api.md | 5 ++ src/build_rust.sh | 16 +++- src/rust/lqos_config/src/etc/mod.rs | 122 +++++++++++++++++++++++++++- 4 files changed, 143 insertions(+), 5 deletions(-) diff --git a/docs-es/v2.0/api-es.md b/docs-es/v2.0/api-es.md index 09d68125..c55f2e49 100644 --- a/docs-es/v2.0/api-es.md +++ b/docs-es/v2.0/api-es.md @@ -43,6 +43,11 @@ cd /opt/libreqos/src ./update_api.sh ``` +Las actualizaciones de LibreQoS instaladas desde Git conservan la clave obsoleta +`integration_common.always_overwrite_network_json` en `/etc/lqos.conf` para +binarios antiguos de `lqos_api`. LibreQoS ignora el valor, pero las versiones +antiguas de la API pueden requerir la clave para leer el archivo de configuración. + Verificar estado del servicio: ```bash diff --git a/docs/v2.0/api.md b/docs/v2.0/api.md index 56a58e46..c902009a 100644 --- a/docs/v2.0/api.md +++ b/docs/v2.0/api.md @@ -43,6 +43,11 @@ cd /opt/libreqos/src ./update_api.sh ``` +Git-installed LibreQoS upgrades preserve the deprecated +`integration_common.always_overwrite_network_json` key in `/etc/lqos.conf` +for older `lqos_api` binaries. LibreQoS ignores the value, but older API +builds may require the key to parse the config file. + Verify service state: ```bash diff --git a/src/build_rust.sh b/src/build_rust.sh index 1c5976d8..d61c9407 100755 --- a/src/build_rust.sh +++ b/src/build_rust.sh @@ -138,7 +138,7 @@ mv liblqos_python.so.new liblqos_python.so # Update the lqos_api binary echo "Updating lqos_api binary..." -bash ./update_api.sh || echo "Warning: Failed to update lqos_api (continuing)." +bash ./update_api.sh --no-restart || echo "Warning: Failed to update lqos_api (continuing)." set_libreqos_operator_permissions() { local runtime_paths=() @@ -173,6 +173,16 @@ service_is_active() { systemctl is-active --quiet "$n.service" } +service_is_enabled() { + local n=$1 + systemctl is-enabled --quiet "$n.service" 2>/dev/null +} + +service_is_failed() { + local n=$1 + systemctl is-failed --quiet "$n.service" 2>/dev/null +} + refresh_service_unit() { local unit_name=$1 local src="./bin/${unit_name}.service.example" @@ -244,8 +254,8 @@ else echo "lqos_scheduler is active as a service. Restarting it. You may need to enter your sudo password." sudo systemctl restart lqos_scheduler fi - if service_is_active lqos_api; then - echo "lqos_api is active as a service. Restarting it. You may need to enter your sudo password." + if service_is_active lqos_api || service_is_failed lqos_api || service_is_enabled lqos_api; then + echo "lqos_api is installed as an active, failed, or enabled service. Restarting it. You may need to enter your sudo password." sudo systemctl restart lqos_api fi if service_is_active lqos_setup; then diff --git a/src/rust/lqos_config/src/etc/mod.rs b/src/rust/lqos_config/src/etc/mod.rs index a796e2c8..bddd2280 100644 --- a/src/rust/lqos_config/src/etc/mod.rs +++ b/src/rust/lqos_config/src/etc/mod.rs @@ -370,6 +370,55 @@ fn maybe_migrate_uisp_capacity_defaults( Ok(migrated) } +fn maybe_migrate_lqos_api_legacy_overwrite_key( + config_location: &str, + raw: String, +) -> Result { + let mut doc: DocumentMut = raw.parse().map_err(|e| LibreQoSConfigError::ParseError { + path: config_location.to_string(), + details: format!("Error parsing config: {e}"), + })?; + + if doc + .get("integration_common") + .and_then(|section| section.as_table_like()) + .and_then(|section| section.get("always_overwrite_network_json")) + .is_some() + { + return Ok(raw); + } + + if let Some(section) = doc.get("integration_common") { + if section.as_table_like().is_none() { + return Ok(raw); + } + } else { + doc["integration_common"] = Item::Table(Table::new()); + } + + doc["integration_common"]["always_overwrite_network_json"] = value(true); + let migrated = doc.to_string(); + + let config_path = Path::new(config_location); + if config_path.exists() { + let backup_path = format!("{config_location}.lqos_api_legacy_overwrite_backup"); + std::fs::copy(config_path, &backup_path).map_err(|e| LibreQoSConfigError::CannotWrite { + path: backup_path, + source: e, + })?; + } + + std::fs::write(config_path, &migrated).map_err(|e| LibreQoSConfigError::CannotWrite { + path: config_location.to_string(), + source: e, + })?; + + info!( + "Added deprecated integration_common.always_overwrite_network_json compatibility key for older lqos_api binaries." + ); + Ok(migrated) +} + fn actually_load_from_disk() -> Result, LibreQoSConfigError> { let config_location = if let Ok(lqos_config) = std::env::var("LQOS_CONFIG") { info!("Overriding lqos.conf location from environment variable."); @@ -414,6 +463,7 @@ fn actually_load_from_disk() -> Result, LibreQoSConfigError> { let raw = maybe_migrate_treeguard_link_virtualization_defaults(&config_location, raw)?; let raw = maybe_migrate_uisp_capacity_defaults(&config_location, raw)?; let raw = maybe_migrate_topology_compile_mode(&config_location, raw)?; + let raw = maybe_migrate_lqos_api_legacy_overwrite_key(&config_location, raw)?; let mut final_config = Config::load_from_string(&raw).map_err(|e| { error!("Unable to parse {config_location}"); @@ -553,8 +603,9 @@ pub enum LibreQoSConfigError { #[cfg(test)] mod tests { use super::{ - maybe_migrate_topology_compile_mode, maybe_migrate_treeguard_link_virtualization_defaults, - maybe_migrate_uisp_capacity_defaults, topology_compile_mode_migration_stamp_path, + maybe_migrate_lqos_api_legacy_overwrite_key, maybe_migrate_topology_compile_mode, + maybe_migrate_treeguard_link_virtualization_defaults, maybe_migrate_uisp_capacity_defaults, + topology_compile_mode_migration_stamp_path, treeguard_links_virtualization_migration_stamp_path, uisp_capacity_defaults_migration_stamp_path, }; @@ -585,6 +636,73 @@ mod tests { path.to_string_lossy().into_owned() } + #[test] + fn lqos_api_legacy_overwrite_key_migration_rewrites_missing_key() { + let test_dir = unique_test_dir(); + let raw = "[integration_common]\ncircuit_name_as_address = false\nqueue_refresh_interval_mins = 30\n"; + let config_path = write_test_config(&test_dir, raw); + + let config_path_str = path_string(&config_path); + let migrated = + maybe_migrate_lqos_api_legacy_overwrite_key(&config_path_str, raw.to_string()) + .expect("migration should succeed"); + + assert!(migrated.contains("always_overwrite_network_json = true")); + assert_eq!( + fs::read_to_string(&config_path).expect("config should be rewritten"), + migrated + ); + assert_eq!( + fs::read_to_string(config_path.with_extension("conf.lqos_api_legacy_overwrite_backup")) + .expect("backup should exist"), + raw + ); + + fs::remove_dir_all(&test_dir).expect("should clean up temp dir"); + } + + #[test] + fn lqos_api_legacy_overwrite_key_migration_leaves_existing_key() { + let test_dir = unique_test_dir(); + let raw = "[integration_common]\nalways_overwrite_network_json = false\nqueue_refresh_interval_mins = 30\n"; + let config_path = write_test_config(&test_dir, raw); + + let config_path_str = path_string(&config_path); + let migrated = + maybe_migrate_lqos_api_legacy_overwrite_key(&config_path_str, raw.to_string()) + .expect("migration should succeed"); + + assert_eq!(migrated, raw); + assert_eq!( + fs::read_to_string(&config_path).expect("config should remain unchanged"), + raw + ); + assert!( + !config_path + .with_extension("conf.lqos_api_legacy_overwrite_backup") + .exists() + ); + + fs::remove_dir_all(&test_dir).expect("should clean up temp dir"); + } + + #[test] + fn lqos_api_legacy_overwrite_key_migration_creates_missing_section() { + let test_dir = unique_test_dir(); + let raw = "version = \"1.5\"\n"; + let config_path = write_test_config(&test_dir, raw); + + let config_path_str = path_string(&config_path); + let migrated = + maybe_migrate_lqos_api_legacy_overwrite_key(&config_path_str, raw.to_string()) + .expect("migration should succeed"); + + assert!(migrated.contains("[integration_common]")); + assert!(migrated.contains("always_overwrite_network_json = true")); + + fs::remove_dir_all(&test_dir).expect("should clean up temp dir"); + } + #[test] fn uisp_capacity_migration_rewrites_existing_values_and_stamps() { let test_dir = unique_test_dir(); -- knotmirror 0.0.1 From 49a734c1151119050cb092c1f87ea35b1e85f2c8 Mon Sep 17 00:00:00 2001 From: Name <2718612@2178972821991.net> Date: Thu, 23 Apr 2026 09:18:36 -0600 Subject: [PATCH 18/51] changes --- docs-es/v2.0/api-es.md | 10 +- docs/v2.0/api.md | 9 +- src/lqos.example | 2 + src/rust/lqos_config/src/etc/mod.rs | 91 ++++++++++++------- src/rust/lqos_config/src/etc/v15/example.toml | 2 + .../src/etc/v15/uisp_integration.rs | 11 ++- .../js_build/src/config/config_helper.js | 7 ++ .../node_manager/js_build/src/config_uisp.js | 2 +- 8 files changed, 88 insertions(+), 46 deletions(-) diff --git a/docs-es/v2.0/api-es.md b/docs-es/v2.0/api-es.md index c55f2e49..5489b32b 100644 --- a/docs-es/v2.0/api-es.md +++ b/docs-es/v2.0/api-es.md @@ -43,10 +43,12 @@ cd /opt/libreqos/src ./update_api.sh ``` -Las actualizaciones de LibreQoS instaladas desde Git conservan la clave obsoleta -`integration_common.always_overwrite_network_json` en `/etc/lqos.conf` para -binarios antiguos de `lqos_api`. LibreQoS ignora el valor, pero las versiones -antiguas de la API pueden requerir la clave para leer el archivo de configuración. +Las actualizaciones de LibreQoS instaladas desde Git conservan claves obsoletas +de compatibilidad, como `integration_common.always_overwrite_network_json` y +`uisp_integration.use_ptmp_as_parent`, en `/etc/lqos.conf` para binarios +antiguos de `lqos_api`. LibreQoS ignora estos valores, pero las versiones +antiguas de la API pueden requerir las claves para leer el archivo de +configuración. Verificar estado del servicio: diff --git a/docs/v2.0/api.md b/docs/v2.0/api.md index c902009a..fee31a3e 100644 --- a/docs/v2.0/api.md +++ b/docs/v2.0/api.md @@ -43,10 +43,11 @@ cd /opt/libreqos/src ./update_api.sh ``` -Git-installed LibreQoS upgrades preserve the deprecated -`integration_common.always_overwrite_network_json` key in `/etc/lqos.conf` -for older `lqos_api` binaries. LibreQoS ignores the value, but older API -builds may require the key to parse the config file. +Git-installed LibreQoS upgrades preserve deprecated compatibility keys such as +`integration_common.always_overwrite_network_json` and +`uisp_integration.use_ptmp_as_parent` in `/etc/lqos.conf` for older +`lqos_api` binaries. LibreQoS ignores these values, but older API builds may +require the keys to parse the config file. Verify service state: diff --git a/src/lqos.example b/src/lqos.example index f4a08ea4..0a11f1be 100644 --- a/src/lqos.example +++ b/src/lqos.example @@ -111,6 +111,8 @@ ipv6_with_mikrotik = false bandwidth_overhead_factor = 1.0 commit_bandwidth_multiplier = 0.98 exception_cpes = [] +# Deprecated compatibility key for older lqos_api binaries. LibreQoS ignores the value. +use_ptmp_as_parent = false ignore_calculated_capacity = false [powercode_integration] diff --git a/src/rust/lqos_config/src/etc/mod.rs b/src/rust/lqos_config/src/etc/mod.rs index bddd2280..6f5a69e1 100644 --- a/src/rust/lqos_config/src/etc/mod.rs +++ b/src/rust/lqos_config/src/etc/mod.rs @@ -370,7 +370,31 @@ fn maybe_migrate_uisp_capacity_defaults( Ok(migrated) } -fn maybe_migrate_lqos_api_legacy_overwrite_key( +fn legacy_bool_key_present(doc: &DocumentMut, section_name: &str, key_name: &str) -> bool { + doc.get(section_name) + .and_then(|section| section.as_table_like()) + .and_then(|section| section.get(key_name)) + .is_some() +} + +fn ensure_legacy_bool_key(doc: &mut DocumentMut, section_name: &str, key_name: &str) -> bool { + if legacy_bool_key_present(doc, section_name, key_name) { + return false; + } + + if let Some(section) = doc.get(section_name) { + if section.as_table_like().is_none() { + return false; + } + } else { + doc[section_name] = Item::Table(Table::new()); + } + + doc[section_name][key_name] = value(false); + true +} + +fn maybe_migrate_lqos_api_legacy_keys( config_location: &str, raw: String, ) -> Result { @@ -379,24 +403,26 @@ fn maybe_migrate_lqos_api_legacy_overwrite_key( details: format!("Error parsing config: {e}"), })?; - if doc - .get("integration_common") - .and_then(|section| section.as_table_like()) - .and_then(|section| section.get("always_overwrite_network_json")) - .is_some() - { - return Ok(raw); - } + let mut changed = false; - if let Some(section) = doc.get("integration_common") { - if section.as_table_like().is_none() { - return Ok(raw); + if !legacy_bool_key_present(&doc, "integration_common", "always_overwrite_network_json") { + if let Some(section) = doc.get("integration_common") { + if section.as_table_like().is_none() { + return Ok(raw); + } + } else { + doc["integration_common"] = Item::Table(Table::new()); } - } else { - doc["integration_common"] = Item::Table(Table::new()); + + doc["integration_common"]["always_overwrite_network_json"] = value(true); + changed = true; } - doc["integration_common"]["always_overwrite_network_json"] = value(true); + changed |= ensure_legacy_bool_key(&mut doc, "uisp_integration", "use_ptmp_as_parent"); + + if !changed { + return Ok(raw); + } let migrated = doc.to_string(); let config_path = Path::new(config_location); @@ -413,9 +439,7 @@ fn maybe_migrate_lqos_api_legacy_overwrite_key( source: e, })?; - info!( - "Added deprecated integration_common.always_overwrite_network_json compatibility key for older lqos_api binaries." - ); + info!("Added deprecated lqos_api compatibility keys required by older lqos_api binaries."); Ok(migrated) } @@ -463,7 +487,7 @@ fn actually_load_from_disk() -> Result, LibreQoSConfigError> { let raw = maybe_migrate_treeguard_link_virtualization_defaults(&config_location, raw)?; let raw = maybe_migrate_uisp_capacity_defaults(&config_location, raw)?; let raw = maybe_migrate_topology_compile_mode(&config_location, raw)?; - let raw = maybe_migrate_lqos_api_legacy_overwrite_key(&config_location, raw)?; + let raw = maybe_migrate_lqos_api_legacy_keys(&config_location, raw)?; let mut final_config = Config::load_from_string(&raw).map_err(|e| { error!("Unable to parse {config_location}"); @@ -603,7 +627,7 @@ pub enum LibreQoSConfigError { #[cfg(test)] mod tests { use super::{ - maybe_migrate_lqos_api_legacy_overwrite_key, maybe_migrate_topology_compile_mode, + maybe_migrate_lqos_api_legacy_keys, maybe_migrate_topology_compile_mode, maybe_migrate_treeguard_link_virtualization_defaults, maybe_migrate_uisp_capacity_defaults, topology_compile_mode_migration_stamp_path, treeguard_links_virtualization_migration_stamp_path, @@ -637,17 +661,18 @@ mod tests { } #[test] - fn lqos_api_legacy_overwrite_key_migration_rewrites_missing_key() { + fn lqos_api_legacy_key_migration_rewrites_missing_keys() { let test_dir = unique_test_dir(); let raw = "[integration_common]\ncircuit_name_as_address = false\nqueue_refresh_interval_mins = 30\n"; let config_path = write_test_config(&test_dir, raw); let config_path_str = path_string(&config_path); - let migrated = - maybe_migrate_lqos_api_legacy_overwrite_key(&config_path_str, raw.to_string()) - .expect("migration should succeed"); + let migrated = maybe_migrate_lqos_api_legacy_keys(&config_path_str, raw.to_string()) + .expect("migration should succeed"); assert!(migrated.contains("always_overwrite_network_json = true")); + assert!(migrated.contains("[uisp_integration]")); + assert!(migrated.contains("use_ptmp_as_parent = false")); assert_eq!( fs::read_to_string(&config_path).expect("config should be rewritten"), migrated @@ -662,15 +687,14 @@ mod tests { } #[test] - fn lqos_api_legacy_overwrite_key_migration_leaves_existing_key() { + fn lqos_api_legacy_key_migration_leaves_existing_keys() { let test_dir = unique_test_dir(); - let raw = "[integration_common]\nalways_overwrite_network_json = false\nqueue_refresh_interval_mins = 30\n"; + let raw = "[integration_common]\nalways_overwrite_network_json = false\nqueue_refresh_interval_mins = 30\n\n[uisp_integration]\nuse_ptmp_as_parent = true\n"; let config_path = write_test_config(&test_dir, raw); let config_path_str = path_string(&config_path); - let migrated = - maybe_migrate_lqos_api_legacy_overwrite_key(&config_path_str, raw.to_string()) - .expect("migration should succeed"); + let migrated = maybe_migrate_lqos_api_legacy_keys(&config_path_str, raw.to_string()) + .expect("migration should succeed"); assert_eq!(migrated, raw); assert_eq!( @@ -687,18 +711,19 @@ mod tests { } #[test] - fn lqos_api_legacy_overwrite_key_migration_creates_missing_section() { + fn lqos_api_legacy_key_migration_creates_missing_sections() { let test_dir = unique_test_dir(); let raw = "version = \"1.5\"\n"; let config_path = write_test_config(&test_dir, raw); let config_path_str = path_string(&config_path); - let migrated = - maybe_migrate_lqos_api_legacy_overwrite_key(&config_path_str, raw.to_string()) - .expect("migration should succeed"); + let migrated = maybe_migrate_lqos_api_legacy_keys(&config_path_str, raw.to_string()) + .expect("migration should succeed"); assert!(migrated.contains("[integration_common]")); assert!(migrated.contains("always_overwrite_network_json = true")); + assert!(migrated.contains("[uisp_integration]")); + assert!(migrated.contains("use_ptmp_as_parent = false")); fs::remove_dir_all(&test_dir).expect("should clean up temp dir"); } diff --git a/src/rust/lqos_config/src/etc/v15/example.toml b/src/rust/lqos_config/src/etc/v15/example.toml index 8e2ad841..8b1db083 100644 --- a/src/rust/lqos_config/src/etc/v15/example.toml +++ b/src/rust/lqos_config/src/etc/v15/example.toml @@ -163,6 +163,8 @@ ipv6_with_mikrotik = false bandwidth_overhead_factor = 1.0 commit_bandwidth_multiplier = 0.98 exception_cpes = [] +# Deprecated compatibility key for older lqos_api binaries. LibreQoS ignores the value. +use_ptmp_as_parent = false infrastructure_transport_caps_enabled = true [powercode_integration] diff --git a/src/rust/lqos_config/src/etc/v15/uisp_integration.rs b/src/rust/lqos_config/src/etc/v15/uisp_integration.rs index 58feac35..35c48cd2 100644 --- a/src/rust/lqos_config/src/etc/v15/uisp_integration.rs +++ b/src/rust/lqos_config/src/etc/v15/uisp_integration.rs @@ -27,8 +27,11 @@ pub struct UispIntegration { pub bandwidth_overhead_factor: f32, pub commit_bandwidth_multiplier: f32, pub exception_cpes: Vec, - /// Deprecated legacy importer-side PtMP-parent toggle. Existing values are ignored. - #[serde(default, skip_serializing)] + /// Deprecated legacy importer-side PtMP-parent toggle. + /// + /// LibreQoS ignores this value, but older `lqos_api` binaries require the + /// key to exist when parsing `/etc/lqos.conf`. + #[serde(default)] pub use_ptmp_as_parent: bool, #[serde(default = "default_ignore_calculated_capacity")] pub ignore_calculated_capacity: bool, @@ -93,7 +96,7 @@ mod tests { } #[test] - fn deprecated_ptmp_parent_flag_loads_but_does_not_serialize() { + fn deprecated_ptmp_parent_flag_loads_and_serializes_for_api_compatibility() { let config: UispIntegration = toml::from_str( r#" enable_uisp = true @@ -118,6 +121,6 @@ use_ptmp_as_parent = true let serialized = toml::to_string(&config).expect("uisp integration config should serialize"); - assert!(!serialized.contains("use_ptmp_as_parent")); + assert!(serialized.contains("use_ptmp_as_parent = true")); } } 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 d35fab49..ed3f4b15 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 @@ -52,6 +52,9 @@ function ensureOptionalConfigSections(config) { if (!config.topology || typeof config.topology !== "object") { config.topology = {}; } + if (!config.uisp_integration || typeof config.uisp_integration !== "object") { + config.uisp_integration = {}; + } if (!config.sonar_integration || typeof config.sonar_integration !== "object") { config.sonar_integration = {}; @@ -85,6 +88,10 @@ function ensureOptionalConfigSections(config) { if (typeof integration.always_overwrite_network_json !== "boolean") { integration.always_overwrite_network_json = true; } + const uisp = config.uisp_integration; + if (typeof uisp.use_ptmp_as_parent !== "boolean") { + uisp.use_ptmp_as_parent = false; + } const topology = config.topology; const normalizeMode = (mode) => { diff --git a/src/rust/lqosd/src/node_manager/js_build/src/config_uisp.js b/src/rust/lqosd/src/node_manager/js_build/src/config_uisp.js index fa9d6eeb..0fd849b2 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/config_uisp.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/config_uisp.js @@ -88,7 +88,6 @@ function updateConfig() { // Parse comma-separated strings into arrays const existingUisp = { ...(window.config.uisp_integration || {}) }; delete existingUisp.enable_squashing; - delete existingUisp.use_ptmp_as_parent; const excludeSites = document.getElementById("uispExcludeSites").value.trim(); const excludeSitesArray = excludeSites ? excludeSites.split(',').map(s => s.trim()) : []; @@ -108,6 +107,7 @@ function updateConfig() { // Update the config object window.config.uisp_integration = { ...existingUisp, + use_ptmp_as_parent: existingUisp.use_ptmp_as_parent ?? false, enable_uisp: document.getElementById("enableUisp").checked, token: document.getElementById("uispToken").value.trim(), url: document.getElementById("uispUrl").value.trim(), -- knotmirror 0.0.1 From 792e4f6f9bcc0463179bcd11503800ec352ba8c1 Mon Sep 17 00:00:00 2001 From: Name <2718612@2178972821991.net> Date: Thu, 23 Apr 2026 10:03:45 -0600 Subject: [PATCH 19/51] changes --- src/update_api.sh | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/src/update_api.sh b/src/update_api.sh index 06a073b0..6f968c71 100755 --- a/src/update_api.sh +++ b/src/update_api.sh @@ -3,7 +3,7 @@ set -euo pipefail # Fetch and install the lqos_api binary into src/bin (or an alternate destination) -# - Downloads https://download.libreqos.com/api2.zip +# - Downloads https://download.libreqos.com/api3.zip by default # - Extracts the single file lqos_api # - Places it into ./bin alongside other binaries (override with --bin-dir) @@ -11,18 +11,21 @@ SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" TMP_ZIP="$(mktemp /tmp/lqos_api.XXXXXX.zip)" BIN_DIR="${LQOS_API_BIN_DIR:-$SCRIPT_DIR/bin}" +API_URL="${LQOS_API_URL:-https://download.libreqos.com/api3.zip}" RESTART_SERVICE="${LQOS_API_RESTART_SERVICE:-1}" usage() { cat < Date: Thu, 23 Apr 2026 10:26:42 -0600 Subject: [PATCH 20/51] changes --- docs-es/v2.0/api-es.md | 7 - docs/v2.0/api.md | 6 - src/configMigrator.py | 1 - src/lqos.example | 4 - src/rust/Cargo.lock | 4 +- src/rust/lqos_config/src/etc/migration.rs | 2 - src/rust/lqos_config/src/etc/mod.rs | 147 +----------------- .../lqos_config/src/etc/python_migration.rs | 92 ----------- src/rust/lqos_config/src/etc/test_data.rs | 3 - src/rust/lqos_config/src/etc/v15/example.toml | 4 - .../src/etc/v15/integration_common.rs | 42 ----- .../src/etc/v15/uisp_integration.rs | 36 ----- src/rust/lqos_probe/src/lib.rs | 2 +- src/rust/lqos_python/src/lib.rs | 7 - .../js_build/src/config/config_helper.js | 9 -- .../js_build/src/config_integration.js | 2 - .../node_manager/js_build/src/config_uisp.js | 1 - 17 files changed, 5 insertions(+), 364 deletions(-) diff --git a/docs-es/v2.0/api-es.md b/docs-es/v2.0/api-es.md index 5489b32b..09d68125 100644 --- a/docs-es/v2.0/api-es.md +++ b/docs-es/v2.0/api-es.md @@ -43,13 +43,6 @@ cd /opt/libreqos/src ./update_api.sh ``` -Las actualizaciones de LibreQoS instaladas desde Git conservan claves obsoletas -de compatibilidad, como `integration_common.always_overwrite_network_json` y -`uisp_integration.use_ptmp_as_parent`, en `/etc/lqos.conf` para binarios -antiguos de `lqos_api`. LibreQoS ignora estos valores, pero las versiones -antiguas de la API pueden requerir las claves para leer el archivo de -configuración. - Verificar estado del servicio: ```bash diff --git a/docs/v2.0/api.md b/docs/v2.0/api.md index fee31a3e..56a58e46 100644 --- a/docs/v2.0/api.md +++ b/docs/v2.0/api.md @@ -43,12 +43,6 @@ cd /opt/libreqos/src ./update_api.sh ``` -Git-installed LibreQoS upgrades preserve deprecated compatibility keys such as -`integration_common.always_overwrite_network_json` and -`uisp_integration.use_ptmp_as_parent` in `/etc/lqos.conf` for older -`lqos_api` binaries. LibreQoS ignores these values, but older API builds may -require the keys to parse the config file. - Verify service state: ```bash diff --git a/src/configMigrator.py b/src/configMigrator.py index 49dcfbb5..7e27533c 100644 --- a/src/configMigrator.py +++ b/src/configMigrator.py @@ -36,7 +36,6 @@ oldConfig = { # Common 'circuitNameUseAddress': getIspConfigValue('circuitNameUseAddress', True), - 'overwriteNetworkJSONalways': getIspConfigValue('overwriteNetworkJSONalways', False), 'ignoreSubnets': getIspConfigValue('ignoreSubnets', ["192.168.0.0/16"]), 'allowedSubnets': getIspConfigValue('allowedSubnets', ["100.64.0.0/10"]), 'excludeSites': getIspConfigValue('excludeSites', []), diff --git a/src/lqos.example b/src/lqos.example index 0a11f1be..547e0ddb 100644 --- a/src/lqos.example +++ b/src/lqos.example @@ -70,8 +70,6 @@ do_not_track_subnets = [ "192.168.66.0/24" ] [integration_common] circuit_name_as_address = false -# Deprecated compatibility key for older lqos_api binaries. LibreQoS ignores the value. -always_overwrite_network_json = true queue_refresh_interval_mins = 30 use_mikrotik_ipv6 = false @@ -111,8 +109,6 @@ ipv6_with_mikrotik = false bandwidth_overhead_factor = 1.0 commit_bandwidth_multiplier = 0.98 exception_cpes = [] -# Deprecated compatibility key for older lqos_api binaries. LibreQoS ignores the value. -use_ptmp_as_parent = false ignore_calculated_capacity = false [powercode_integration] diff --git a/src/rust/Cargo.lock b/src/rust/Cargo.lock index 2d7f16bc..3b0da010 100644 --- a/src/rust/Cargo.lock +++ b/src/rust/Cargo.lock @@ -3735,9 +3735,9 @@ checksum = "f87165f0995f63a9fbeea62b64d10b4d9d8e78ec6d7d51fb2125fda7bb36788f" [[package]] name = "rustls-webpki" -version = "0.103.12" +version = "0.103.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8279bb85272c9f10811ae6a6c547ff594d6a7f3c6c6b02ee9726d1d0dcfcdd06" +checksum = "61c429a8649f110dddef65e2a5ad240f747e85f7758a6bccc7e5777bd33f756e" dependencies = [ "aws-lc-rs", "ring", diff --git a/src/rust/lqos_config/src/etc/migration.rs b/src/rust/lqos_config/src/etc/migration.rs index 3a4a8fb8..9686a1ef 100644 --- a/src/rust/lqos_config/src/etc/migration.rs +++ b/src/rust/lqos_config/src/etc/migration.rs @@ -255,8 +255,6 @@ fn migrate_integration_common( new_config: &mut Config, ) -> Result<(), MigrationError> { new_config.integration_common.circuit_name_as_address = python_config.circuit_name_use_address; - new_config.integration_common.always_overwrite_network_json = - python_config.overwrite_network_jsonalways; new_config.integration_common.queue_refresh_interval_mins = python_config.queue_refresh_interval_mins as u32; new_config.integration_common.use_mikrotik_ipv6 = python_config.find_ipv6using_mikrotik_api; diff --git a/src/rust/lqos_config/src/etc/mod.rs b/src/rust/lqos_config/src/etc/mod.rs index 6f5a69e1..a796e2c8 100644 --- a/src/rust/lqos_config/src/etc/mod.rs +++ b/src/rust/lqos_config/src/etc/mod.rs @@ -370,79 +370,6 @@ fn maybe_migrate_uisp_capacity_defaults( Ok(migrated) } -fn legacy_bool_key_present(doc: &DocumentMut, section_name: &str, key_name: &str) -> bool { - doc.get(section_name) - .and_then(|section| section.as_table_like()) - .and_then(|section| section.get(key_name)) - .is_some() -} - -fn ensure_legacy_bool_key(doc: &mut DocumentMut, section_name: &str, key_name: &str) -> bool { - if legacy_bool_key_present(doc, section_name, key_name) { - return false; - } - - if let Some(section) = doc.get(section_name) { - if section.as_table_like().is_none() { - return false; - } - } else { - doc[section_name] = Item::Table(Table::new()); - } - - doc[section_name][key_name] = value(false); - true -} - -fn maybe_migrate_lqos_api_legacy_keys( - config_location: &str, - raw: String, -) -> Result { - let mut doc: DocumentMut = raw.parse().map_err(|e| LibreQoSConfigError::ParseError { - path: config_location.to_string(), - details: format!("Error parsing config: {e}"), - })?; - - let mut changed = false; - - if !legacy_bool_key_present(&doc, "integration_common", "always_overwrite_network_json") { - if let Some(section) = doc.get("integration_common") { - if section.as_table_like().is_none() { - return Ok(raw); - } - } else { - doc["integration_common"] = Item::Table(Table::new()); - } - - doc["integration_common"]["always_overwrite_network_json"] = value(true); - changed = true; - } - - changed |= ensure_legacy_bool_key(&mut doc, "uisp_integration", "use_ptmp_as_parent"); - - if !changed { - return Ok(raw); - } - let migrated = doc.to_string(); - - let config_path = Path::new(config_location); - if config_path.exists() { - let backup_path = format!("{config_location}.lqos_api_legacy_overwrite_backup"); - std::fs::copy(config_path, &backup_path).map_err(|e| LibreQoSConfigError::CannotWrite { - path: backup_path, - source: e, - })?; - } - - std::fs::write(config_path, &migrated).map_err(|e| LibreQoSConfigError::CannotWrite { - path: config_location.to_string(), - source: e, - })?; - - info!("Added deprecated lqos_api compatibility keys required by older lqos_api binaries."); - Ok(migrated) -} - fn actually_load_from_disk() -> Result, LibreQoSConfigError> { let config_location = if let Ok(lqos_config) = std::env::var("LQOS_CONFIG") { info!("Overriding lqos.conf location from environment variable."); @@ -487,7 +414,6 @@ fn actually_load_from_disk() -> Result, LibreQoSConfigError> { let raw = maybe_migrate_treeguard_link_virtualization_defaults(&config_location, raw)?; let raw = maybe_migrate_uisp_capacity_defaults(&config_location, raw)?; let raw = maybe_migrate_topology_compile_mode(&config_location, raw)?; - let raw = maybe_migrate_lqos_api_legacy_keys(&config_location, raw)?; let mut final_config = Config::load_from_string(&raw).map_err(|e| { error!("Unable to parse {config_location}"); @@ -627,9 +553,8 @@ pub enum LibreQoSConfigError { #[cfg(test)] mod tests { use super::{ - maybe_migrate_lqos_api_legacy_keys, maybe_migrate_topology_compile_mode, - maybe_migrate_treeguard_link_virtualization_defaults, maybe_migrate_uisp_capacity_defaults, - topology_compile_mode_migration_stamp_path, + maybe_migrate_topology_compile_mode, maybe_migrate_treeguard_link_virtualization_defaults, + maybe_migrate_uisp_capacity_defaults, topology_compile_mode_migration_stamp_path, treeguard_links_virtualization_migration_stamp_path, uisp_capacity_defaults_migration_stamp_path, }; @@ -660,74 +585,6 @@ mod tests { path.to_string_lossy().into_owned() } - #[test] - fn lqos_api_legacy_key_migration_rewrites_missing_keys() { - let test_dir = unique_test_dir(); - let raw = "[integration_common]\ncircuit_name_as_address = false\nqueue_refresh_interval_mins = 30\n"; - let config_path = write_test_config(&test_dir, raw); - - let config_path_str = path_string(&config_path); - let migrated = maybe_migrate_lqos_api_legacy_keys(&config_path_str, raw.to_string()) - .expect("migration should succeed"); - - assert!(migrated.contains("always_overwrite_network_json = true")); - assert!(migrated.contains("[uisp_integration]")); - assert!(migrated.contains("use_ptmp_as_parent = false")); - assert_eq!( - fs::read_to_string(&config_path).expect("config should be rewritten"), - migrated - ); - assert_eq!( - fs::read_to_string(config_path.with_extension("conf.lqos_api_legacy_overwrite_backup")) - .expect("backup should exist"), - raw - ); - - fs::remove_dir_all(&test_dir).expect("should clean up temp dir"); - } - - #[test] - fn lqos_api_legacy_key_migration_leaves_existing_keys() { - let test_dir = unique_test_dir(); - let raw = "[integration_common]\nalways_overwrite_network_json = false\nqueue_refresh_interval_mins = 30\n\n[uisp_integration]\nuse_ptmp_as_parent = true\n"; - let config_path = write_test_config(&test_dir, raw); - - let config_path_str = path_string(&config_path); - let migrated = maybe_migrate_lqos_api_legacy_keys(&config_path_str, raw.to_string()) - .expect("migration should succeed"); - - assert_eq!(migrated, raw); - assert_eq!( - fs::read_to_string(&config_path).expect("config should remain unchanged"), - raw - ); - assert!( - !config_path - .with_extension("conf.lqos_api_legacy_overwrite_backup") - .exists() - ); - - fs::remove_dir_all(&test_dir).expect("should clean up temp dir"); - } - - #[test] - fn lqos_api_legacy_key_migration_creates_missing_sections() { - let test_dir = unique_test_dir(); - let raw = "version = \"1.5\"\n"; - let config_path = write_test_config(&test_dir, raw); - - let config_path_str = path_string(&config_path); - let migrated = maybe_migrate_lqos_api_legacy_keys(&config_path_str, raw.to_string()) - .expect("migration should succeed"); - - assert!(migrated.contains("[integration_common]")); - assert!(migrated.contains("always_overwrite_network_json = true")); - assert!(migrated.contains("[uisp_integration]")); - assert!(migrated.contains("use_ptmp_as_parent = false")); - - fs::remove_dir_all(&test_dir).expect("should clean up temp dir"); - } - #[test] fn uisp_capacity_migration_rewrites_existing_values_and_stamps() { let test_dir = unique_test_dir(); diff --git a/src/rust/lqos_config/src/etc/python_migration.rs b/src/rust/lqos_config/src/etc/python_migration.rs index 56da8dd1..984d37f0 100644 --- a/src/rust/lqos_config/src/etc/python_migration.rs +++ b/src/rust/lqos_config/src/etc/python_migration.rs @@ -77,12 +77,6 @@ pub struct PythonMigration { pub influx_dbtoken: String, #[serde(rename = "circuitNameUseAddress")] pub circuit_name_use_address: bool, - #[serde( - default, - rename = "overwriteNetworkJSONalways", - alias = "always_overwrite_network_json" - )] - pub overwrite_network_jsonalways: bool, #[serde(rename = "ignoreSubnets")] pub ignore_subnets: Vec, #[serde(rename = "allowedSubnets")] @@ -177,89 +171,3 @@ impl PythonMigration { } } } - -#[cfg(test)] -mod tests { - use super::PythonMigration; - - fn minimal_python_migration_json() -> &'static str { - r#"{ - "sqm": "cake diffserv4", - "monitorOnlyMode": false, - "upstreamBandwidthCapacityDownloadMbps": 1000, - "upstreamBandwidthCapacityUploadMbps": 1000, - "generatedPNDownloadMbps": 1000, - "generatedPNUploadMbps": 1000, - "interfaceA": "ens20", - "interfaceB": "ens19", - "queueRefreshIntervalMins": 30, - "OnAStick": false, - "StickVlanA": 0, - "StickVlanB": 0, - "enableActualShellCommands": true, - "runShellCommandsAsSudo": false, - "queuesAvailableOverride": 0, - "useBinPackingToBalanceCPU": false, - "influxEnabled": false, - "influxDBurl": "http://localhost:8086", - "influxDBBucket": "libreqos", - "influxDBOrg": "libreqos", - "influxDBtoken": "", - "circuitNameUseAddress": false, - "ignoreSubnets": ["192.168.0.0/16"], - "allowedSubnets": ["100.64.0.0/10"], - "excludeSites": [], - "findIPv6usingMikrotikAPI": false, - "automaticImportSplynx": false, - "splynx_api_key": "", - "splynx_api_secret": "", - "splynx_api_url": "", - "automaticImportNetzur": false, - "netzur_api_key": "", - "netzur_api_url": "", - "netzur_api_timeout": 60, - "automaticImportUISP": false, - "uispAuthToken": "", - "UISPbaseURL": "", - "uispSite": "", - "uispStrategy": "full", - "uispSuspendedStrategy": "none", - "airMax_capacity": 1.0, - "ltu_capacity": 1.0, - "bandwidthOverheadFactor": 1.0, - "committedBandwidthMultiplier": 0.98, - "exceptionCPEs": {}, - "apiUsername": "", - "apiPassword": "", - "apiHostIP": "127.0.0.1", - "apiHostPost": 5000, - "automaticImportPowercode": false, - "powercode_api_key": "", - "powercode_api_url": "", - "automaticImportSonar": false, - "sonar_api_key": "", - "sonar_api_url": "", - "snmp_community": "public", - "sonar_active_status_ids": [], - "sonar_airmax_ap_model_ids": [], - "sonar_ltu_ap_model_ids": [] - }"# - } - - #[test] - fn python_migration_defaults_missing_deprecated_overwrite_flag() { - let parsed: PythonMigration = - serde_json::from_str(minimal_python_migration_json()).expect("json should parse"); - assert!(!parsed.overwrite_network_jsonalways); - } - - #[test] - fn python_migration_accepts_snake_case_deprecated_overwrite_flag_alias() { - let raw = minimal_python_migration_json().replace( - "\"circuitNameUseAddress\": false,", - "\"circuitNameUseAddress\": false,\n \"always_overwrite_network_json\": true,", - ); - let parsed: PythonMigration = serde_json::from_str(&raw).expect("json should parse"); - assert!(parsed.overwrite_network_jsonalways); - } -} diff --git a/src/rust/lqos_config/src/etc/test_data.rs b/src/rust/lqos_config/src/etc/test_data.rs index ea201d98..a7e84fbb 100644 --- a/src/rust/lqos_config/src/etc/test_data.rs +++ b/src/rust/lqos_config/src/etc/test_data.rs @@ -123,9 +123,6 @@ influxDBtoken = \"\" # Use Customer Name or Address as Circuit Name circuitNameUseAddress = True -# Legacy network.json overwrite flag from older configs. Modern integration mode ignores it. -overwriteNetworkJSONalways = False - # If a device shows a WAN IP within these subnets, assume they are behind NAT / un-shapable, and ignore them ignoreSubnets = ['192.168.0.0/16'] allowedSubnets = ['100.64.0.0/10'] diff --git a/src/rust/lqos_config/src/etc/v15/example.toml b/src/rust/lqos_config/src/etc/v15/example.toml index 8b1db083..730f272d 100644 --- a/src/rust/lqos_config/src/etc/v15/example.toml +++ b/src/rust/lqos_config/src/etc/v15/example.toml @@ -101,8 +101,6 @@ allow_subnets = [ "172.16.0.0/12", "10.0.0.0/8", "100.64.0.0/16", "192.168.0.0/1 [integration_common] circuit_name_as_address = false -# Deprecated compatibility key for older lqos_api binaries. LibreQoS ignores the value. -always_overwrite_network_json = true queue_refresh_interval_mins = 30 use_mikrotik_ipv6 = false ethernet_port_limits_enabled = true @@ -163,8 +161,6 @@ ipv6_with_mikrotik = false bandwidth_overhead_factor = 1.0 commit_bandwidth_multiplier = 0.98 exception_cpes = [] -# Deprecated compatibility key for older lqos_api binaries. LibreQoS ignores the value. -use_ptmp_as_parent = false infrastructure_transport_caps_enabled = true [powercode_integration] diff --git a/src/rust/lqos_config/src/etc/v15/integration_common.rs b/src/rust/lqos_config/src/etc/v15/integration_common.rs index 7ae9ec5f..06867725 100644 --- a/src/rust/lqos_config/src/etc/v15/integration_common.rs +++ b/src/rust/lqos_config/src/etc/v15/integration_common.rs @@ -7,10 +7,6 @@ fn default_ethernet_port_limits_enabled() -> bool { true } -fn default_always_overwrite_network_json() -> bool { - true -} - fn default_attachment_health_enabled() -> bool { true } @@ -82,14 +78,6 @@ pub struct IntegrationConfig { /// Replace names with addresses? pub circuit_name_as_address: bool, - /// Deprecated compatibility field for older sidecar services. - /// - /// LibreQoS no longer uses this value to decide whether integrations may - /// replace `network.json`, but older `lqos_api` binaries still require the - /// key to exist when parsing `/etc/lqos.conf`. - #[serde(default = "default_always_overwrite_network_json")] - pub always_overwrite_network_json: bool, - /// Queue refresh interval in minutes pub queue_refresh_interval_mins: u32, @@ -122,7 +110,6 @@ impl Default for IntegrationConfig { fn default() -> Self { Self { circuit_name_as_address: false, - always_overwrite_network_json: true, queue_refresh_interval_mins: 30, use_mikrotik_ipv6: false, promote_to_root: None, @@ -133,32 +120,3 @@ impl Default for IntegrationConfig { } } } - -#[cfg(test)] -mod tests { - use super::IntegrationConfig; - - #[test] - fn missing_legacy_overwrite_key_defaults_to_true() { - let config: IntegrationConfig = toml::from_str( - r#" -circuit_name_as_address = false -queue_refresh_interval_mins = 30 -"#, - ) - .expect("integration config without legacy key should deserialize"); - - assert!(config.always_overwrite_network_json); - } - - #[test] - fn serialized_config_includes_legacy_overwrite_key() { - let serialized = - toml::to_string(&IntegrationConfig::default()).expect("config should serialize"); - - assert!( - serialized.contains("always_overwrite_network_json = true"), - "serialized config should keep legacy key for older lqos_api binaries" - ); - } -} diff --git a/src/rust/lqos_config/src/etc/v15/uisp_integration.rs b/src/rust/lqos_config/src/etc/v15/uisp_integration.rs index 35c48cd2..3d31e1cb 100644 --- a/src/rust/lqos_config/src/etc/v15/uisp_integration.rs +++ b/src/rust/lqos_config/src/etc/v15/uisp_integration.rs @@ -27,12 +27,6 @@ pub struct UispIntegration { pub bandwidth_overhead_factor: f32, pub commit_bandwidth_multiplier: f32, pub exception_cpes: Vec, - /// Deprecated legacy importer-side PtMP-parent toggle. - /// - /// LibreQoS ignores this value, but older `lqos_api` binaries require the - /// key to exist when parsing `/etc/lqos.conf`. - #[serde(default)] - pub use_ptmp_as_parent: bool, #[serde(default = "default_ignore_calculated_capacity")] pub ignore_calculated_capacity: bool, #[serde(default = "default_infrastructure_transport_caps_enabled")] @@ -72,7 +66,6 @@ impl Default for UispIntegration { bandwidth_overhead_factor: 1.0, commit_bandwidth_multiplier: 1.0, exception_cpes: vec![], - use_ptmp_as_parent: false, ignore_calculated_capacity: false, infrastructure_transport_caps_enabled: default_infrastructure_transport_caps_enabled(), insecure_ssl: None, @@ -94,33 +87,4 @@ mod tests { assert_eq!(config.ltu_capacity, 1.0); assert!(config.infrastructure_transport_caps_enabled); } - - #[test] - fn deprecated_ptmp_parent_flag_loads_and_serializes_for_api_compatibility() { - let config: UispIntegration = toml::from_str( - r#" -enable_uisp = true -token = "" -url = "" -site = "" -strategy = "" -suspended_strategy = "" -airmax_capacity = 1.0 -ltu_capacity = 1.0 -exclude_sites = [] -ipv6_with_mikrotik = false -bandwidth_overhead_factor = 1.0 -commit_bandwidth_multiplier = 1.0 -exception_cpes = [] -use_ptmp_as_parent = true -"#, - ) - .expect("deprecated use_ptmp_as_parent key should still deserialize"); - - assert!(config.use_ptmp_as_parent); - - let serialized = - toml::to_string(&config).expect("uisp integration config should serialize"); - assert!(serialized.contains("use_ptmp_as_parent = true")); - } } diff --git a/src/rust/lqos_probe/src/lib.rs b/src/rust/lqos_probe/src/lib.rs index 6422c48a..03c63b92 100644 --- a/src/rust/lqos_probe/src/lib.rs +++ b/src/rust/lqos_probe/src/lib.rs @@ -344,7 +344,7 @@ impl ProbeManagerState { results .into_iter() - .zip(requests.into_iter()) + .zip(requests) .map(|(result, request)| { result.unwrap_or_else(|| { failed_observation( diff --git a/src/rust/lqos_python/src/lib.rs b/src/rust/lqos_python/src/lib.rs index 588b96e3..aafb385d 100644 --- a/src/rust/lqos_python/src/lib.rs +++ b/src/rust/lqos_python/src/lib.rs @@ -987,7 +987,6 @@ fn liblqos_python(m: &Bound<'_, PyModule>) -> PyResult<()> { m.add_function(wrap_pyfunction!(uisp_suspended_strategy, m)?)?; m.add_function(wrap_pyfunction!(airmax_capacity, m)?)?; m.add_function(wrap_pyfunction!(ltu_capacity, m)?)?; - m.add_function(wrap_pyfunction!(use_ptmp_as_parent, m)?)?; m.add_function(wrap_pyfunction!(uisp_base_url, m)?)?; m.add_function(wrap_pyfunction!(uisp_auth_token, m)?)?; m.add_function(wrap_pyfunction!(splynx_api_key, m)?)?; @@ -2292,12 +2291,6 @@ fn ltu_capacity() -> PyResult { Ok(config.uisp_integration.ltu_capacity) } -#[pyfunction] -fn use_ptmp_as_parent() -> PyResult { - let config = lqos_config::load_config().unwrap(); - Ok(config.uisp_integration.use_ptmp_as_parent) -} - #[pyfunction] fn uisp_base_url() -> PyResult { let config = lqos_config::load_config().unwrap(); 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 ed3f4b15..b5c5950e 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 @@ -84,15 +84,6 @@ function ensureOptionalConfigSections(config) { splynx.strategy = "ap_site"; } - const integration = config.integration_common; - if (typeof integration.always_overwrite_network_json !== "boolean") { - integration.always_overwrite_network_json = true; - } - const uisp = config.uisp_integration; - if (typeof uisp.use_ptmp_as_parent !== "boolean") { - uisp.use_ptmp_as_parent = false; - } - const topology = config.topology; const normalizeMode = (mode) => { if (typeof mode !== "string") { diff --git a/src/rust/lqosd/src/node_manager/js_build/src/config_integration.js b/src/rust/lqosd/src/node_manager/js_build/src/config_integration.js index a09b1fe4..47d7a295 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/config_integration.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/config_integration.js @@ -55,8 +55,6 @@ function updateConfig() { // Update only the integration_common section window.config.integration_common = { ...(window.config.integration_common || {}), - always_overwrite_network_json: - window.config.integration_common?.always_overwrite_network_json ?? true, circuit_name_as_address: document.getElementById("circuitNameAsAddress").checked, use_mikrotik_ipv6: document.getElementById("useMikrotikIpv6").checked, queue_refresh_interval_mins: parseInt(document.getElementById("queueRefreshInterval").value), diff --git a/src/rust/lqosd/src/node_manager/js_build/src/config_uisp.js b/src/rust/lqosd/src/node_manager/js_build/src/config_uisp.js index 0fd849b2..7aeb4c92 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/config_uisp.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/config_uisp.js @@ -107,7 +107,6 @@ function updateConfig() { // Update the config object window.config.uisp_integration = { ...existingUisp, - use_ptmp_as_parent: existingUisp.use_ptmp_as_parent ?? false, enable_uisp: document.getElementById("enableUisp").checked, token: document.getElementById("uispToken").value.trim(), url: document.getElementById("uispUrl").value.trim(), -- knotmirror 0.0.1 From 1ea441250dacc1a9b78489b54058138bc667e043 Mon Sep 17 00:00:00 2001 From: Name <2718612@2178972821991.net> Date: Thu, 23 Apr 2026 15:31:11 -0600 Subject: [PATCH 21/51] changes --- src/rust/lqos_bakery/src/lib.rs | 254 ++++++++++++++++++- src/rust/lqos_sys/src/bpf/common/lpm.h | 22 ++ src/rust/lqos_sys/src/bpf/lqos_kern.c | 3 + src/rust/lqos_sys/src/lib.rs | 2 + src/rust/lqos_sys/src/lqos_kernel.rs | 6 + src/rust/lqos_sys/src/tc_classify_control.rs | 144 +++++++++++ 6 files changed, 418 insertions(+), 13 deletions(-) create mode 100644 src/rust/lqos_sys/src/tc_classify_control.rs diff --git a/src/rust/lqos_bakery/src/lib.rs b/src/rust/lqos_bakery/src/lib.rs index c21c7ef7..28c47d3a 100644 --- a/src/rust/lqos_bakery/src/lib.rs +++ b/src/rust/lqos_bakery/src/lib.rs @@ -1936,6 +1936,91 @@ impl Drop for FullReloadScope { } } +struct TcClassifyBypassGuard { + cleanup_on_drop: bool, + setter: fn(bool) -> anyhow::Result<()>, +} + +struct BakeryFullReloadBatchResult { + result: ExecuteResult, + summary: String, + build_duration_ms: u64, + total_tc_commands: usize, + class_commands: usize, + qdisc_commands: usize, +} + +impl BakeryFullReloadBatchResult { + fn metrics<'a>(&self, summary: &'a str, ok: bool) -> BakeryApplyMetrics<'a> { + BakeryApplyMetrics { + apply_type: BakeryApplyType::FullReload, + summary, + build_duration_ms: self.build_duration_ms, + apply_duration_ms: self.result.duration_ms, + total_tc_commands: self.total_tc_commands, + class_commands: self.class_commands, + qdisc_commands: self.qdisc_commands, + ok, + } + } +} + +impl TcClassifyBypassGuard { + fn new() -> anyhow::Result { + Self::with_setter(lqos_sys::set_tc_classify_bypass) + } + + fn with_setter(setter: fn(bool) -> anyhow::Result<()>) -> anyhow::Result { + setter(true).map_err(|error| { + error!( + "Bakery full reload failed to enable TC classify bypass via tc_classify_control: {error}" + ); + error + })?; + info!("Bakery full reload enabled TC classify bypass"); + Ok(Self { + cleanup_on_drop: true, + setter, + }) + } + + fn disable(&mut self) -> anyhow::Result<()> { + if !self.cleanup_on_drop { + return Ok(()); + } + self.cleanup_on_drop = false; + (self.setter)(false).map_err(|error| { + error!( + "Bakery full reload failed to disable TC classify bypass via tc_classify_control: {error}" + ); + error + })?; + info!("Bakery full reload disabled TC classify bypass"); + Ok(()) + } + + fn keep_bypass_enabled_after_failure(&mut self, summary: &str) { + self.cleanup_on_drop = false; + error!( + "Bakery full reload keeping TC classify bypass enabled after failure: {}", + summary + ); + } +} + +impl Drop for TcClassifyBypassGuard { + fn drop(&mut self) { + if !self.cleanup_on_drop { + return; + } + if let Err(error) = self.disable() { + mark_reload_required(format!( + "Bakery full reload could not disable TC classify bypass after reload: {error}. Operator intervention may be required because traffic may remain unshaped." + )); + } + } +} + fn telemetry_state() -> &'static RwLock { BAKERY_TELEMETRY.get_or_init(|| RwLock::new(BakeryTelemetryState::default())) } @@ -10447,6 +10532,29 @@ fn full_reload( trigger_summary, ); let _reload_scope = FullReloadScope; + let mut tc_bypass_guard = match TcClassifyBypassGuard::new() { + Ok(guard) => guard, + Err(error) => { + let summary = + format!("Failed to enable TC classify bypass before full reload: {error}"); + error!("{summary}"); + mark_reload_required(format!( + "{summary}. Full reload was not attempted because TC classify could not be safely bypassed." + )); + mark_bakery_action_finished(BakeryApplyMetrics { + apply_type: BakeryApplyType::FullReload, + summary: &summary, + build_duration_ms: 0, + apply_duration_ms: 0, + total_tc_commands: 0, + class_commands: 0, + qdisc_commands: 0, + ok: false, + }); + *batch = None; + return; + } + }; let previous_sites = sites.clone(); let previous_circuits = circuits.clone(); let previous_live_circuits = live_circuits.clone(); @@ -10457,6 +10565,10 @@ fn full_reload( if let Err(error) = prepare_root_mq_for_full_reload(config) { let summary = format!("Failed to prepare root mq state before full reload: {error}"); error!("{summary}"); + tc_bypass_guard.keep_bypass_enabled_after_failure(&summary); + mark_reload_required(format!( + "{summary}. TC classify bypass remains enabled to avoid stale class-handle classification until a successful reload or operator intervention." + )); mark_bakery_action_finished(BakeryApplyMetrics { apply_type: BakeryApplyType::FullReload, summary: &summary, @@ -10479,6 +10591,10 @@ fn full_reload( let summary = format!("Failed to snapshot live qdisc handles before full reload: {error}"); error!("{summary}"); + tc_bypass_guard.keep_bypass_enabled_after_failure(&summary); + mark_reload_required(format!( + "{summary}. TC classify bypass remains enabled to avoid stale class-handle classification until a successful reload or operator intervention." + )); mark_bakery_action_finished(BakeryApplyMetrics { apply_type: BakeryApplyType::FullReload, summary: &summary, @@ -10502,7 +10618,7 @@ fn full_reload( warn!("Bakery: full reload skipped MQ layout restore because layout is unknown"); } - let result = process_batch( + let batch_result = process_batch( new_batch, config, &mut working_sites, @@ -10512,7 +10628,7 @@ fn full_reload( &live_reserved_handles, ); - if result.ok { + if batch_result.result.ok { *sites = working_sites; *circuits = working_circuits; live_circuits.clear(); @@ -10538,11 +10654,28 @@ fn full_reload( *mq_layout = previous_mq_layout; MQ_CREATED.store(previous_mq_created, Ordering::Relaxed); SHAPING_TREE_ACTIVE.store(previous_shaping_tree_active, Ordering::Relaxed); + let summary = "Bakery full reload failed while applying TC command batch"; + tc_bypass_guard.keep_bypass_enabled_after_failure(summary); + mark_reload_required(format!( + "{summary}. TC classify bypass remains enabled to avoid stale class-handle classification until a successful reload or operator intervention." + )); } - if result.ok { + if batch_result.result.ok { refresh_live_capacity_snapshot(config, true); + update_queue_distribution_snapshot(sites, circuits); + if let Err(error) = tc_bypass_guard.disable() { + let summary = format!( + "Bakery full reload applied TC commands but could not disable TC classify bypass: {error}. Operator intervention may be required because traffic may remain unshaped." + ); + mark_reload_required(summary.clone()); + mark_bakery_action_finished(batch_result.metrics(&summary, false)); + } else { + mark_bakery_action_finished(batch_result.metrics(&batch_result.summary, true)); + } + } else { + update_queue_distribution_snapshot(sites, circuits); + mark_bakery_action_finished(batch_result.metrics(&batch_result.summary, false)); } - update_queue_distribution_snapshot(sites, circuits); *batch = None; } @@ -10554,7 +10687,7 @@ fn process_batch( mq_layout: &MqDeviceLayout, qdisc_handles: &mut QdiscHandleState, extra_reserved_handles: &HashMap>, -) -> ExecuteResult { +) -> BakeryFullReloadBatchResult { info!("Bakery: Processing batch of {} commands", batch.len()); update_bakery_apply_progress(Some("Building tc command batch"), 0, 0, 0, 0); let build_started = std::time::Instant::now(); @@ -10620,18 +10753,14 @@ fn process_batch( ); let summary = summarize_apply_result("processing batch", &result); maybe_emit_memory_guard_urgent(&summary); - mark_bakery_action_finished(BakeryApplyMetrics { - apply_type: BakeryApplyType::FullReload, - summary: &summary, + BakeryFullReloadBatchResult { + result, + summary, build_duration_ms, - apply_duration_ms: result.duration_ms, total_tc_commands, class_commands, qdisc_commands, - ok: result.ok, - }); - - result + } } fn apply_stormguard_overrides( @@ -10679,8 +10808,34 @@ fn apply_stormguard_overrides( mod tests { use super::*; use lqos_config::Config; + use std::sync::Mutex; use std::time::{SystemTime, UNIX_EPOCH}; + static TC_BYPASS_SETTER_CALLS: Mutex> = Mutex::new(Vec::new()); + + fn recording_tc_bypass_setter(enabled: bool) -> anyhow::Result<()> { + TC_BYPASS_SETTER_CALLS.lock().expect("record setter call").push(enabled); + Ok(()) + } + + fn failing_tc_bypass_setter(enabled: bool) -> anyhow::Result<()> { + TC_BYPASS_SETTER_CALLS.lock().expect("record setter call").push(enabled); + Err(anyhow::anyhow!("synthetic TC classify bypass setter failure")) + } + + fn disable_failing_tc_bypass_setter(enabled: bool) -> anyhow::Result<()> { + TC_BYPASS_SETTER_CALLS.lock().expect("record setter call").push(enabled); + if enabled { + Ok(()) + } else { + Err(anyhow::anyhow!("synthetic TC classify bypass disable failure")) + } + } + + fn take_tc_bypass_setter_calls() -> Vec { + std::mem::take(&mut *TC_BYPASS_SETTER_CALLS.lock().expect("take setter calls")) + } + fn bakery_test_lock() -> &'static std::sync::Mutex<()> { crate::test_state_lock() } @@ -10725,9 +10880,82 @@ mod tests { SHAPING_TREE_ACTIVE.store(false, Ordering::Relaxed); FIRST_COMMIT_APPLIED.store(false, Ordering::Relaxed); FULL_RELOAD_IN_PROGRESS.store(false, Ordering::Relaxed); + take_tc_bypass_setter_calls(); install_bakery_test_config(); } + #[test] + fn tc_classify_bypass_guard_disables_on_scope_exit() { + let _guard = bakery_test_lock().lock().expect("bakery test lock"); + reset_bakery_test_state(); + + { + let _bypass_guard = + TcClassifyBypassGuard::with_setter(recording_tc_bypass_setter) + .expect("enable bypass guard"); + assert_eq!(take_tc_bypass_setter_calls(), vec![true]); + } + + assert_eq!(take_tc_bypass_setter_calls(), vec![false]); + } + + #[test] + fn tc_classify_bypass_guard_disables_on_early_return() { + fn early_return() -> Result<(), ()> { + let _bypass_guard = + TcClassifyBypassGuard::with_setter(recording_tc_bypass_setter) + .map_err(|_| ())?; + Err(()) + } + + let _guard = bakery_test_lock().lock().expect("bakery test lock"); + reset_bakery_test_state(); + + assert_eq!(early_return(), Err(())); + + assert_eq!(take_tc_bypass_setter_calls(), vec![true, false]); + } + + #[test] + fn tc_classify_bypass_guard_does_not_disable_when_enable_fails() { + let _guard = bakery_test_lock().lock().expect("bakery test lock"); + reset_bakery_test_state(); + + assert!(TcClassifyBypassGuard::with_setter(failing_tc_bypass_setter).is_err()); + + assert_eq!(take_tc_bypass_setter_calls(), vec![true]); + } + + #[test] + fn tc_classify_bypass_guard_reports_disable_failure_once() { + let _guard = bakery_test_lock().lock().expect("bakery test lock"); + reset_bakery_test_state(); + + { + let mut bypass_guard = + TcClassifyBypassGuard::with_setter(disable_failing_tc_bypass_setter) + .expect("enable bypass guard"); + assert!(bypass_guard.disable().is_err()); + } + + assert_eq!(take_tc_bypass_setter_calls(), vec![true, false]); + } + + #[test] + fn tc_classify_bypass_guard_keeps_bypass_enabled_after_failure() { + let _guard = bakery_test_lock().lock().expect("bakery test lock"); + reset_bakery_test_state(); + + { + let mut bypass_guard = + TcClassifyBypassGuard::with_setter(recording_tc_bypass_setter) + .expect("enable bypass guard"); + bypass_guard.keep_bypass_enabled_after_failure("test failure after TC mutation"); + } + + assert_eq!(take_tc_bypass_setter_calls(), vec![true]); + } + fn mk_add_circuit(hash: i64, ip_addresses: &str) -> Arc { Arc::new(BakeryCommands::AddCircuit { circuit_hash: hash, diff --git a/src/rust/lqos_sys/src/bpf/common/lpm.h b/src/rust/lqos_sys/src/bpf/common/lpm.h index 8bc1efe1..62529b0c 100644 --- a/src/rust/lqos_sys/src/bpf/common/lpm.h +++ b/src/rust/lqos_sys/src/bpf/common/lpm.h @@ -19,6 +19,28 @@ struct ip_hash_info { __u64 device_id; }; +struct tc_classify_control { + __u32 bypass; +}; + +struct { + __uint(type, BPF_MAP_TYPE_PERCPU_ARRAY); + __uint(max_entries, 1); + __type(key, __u32); + __type(value, struct tc_classify_control); + __uint(pinning, LIBBPF_PIN_BY_NAME); +} tc_classify_control SEC(".maps"); + +static __always_inline bool tc_classify_bypass_enabled(void) { + __u32 key = 0; + struct tc_classify_control *control = bpf_map_lookup_elem(&tc_classify_control, &key); + if (!control) { + // Fail safe: bypass classification rather than risk stale TC handles. + return true; + } + return control->bypass != 0; +} + // In on-a-stick mode, upload classes/CPUs are offset by this amount. // This is configured by userspace at load time. extern __u32 stick_offset; diff --git a/src/rust/lqos_sys/src/bpf/lqos_kern.c b/src/rust/lqos_sys/src/bpf/lqos_kern.c index f739de15..c127220e 100644 --- a/src/rust/lqos_sys/src/bpf/lqos_kern.c +++ b/src/rust/lqos_sys/src/bpf/lqos_kern.c @@ -266,6 +266,9 @@ int tc_iphash_to_cpu(struct __sk_buff *skb) bpf_debug("(TC) Error: interface direction unspecified, aborting."); return TC_ACT_OK; } + if (tc_classify_bypass_enabled()) { + return TC_ACT_OK; + } #ifdef VERBOSE bpf_debug("(TC) SKB VLAN TCI: %u", skb->vlan_tci); #endif diff --git a/src/rust/lqos_sys/src/lib.rs b/src/rust/lqos_sys/src/lib.rs index d7f7a462..f1e10074 100644 --- a/src/rust/lqos_sys/src/lib.rs +++ b/src/rust/lqos_sys/src/lib.rs @@ -22,6 +22,7 @@ mod ip_mapping; mod kernel_wrapper; mod linux; mod lqos_kernel; +mod tc_classify_control; mod throughput; pub use bpf_iterator::{end_flows, expire_throughput, iterate_flows}; @@ -35,4 +36,5 @@ pub use lqos_kernel::interface_name_to_index; pub use lqos_kernel::ip_mapping_capacity; pub use lqos_kernel::max_tracked_ips; pub use lqos_kernel::unload_xdp_from_interface; +pub use tc_classify_control::{initialize_tc_classify_bypass, set_tc_classify_bypass}; pub use throughput::{HostCounter, throughput_for_each}; diff --git a/src/rust/lqos_sys/src/lqos_kernel.rs b/src/rust/lqos_sys/src/lqos_kernel.rs index 4de922d9..809d05dc 100644 --- a/src/rust/lqos_sys/src/lqos_kernel.rs +++ b/src/rust/lqos_sys/src/lqos_kernel.rs @@ -152,6 +152,11 @@ fn ensure_ip_mapping_maps_abi() -> Result<()> { std::mem::size_of::() as u32, std::mem::size_of::() as u32, )?; + remove_incompatible_pinned_map( + "/sys/fs/bpf/tc_classify_control", + std::mem::size_of::() as u32, + std::mem::size_of::() as u32, + )?; remove_incompatible_pinned_map( "/sys/fs/bpf/map_traffic", std::mem::size_of::() as u32, @@ -339,6 +344,7 @@ pub fn attach_xdp_and_tc_to_interface( // Ensure no lingering XDP programs before loading/attaching let _ = unload_xdp_from_interface(interface_name); load_kernel(skeleton)?; + crate::initialize_tc_classify_bypass()?; let prog_fd = bpf::bpf_program__fd((*skeleton).progs.xdp_prog); attach_xdp_best_available(interface_index, prog_fd, interface_name)?; skeleton diff --git a/src/rust/lqos_sys/src/tc_classify_control.rs b/src/rust/lqos_sys/src/tc_classify_control.rs new file mode 100644 index 00000000..4af2788b --- /dev/null +++ b/src/rust/lqos_sys/src/tc_classify_control.rs @@ -0,0 +1,144 @@ +//! Control-map helpers for temporarily bypassing TC classification. + +use crate::lqos_kernel::bpf::libbpf_num_possible_cpus; +use anyhow::{Error, Result}; +use libbpf_sys::{bpf_map_update_elem, bpf_obj_get}; +use nix::libc::close; +use std::{ + ffi::{CString, c_void}, + io, + mem::size_of, +}; +use tracing::error; + +const TC_CLASSIFY_CONTROL_PATH: &str = "/sys/fs/bpf/tc_classify_control"; +const TC_CLASSIFY_CONTROL_KEY: u32 = 0; +const PER_CPU_VALUE_ALIGNMENT: usize = 8; + +/// Rust mirror of `struct tc_classify_control` in the eBPF program. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[repr(C)] +pub struct TcClassifyControl { + /// Non-zero tells TC classify to pass packets without setting TC handles. + pub bypass: u32, +} + +fn aligned_per_cpu_value_size() -> usize { + size_of::().div_ceil(PER_CPU_VALUE_ALIGNMENT) * PER_CPU_VALUE_ALIGNMENT +} + +fn per_cpu_payload(enabled: bool, cpu_count: u32) -> Vec { + let stride = aligned_per_cpu_value_size(); + let mut payload = vec![0u8; stride * cpu_count as usize]; + let control = TcClassifyControl { + bypass: u32::from(enabled), + }; + let bytes = control.bypass.to_ne_bytes(); + for cpu in 0..cpu_count as usize { + let offset = cpu * stride; + payload[offset..offset + bytes.len()].copy_from_slice(&bytes); + } + payload +} + +fn update_tc_classify_control(enabled: bool) -> Result<()> { + let path_c = CString::new(TC_CLASSIFY_CONTROL_PATH)?; + let fd = unsafe { bpf_obj_get(path_c.as_ptr()) }; + if fd < 0 { + let error = io::Error::last_os_error(); + let errno = error.raw_os_error().unwrap_or(0); + return Err(Error::msg(format!( + "Unable to open BPF map '{TC_CLASSIFY_CONTROL_PATH}' for TC classify bypass update (fd={fd}, errno={errno}, error={error})" + ))); + } + + let cpu_count = unsafe { libbpf_num_possible_cpus() }; + if cpu_count <= 0 { + unsafe { + close(fd); + } + return Err(Error::msg(format!( + "Unable to determine CPU count for TC classify bypass update: libbpf_num_possible_cpus returned {cpu_count}" + ))); + } + let cpu_count = u32::try_from(cpu_count).map_err(|e| { + unsafe { + close(fd); + } + Error::msg(format!( + "Unable to convert CPU count for TC classify bypass update: {e}" + )) + })?; + let mut key = TC_CLASSIFY_CONTROL_KEY; + let payload = per_cpu_payload(enabled, cpu_count); + let err = unsafe { + bpf_map_update_elem( + fd, + &mut key as *mut u32 as *mut c_void, + payload.as_ptr() as *mut c_void, + 0, + ) + }; + let update_error = (err != 0).then(io::Error::last_os_error); + unsafe { + close(fd); + } + if err != 0 { + let error = update_error.unwrap_or_else(|| io::Error::from_raw_os_error(0)); + let errno = error.raw_os_error().unwrap_or(0); + error!( + "Unable to update BPF map '{}' for TC classify bypass={} (err={}, errno={}, error={})", + TC_CLASSIFY_CONTROL_PATH, enabled, err, errno, error + ); + return Err(Error::msg(format!( + "Unable to update BPF map '{TC_CLASSIFY_CONTROL_PATH}' for TC classify bypass={enabled} (err={err}, errno={errno}, error={error})" + ))); + } + + Ok(()) +} + +/// Initializes TC classify bypass to disabled. +/// +/// This function has side effects: it writes all per-CPU values for the pinned +/// `tc_classify_control` BPF map. +pub fn initialize_tc_classify_bypass() -> Result<()> { + update_tc_classify_control(false) +} + +/// Enables or disables TC classify bypass. +/// +/// This function has side effects: it writes all per-CPU values for the pinned +/// `tc_classify_control` BPF map. When enabled, TC classify returns `TC_ACT_OK` +/// before consuming XDP metadata, flow cache, hot cache, or LPM mappings. +pub fn set_tc_classify_bypass(enabled: bool) -> Result<()> { + update_tc_classify_control(enabled) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn per_cpu_payload_uses_eight_byte_stride() { + let payload = per_cpu_payload(true, 3); + assert_eq!(payload.len(), 3 * PER_CPU_VALUE_ALIGNMENT); + for cpu in 0..3 { + let offset = cpu * PER_CPU_VALUE_ALIGNMENT; + assert_eq!( + &payload[offset..offset + size_of::()], + &1u32.to_ne_bytes() + ); + assert_eq!( + &payload[offset + size_of::()..offset + PER_CPU_VALUE_ALIGNMENT], + &[0, 0, 0, 0] + ); + } + } + + #[test] + fn disabled_payload_clears_all_per_cpu_values() { + let payload = per_cpu_payload(false, 2); + assert_eq!(payload, vec![0u8; 2 * PER_CPU_VALUE_ALIGNMENT]); + } +} -- knotmirror 0.0.1 From 24320563e31ee20fef39684b668045e236c3e128 Mon Sep 17 00:00:00 2001 From: Name <2718612@2178972821991.net> Date: Thu, 23 Apr 2026 15:40:44 -0600 Subject: [PATCH 22/51] changes --- .../lqosd/src/lts2_sys/control_channel.rs | 64 +++++++++---------- .../local_api/shaped_devices_page.rs | 4 +- src/rust/lqosd/src/node_manager/template.rs | 9 +-- .../lqosd/src/shaped_devices_tracker/mod.rs | 12 ++-- .../uisp_integration/src/strategies/common.rs | 2 +- 5 files changed, 46 insertions(+), 45 deletions(-) diff --git a/src/rust/lqosd/src/lts2_sys/control_channel.rs b/src/rust/lqosd/src/lts2_sys/control_channel.rs index 61d70af2..af32e472 100644 --- a/src/rust/lqosd/src/lts2_sys/control_channel.rs +++ b/src/rust/lqosd/src/lts2_sys/control_channel.rs @@ -1169,38 +1169,6 @@ async fn persistent_connection( } } -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn encode_ws_binary_round_trips_begin_ingest() { - let encoded = encode_ws_binary( - &messages::WsMessage::BeginIngest { - unique_id: 42, - n_chunks: 7, - }, - "BeginIngest", - ) - .expect("BeginIngest should encode"); - - let Message::Binary(bytes) = encoded else { - panic!("BeginIngest should encode to a binary websocket frame"); - }; - - match messages::WsMessage::from_bytes(&bytes).expect("BeginIngest should decode") { - messages::WsMessage::BeginIngest { - unique_id, - n_chunks, - } => { - assert_eq!(unique_id, 42); - assert_eq!(n_chunks, 7); - } - other => panic!("unexpected decoded message: {other:?}"), - } - } -} - async fn connect() -> anyhow::Result>> { let remote_host = crate::lts2_sys::lts2_client::get_remote_host(); let target = format!("wss://{}:443/shaper_gateway/ws", &remote_host); @@ -1789,3 +1757,35 @@ async fn tree_snapshot_streaming( } Ok(()) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn encode_ws_binary_round_trips_begin_ingest() { + let encoded = encode_ws_binary( + &messages::WsMessage::BeginIngest { + unique_id: 42, + n_chunks: 7, + }, + "BeginIngest", + ) + .expect("BeginIngest should encode"); + + let Message::Binary(bytes) = encoded else { + panic!("BeginIngest should encode to a binary websocket frame"); + }; + + match messages::WsMessage::from_bytes(&bytes).expect("BeginIngest should decode") { + messages::WsMessage::BeginIngest { + unique_id, + n_chunks, + } => { + assert_eq!(unique_id, 42); + assert_eq!(n_chunks, 7); + } + other => panic!("unexpected decoded message: {other:?}"), + } + } +} diff --git a/src/rust/lqosd/src/node_manager/local_api/shaped_devices_page.rs b/src/rust/lqosd/src/node_manager/local_api/shaped_devices_page.rs index 5ed297da..74ef024e 100644 --- a/src/rust/lqosd/src/node_manager/local_api/shaped_devices_page.rs +++ b/src/rust/lqosd/src/node_manager/local_api/shaped_devices_page.rs @@ -234,7 +234,7 @@ mod tests { ("fast", 40, 90, 2_000), ("idle", 0, 0, u64::MAX), ]); - let mut rows = vec![ + let mut rows = [ test_device("slow", "Slow Circuit", "Slow Device"), test_device("idle", "Idle Circuit", "Idle Device"), test_device("fast", "Fast Circuit", "Fast Device"), @@ -253,7 +253,7 @@ mod tests { #[test] fn dynamic_inventory_order_uses_alphabetic_tie_breakers() { let snapshot = test_snapshot(&[("alpha", 25, 25, 100), ("beta", 25, 25, 100)]); - let mut rows = vec![ + let mut rows = [ test_device("beta", "Beta Circuit", "Second Device"), test_device("alpha", "Alpha Circuit", "First Device"), ]; diff --git a/src/rust/lqosd/src/node_manager/template.rs b/src/rust/lqosd/src/node_manager/template.rs index aeb2c8be..774a0db9 100644 --- a/src/rust/lqosd/src/node_manager/template.rs +++ b/src/rust/lqosd/src/node_manager/template.rs @@ -287,10 +287,11 @@ mod tests { } fn test_config(runtime_dir: &std::path::Path, display_cobrand: bool) -> Config { - let mut config = Config::default(); - config.lqos_directory = runtime_dir.display().to_string(); - config.display_cobrand = display_cobrand; - config + Config { + lqos_directory: runtime_dir.display().to_string(), + display_cobrand, + ..Default::default() + } } #[test] diff --git a/src/rust/lqosd/src/shaped_devices_tracker/mod.rs b/src/rust/lqosd/src/shaped_devices_tracker/mod.rs index f311fd94..dee9d7b5 100644 --- a/src/rust/lqosd/src/shaped_devices_tracker/mod.rs +++ b/src/rust/lqosd/src/shaped_devices_tracker/mod.rs @@ -121,12 +121,12 @@ fn active_runtime_shaping_inputs_path(config: &lqos_config::Config) -> Result Result> { - if let Some(active_path) = active_runtime_shaping_inputs_path(config)? { - if active_path.exists() { - let raw = std::fs::read_to_string(&active_path)?; - let shaping_inputs = serde_json::from_str(&raw)?; - return Ok(Some(shaping_inputs)); - } + if let Some(active_path) = active_runtime_shaping_inputs_path(config)? + && active_path.exists() + { + let raw = std::fs::read_to_string(&active_path)?; + let shaping_inputs = serde_json::from_str(&raw)?; + return Ok(Some(shaping_inputs)); } let fallback_path = topology_shaping_inputs_path(config); diff --git a/src/rust/uisp_integration/src/strategies/common.rs b/src/rust/uisp_integration/src/strategies/common.rs index 30f0348d..ef45d236 100644 --- a/src/rust/uisp_integration/src/strategies/common.rs +++ b/src/rust/uisp_integration/src/strategies/common.rs @@ -213,7 +213,7 @@ fn dedup_raw_devices_by_id( let mut deduped_devices = Vec::with_capacity(original_raw_len); let mut deduped_json = Vec::with_capacity(original_json_len); - for (device, raw_json) in devices_raw.into_iter().zip(devices_as_json.into_iter()) { + for (device, raw_json) in devices_raw.into_iter().zip(devices_as_json) { let device_id = device.identification.id.clone(); if !seen_ids.insert(device_id.clone()) { *duplicate_counts.entry(device_id).or_insert(0) += 1; -- knotmirror 0.0.1 From 3597bd53ba9c2e11d4842b0a44f98fba631e10f8 Mon Sep 17 00:00:00 2001 From: Name <2718612@2178972821991.net> Date: Thu, 23 Apr 2026 20:41:01 -0600 Subject: [PATCH 23/51] changes --- src/rust/lqos_bakery/src/lib.rs | 566 +++++++++++++++--- src/rust/lqos_sys/src/bpf/lqos_kern.c | 3 + src/rust/lqos_sys/src/tc_classify_control.rs | 10 +- .../js_build/src/dashlets/bakery_activity.js | 8 +- .../js_build/src/dashlets/bakery_status.js | 10 +- .../src/dashlets/bakery_status_summary.js | 13 + .../src/node_manager/js_build/src/template.js | 5 +- .../src/node_manager/local_api/urgent.rs | 54 +- .../lqosd/src/node_manager/ws/messages.rs | 2 + .../src/node_manager/ws/ticker/bakery.rs | 2 + 10 files changed, 585 insertions(+), 88 deletions(-) diff --git a/src/rust/lqos_bakery/src/lib.rs b/src/rust/lqos_bakery/src/lib.rs index 28c47d3a..18579bd6 100644 --- a/src/rust/lqos_bakery/src/lib.rs +++ b/src/rust/lqos_bakery/src/lib.rs @@ -27,6 +27,7 @@ mod utils; use crossbeam_channel::{Receiver, RecvTimeoutError, Sender}; use parking_lot::RwLock; +use std::cmp::Reverse; use std::collections::VecDeque; use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; use std::path::{Path, PathBuf}; @@ -1742,6 +1743,10 @@ pub struct BakeryStatusSnapshot { pub reload_required: bool, /// Operator-facing reason for why a full reload is now required, if any. pub reload_required_reason: Option, + /// True when Bakery has put traffic into pass-through mode to avoid stale TC classification. + pub passthrough_degraded: bool, + /// Operator-facing reason for pass-through mode, if active. + pub passthrough_degraded_reason: Option, /// Number of runtime node operations currently marked dirty. pub dirty_subtree_count: usize, } @@ -1789,6 +1794,8 @@ struct BakeryTelemetryState { preflight: Option, reload_required: bool, reload_required_reason: Option, + passthrough_degraded: bool, + passthrough_degraded_reason: Option, dirty_subtree_count: usize, runtime_operations_by_site: HashMap, runtime_branch_states_by_site: HashMap, @@ -1904,6 +1911,8 @@ impl Default for BakeryTelemetryState { preflight: None, reload_required: false, reload_required_reason: None, + passthrough_degraded: false, + passthrough_degraded_reason: None, dirty_subtree_count: 0, runtime_operations_by_site: HashMap::new(), runtime_branch_states_by_site: HashMap::new(), @@ -1950,6 +1959,11 @@ struct BakeryFullReloadBatchResult { qdisc_commands: usize, } +struct ProcessBatchOptions<'a> { + extra_reserved_handles: &'a HashMap>, + preserved_root_child_majors: &'a HashMap>, +} + impl BakeryFullReloadBatchResult { fn metrics<'a>(&self, summary: &'a str, ok: bool) -> BakeryApplyMetrics<'a> { BakeryApplyMetrics { @@ -1978,6 +1992,10 @@ impl TcClassifyBypassGuard { error })?; info!("Bakery full reload enabled TC classify bypass"); + mark_passthrough_degraded( + "Bakery full reload is rebuilding TC. Traffic is temporarily passing without shaping to avoid stale class-handle classification.", + false, + ); Ok(Self { cleanup_on_drop: true, setter, @@ -1993,9 +2011,15 @@ impl TcClassifyBypassGuard { error!( "Bakery full reload failed to disable TC classify bypass via tc_classify_control: {error}" ); + mark_passthrough_degraded(format!( + "Bakery full reload applied TC commands but could not disable pass-through mode: {error}. Traffic may remain unshaped until operator intervention or a later successful reload." + ), true); error })?; info!("Bakery full reload disabled TC classify bypass"); + clear_passthrough_degraded( + "Bakery full reload disabled pass-through mode; normal shaping is active.", + ); Ok(()) } @@ -2005,6 +2029,12 @@ impl TcClassifyBypassGuard { "Bakery full reload keeping TC classify bypass enabled after failure: {}", summary ); + mark_passthrough_degraded( + format!( + "{summary}. Traffic is passing without shaping until a successful full reload clears TC classify bypass." + ), + true, + ); } } @@ -2101,6 +2131,39 @@ fn mark_reload_required(summary: String) { } } +fn mark_passthrough_degraded(summary: impl Into, emit_activity: bool) { + let summary = summary.into(); + let mut should_emit = false; + { + let mut state = telemetry_state().write(); + if !state.passthrough_degraded + || state.passthrough_degraded_reason.as_deref() != Some(summary.as_str()) + { + state.passthrough_degraded = true; + state.passthrough_degraded_reason = Some(summary.clone()); + should_emit = true; + } + } + if should_emit && emit_activity { + push_bakery_event("passthrough_degraded", "warning", summary); + } +} + +fn clear_passthrough_degraded(summary: &str) { + let mut should_emit = false; + { + let mut state = telemetry_state().write(); + if state.passthrough_degraded || state.passthrough_degraded_reason.is_some() { + state.passthrough_degraded = false; + state.passthrough_degraded_reason = None; + should_emit = true; + } + } + if should_emit { + push_bakery_event("passthrough_degraded_cleared", "info", summary.to_string()); + } +} + fn is_live_migration_reload_required_reason(reason: &str) -> bool { reason.starts_with("Bakery live-move ") || reason.starts_with("Bakery live migration ") } @@ -2239,6 +2302,8 @@ pub fn bakery_status_snapshot() -> BakeryStatusSnapshot { preflight: state.preflight, reload_required: state.reload_required, reload_required_reason: state.reload_required_reason, + passthrough_degraded: state.passthrough_degraded, + passthrough_degraded_reason: state.passthrough_degraded_reason, dirty_subtree_count: state.dirty_subtree_count, } } @@ -2749,42 +2814,228 @@ fn root_mq_add_command(interface_name: &str) -> Vec { ] } -fn prepare_root_mq_for_full_reload(config: &Arc) -> Result<(), String> { +fn command_token_after<'a>(command: &'a [String], needle: &str) -> Option<&'a str> { + command + .windows(2) + .find(|tokens| tokens[0] == needle) + .map(|tokens| tokens[1].as_str()) +} + +fn command_handle_after(command: &[String], needle: &str) -> Option { + command_token_after(command, needle).and_then(|token| TcHandle::from_string(token).ok()) +} + +fn command_interface(command: &[String]) -> Option<&str> { + command_token_after(command, "dev") +} + +fn root_infra_class_handle(handle: TcHandle, root_child_majors: &HashSet) -> bool { + let (major, minor) = handle.get_major_minor(); + root_child_majors.contains(&major) && matches!(minor, 1 | 2) +} + +fn root_infra_class_entry(entry: &LiveTcClassEntry, root_child_majors: &HashSet) -> bool { + let (major, minor) = entry.class_id.get_major_minor(); + if !root_child_majors.contains(&major) { + return false; + } + match (minor, entry.parent) { + (1, Some(parent)) => parent == tc_handle_from_major_minor(major, 0), + (2, Some(parent)) => parent == tc_handle_from_major_minor(major, 1), + _ => false, + } +} + +fn root_infra_qdisc_entry(entry: &LiveTcQdiscEntry, root_child_majors: &HashSet) -> bool { + if entry.is_root { + return true; + } + if entry + .parent + .is_some_and(|parent| parent.get_major_minor().0 == ROOT_MQ_MAJOR) + { + return true; + } + entry.parent.is_some_and(|parent| { + let (major, minor) = parent.get_major_minor(); + root_child_majors.contains(&major) && matches!(minor, 1 | 2) + }) +} + +fn root_infra_class_command( + command: &[String], + preserved_root_child_majors: &HashMap>, +) -> bool { + if !matches!(command.first().map(String::as_str), Some("class")) { + return false; + } + let Some(interface) = command_interface(command) else { + return false; + }; + let Some(root_child_majors) = preserved_root_child_majors.get(interface) else { + return false; + }; + command_handle_after(command, "classid") + .is_some_and(|handle| root_infra_class_handle(handle, root_child_majors)) +} + +fn root_infra_qdisc_command( + command: &[String], + preserved_root_child_majors: &HashMap>, +) -> bool { + if !matches!(command.first().map(String::as_str), Some("qdisc")) { + return false; + } + let Some(interface) = command_interface(command) else { + return false; + }; + let Some(root_child_majors) = preserved_root_child_majors.get(interface) else { + return false; + }; + command_handle_after(command, "parent").is_some_and(|parent| { + let (major, minor) = parent.get_major_minor(); + major == ROOT_MQ_MAJOR || root_child_majors.contains(&major) && matches!(minor, 1 | 2) + }) +} + +fn idempotent_full_reload_command( + mut command: Vec, + preserved_root_child_majors: &HashMap>, +) -> Vec { + if matches!(command.get(1).map(String::as_str), Some("add")) + && root_infra_class_command(&command, preserved_root_child_majors) + { + command[1] = "replace".to_string(); + } + command +} + +fn class_depth( + handle: TcHandle, + snapshot: &HashMap, + seen: &mut HashSet, +) -> usize { + if !seen.insert(handle) { + return 0; + } + snapshot + .get(&handle) + .and_then(|entry| entry.parent) + .map(|parent| 1 + class_depth(parent, snapshot, seen)) + .unwrap_or(0) +} + +fn class_delete_commands( + interface: &str, + class_snapshot: &HashMap, + root_child_majors: &HashSet, +) -> Vec> { + let mut entries = class_snapshot + .values() + .filter(|entry| { + entry.class_id.get_major_minor().0 != ROOT_MQ_MAJOR + && !root_infra_class_entry(entry, root_child_majors) + }) + .filter_map(|entry| { + entry.parent.map(|parent| { + let mut seen = HashSet::new(); + ( + class_depth(entry.class_id, class_snapshot, &mut seen), + entry.class_id, + parent, + ) + }) + }) + .collect::>(); + entries.sort_by_key(|entry| Reverse(entry.0)); + entries + .into_iter() + .map(|(_, class_id, parent)| { + vec![ + "class".to_string(), + "del".to_string(), + "dev".to_string(), + interface.to_string(), + "parent".to_string(), + parent.as_tc_string(), + "classid".to_string(), + class_id.as_tc_string(), + ] + }) + .collect() +} + +fn qdisc_delete_commands( + interface: &str, + qdisc_snapshot: &[LiveTcQdiscEntry], + root_child_majors: &HashSet, +) -> Vec> { + qdisc_snapshot + .iter() + .filter(|entry| !root_infra_qdisc_entry(entry, root_child_majors)) + .filter_map(|entry| entry.parent) + .map(|parent| { + vec![ + "qdisc".to_string(), + "del".to_string(), + "dev".to_string(), + interface.to_string(), + "parent".to_string(), + parent.as_tc_string(), + ] + }) + .collect() +} + +fn drain_managed_tree_to_defaults( + interface: &str, + qdisc_snapshot: &[LiveTcQdiscEntry], +) -> Result, String> { + let root_child_majors = managed_root_child_parent_handles(qdisc_snapshot) + .into_iter() + .map(|parent| parent.get_major_minor().1) + .collect::>(); + if root_child_majors.is_empty() { + return Ok(root_child_majors); + } + let class_snapshot = read_live_class_snapshot(interface)?; + let mut commands = qdisc_delete_commands(interface, qdisc_snapshot, &root_child_majors); + commands.extend(class_delete_commands( + interface, + &class_snapshot, + &root_child_majors, + )); + if commands.is_empty() { + return Ok(root_child_majors); + } + run_root_preflight_commands( + &commands, + &format!("full reload drain managed tree to defaults on {interface}"), + )?; + invalidate_live_tc_snapshots(); + Ok(root_child_majors) +} + +fn prepare_root_mq_for_full_reload( + config: &Arc, +) -> Result>, String> { + let mut preserved_root_child_majors = HashMap::new(); for interface in managed_interfaces_for_config(config) { let qdisc_snapshot = read_live_qdisc_snapshot(&interface)?; if retained_root_mq_entry(&qdisc_snapshot).is_some() { - let prune_commands = managed_root_child_parent_handles(&qdisc_snapshot) - .into_iter() - .map(|parent| { - vec![ - "qdisc".to_string(), - "del".to_string(), - "dev".to_string(), - interface.clone(), - "parent".to_string(), - parent.as_tc_string(), - ] - }) - .collect::>(); - if !prune_commands.is_empty() { - run_root_preflight_commands( - &prune_commands, - &format!("full reload retained-root child prune on {interface}"), - )?; - invalidate_live_tc_snapshots(); - } - - let pruned_qdisc_snapshot = read_live_qdisc_snapshot(&interface)?; - let pruned_class_snapshot = read_live_class_snapshot(&interface)?; - if verify_clean_root_child_tree( - &pruned_qdisc_snapshot, - &pruned_class_snapshot, - &interface, - ) - .is_ok() - { - continue; + let has_managed_root_children = + !managed_root_child_parent_handles(&qdisc_snapshot).is_empty(); + if has_managed_root_children { + let root_child_majors = + drain_managed_tree_to_defaults(&interface, &qdisc_snapshot)?; + if !root_child_majors.is_empty() { + preserved_root_child_majors.insert(interface.clone(), root_child_majors); + } } + info!( + "Bakery: preserving existing root mq/default path on {interface} during full reload" + ); + continue; } let replace_summary = run_root_preflight_commands( @@ -2832,7 +3083,7 @@ fn prepare_root_mq_for_full_reload(config: &Arc) -> Result<(), String> { )?; } - Ok(()) + Ok(preserved_root_child_majors) } fn live_tree_mutations_allowed(config: &Arc) -> bool { @@ -10562,26 +10813,29 @@ fn full_reload( let previous_mq_created = MQ_CREATED.load(Ordering::Relaxed); let previous_shaping_tree_active = SHAPING_TREE_ACTIVE.load(Ordering::Relaxed); - if let Err(error) = prepare_root_mq_for_full_reload(config) { - let summary = format!("Failed to prepare root mq state before full reload: {error}"); - error!("{summary}"); - tc_bypass_guard.keep_bypass_enabled_after_failure(&summary); - mark_reload_required(format!( - "{summary}. TC classify bypass remains enabled to avoid stale class-handle classification until a successful reload or operator intervention." - )); - mark_bakery_action_finished(BakeryApplyMetrics { - apply_type: BakeryApplyType::FullReload, - summary: &summary, - build_duration_ms: 0, - apply_duration_ms: 0, - total_tc_commands: 0, - class_commands: 0, - qdisc_commands: 0, - ok: false, - }); - *batch = None; - return; - } + let preserved_root_child_majors = match prepare_root_mq_for_full_reload(config) { + Ok(preserved_root_child_majors) => preserved_root_child_majors, + Err(error) => { + let summary = format!("Failed to prepare root mq state before full reload: {error}"); + error!("{summary}"); + tc_bypass_guard.keep_bypass_enabled_after_failure(&summary); + mark_reload_required(format!( + "{summary}. TC classify bypass remains enabled to avoid stale class-handle classification until a successful reload or operator intervention." + )); + mark_bakery_action_finished(BakeryApplyMetrics { + apply_type: BakeryApplyType::FullReload, + summary: &summary, + build_duration_ms: 0, + apply_duration_ms: 0, + total_tc_commands: 0, + class_commands: 0, + qdisc_commands: 0, + ok: false, + }); + *batch = None; + return; + } + }; invalidate_live_tc_snapshots(); MQ_CREATED.store(true, Ordering::Relaxed); @@ -10625,7 +10879,10 @@ fn full_reload( &mut working_circuits, &layout, &mut working_qdisc_handles, - &live_reserved_handles, + ProcessBatchOptions { + extra_reserved_handles: &live_reserved_handles, + preserved_root_child_majors: &preserved_root_child_majors, + }, ); if batch_result.result.ok { @@ -10686,7 +10943,7 @@ fn process_batch( circuits: &mut HashMap>, mq_layout: &MqDeviceLayout, qdisc_handles: &mut QdiscHandleState, - extra_reserved_handles: &HashMap>, + options: ProcessBatchOptions<'_>, ) -> BakeryFullReloadBatchResult { info!("Bakery: Processing batch of {} commands", batch.len()); update_bakery_apply_progress(Some("Building tc command batch"), 0, 0, 0, 0); @@ -10700,7 +10957,7 @@ fn process_batch( config, mq_layout, qdisc_handles, - extra_reserved_handles, + options.extra_reserved_handles, ) }) .filter_map(|b| { @@ -10718,6 +10975,8 @@ fn process_batch( b.to_commands(config, ExecutionMode::Builder) }) .flatten() + .map(|command| idempotent_full_reload_command(command, options.preserved_root_child_majors)) + .filter(|command| !root_infra_qdisc_command(command, options.preserved_root_child_majors)) .collect::>>(); let path = config.debug_state_file_path("linux_tc_rust.txt"); @@ -10814,21 +11073,34 @@ mod tests { static TC_BYPASS_SETTER_CALLS: Mutex> = Mutex::new(Vec::new()); fn recording_tc_bypass_setter(enabled: bool) -> anyhow::Result<()> { - TC_BYPASS_SETTER_CALLS.lock().expect("record setter call").push(enabled); + TC_BYPASS_SETTER_CALLS + .lock() + .expect("record setter call") + .push(enabled); Ok(()) } fn failing_tc_bypass_setter(enabled: bool) -> anyhow::Result<()> { - TC_BYPASS_SETTER_CALLS.lock().expect("record setter call").push(enabled); - Err(anyhow::anyhow!("synthetic TC classify bypass setter failure")) + TC_BYPASS_SETTER_CALLS + .lock() + .expect("record setter call") + .push(enabled); + Err(anyhow::anyhow!( + "synthetic TC classify bypass setter failure" + )) } fn disable_failing_tc_bypass_setter(enabled: bool) -> anyhow::Result<()> { - TC_BYPASS_SETTER_CALLS.lock().expect("record setter call").push(enabled); + TC_BYPASS_SETTER_CALLS + .lock() + .expect("record setter call") + .push(enabled); if enabled { Ok(()) } else { - Err(anyhow::anyhow!("synthetic TC classify bypass disable failure")) + Err(anyhow::anyhow!( + "synthetic TC classify bypass disable failure" + )) } } @@ -10890,21 +11162,22 @@ mod tests { reset_bakery_test_state(); { - let _bypass_guard = - TcClassifyBypassGuard::with_setter(recording_tc_bypass_setter) - .expect("enable bypass guard"); + let _bypass_guard = TcClassifyBypassGuard::with_setter(recording_tc_bypass_setter) + .expect("enable bypass guard"); assert_eq!(take_tc_bypass_setter_calls(), vec![true]); } assert_eq!(take_tc_bypass_setter_calls(), vec![false]); + let status = bakery_status_snapshot(); + assert!(!status.passthrough_degraded); + assert!(status.passthrough_degraded_reason.is_none()); } #[test] fn tc_classify_bypass_guard_disables_on_early_return() { fn early_return() -> Result<(), ()> { let _bypass_guard = - TcClassifyBypassGuard::with_setter(recording_tc_bypass_setter) - .map_err(|_| ())?; + TcClassifyBypassGuard::with_setter(recording_tc_bypass_setter).map_err(|_| ())?; Err(()) } @@ -10924,6 +11197,9 @@ mod tests { assert!(TcClassifyBypassGuard::with_setter(failing_tc_bypass_setter).is_err()); assert_eq!(take_tc_bypass_setter_calls(), vec![true]); + let status = bakery_status_snapshot(); + assert!(!status.passthrough_degraded); + assert!(status.passthrough_degraded_reason.is_none()); } #[test] @@ -10939,6 +11215,15 @@ mod tests { } assert_eq!(take_tc_bypass_setter_calls(), vec![true, false]); + let status = bakery_status_snapshot(); + assert!(status.passthrough_degraded); + assert!( + status + .passthrough_degraded_reason + .as_deref() + .unwrap_or_default() + .contains("could not disable pass-through mode") + ); } #[test] @@ -10947,13 +11232,21 @@ mod tests { reset_bakery_test_state(); { - let mut bypass_guard = - TcClassifyBypassGuard::with_setter(recording_tc_bypass_setter) - .expect("enable bypass guard"); + let mut bypass_guard = TcClassifyBypassGuard::with_setter(recording_tc_bypass_setter) + .expect("enable bypass guard"); bypass_guard.keep_bypass_enabled_after_failure("test failure after TC mutation"); } assert_eq!(take_tc_bypass_setter_calls(), vec![true]); + let status = bakery_status_snapshot(); + assert!(status.passthrough_degraded); + assert!( + status + .passthrough_degraded_reason + .as_deref() + .unwrap_or_default() + .contains("Traffic is passing without shaping") + ); } fn mk_add_circuit(hash: i64, ip_addresses: &str) -> Arc { @@ -13193,6 +13486,141 @@ mod tests { ); } + #[test] + fn idempotent_full_reload_command_replaces_class_adds() { + let root_child_majors = HashMap::from([("eth0".to_string(), HashSet::from([0x1]))]); + assert_eq!( + idempotent_full_reload_command( + vec![ + "class".to_string(), + "add".to_string(), + "dev".to_string(), + "eth0".to_string(), + "classid".to_string(), + "0x1:1".to_string(), + ], + &root_child_majors, + ), + vec![ + "class".to_string(), + "replace".to_string(), + "dev".to_string(), + "eth0".to_string(), + "classid".to_string(), + "0x1:1".to_string(), + ] + ); + } + + #[test] + fn idempotent_full_reload_command_leaves_non_add_commands_unchanged() { + let root_child_majors = HashMap::from([("eth0".to_string(), HashSet::from([0x1]))]); + assert_eq!( + idempotent_full_reload_command( + vec![ + "qdisc".to_string(), + "add".to_string(), + "dev".to_string(), + "eth0".to_string(), + ], + &root_child_majors, + ), + vec![ + "qdisc".to_string(), + "add".to_string(), + "dev".to_string(), + "eth0".to_string(), + ] + ); + assert_eq!( + idempotent_full_reload_command( + vec![ + "class".to_string(), + "del".to_string(), + "dev".to_string(), + "eth0".to_string(), + ], + &root_child_majors, + ), + vec![ + "class".to_string(), + "del".to_string(), + "dev".to_string(), + "eth0".to_string(), + ] + ); + assert_eq!( + idempotent_full_reload_command( + vec![ + "filter".to_string(), + "add".to_string(), + "dev".to_string(), + "eth0".to_string(), + ], + &root_child_majors, + ), + vec![ + "filter".to_string(), + "add".to_string(), + "dev".to_string(), + "eth0".to_string(), + ] + ); + } + + #[test] + fn root_infra_qdisc_command_matches_root_and_default_qdiscs() { + let root_child_majors = HashMap::from([("eth0".to_string(), HashSet::from([0x1]))]); + assert!(root_infra_qdisc_command( + &[ + "qdisc".to_string(), + "add".to_string(), + "dev".to_string(), + "eth0".to_string(), + "parent".to_string(), + "7FFF:0x1".to_string() + ], + &root_child_majors, + )); + assert!(root_infra_qdisc_command( + &[ + "qdisc".to_string(), + "add".to_string(), + "dev".to_string(), + "eth0".to_string(), + "parent".to_string(), + "0x1:2".to_string() + ], + &root_child_majors, + )); + assert!(!root_infra_qdisc_command( + &[ + "qdisc".to_string(), + "add".to_string(), + "dev".to_string(), + "eth0".to_string(), + "parent".to_string(), + "0x1:0x20".to_string() + ], + &root_child_majors, + )); + assert!(!root_infra_qdisc_command( + &[ + "qdisc".to_string(), + "add".to_string(), + "dev".to_string(), + "eth0".to_string(), + "parent".to_string(), + "0x3:2".to_string() + ], + &root_child_majors, + )); + assert!(!root_infra_qdisc_command( + &["class".to_string(), "replace".to_string()], + &root_child_majors, + )); + } + #[test] fn grouped_runtime_site_events_retain_human_site_name() { let _guard = bakery_test_lock().lock().expect("lock"); diff --git a/src/rust/lqos_sys/src/bpf/lqos_kern.c b/src/rust/lqos_sys/src/bpf/lqos_kern.c index c127220e..fa4d5b9d 100644 --- a/src/rust/lqos_sys/src/bpf/lqos_kern.c +++ b/src/rust/lqos_sys/src/bpf/lqos_kern.c @@ -109,6 +109,9 @@ int xdp_prog(struct xdp_md *ctx) bpf_debug("Error: interface direction unspecified, aborting."); return XDP_PASS; } + if (tc_classify_bypass_enabled()) { + return XDP_PASS; + } // Do we need to perform a VLAN redirect? bool vlan_redirect = false; diff --git a/src/rust/lqos_sys/src/tc_classify_control.rs b/src/rust/lqos_sys/src/tc_classify_control.rs index 4af2788b..c183a72f 100644 --- a/src/rust/lqos_sys/src/tc_classify_control.rs +++ b/src/rust/lqos_sys/src/tc_classify_control.rs @@ -1,4 +1,4 @@ -//! Control-map helpers for temporarily bypassing TC classification. +//! Control-map helpers for temporarily bypassing XDP redirection and TC classification. use crate::lqos_kernel::bpf::libbpf_num_possible_cpus; use anyhow::{Error, Result}; @@ -19,7 +19,8 @@ const PER_CPU_VALUE_ALIGNMENT: usize = 8; #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] #[repr(C)] pub struct TcClassifyControl { - /// Non-zero tells TC classify to pass packets without setting TC handles. + /// Non-zero tells XDP and TC classify to pass packets without redirecting + /// or setting TC handles. pub bypass: u32, } @@ -109,8 +110,9 @@ pub fn initialize_tc_classify_bypass() -> Result<()> { /// Enables or disables TC classify bypass. /// /// This function has side effects: it writes all per-CPU values for the pinned -/// `tc_classify_control` BPF map. When enabled, TC classify returns `TC_ACT_OK` -/// before consuming XDP metadata, flow cache, hot cache, or LPM mappings. +/// `tc_classify_control` BPF map. When enabled, XDP returns `XDP_PASS` before +/// CPU redirection, and TC classify returns `TC_ACT_OK` before consuming XDP +/// metadata, flow cache, hot cache, or LPM mappings. pub fn set_tc_classify_bypass(enabled: bool) -> Result<()> { update_tc_classify_control(enabled) } diff --git a/src/rust/lqosd/src/node_manager/js_build/src/dashlets/bakery_activity.js b/src/rust/lqosd/src/node_manager/js_build/src/dashlets/bakery_activity.js index e65b1ed2..4273f3b4 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/dashlets/bakery_activity.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/dashlets/bakery_activity.js @@ -86,12 +86,12 @@ function classifyEvent(entry) { if (event.endsWith("_started")) { outcome = "Running"; outcomeClass = "bg-primary-subtle text-primary border border-primary-subtle"; - } else if (event === "reload_required") { + } else if (event === "reload_required" || event === "passthrough_degraded") { stage = "Verify"; scope = "Full Reload"; - outcome = "Reload Required"; + outcome = event === "passthrough_degraded" ? "Pass-Through" : "Reload Required"; outcomeClass = "bg-danger-subtle text-danger border border-danger-subtle"; - } else if (event === "reload_required_cleared") { + } else if (event === "reload_required_cleared" || event === "passthrough_degraded_cleared") { stage = "Verify"; scope = "Full Reload"; outcome = "Cleared"; @@ -182,6 +182,8 @@ function describeOperation(entry, meta) { || event === "full_reload_started" || event === "reload_required" || event === "reload_required_cleared" + || event === "passthrough_degraded" + || event === "passthrough_degraded_cleared" || meta.scope === "Full Reload" ) { return { diff --git a/src/rust/lqosd/src/node_manager/js_build/src/dashlets/bakery_status.js b/src/rust/lqosd/src/node_manager/js_build/src/dashlets/bakery_status.js index f92c3f3c..abb7c63f 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/dashlets/bakery_status.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/dashlets/bakery_status.js @@ -16,12 +16,18 @@ function classifyOutcome(entry) { const event = (entry?.event ?? "").toString().trim().toLowerCase(); const status = (entry?.status ?? "").toString().trim().toLowerCase(); - if (event === "reload_required") { + if (event === "reload_required" || event === "passthrough_degraded") { return { - label: "Reload Required", + label: event === "passthrough_degraded" ? "Pass-Through" : "Reload Required", className: "bg-danger-subtle text-danger border border-danger-subtle", }; } + if (event === "passthrough_degraded_cleared") { + return { + label: "Shaping Restored", + className: "bg-success-subtle text-success border border-success-subtle", + }; + } if (event === "apply_failed" || status === "error") { return { label: "Failed", diff --git a/src/rust/lqosd/src/node_manager/js_build/src/dashlets/bakery_status_summary.js b/src/rust/lqosd/src/node_manager/js_build/src/dashlets/bakery_status_summary.js index 8ed1d8c6..74b25df0 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/dashlets/bakery_status_summary.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/dashlets/bakery_status_summary.js @@ -58,6 +58,10 @@ export class BakeryStatusSummaryDashlet extends BaseDashlet { this.lastFailureSummaryEl = document.createElement("span"); this.lastFailureSummaryEl.style.whiteSpace = "normal"; this.lastFailureSummaryEl.style.wordBreak = "break-word"; + this.shapingStateEl = document.createElement("div"); + this.passthroughReasonEl = document.createElement("span"); + this.passthroughReasonEl.style.whiteSpace = "normal"; + this.passthroughReasonEl.style.wordBreak = "break-word"; this.reloadRequiredEl = document.createElement("div"); this.reloadReasonEl = document.createElement("span"); this.reloadReasonEl.style.whiteSpace = "normal"; @@ -65,10 +69,12 @@ export class BakeryStatusSummaryDashlet extends BaseDashlet { tbody.appendChild(mkRow("Current Mode", this.modeEl)); tbody.appendChild(mkRow("Current Duration", this.durationEl)); + tbody.appendChild(mkRow("Shaping State", this.shapingStateEl)); tbody.appendChild(mkRow("Runtime Drift", this.reloadRequiredEl)); tbody.appendChild(mkRow("Last Success", this.lastSuccessEl)); tbody.appendChild(mkRow("Last Failure", this.lastFailureEl)); tbody.appendChild(mkRow("Failure Summary", this.lastFailureSummaryEl)); + tbody.appendChild(mkRow("Pass-Through Reason", this.passthroughReasonEl)); tbody.appendChild(mkRow("Reload Reason", this.reloadReasonEl)); table.appendChild(tbody); @@ -91,6 +97,12 @@ export class BakeryStatusSummaryDashlet extends BaseDashlet { this.modeEl.innerHTML = ""; this.modeEl.appendChild(bakeryModeBadge(status.mode)); + this.shapingStateEl.innerHTML = ""; + this.shapingStateEl.appendChild( + status.passthroughDegraded + ? mkBadge("Pass-Through / Unshaped", "bg-danger-subtle text-danger border border-danger-subtle") + : mkBadge("Normal Shaping", "bg-success-subtle text-success border border-success-subtle"), + ); this.reloadRequiredEl.innerHTML = ""; this.reloadRequiredEl.appendChild( status.reloadRequired @@ -104,6 +116,7 @@ export class BakeryStatusSummaryDashlet extends BaseDashlet { this.lastSuccessEl.textContent = formatUnixSecondsToLocalDateTime(status.lastSuccessUnix); this.lastFailureEl.textContent = formatUnixSecondsToLocalDateTime(status.lastFailureUnix); this.lastFailureSummaryEl.textContent = status.lastFailureSummary || "—"; + this.passthroughReasonEl.textContent = status.passthroughDegradedReason || "—"; this.reloadReasonEl.textContent = status.reloadRequiredReason || "—"; } } diff --git a/src/rust/lqosd/src/node_manager/js_build/src/template.js b/src/rust/lqosd/src/node_manager/js_build/src/template.js index 5f26f50b..227ea555 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/template.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/template.js @@ -1159,13 +1159,16 @@ function initUrgentIssues() { const td = document.createElement('td'); const when = new Date(it.ts * 1000).toLocaleString(); const sev = it.severity === 'Error' ? 'danger' : 'warning'; + const clearControl = it.clearable === false + ? 'Active' + : ``; td.innerHTML = `
${it.severity} ${it.code} (${it.source}) ${when} - + ${clearControl}
${it.message}
${it.context ? `
${it.context}
` : ''} diff --git a/src/rust/lqosd/src/node_manager/local_api/urgent.rs b/src/rust/lqosd/src/node_manager/local_api/urgent.rs index 5b0ff3d5..e2aeba9d 100644 --- a/src/rust/lqosd/src/node_manager/local_api/urgent.rs +++ b/src/rust/lqosd/src/node_manager/local_api/urgent.rs @@ -73,6 +73,7 @@ pub struct UrgentItem { pub code: String, pub message: String, pub context: Option, + pub clearable: bool, } #[derive(Debug, Serialize)] @@ -80,17 +81,32 @@ pub struct UrgentList { pub items: Vec, } -pub fn urgent_status_data() -> UrgentStatus { - let items = urgent::list(); - UrgentStatus { - has_urgent: !items.is_empty(), - count: items.len(), +fn bakery_passthrough_issue() -> Option { + let status = lqos_bakery::bakery_status_snapshot(); + if !status.reload_required || !status.passthrough_degraded { + return None; } + Some(UrgentItem { + id: u64::MAX, + ts: status + .last_failure_unix + .or(status.current_action_started_unix) + .unwrap_or_default(), + source: "System".to_string(), + severity: "Error".to_string(), + code: "BAKERY_PASSTHROUGH_DEGRADED".to_string(), + message: status.passthrough_degraded_reason.unwrap_or_else(|| { + "Bakery full reload failed while pass-through mode was active. Traffic may be unshaped until a successful full reload clears the degraded state.".to_string() + }), + context: status.reload_required_reason.map(|reason| { + format!("Reload required reason: {reason}") + }), + clearable: false, + }) } -pub fn urgent_list_data() -> UrgentList { - let items = urgent::list(); - let items: Vec = items +fn merged_urgent_items() -> Vec { + let mut items: Vec = urgent::list() .into_iter() .map(|i| UrgentItem { id: i.id, @@ -100,9 +116,29 @@ pub fn urgent_list_data() -> UrgentList { code: i.code, message: strip_ansi(&i.message), context: i.context, + clearable: true, }) .collect(); - UrgentList { items } + if let Some(issue) = bakery_passthrough_issue() { + items.push(issue); + } + items.sort_by_key(|item| item.ts); + items.reverse(); + items +} + +pub fn urgent_status_data() -> UrgentStatus { + let items = merged_urgent_items(); + UrgentStatus { + has_urgent: !items.is_empty(), + count: items.len(), + } +} + +pub fn urgent_list_data() -> UrgentList { + UrgentList { + items: merged_urgent_items(), + } } pub fn urgent_clear_id(id: u64) -> bool { diff --git a/src/rust/lqosd/src/node_manager/ws/messages.rs b/src/rust/lqosd/src/node_manager/ws/messages.rs index 83634905..c8967fe4 100644 --- a/src/rust/lqosd/src/node_manager/ws/messages.rs +++ b/src/rust/lqosd/src/node_manager/ws/messages.rs @@ -447,6 +447,8 @@ pub struct BakeryStatusState { pub preflight: Option, pub reload_required: bool, pub reload_required_reason: Option, + pub passthrough_degraded: bool, + pub passthrough_degraded_reason: Option, pub dirty_subtree_count: usize, } diff --git a/src/rust/lqosd/src/node_manager/ws/ticker/bakery.rs b/src/rust/lqosd/src/node_manager/ws/ticker/bakery.rs index 037697f4..dadbf324 100644 --- a/src/rust/lqosd/src/node_manager/ws/ticker/bakery.rs +++ b/src/rust/lqosd/src/node_manager/ws/ticker/bakery.rs @@ -152,6 +152,8 @@ fn map_status(snapshot: BakeryStatusSnapshot) -> BakeryStatusData { }, reload_required: snapshot.reload_required, reload_required_reason: snapshot.reload_required_reason, + passthrough_degraded: snapshot.passthrough_degraded, + passthrough_degraded_reason: snapshot.passthrough_degraded_reason, dirty_subtree_count: snapshot.dirty_subtree_count, queue_distribution: snapshot .queue_distribution -- knotmirror 0.0.1 From acaac20b4a2c41b59342e69b327447493bd11415 Mon Sep 17 00:00:00 2001 From: Name <2718612@2178972821991.net> Date: Thu, 23 Apr 2026 21:41:08 -0600 Subject: [PATCH 24/51] changes --- src/rust/lqos_bakery/src/lib.rs | 83 +++++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) diff --git a/src/rust/lqos_bakery/src/lib.rs b/src/rust/lqos_bakery/src/lib.rs index 18579bd6..9264b986 100644 --- a/src/rust/lqos_bakery/src/lib.rs +++ b/src/rust/lqos_bakery/src/lib.rs @@ -2847,6 +2847,9 @@ fn root_infra_class_entry(entry: &LiveTcClassEntry, root_child_majors: &HashSet< } fn root_infra_qdisc_entry(entry: &LiveTcQdiscEntry, root_child_majors: &HashSet) -> bool { + if entry.kind == "clsact" { + return true; + } if entry.is_root { return true; } @@ -2987,6 +2990,46 @@ fn qdisc_delete_commands( .collect() } +fn tc_classify_attached(interface: &str) -> Result { + let output = std::process::Command::new("/sbin/tc") + .args(["filter", "show", "dev", interface, "egress"]) + .output() + .map_err(|error| { + format!("Failed to inspect TC classify attachment on {interface}: {error}") + })?; + if !output.status.success() { + let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string(); + return Err(if stderr.is_empty() { + format!( + "Failed to inspect TC classify attachment on {interface}: tc exited with {:?}", + output.status.code() + ) + } else { + format!("Failed to inspect TC classify attachment on {interface}: {stderr}") + }); + } + Ok(String::from_utf8_lossy(&output.stdout).contains("tc_iphash_to_cp")) +} + +fn verify_tc_classify_attached(config: &Arc) -> Result<(), String> { + let mut missing = Vec::new(); + for interface in managed_interfaces_for_config(config) { + match tc_classify_attached(&interface) { + Ok(true) => {} + Ok(false) => missing.push(interface), + Err(error) => return Err(error), + } + } + if missing.is_empty() { + Ok(()) + } else { + Err(format!( + "TC classify egress attachment missing on interface(s): {}", + missing.join(", ") + )) + } +} + fn drain_managed_tree_to_defaults( interface: &str, qdisc_snapshot: &[LiveTcQdiscEntry], @@ -10920,6 +10963,18 @@ fn full_reload( if batch_result.result.ok { refresh_live_capacity_snapshot(config, true); update_queue_distribution_snapshot(sites, circuits); + if let Err(error) = verify_tc_classify_attached(config) { + let summary = format!( + "Bakery full reload applied TC commands but TC classify is not attached: {error}. Operator intervention may be required because traffic would otherwise remain unshaped." + ); + tc_bypass_guard.keep_bypass_enabled_after_failure(&summary); + mark_reload_required(format!( + "{summary}. TC classify bypass remains enabled until a successful reload or lqosd restart restores classifier attachment." + )); + mark_bakery_action_finished(batch_result.metrics(&summary, false)); + *batch = None; + return; + } if let Err(error) = tc_bypass_guard.disable() { let summary = format!( "Bakery full reload applied TC commands but could not disable TC classify bypass: {error}. Operator intervention may be required because traffic may remain unshaped." @@ -13486,6 +13541,34 @@ mod tests { ); } + #[test] + fn root_infra_qdisc_entry_preserves_clsact() { + let root_child_majors = HashSet::from([0x1]); + assert!(root_infra_qdisc_entry( + &live_qdisc_entry("clsact", Some(0xffff0000), Some(0xfffffff1), false), + &root_child_majors, + )); + } + + #[test] + fn qdisc_delete_commands_skip_clsact() { + let qdisc_snapshot = vec![ + live_qdisc_entry("clsact", Some(0xffff0000), Some(0xfffffff1), false), + live_qdisc_entry("fq_codel", Some(0x95000000), Some(0x10020), false), + ]; + assert_eq!( + qdisc_delete_commands("eth0", &qdisc_snapshot, &HashSet::from([0x1])), + vec![vec![ + "qdisc".to_string(), + "del".to_string(), + "dev".to_string(), + "eth0".to_string(), + "parent".to_string(), + "0x1:0x20".to_string(), + ]] + ); + } + #[test] fn idempotent_full_reload_command_replaces_class_adds() { let root_child_majors = HashMap::from([("eth0".to_string(), HashSet::from([0x1]))]); -- knotmirror 0.0.1 From c330cec1104f0ccfee7753af0a82ec3f17e26627 Mon Sep 17 00:00:00 2001 From: Name <2718612@2178972821991.net> Date: Sun, 26 Apr 2026 10:56:56 -0600 Subject: [PATCH 25/51] changes --- .../src/node_manager/js_build/src/circuit.js | 1 + .../lqosd/src/node_manager/ws/messages.rs | 1 + .../node_manager/ws/single_user_channels.rs | 19 ++++++++++++++++++- 3 files changed, 20 insertions(+), 1 deletion(-) 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 2e93c16c..716a44b8 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 @@ -2617,6 +2617,7 @@ function cleanupCircuitPage() { channelLink = null; } if (cakeChannel) { + wsClient.send({ Private: { StopCakeWatcher: null } }); cakeChannel.close(); cakeChannel = null; } diff --git a/src/rust/lqosd/src/node_manager/ws/messages.rs b/src/rust/lqosd/src/node_manager/ws/messages.rs index c8967fe4..37c41c7a 100644 --- a/src/rust/lqosd/src/node_manager/ws/messages.rs +++ b/src/rust/lqosd/src/node_manager/ws/messages.rs @@ -92,6 +92,7 @@ pub enum PrivateRequest { StopCircuitWatcher, StopPingMonitorWatch, CakeWatcher { circuit: String }, + StopCakeWatcher, Chatbot { browser_ts_ms: Option }, ChatbotUserInput { text: String }, WatchTreeAttachedCircuits { query: TreeAttachedCircuitsQuery }, diff --git a/src/rust/lqosd/src/node_manager/ws/single_user_channels.rs b/src/rust/lqosd/src/node_manager/ws/single_user_channels.rs index e80707c8..fc4c8eba 100644 --- a/src/rust/lqosd/src/node_manager/ws/single_user_channels.rs +++ b/src/rust/lqosd/src/node_manager/ws/single_user_channels.rs @@ -29,6 +29,7 @@ pub struct PrivateState { chatbot_request: Option, circuit_watch: Option>, ping_monitor_watch: Option>, + cake_watch: Option>, tree_attached_circuits_watch: Option>, circuit_metrics_watch: Option>, } @@ -55,6 +56,7 @@ impl PrivateState { chatbot_request: None, circuit_watch: None, ping_monitor_watch: None, + cake_watch: None, tree_attached_circuits_watch: None, circuit_metrics_watch: None, } @@ -90,7 +92,10 @@ impl PrivateState { self.abort_ping_monitor_watch(); } PrivateRequest::CakeWatcher { circuit } => { - spawn(cake_watcher(circuit, self.tx.clone())); + self.replace_cake_watch(circuit); + } + PrivateRequest::StopCakeWatcher => { + self.abort_cake_watch(); } PrivateRequest::Chatbot { browser_ts_ms } => { self.start_chatbot(normalize_browser_ts_ms(browser_ts_ms)) @@ -144,6 +149,17 @@ impl PrivateState { } } + fn replace_cake_watch(&mut self, circuit: String) { + self.abort_cake_watch(); + self.cake_watch = Some(spawn(cake_watcher(circuit, self.tx.clone()))); + } + + fn abort_cake_watch(&mut self) { + if let Some(handle) = self.cake_watch.take() { + handle.abort(); + } + } + fn replace_tree_attached_circuits_watch( &mut self, query: crate::node_manager::local_api::tree_attached_circuits::TreeAttachedCircuitsQuery, @@ -250,6 +266,7 @@ impl Drop for PrivateState { fn drop(&mut self) { self.abort_circuit_watch(); self.abort_ping_monitor_watch(); + self.abort_cake_watch(); self.abort_tree_attached_circuits_watch(); self.abort_circuit_metrics_watch(); } -- knotmirror 0.0.1 From 257dc0472105af34039d374ab73a5671b86be450 Mon Sep 17 00:00:00 2001 From: Name <2718612@2178972821991.net> Date: Sun, 26 Apr 2026 18:45:59 -0600 Subject: [PATCH 26/51] changes --- src/LibreQoS.py | 22 ++- src/rust/lqos_topology/src/lib.rs | 272 +++++++++++++++++++++++++----- 2 files changed, 248 insertions(+), 46 deletions(-) diff --git a/src/LibreQoS.py b/src/LibreQoS.py index 3a308d40..c1c1e289 100755 --- a/src/LibreQoS.py +++ b/src/LibreQoS.py @@ -2356,15 +2356,33 @@ def refreshShapers(): f"{circuit_id} ({circuit.get('circuitName', '')}) parent={circuit.get('ParentNode', '')} parent_id={circuit.get('effectiveParentNodeID', circuit.get('ParentNodeID', ''))}" ) if unattached_circuits: + examples = unattached_circuits[:20] warnings.warn( - "Some shaped circuits did not attach to the live queue tree. First examples: " + "; ".join(unattached_circuits[:20]), + "Some shaped circuits did not attach to the live queue tree. First examples: " + "; ".join(examples), stacklevel=2, ) logging.warning( "Unattached shaped circuits after queue build: %s total. Examples: %s", len(unattached_circuits), - "; ".join(unattached_circuits[:20]), + "; ".join(examples), ) + try: + submit_urgent_issue( + "LibreQoS", + "Warning", + "UNATTACHED_SHAPED_CIRCUITS", + ( + f"{len(unattached_circuits)} shaped circuit(s) did not attach to the live queue tree. " + "These circuits will not have class IDs or queue stats until topology/shaping inputs are fixed." + ), + json.dumps({ + "count": len(unattached_circuits), + "examples": examples, + }), + "UNATTACHED_SHAPED_CIRCUITS", + ) + except Exception as exc: + logging.debug("Unable to submit unattached shaped circuits urgent issue: %s", exc) minorByCPU = { int(queue): int(minor) diff --git a/src/rust/lqos_topology/src/lib.rs b/src/rust/lqos_topology/src/lib.rs index 17ef7764..9d773dcd 100644 --- a/src/rust/lqos_topology/src/lib.rs +++ b/src/rust/lqos_topology/src/lib.rs @@ -206,9 +206,6 @@ fn build_effective_queue_aliases( if exported_effective_nodes.contains_key(&effective_node.node_id) { continue; } - if effective_node.effective_attachment_id.is_some() { - continue; - } let Some(parent_name) = exported_effective_nodes .get(effective_node.logical_parent_node_id.as_str()) .cloned() @@ -232,6 +229,18 @@ fn build_effective_queue_aliases( (aliases_by_id, aliases_by_name) } +fn effective_parent_is_exported( + parent_id: &str, + parent_name: &str, + exported_effective_nodes: &HashMap, + exported_effective_names: &HashMap>, +) -> bool { + optional_non_empty(parent_id) + .is_some_and(|node_id| exported_effective_nodes.contains_key(&node_id)) + || optional_non_empty(parent_name) + .is_some_and(|node_name| exported_effective_names.contains_key(&node_name)) +} + fn resolve_legacy_parent_from_effective_tree( parent_node: &str, parent_node_id: Option<&str>, @@ -338,7 +347,7 @@ fn resolve_effective_parent_from_anchor( attachment_name, )); } - let Some((owner_node_id, owner_node_name)) = + let Some((owner_node_id, _owner_node_name)) = attachment_owner_by_attachment_id.get(anchor_id).cloned() else { if let Some((parent_id, parent_name)) = queue_aliases_by_id.get(anchor_id).cloned() { @@ -375,15 +384,15 @@ fn resolve_effective_parent_from_anchor( } if let Some((parent_id, parent_name)) = queue_aliases_by_id.get(owner_node_id.as_str()).cloned() { - return Some((parent_id, parent_name, None, None)); + return Some(( + parent_id, + parent_name, + optional_non_empty_owned(owner_effective.effective_attachment_id.clone()), + selected_attachment_name_for_node(owner_ui, owner_effective), + )); } - Some(( - owner_node_id, - owner_node_name, - optional_non_empty_owned(owner_effective.effective_attachment_id.clone()), - selected_attachment_name_for_node(owner_ui, owner_effective), - )) + None } fn ipv4_with_prefix_to_string(entry: &(std::net::Ipv4Addr, u32)) -> String { @@ -554,11 +563,11 @@ fn build_shaping_inputs( .and_then(|value| optional_non_empty(value)) }); let ( - effective_parent_node_id, - effective_parent_node_name, - effective_attachment_id, - effective_attachment_name, - resolution_source, + mut effective_parent_node_id, + mut effective_parent_node_name, + mut effective_attachment_id, + mut effective_attachment_name, + mut resolution_source, ) = if let Some((bucket_id, bucket_name)) = flat_bucket_assignments .as_ref() .and_then(|assignments| assignments.get(&device.circuit_id)) @@ -688,6 +697,27 @@ fn build_shaping_inputs( ) }; + if matches!( + resolution_source, + TopologyShapingResolutionSource::TopologyAnchor + | TopologyShapingResolutionSource::LegacyParent + ) && !effective_parent_is_exported( + &effective_parent_node_id, + &effective_parent_node_name, + &exported_effective_nodes, + &exported_effective_names, + ) { + warnings.push(format!( + "Circuit '{}' resolved to non-exported effective parent '{}' ({}). Falling back to generated parent-node shaping.", + device.circuit_id, effective_parent_node_name, effective_parent_node_id + )); + effective_parent_node_id.clear(); + effective_parent_node_name.clear(); + effective_attachment_id = None; + effective_attachment_name = None; + resolution_source = TopologyShapingResolutionSource::RuntimeFallback; + } + let logical_parent_node_name = optional_non_empty(&device.parent_node); let logical_parent_node_id = optional_non_empty_owned(device.parent_node_id.clone()); let circuit_index = if let Some(index) = circuits_by_id.get(&device.circuit_id).copied() { @@ -992,23 +1022,44 @@ struct QueueVirtualizationContext { forced_visible_node_names: HashSet, } -fn insert_optional_node_id(target: &mut HashSet, value: Option<&str>) { - if let Some(node_id) = value.map(str::trim).filter(|value| !value.is_empty()) { - target.insert(node_id.to_string()); +fn insert_direct_node_and_attachment_owner( + target: &mut HashSet, + value: Option<&str>, + attachment_owner_by_attachment_id: &HashMap, +) { + let Some(node_id) = value.map(str::trim).filter(|value| !value.is_empty()) else { + return; + }; + target.insert(node_id.to_string()); + if let Some((owner_node_id, _)) = attachment_owner_by_attachment_id.get(node_id) { + target.insert(owner_node_id.clone()); } } fn collect_direct_circuit_node_ids( shaped_devices: &ConfigShapedDevices, circuit_anchors: &[CircuitAnchor], + attachment_owner_by_attachment_id: &HashMap, ) -> HashSet { let mut direct_node_ids = HashSet::new(); for device in &shaped_devices.devices { - insert_optional_node_id(&mut direct_node_ids, device.parent_node_id.as_deref()); - insert_optional_node_id(&mut direct_node_ids, device.anchor_node_id.as_deref()); + insert_direct_node_and_attachment_owner( + &mut direct_node_ids, + device.parent_node_id.as_deref(), + attachment_owner_by_attachment_id, + ); + insert_direct_node_and_attachment_owner( + &mut direct_node_ids, + device.anchor_node_id.as_deref(), + attachment_owner_by_attachment_id, + ); } for anchor in circuit_anchors { - insert_optional_node_id(&mut direct_node_ids, Some(anchor.anchor_node_id.as_str())); + insert_direct_node_and_attachment_owner( + &mut direct_node_ids, + Some(anchor.anchor_node_id.as_str()), + attachment_owner_by_attachment_id, + ); } direct_node_ids } @@ -1029,8 +1080,12 @@ fn forced_visible_node_names(overrides: &lqos_overrides::OverrideFile) -> HashSe .collect() } -fn load_queue_virtualization_context(config: &Config) -> Result { +fn load_queue_virtualization_context( + config: &Config, + ui_state: &TopologyEditorStateFile, +) -> Result { let runtime_overrides = load_runtime_shaping_overrides(config)?; + let attachment_owner_by_attachment_id = build_attachment_owner_map(ui_state); let direct_circuit_node_ids = if topology_import_ingress_enabled(config) { let Some((mut shaped_devices, circuit_anchors)) = load_integration_shaping_artifacts(config)? @@ -1045,7 +1100,11 @@ fn load_queue_virtualization_context(config: &Config) -> Result Result std::result::Result> { let prepared = prepared_runtime_topology_editor_state(&canonical.to_editor_state(), overrides); - let virtualization = load_queue_virtualization_context(config).map_err(|err| { + let virtualization = load_queue_virtualization_context(config, &prepared).map_err(|err| { vec![format!( "Unable to load queue virtualization context: {err:#}" )] @@ -2527,6 +2590,18 @@ fn resolved_queue_visibility_policy( child_branch_counts: &HashMap, virtualization: &QueueVirtualizationContext, ) -> TopologyQueueVisibilityPolicy { + if virtualization + .forced_visible_node_names + .contains(ui_node.node_name.as_str()) + { + return TopologyQueueVisibilityPolicy::QueueVisible; + } + if virtualization + .direct_circuit_node_ids + .contains(ui_node.node_id.as_str()) + { + return TopologyQueueVisibilityPolicy::QueueVisible; + } match ui_node.queue_visibility_policy { TopologyQueueVisibilityPolicy::QueueVisible => resolved_auto_queue_visibility_policy( config, @@ -2553,20 +2628,8 @@ fn resolved_auto_queue_visibility_policy( ui_node: &TopologyEditorNode, tree_node: Option<&Value>, child_branch_counts: &HashMap, - virtualization: &QueueVirtualizationContext, + _virtualization: &QueueVirtualizationContext, ) -> TopologyQueueVisibilityPolicy { - if virtualization - .forced_visible_node_names - .contains(ui_node.node_name.as_str()) - { - return TopologyQueueVisibilityPolicy::QueueVisible; - } - if virtualization - .direct_circuit_node_ids - .contains(ui_node.node_id.as_str()) - { - return TopologyQueueVisibilityPolicy::QueueVisible; - } let Some(tree_node) = tree_node.and_then(Value::as_object) else { return TopologyQueueVisibilityPolicy::QueueVisible; }; @@ -4185,12 +4248,13 @@ mod tests { apply_effective_topology_to_canonical_state, apply_effective_topology_to_network_json, apply_effective_topology_to_network_json_from_canonical, auto_attachment_option, build_effective_topology_artifacts, build_effective_topology_artifacts_from_canonical, - build_shaping_inputs, compute_effective_state, publish_effective_topology_artifacts, - publish_topology_runtime_error_status, validate_effective_topology_network, + build_shaping_inputs, collect_direct_circuit_node_ids, compute_effective_state, + publish_effective_topology_artifacts, publish_topology_runtime_error_status, + validate_effective_topology_network, }; use lqos_config::{ - CircuitAnchor, CircuitAnchorsFile, Config, TopologyAllowedParent, - TopologyAttachmentHealthStateFile, TopologyAttachmentHealthStatus, + CircuitAnchor, CircuitAnchorsFile, Config, ConfigShapedDevices, ShapedDevice, + TopologyAllowedParent, TopologyAttachmentHealthStateFile, TopologyAttachmentHealthStatus, TopologyAttachmentOption, TopologyAttachmentRateSource, TopologyAttachmentRole, TopologyCanonicalIngressKind, TopologyCanonicalNode, TopologyCanonicalStateFile, TopologyEditorNode, TopologyEditorStateFile, TopologyEffectiveAttachmentState, @@ -4200,7 +4264,7 @@ mod tests { }; use lqos_overrides::{TopologyAttachmentMode, TopologyOverridesFile}; use serde_json::{Value, json}; - use std::collections::HashSet; + use std::collections::{HashMap, HashSet}; use std::fs; use std::path::PathBuf; use std::time::{SystemTime, UNIX_EPOCH}; @@ -4971,6 +5035,99 @@ mod tests { ); } + #[test] + fn shaping_inputs_resolve_virtual_attachment_owner_to_exported_parent_queue() { + let lqos_directory = unique_temp_dir("lqos-topology-virtual-owner-anchor"); + let config = Config { + lqos_directory: lqos_directory.to_string_lossy().to_string(), + state_directory: None, + ..Config::default() + }; + fs::write( + lqos_directory.join("ShapedDevices.csv"), + concat!( + "Circuit ID,Circuit Name,Device ID,Device Name,Parent Node,Parent Node ID,Anchor Node ID,MAC,IPv4,IPv6,Download Min Mbps,Upload Min Mbps,Download Max Mbps,Upload Max Mbps,Comment\n", + "\"circuit-1\",\"Glenn Tower Client Site\",\"device-1\",\"Device 1\",\"glenn-s1.streamitnet.com\",\"attachment-node\",\"attachment-node\",\"aa:bb:cc:dd:ee:ff\",\"192.0.2.10/32\",\"\",\"10\",\"10\",\"100\",\"100\",\"\"\n", + ), + ) + .expect("ShapedDevices.csv should write"); + + let artifacts = EffectiveTopologyArtifacts { + effective: TopologyEffectiveStateFile { + schema_version: 1, + generated_unix: Some(1), + canonical_generated_unix: Some(1), + health_generated_unix: Some(1), + nodes: vec![TopologyEffectiveNodeState { + node_id: "site-pop".to_string(), + logical_parent_node_id: "parent-switch".to_string(), + preferred_attachment_id: Some("attachment-node".to_string()), + effective_attachment_id: Some("attachment-node".to_string()), + fallback_reason: None, + all_attachments_suppressed: false, + attachments: Vec::new(), + }], + }, + ui_state: TopologyEditorStateFile { + schema_version: 1, + source: "test".to_string(), + generated_unix: Some(1), + ingress_identity: None, + nodes: vec![TopologyEditorNode { + node_id: "site-pop".to_string(), + node_name: "Glenn Fiber PoP".to_string(), + allowed_parents: vec![TopologyAllowedParent { + parent_node_id: "parent-switch".to_string(), + parent_node_name: "Parent Switch".to_string(), + attachment_options: vec![sample_attachment_option( + "attachment-node", + "glenn-s1.streamitnet.com", + )], + all_attachments_suppressed: false, + has_probe_unavailable_attachments: false, + }], + effective_attachment_name: Some("glenn-s1.streamitnet.com".to_string()), + ..TopologyEditorNode::default() + }], + }, + effective_network: Some(json!({ + "Parent Switch": { + "id": "parent-switch", + "name": "Parent Switch", + "children": { + "Glenn Fiber PoP": { + "id": "site-pop", + "name": "Glenn Fiber PoP", + "virtual": true, + "active_attachment_name": "glenn-s1.streamitnet.com", + "children": {} + } + } + } + })), + }; + + let shaping_inputs = build_shaping_inputs(&config, &artifacts) + .expect("shaping inputs should build") + .expect("shaping inputs should exist"); + let circuit = shaping_inputs + .circuits + .iter() + .find(|circuit| circuit.circuit_id == "circuit-1") + .expect("expected circuit"); + + assert_eq!(circuit.effective_parent_node_id, "parent-switch"); + assert_eq!(circuit.effective_parent_node_name, "Parent Switch"); + assert_eq!( + circuit.effective_attachment_name.as_deref(), + Some("glenn-s1.streamitnet.com") + ); + assert_eq!( + circuit.resolution_source, + lqos_config::TopologyShapingResolutionSource::TopologyAnchor + ); + } + #[test] fn shaping_inputs_resolve_legacy_parent_against_exported_effective_tree() { let lqos_directory = unique_temp_dir("lqos-topology-legacy-parent-resolution"); @@ -6049,6 +6206,33 @@ mod tests { assert_eq!(site.get("virtual").and_then(Value::as_bool), None); } + #[test] + fn active_attachment_circuit_marks_owner_site_direct() { + let shaped_devices = ConfigShapedDevices { + devices: vec![ShapedDevice { + circuit_id: "circuit-1".to_string(), + circuit_name: "Circuit 1".to_string(), + device_id: "device-1".to_string(), + device_name: "Device 1".to_string(), + parent_node: "Attachment Node".to_string(), + parent_node_id: Some("attachment-node".to_string()), + anchor_node_id: Some("attachment-node".to_string()), + ..ShapedDevice::default() + }], + ..ConfigShapedDevices::default() + }; + let attachment_owners = HashMap::from([( + "attachment-node".to_string(), + ("site-agg".to_string(), "Aggregation".to_string()), + )]); + + let direct_node_ids = + collect_direct_circuit_node_ids(&shaped_devices, &[], &attachment_owners); + + assert!(direct_node_ids.contains("attachment-node")); + assert!(direct_node_ids.contains("site-agg")); + } + #[test] fn large_site_with_force_visible_override_stays_visible() { let (config, canonical, editor_state, effective) = site_with_ap_fixture(); -- knotmirror 0.0.1 From a7ef49a3cb89fd46b5afe9e71fcc918d49e1574e Mon Sep 17 00:00:00 2001 From: Name <2718612@2178972821991.net> Date: Mon, 27 Apr 2026 08:09:30 -0600 Subject: [PATCH 27/51] changes --- .../src/lq_js_common/dashboard/dashboard.js | 48 +++++++++++++++++++ .../node_manager/js_build/src/pubsub/ws.js | 10 +++- 2 files changed, 57 insertions(+), 1 deletion(-) diff --git a/src/rust/lqosd/src/node_manager/js_build/src/lq_js_common/dashboard/dashboard.js b/src/rust/lqosd/src/node_manager/js_build/src/lq_js_common/dashboard/dashboard.js index f7448c8b..ba650d04 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/lq_js_common/dashboard/dashboard.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/lq_js_common/dashboard/dashboard.js @@ -5,6 +5,9 @@ import {heading5Icon} from "../helpers/content_builders"; import {openDashboardEditor} from "./dashboard_editor"; const DIAGNOSTIC_CHANNELS = new Set(["Cpu", "Ram", "RttHistogram"]); +const DASHBOARD_DATA_STALE_MS = 15000; +const DASHBOARD_SUBSCRIPTION_REFRESH_COOLDOWN_MS = 30000; +const DASHBOARD_WATCHDOG_INTERVAL_MS = 5000; export class Dashboard { // Takes the target DIV in which to build the dashboard, @@ -51,6 +54,9 @@ export class Dashboard { this.channelDisposers = new Map(); this.subscribedChannels = new Set(); this.lastMessages = new Map(); + this.lastDashboardMessageAt = Date.now(); + this.lastSubscriptionRefreshAt = 0; + this.watchdogTimer = null; // Auto Refresh Handling this.paused = false; @@ -256,10 +262,12 @@ export class Dashboard { } this.#queueImmediateDashlets(renderableDashlets); this.#syncWebSocketChannels(); + this.#startWatchdog(); this.#replayCachedMessages(renderableDashlets); } destroy() { + this.#stopWatchdog(); this.#disposeWebSocketChannels(); if (window.__lqosDashboardDashletHook) { delete window.__lqosDashboardDashletHook; @@ -680,12 +688,52 @@ export class Dashboard { }); } + #startWatchdog() { + this.#stopWatchdog(); + this.lastDashboardMessageAt = Date.now(); + this.watchdogTimer = window.setInterval(() => { + this.#checkDashboardDataFlow(); + }, DASHBOARD_WATCHDOG_INTERVAL_MS); + } + + #stopWatchdog() { + if (this.watchdogTimer !== null) { + window.clearInterval(this.watchdogTimer); + this.watchdogTimer = null; + } + } + + #checkDashboardDataFlow() { + if (this.paused || this.subscribedChannels.size === 0) { + return; + } + const now = Date.now(); + const ageMs = now - this.lastDashboardMessageAt; + if (ageMs < DASHBOARD_DATA_STALE_MS) { + return; + } + if (now - this.lastSubscriptionRefreshAt < DASHBOARD_SUBSCRIPTION_REFRESH_COOLDOWN_MS) { + return; + } + const activeChannels = Array.from(this.subscribedChannels); + this.lastSubscriptionRefreshAt = now; + this.lastDashboardMessageAt = now; + this.#debug("stale-data-refresh", { + ageMs, + channels: activeChannels, + wsConnected: !!this.wsClient.ws, + handshakeDone: !!this.wsClient.handshake_done, + }); + this.wsClient.refreshSubscriptions("dashboard-data-stale"); + } + #handleWebSocketMessage(msg) { if (!msg || !msg.event || this.paused) { return; } this.lastMessages.set(msg.event, msg); + this.lastDashboardMessageAt = Date.now(); this.tickCounter++; this.tickCounter %= this.cadence; const renderableDashlets = this.#renderableDashlets(); diff --git a/src/rust/lqosd/src/node_manager/js_build/src/pubsub/ws.js b/src/rust/lqosd/src/node_manager/js_build/src/pubsub/ws.js index b528b77c..71b2ed3b 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/pubsub/ws.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/pubsub/ws.js @@ -356,7 +356,15 @@ export class WsClient { return; } for (const handler of Array.from(list)) { - handler(msg); + try { + handler(msg); + } catch (err) { + console.error(`Websocket handler failed for ${msg.event}`, err); + dashboardWsDebug("handler-error", { + eventName: msg.event, + message: err && err.message ? err.message : String(err), + }); + } } } -- knotmirror 0.0.1 From 6e82dad7cd6b531935cf7b716d76afbaa5db8d7b Mon Sep 17 00:00:00 2001 From: Name <2718612@2178972821991.net> Date: Tue, 28 Apr 2026 08:47:33 -0600 Subject: [PATCH 28/51] changes --- src/LibreQoS.py | 81 ++----------------------- src/rust/lqos_config/src/planner.rs | 91 +++++++++++++++++++++++++++++ 2 files changed, 95 insertions(+), 77 deletions(-) diff --git a/src/LibreQoS.py b/src/LibreQoS.py index c1c1e289..657741b8 100755 --- a/src/LibreQoS.py +++ b/src/LibreQoS.py @@ -664,60 +664,6 @@ def planner_circuit_identity_key(circuit): return circuit_id -def load_minor_state_from_queuing_structure(path=None): - if path is None: - path = get_queuing_structure_path() - data = _load_json_dict(path) - network = data.get("Network") - if not isinstance(network, dict): - return {"sites": {}, "circuits": {}} - - sites = {} - circuits = {} - - def walk(node_map, trail=()): - for node_name, node in sorted(node_map.items()): - if not isinstance(node, dict): - continue - node_path = trail + (node_name,) - site_key = "/".join(node_path) - parent_path = "/".join(trail) - queue = _parse_int_token(node.get("cpuNum")) - class_minor = _parse_int_token(node.get("classMinor")) - class_major = _parse_int_token(node.get("classMajor")) - up_class_major = _parse_int_token(node.get("up_classMajor")) - if queue is not None and class_minor is not None: - sites[site_key] = { - "class_minor": class_minor, - "queue": queue + 1, - "parent_path": parent_path, - "class_major": class_major, - "up_class_major": up_class_major, - } - - if isinstance(node.get("circuits"), list): - for circuit in node.get("circuits", []): - if not isinstance(circuit, dict): - continue - circuit_id = circuit.get("circuitID") - circuit_minor = _parse_int_token(circuit.get("classMinor")) - if queue is None or circuit_id is None or circuit_minor is None: - continue - circuits[str(circuit_id)] = { - "class_minor": circuit_minor, - "queue": queue + 1, - "parent_node": circuit.get("ParentNode", node_name), - "class_major": _parse_int_token(circuit.get("classMajor")), - "up_class_major": _parse_int_token(circuit.get("up_classMajor")), - } - - children = node.get("children") - if isinstance(children, dict): - walk(children, node_path) - - walk(network) - return {"sites": sites, "circuits": circuits} - 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 @@ -2029,9 +1975,8 @@ def refreshShapers(): f"Failed to save planner state at {state_path}: {e}", stacklevel=2 ) - # Seed persisted site/circuit minor assignments. When planner state is absent, - # fall back to the previous queuing structure so the first run after an upgrade - # can preserve existing class IDs. + # Load persisted top-level planner state. Full reloads rebuild TC, so + # site/circuit class minors are runtime artifacts and are not reused below. try: state # noqa: B018 except NameError: @@ -2039,24 +1984,6 @@ def refreshShapers(): state_path = get_planner_state_path() if not isinstance(state, dict) or len(state.keys()) == 0: state = load_planner_state(state_path, None) - try: - circuit_state_from_disk = state.get("circuits", {}) if isinstance(state, dict) else {} - except Exception: - circuit_state_from_disk = {} - try: - site_state_from_disk = state.get("sites", {}) if isinstance(state, dict) else {} - except Exception: - site_state_from_disk = {} - if not isinstance(circuit_state_from_disk, dict): - circuit_state_from_disk = {} - if not isinstance(site_state_from_disk, dict): - site_state_from_disk = {} - if not circuit_state_from_disk or not site_state_from_disk: - fallback_minor_state = load_minor_state_from_queuing_structure() - if not site_state_from_disk: - site_state_from_disk = fallback_minor_state.get("sites", {}) or {} - if not circuit_state_from_disk: - circuit_state_from_disk = fallback_minor_state.get("circuits", {}) or {} circuit_state_updated = {} site_state_updated = {} planner_site_inputs = [] @@ -2126,8 +2053,8 @@ def refreshShapers(): identity_plan = plan_class_identities( planner_site_inputs, planner_circuit_groups, - site_state=site_state_from_disk, - circuit_state=circuit_state_from_disk, + site_state={}, + circuit_state={}, stick_offset=stickOffset, circuit_padding=CIRCUIT_PADDING, ) diff --git a/src/rust/lqos_config/src/planner.rs b/src/rust/lqos_config/src/planner.rs index 9b2c87ac..44edbee1 100644 --- a/src/rust/lqos_config/src/planner.rs +++ b/src/rust/lqos_config/src/planner.rs @@ -834,6 +834,97 @@ mod tests { assert_ne!(result.sites[0].class_minor, 0x29); } + #[test] + fn class_identity_planner_compacts_when_full_reload_ignores_saved_minors() { + const FRAGMENTED_SITE_MINOR: u16 = 0xff00; + const FRAGMENTED_CHILD_MINOR: u16 = 0xff02; + const FRAGMENTED_CIRCUIT_MINOR: u16 = 0xff10; + const CIRCUIT_PADDING: u32 = 8; + + let site_inputs = vec![ + SiteIdentityInput { + site_key: "CpueQueue0/site-a".to_string(), + parent_path: "CpueQueue0".to_string(), + queue: 1, + has_children: true, + }, + SiteIdentityInput { + site_key: "CpueQueue0/site-a/child".to_string(), + parent_path: "CpueQueue0/site-a".to_string(), + queue: 1, + has_children: false, + }, + ]; + let circuit_groups = vec![CircuitIdentityGroupInput { + parent_node: "child".to_string(), + queue: 1, + circuit_ids: vec!["c1".to_string(), "c2".to_string()], + }]; + let fragmented_sites = BTreeMap::from([ + ( + "CpueQueue0/site-a".to_string(), + PlannerSiteIdentityState { + class_minor: FRAGMENTED_SITE_MINOR, + queue: 1, + parent_path: "CpueQueue0".to_string(), + class_major: 1, + up_class_major: 0x41, + }, + ), + ( + "CpueQueue0/site-a/child".to_string(), + PlannerSiteIdentityState { + class_minor: FRAGMENTED_CHILD_MINOR, + queue: 1, + parent_path: "CpueQueue0/site-a".to_string(), + class_major: 1, + up_class_major: 0x41, + }, + ), + ]); + let fragmented_circuits = BTreeMap::from([( + "c1".to_string(), + PlannerCircuitIdentityState { + class_minor: FRAGMENTED_CIRCUIT_MINOR, + queue: 1, + parent_node: "child".to_string(), + class_major: 1, + up_class_major: 0x41, + }, + )]); + + let sticky_result = plan_class_identities( + &site_inputs, + &circuit_groups, + &fragmented_sites, + &fragmented_circuits, + 0x40, + CIRCUIT_PADDING, + ); + assert!(sticky_result.last_used_minor_by_queue[&1] > u32::from(FRAGMENTED_CIRCUIT_MINOR)); + + let full_reload_result = plan_class_identities( + &site_inputs, + &circuit_groups, + &BTreeMap::new(), + &BTreeMap::new(), + 0x40, + CIRCUIT_PADDING, + ); + + let expected_last_minor = u32::from(full_reload_result.circuits[1].class_minor) + .saturating_add(1) + .saturating_add(CIRCUIT_PADDING); + assert_eq!(full_reload_result.sites[0].class_minor, 3); + assert_eq!(full_reload_result.sites[1].class_minor, 5); + assert_eq!(full_reload_result.circuits[0].class_minor, 6); + assert_eq!(full_reload_result.circuits[1].class_minor, 7); + assert_eq!( + full_reload_result.last_used_minor_by_queue[&1], + expected_last_minor + ); + } + #[test] fn class_identity_planner_runtime_constraints_prefer_runtime_band() { let site_inputs = vec![SiteIdentityInput { -- knotmirror 0.0.1 From 94ab976a828f9751852d244eea0fc78c4234e846 Mon Sep 17 00:00:00 2001 From: Name <2718612@2178972821991.net> Date: Tue, 28 Apr 2026 22:17:10 -0600 Subject: [PATCH 29/51] changes --- .../node_manager/js_build/src/pubsub/ws.js | 87 ++++++++++++++++++- 1 file changed, 84 insertions(+), 3 deletions(-) diff --git a/src/rust/lqosd/src/node_manager/js_build/src/pubsub/ws.js b/src/rust/lqosd/src/node_manager/js_build/src/pubsub/ws.js index 71b2ed3b..46b4f9e3 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/pubsub/ws.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/pubsub/ws.js @@ -3,6 +3,7 @@ import { Encoder, decode } from "../lq_js_common/helpers/cbor-x"; const ACK_TEXT = "I accept that this is an unstable, internal API and is unsupported"; const EXPECTED_UI_VERSION = (window.LQOS_UI_VERSION || "").trim() || null; const USER_TOKEN_COOKIE = "User-Token"; +const VERSION_RELOAD_KEY = "lqosWsVersionReload"; const encoder = new Encoder({ useRecords: false, variableMapSize: true }); const DIAGNOSTIC_CHANNELS = new Set(["Cpu", "Ram", "RttHistogram"]); @@ -78,6 +79,28 @@ function get_user_token() { return get_cookie_value(USER_TOKEN_COOKIE); } +function versionReloadKey(serverVersion) { + const clientVersion = EXPECTED_UI_VERSION || "missing"; + const wsVersion = (serverVersion || "missing").toString().trim() || "missing"; + return `${clientVersion}->${wsVersion}`; +} + +function hasReloadedForVersionMismatch(mismatchKey) { + try { + if (window.sessionStorage.getItem(VERSION_RELOAD_KEY) === mismatchKey) { + return true; + } + window.sessionStorage.setItem(VERSION_RELOAD_KEY, mismatchKey); + return false; + } catch (_) { + if (window.__lqosWsVersionReload === mismatchKey) { + return true; + } + window.__lqosWsVersionReload = mismatchKey; + return false; + } +} + export function ws_proto() { if (window.location.protocol.startsWith("https")) { return "wss://"; @@ -95,6 +118,7 @@ export class WsClient { this.reconnectTimer = null; this.reconnectDelayMs = 1000; this.manualClose = false; + this.versionReloading = false; } connect() { @@ -159,7 +183,9 @@ export class WsClient { }); this.ws = null; this.handshake_done = false; - this._scheduleReconnect(); + if (!this.versionReloading) { + this._scheduleReconnect(); + } }; socket.onerror = () => { @@ -171,7 +197,9 @@ export class WsClient { }); this.ws = null; this.handshake_done = false; - this._scheduleReconnect(); + if (!this.versionReloading) { + this._scheduleReconnect(); + } }; } @@ -194,6 +222,54 @@ export class WsClient { this.handlers.clear(); } + _dropSocket(reason = "unspecified") { + dashboardWsDebug("drop-socket", { + reason, + desiredChannels: Array.from(this.desiredChannels.keys()), + }); + const oldSocket = this.ws; + this.ws = null; + this.handshake_done = false; + if (oldSocket) { + try { + oldSocket.close(); + } catch (_) { + // Ignore close errors; reconnect/reload handling continues below. + } + } + } + + _reloadForVersionMismatch(serverVersion) { + const mismatchKey = versionReloadKey(serverVersion); + dashboardWsDebug("version-mismatch", { + expected: EXPECTED_UI_VERSION || "missing", + actual: serverVersion || "missing", + mismatchKey, + }); + + if (!hasReloadedForVersionMismatch(mismatchKey)) { + this.versionReloading = true; + this._dropSocket("version-mismatch"); + window.location.reload(); + window.setTimeout(() => { + if (this.versionReloading) { + this.versionReloading = false; + this._scheduleReconnect(); + } + }, 3000); + return true; + } + + console.error( + "Websocket version mismatch persisted after reload:", + `client=${EXPECTED_UI_VERSION || "missing"}`, + `server=${serverVersion || "missing"}`, + ); + this._dropSocket("version-mismatch-persistent"); + this._scheduleReconnect(); + return true; + } + refreshSubscriptions(reason = "unspecified") { dashboardWsDebug("refresh-subscriptions", { reason, @@ -318,9 +394,14 @@ export class WsClient { "Websocket version mismatch:", hello ? hello.version : "missing", ); - this.close(); + this._reloadForVersionMismatch(hello ? hello.version : null); return; } + try { + window.sessionStorage.removeItem(VERSION_RELOAD_KEY); + } catch (_) { + // Storage cleanup is best-effort. + } this.handshake_done = true; dashboardWsDebug("handshake-complete", { desiredChannels: Array.from(this.desiredChannels.keys()), -- knotmirror 0.0.1 From 691ff7dda4c1477201d85f22eda527338c3b5663 Mon Sep 17 00:00:00 2001 From: Name <2718612@2178972821991.net> Date: Wed, 29 Apr 2026 13:58:19 -0600 Subject: [PATCH 30/51] changes --- docs-es/v2.0/integrations-uisp-es.md | 2 + docs/v2.0/integrations-uisp.md | 3 + src/LibreQoS.py | 31 ++- .../node_manager/js_build/src/config_uisp.js | 31 ++- .../src/node_manager/static2/config_uisp.html | 4 +- src/rust/uisp_integration/src/errors.rs | 4 +- .../src/strategies/full/root_site.rs | 15 +- .../src/strategies/full/tree_walk.rs | 2 +- .../uisp_integration/src/strategies/full2.rs | 195 +++++++++++++++++- .../uisp_integration/src/strategies/mod.rs | 6 +- src/test_libreqos_shaping_inputs.py | 33 +++ 11 files changed, 309 insertions(+), 17 deletions(-) diff --git a/docs-es/v2.0/integrations-uisp-es.md b/docs-es/v2.0/integrations-uisp-es.md index b2a233e1..22177b1a 100644 --- a/docs-es/v2.0/integrations-uisp-es.md +++ b/docs-es/v2.0/integrations-uisp-es.md @@ -19,6 +19,8 @@ Use esta guía para evitar confusión con opciones: 3. Use `full` cuando necesite jerarquía/backhaul completo, tenga margen de CPU y ya haya validado topología/overrides. 4. Use `flat` solo si la jerarquía no es necesaria y prioriza rendimiento máximo. +El ajuste `Root UISP Site` solo es obligatorio en modo de topología `full`. En los modos `flat`, `ap_only` y `ap_site`, puede dejarse vacío; LibreQoS usará los data-links de Internet de UISP para elegir la raíz de importación, o creará una raíz de Internet generada cuando UISP reporte varios sitios conectados a Internet. + ## Expectativas en router mode - Router mode en UISP es compatible, pero depende de que la topología en UISP esté bien definida. diff --git a/docs/v2.0/integrations-uisp.md b/docs/v2.0/integrations-uisp.md index 649fa2d3..5b0b2497 100644 --- a/docs/v2.0/integrations-uisp.md +++ b/docs/v2.0/integrations-uisp.md @@ -11,6 +11,8 @@ Use this section first to avoid common topology-mode confusion. 3. Use `full` when you need full hierarchy/backhaul representation and have CPU headroom. 4. Use `flat` only when hierarchy is not needed and maximum performance is the priority. +The `Root UISP Site` setting is required only for `full` topology mode. In `flat`, `ap_only`, and `ap_site` modes, you may leave it blank; LibreQoS will use UISP Internet data-links to pick the import root, or create a generated Internet root when UISP reports multiple Internet-connected sites. + ## Router-Mode Expectations - UISP router mode is supported, but parent/route discovery quality depends on your UISP topology data quality. @@ -124,6 +126,7 @@ enable_uisp = true token = "your-api-token-here" url = "https://uisp.your_domain.com" site = "Root_Site_Name" # Root site for topology perspective +# Required for full topology mode; optional for flat, ap_only, and ap_site # Suspension Handling (see table above) suspended_strategy = "none" diff --git a/src/LibreQoS.py b/src/LibreQoS.py index 657741b8..93f17ac4 100755 --- a/src/LibreQoS.py +++ b/src/LibreQoS.py @@ -363,6 +363,32 @@ def _circuit_attachment_name_candidates(circuit): return candidates +def _normalize_circuit_shaping_parent(circuit, parent_node_ids=None): + parent_name = str(circuit.get('ParentNode', '') or '').strip() + effective_name = str(circuit.get('effectiveParentNodeName', '') or '').strip() + parent_id = str(circuit.get('effectiveParentNodeID', '') or circuit.get('ParentNodeID', '') or '').strip() + resolved_id_parent = '' + if parent_node_ids and parent_id: + resolved_id_parent = str(parent_node_ids.get(parent_id, '') or '').strip() + + if not parent_name: + parent_name = effective_name + if (not parent_name or parent_name == 'none') and resolved_id_parent: + parent_name = resolved_id_parent + if not parent_name: + parent_name = 'none' + + if is_generated_parent_node_name(parent_name) or ( + resolved_id_parent and resolved_id_parent != parent_name + ): + parent_id = '' + + circuit['shapingParentNode'] = parent_name + circuit['shapingParentNodeID'] = parent_id + circuit['shapingParentKey'] = f"id:{parent_id}" if parent_id else f"name:{parent_name}" + return parent_name, parent_id + + def _validate_planned_circuit_attachment(node_name, node_data, circuit, planned_identity): site_major = _parse_int_token(node_data.get('classMajor')) site_up_major = _parse_int_token(node_data.get('up_classMajor')) @@ -1753,11 +1779,10 @@ def refreshShapers(): circuits_by_parent_id = {} circuits_by_parent_name = {} for circuit in subscriberCircuits: - parent_id = str(circuit.get('effectiveParentNodeID', '') or circuit.get('ParentNodeID', '') or '').strip() + parent_name, parent_id = _normalize_circuit_shaping_parent(circuit, parent_node_ids) if parent_id: circuits_by_parent_id.setdefault(parent_id, []).append(circuit) - - for parent_name in _circuit_attachment_name_candidates(circuit): + elif parent_name and parent_name != 'none': circuits_by_parent_name.setdefault(parent_name, []).append(circuit) # Parse network structure and add devices from ShapedDevices.csv diff --git a/src/rust/lqosd/src/node_manager/js_build/src/config_uisp.js b/src/rust/lqosd/src/node_manager/js_build/src/config_uisp.js index 7aeb4c92..1f7a5994 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/config_uisp.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/config_uisp.js @@ -6,6 +6,30 @@ import { secretWillExistAfterSave, } from "./config/config_helper"; +function currentTopologyMode() { + return ( + window.config?.topology?.compile_mode + ?? document.getElementById("uispStrategy").value.trim() + ); +} + +function rootSiteRequiredForMode(mode) { + return mode === "full" || mode === "full2"; +} + +function updateRootSiteRequirement() { + const required = rootSiteRequiredForMode(currentTopologyMode()); + const siteInput = document.getElementById("uispSite"); + const siteLabel = document.getElementById("uispSiteLabel"); + const siteHelp = document.getElementById("uispSiteHelp"); + + siteInput.required = required; + siteLabel.textContent = required ? "Root UISP Site" : "Root UISP Site (Optional)"; + siteHelp.textContent = required + ? "Required for full topology mode. Enter the exact UISP site name at the root of the network." + : "Optional in this topology mode. Leave blank to let LibreQoS choose the import root."; +} + function validateConfig() { // Validate required fields when enabled if (document.getElementById("enableUisp").checked) { @@ -27,8 +51,8 @@ function validateConfig() { } const site = document.getElementById("uispSite").value.trim(); - if (!site) { - alert("UISP Site is required when UISP integration is enabled"); + if (rootSiteRequiredForMode(currentTopologyMode()) && !site) { + alert("Root UISP Site is required when full topology mode is selected"); return false; } @@ -148,6 +172,7 @@ loadConfig(() => { document.getElementById("uispSite").value = uisp.site ?? ""; document.getElementById("uispStrategy").value = window.config.topology?.compile_mode ?? uisp.strategy ?? "ap_site"; document.getElementById("uispSuspendedStrategy").value = uisp.suspended_strategy ?? "none"; + updateRootSiteRequirement(); // Numeric fields document.getElementById("uispAirmaxCapacity").value = uisp.airmax_capacity ?? 1.0; @@ -170,6 +195,8 @@ loadConfig(() => { clearButtonId: "clearUispToken", }); + document.getElementById("uispStrategy").addEventListener("change", updateRootSiteRequirement); + // Add save button click handler document.getElementById('saveButton').addEventListener('click', () => { if (validateConfig()) { diff --git a/src/rust/lqosd/src/node_manager/static2/config_uisp.html b/src/rust/lqosd/src/node_manager/static2/config_uisp.html index e52c81f5..c6d51f80 100644 --- a/src/rust/lqosd/src/node_manager/static2/config_uisp.html +++ b/src/rust/lqosd/src/node_manager/static2/config_uisp.html @@ -39,9 +39,9 @@
- + -
Optional site identifier in UISP.
+
Required only for full topology mode. Leave blank in other modes to let LibreQoS choose the import root.
diff --git a/src/rust/uisp_integration/src/errors.rs b/src/rust/uisp_integration/src/errors.rs index caa7c9eb..5f3af4ae 100644 --- a/src/rust/uisp_integration/src/errors.rs +++ b/src/rust/uisp_integration/src/errors.rs @@ -11,8 +11,8 @@ pub enum UispIntegrationError { UnknownIntegrationStrategy, #[error("Error contacting UISP")] UispConnectError, - #[error("Root site not found")] - NoRootSite, + #[error("Root site not found: {0}")] + NoRootSite(String), #[error("Unknown Site Type")] UnknownSiteType, #[error("CSV Error")] diff --git a/src/rust/uisp_integration/src/strategies/full/root_site.rs b/src/rust/uisp_integration/src/strategies/full/root_site.rs index ee1973c8..38de3506 100644 --- a/src/rust/uisp_integration/src/strategies/full/root_site.rs +++ b/src/rust/uisp_integration/src/strategies/full/root_site.rs @@ -23,7 +23,7 @@ pub fn find_root_site( if !sites.iter().any(|s| s.name == root_site_name) { error!("Site {root_site_name} (from /etc/lqos.conf) not found in the UISP sites list"); - return Err(UispIntegrationError::NoRootSite); + return Err(UispIntegrationError::NoRootSite(root_site_name)); } else { info!("{root_site_name} found in the sites list."); } @@ -45,7 +45,9 @@ fn handle_multiple_internet_connected_sites( if candidates.is_empty() { error!("Unable to find a root site in the sites/data-links."); - return Err(UispIntegrationError::NoRootSite); + return Err(UispIntegrationError::NoRootSite( + "no Internet-connected UISP sites were found".to_string(), + )); } else if candidates.len() == 1 { info!( "Found only one site with an Internet connection: {root_site_name}, using it as root" @@ -81,7 +83,9 @@ pub fn set_root_site(sites: &mut [UispSite], root_site: &str) -> Result<(), Uisp .count(); if number_of_roots > 1 { error!("More than one root present in the tree! That's not going to work. Bailing."); - return Err(UispIntegrationError::NoRootSite); + return Err(UispIntegrationError::NoRootSite( + "more than one root site was tagged".to_string(), + )); } else { info!("Single root tagged in the tree"); } @@ -123,7 +127,10 @@ mod test { let data_links = vec![]; let result = find_root_site(&cfg, &mut sites, &data_links); assert!(result.is_err()); - assert_eq!(result.unwrap_err(), UispIntegrationError::NoRootSite); + assert_eq!( + result.unwrap_err(), + UispIntegrationError::NoRootSite("TEST".to_string()) + ); } #[test] diff --git a/src/rust/uisp_integration/src/strategies/full/tree_walk.rs b/src/rust/uisp_integration/src/strategies/full/tree_walk.rs index aab7965f..2ee5ab1f 100644 --- a/src/rust/uisp_integration/src/strategies/full/tree_walk.rs +++ b/src/rust/uisp_integration/src/strategies/full/tree_walk.rs @@ -22,7 +22,7 @@ pub fn walk_tree_for_routing( // Make sure we know where the root is let Some(root_idx) = sites.iter().position(|s| s.name == root_site) else { tracing::error!("Unable to build a path-weights graph because I can't find the root node"); - return Err(UispIntegrationError::NoRootSite); + return Err(UispIntegrationError::NoRootSite(root_site.to_string())); }; // Now we iterate through every node that ISN'T the root diff --git a/src/rust/uisp_integration/src/strategies/full2.rs b/src/rust/uisp_integration/src/strategies/full2.rs index 8d78d143..63b2b6a6 100644 --- a/src/rust/uisp_integration/src/strategies/full2.rs +++ b/src/rust/uisp_integration/src/strategies/full2.rs @@ -40,6 +40,8 @@ use std::time::Instant; use tracing::{debug, info, warn}; type GraphType = petgraph::Graph; +const GENERATED_INTERNET_ROOT_NAME: &str = "INSERTED_INTERNET"; +const GENERATED_INTERNET_ROOT_ID: &str = "ROOT-001"; #[derive(Clone, Debug)] struct LegacyShapedDevice { @@ -152,9 +154,145 @@ fn anchor_for_site_ap( }) } +#[derive(Debug, PartialEq, Eq)] +enum ResolvedRootSite { + Existing(String), + GeneratedInternet, +} + +impl ResolvedRootSite { + fn name(&self) -> String { + match self { + ResolvedRootSite::Existing(name) => name.clone(), + ResolvedRootSite::GeneratedInternet => GENERATED_INTERNET_ROOT_NAME.to_string(), + } + } +} + +fn generated_internet_root() -> GraphMapping { + GraphMapping::Root { + name: GENERATED_INTERNET_ROOT_NAME.to_string(), + id: GENERATED_INTERNET_ROOT_ID.to_string(), + latitude: None, + longitude: None, + } +} + +fn resolve_root_site_from_names( + configured_site: &str, + site_names: &[String], + internet_site_candidates: &[String], + require_configured_root_site: bool, +) -> Result { + let configured_site = configured_site.trim(); + if !configured_site.is_empty() { + if site_names.iter().any(|site_name| site_name == configured_site) { + info!("Using root UISP site from /etc/lqos.conf: {configured_site}"); + return Ok(ResolvedRootSite::Existing(configured_site.to_string())); + } + + let mut sorted_site_names = site_names.to_vec(); + sorted_site_names.sort_unstable(); + let sample_sites = sorted_site_names + .iter() + .take(10) + .cloned() + .collect::>() + .join(", "); + if require_configured_root_site { + tracing::error!( + "Configured UISP root site '{configured_site}' was not found. Available non-client site sample: {sample_sites}" + ); + return Err(UispIntegrationError::NoRootSite(configured_site.to_string())); + } + + warn!( + "Configured UISP root site '{configured_site}' was not found. Non-full topology mode will auto-detect a root instead." + ); + } else { + warn!("Root UISP site is blank; attempting to auto-detect an import root."); + } + + let mut candidates = internet_site_candidates + .iter() + .filter(|candidate| site_names.iter().any(|site_name| site_name == *candidate)) + .cloned() + .collect::>(); + candidates.sort_unstable(); + candidates.dedup(); + + match candidates.len() { + 0 => { + tracing::error!("Unable to auto-detect a UISP root site from Internet data-links."); + Err(UispIntegrationError::NoRootSite( + "no Internet-connected UISP sites were found".to_string(), + )) + } + 1 => { + info!( + "Auto-detected root UISP site from Internet data-links: {}", + candidates[0] + ); + Ok(ResolvedRootSite::Existing(candidates.remove(0))) + } + _ => { + warn!( + "Multiple Internet-connected UISP sites detected. Creating a generated Internet root." + ); + Ok(ResolvedRootSite::GeneratedInternet) + } + } +} + +fn resolve_root_site( + config: &Config, + uisp_data: &UispData, + require_configured_root_site: bool, +) -> Result { + let mut site_names = uisp_data + .sites_raw + .iter() + .filter(|site| !site.is_client_site()) + .map(|site| site.name_or_blank()) + .collect::>(); + site_names.sort_unstable(); + site_names.dedup(); + + let mut internet_site_ids = uisp_data + .data_links_raw + .iter() + .filter(|link| !link.can_delete) + .filter_map(|link| { + link.from + .site + .as_ref() + .map(|site| site.identification.id.clone()) + }) + .collect::>(); + internet_site_ids.sort_unstable(); + internet_site_ids.dedup(); + + let mut internet_site_candidates = uisp_data + .sites_raw + .iter() + .filter(|site| internet_site_ids.iter().any(|site_id| site_id == &site.id)) + .map(|site| site.name_or_blank()) + .collect::>(); + internet_site_candidates.sort_unstable(); + internet_site_candidates.dedup(); + + resolve_root_site_from_names( + &config.uisp_integration.site, + &site_names, + &internet_site_candidates, + require_configured_root_site, + ) +} + pub async fn build_imported_full2_bundle( config: Arc, ip_ranges: IpRanges, + require_configured_root_site: bool, ) -> Result { let build_started = Instant::now(); let ethernet_policy = EthernetPortLimitPolicy::from(&config.integration_common); @@ -170,7 +308,9 @@ pub async fn build_imported_full2_bundle( let mut graph = GraphType::new(); // Find the root - let root_site_name = config.uisp_integration.site.clone(); + let resolved_root_site = + resolve_root_site(&config, &uisp_data, require_configured_root_site)?; + let root_site_name = resolved_root_site.name(); // Add all sites to the graph let graph_build_started = Instant::now(); @@ -183,7 +323,14 @@ pub async fn build_imported_full2_bundle( &mut site_map, &mut root_idx, ); - let root_idx = root_idx.expect("Root site not found"); + let root_idx = match (root_idx, resolved_root_site) { + (Some(root_idx), _) => root_idx, + (None, ResolvedRootSite::GeneratedInternet) => graph.add_node(generated_internet_root()), + (None, ResolvedRootSite::Existing(root_site_name)) => { + tracing::error!("Root UISP site '{root_site_name}' was not added to the graph."); + return Err(UispIntegrationError::NoRootSite(root_site_name)); + } + }; let site_graph_elapsed_ms = graph_build_started.elapsed().as_millis(); // Iterate all UISP devices and if their parent site is in the graph, add them @@ -3090,6 +3237,50 @@ mod tests { .expect("expected node to exist") } + #[test] + fn root_resolution_accepts_configured_site() { + let sites = vec!["Main".to_string(), "Backup".to_string()]; + let internet_candidates = vec!["Backup".to_string()]; + + let root = + resolve_root_site_from_names("Main", &sites, &internet_candidates, true).unwrap(); + + assert_eq!(root, ResolvedRootSite::Existing("Main".to_string())); + } + + #[test] + fn root_resolution_rejects_bad_configured_site_for_full_mode() { + let sites = vec!["Main".to_string(), "Backup".to_string()]; + let internet_candidates = vec!["Backup".to_string()]; + + let error = + resolve_root_site_from_names("Old Root", &sites, &internet_candidates, true) + .unwrap_err(); + + assert_eq!(error, UispIntegrationError::NoRootSite("Old Root".to_string())); + } + + #[test] + fn root_resolution_auto_detects_for_non_full_mode() { + let sites = vec!["Main".to_string(), "Backup".to_string()]; + let internet_candidates = vec!["Backup".to_string()]; + + let root = + resolve_root_site_from_names("Old Root", &sites, &internet_candidates, false).unwrap(); + + assert_eq!(root, ResolvedRootSite::Existing("Backup".to_string())); + } + + #[test] + fn root_resolution_uses_generated_root_for_multiple_internet_sites() { + let sites = vec!["Main".to_string(), "Backup".to_string()]; + let internet_candidates = vec!["Main".to_string(), "Backup".to_string()]; + + let root = resolve_root_site_from_names("", &sites, &internet_candidates, false).unwrap(); + + assert_eq!(root, ResolvedRootSite::GeneratedInternet); + } + #[test] fn squash_candidate_collection_is_deterministic() { let config = Arc::new(Config::default()); diff --git a/src/rust/uisp_integration/src/strategies/mod.rs b/src/rust/uisp_integration/src/strategies/mod.rs index 78a62b98..fd1da0bd 100644 --- a/src/rust/uisp_integration/src/strategies/mod.rs +++ b/src/rust/uisp_integration/src/strategies/mod.rs @@ -79,7 +79,11 @@ pub async fn build_with_strategy( blackboard(BlackboardSystem::System, "UISP", strategy.as_str()).await; let mode = compile_mode_for_strategy(&strategy)?; info!("Strategy selected: {strategy}"); - let imported = full2::build_imported_full2_bundle(config.clone(), ip_ranges).await?; + let require_configured_root_site = + matches!(mode, TopologyCompileMode::Full | TopologyCompileMode::Full2); + let imported = + full2::build_imported_full2_bundle(config.clone(), ip_ranges, require_configured_root_site) + .await?; let topology_import = TopologyImportFile::from_imported_bundle(&imported, strategy.clone()); let compiled = compile_topology(imported, mode).map_err(|e| { error!("Unable to compile UISP topology for mode '{strategy}': {e:?}"); diff --git a/src/test_libreqos_shaping_inputs.py b/src/test_libreqos_shaping_inputs.py index 57531a3c..afd303c5 100644 --- a/src/test_libreqos_shaping_inputs.py +++ b/src/test_libreqos_shaping_inputs.py @@ -111,6 +111,39 @@ class TestLibreQoSShapingInputs(unittest.TestCase): ) self.assertEqual(candidates, ["Generated_PN_2"]) + def test_canonical_shaping_parent_ignores_logical_anchor_for_generated_parent(self): + circuit = { + "ParentNode": "Generated_PN_1", + "effectiveParentNodeName": "Generated_PN_1", + "ParentNodeID": "uisp:device:glenn-s1", + "effectiveParentNodeID": "uisp:device:glenn-s1", + "logicalParentNode": "glenn-s1.streamitnet.com", + "parentResolutionSource": "topology_anchor", + } + + parent_name, parent_id = LibreQoS._normalize_circuit_shaping_parent(circuit) + + self.assertEqual(parent_name, "Generated_PN_1") + self.assertEqual(parent_id, "") + self.assertEqual(circuit["shapingParentNode"], "Generated_PN_1") + self.assertEqual(circuit["shapingParentNodeID"], "") + self.assertEqual(circuit["shapingParentKey"], "name:Generated_PN_1") + + def test_canonical_shaping_parent_drops_mismatched_parent_id(self): + circuit = { + "ParentNode": "Physical_AP", + "ParentNodeID": "uisp:device:logical-ap", + } + + parent_name, parent_id = LibreQoS._normalize_circuit_shaping_parent( + circuit, + {"uisp:device:logical-ap": "Logical_AP"}, + ) + + self.assertEqual(parent_name, "Physical_AP") + self.assertEqual(parent_id, "") + self.assertEqual(circuit["shapingParentKey"], "name:Physical_AP") + def test_validate_planned_circuit_attachment_rejects_major_mismatch(self): with self.assertRaisesRegex(ValueError, "Planned circuit class majors do not match"): LibreQoS._validate_planned_circuit_attachment( -- knotmirror 0.0.1 From 4d9e27798f67af5e2f8293d93e1a8f9adddb6587 Mon Sep 17 00:00:00 2001 From: rchac Date: Thu, 30 Apr 2026 13:10:00 -0600 Subject: [PATCH 31/51] changes --- src/systemd_hotfix.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/systemd_hotfix.sh b/src/systemd_hotfix.sh index cc5f3c57..1ad9f015 100755 --- a/src/systemd_hotfix.sh +++ b/src/systemd_hotfix.sh @@ -11,7 +11,7 @@ HOTFIX_APT_SOURCE_PATH="${HOTFIX_APT_SOURCE_PATH:-/etc/apt/sources.list.d/libreq HOTFIX_APT_PREFERENCES_PATH="${HOTFIX_APT_PREFERENCES_PATH:-/etc/apt/preferences.d/libreqos-systemd-hotfix}" HOTFIX_APT_PIN_ORIGIN="${HOTFIX_APT_PIN_ORIGIN:-LibreQoS}" HOTFIX_APT_PIN_LABEL="${HOTFIX_APT_PIN_LABEL:-LibreQoS}" -HOTFIX_PACKAGE_VERSION="${HOTFIX_PACKAGE_VERSION:-255.4-1ubuntu8.14+libreqos2}" +HOTFIX_PACKAGE_VERSION="${HOTFIX_PACKAGE_VERSION:-255.4-1ubuntu8.15+libreqos1}" SUPPORTED_UBUNTU_SYSTEMD_VERSION_GLOBS="${SUPPORTED_UBUNTU_SYSTEMD_VERSION_GLOBS:-255.4-1ubuntu8 255.4-1ubuntu8.*}" HOTFIX_MARKER="${HOTFIX_MARKER:-/opt/libreqos/src/.systemd_hotfix_installed}" HOTFIX_SKIP_REBOOT_PROMPT="${HOTFIX_SKIP_REBOOT_PROMPT:-0}" -- knotmirror 0.0.1 From 7e8fe7bd7dbf868ddfa7ba06ba2b83d85baf8d00 Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Thu, 30 Apr 2026 15:18:49 -0500 Subject: [PATCH 32/51] Fix: Bound node manager wait paths --- src/rust/lqos_bus/src/bus/client.rs | 43 ++++ src/rust/lqos_bus/src/bus/mod.rs | 5 +- .../lqos_bus/src/bus/unix_socket_server.rs | 52 +++- src/rust/lqos_bus/src/lib.rs | 2 +- src/rust/lqos_network_devices/src/actor.rs | 124 +++++---- src/rust/lqos_probe/src/lib.rs | 129 ++++++++-- src/rust/lqos_topology/src/runtime.rs | 14 +- .../src/node_manager/local_api/config.rs | 14 +- .../lqosd/src/node_manager/local_api/lts.rs | 34 ++- .../local_api/lts/last_24_hours.rs | 241 +++++++++--------- .../shaper_queries_actor/queries.rs | 37 ++- src/rust/lqosd/src/node_manager/ws.rs | 117 +++++---- .../node_manager/ws/single_user_channels.rs | 93 ++++--- .../ws/single_user_channels/cake_watcher.rs | 10 +- .../ws/single_user_channels/circuit.rs | 3 +- .../single_user_channels/circuit_metrics.rs | 5 +- .../ws/single_user_channels/ping_monitor.rs | 39 +-- .../tree_attached_circuits.rs | 5 +- .../node_manager/ws/ticker/network_tree.rs | 69 +++-- 19 files changed, 673 insertions(+), 363 deletions(-) diff --git a/src/rust/lqos_bus/src/bus/client.rs b/src/rust/lqos_bus/src/bus/client.rs index 8320035d..a2cb7e4a 100644 --- a/src/rust/lqos_bus/src/bus/client.rs +++ b/src/rust/lqos_bus/src/bus/client.rs @@ -2,9 +2,11 @@ // SPDX-License-Identifier: AGPL-3.0-or-later WITH LicenseRef-LibreQoS-Exception use crate::{BUS_SOCKET_PATH, BusReply, BusRequest, BusResponse, BusSession, bus::BusClientError}; +use std::time::Duration; use tokio::{ io::{AsyncReadExt, AsyncWriteExt}, net::UnixStream, + time::timeout, }; use tracing::error; @@ -50,6 +52,16 @@ impl LibreqosBusClient { }) } + /// Creates a new `LibreqosBusClient`, failing if connection setup exceeds + /// `request_timeout`. + /// + /// Side effects: opens a Unix socket connection to the local `lqosd` bus. + pub async fn new_with_timeout(request_timeout: Duration) -> Result { + timeout(request_timeout, Self::new()) + .await + .map_err(|_| BusClientError::TimedOut)? + } + /// Sends a request to the bus and waits for a response. /// /// ## Arguments @@ -91,6 +103,21 @@ impl LibreqosBusClient { } Ok(response.responses) } + + /// Sends a request to the bus and waits for a bounded response. + /// + /// Side effects: writes the request to the connected Unix socket. If this + /// call times out, discard the client because the stream may later receive + /// the timed-out reply. + pub async fn request_with_timeout( + &mut self, + requests: Vec, + request_timeout: Duration, + ) -> Result, BusClientError> { + timeout(request_timeout, self.request(requests)) + .await + .map_err(|_| BusClientError::TimedOut)? + } } /// Convenient wrapper for accessing the bus, for a single request-response cycle. This @@ -108,3 +135,19 @@ pub async fn bus_request(requests: Vec) -> Result, }; client.request(requests).await } + +/// Convenient wrapper for a single bus request with an end-to-end timeout. +/// +/// Side effects: opens a Unix socket connection, sends the request, and closes +/// the connection when the client is dropped. +pub async fn bus_request_with_timeout( + requests: Vec, + request_timeout: Duration, +) -> Result, BusClientError> { + timeout(request_timeout, async move { + let mut client = LibreqosBusClient::new().await?; + client.request(requests).await + }) + .await + .map_err(|_| BusClientError::TimedOut)? +} diff --git a/src/rust/lqos_bus/src/bus/mod.rs b/src/rust/lqos_bus/src/bus/mod.rs index efd88fe9..91f01315 100644 --- a/src/rust/lqos_bus/src/bus/mod.rs +++ b/src/rust/lqos_bus/src/bus/mod.rs @@ -9,7 +9,7 @@ mod request; pub mod response; mod session; mod unix_socket_server; -pub use client::{LibreqosBusClient, bus_request}; +pub use client::{LibreqosBusClient, bus_request, bus_request_with_timeout}; pub use queue_data::*; pub use reply::BusReply; pub use request::{ @@ -55,6 +55,9 @@ pub enum BusClientError { /// Reading the reply from the socket failed. #[error("Cannot read from socket")] StreamReadError, + /// The socket operation exceeded the caller's deadline. + #[error("Timed out waiting for bus response")] + TimedOut, /// The socket connection is no longer usable. #[error("Stream is no longer connected")] StreamNotConnected, diff --git a/src/rust/lqos_bus/src/bus/unix_socket_server.rs b/src/rust/lqos_bus/src/bus/unix_socket_server.rs index 59b89e3f..ddfae309 100644 --- a/src/rust/lqos_bus/src/bus/unix_socket_server.rs +++ b/src/rust/lqos_bus/src/bus/unix_socket_server.rs @@ -5,21 +5,63 @@ use crate::{ BUS_SOCKET_PATH, BusReply, BusRequest, BusResponse, bus::client::{MAGIC_NUMBER, MAGIC_RESPONSE}, }; -use std::{ffi::CString, fs::remove_file}; +use std::{ffi::CString, fs::remove_file, time::Duration}; use thiserror::Error; use tokio::{ io::{AsyncReadExt, AsyncWriteExt}, net::UnixListener, + task::spawn_blocking, + time::timeout, }; use tracing::{debug, error, info, warn}; use super::BUS_SOCKET_DIRECTORY; use super::protocol::{decode_session_cbor, encode_reply_cbor, read_frame, write_frame}; +const BUS_HANDLER_TIMEOUT: Duration = Duration::from_secs(30); + fn dropped_reply_response_count(reply: &BusReply) -> usize { reply.responses.len() } +fn timeout_reply(request_count: usize) -> BusReply { + BusReply { + responses: (0..request_count) + .map(|_| BusResponse::Fail("Bus request handler timed out".to_string())) + .collect(), + } +} + +async fn handle_requests_with_deadline( + handle_bus_requests: fn(&[BusRequest], &mut Vec), + requests: Vec, +) -> BusReply { + let request_count = requests.len(); + let handler = spawn_blocking(move || { + let mut response = BusReply { + responses: Vec::with_capacity(request_count), + }; + handle_bus_requests(&requests, &mut response.responses); + response + }); + + match timeout(BUS_HANDLER_TIMEOUT, handler).await { + Ok(Ok(response)) => response, + Ok(Err(err)) => { + warn!("Bus request handler task failed: {err}"); + BusReply { + responses: (0..request_count) + .map(|_| BusResponse::Fail("Bus request handler failed".to_string())) + .collect(), + } + } + Err(_) => { + warn!("Bus request handler timed out after {BUS_HANDLER_TIMEOUT:?}"); + timeout_reply(request_count) + } + } +} + /// Implements a Tokio-friendly server using Unix Sockets and the bus protocol. /// Requests are handled and then forwarded to the handler. pub struct UnixSocketServer {} @@ -113,8 +155,7 @@ impl UnixSocketServer { ret = bus_rx.recv() => { // We received a channel-based message if let Some((reply_channel, msg)) = ret { - let mut response = BusReply { responses: Vec::with_capacity(8) }; - handle_bus_requests(&[msg], &mut response.responses); + let response = handle_requests_with_deadline(handle_bus_requests, vec![msg]).await; if let Err(reply) = reply_channel.send(response) { warn!( dropped_response_count = dropped_reply_response_count(&reply), @@ -182,8 +223,9 @@ impl UnixSocketServer { debug!("Received request: {:?}", request); // Handle the request and build the response - let mut response = BusReply { responses: Vec::with_capacity(8) }; - handle_bus_requests(&request.requests, &mut response.responses); + let response = + handle_requests_with_deadline(handle_bus_requests, request.requests) + .await; // Encode the response let Ok(encoded_response) = encode_reply_cbor(&response) else { diff --git a/src/rust/lqos_bus/src/lib.rs b/src/rust/lqos_bus/src/lib.rs index 48f9bd08..a8d0e5f5 100644 --- a/src/rust/lqos_bus/src/lib.rs +++ b/src/rust/lqos_bus/src/lib.rs @@ -37,7 +37,7 @@ pub use bus::{ BUS_SOCKET_PATH, BakeryCapacityReportInterface, BlackboardSystem, BusClientError, BusReply, BusRequest, BusResponse, BusSession, CakeDiffTinTransit, CakeDiffTransit, CakeTransit, LibreqosBusClient, QueueStoreTransit, SchedulerProgressReport, TopFlowType, UnixSocketServer, - UrgentSeverity, UrgentSource, bus_request, + UrgentSeverity, UrgentSource, bus_request, bus_request_with_timeout, }; pub use tc_handle::TcHandle; diff --git a/src/rust/lqos_network_devices/src/actor.rs b/src/rust/lqos_network_devices/src/actor.rs index 6b6f3069..b349e477 100644 --- a/src/rust/lqos_network_devices/src/actor.rs +++ b/src/rust/lqos_network_devices/src/actor.rs @@ -5,18 +5,18 @@ use crate::dynamic_store::{load_dynamic_circuits_from_disk, persist_dynamic_circ use crate::state; use crate::{DaemonHooks, ShapedDevicesCatalog, load_network_json, load_shaped_devices}; use anyhow::{Context, Result, anyhow}; -use crossbeam_channel::{Receiver, Sender}; +use crossbeam_channel::{Receiver, RecvTimeoutError, SendTimeoutError, Sender, bounded}; use ip_network_table::IpNetworkTable; use once_cell::sync::OnceCell; use std::collections::HashSet; use std::net::IpAddr; use std::sync::Arc; use std::time::Duration; -use tokio::sync::oneshot; use tracing::{debug, error, warn}; const RELOAD_RETRY_DELAY_MS: u64 = 500; const RELOAD_ATTEMPTS: usize = 2; +const ACTOR_COMMAND_TIMEOUT: Duration = Duration::from_secs(10); const DYNAMIC_CIRCUITS_MAINTENANCE_TICK_SECONDS: u64 = 60; const MAX_UNKNOWN_IP_PROMOTIONS_PER_OBSERVATION: usize = 32; @@ -44,41 +44,67 @@ fn sender() -> Result> { .ok_or_else(|| anyhow!("lqos_network_devices runtime actor is not running")) } +fn send_actor_command(command: NetworkDevicesCommand, operation: &str) -> Result<()> { + sender()? + .send_timeout(command, ACTOR_COMMAND_TIMEOUT) + .map_err(|err| match err { + SendTimeoutError::Timeout(_) => { + anyhow!("{operation} timed out while queueing lqos_network_devices actor command") + } + SendTimeoutError::Disconnected(_) => { + anyhow!("{operation} failed because lqos_network_devices actor stopped") + } + }) +} + +fn receive_actor_reply(reply_rx: Receiver>, operation: &str) -> Result { + match reply_rx.recv_timeout(ACTOR_COMMAND_TIMEOUT) { + Ok(result) => result, + Err(RecvTimeoutError::Timeout) => { + Err(anyhow!("{operation} timed out waiting for actor reply")) + } + Err(RecvTimeoutError::Disconnected) => Err(anyhow!("{operation} reply channel closed")), + } +} + pub(crate) fn request_reload_shaped_devices(reason: &str) -> Result<()> { - let (reply_tx, reply_rx) = oneshot::channel(); - sender()?.send(NetworkDevicesCommand::ReloadShapedDevices { - reason: reason.to_string(), - reply: reply_tx, - })?; - reply_rx - .blocking_recv() - .map_err(|_| anyhow!("ShapedDevices reload reply channel closed"))? + let (reply_tx, reply_rx) = bounded(1); + send_actor_command( + NetworkDevicesCommand::ReloadShapedDevices { + reason: reason.to_string(), + reply: reply_tx, + }, + "ShapedDevices reload", + )?; + receive_actor_reply(reply_rx, "ShapedDevices reload") } pub(crate) fn request_reload_network_json(reason: &str) -> Result<()> { - let (reply_tx, reply_rx) = oneshot::channel(); - sender()?.send(NetworkDevicesCommand::ReloadNetworkJson { - reason: reason.to_string(), - reply: reply_tx, - })?; - reply_rx - .blocking_recv() - .map_err(|_| anyhow!("NetworkJson reload reply channel closed"))? + let (reply_tx, reply_rx) = bounded(1); + send_actor_command( + NetworkDevicesCommand::ReloadNetworkJson { + reason: reason.to_string(), + reply: reply_tx, + }, + "NetworkJson reload", + )?; + receive_actor_reply(reply_rx, "NetworkJson reload") } pub(crate) fn apply_shaped_devices_snapshot( reason: &str, shaped: lqos_config::ConfigShapedDevices, ) -> Result<()> { - let (reply_tx, reply_rx) = oneshot::channel(); - sender()?.send(NetworkDevicesCommand::ApplyShapedDevicesSnapshot { - reason: reason.to_string(), - shaped: Box::new(shaped), - reply: reply_tx, - })?; - reply_rx - .blocking_recv() - .map_err(|_| anyhow!("Apply shaped devices reply channel closed"))? + let (reply_tx, reply_rx) = bounded(1); + send_actor_command( + NetworkDevicesCommand::ApplyShapedDevicesSnapshot { + reason: reason.to_string(), + shaped: Box::new(shaped), + reply: reply_tx, + }, + "Apply shaped devices", + )?; + receive_actor_reply(reply_rx, "Apply shaped devices") } pub(crate) fn report_observations(observations: &[CircuitObservation]) { @@ -95,51 +121,53 @@ pub(crate) fn report_observations(observations: &[CircuitObservation]) { } pub(crate) fn upsert_dynamic_circuit(shaped_device: lqos_config::ShapedDevice) -> Result<()> { - let (reply_tx, reply_rx) = oneshot::channel(); - sender()?.send(NetworkDevicesCommand::UpsertDynamicCircuit { - shaped_device: Box::new(shaped_device), - reply: reply_tx, - })?; - reply_rx - .blocking_recv() - .map_err(|_| anyhow!("Upsert dynamic circuit reply channel closed"))? + let (reply_tx, reply_rx) = bounded(1); + send_actor_command( + NetworkDevicesCommand::UpsertDynamicCircuit { + shaped_device: Box::new(shaped_device), + reply: reply_tx, + }, + "Upsert dynamic circuit", + )?; + receive_actor_reply(reply_rx, "Upsert dynamic circuit") } pub(crate) fn remove_dynamic_circuit(circuit_id: &str) -> Result { - let (reply_tx, reply_rx) = oneshot::channel(); - sender()?.send(NetworkDevicesCommand::RemoveDynamicCircuit { - circuit_id: circuit_id.to_string(), - reply: reply_tx, - })?; - reply_rx - .blocking_recv() - .map_err(|_| anyhow!("Remove dynamic circuit reply channel closed"))? + let (reply_tx, reply_rx) = bounded(1); + send_actor_command( + NetworkDevicesCommand::RemoveDynamicCircuit { + circuit_id: circuit_id.to_string(), + reply: reply_tx, + }, + "Remove dynamic circuit", + )?; + receive_actor_reply(reply_rx, "Remove dynamic circuit") } enum NetworkDevicesCommand { ReloadShapedDevices { reason: String, - reply: oneshot::Sender>, + reply: Sender>, }, ReloadNetworkJson { reason: String, - reply: oneshot::Sender>, + reply: Sender>, }, ApplyShapedDevicesSnapshot { reason: String, shaped: Box, - reply: oneshot::Sender>, + reply: Sender>, }, ReportObservations { observations: Vec, }, UpsertDynamicCircuit { shaped_device: Box, - reply: oneshot::Sender>, + reply: Sender>, }, RemoveDynamicCircuit { circuit_id: String, - reply: oneshot::Sender>, + reply: Sender>, }, } diff --git a/src/rust/lqos_probe/src/lib.rs b/src/rust/lqos_probe/src/lib.rs index 03c63b92..936cc67c 100644 --- a/src/rust/lqos_probe/src/lib.rs +++ b/src/rust/lqos_probe/src/lib.rs @@ -15,8 +15,14 @@ use std::time::{Duration, SystemTime, UNIX_EPOCH}; use surge_ping::{Client, Config as PingConfig, ICMP, IcmpPacket, PingIdentifier, PingSequence}; use thiserror::Error; use tokio::sync::{Semaphore, mpsc, oneshot}; +use tokio::time::timeout; use tracing::warn; +const PROBE_DNS_RESOLUTION_TIMEOUT: Duration = Duration::from_secs(2); +const PROBE_WORKER_GRACE: Duration = Duration::from_secs(1); +const PROBE_MANAGER_REPLY_GRACE: Duration = Duration::from_secs(5); +const PROBE_BATCH_CONCURRENCY_ESTIMATE: usize = 256; + /// Logical consumer class for a probe request. #[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, Serialize, Allocative)] pub enum ProbeClass { @@ -135,18 +141,23 @@ impl ProbeClient { if requests.is_empty() { return Ok(Vec::new()); } + let wait_timeout = probe_batch_wait_timeout(&requests); let (reply_tx, reply_rx) = oneshot::channel(); - self.tx - .send(ProbeCommand::ProbeBatch { - requests, - max_age, - reply: reply_tx, - }) - .await - .map_err(|_| ProbeClientError::ManagerUnavailable)?; - reply_rx - .await - .map_err(|_| ProbeClientError::ManagerUnavailable) + timeout(wait_timeout, async { + self.tx + .send(ProbeCommand::ProbeBatch { + requests, + max_age, + reply: reply_tx, + }) + .await + .map_err(|_| ProbeClientError::ManagerUnavailable)?; + reply_rx + .await + .map_err(|_| ProbeClientError::ManagerUnavailable) + }) + .await + .map_err(|_| ProbeClientError::TimedOut)? } /// Probes a batch of targets for reachability. @@ -192,6 +203,9 @@ pub enum ProbeClientError { /// The manager returned no observations for the request. #[error("shared probe manager returned no observations")] EmptyResponse, + /// The manager did not answer before the caller's deadline. + #[error("shared probe manager timed out")] + TimedOut, } /// Background shared probe manager. @@ -213,6 +227,27 @@ impl ProbeManager { } } +fn probe_worker_timeout(request_timeout: Duration) -> Duration { + PROBE_DNS_RESOLUTION_TIMEOUT + .saturating_add(request_timeout) + .saturating_add(PROBE_WORKER_GRACE) +} + +fn probe_batch_wait_timeout(requests: &[ProbeRequest]) -> Duration { + let worker_timeout = requests + .iter() + .map(|request| probe_worker_timeout(request.timeout)) + .max() + .unwrap_or(PROBE_MANAGER_REPLY_GRACE); + let wave_count = requests + .len() + .max(1) + .div_ceil(PROBE_BATCH_CONCURRENCY_ESTIMATE) as u32; + worker_timeout + .saturating_mul(wave_count) + .saturating_add(PROBE_MANAGER_REPLY_GRACE) +} + #[derive(Clone, Debug)] struct ProbeCacheEntry { normalized_target: String, @@ -313,7 +348,23 @@ impl ProbeManagerState { let semaphore = self.semaphore.clone(); join_set.spawn(async move { let _permit = semaphore.acquire_owned().await.ok(); - let observation = execute_probe(&request, &key.normalized_target).await; + let observation = match timeout( + probe_worker_timeout(request.timeout), + execute_probe(&request, &key.normalized_target), + ) + .await + { + Ok(observation) => observation, + Err(_) => ProbeCacheEntry { + normalized_target: key.normalized_target.clone(), + resolved_ip: None, + kind: request.kind, + observed_at_unix_ms: now_unix_ms(), + reachable: false, + rtt_ms: None, + error: Some("probe worker timed out".to_string()), + }, + }; (key, observation) }); } @@ -529,9 +580,15 @@ async fn resolve_target(normalized_target: &str) -> Result<(IpAddr, String), Str return Ok((ip, ip.to_string())); } - let mut addrs = tokio::net::lookup_host((normalized_target, 80)) - .await - .map_err(|err| format!("unable to resolve target '{normalized_target}': {err}"))?; + let lookup = timeout( + PROBE_DNS_RESOLUTION_TIMEOUT, + tokio::net::lookup_host((normalized_target, 80)), + ) + .await + .map_err(|_| format!("timed out resolving target '{normalized_target}'"))?; + + let mut addrs = + lookup.map_err(|err| format!("unable to resolve target '{normalized_target}': {err}"))?; let Some(addr) = addrs.next() else { return Err(format!("unable to resolve target '{normalized_target}'")); }; @@ -540,7 +597,11 @@ async fn resolve_target(normalized_target: &str) -> Result<(IpAddr, String), Str #[cfg(test)] mod tests { - use super::{ProbeKind, ProbeRequest, duration_to_millis, normalize_target}; + use super::{ + PROBE_DNS_RESOLUTION_TIMEOUT, PROBE_MANAGER_REPLY_GRACE, PROBE_WORKER_GRACE, ProbeKind, + ProbeRequest, duration_to_millis, normalize_target, probe_batch_wait_timeout, + probe_worker_timeout, + }; use std::time::Duration; #[test] @@ -576,4 +637,40 @@ mod tests { assert_eq!(reachability.kind, ProbeKind::Reachability); assert_eq!(rtt.kind, ProbeKind::RoundTripTime); } + + #[test] + fn probe_deadlines_include_dns_probe_and_reply_grace() { + let request = ProbeRequest::reachability( + "example.com", + super::ProbeClass::UiMonitor, + Duration::from_millis(750), + ); + assert_eq!( + probe_worker_timeout(request.timeout), + PROBE_DNS_RESOLUTION_TIMEOUT + Duration::from_millis(750) + PROBE_WORKER_GRACE + ); + assert_eq!( + probe_batch_wait_timeout(&[request]), + PROBE_DNS_RESOLUTION_TIMEOUT + + Duration::from_millis(750) + + PROBE_WORKER_GRACE + + PROBE_MANAGER_REPLY_GRACE + ); + } + + #[test] + fn probe_batch_deadline_scales_for_multiple_probe_waves() { + let requests = vec![ + ProbeRequest::reachability( + "example.com", + super::ProbeClass::UiMonitor, + Duration::from_secs(1), + ); + 257 + ]; + assert_eq!( + probe_batch_wait_timeout(&requests), + probe_worker_timeout(Duration::from_secs(1)) * 2 + PROBE_MANAGER_REPLY_GRACE + ); + } } diff --git a/src/rust/lqos_topology/src/runtime.rs b/src/rust/lqos_topology/src/runtime.rs index 1a8b763d..103f179f 100644 --- a/src/rust/lqos_topology/src/runtime.rs +++ b/src/rust/lqos_topology/src/runtime.rs @@ -1,5 +1,5 @@ use anyhow::{Context, Result}; -use lqos_bus::{BusRequest, BusResponse, bus_request}; +use lqos_bus::{BusRequest, BusResponse, bus_request_with_timeout}; use lqos_config::{ TopologyAttachmentEndpointStatus, TopologyAttachmentHealthEntry, TopologyAttachmentHealthStateFile, TopologyAttachmentHealthStatus, @@ -21,6 +21,7 @@ use crate::{ }; const TOPOLOGY_PROBE_MAX_AGE_MS: u64 = 250; +const TOPOLOGY_PROBE_BUS_TIMEOUT: Duration = Duration::from_secs(8); fn now_unix() -> Option { SystemTime::now() @@ -120,10 +121,13 @@ async fn probe_specs( return Ok(HashMap::new()); } - let responses = bus_request(vec![BusRequest::ProbeBatch { - requests: probe_requests, - max_age_ms: TOPOLOGY_PROBE_MAX_AGE_MS, - }]) + let responses = bus_request_with_timeout( + vec![BusRequest::ProbeBatch { + requests: probe_requests, + max_age_ms: TOPOLOGY_PROBE_MAX_AGE_MS, + }], + TOPOLOGY_PROBE_BUS_TIMEOUT, + ) .await .map_err(|err| anyhow::anyhow!("unable to query shared probe manager: {err}"))?; let Some(response) = responses.into_iter().next() else { diff --git a/src/rust/lqosd/src/node_manager/local_api/config.rs b/src/rust/lqosd/src/node_manager/local_api/config.rs index a024764b..f8d7f9da 100644 --- a/src/rust/lqosd/src/node_manager/local_api/config.rs +++ b/src/rust/lqosd/src/node_manager/local_api/config.rs @@ -7,7 +7,7 @@ use axum::body::Bytes; use axum::http::StatusCode; use axum::http::header; use default_net::get_interfaces; -use lqos_bus::{BusRequest, BusResponse, bus_request}; +use lqos_bus::{BusRequest, BusResponse, bus_request_with_timeout}; use lqos_config::{ Config, ConfigShapedDevices, NetworkJson, ShapedDevice, UserRole, WebUser, WebUsers, }; @@ -17,13 +17,14 @@ use serde_json::Value; use std::collections::{BTreeMap, BTreeSet, HashSet}; use std::io::{Cursor, ErrorKind, Write}; use std::path::{Path, PathBuf}; -use std::time::{SystemTime, UNIX_EPOCH}; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; const COBRAND_FILE_NAME: &str = "cobrand.png"; const COBRAND_DISPLAY_HEIGHT_PX: u64 = 48; const COBRAND_MAX_DISPLAY_WIDTH_PX: u64 = 176; const COBRAND_MAX_DECODE_BYTES: usize = 64 * 1024 * 1024; const PNG_SIGNATURE: &[u8; 8] = b"\x89PNG\r\n\x1a\n"; +const CONFIG_BUS_REQUEST_TIMEOUT: Duration = Duration::from_secs(10); #[derive(Clone, Copy, Debug, Eq, PartialEq)] enum CobrandUploadValidationError { @@ -802,9 +803,12 @@ pub async fn update_lqosd_config_data( let existing = lqos_config::load_config().map_err(|_| "Unable to load the current config".to_string())?; apply_secret_updates(existing.as_ref(), &mut config, &clear_secrets); - let mut responses = bus_request(vec![BusRequest::UpdateLqosdConfig(Box::new(config))]) - .await - .map_err(|err| format!("Unable to update config: {err}"))?; + let mut responses = bus_request_with_timeout( + vec![BusRequest::UpdateLqosdConfig(Box::new(config))], + CONFIG_BUS_REQUEST_TIMEOUT, + ) + .await + .map_err(|err| format!("Unable to update config: {err}"))?; match responses.pop() { Some(BusResponse::Ack) => Ok(()), diff --git a/src/rust/lqosd/src/node_manager/local_api/lts.rs b/src/rust/lqosd/src/node_manager/local_api/lts.rs index baca3ceb..dbb02519 100644 --- a/src/rust/lqosd/src/node_manager/local_api/lts.rs +++ b/src/rust/lqosd/src/node_manager/local_api/lts.rs @@ -7,7 +7,7 @@ use crate::node_manager::local_api::circuit_count; use axum::http::StatusCode; pub use last_24_hours::*; use lqos_bus::LtsCapabilitiesSummary; -use lqos_bus::{BusRequest, bus_request}; +use lqos_bus::{BusRequest, bus_request_with_timeout}; use lqos_config::load_config; use serde::{Deserialize, Serialize}; pub use shaper_status::ShaperStatus; @@ -18,6 +18,8 @@ use tracing::{debug, info, warn}; use uuid::Uuid; const SIGNUP_POLL_INTERVAL: Duration = Duration::from_secs(10); +const CONFIG_BUS_REQUEST_TIMEOUT: Duration = Duration::from_secs(10); +const SERVICE_RESTART_TIMEOUT: Duration = Duration::from_secs(10); const INSIGHT_FREE_TRIAL_STATUS_CODE: i32 = 2; const INSIGHT_TRIAL_DAYS_HINT: i32 = 30; @@ -132,9 +134,15 @@ async fn apply_insight_license( .clone(); cfg.long_term_stats.gather_stats = true; cfg.long_term_stats.license_key = Some(license_key.clone()); - bus_request(vec![BusRequest::UpdateLqosdConfig(Box::new(cfg))]) - .await - .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + bus_request_with_timeout( + vec![BusRequest::UpdateLqosdConfig(Box::new(cfg))], + CONFIG_BUS_REQUEST_TIMEOUT, + ) + .await + .map_err(|err| { + warn!("Unable to update config with Insight license: {err}"); + StatusCode::GATEWAY_TIMEOUT + })?; crate::lts2_sys::capabilities::set_signup_bootstrap_active(false); crate::lts2_sys::capabilities::clear_bootstrap_suppression(); crate::lts2_sys::capabilities::wake_control_channel(); @@ -147,9 +155,21 @@ async fn apply_insight_license( info!("LQOSD configuration updated with new Insight license key."); if restart_lqos_api { - let _ = Command::new("/bin/systemctl") - .args(["restart", "lqos_api"]) - .output(); + let restart = tokio::time::timeout( + SERVICE_RESTART_TIMEOUT, + tokio::task::spawn_blocking(|| { + Command::new("/bin/systemctl") + .args(["restart", "lqos_api"]) + .output() + }), + ) + .await; + match restart { + Ok(Ok(Ok(_))) => {} + Ok(Ok(Err(err))) => warn!("Unable to restart lqos_api: {err}"), + Ok(Err(err)) => warn!("lqos_api restart task failed: {err}"), + Err(_) => warn!("Timed out restarting lqos_api"), + } } Ok(()) diff --git a/src/rust/lqosd/src/node_manager/local_api/lts/last_24_hours.rs b/src/rust/lqosd/src/node_manager/local_api/lts/last_24_hours.rs index 151f5697..55757df5 100644 --- a/src/rust/lqosd/src/node_manager/local_api/lts/last_24_hours.rs +++ b/src/rust/lqosd/src/node_manager/local_api/lts/last_24_hours.rs @@ -1,8 +1,13 @@ use crate::node_manager::shaper_queries_actor::ShaperQueryCommand; use axum::http::StatusCode; use serde::{Deserialize, Serialize}; +use std::time::Duration; +use tokio::time::timeout; use tracing::warn; +const SHAPER_QUERY_RESPONSE_TIMEOUT: Duration = Duration::from_secs(35); +const SHAPER_QUERY_SEND_TIMEOUT: Duration = Duration::from_secs(5); + #[derive(Serialize, Deserialize, Copy, Clone, Debug)] pub struct ThroughputData { time: i64, // Unix timestamp @@ -136,20 +141,54 @@ pub struct RecentMedians { pub last_week: (i64, i64), } +async fn wait_for_shaper_response( + context: &'static str, + rx: tokio::sync::oneshot::Receiver>, +) -> Result, StatusCode> { + match timeout(SHAPER_QUERY_RESPONSE_TIMEOUT, rx).await { + Ok(Ok(response)) => Ok(response), + Ok(Err(err)) => { + warn!("Error getting {context}: {err:?}"); + Err(StatusCode::INTERNAL_SERVER_ERROR) + } + Err(_) => { + warn!("Timed out waiting for {context}"); + Err(StatusCode::GATEWAY_TIMEOUT) + } + } +} + +async fn send_shaper_query( + context: &'static str, + shaper_query: &tokio::sync::mpsc::Sender, + command: ShaperQueryCommand, +) -> Result<(), StatusCode> { + match timeout(SHAPER_QUERY_SEND_TIMEOUT, shaper_query.send(command)).await { + Ok(Ok(())) => Ok(()), + Ok(Err(_)) => { + warn!("Error sending {context} query"); + Err(StatusCode::INTERNAL_SERVER_ERROR) + } + Err(_) => { + warn!("Timed out queueing {context} query"); + Err(StatusCode::GATEWAY_TIMEOUT) + } + } +} + pub async fn throughput_period_data( shaper_query: tokio::sync::mpsc::Sender, seconds: i32, ) -> Result, StatusCode> { super::insight_gate().await?; let (tx, rx) = tokio::sync::oneshot::channel(); - shaper_query - .send(ShaperQueryCommand::ShaperThroughput { seconds, reply: tx }) - .await - .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; - let throughput = rx.await.map_err(|e| { - warn!("Error getting total throughput: {:?}", e); - StatusCode::INTERNAL_SERVER_ERROR - })?; + send_shaper_query( + "throughput", + &shaper_query, + ShaperQueryCommand::ShaperThroughput { seconds, reply: tx }, + ) + .await?; + let throughput = wait_for_shaper_response("total throughput", rx).await?; Ok(throughput) } @@ -159,17 +198,13 @@ pub async fn packets_period_data( ) -> Result, StatusCode> { super::insight_gate().await?; let (tx, rx) = tokio::sync::oneshot::channel(); - shaper_query - .send(ShaperQueryCommand::ShaperPackets { seconds, reply: tx }) - .await - .map_err(|_| { - warn!("Error sending packets period"); - StatusCode::INTERNAL_SERVER_ERROR - })?; - let throughput = rx.await.map_err(|e| { - warn!("Error getting packets period: {:?}", e); - StatusCode::INTERNAL_SERVER_ERROR - })?; + send_shaper_query( + "packets period", + &shaper_query, + ShaperQueryCommand::ShaperPackets { seconds, reply: tx }, + ) + .await?; + let throughput = wait_for_shaper_response("packets period", rx).await?; Ok(throughput) } @@ -179,17 +214,13 @@ pub async fn percent_shaped_period_data( ) -> Result, StatusCode> { super::insight_gate().await?; let (tx, rx) = tokio::sync::oneshot::channel(); - shaper_query - .send(ShaperQueryCommand::ShaperPercent { seconds, reply: tx }) - .await - .map_err(|_| { - warn!("Error sending percent shaped period"); - StatusCode::INTERNAL_SERVER_ERROR - })?; - let throughput = rx.await.map_err(|e| { - warn!("Error getting percent shaped: {:?}", e); - StatusCode::INTERNAL_SERVER_ERROR - })?; + send_shaper_query( + "percent shaped period", + &shaper_query, + ShaperQueryCommand::ShaperPercent { seconds, reply: tx }, + ) + .await?; + let throughput = wait_for_shaper_response("percent shaped", rx).await?; Ok(throughput) } @@ -199,17 +230,13 @@ pub async fn percent_flows_period_data( ) -> Result, StatusCode> { super::insight_gate().await?; let (tx, rx) = tokio::sync::oneshot::channel(); - shaper_query - .send(ShaperQueryCommand::ShaperFlows { seconds, reply: tx }) - .await - .map_err(|_| { - warn!("Error sending flows period"); - StatusCode::INTERNAL_SERVER_ERROR - })?; - let throughput = rx.await.map_err(|e| { - warn!("Error getting flows: {:?}", e); - StatusCode::INTERNAL_SERVER_ERROR - })?; + send_shaper_query( + "flows period", + &shaper_query, + ShaperQueryCommand::ShaperFlows { seconds, reply: tx }, + ) + .await?; + let throughput = wait_for_shaper_response("flows", rx).await?; Ok(throughput) } @@ -218,19 +245,14 @@ pub async fn rtt_histo_period_data( seconds: i32, ) -> Result, StatusCode> { super::insight_gate().await?; - tracing::error!("rtt_histo_period"); let (tx, rx) = tokio::sync::oneshot::channel(); - shaper_query - .send(ShaperQueryCommand::ShaperRttHistogram { seconds, reply: tx }) - .await - .map_err(|_| { - warn!("Error sending flows period"); - StatusCode::INTERNAL_SERVER_ERROR - })?; - let throughput = rx.await.map_err(|e| { - warn!("Error getting flows: {:?}", e); - StatusCode::INTERNAL_SERVER_ERROR - })?; + send_shaper_query( + "RTT histogram period", + &shaper_query, + ShaperQueryCommand::ShaperRttHistogram { seconds, reply: tx }, + ) + .await?; + let throughput = wait_for_shaper_response("RTT histogram", rx).await?; Ok(throughput) } @@ -239,19 +261,14 @@ pub async fn top10_downloaders_period_data( seconds: i32, ) -> Result, StatusCode> { super::insight_gate().await?; - tracing::error!("rtt_histo_period"); let (tx, rx) = tokio::sync::oneshot::channel(); - shaper_query - .send(ShaperQueryCommand::ShaperTopDownloaders { seconds, reply: tx }) - .await - .map_err(|_| { - warn!("Error sending flows period"); - StatusCode::INTERNAL_SERVER_ERROR - })?; - let throughput = rx.await.map_err(|e| { - warn!("Error getting flows: {:?}", e); - StatusCode::INTERNAL_SERVER_ERROR - })?; + send_shaper_query( + "top downloaders period", + &shaper_query, + ShaperQueryCommand::ShaperTopDownloaders { seconds, reply: tx }, + ) + .await?; + let throughput = wait_for_shaper_response("top downloaders", rx).await?; Ok(throughput) } @@ -260,19 +277,14 @@ pub async fn worst10_rtt_period_data( seconds: i32, ) -> Result, StatusCode> { super::insight_gate().await?; - tracing::error!("rtt_histo_period"); let (tx, rx) = tokio::sync::oneshot::channel(); - shaper_query - .send(ShaperQueryCommand::ShaperWorstRtt { seconds, reply: tx }) - .await - .map_err(|_| { - warn!("Error sending flows period"); - StatusCode::INTERNAL_SERVER_ERROR - })?; - let throughput = rx.await.map_err(|e| { - warn!("Error getting flows: {:?}", e); - StatusCode::INTERNAL_SERVER_ERROR - })?; + send_shaper_query( + "worst RTT period", + &shaper_query, + ShaperQueryCommand::ShaperWorstRtt { seconds, reply: tx }, + ) + .await?; + let throughput = wait_for_shaper_response("worst RTT", rx).await?; Ok(throughput) } @@ -281,19 +293,14 @@ pub async fn worst10_rxmit_period_data( seconds: i32, ) -> Result, StatusCode> { super::insight_gate().await?; - tracing::error!("rtt_histo_period"); let (tx, rx) = tokio::sync::oneshot::channel(); - shaper_query - .send(ShaperQueryCommand::ShaperWorstRxmit { seconds, reply: tx }) - .await - .map_err(|_| { - warn!("Error sending flows period"); - StatusCode::INTERNAL_SERVER_ERROR - })?; - let throughput = rx.await.map_err(|e| { - warn!("Error getting flows: {:?}", e); - StatusCode::INTERNAL_SERVER_ERROR - })?; + send_shaper_query( + "worst retransmits period", + &shaper_query, + ShaperQueryCommand::ShaperWorstRxmit { seconds, reply: tx }, + ) + .await?; + let throughput = wait_for_shaper_response("worst retransmits", rx).await?; Ok(throughput) } @@ -302,19 +309,14 @@ pub async fn top10_flows_period_data( seconds: i32, ) -> Result, StatusCode> { super::insight_gate().await?; - tracing::error!("rtt_histo_period"); let (tx, rx) = tokio::sync::oneshot::channel(); - shaper_query - .send(ShaperQueryCommand::ShaperTopFlows { seconds, reply: tx }) - .await - .map_err(|_| { - warn!("Error sending flows period"); - StatusCode::INTERNAL_SERVER_ERROR - })?; - let throughput = rx.await.map_err(|e| { - warn!("Error getting flows: {:?}", e); - StatusCode::INTERNAL_SERVER_ERROR - })?; + send_shaper_query( + "top flows period", + &shaper_query, + ShaperQueryCommand::ShaperTopFlows { seconds, reply: tx }, + ) + .await?; + let throughput = wait_for_shaper_response("top flows", rx).await?; Ok(throughput) } @@ -322,19 +324,14 @@ pub async fn recent_medians_data( shaper_query: tokio::sync::mpsc::Sender, ) -> Result, StatusCode> { super::insight_gate().await?; - tracing::debug!("rtt_histo_period"); let (tx, rx) = tokio::sync::oneshot::channel(); - shaper_query - .send(ShaperQueryCommand::ShaperRecentMedian { reply: tx }) - .await - .map_err(|_| { - warn!("Error sending flows period"); - StatusCode::INTERNAL_SERVER_ERROR - })?; - let throughput = rx.await.map_err(|e| { - warn!("Error getting flows: {:?}", e); - StatusCode::INTERNAL_SERVER_ERROR - })?; + send_shaper_query( + "recent median", + &shaper_query, + ShaperQueryCommand::ShaperRecentMedian { reply: tx }, + ) + .await?; + let throughput = wait_for_shaper_response("recent medians", rx).await?; Ok(throughput) } @@ -344,16 +341,12 @@ pub async fn cake_period_data( ) -> Result, StatusCode> { super::insight_gate().await?; let (tx, rx) = tokio::sync::oneshot::channel(); - shaper_query - .send(ShaperQueryCommand::CakeTotals { seconds, reply: tx }) - .await - .map_err(|_| { - warn!("Error sending cake stats period"); - StatusCode::INTERNAL_SERVER_ERROR - })?; - let response = rx.await.map_err(|e| { - warn!("Error getting cake stats: {:?}", e); - StatusCode::INTERNAL_SERVER_ERROR - })?; + send_shaper_query( + "cake stats period", + &shaper_query, + ShaperQueryCommand::CakeTotals { seconds, reply: tx }, + ) + .await?; + let response = wait_for_shaper_response("cake stats", rx).await?; Ok(response) } diff --git a/src/rust/lqosd/src/node_manager/shaper_queries_actor/queries.rs b/src/rust/lqosd/src/node_manager/shaper_queries_actor/queries.rs index 1b5a1298..b3628ae1 100644 --- a/src/rust/lqosd/src/node_manager/shaper_queries_actor/queries.rs +++ b/src/rust/lqosd/src/node_manager/shaper_queries_actor/queries.rs @@ -9,8 +9,11 @@ use crate::node_manager::shaper_queries_actor::ShaperQueryCommand; use crate::node_manager::shaper_queries_actor::caches::Caches; use std::time::Duration; use tokio::sync::oneshot; +use tokio::time::timeout; use tracing::{info, warn}; +const HISTORY_QUERY_ATTEMPT_TIMEOUT: Duration = Duration::from_secs(30); + #[derive(Clone)] struct HistoryClient { control_tx: tokio::sync::mpsc::Sender, @@ -26,21 +29,30 @@ impl HistoryClient { request: RemoteInsightRequest, ) -> Result { let (tx, rx) = oneshot::channel(); - if self - .control_tx - .send(ControlChannelCommand::FetchHistory { + let send_result = timeout( + HISTORY_QUERY_ATTEMPT_TIMEOUT, + self.control_tx.send(ControlChannelCommand::FetchHistory { request, responder: tx, - }) - .await - .is_err() - { - return Err(()); + }), + ) + .await; + match send_result { + Ok(Ok(())) => {} + Ok(Err(_)) => return Err(()), + Err(_) => { + warn!("Timed out queueing Insight history request"); + return Err(()); + } } - match rx.await { - Ok(result) => result, - Err(_) => Err(()), + match timeout(HISTORY_QUERY_ATTEMPT_TIMEOUT, rx).await { + Ok(Ok(result)) => result, + Ok(Err(_)) => Err(()), + Err(_) => { + warn!("Timed out waiting for Insight history response"); + Err(()) + } } } } @@ -89,6 +101,9 @@ macro_rules! shaper_query { break; } Err(()) => { + if my_reply.is_closed() { + break; + } attempts += 1; if attempts >= 3 { warn!("History request exhausted retries"); diff --git a/src/rust/lqosd/src/node_manager/ws.rs b/src/rust/lqosd/src/node_manager/ws.rs index 4e359bd8..7481e364 100644 --- a/src/rust/lqosd/src/node_manager/ws.rs +++ b/src/rust/lqosd/src/node_manager/ws.rs @@ -7,7 +7,9 @@ use std::collections::{BTreeMap, HashSet}; use std::sync::Arc; +use std::time::Duration; +use crate::lts2_sys::control_channel::ControlChannelCommand; use crate::node_manager::auth::{LoginResult, login_from_token}; use crate::node_manager::local_api::{ circuit, circuit_count, config, cpu_affinity, dashboard_themes, device_counts, directories, @@ -55,6 +57,21 @@ mod ticker; const WS_VERSION: &str = include_str!("../../../../VERSION_STRING"); const HANDSHAKE_TIMEOUT_SECS: u64 = 10; +const CONTROL_CHANNEL_SEND_TIMEOUT: Duration = Duration::from_secs(5); + +async fn send_control_command( + control_tx: &tokio::sync::mpsc::Sender, + command: ControlChannelCommand, +) -> bool { + match tokio::time::timeout(CONTROL_CHANNEL_SEND_TIMEOUT, control_tx.send(command)).await { + Ok(Ok(())) => true, + Ok(Err(_)) => false, + Err(_) => { + warn!("Timed out queueing websocket control-channel command"); + false + } + } +} /// Provides an Axum router for the websocket system. Exposes a single /ws route that supports /// pubsub subscriptions and private commands. @@ -742,14 +759,13 @@ async fn receive_channel_message( _ => { let (reply_tx, reply_rx) = tokio::sync::oneshot::channel(); let control_tx = request_state.private_state.control_tx(); - if control_tx - .send( - crate::lts2_sys::control_channel::ControlChannelCommand::SupportTicketList { - responder: reply_tx, - }, - ) - .await - .is_err() + if !send_control_command( + &control_tx, + ControlChannelCommand::SupportTicketList { + responder: reply_tx, + }, + ) + .await { if send_ws_response( &tx, @@ -766,8 +782,11 @@ async fn receive_channel_message( tokio::time::timeout(std::time::Duration::from_secs(30), reply_rx).await; match result { Ok(Ok(Ok(tickets))) => { - if send_ws_response(&tx, WsResponse::SupportTicketListResult { tickets }) - .await + if send_ws_response( + &tx, + WsResponse::SupportTicketListResult { tickets }, + ) + .await { return true; } @@ -816,15 +835,14 @@ async fn receive_channel_message( _ => { let (reply_tx, reply_rx) = tokio::sync::oneshot::channel(); let control_tx = request_state.private_state.control_tx(); - if control_tx - .send( - crate::lts2_sys::control_channel::ControlChannelCommand::SupportTicketGet { - ticket_id, - responder: reply_tx, - }, - ) - .await - .is_err() + if !send_control_command( + &control_tx, + ControlChannelCommand::SupportTicketGet { + ticket_id, + responder: reply_tx, + }, + ) + .await { if send_ws_response( &tx, @@ -899,18 +917,17 @@ async fn receive_channel_message( } else { let (reply_tx, reply_rx) = tokio::sync::oneshot::channel(); let control_tx = request_state.private_state.control_tx(); - if control_tx - .send( - crate::lts2_sys::control_channel::ControlChannelCommand::SupportTicketCreate { - subject, - priority, - body, - commentor, - responder: reply_tx, - }, - ) - .await - .is_err() + if !send_control_command( + &control_tx, + ControlChannelCommand::SupportTicketCreate { + subject, + priority, + body, + commentor, + responder: reply_tx, + }, + ) + .await { if send_ws_response( &tx, @@ -923,12 +940,15 @@ async fn receive_channel_message( return true; } } else { - let result = tokio::time::timeout(std::time::Duration::from_secs(30), reply_rx) - .await; + let result = + tokio::time::timeout(std::time::Duration::from_secs(30), reply_rx).await; match result { Ok(Ok(Ok(ticket))) => { - if send_ws_response(&tx, WsResponse::SupportTicketCreateResult { ticket }) - .await + if send_ws_response( + &tx, + WsResponse::SupportTicketCreateResult { ticket }, + ) + .await { return true; } @@ -988,18 +1008,17 @@ async fn receive_channel_message( .unwrap_or(0); let (reply_tx, reply_rx) = tokio::sync::oneshot::channel(); let control_tx = request_state.private_state.control_tx(); - if control_tx - .send( - crate::lts2_sys::control_channel::ControlChannelCommand::SupportTicketAddComment { - ticket_id, - commentor, - body, - date, - responder: reply_tx, - }, - ) - .await - .is_err() + if !send_control_command( + &control_tx, + ControlChannelCommand::SupportTicketAddComment { + ticket_id, + commentor, + body, + date, + responder: reply_tx, + }, + ) + .await { if send_ws_response( &tx, @@ -1012,8 +1031,8 @@ async fn receive_channel_message( return true; } } else { - let result = tokio::time::timeout(std::time::Duration::from_secs(30), reply_rx) - .await; + let result = + tokio::time::timeout(std::time::Duration::from_secs(30), reply_rx).await; match result { Ok(Ok(Ok(()))) => { if send_ws_response( diff --git a/src/rust/lqosd/src/node_manager/ws/single_user_channels.rs b/src/rust/lqosd/src/node_manager/ws/single_user_channels.rs index fc4c8eba..43d655a9 100644 --- a/src/rust/lqosd/src/node_manager/ws/single_user_channels.rs +++ b/src/rust/lqosd/src/node_manager/ws/single_user_channels.rs @@ -6,6 +6,7 @@ pub(crate) mod flows_by_circuit; mod ping_monitor; mod tree_attached_circuits; +use crate::lts2_sys::control_channel::ControlChannelCommand; use crate::node_manager::ws::messages::{PrivateRequest, WsResponse, encode_ws_message}; use crate::node_manager::ws::single_user_channels::cake_watcher::cake_watcher; use crate::node_manager::ws::single_user_channels::circuit::circuit_watcher; @@ -13,17 +14,52 @@ use crate::node_manager::ws::single_user_channels::circuit_metrics::watch_circui use crate::node_manager::ws::single_user_channels::ping_monitor::ping_monitor; use crate::node_manager::ws::single_user_channels::tree_attached_circuits::watch_tree_attached_circuits; use lqos_probe::ProbeClient; +use std::{sync::Arc, time::Duration}; use tokio::spawn; -use tokio::sync::mpsc::Sender; -use tracing::info; +use tokio::sync::mpsc::{Sender, error::TrySendError}; +use tokio::time::timeout; +use tracing::{debug, info}; + +const CONTROL_CHANNEL_SEND_TIMEOUT: Duration = Duration::from_secs(5); + +/// Sends a private watcher payload without waiting behind a slow websocket. +pub(super) fn try_send_private_payload( + tx: &Sender>>, + payload: Arc>, + channel_name: &'static str, +) -> bool { + match tx.try_send(payload) { + Ok(()) => true, + Err(TrySendError::Full(_)) => { + debug!("{channel_name} outbound queue full; stopping watcher"); + false + } + Err(TrySendError::Closed(_)) => { + debug!("{channel_name} channel closed"); + false + } + } +} + +async fn send_control_command( + control_tx: &tokio::sync::mpsc::Sender, + command: ControlChannelCommand, + context: &'static str, +) { + match timeout(CONTROL_CHANNEL_SEND_TIMEOUT, control_tx.send(command)).await { + Ok(Ok(())) => {} + Ok(Err(_)) => debug!("{context} control channel is closed"), + Err(_) => debug!("{context} timed out queueing control channel command"), + } +} pub struct PrivateState { - tx: Sender>>, + tx: Sender>>, bus_tx: Sender<( tokio::sync::oneshot::Sender, lqos_bus::BusRequest, )>, - control_tx: tokio::sync::mpsc::Sender, + control_tx: tokio::sync::mpsc::Sender, probe_client: ProbeClient, browser_language: Option, chatbot_request: Option, @@ -41,9 +77,7 @@ impl PrivateState { tokio::sync::oneshot::Sender, lqos_bus::BusRequest, )>, - control_tx: tokio::sync::mpsc::Sender< - crate::lts2_sys::control_channel::ControlChannelCommand, - >, + control_tx: tokio::sync::mpsc::Sender, probe_client: ProbeClient, browser_language: Option, ) -> Self { @@ -62,9 +96,7 @@ impl PrivateState { } } - pub fn control_tx( - &self, - ) -> tokio::sync::mpsc::Sender { + pub fn control_tx(&self) -> tokio::sync::mpsc::Sender { self.control_tx.clone() } @@ -205,7 +237,7 @@ impl PrivateState { message: message.to_string(), }; if let Ok(payload) = encode_ws_message(&response) { - let _ = self.tx.send(payload).await; + let _ = try_send_private_payload(&self.tx, payload, "Chatbot"); } return; } @@ -220,7 +252,7 @@ impl PrivateState { let text = String::from_utf8_lossy(&chunk).to_string(); let response = WsResponse::ChatbotChunk { text }; if let Ok(payload) = encode_ws_message(&response) { - if to_client.send(payload).await.is_err() { + if !try_send_private_payload(&to_client, payload, "Chatbot") { break; } } else { @@ -229,17 +261,17 @@ impl PrivateState { } }); - let _ = self - .control_tx - .send( - crate::lts2_sys::control_channel::ControlChannelCommand::StartChat { - request_id, - browser_ts_ms, - browser_language: self.browser_language.clone(), - stream: stream_tx, - }, - ) - .await; + send_control_command( + &self.control_tx, + ControlChannelCommand::StartChat { + request_id, + browser_ts_ms, + browser_language: self.browser_language.clone(), + stream: stream_tx, + }, + "StartChat", + ) + .await; info!( "[chatbot] starting session request_id={} browser_ts_ms={:?}", request_id, browser_ts_ms @@ -250,15 +282,12 @@ impl PrivateState { let Some(request_id) = self.chatbot_request else { return; }; - let _ = self - .control_tx - .send( - crate::lts2_sys::control_channel::ControlChannelCommand::ChatSend { - request_id, - text, - }, - ) - .await; + send_control_command( + &self.control_tx, + ControlChannelCommand::ChatSend { request_id, text }, + "ChatSend", + ) + .await; } } diff --git a/src/rust/lqosd/src/node_manager/ws/single_user_channels/cake_watcher.rs b/src/rust/lqosd/src/node_manager/ws/single_user_channels/cake_watcher.rs index 1267eac7..d6a63db5 100644 --- a/src/rust/lqosd/src/node_manager/ws/single_user_channels/cake_watcher.rs +++ b/src/rust/lqosd/src/node_manager/ws/single_user_channels/cake_watcher.rs @@ -1,4 +1,5 @@ use crate::node_manager::ws::messages::{WsResponse, encode_ws_message}; +use crate::node_manager::ws::single_user_channels::try_send_private_payload; use lqos_queue_tracker::{add_watched_queue, get_raw_circuit_data, still_watching}; pub(super) async fn cake_watcher( @@ -16,11 +17,10 @@ pub(super) async fn cake_watcher( if let lqos_bus::BusResponse::RawQueueData(Some(msg)) = get_raw_circuit_data(&circuit_id) { let response = WsResponse::CakeWatcher { data: *msg }; - if let Ok(payload) = encode_ws_message(&response) { - let send_result = tx.send(payload).await; - if send_result.is_err() { - break; - } + if let Ok(payload) = encode_ws_message(&response) + && !try_send_private_payload(&tx, payload, "CakeWatcher") + { + break; } } } diff --git a/src/rust/lqosd/src/node_manager/ws/single_user_channels/circuit.rs b/src/rust/lqosd/src/node_manager/ws/single_user_channels/circuit.rs index b5a1eccd..4881b460 100644 --- a/src/rust/lqosd/src/node_manager/ws/single_user_channels/circuit.rs +++ b/src/rust/lqosd/src/node_manager/ws/single_user_channels/circuit.rs @@ -1,5 +1,6 @@ use crate::node_manager::local_api::circuit_activity::{CircuitSummaryData, circuit_flow_counts}; use crate::node_manager::ws::messages::{CircuitDevicesResult, WsResponse, encode_ws_message}; +use crate::node_manager::ws::single_user_channels::try_send_private_payload; use crate::node_manager::ws::ticker::all_circuits; use crate::rtt_exclusions; use crate::throughput_tracker::{circuit_current_qoo, circuit_current_rtt_p50_nanos}; @@ -121,7 +122,7 @@ pub(super) async fn circuit_watcher( }; if let Ok(payload) = encode_ws_message(&response) { - if tx.send(payload).await.is_err() { + if !try_send_private_payload(&tx, payload, "CircuitWatcher") { info!("CircuitWatcher channel is gone"); break; } diff --git a/src/rust/lqosd/src/node_manager/ws/single_user_channels/circuit_metrics.rs b/src/rust/lqosd/src/node_manager/ws/single_user_channels/circuit_metrics.rs index d03dcbd2..c950b88c 100644 --- a/src/rust/lqosd/src/node_manager/ws/single_user_channels/circuit_metrics.rs +++ b/src/rust/lqosd/src/node_manager/ws/single_user_channels/circuit_metrics.rs @@ -2,9 +2,9 @@ use crate::node_manager::local_api::circuit_live::{ CircuitLiveMetrics, CircuitMetricsQuery, circuit_live_metrics, }; use crate::node_manager::ws::messages::{WsResponse, encode_ws_message}; +use crate::node_manager::ws::single_user_channels::try_send_private_payload; use std::time::Duration; use tokio::time::MissedTickBehavior; -use tracing::debug; pub(super) async fn watch_circuit_metrics( query: CircuitMetricsQuery, @@ -33,8 +33,7 @@ pub(super) async fn watch_circuit_metrics( if let Some(response) = response { match encode_ws_message(&response) { Ok(payload) => { - if tx.send(payload).await.is_err() { - debug!("CircuitMetrics watcher channel closed"); + if !try_send_private_payload(&tx, payload, "CircuitMetrics") { break; } } diff --git a/src/rust/lqosd/src/node_manager/ws/single_user_channels/ping_monitor.rs b/src/rust/lqosd/src/node_manager/ws/single_user_channels/ping_monitor.rs index 69133f21..ab0cf73e 100644 --- a/src/rust/lqosd/src/node_manager/ws/single_user_channels/ping_monitor.rs +++ b/src/rust/lqosd/src/node_manager/ws/single_user_channels/ping_monitor.rs @@ -1,8 +1,9 @@ use crate::node_manager::ws::messages::{PingState, WsResponse, encode_ws_message}; +use crate::node_manager::ws::single_user_channels::try_send_private_payload; use lqos_probe::{ProbeClass, ProbeClient}; use std::time::Duration; use tokio::time::MissedTickBehavior; -use tracing::{debug, info}; +use tracing::debug; const UI_MONITOR_PROBE_MAX_AGE: Duration = Duration::from_millis(250); @@ -32,13 +33,15 @@ pub(super) async fn ping_monitor( } }; - for ((ip, label), observation) in ip_addresses.iter().zip(observations) { + 'observations: for ((ip, label), observation) in ip_addresses.iter().zip(observations) { if observation.reachable { let ping_time = observation .rtt_ms .map(|rtt_ms| Duration::from_secs_f64(rtt_ms / 1000.0)) .unwrap_or_else(|| Duration::from_secs(0)); - send_alive(tx.clone(), ip.clone(), ping_time, label.clone()).await; + if !send_alive(&tx, ip.clone(), ping_time, label.clone()) { + break 'observations; + } } else { if let Some(error) = observation.error.as_deref() { debug!( @@ -46,7 +49,9 @@ pub(super) async fn ping_monitor( observation.normalized_target, error ); } - send_timeout(tx.clone(), ip.clone()).await; + if !send_timeout(&tx, ip.clone()) { + break 'observations; + } } } @@ -55,7 +60,7 @@ pub(super) async fn ping_monitor( result: PingState::ChannelTest, }; if let Ok(payload) = encode_ws_message(&channel_test) { - if tx.send(payload).await.is_err() { + if !try_send_private_payload(&tx, payload, "PingMonitor") { debug!("Channel is gone"); break; } @@ -65,24 +70,22 @@ pub(super) async fn ping_monitor( } } -async fn send_timeout(tx: tokio::sync::mpsc::Sender>>, ip: String) { +fn send_timeout(tx: &tokio::sync::mpsc::Sender>>, ip: String) -> bool { let result = WsResponse::PingMonitor { ip, result: PingState::NoResponse, }; - if let Ok(payload) = encode_ws_message(&result) - && tx.send(payload).await.is_err() - { - info!("Channel is gone"); - } + encode_ws_message(&result) + .map(|payload| try_send_private_payload(tx, payload, "PingMonitor")) + .unwrap_or(false) } -async fn send_alive( - tx: tokio::sync::mpsc::Sender>>, +fn send_alive( + tx: &tokio::sync::mpsc::Sender>>, ip: String, ping_time: Duration, label: String, -) { +) -> bool { let result = WsResponse::PingMonitor { ip, result: PingState::Ping { @@ -90,9 +93,7 @@ async fn send_alive( label, }, }; - if let Ok(payload) = encode_ws_message(&result) - && tx.send(payload).await.is_err() - { - info!("Channel is gone"); - } + encode_ws_message(&result) + .map(|payload| try_send_private_payload(tx, payload, "PingMonitor")) + .unwrap_or(false) } diff --git a/src/rust/lqosd/src/node_manager/ws/single_user_channels/tree_attached_circuits.rs b/src/rust/lqosd/src/node_manager/ws/single_user_channels/tree_attached_circuits.rs index ee7e791f..eacdf8f3 100644 --- a/src/rust/lqosd/src/node_manager/ws/single_user_channels/tree_attached_circuits.rs +++ b/src/rust/lqosd/src/node_manager/ws/single_user_channels/tree_attached_circuits.rs @@ -2,9 +2,9 @@ use crate::node_manager::local_api::tree_attached_circuits::{ TreeAttachedCircuitsPage, TreeAttachedCircuitsQuery, tree_attached_circuits, }; use crate::node_manager::ws::messages::{WsResponse, encode_ws_message}; +use crate::node_manager::ws::single_user_channels::try_send_private_payload; use std::time::Duration; use tokio::time::MissedTickBehavior; -use tracing::debug; pub(super) async fn watch_tree_attached_circuits( query: TreeAttachedCircuitsQuery, @@ -29,8 +29,7 @@ pub(super) async fn watch_tree_attached_circuits( if let Some(response) = response { match encode_ws_message(&response) { Ok(payload) => { - if tx.send(payload).await.is_err() { - debug!("TreeAttachedCircuits watcher channel closed"); + if !try_send_private_payload(&tx, payload, "TreeAttachedCircuits") { break; } } diff --git a/src/rust/lqosd/src/node_manager/ws/ticker/network_tree.rs b/src/rust/lqosd/src/node_manager/ws/ticker/network_tree.rs index 4c49a3b3..84906f7e 100644 --- a/src/rust/lqosd/src/node_manager/ws/ticker/network_tree.rs +++ b/src/rust/lqosd/src/node_manager/ws/ticker/network_tree.rs @@ -3,7 +3,42 @@ use crate::node_manager::ws::publish_subscribe::PubSub; use crate::node_manager::ws::published_channels::PublishedChannels; use lqos_bus::{BusReply, BusRequest, BusResponse, Circuit}; use std::sync::Arc; +use std::time::Duration; use tokio::sync::mpsc::Sender; +use tokio::time::timeout; + +const INTERNAL_BUS_TIMEOUT: Duration = Duration::from_secs(5); + +async fn request_internal_bus( + context: &'static str, + bus_tx: Sender<(tokio::sync::oneshot::Sender, BusRequest)>, + request: BusRequest, +) -> Option { + let (tx, rx) = tokio::sync::oneshot::channel::(); + match timeout(INTERNAL_BUS_TIMEOUT, bus_tx.send((tx, request))).await { + Ok(Ok(())) => {} + Ok(Err(err)) => { + tracing::warn!("{context}: failed to send request to bus: {err:?}"); + return None; + } + Err(_) => { + tracing::warn!("{context}: timed out queueing request to bus"); + return None; + } + } + + match timeout(INTERNAL_BUS_TIMEOUT, rx).await { + Ok(Ok(replies)) => Some(replies), + Ok(Err(err)) => { + tracing::warn!("{context}: failed to receive response from bus: {err:?}"); + None + } + Err(_) => { + tracing::warn!("{context}: timed out waiting for bus response"); + None + } + } +} pub async fn network_tree( channels: Arc, @@ -16,21 +51,10 @@ pub async fn network_tree( return; } - let (tx, rx) = tokio::sync::oneshot::channel::(); - let request = BusRequest::GetFullNetworkMap; - if let Err(e) = bus_tx.send((tx, request)).await { - tracing::warn!("NetworkTree: failed to send request to bus: {:?}", e); + let Some(replies) = + request_internal_bus("NetworkTree", bus_tx, BusRequest::GetFullNetworkMap).await + else { return; - } - let replies = match rx.await { - Ok(r) => r, - Err(e) => { - tracing::warn!( - "NetworkTree: failed to receive throughput from bus: {:?}", - e - ); - return; - } }; for reply in replies.responses.into_iter() { if let BusResponse::NetworkMap(nodes) = reply { @@ -43,21 +67,10 @@ pub async fn network_tree( pub async fn all_circuits( bus_tx: Sender<(tokio::sync::oneshot::Sender, BusRequest)>, ) -> Vec { - let (tx, rx) = tokio::sync::oneshot::channel::(); - let request = BusRequest::GetAllCircuits; - if let Err(e) = bus_tx.send((tx, request)).await { - tracing::warn!("AllCircuits: failed to send request to bus: {:?}", e); + let Some(replies) = + request_internal_bus("AllCircuits", bus_tx, BusRequest::GetAllCircuits).await + else { return Vec::new(); - } - let replies = match rx.await { - Ok(r) => r, - Err(e) => { - tracing::warn!( - "AllCircuits: failed to receive throughput from bus: {:?}", - e - ); - return Vec::new(); - } }; for reply in replies.responses.into_iter() { if let BusResponse::CircuitData(circuits) = reply { -- knotmirror 0.0.1 From befbf8d3ef4f495ae671a5189f1a40a52105f9ff Mon Sep 17 00:00:00 2001 From: rchac Date: Fri, 1 May 2026 15:27:59 +0000 Subject: [PATCH 33/51] Install Python dependencies in root-owned venv --- docs-es/v2.0/Quickstart/services-and-run.md | 6 ++-- docs-es/v2.0/TechnicalDocs/git-install.md | 7 +++-- docs-es/v2.0/TechnicalDocs/troubleshooting.md | 14 ++++++++-- docs-es/v2.0/components-es.md | 6 ++-- docs-es/v2.0/git-install-es.md | 7 +++-- docs-es/v2.0/troubleshooting-es.md | 10 ++++++- docs/v2.0/components.md | 7 +++-- docs/v2.0/git-install.md | 7 +++-- docs/v2.0/troubleshooting.md | 24 ++++++++++++++-- src/bin/lqos_scheduler.service.example | 2 +- src/bin/rebuild_python_venv.sh | 28 +++++++++++++++++++ src/build_dpkg.sh | 20 ++++++------- src/build_rust.sh | 16 ++++++++++- 13 files changed, 117 insertions(+), 37 deletions(-) create mode 100755 src/bin/rebuild_python_venv.sh diff --git a/docs-es/v2.0/Quickstart/services-and-run.md b/docs-es/v2.0/Quickstart/services-and-run.md index 1e4c6864..b05fc9af 100644 --- a/docs-es/v2.0/Quickstart/services-and-run.md +++ b/docs-es/v2.0/Quickstart/services-and-run.md @@ -48,19 +48,19 @@ sudo systemctl stop lqos_scheduler For one-time runs of LibreQoS.py, use ```shell -sudo ./LibreQoS.py +sudo /opt/libreqos/venv/bin/python /opt/libreqos/src/LibreQoS.py ``` - To use the debug mode with more verbose output, use: ```shell -sudo ./LibreQoS.py --debug +sudo /opt/libreqos/venv/bin/python /opt/libreqos/src/LibreQoS.py --debug ``` To confirm that lqos_scheduler (scheduler.py) is able to work correctly, run: ```shell -sudo python3 scheduler.py +sudo /opt/libreqos/venv/bin/python /opt/libreqos/src/scheduler.py ``` Once you have any errors eliminated, restart lqos_scheduler with diff --git a/docs-es/v2.0/TechnicalDocs/git-install.md b/docs-es/v2.0/TechnicalDocs/git-install.md index 154e2127..1b3a4405 100644 --- a/docs-es/v2.0/TechnicalDocs/git-install.md +++ b/docs-es/v2.0/TechnicalDocs/git-install.md @@ -21,15 +21,16 @@ By specifying `libreqos` at the end, git will ensure the folder name is lowercas You need to have a few packages from `apt` installed: ```shell -sudo apt-get install -y python3-pip clang gcc gcc-multilib llvm libelf-dev git nano graphviz curl screen llvm pkg-config linux-tools-common linux-tools-`uname -r` libbpf-dev libssl-dev +sudo apt-get install -y python3-pip python3-venv clang gcc gcc-multilib llvm libelf-dev git nano graphviz curl screen llvm pkg-config linux-tools-common linux-tools-`uname -r` libbpf-dev libssl-dev ``` Then you need to install some Python dependencies: ```shell cd /opt/libreqos -PIP_BREAK_SYSTEM_PACKAGES=1 pip install -r requirements.txt -sudo PIP_BREAK_SYSTEM_PACKAGES=1 pip install -r requirements.txt +sudo python3 -m venv /opt/libreqos/venv +sudo /opt/libreqos/venv/bin/python -m pip install --upgrade pip +sudo /opt/libreqos/venv/bin/python -m pip install --upgrade -r requirements.txt ``` ## Install the Rust development system diff --git a/docs-es/v2.0/TechnicalDocs/troubleshooting.md b/docs-es/v2.0/TechnicalDocs/troubleshooting.md index 5bd88b72..31155216 100644 --- a/docs-es/v2.0/TechnicalDocs/troubleshooting.md +++ b/docs-es/v2.0/TechnicalDocs/troubleshooting.md @@ -57,7 +57,17 @@ At the command-line, run ```sudo RUST_LOG=info /opt/libreqos/src/bin/lqosd``` wh This tends to show up when the MQ qdisc cannot be added correctly to the NIC interface. This would suggest the NIC has insufficient RX/TX queues. Please make sure you are using the [recommended NICs](../../SystemRequirements/Compute.md#network-interface-requirements). -### Python ModuleNotFoundError in Ubuntu 24.04 +### Python dependency or virtual environment errors + +Packaged installs keep LibreQoS Python dependencies in `/opt/libreqos/venv`. The services still run as root, but Python packages do not mix with apt-managed system packages. If the scheduler reports missing Python modules, or package configuration was interrupted while installing Python dependencies, rebuild the virtual environment: + +```bash +sudo /opt/libreqos/src/bin/rebuild_python_venv.sh +sudo dpkg --configure -a +sudo systemctl restart lqosd lqos_scheduler +``` + +### Python ModuleNotFoundError in older Ubuntu 24.04 installs ``` pip uninstall binpacking --break-system-packages --yes sudo pip uninstall binpacking --break-system-packages --yes @@ -73,7 +83,7 @@ sudo pip install deepdiff --break-system-packages ``` cd /opt/libreqos/src sudo systemctl stop lqos_scheduler -sudo python3 LibreQoS.py +sudo /opt/libreqos/venv/bin/python /opt/libreqos/src/LibreQoS.py ``` The console output from running LibreQoS.py directly provides more specific errors regarding issues with ShapedDevices.csv and network.json diff --git a/docs-es/v2.0/components-es.md b/docs-es/v2.0/components-es.md index 0eff075d..7dcbed04 100644 --- a/docs-es/v2.0/components-es.md +++ b/docs-es/v2.0/components-es.md @@ -51,15 +51,15 @@ sudo journalctl -u lqos_scheduler -b ### Depuración de lqos_scheduler -`lqos_scheduler` ejecuta `scheduler.py`, que a su vez invoca `LibreQoS.py`. +`lqos_scheduler` ejecuta `scheduler.py`, que a su vez invoca `LibreQoS.py`. En instalaciones empaquetadas, Python se ejecuta desde el entorno virtual propiedad de root en `/opt/libreqos/venv`. Flujo de depuración recomendado: ```bash sudo systemctl stop lqos_scheduler cd /opt/libreqos/src -sudo ./LibreQoS.py --debug -sudo python3 scheduler.py +sudo /opt/libreqos/venv/bin/python /opt/libreqos/src/LibreQoS.py --debug +sudo /opt/libreqos/venv/bin/python /opt/libreqos/src/scheduler.py sudo systemctl start lqos_scheduler ``` diff --git a/docs-es/v2.0/git-install-es.md b/docs-es/v2.0/git-install-es.md index 9f155ef8..e1670714 100644 --- a/docs-es/v2.0/git-install-es.md +++ b/docs-es/v2.0/git-install-es.md @@ -20,15 +20,16 @@ Al especificar `libreqos` al final, Git asegurará que el nombre del directorio Es necesario instalar ciertos paquetes mediante `apt`: ```shell -sudo apt-get install -y python3-pip clang mold esbuild gcc gcc-multilib llvm libelf-dev git nano graphviz curl screen llvm pkg-config linux-tools-common linux-tools-`uname -r` libbpf-dev libssl-dev +sudo apt-get install -y python3-pip python3-venv clang mold esbuild gcc gcc-multilib llvm libelf-dev git nano graphviz curl screen llvm pkg-config linux-tools-common linux-tools-`uname -r` libbpf-dev libssl-dev ``` Posteriormente, debe instalar algunas dependencias de Python: ```shell cd /opt/libreqos -PIP_BREAK_SYSTEM_PACKAGES=1 pip install -r requirements.txt -sudo PIP_BREAK_SYSTEM_PACKAGES=1 pip install -r requirements.txt +sudo python3 -m venv /opt/libreqos/venv +sudo /opt/libreqos/venv/bin/python -m pip install --upgrade pip +sudo /opt/libreqos/venv/bin/python -m pip install --upgrade -r requirements.txt ``` ## Instalar el entorno de desarrollo de Rust diff --git a/docs-es/v2.0/troubleshooting-es.md b/docs-es/v2.0/troubleshooting-es.md index db4a348d..1afcd98e 100644 --- a/docs-es/v2.0/troubleshooting-es.md +++ b/docs-es/v2.0/troubleshooting-es.md @@ -112,6 +112,14 @@ sudo RUST_LOG=info /opt/libreqos/src/bin/lqosd sudo journalctl -u lqos_scheduler --since "1 day ago" --no-pager > lqos_sched_log.txt ``` +Las instalaciones empaquetadas mantienen las dependencias Python de LibreQoS en `/opt/libreqos/venv`. Los servicios siguen ejecutándose como root, pero los paquetes Python no se mezclan con los paquetes administrados por apt. Si el scheduler informa módulos faltantes, o si la configuración del paquete se interrumpió al instalar dependencias Python, reconstruya el entorno virtual: + +```bash +sudo /opt/libreqos/src/bin/rebuild_python_venv.sh +sudo dpkg --configure -a +sudo systemctl restart lqosd lqos_scheduler +``` + Si el scheduler falla inmediatamente después de un reinicio con un mensaje como `Socket (typically /run/lqos/bus) not found`, eso indica que `lqosd` todavía no había terminado de enlazar el bus local. Los builds actuales esperan brevemente la disponibilidad del bus al arrancar el scheduler en lugar de abortar de inmediato, por lo que ya no deberían aparecer panics repetidos de arranque tras un reinicio. ### El estado del scheduler en WebUI aparece no saludable @@ -174,7 +182,7 @@ sudo pip install deepdiff --break-system-packages ```bash cd /opt/libreqos/src sudo systemctl stop lqos_scheduler -sudo python3 LibreQoS.py +sudo /opt/libreqos/venv/bin/python /opt/libreqos/src/LibreQoS.py ``` Corrija errores en `ShapedDevices.csv` y/o `network.json`, luego: diff --git a/docs/v2.0/components.md b/docs/v2.0/components.md index bc4bdf7b..a43fec72 100644 --- a/docs/v2.0/components.md +++ b/docs/v2.0/components.md @@ -31,6 +31,7 @@ flowchart LR ### lqos_scheduler - lqos_scheduler performs continuous refreshes of LibreQoS' shapers, including pulling from any enabled CRM Integrations (UISP, Splynx, Netzur). +- Packaged installs run scheduler Python from the root-owned virtual environment at `/opt/libreqos/venv`. - Actions: - On start: Run a full setup of queues - Current builds wait briefly for `lqosd` to finish binding the local bus before the first scheduler run. @@ -89,19 +90,19 @@ sudo systemctl stop lqos_scheduler For one-time runs of LibreQoS.py, use ```shell -sudo ./LibreQoS.py +sudo /opt/libreqos/venv/bin/python /opt/libreqos/src/LibreQoS.py ``` - To use the debug mode with more verbose output, use: ```shell -sudo ./LibreQoS.py --debug +sudo /opt/libreqos/venv/bin/python /opt/libreqos/src/LibreQoS.py --debug ``` To confirm that lqos_scheduler (scheduler.py) is able to work correctly, run: ```shell -sudo python3 scheduler.py +sudo /opt/libreqos/venv/bin/python /opt/libreqos/src/scheduler.py ``` If an integration fails during a scheduler run, current builds keep the scheduler alive, surface a shortened output preview in scheduler status/error reporting, and save the full captured output to a timestamped `/tmp/lqos_scheduler__*.log` file. diff --git a/docs/v2.0/git-install.md b/docs/v2.0/git-install.md index 4c4ad0ba..0c5d2287 100644 --- a/docs/v2.0/git-install.md +++ b/docs/v2.0/git-install.md @@ -20,15 +20,16 @@ By specifying `libreqos` at the end, git will ensure the folder name is lowercas You need to have a few packages from `apt` installed: ```shell -sudo apt-get install -y python3-pip clang mold esbuild gcc gcc-multilib llvm libelf-dev git nano graphviz curl screen llvm pkg-config linux-tools-common linux-tools-`uname -r` libbpf-dev libssl-dev +sudo apt-get install -y python3-pip python3-venv clang mold esbuild gcc gcc-multilib llvm libelf-dev git nano graphviz curl screen llvm pkg-config linux-tools-common linux-tools-`uname -r` libbpf-dev libssl-dev ``` Then you need to install some Python dependencies: ```shell cd /opt/libreqos -PIP_BREAK_SYSTEM_PACKAGES=1 pip install -r requirements.txt -sudo PIP_BREAK_SYSTEM_PACKAGES=1 pip install -r requirements.txt +sudo python3 -m venv /opt/libreqos/venv +sudo /opt/libreqos/venv/bin/python -m pip install --upgrade pip +sudo /opt/libreqos/venv/bin/python -m pip install --upgrade -r requirements.txt ``` ## Install the Rust development system diff --git a/docs/v2.0/troubleshooting.md b/docs/v2.0/troubleshooting.md index 609287fe..edb1f60d 100644 --- a/docs/v2.0/troubleshooting.md +++ b/docs/v2.0/troubleshooting.md @@ -214,7 +214,27 @@ If status repeatedly oscillates between ready/error, collect both logs and confi This tends to show up when the MQ qdisc cannot be added correctly to the NIC interface. This would suggest the NIC has insufficient RX/TX queues. Please make sure you are using the [recommended NICs](requirements.md). -### Python ModuleNotFoundError in Ubuntu 24.04 +### Python dependency or virtual environment errors + +Packaged installs keep LibreQoS Python dependencies in `/opt/libreqos/venv`. The services still run as root, but Python packages do not mix with apt-managed system packages. If the scheduler reports missing Python modules, or package configuration was interrupted while installing Python dependencies, rebuild the virtual environment: + +```bash +sudo /opt/libreqos/src/bin/rebuild_python_venv.sh +sudo dpkg --configure -a +sudo systemctl restart lqosd lqos_scheduler +``` + +For manual shaping tests, use the same interpreter as the service: + +```bash +sudo systemctl stop lqos_scheduler +sudo /opt/libreqos/venv/bin/python /opt/libreqos/src/LibreQoS.py +sudo systemctl start lqos_scheduler +``` + +Older installs that predate the virtual environment may show `ModuleNotFoundError` and suggest system `pip` commands. Upgrade to a package that creates `/opt/libreqos/venv`, then use the repair command above. + +### Python ModuleNotFoundError in older Ubuntu 24.04 installs ``` pip uninstall binpacking --break-system-packages --yes sudo pip uninstall binpacking --break-system-packages --yes @@ -230,7 +250,7 @@ sudo pip install deepdiff --break-system-packages ``` cd /opt/libreqos/src sudo systemctl stop lqos_scheduler -sudo python3 LibreQoS.py +sudo /opt/libreqos/venv/bin/python /opt/libreqos/src/LibreQoS.py ``` The console output from running LibreQoS.py directly provides more specific errors regarding issues with ShapedDevices.csv and network.json diff --git a/src/bin/lqos_scheduler.service.example b/src/bin/lqos_scheduler.service.example index c1e766dc..78a42d74 100644 --- a/src/bin/lqos_scheduler.service.example +++ b/src/bin/lqos_scheduler.service.example @@ -5,7 +5,7 @@ Requires=lqosd.service [Service] WorkingDirectory=/opt/libreqos/src -ExecStart=/usr/bin/python3 /opt/libreqos/src/scheduler.py +ExecStart=/opt/libreqos/venv/bin/python /opt/libreqos/src/scheduler.py Restart=always [Install] diff --git a/src/bin/rebuild_python_venv.sh b/src/bin/rebuild_python_venv.sh new file mode 100755 index 00000000..247ef4db --- /dev/null +++ b/src/bin/rebuild_python_venv.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -euo pipefail + +VENV_DIR="/opt/libreqos/venv" +REQUIREMENTS="/opt/libreqos/src/requirements.txt" +CONSTRAINTS="/opt/libreqos/src/deb-requirements-constraints.txt" + +if [ "$(id -u)" -ne 0 ]; then + echo "rebuild_python_venv.sh must be run as root." >&2 + exit 1 +fi + +if [ ! -f "$REQUIREMENTS" ]; then + echo "LibreQoS Python requirements file not found: $REQUIREMENTS" >&2 + exit 1 +fi + +python3 -m venv --clear "$VENV_DIR" +"$VENV_DIR/bin/python" -m pip install --upgrade pip + +if [ -s "$CONSTRAINTS" ]; then + "$VENV_DIR/bin/python" -m pip install --upgrade -c "$CONSTRAINTS" -r "$REQUIREMENTS" +else + "$VENV_DIR/bin/python" -m pip install --upgrade -r "$REQUIREMENTS" +fi + +chown -R root:root "$VENV_DIR" +chmod -R go-w "$VENV_DIR" diff --git a/src/build_dpkg.sh b/src/build_dpkg.sh index 66388a1d..45e2c74c 100755 --- a/src/build_dpkg.sh +++ b/src/build_dpkg.sh @@ -12,7 +12,7 @@ PACKAGE=libreqos VERSION=$(cat ./VERSION_STRING).$BUILD_DATE PKGVERSION="${PACKAGE}_${VERSION}" DPKG_DIR=dist/$PKGVERSION-1_amd64 -APT_DEPENDENCIES="python3-pip, nano, curl, ca-certificates" +APT_DEPENDENCIES="python3-pip, python3-venv, nano, curl, ca-certificates" DEBIAN_DIR=$DPKG_DIR/DEBIAN LQOS_DIR=$DPKG_DIR/opt/libreqos/src LQOS_STATE_DIR=$DPKG_DIR/opt/libreqos/state @@ -53,6 +53,7 @@ LQOS_BIN_FILES=( lqosd.service.example lqos_api.service.example lqos_setup.service.example + rebuild_python_venv.sh ) RUSTPROGS=( @@ -140,16 +141,10 @@ else fi } -# Install Python Dependencies -pushd /opt/libreqos > /dev/null -# - Setup Python dependencies as a post-install task. Use --ignore-installed so -# pip does not try to uninstall Debian-managed packages that do not ship a -# pip RECORD file (for example blinker on Ubuntu 24.04). -if [ -s src/deb-requirements-constraints.txt ]; then -PIP_BREAK_SYSTEM_PACKAGES=1 python3 -m pip install --ignore-installed -c src/deb-requirements-constraints.txt -r src/requirements.txt -else -PIP_BREAK_SYSTEM_PACKAGES=1 python3 -m pip install --ignore-installed -r src/requirements.txt -fi +# - Setup Python dependencies in a root-owned virtual environment. LibreQoS +# services still run as root, but Python packages no longer mix with +# apt-managed system site-packages. +/opt/libreqos/src/bin/rebuild_python_venv.sh # Ensure folder permissions are correct post-install set_libreqos_operator_permissions @@ -191,7 +186,6 @@ HOTFIX exit 1 ;; esac -popd > /dev/null EOF # Uninstall Script @@ -235,6 +229,8 @@ for file in "${LQOS_BIN_FILES[@]}"; do cp "bin/$file" "$LQOS_DIR/bin" done +chmod a+x "$LQOS_DIR/bin/rebuild_python_venv.sh" + # Copy the remove pinned maps cp rust/remove_pinned_maps.sh "$LQOS_DIR"/rust diff --git a/src/build_rust.sh b/src/build_rust.sh index d61c9407..234dc8fe 100755 --- a/src/build_rust.sh +++ b/src/build_rust.sh @@ -23,7 +23,7 @@ do done # Check Pre-Requisites -sudo apt install python3-pip clang gcc gcc-multilib llvm libelf-dev git nano curl screen llvm pkg-config linux-tools-common linux-tools-`uname -r` libbpf-dev libssl-dev curl +sudo apt install python3-pip python3-venv clang gcc gcc-multilib llvm libelf-dev git nano curl screen llvm pkg-config linux-tools-common linux-tools-`uname -r` libbpf-dev libssl-dev curl if ! rustup -V &> /dev/null then @@ -214,6 +214,17 @@ clear_pinned_maps_before_lqosd_restart() { fi } +rebuild_python_venv() { + local script_path="./bin/rebuild_python_venv.sh" + if [ ! -x "$script_path" ]; then + echo "Expected $script_path to exist and be executable before refreshing Python services." + exit 1 + fi + + echo "Rebuilding /opt/libreqos/venv before restarting Python services." + sudo "$script_path" +} + SERVICE_UNITS_UPDATED=0 refresh_service_unit lqosd refresh_service_unit lqos_scheduler @@ -240,6 +251,8 @@ if service_unit_exists lqos_netplan_helper; then fi fi +rebuild_python_venv + if hotfix_blocks_service_restart; then echo "Ubuntu 24.04 systemd hotfix is still required. Skipping LibreQoS service restarts." echo "Install it with: sudo ./systemd_hotfix.sh install" @@ -267,6 +280,7 @@ fi echo "-----------------------------------------------------------------" echo "Don't forget to setup /etc/lqos.conf!" echo "Template .service files can be found in bin/" +echo "Debian package installs create/update /opt/libreqos/venv for Python dependencies." echo "If src/deb-requirements-constraints.txt exists, Debian package installs use it to constrain Python dependencies." echo "Use ./systemd_hotfix.sh to evaluate or install the Ubuntu 24.04 networkd hotfix from the LibreQoS APT repo at https://repo.libreqos.com." echo "The hotfix installer now offers to schedule a reboot after it finishes." -- knotmirror 0.0.1 From 85fe3db2b2ca478c079c6acf92f7d81a91dfcd40 Mon Sep 17 00:00:00 2001 From: rchac Date: Fri, 1 May 2026 15:52:32 +0000 Subject: [PATCH 34/51] changes --- docs-es/v2.0/TechnicalDocs/troubleshooting.md | 2 ++ docs-es/v2.0/troubleshooting-es.md | 2 ++ docs/v2.0/troubleshooting.md | 2 ++ src/build_rust.sh | 5 +++-- 4 files changed, 9 insertions(+), 2 deletions(-) diff --git a/docs-es/v2.0/TechnicalDocs/troubleshooting.md b/docs-es/v2.0/TechnicalDocs/troubleshooting.md index 31155216..c53a57f6 100644 --- a/docs-es/v2.0/TechnicalDocs/troubleshooting.md +++ b/docs-es/v2.0/TechnicalDocs/troubleshooting.md @@ -67,6 +67,8 @@ sudo dpkg --configure -a sudo systemctl restart lqosd lqos_scheduler ``` +Git-based installs must rebuild the virtual environment before restarting `lqos_scheduler` after pulling updates that change the service file. If systemd reports `status=203/EXEC`, rebuild the virtual environment with the command above and restart `lqos_scheduler`. + ### Python ModuleNotFoundError in older Ubuntu 24.04 installs ``` pip uninstall binpacking --break-system-packages --yes diff --git a/docs-es/v2.0/troubleshooting-es.md b/docs-es/v2.0/troubleshooting-es.md index 1afcd98e..2f661992 100644 --- a/docs-es/v2.0/troubleshooting-es.md +++ b/docs-es/v2.0/troubleshooting-es.md @@ -120,6 +120,8 @@ sudo dpkg --configure -a sudo systemctl restart lqosd lqos_scheduler ``` +Las instalaciones basadas en git deben reconstruir el entorno virtual antes de reiniciar `lqos_scheduler` después de actualizar cambios que modifiquen el archivo de servicio. Si systemd informa `status=203/EXEC`, reconstruya el entorno virtual con el comando anterior y reinicie `lqos_scheduler`. + Si el scheduler falla inmediatamente después de un reinicio con un mensaje como `Socket (typically /run/lqos/bus) not found`, eso indica que `lqosd` todavía no había terminado de enlazar el bus local. Los builds actuales esperan brevemente la disponibilidad del bus al arrancar el scheduler en lugar de abortar de inmediato, por lo que ya no deberían aparecer panics repetidos de arranque tras un reinicio. ### El estado del scheduler en WebUI aparece no saludable diff --git a/docs/v2.0/troubleshooting.md b/docs/v2.0/troubleshooting.md index edb1f60d..8ef8588f 100644 --- a/docs/v2.0/troubleshooting.md +++ b/docs/v2.0/troubleshooting.md @@ -224,6 +224,8 @@ sudo dpkg --configure -a sudo systemctl restart lqosd lqos_scheduler ``` +Git-based installs must rebuild the virtual environment before restarting `lqos_scheduler` after pulling updates that change the service file. If systemd reports `status=203/EXEC`, rebuild the virtual environment with the command above and restart `lqos_scheduler`. + For manual shaping tests, use the same interpreter as the service: ```bash diff --git a/src/build_rust.sh b/src/build_rust.sh index 234dc8fe..3182e4cb 100755 --- a/src/build_rust.sh +++ b/src/build_rust.sh @@ -226,6 +226,9 @@ rebuild_python_venv() { } SERVICE_UNITS_UPDATED=0 + +rebuild_python_venv + refresh_service_unit lqosd refresh_service_unit lqos_scheduler refresh_service_unit lqos_api @@ -251,8 +254,6 @@ if service_unit_exists lqos_netplan_helper; then fi fi -rebuild_python_venv - if hotfix_blocks_service_restart; then echo "Ubuntu 24.04 systemd hotfix is still required. Skipping LibreQoS service restarts." echo "Install it with: sudo ./systemd_hotfix.sh install" -- knotmirror 0.0.1 From f9dc6e0047f6b407e805aad195e3d9cf64454170 Mon Sep 17 00:00:00 2001 From: rchac Date: Fri, 1 May 2026 15:58:07 +0000 Subject: [PATCH 35/51] changes --- docs-es/v2.0/TechnicalDocs/troubleshooting.md | 2 +- docs-es/v2.0/troubleshooting-es.md | 2 +- docs/v2.0/troubleshooting.md | 2 +- src/build_rust.sh | 13 ++++++++++++- 4 files changed, 15 insertions(+), 4 deletions(-) diff --git a/docs-es/v2.0/TechnicalDocs/troubleshooting.md b/docs-es/v2.0/TechnicalDocs/troubleshooting.md index c53a57f6..e91e2600 100644 --- a/docs-es/v2.0/TechnicalDocs/troubleshooting.md +++ b/docs-es/v2.0/TechnicalDocs/troubleshooting.md @@ -67,7 +67,7 @@ sudo dpkg --configure -a sudo systemctl restart lqosd lqos_scheduler ``` -Git-based installs must rebuild the virtual environment before restarting `lqos_scheduler` after pulling updates that change the service file. If systemd reports `status=203/EXEC`, rebuild the virtual environment with the command above and restart `lqos_scheduler`. +Git-based installs should use `./build_rust.sh` after pulling updates. It rebuilds the virtual environment before refreshing service files or restarting services. If systemd reports `status=203/EXEC`, rebuild the virtual environment with the command above and restart `lqos_scheduler`. ### Python ModuleNotFoundError in older Ubuntu 24.04 installs ``` diff --git a/docs-es/v2.0/troubleshooting-es.md b/docs-es/v2.0/troubleshooting-es.md index 2f661992..c9883eec 100644 --- a/docs-es/v2.0/troubleshooting-es.md +++ b/docs-es/v2.0/troubleshooting-es.md @@ -120,7 +120,7 @@ sudo dpkg --configure -a sudo systemctl restart lqosd lqos_scheduler ``` -Las instalaciones basadas en git deben reconstruir el entorno virtual antes de reiniciar `lqos_scheduler` después de actualizar cambios que modifiquen el archivo de servicio. Si systemd informa `status=203/EXEC`, reconstruya el entorno virtual con el comando anterior y reinicie `lqos_scheduler`. +Las instalaciones basadas en git deben usar `./build_rust.sh` después de actualizar. Ese script reconstruye el entorno virtual antes de actualizar los archivos de servicio o reiniciar servicios. Si systemd informa `status=203/EXEC`, reconstruya el entorno virtual con el comando anterior y reinicie `lqos_scheduler`. Si el scheduler falla inmediatamente después de un reinicio con un mensaje como `Socket (typically /run/lqos/bus) not found`, eso indica que `lqosd` todavía no había terminado de enlazar el bus local. Los builds actuales esperan brevemente la disponibilidad del bus al arrancar el scheduler en lugar de abortar de inmediato, por lo que ya no deberían aparecer panics repetidos de arranque tras un reinicio. diff --git a/docs/v2.0/troubleshooting.md b/docs/v2.0/troubleshooting.md index 8ef8588f..e4da9fc3 100644 --- a/docs/v2.0/troubleshooting.md +++ b/docs/v2.0/troubleshooting.md @@ -224,7 +224,7 @@ sudo dpkg --configure -a sudo systemctl restart lqosd lqos_scheduler ``` -Git-based installs must rebuild the virtual environment before restarting `lqos_scheduler` after pulling updates that change the service file. If systemd reports `status=203/EXEC`, rebuild the virtual environment with the command above and restart `lqos_scheduler`. +Git-based installs should use `./build_rust.sh` after pulling updates. It rebuilds the virtual environment before refreshing service files or restarting services. If systemd reports `status=203/EXEC`, rebuild the virtual environment with the command above and restart `lqos_scheduler`. For manual shaping tests, use the same interpreter as the service: diff --git a/src/build_rust.sh b/src/build_rust.sh index 3182e4cb..b6c92891 100755 --- a/src/build_rust.sh +++ b/src/build_rust.sh @@ -22,6 +22,8 @@ do esac done +VENV_PYTHON="/opt/libreqos/venv/bin/python" + # Check Pre-Requisites sudo apt install python3-pip python3-venv clang gcc gcc-multilib llvm libelf-dev git nano curl screen llvm pkg-config linux-tools-common linux-tools-`uname -r` libbpf-dev libssl-dev curl @@ -222,7 +224,16 @@ rebuild_python_venv() { fi echo "Rebuilding /opt/libreqos/venv before restarting Python services." - sudo "$script_path" + if ! sudo "$script_path"; then + echo "Failed to rebuild /opt/libreqos/venv. Skipping service refresh/restarts." + exit 1 + fi + + if [ ! -x "$VENV_PYTHON" ]; then + echo "Expected $VENV_PYTHON to exist and be executable after rebuilding the Python venv." + echo "Skipping service refresh/restarts." + exit 1 + fi } SERVICE_UNITS_UPDATED=0 -- knotmirror 0.0.1 From a426c9d4d88c53245d31cb8c5c2514da46699a86 Mon Sep 17 00:00:00 2001 From: rchac Date: Fri, 1 May 2026 15:59:56 +0000 Subject: [PATCH 36/51] changes --- src/bin/rebuild_python_venv.sh | 24 +++++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/src/bin/rebuild_python_venv.sh b/src/bin/rebuild_python_venv.sh index 247ef4db..b3909d11 100755 --- a/src/bin/rebuild_python_venv.sh +++ b/src/bin/rebuild_python_venv.sh @@ -2,23 +2,37 @@ set -euo pipefail VENV_DIR="/opt/libreqos/venv" -REQUIREMENTS="/opt/libreqos/src/requirements.txt" -CONSTRAINTS="/opt/libreqos/src/deb-requirements-constraints.txt" +REQUIREMENTS="" +CONSTRAINTS="" if [ "$(id -u)" -ne 0 ]; then echo "rebuild_python_venv.sh must be run as root." >&2 exit 1 fi -if [ ! -f "$REQUIREMENTS" ]; then - echo "LibreQoS Python requirements file not found: $REQUIREMENTS" >&2 +for candidate in /opt/libreqos/src/requirements.txt /opt/libreqos/requirements.txt; do + if [ -f "$candidate" ]; then + REQUIREMENTS="$candidate" + break + fi +done + +if [ -z "$REQUIREMENTS" ]; then + echo "LibreQoS Python requirements file not found in /opt/libreqos/src or /opt/libreqos." >&2 exit 1 fi +for candidate in /opt/libreqos/src/deb-requirements-constraints.txt /opt/libreqos/deb-requirements-constraints.txt; do + if [ -s "$candidate" ]; then + CONSTRAINTS="$candidate" + break + fi +done + python3 -m venv --clear "$VENV_DIR" "$VENV_DIR/bin/python" -m pip install --upgrade pip -if [ -s "$CONSTRAINTS" ]; then +if [ -n "$CONSTRAINTS" ]; then "$VENV_DIR/bin/python" -m pip install --upgrade -c "$CONSTRAINTS" -r "$REQUIREMENTS" else "$VENV_DIR/bin/python" -m pip install --upgrade -r "$REQUIREMENTS" -- knotmirror 0.0.1 From 3cd14ed4a627390be84af624321138a23e59bb68 Mon Sep 17 00:00:00 2001 From: rchac Date: Fri, 1 May 2026 16:03:16 +0000 Subject: [PATCH 37/51] changes --- src/build_rust.sh | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/build_rust.sh b/src/build_rust.sh index b6c92891..36f15f02 100755 --- a/src/build_rust.sh +++ b/src/build_rust.sh @@ -275,8 +275,9 @@ else echo "lqosd is active as a service. Restarting it. You may need to enter your sudo password." sudo systemctl restart lqosd fi - if service_is_active lqos_scheduler; then - echo "lqos_scheduler is active as a service. Restarting it. You may need to enter your sudo password." + if service_is_active lqos_scheduler || service_is_failed lqos_scheduler || service_is_enabled lqos_scheduler; then + echo "lqos_scheduler is installed as an active, failed, or enabled service. Restarting it. You may need to enter your sudo password." + sudo systemctl reset-failed lqos_scheduler || true sudo systemctl restart lqos_scheduler fi if service_is_active lqos_api || service_is_failed lqos_api || service_is_enabled lqos_api; then -- knotmirror 0.0.1 From e5a721b4ec258f3f7f8a91a404b875e076e60aa6 Mon Sep 17 00:00:00 2001 From: rchac Date: Fri, 1 May 2026 21:08:44 +0000 Subject: [PATCH 38/51] changes --- src/rust/lqos_python/src/device_weights.rs | 89 +++++++++++++++++-- src/rust/lqos_queue_tracker/src/queue_diff.rs | 76 ++++++++++++++-- .../node_manager/js_build/src/pubsub/ws.js | 75 ++++++++++++---- src/rust/lqosd/src/node_manager/ws.rs | 40 ++++++--- 4 files changed, 235 insertions(+), 45 deletions(-) diff --git a/src/rust/lqos_python/src/device_weights.rs b/src/rust/lqos_python/src/device_weights.rs index 770975ae..7d0076ae 100644 --- a/src/rust/lqos_python/src/device_weights.rs +++ b/src/rust/lqos_python/src/device_weights.rs @@ -16,7 +16,13 @@ use lqos_bus::{BusRequest, BusResponse}; use lqos_config::{ShapedDevice, load_config}; use pyo3::pyclass; use serde::{Deserialize, Serialize}; -use std::time::Duration; +use std::{ + sync::{Mutex, OnceLock}, + time::{Duration, Instant}, +}; + +const REMOTE_WEIGHT_SUCCESS_TTL: Duration = Duration::from_secs(300); +const REMOTE_WEIGHT_FAILURE_BACKOFF: Duration = Duration::from_secs(300); /// This struct is used to send a request to the Long Term Stats API #[derive(Serialize, Deserialize)] @@ -30,7 +36,7 @@ pub struct DeviceWeightRequest { /// This struct is used to receive a response from the Long Term Stats API /// It contains the circuit_id and the weight of the device -#[derive(Serialize, Deserialize, Debug)] +#[derive(Serialize, Deserialize, Debug, Clone)] #[pyclass] pub struct DeviceWeightResponse { #[pyo3(get)] @@ -39,6 +45,57 @@ pub struct DeviceWeightResponse { pub weight: i64, } +#[derive(Clone)] +struct CachedRemoteWeights { + fetched_at: Instant, + weights: Vec, +} + +#[derive(Default)] +struct RemoteWeightCache { + last_success: Option, + last_failure: Option, +} + +fn remote_weight_cache() -> &'static Mutex { + static CACHE: OnceLock> = OnceLock::new(); + CACHE.get_or_init(|| Mutex::new(RemoteWeightCache::default())) +} + +fn cached_remote_weights() -> Option> { + let cache = remote_weight_cache().lock().ok()?; + let cached = cache.last_success.as_ref()?; + if cached.fetched_at.elapsed() <= REMOTE_WEIGHT_SUCCESS_TTL { + return Some(cached.weights.clone()); + } + None +} + +fn recent_remote_weight_failure() -> bool { + let Ok(cache) = remote_weight_cache().lock() else { + return false; + }; + cache + .last_failure + .is_some_and(|failed_at| failed_at.elapsed() <= REMOTE_WEIGHT_FAILURE_BACKOFF) +} + +fn remember_remote_weight_success(weights: &[DeviceWeightResponse]) { + if let Ok(mut cache) = remote_weight_cache().lock() { + cache.last_success = Some(CachedRemoteWeights { + fetched_at: Instant::now(), + weights: weights.to_vec(), + }); + cache.last_failure = None; + } +} + +fn remember_remote_weight_failure() { + if let Ok(mut cache) = remote_weight_cache().lock() { + cache.last_failure = Some(Instant::now()); + } +} + /// This function is used to get the device weights from the Long Term Stats API fn get_weights_from_lts( org_key: &str, @@ -147,10 +204,28 @@ pub(crate) fn get_weights_rust() -> Result> { let duration_seconds = 60 * 60 * 24; // 1 day let percentile = 0.95; - eprintln!("Getting weights from Insight"); - let weights = get_weights_from_lts(&org_key, &node_id, start, duration_seconds, percentile); - if let Ok(weights) = weights { - eprintln!("Retrieved {} weights from Insight", weights.len()); + let remote_weights = if let Some(weights) = cached_remote_weights() { + eprintln!("Using cached Insight weights"); + Some(weights) + } else if recent_remote_weight_failure() { + eprintln!("Skipping Insight weight fetch; recent request failed"); + None + } else { + eprintln!("Getting weights from Insight"); + match get_weights_from_lts(&org_key, &node_id, start, duration_seconds, percentile) { + Ok(weights) => { + eprintln!("Retrieved {} weights from Insight", weights.len()); + remember_remote_weight_success(&weights); + Some(weights) + } + Err(err) => { + remember_remote_weight_failure(); + eprintln!("Failed to get weights from Insight: {:?}", err); + None + } + } + }; + if let Some(weights) = remote_weights { // Merge them for weight in weights.iter() { if let Some(existing) = shaped_devices_weights @@ -160,8 +235,6 @@ pub(crate) fn get_weights_rust() -> Result> { existing.weight = weight.weight; } } - } else { - eprintln!("Failed to get weights from Insight: {:?}", weights); } } diff --git a/src/rust/lqos_queue_tracker/src/queue_diff.rs b/src/rust/lqos_queue_tracker/src/queue_diff.rs index c343c0e0..d5e3c207 100644 --- a/src/rust/lqos_queue_tracker/src/queue_diff.rs +++ b/src/rust/lqos_queue_tracker/src/queue_diff.rs @@ -1,7 +1,7 @@ use crate::queue_types::QueueType; use serde::Serialize; use thiserror::Error; -use tracing::error; +use tracing::warn; #[derive(Debug, Clone, Serialize)] pub enum QueueDiff { @@ -21,27 +21,46 @@ pub(crate) fn make_queue_diff( QueueType::FqCodel(..) => match current { QueueType::FqCodel(..) => Ok(fq_codel_diff(previous, current)?), _ => { - error!( - "Queue diffs are not implemented for FqCodel to {:?}", - current + warn!( + previous = queue_kind(previous), + current = queue_kind(current), + "Queue type changed; resetting queue diff sample" ); - Err(QueueDiffError::NotImplemented) + Ok(QueueDiff::None) } }, QueueType::Cake(..) => match current { QueueType::Cake(..) => Ok(cake_diff(previous, current)?), _ => { - error!("Queue diffs are not implemented for Cake to {:?}", current); - Err(QueueDiffError::NotImplemented) + warn!( + previous = queue_kind(previous), + current = queue_kind(current), + "Queue type changed; resetting queue diff sample" + ); + Ok(QueueDiff::None) } }, _ => { - error!("Queue diffs are not implemented for {:?}", current); - Err(QueueDiffError::NotImplemented) + warn!( + previous = queue_kind(previous), + current = queue_kind(current), + "Queue diff unavailable for queue type; resetting queue diff sample" + ); + Ok(QueueDiff::None) } } } +fn queue_kind(queue: &QueueType) -> &'static str { + match queue { + QueueType::FqCodel(_) => "fq_codel", + QueueType::Cake(_) => "cake", + QueueType::Mq(_) => "mq", + QueueType::Htb(_) => "htb", + QueueType::ClsAct => "clsact", + } +} + #[derive(Serialize, Clone, Debug)] pub struct CakeDiff { pub bytes: u64, @@ -116,3 +135,42 @@ fn fq_codel_diff(previous: &QueueType, current: &QueueType) -> Result 0) { @@ -339,7 +347,7 @@ export class WsClient { dashboardWsInteresting("unsubscribe-wire-interesting", [channel], { desiredChannels: Array.from(this.desiredChannels.keys()), }); - this.ws.send(encoder.encode({ Unsubscribe: { channel } })); + this._sendControl({ Unsubscribe: { channel } }); } } else { this.desiredChannels.set(channel, current - 1); @@ -355,11 +363,16 @@ export class WsClient { if (!this.ws) { this.connect(); } - if (!this.handshake_done) { + if (!this.handshake_done || !this._socketIsOpen()) { this.pending.push(normalized); + if (this.handshake_done && this.ws && !this._socketIsOpen()) { + this._retireSocket(); + } return; } - this.ws.send(encoder.encode(normalized)); + if (!this._sendControl(normalized)) { + this.pending.push(normalized); + } } on(event_name, handler) { @@ -406,28 +419,58 @@ export class WsClient { dashboardWsDebug("handshake-complete", { desiredChannels: Array.from(this.desiredChannels.keys()), }); - this.ws.send( - encoder.encode({ - HelloReply: { - ack: ACK_TEXT, - token: get_user_token(), - }, - }), - ); - for (let i = 0; i < this.pending.length; i++) { - this.ws.send(encoder.encode(this.pending[i])); + if (!this._sendControl({ + HelloReply: { + ack: ACK_TEXT, + token: get_user_token(), + }, + })) { + return; } + const pending = this.pending; this.pending = []; + for (let i = 0; i < pending.length; i++) { + if (!this._sendControl(pending[i])) { + this.pending = pending.slice(i).concat(this.pending); + return; + } + } for (const channel of this.desiredChannels.keys()) { dashboardWsInteresting("subscribe-wire-interesting", [channel], { desiredChannels: Array.from(this.desiredChannels.keys()), fromHandshake: true, }); - this.ws.send(encoder.encode({ Subscribe: { channel } })); + if (!this._sendControl({ Subscribe: { channel } })) { + return; + } } this.reconnectDelayMs = 1000; } + _socketIsOpen() { + return this.ws && this.ws.readyState === WebSocket.OPEN; + } + + _retireSocket() { + this._dropSocket("retire-socket"); + this._scheduleReconnect(); + } + + _sendControl(request_obj) { + if (!this._socketIsOpen()) { + this._retireSocket(); + return false; + } + try { + this.ws.send(encoder.encode(request_obj)); + return true; + } catch (err) { + console.warn("Websocket send failed; reconnecting", err); + this._retireSocket(); + return false; + } + } + _dispatch(msg) { if (!msg || !msg.event) { return; diff --git a/src/rust/lqosd/src/node_manager/ws.rs b/src/rust/lqosd/src/node_manager/ws.rs index 4e359bd8..6b5bb6eb 100644 --- a/src/rust/lqosd/src/node_manager/ws.rs +++ b/src/rust/lqosd/src/node_manager/ws.rs @@ -55,6 +55,7 @@ mod ticker; const WS_VERSION: &str = include_str!("../../../../VERSION_STRING"); const HANDSHAKE_TIMEOUT_SECS: u64 = 10; +const REQUEST_TIMEOUT_SECS: u64 = 15; /// Provides an Axum router for the websocket system. Exposes a single /ws route that supports /// pubsub subscriptions and private commands. @@ -182,19 +183,29 @@ async fn handle_socket( // Received a websocket message match inbound { Some(Ok(msg)) => { - let should_close = receive_channel_message( - msg, - channels.clone(), - tx.clone(), - &mut subscribed_channels, - &mut handshake_complete, - &mut WsRequestState { - private_state: &mut private_state, - login: &mut login, - shaper_query: shaper_query.clone(), - }, + let should_close = match tokio::time::timeout( + std::time::Duration::from_secs(REQUEST_TIMEOUT_SECS), + receive_channel_message( + msg, + channels.clone(), + tx.clone(), + &mut subscribed_channels, + &mut handshake_complete, + &mut WsRequestState { + private_state: &mut private_state, + login: &mut login, + shaper_query: shaper_query.clone(), + }, + ), ) - .await; + .await + { + Ok(should_close) => should_close, + Err(_) => { + warn!("Websocket request timed out; closing connection"); + true + } + }; if should_close { break; } @@ -212,6 +223,11 @@ async fn handle_socket( } } } + for channel in subscribed_channels.drain() { + channels.unsubscribe(channel, tx.clone()).await; + } + drop(private_state); + drop(tx); outbound_handle.abort(); let _ = outbound_handle.await; info!("Websocket disconnected"); -- knotmirror 0.0.1 From 45a641a3595c84181067e9903b3a139e4da60370 Mon Sep 17 00:00:00 2001 From: rchac Date: Sun, 3 May 2026 19:21:43 -0600 Subject: [PATCH 39/51] changes --- .../v2.0/libreqos-backend-architecture-es.md | 9 +- docs-es/v2.0/troubleshooting-es.md | 2 +- docs/v2.0/libreqos-backend-architecture.md | 7 +- docs/v2.0/troubleshooting.md | 2 +- src/rust/lqos_bakery/src/lib.rs | 222 ++++++++++++++++-- src/rust/lqos_bakery/src/utils.rs | 2 +- src/rust/lqos_python/src/lib.rs | 12 +- 7 files changed, 214 insertions(+), 42 deletions(-) diff --git a/docs-es/v2.0/libreqos-backend-architecture-es.md b/docs-es/v2.0/libreqos-backend-architecture-es.md index 741bceff..1ca79e39 100644 --- a/docs-es/v2.0/libreqos-backend-architecture-es.md +++ b/docs-es/v2.0/libreqos-backend-architecture-es.md @@ -270,14 +270,15 @@ flowchart TD 3. Esperar mayor riesgo cuando coinciden muchos circuitos y muchos cambios estructurales. 4. Diseñar la cadencia operativa para priorizar cambios incrementalmente seguros. -### 7.4 Guardrails de seguridad para recargas completas +### 7.4 Salvaguardas de seguridad para recargas completas -Las recargas completas actuales de Bakery aplican dos verificaciones conservadoras de seguridad antes y durante reconstrucciones grandes de colas: +Las recargas completas actuales de Bakery aplican verificaciones conservadoras de seguridad antes y durante reconstrucciones grandes de colas: 1. Un preflight de qdisc estima los qdisc planificados por interfaz y además separa qdisc de infraestructura, hojas `cake` y hojas `fq_codel`. 2. Ese mismo preflight aplica una proyección conservadora de memoria y bloquea de forma estricta las recargas completas claramente inseguras antes de arrancar `tc -batch`. -3. Durante la aplicación chunked de una recarga completa, Bakery vuelve a revisar la memoria del host en los límites de chunk y aborta el resto de la aplicación si la memoria disponible cae por debajo de su piso de seguridad. -4. Estos guardrails están sesgados intencionalmente hacia falsos positivos en recargas grandes para fallar temprano con diagnósticos en lugar de entrar en una espiral OOM. +3. El piso de memoria de Bakery escala con la RAM del host: mantiene al menos 2 GiB disponibles, o un octavo de la RAM total en sistemas más grandes. +4. Durante la aplicación por fragmentos de una recarga completa, Bakery vuelve a revisar la memoria del host en los límites de cada fragmento y aborta el resto de la aplicación si la memoria disponible cae por debajo del piso escalado más la memoria qdisc proyectada para el lote. +5. Estas salvaguardas están sesgadas intencionalmente hacia falsos positivos en recargas grandes para fallar temprano con diagnósticos en lugar de entrar en una espiral OOM. ## 8) Límites de Diseño para Operadores diff --git a/docs-es/v2.0/troubleshooting-es.md b/docs-es/v2.0/troubleshooting-es.md index c9883eec..c5daff47 100644 --- a/docs-es/v2.0/troubleshooting-es.md +++ b/docs-es/v2.0/troubleshooting-es.md @@ -253,7 +253,7 @@ WebUI muestra códigos legibles por máquina para triage rápido. | `MAPPED_CIRCUIT_LIMIT` | Bakery está forzando límite de circuitos mapeados. | Estado de licencia Insight y `journalctl -u lqosd` con requested/allowed/dropped. | Reducir circuitos mapeados o actualizar licencia/límites. | | `TC_U16_OVERFLOW` | IDs minor de clases/colas excedieron rango u16 de tc en una cola CPU. | `journalctl -u lqos_scheduler -u lqosd`, profundidad topológica y distribución por colas. | Aumentar paralelismo de colas y/o simplificar/rebalancear jerarquía. | | `TC_QDISC_CAPACITY` | Los qdisc autoasignados planificados exceden el presupuesto seguro por interfaz o el preflight conservador de seguridad de memoria de Bakery antes de aplicar. | Conteos estimados por interfaz, desglose por tipo de qdisc y campos de memoria en el contexto del urgent issue, `journalctl -u lqos_scheduler -u lqosd`, configuración `on_a_stick` y `monitor_only`. | Reducir la carga planificada de qdisc para esta ejecución (por ejemplo menos circuitos/dispositivos en la forma de prueba) antes de reintentar; no confiar en una aplicación parcial. | -| `BAKERY_MEMORY_GUARD` | Un full reload chunked de Bakery fue detenido a mitad de aplicación porque la memoria disponible del host cayó por debajo del piso de seguridad. | `journalctl -u lqosd`, memoria disponible/total en el contexto del urgent issue y progreso reciente de aplicación de Bakery. | Tratar la ejecución como fallida, reducir presión de memoria o huella de colas y reintentar solo cuando el host esté estable. | +| `BAKERY_MEMORY_GUARD` | Una recarga completa por fragmentos de Bakery fue detenida a mitad de aplicación porque la memoria disponible del host cayó por debajo del piso de seguridad escalado. | `journalctl -u lqosd`, memoria disponible/total en el contexto del urgent issue y progreso reciente de aplicación de Bakery. | Tratar la ejecución como fallida, reducir presión de memoria o huella de colas y reintentar solo cuando el host esté estable. | | `XDP_IP_MAPPING_CAPACITY` | Los mapeos IP requeridos exceden la capacidad actual del mapa XDP en el kernel. | Forma de `ShapedDevices.csv`, mezcla IPv4/IPv6, supuesto de un dispositivo frente a varios dispositivos, `journalctl -u lqos_scheduler -u lqosd`. | Reducir mapeos requeridos de inmediato (por ejemplo menos dispositivos o prueba IPv4-only), o aumentar la capacidad del mapa del kernel en un cambio coordinado. | | `XDP_IP_MAPPING_APPLY_FAILED` | Uno o más inserts de mapeo IP fallaron durante la aplicación. | `journalctl -u lqos_scheduler -u lqosd` para ejemplos resumidos y conteos de fallo. | Corregir la causa del fallo y volver a ejecutar; no confiar en shaping parcial. | diff --git a/docs/v2.0/libreqos-backend-architecture.md b/docs/v2.0/libreqos-backend-architecture.md index 13e58fbb..195317b7 100644 --- a/docs/v2.0/libreqos-backend-architecture.md +++ b/docs/v2.0/libreqos-backend-architecture.md @@ -343,12 +343,13 @@ This retained-root strategy reduces avoidable root-level churn, while still pref ### 8.6 Full-reload safety guards -Current Bakery full reloads apply two conservative safety checks before and during large queue rebuilds: +Current Bakery full reloads apply conservative safety checks before and during large queue rebuilds: 1. A qdisc preflight estimates planned qdiscs per interface and also separates infrastructure, `cake`, and `fq_codel` leaf qdiscs. 2. That same preflight applies a conservative memory forecast and hard-blocks clearly unsafe full reloads before `tc -batch` starts. -3. During chunked full reload apply, Bakery re-checks host memory at chunk boundaries and aborts the remaining apply if available memory drops below its safety floor. -4. These guards are intentionally biased toward false positives on large reloads so the system fails early with diagnostics instead of spiraling into an OOM event. +3. Bakery's memory floor scales with host RAM: it keeps at least 2 GiB available, or one eighth of total RAM on larger systems. +4. During chunked full reload apply, Bakery re-checks host memory at chunk boundaries and aborts the remaining apply if available memory drops below the scaled floor plus the projected qdisc memory for the batch. +5. These guards are intentionally biased toward false positives on large reloads so the system fails early with diagnostics instead of spiraling into an OOM event. ### 8.7 Runtime safety model diff --git a/docs/v2.0/troubleshooting.md b/docs/v2.0/troubleshooting.md index e4da9fc3..058d56a2 100644 --- a/docs/v2.0/troubleshooting.md +++ b/docs/v2.0/troubleshooting.md @@ -330,7 +330,7 @@ WebUI urgent issues include machine-readable codes. Use them to triage quickly. | `MAPPED_CIRCUIT_LIMIT` | Bakery is enforcing a mapped-circuit limit. | Insight license status, `journalctl -u lqosd` for requested/allowed/dropped counts. | Reduce mapped circuits immediately or update license/limits. | | `TC_U16_OVERFLOW` | Queue/class minor IDs exceeded the Linux tc u16 range on a CPU queue. | `journalctl -u lqos_scheduler -u lqosd`, topology depth/queue distribution. | Increase queue count and/or simplify/rebalance hierarchy (for example with integration strategy or root promotion changes). | | `TC_QDISC_CAPACITY` | Planned auto-allocated qdiscs exceed the per-interface safe budget or Bakery's conservative memory-safety preflight before apply. | Estimated per-interface qdisc counts, qdisc-kind breakdown, and memory fields in the urgent issue context, `journalctl -u lqos_scheduler -u lqosd`, `on_a_stick` and `queue_mode` config. | Reduce the planned qdisc load for this run (for example fewer circuits/devices in the test shape) before retrying; do not trust partial apply. | -| `BAKERY_MEMORY_GUARD` | A chunked Bakery full reload was stopped mid-apply because available host memory fell below the safety floor. | `journalctl -u lqosd`, available/total memory in the urgent issue context, and recent Bakery apply progress. | Treat the run as failed, reduce memory pressure or queue footprint, and retry only after the host is stable. | +| `BAKERY_MEMORY_GUARD` | A chunked Bakery full reload was stopped mid-apply because available host memory fell below the scaled safety floor. | `journalctl -u lqosd`, available/total memory in the urgent issue context, and recent Bakery apply progress. | Treat the run as failed, reduce memory pressure or queue footprint, and retry only after the host is stable. | | `XDP_IP_MAPPING_CAPACITY` | Required IP mappings exceed the current XDP kernel map capacity. | `ShapedDevices.csv` row shape, IPv4/IPv6 mix, one-device-vs-many-device assumptions, `journalctl -u lqos_scheduler -u lqosd`. | Reduce required mappings immediately (for example fewer devices or IPv4-only test shape), or raise kernel map capacity in a coordinated change. | | `XDP_IP_MAPPING_APPLY_FAILED` | One or more IP mapping inserts failed during apply. | `journalctl -u lqos_scheduler -u lqosd` for summarized failure examples and counts. | Fix the underlying mapping failure, then rerun; do not trust partial shaping. | diff --git a/src/rust/lqos_bakery/src/lib.rs b/src/rust/lqos_bakery/src/lib.rs index 9264b986..7d4c34f1 100644 --- a/src/rust/lqos_bakery/src/lib.rs +++ b/src/rust/lqos_bakery/src/lib.rs @@ -1513,7 +1513,14 @@ pub const FQ_CODEL_QDISC_ESTIMATED_MEMORY_BYTES: u64 = 64 * 1024; /// substantially exceeding the earlier heuristic during busy periods. pub const CAKE_QDISC_ESTIMATED_MEMORY_BYTES: u64 = 512 * 1024; /// Minimum memory headroom Bakery tries to leave unused after a projected or in-flight apply. -pub const BAKERY_MEMORY_GUARD_MIN_AVAILABLE_BYTES: u64 = 768 * 1024 * 1024; +pub const BAKERY_MEMORY_GUARD_MIN_AVAILABLE_BYTES: u64 = 2 * 1024 * 1024 * 1024; +/// Divisor used to scale Bakery's memory guard floor with installed RAM. +pub const BAKERY_MEMORY_GUARD_TOTAL_RAM_DIVISOR: u64 = 8; + +/// Returns Bakery's effective memory guard floor for a host with `total_bytes` RAM. +pub fn bakery_memory_guard_min_available_bytes(total_bytes: u64) -> u64 { + BAKERY_MEMORY_GUARD_MIN_AVAILABLE_BYTES.max(total_bytes / BAKERY_MEMORY_GUARD_TOTAL_RAM_DIVISOR) +} /// Maximum number of mapped circuits allowed without Insight. const DEFAULT_MAPPED_CIRCUITS_LIMIT: usize = 1000; /// Minimum interval between repeated mapped-circuit-limit urgent issues. @@ -2055,22 +2062,69 @@ fn telemetry_state() -> &'static RwLock { BAKERY_TELEMETRY.get_or_init(|| RwLock::new(BakeryTelemetryState::default())) } +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum TcCommandType { + Class, + Qdisc, +} + +fn tc_command_type(argv: &[String]) -> Option { + match argv.first()?.as_str() { + "class" => Some(TcCommandType::Class), + "qdisc" => Some(TcCommandType::Qdisc), + _ => None, + } +} + fn count_tc_command_types(commands: &[Vec]) -> (usize, usize, usize) { let total = commands.len(); let mut class_count = 0usize; let mut qdisc_count = 0usize; for argv in commands { - if let Some(kind) = argv.first() { - match kind.as_str() { - "class" => class_count += 1, - "qdisc" => qdisc_count += 1, - _ => {} - } + match tc_command_type(argv) { + Some(TcCommandType::Class) => class_count += 1, + Some(TcCommandType::Qdisc) => qdisc_count += 1, + None => {} } } (total, class_count, qdisc_count) } +fn count_tc_command_types_and_estimate_qdisc_memory( + commands: &[Vec], +) -> (usize, usize, usize, u64) { + let total = commands.len(); + let mut class_count = 0usize; + let mut qdisc_count = 0usize; + let mut estimated_qdisc_memory_bytes = 0u64; + let mut seen_qdiscs = HashSet::new(); + + for argv in commands { + match tc_command_type(argv) { + Some(TcCommandType::Class) => class_count += 1, + Some(TcCommandType::Qdisc) => qdisc_count += 1, + None => {} + } + + let Some(qdisc_identity) = planned_qdisc_identity(argv) else { + continue; + }; + if !seen_qdiscs.insert(qdisc_identity) { + continue; + } + let kind = planned_qdisc_kind(argv).unwrap_or(PlannedQdiscKind::Infra); + estimated_qdisc_memory_bytes = + estimated_qdisc_memory_bytes.saturating_add(qdisc_kind_estimated_memory_bytes(kind)); + } + + ( + total, + class_count, + qdisc_count, + estimated_qdisc_memory_bytes, + ) +} + fn push_bakery_event(event: &str, status: &str, summary: String) { push_bakery_event_with_site(event, status, None, summary); } @@ -2505,6 +2559,8 @@ pub struct QdiscBudgetEstimate { pub estimated_total_memory_bytes: u64, /// Current host memory snapshot used for preflight, if available. pub memory_snapshot: Option, + /// Effective memory floor used for the memory preflight. + pub memory_guard_min_available_bytes: u64, /// Whether the memory preflight passed. pub memory_ok: bool, } @@ -2649,10 +2705,14 @@ pub fn estimate_full_reload_auto_qdisc_budget( acc.saturating_add(detail.estimated_memory_bytes) }); let memory_snapshot = read_memory_snapshot().ok(); + let memory_guard_min_available_bytes = memory_snapshot + .as_ref() + .map(|snapshot| bakery_memory_guard_min_available_bytes(snapshot.total_bytes)) + .unwrap_or(BAKERY_MEMORY_GUARD_MIN_AVAILABLE_BYTES); let memory_ok = memory_snapshot.as_ref().is_none_or(|snapshot| { snapshot .available_bytes - .saturating_sub(BAKERY_MEMORY_GUARD_MIN_AVAILABLE_BYTES) + .saturating_sub(memory_guard_min_available_bytes) >= estimated_total_memory_bytes }); @@ -2663,6 +2723,7 @@ pub fn estimate_full_reload_auto_qdisc_budget( hard_limit: HARD_QDISC_HANDLE_LIMIT_PER_INTERFACE, estimated_total_memory_bytes, memory_snapshot, + memory_guard_min_available_bytes, memory_ok, } } @@ -3889,16 +3950,26 @@ fn maybe_emit_mapped_circuit_limit_urgent(stats: &MappedLimitStats) { }); } -fn maybe_emit_memory_guard_urgent(summary: &str) { +fn maybe_emit_memory_guard_urgent( + summary: &str, + memory_guard_required_available_bytes: u64, + estimated_qdisc_memory_bytes: u64, +) { if !summary.contains("Bakery memory guard stopped") { return; } let message = summary.to_string(); let context = read_memory_snapshot().ok().map(|snapshot| { + let memory_guard_floor_bytes = + bakery_memory_guard_min_available_bytes(snapshot.total_bytes); format!( - "{{\"available_bytes\":{},\"total_bytes\":{},\"memory_guard_floor_bytes\":{}}}", - snapshot.available_bytes, snapshot.total_bytes, BAKERY_MEMORY_GUARD_MIN_AVAILABLE_BYTES + "{{\"available_bytes\":{},\"total_bytes\":{},\"memory_guard_floor_bytes\":{},\"estimated_qdisc_memory_bytes\":{},\"memory_guard_required_available_bytes\":{}}}", + snapshot.available_bytes, + snapshot.total_bytes, + memory_guard_floor_bytes, + estimated_qdisc_memory_bytes, + memory_guard_required_available_bytes ) }); @@ -9059,6 +9130,34 @@ fn site_commands_observed_live( }) } +fn read_optional_restore_class_snapshots( + config: &Arc, + site_label: &str, +) -> Option<( + HashMap, + HashMap, +)> { + let down_snapshot = match read_live_class_snapshot(&config.isp_interface()) { + Ok(snapshot) => snapshot, + Err(summary) => { + debug!( + "Bakery: skipping live restore shortcut for {site_label}; unable to snapshot downlink classes: {summary}" + ); + return None; + } + }; + let up_snapshot = match read_live_class_snapshot(&config.internet_interface()) { + Ok(snapshot) => snapshot, + Err(summary) => { + debug!( + "Bakery: skipping live restore shortcut for {site_label}; unable to snapshot uplink classes: {summary}" + ); + return None; + } + }; + Some((down_snapshot, up_snapshot)) +} + fn live_parent_matches(observed: Option, expected: TcHandle) -> bool { if observed == Some(expected) { return true; @@ -10593,28 +10692,27 @@ fn handle_treeguard_set_node_virtual_live( } let reversible_standby = saved_state.active_branch_hides_original_site(); - let live_restore_snapshots = if reversible_standby { - Some(( - read_live_class_snapshot(&config.isp_interface())?, - read_live_class_snapshot(&config.internet_interface())?, - )) - } else { - None - }; + let mut live_restore_snapshots = None; if !saved_state.pending_prune && let Some(cmds) = saved_state .site .to_commands(&config, ExecutionMode::Builder) { - let root_already_live = + let root_already_live = if reversible_standby { live_restore_snapshots + .get_or_insert_with(|| { + read_optional_restore_class_snapshots(&config, &site_label) + }) .as_ref() .is_some_and(|(down_snapshot, up_snapshot)| { let mut only_root = HashMap::new(); only_root.insert(site_hash, saved_state.site.clone()); site_commands_observed_live(&only_root, down_snapshot, up_snapshot) - }); + }) + } else { + false + }; if !root_already_live { let result = execute_and_record_live_change(&cmds, "TreeGuard runtime hidden site restore"); @@ -10643,8 +10741,9 @@ fn handle_treeguard_set_node_virtual_live( ) }) .collect(); - let originals_already_live = + let originals_already_live = if reversible_standby && !saved_state.saved_sites.is_empty() { live_restore_snapshots + .get_or_insert_with(|| read_optional_restore_class_snapshots(&config, &site_label)) .as_ref() .is_some_and(|(down_snapshot, up_snapshot)| { site_commands_observed_live( @@ -10652,7 +10751,10 @@ fn handle_treeguard_set_node_virtual_live( down_snapshot, up_snapshot, ) - }); + }) + } else { + false + }; if reversible_standby && originals_already_live { for (hash, command) in &saved_state.saved_sites { sites.insert(*hash, Arc::clone(command)); @@ -11037,7 +11139,12 @@ fn process_batch( let path = config.debug_state_file_path("linux_tc_rust.txt"); write_command_file(&path, &commands); let build_duration_ms = build_started.elapsed().as_millis() as u64; - let (total_tc_commands, class_commands, qdisc_commands) = count_tc_command_types(&commands); + let (total_tc_commands, class_commands, qdisc_commands, estimated_qdisc_memory_bytes) = + count_tc_command_types_and_estimate_qdisc_memory(&commands); + let memory_guard_required_available_bytes = read_memory_snapshot() + .map(|snapshot| bakery_memory_guard_min_available_bytes(snapshot.total_bytes)) + .unwrap_or(BAKERY_MEMORY_GUARD_MIN_AVAILABLE_BYTES) + .saturating_add(estimated_qdisc_memory_bytes); let total_chunks = if total_tc_commands == 0 { 0 } else { @@ -11054,7 +11161,7 @@ fn process_batch( &commands, "processing batch", FULL_RELOAD_TC_CHUNK_SIZE, - Some(BAKERY_MEMORY_GUARD_MIN_AVAILABLE_BYTES), + Some(memory_guard_required_available_bytes), |completed_tc_commands, total_tc_commands, completed_chunks, total_chunks| { update_bakery_apply_progress( Some("Applying tc command chunks"), @@ -11066,7 +11173,11 @@ fn process_batch( }, ); let summary = summarize_apply_result("processing batch", &result); - maybe_emit_memory_guard_urgent(&summary); + maybe_emit_memory_guard_urgent( + &summary, + memory_guard_required_available_bytes, + estimated_qdisc_memory_bytes, + ); BakeryFullReloadBatchResult { result, summary, @@ -13363,6 +13474,65 @@ mod tests { assert!(estimate.ok()); } + #[test] + fn bakery_memory_guard_floor_scales_with_host_ram() { + assert_eq!( + bakery_memory_guard_min_available_bytes(8 * 1024 * 1024 * 1024), + BAKERY_MEMORY_GUARD_MIN_AVAILABLE_BYTES + ); + assert_eq!( + bakery_memory_guard_min_available_bytes(64 * 1024 * 1024 * 1024), + 8 * 1024 * 1024 * 1024 + ); + } + + #[test] + fn command_qdisc_memory_estimate_deduplicates_qdisc_identity() { + let commands = vec![ + vec![ + "qdisc".to_string(), + "add".to_string(), + "dev".to_string(), + "eth0".to_string(), + "parent".to_string(), + "1:10".to_string(), + "cake".to_string(), + ], + vec![ + "qdisc".to_string(), + "replace".to_string(), + "dev".to_string(), + "eth0".to_string(), + "parent".to_string(), + "1:10".to_string(), + "cake".to_string(), + ], + vec![ + "qdisc".to_string(), + "add".to_string(), + "dev".to_string(), + "eth1".to_string(), + "parent".to_string(), + "1:10".to_string(), + "cake".to_string(), + ], + vec![ + "qdisc".to_string(), + "add".to_string(), + "dev".to_string(), + "eth0".to_string(), + "parent".to_string(), + "1:11".to_string(), + "fq_codel".to_string(), + ], + ]; + + assert_eq!( + count_tc_command_types_and_estimate_qdisc_memory(&commands).3, + (CAKE_QDISC_ESTIMATED_MEMORY_BYTES * 2) + FQ_CODEL_QDISC_ESTIMATED_MEMORY_BYTES + ); + } + #[test] fn qdisc_budget_estimate_counts_only_root_mq_in_observe_mode() { let _guard = bakery_test_lock().lock().expect("lock"); diff --git a/src/rust/lqos_bakery/src/utils.rs b/src/rust/lqos_bakery/src/utils.rs index a0aa61d2..350fc435 100644 --- a/src/rust/lqos_bakery/src/utils.rs +++ b/src/rust/lqos_bakery/src/utils.rs @@ -269,7 +269,7 @@ fn memory_guard_failure_summary( phase: &str, ) -> String { format!( - "Bakery memory guard stopped {purpose} {phase} chunk {}/{}: available memory {} bytes is below safety floor {} bytes (total RAM {} bytes).", + "Bakery memory guard stopped {purpose} {phase} chunk {}/{}: available memory {} bytes is below required available memory {} bytes (total RAM {} bytes).", chunk_number, total_chunks, snapshot.available_bytes, diff --git a/src/rust/lqos_python/src/lib.rs b/src/rust/lqos_python/src/lib.rs index aafb385d..4c2c9484 100644 --- a/src/rust/lqos_python/src/lib.rs +++ b/src/rust/lqos_python/src/lib.rs @@ -3571,15 +3571,15 @@ impl Bakery { (false, false) => "exceeds qdisc-count preflight and failed memory preflight", }; let memory_summary = if let Some(snapshot) = estimate.memory_snapshot.as_ref() { - let memory_floor = lqos_bakery::BAKERY_MEMORY_GUARD_MIN_AVAILABLE_BYTES; - let required_available_bytes = - memory_floor.saturating_add(estimate.estimated_total_memory_bytes); + let required_available_bytes = estimate + .memory_guard_min_available_bytes + .saturating_add(estimate.estimated_total_memory_bytes); format!( "estimated qdisc memory {} bytes; available memory {} bytes; required minimum {} bytes (safety floor {} bytes plus estimate)", estimate.estimated_total_memory_bytes, snapshot.available_bytes, required_available_bytes, - memory_floor + estimate.memory_guard_min_available_bytes ) } else { format!( @@ -3625,7 +3625,7 @@ impl Bakery { .memory_snapshot .as_ref() .map(|snapshot| snapshot.available_bytes), - memory_guard_min_available_bytes: lqos_bakery::BAKERY_MEMORY_GUARD_MIN_AVAILABLE_BYTES, + memory_guard_min_available_bytes: estimate.memory_guard_min_available_bytes, memory_ok: estimate.memory_ok, interfaces: interface_reports, }]); @@ -3658,7 +3658,7 @@ impl Bakery { result.set_item("memory_ok", estimate.memory_ok)?; result.set_item( "memory_guard_min_available_bytes", - lqos_bakery::BAKERY_MEMORY_GUARD_MIN_AVAILABLE_BYTES, + estimate.memory_guard_min_available_bytes, )?; if let Some(snapshot) = estimate.memory_snapshot { result.set_item("memory_total_bytes", snapshot.total_bytes)?; -- knotmirror 0.0.1 From 8e9b14d46eb033a773adc9ae65d34dec4cabc88b Mon Sep 17 00:00:00 2001 From: Name <2718612@2178972821991.net> Date: Tue, 5 May 2026 14:27:23 -0600 Subject: [PATCH 40/51] changes --- docs-es/v2.0/troubleshooting-es.md | 10 + docs/v2.0/troubleshooting.md | 10 + src/rust/lqosd/src/main.rs | 2 + src/rust/lqosd/src/memory_watchdog.rs | 337 ++++++++++++++++++++++++++ 4 files changed, 359 insertions(+) create mode 100644 src/rust/lqosd/src/memory_watchdog.rs diff --git a/docs-es/v2.0/troubleshooting-es.md b/docs-es/v2.0/troubleshooting-es.md index c5daff47..f95ea6a0 100644 --- a/docs-es/v2.0/troubleshooting-es.md +++ b/docs-es/v2.0/troubleshooting-es.md @@ -124,6 +124,16 @@ Las instalaciones basadas en git deben usar `./build_rust.sh` después de actual Si el scheduler falla inmediatamente después de un reinicio con un mensaje como `Socket (typically /run/lqos/bus) not found`, eso indica que `lqosd` todavía no había terminado de enlazar el bus local. Los builds actuales esperan brevemente la disponibilidad del bus al arrancar el scheduler en lugar de abortar de inmediato, por lo que ya no deberían aparecer panics repetidos de arranque tras un reinicio. +Si `journalctl -u lqosd` muestra `lqosd memory watchdog restarting daemon`, el daemon salió intencionalmente antes de que la presión de memoria del host llegara al camino OOM del kernel. Systemd debería reiniciar `lqosd` automáticamente. Capture esa línea de log antes de cambiar ajustes; incluye memoria disponible, RSS/swap de `lqosd`, cantidad de hilos, cantidad de flujos y contadores de tiempo que ayudan a diagnosticar el origen del crecimiento de memoria. + +El watchdog se puede ajustar con overrides de entorno de systemd: + +```bash +sudo systemctl edit lqosd +``` + +Las variables comunes son `LQOSD_MEMORY_WATCHDOG_MIN_AVAILABLE_MB`, `LQOSD_MEMORY_WATCHDOG_MAX_PROCESS_MB` y `LQOSD_MEMORY_WATCHDOG_MAX_SWAP_MB`. Use `LQOSD_MEMORY_WATCHDOG_DISABLED=1` solo durante ventanas cortas de diagnóstico en las que esté observando activamente la presión de memoria. + ### El estado del scheduler en WebUI aparece no saludable Versiones recientes muestran estado/readiness del scheduler en WebUI. diff --git a/docs/v2.0/troubleshooting.md b/docs/v2.0/troubleshooting.md index 058d56a2..fb5c21b7 100644 --- a/docs/v2.0/troubleshooting.md +++ b/docs/v2.0/troubleshooting.md @@ -122,6 +122,16 @@ Press the End key on the keyboard to take you to the bottom of the log to see th Lqosd will provide specific reasons it failed, such as an interface not being up, an interface lacking multi-queue, or other concerns. +If `journalctl -u lqosd` shows `lqosd memory watchdog restarting daemon`, the daemon intentionally exited before host memory pressure reached the kernel OOM path. Systemd should restart `lqosd` automatically. Capture the watchdog log line before changing settings; it includes available memory, `lqosd` RSS/swap, thread count, flow count, and timing counters that help diagnose the source of memory growth. + +The watchdog can be tuned with systemd environment overrides: + +```bash +sudo systemctl edit lqosd +``` + +Common override variables are `LQOSD_MEMORY_WATCHDOG_MIN_AVAILABLE_MB`, `LQOSD_MEMORY_WATCHDOG_MAX_PROCESS_MB`, and `LQOSD_MEMORY_WATCHDOG_MAX_SWAP_MB`. Use `LQOSD_MEMORY_WATCHDOG_DISABLED=1` only for short troubleshooting windows where you are actively watching memory pressure. + ### Advanced lqosd debug At the command-line, run: diff --git a/src/rust/lqosd/src/main.rs b/src/rust/lqosd/src/main.rs index de540d0f..7b856014 100644 --- a/src/rust/lqosd/src/main.rs +++ b/src/rust/lqosd/src/main.rs @@ -10,6 +10,7 @@ mod ip_mapping; #[cfg(feature = "equinix_tests")] mod lqos_daht_test; pub mod lts2_sys; +mod memory_watchdog; mod network_devices_hooks; mod node_manager; mod preflight_checks; @@ -248,6 +249,7 @@ fn main() -> Result<()> { // Memory Debugging memory_debug(); + memory_watchdog::start_memory_watchdog(); let control_tx_for_webserver = control_tx_for_web.clone(); let system_usage_tx_for_web = system_usage_tx.clone(); diff --git a/src/rust/lqosd/src/memory_watchdog.rs b/src/rust/lqosd/src/memory_watchdog.rs new file mode 100644 index 00000000..6e202137 --- /dev/null +++ b/src/rust/lqosd/src/memory_watchdog.rs @@ -0,0 +1,337 @@ +//! Memory pressure watchdog for controlled `lqosd` restarts. +//! +//! The watchdog samples `/proc` and exits the daemon before the kernel OOM +//! path has to choose a victim. `lqosd.service` is configured with +//! `Restart=always`, so this releases process memory while preserving logs that +//! explain why the restart happened. + +use crate::stats::{BUS_REQUESTS, FLOWS_TRACKED, HIGH_WATERMARK, TIME_TO_POLL_HOSTS}; +use std::collections::HashMap; +use std::sync::atomic::Ordering; +use std::time::Duration; +use tracing::{error, info, warn}; + +const CHECK_INTERVAL_SECONDS: u64 = 15; +const PRESSURE_WARNING_AVAILABLE_BYTES: u64 = mib(3_072); +const DEFAULT_MIN_AVAILABLE_BYTES: u64 = mib(2_304); +const DEFAULT_MIN_PROCESS_BYTES: u64 = mib(1_024); +const DEFAULT_MAX_PROCESS_BYTES: u64 = gib(4); +const DEFAULT_MAX_SWAP_BYTES: u64 = gib(1); +const WATCHDOG_EXIT_CODE: i32 = 75; + +/// Spawns the memory watchdog thread. +/// +/// Side effects: this function starts a background thread. The thread reads +/// `/proc/meminfo`, `/proc/self/status`, and exits the process when memory +/// pressure reaches the configured critical threshold. +pub fn start_memory_watchdog() { + if env_flag_enabled("LQOSD_MEMORY_WATCHDOG_DISABLED") { + warn!("lqosd memory watchdog disabled by LQOSD_MEMORY_WATCHDOG_DISABLED"); + return; + } + + match std::thread::Builder::new() + .name("Memory Watchdog".to_string()) + .spawn(memory_watchdog_loop) + { + Ok(_) => info!("lqosd memory watchdog started"), + Err(err) => warn!("Failed to start lqosd memory watchdog: {err:?}"), + } +} + +fn memory_watchdog_loop() { + let config = MemoryWatchdogConfig::from_env(); + let mut warned_about_pressure = false; + + loop { + std::thread::sleep(Duration::from_secs(CHECK_INTERVAL_SECONDS)); + + let Ok(snapshot) = MemorySnapshot::read() else { + warn!("Unable to sample lqosd memory state from /proc"); + continue; + }; + + if let Some(reason) = config.critical_reason(&snapshot) { + log_critical_memory_snapshot(&snapshot, &config, &reason); + std::thread::sleep(Duration::from_millis(250)); + std::process::exit(WATCHDOG_EXIT_CODE); + } + + if snapshot.mem_available_bytes < PRESSURE_WARNING_AVAILABLE_BYTES { + if !warned_about_pressure { + warn!( + "lqosd memory pressure warning: mem_available={} process_rss={} process_swap={} process_total={} threads={}", + format_bytes(snapshot.mem_available_bytes), + format_bytes(snapshot.process_rss_bytes), + format_bytes(snapshot.process_swap_bytes), + format_bytes(snapshot.process_total_bytes()), + snapshot.thread_count, + ); + warned_about_pressure = true; + } + } else { + warned_about_pressure = false; + } + } +} + +fn log_critical_memory_snapshot( + snapshot: &MemorySnapshot, + config: &MemoryWatchdogConfig, + reason: &str, +) { + error!( + "lqosd memory watchdog restarting daemon: reason={} mem_available={} mem_total={} process_rss={} process_swap={} process_total={} threads={} thresholds=min_available:{} min_process:{} max_process:{} max_swap:{}", + reason, + format_bytes(snapshot.mem_available_bytes), + format_bytes(snapshot.mem_total_bytes), + format_bytes(snapshot.process_rss_bytes), + format_bytes(snapshot.process_swap_bytes), + format_bytes(snapshot.process_total_bytes()), + snapshot.thread_count, + format_bytes(config.min_available_bytes), + format_bytes(config.min_process_bytes), + format_bytes(config.max_process_bytes), + format_bytes(config.max_swap_bytes), + ); + error!( + "lqosd memory watchdog diagnostics: flows_tracked={} bus_requests={} time_to_poll_hosts_us={} high_watermark_down={} high_watermark_up={}", + FLOWS_TRACKED.load(Ordering::Relaxed), + BUS_REQUESTS.load(Ordering::Relaxed), + TIME_TO_POLL_HOSTS.load(Ordering::Relaxed), + HIGH_WATERMARK.get_down(), + HIGH_WATERMARK.get_up(), + ); +} + +#[derive(Debug)] +struct MemoryWatchdogConfig { + min_available_bytes: u64, + min_process_bytes: u64, + max_process_bytes: u64, + max_swap_bytes: u64, +} + +impl MemoryWatchdogConfig { + fn from_env() -> Self { + Self { + min_available_bytes: env_mib( + "LQOSD_MEMORY_WATCHDOG_MIN_AVAILABLE_MB", + DEFAULT_MIN_AVAILABLE_BYTES, + ), + min_process_bytes: env_mib( + "LQOSD_MEMORY_WATCHDOG_MIN_PROCESS_MB", + DEFAULT_MIN_PROCESS_BYTES, + ), + max_process_bytes: env_mib( + "LQOSD_MEMORY_WATCHDOG_MAX_PROCESS_MB", + DEFAULT_MAX_PROCESS_BYTES, + ), + max_swap_bytes: env_mib("LQOSD_MEMORY_WATCHDOG_MAX_SWAP_MB", DEFAULT_MAX_SWAP_BYTES), + } + } + + fn critical_reason(&self, snapshot: &MemorySnapshot) -> Option { + if snapshot.process_swap_bytes >= self.max_swap_bytes { + return Some(format!( + "process swap {} reached limit {}", + format_bytes(snapshot.process_swap_bytes), + format_bytes(self.max_swap_bytes) + )); + } + + if snapshot.process_total_bytes() >= self.max_process_bytes { + return Some(format!( + "process rss+swap {} reached limit {}", + format_bytes(snapshot.process_total_bytes()), + format_bytes(self.max_process_bytes) + )); + } + + if snapshot.mem_available_bytes < self.min_available_bytes + && snapshot.process_total_bytes() >= self.min_process_bytes + { + return Some(format!( + "available memory {} below limit {} while lqosd uses {}", + format_bytes(snapshot.mem_available_bytes), + format_bytes(self.min_available_bytes), + format_bytes(snapshot.process_total_bytes()) + )); + } + + None + } +} + +#[derive(Debug, PartialEq, Eq)] +struct MemorySnapshot { + mem_total_bytes: u64, + mem_available_bytes: u64, + process_rss_bytes: u64, + process_swap_bytes: u64, + thread_count: u64, +} + +impl MemorySnapshot { + fn read() -> anyhow::Result { + let meminfo = parse_proc_key_values(&std::fs::read_to_string("/proc/meminfo")?); + let status = parse_proc_key_values(&std::fs::read_to_string("/proc/self/status")?); + + Ok(Self { + mem_total_bytes: read_required_kb(&meminfo, "MemTotal")?, + mem_available_bytes: read_required_kb(&meminfo, "MemAvailable")?, + process_rss_bytes: read_required_kb(&status, "VmRSS")?, + process_swap_bytes: read_optional_kb(&status, "VmSwap"), + thread_count: read_optional_raw(&status, "Threads"), + }) + } + + fn process_total_bytes(&self) -> u64 { + self.process_rss_bytes + .saturating_add(self.process_swap_bytes) + } +} + +fn parse_proc_key_values(input: &str) -> HashMap { + input + .lines() + .filter_map(|line| { + let (key, rest) = line.split_once(':')?; + let value = rest.split_whitespace().next()?.parse::().ok()?; + Some((key.to_string(), value)) + }) + .collect() +} + +fn read_required_kb(values: &HashMap, key: &str) -> anyhow::Result { + values + .get(key) + .copied() + .map(kib) + .ok_or_else(|| anyhow::anyhow!("{key} missing from /proc memory data")) +} + +fn read_optional_kb(values: &HashMap, key: &str) -> u64 { + values.get(key).copied().map(kib).unwrap_or(0) +} + +fn read_optional_raw(values: &HashMap, key: &str) -> u64 { + values.get(key).copied().unwrap_or(0) +} + +fn env_flag_enabled(name: &str) -> bool { + std::env::var(name) + .map(|value| matches!(value.as_str(), "1" | "true" | "TRUE" | "yes" | "YES")) + .unwrap_or(false) +} + +fn env_mib(name: &str, default_bytes: u64) -> u64 { + std::env::var(name) + .ok() + .and_then(|value| value.parse::().ok()) + .map(mib) + .unwrap_or(default_bytes) +} + +const fn kib(value: u64) -> u64 { + value * 1024 +} + +const fn mib(value: u64) -> u64 { + value * 1024 * 1024 +} + +const fn gib(value: u64) -> u64 { + value * 1024 * 1024 * 1024 +} + +fn format_bytes(bytes: u64) -> String { + let mib_value = bytes as f64 / mib(1) as f64; + format!("{mib_value:.1} MiB") +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn proc_parser_reads_kb_and_raw_values() { + let parsed = parse_proc_key_values( + "MemTotal: 15458992 kB\nMemAvailable: 12843176 kB\nThreads:\t44\n", + ); + + assert_eq!( + read_required_kb(&parsed, "MemTotal").unwrap(), + 15_458_992 * 1024 + ); + assert_eq!(read_optional_raw(&parsed, "Threads"), 44); + assert_eq!(read_optional_kb(&parsed, "VmSwap"), 0); + } + + #[test] + fn watchdog_restarts_on_process_swap_limit() { + let config = MemoryWatchdogConfig { + min_available_bytes: mib(2_304), + min_process_bytes: mib(1_024), + max_process_bytes: gib(4), + max_swap_bytes: gib(1), + }; + let snapshot = MemorySnapshot { + mem_total_bytes: gib(16), + mem_available_bytes: gib(12), + process_rss_bytes: mib(900), + process_swap_bytes: gib(2), + thread_count: 44, + }; + + assert!( + config + .critical_reason(&snapshot) + .unwrap() + .contains("process swap") + ); + } + + #[test] + fn watchdog_restarts_on_low_available_memory_with_large_lqosd() { + let config = MemoryWatchdogConfig { + min_available_bytes: mib(2_304), + min_process_bytes: mib(1_024), + max_process_bytes: gib(4), + max_swap_bytes: gib(1), + }; + let snapshot = MemorySnapshot { + mem_total_bytes: gib(16), + mem_available_bytes: mib(1_900), + process_rss_bytes: mib(1_500), + process_swap_bytes: 0, + thread_count: 44, + }; + + assert!( + config + .critical_reason(&snapshot) + .unwrap() + .contains("available memory") + ); + } + + #[test] + fn watchdog_ignores_low_memory_when_lqosd_is_small() { + let config = MemoryWatchdogConfig { + min_available_bytes: mib(2_304), + min_process_bytes: mib(1_024), + max_process_bytes: gib(4), + max_swap_bytes: gib(1), + }; + let snapshot = MemorySnapshot { + mem_total_bytes: gib(16), + mem_available_bytes: mib(1_900), + process_rss_bytes: mib(256), + process_swap_bytes: 0, + thread_count: 44, + }; + + assert!(config.critical_reason(&snapshot).is_none()); + } +} -- knotmirror 0.0.1 From 6e91d72c4eaea37214b4b7e5866750737bd99458 Mon Sep 17 00:00:00 2001 From: rchac Date: Tue, 5 May 2026 22:08:28 +0000 Subject: [PATCH 41/51] changes --- docs-es/v2.0/integrations-reference-es.md | 2 +- docs/v2.0/integrations-netzur.md | 2 +- docs/v2.0/integrations-reference.md | 2 +- src/build_dpkg.sh | 1 + src/integrationUtils.py | 10 + src/integrationVISP.py | 19 +- src/mikrotikFindIPv6.py | 256 +++++++++++--- src/test_mikrotik_find_ipv6.py | 395 ++++++++++++++++++++++ 8 files changed, 618 insertions(+), 69 deletions(-) create mode 100644 src/integrationUtils.py create mode 100644 src/test_mikrotik_find_ipv6.py diff --git a/docs-es/v2.0/integrations-reference-es.md b/docs-es/v2.0/integrations-reference-es.md index 60b472ef..aa8651fc 100644 --- a/docs-es/v2.0/integrations-reference-es.md +++ b/docs-es/v2.0/integrations-reference-es.md @@ -151,7 +151,7 @@ use_mikrotik_ipv6 = false - `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). -- `use_mikrotik_ipv6` agrega prefijos IPv6 obtenidos de `/etc/libreqos/mikrotik_ipv6.toml`. +- `use_mikrotik_ipv6` agrega prefijos IPv6 obtenidos de `/etc/libreqos/mikrotik_ipv6.toml`. LibreQoS relaciona IPv4 e IPv6 por dirección MAC usando datos de ARP, DHCPv4, DHCPv6 y vecinos IPv6 de MikroTik. Para una importación manual: diff --git a/docs/v2.0/integrations-netzur.md b/docs/v2.0/integrations-netzur.md index a4fb385b..3e18bd04 100644 --- a/docs/v2.0/integrations-netzur.md +++ b/docs/v2.0/integrations-netzur.md @@ -15,7 +15,7 @@ use_mikrotik_ipv6 = false - `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. -- `use_mikrotik_ipv6` enriches subscriber devices with IPv6 prefixes discovered via `/etc/libreqos/mikrotik_ipv6.toml`. +- `use_mikrotik_ipv6` enriches subscriber devices with IPv6 prefixes discovered via `/etc/libreqos/mikrotik_ipv6.toml`. LibreQoS matches IPv4 and IPv6 by MAC address using MikroTik ARP, DHCPv4, DHCPv6, and IPv6 neighbor data. Run a manual import with: diff --git a/docs/v2.0/integrations-reference.md b/docs/v2.0/integrations-reference.md index 2fd00ebe..11c79949 100644 --- a/docs/v2.0/integrations-reference.md +++ b/docs/v2.0/integrations-reference.md @@ -153,7 +153,7 @@ use_mikrotik_ipv6 = false - `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. -- `use_mikrotik_ipv6` enriches subscriber devices with IPv6 prefixes discovered via `/etc/libreqos/mikrotik_ipv6.toml`. +- `use_mikrotik_ipv6` enriches subscriber devices with IPv6 prefixes discovered via `/etc/libreqos/mikrotik_ipv6.toml`. LibreQoS matches IPv4 and IPv6 by MAC address using MikroTik ARP, DHCPv4, DHCPv6, and IPv6 neighbor data. Run a manual import with: diff --git a/src/build_dpkg.sh b/src/build_dpkg.sh index 45e2c74c..32d8a474 100755 --- a/src/build_dpkg.sh +++ b/src/build_dpkg.sh @@ -27,6 +27,7 @@ LQOS_FILES=( integrationNetzur.py integrationRestHttp.py integrationSonar.py + integrationUtils.py integrationSplynx.py integrationVISP.py integrationWISPGate.py diff --git a/src/integrationUtils.py b/src/integrationUtils.py new file mode 100644 index 00000000..38d3b479 --- /dev/null +++ b/src/integrationUtils.py @@ -0,0 +1,10 @@ +from typing import Any + + +def normalize_mac(mac: Any) -> str: + if mac is None: + return "" + value = str(mac).strip() + if not value: + return "" + return value.replace(":", "").replace("-", "").upper() diff --git a/src/integrationVISP.py b/src/integrationVISP.py index 4eb3ccb4..680bc39b 100644 --- a/src/integrationVISP.py +++ b/src/integrationVISP.py @@ -34,6 +34,7 @@ from integrationCommon import ( apply_client_bandwidth_multiplier, isIntegrationOutputIpAllowed, ) +from integrationUtils import normalize_mac TOKEN_URL = "https://data.visp.net/token" @@ -71,16 +72,6 @@ def _unit_to_mbps(value: Any, unit: Any) -> Optional[float]: return v -def _normalize_mac(mac: Any) -> str: - if mac is None: - return "" - s = str(mac).strip() - if not s: - return "" - # VISP sometimes returns MACs without separators. Keep uppercase hex. - return s.replace(":", "").replace("-", "").upper() - - def _safe_isp_id_from_token_payload(payload: Dict[str, Any]) -> Optional[int]: isp_ids = payload.get("ispId") if isinstance(isp_ids, list) and isp_ids: @@ -505,7 +496,7 @@ def _extract_mac_candidates(row: Dict[str, Any]) -> List[str]: if not isinstance(equipment_data, dict): equipment_data = {} for key in ("Fiber MAC", "mac_address", "Ethernet MAC", "WAN MAC", "MAC Addr", "radio_mac"): - mac = _normalize_mac(equipment_data.get(key)) + mac = normalize_mac(equipment_data.get(key)) if mac and mac not in seen: seen.add(mac) candidates.append(mac) @@ -921,7 +912,7 @@ def createShaper() -> None: if eq_id > 0: equipment_ids.add(eq_id) for key in ("mac_address", "radio_mac"): - mac = _normalize_mac(eq.get(key)) + mac = normalize_mac(eq.get(key)) if mac: preferred_macs.add(mac) for ws in ws_list: @@ -947,7 +938,7 @@ def createShaper() -> None: if not ipv4s: counters["skipped_no_ip"] += 1 continue - mac = _normalize_mac(ws.get("mac_address")) + mac = normalize_mac(ws.get("mac_address")) if mac: preferred_macs.add(mac) add_service_record( @@ -1032,7 +1023,7 @@ def createShaper() -> None: ipv4s = list(ip_cache) except Exception: ipv4s = list(ip_cache) - mac = _normalize_mac(service_details.get("mac_address")) + mac = normalize_mac(service_details.get("mac_address")) if not mac and preferred_macs: mac = sorted(preferred_macs)[0] diff --git a/src/mikrotikFindIPv6.py b/src/mikrotikFindIPv6.py index afc4874d..6682c499 100644 --- a/src/mikrotikFindIPv6.py +++ b/src/mikrotikFindIPv6.py @@ -1,12 +1,39 @@ #!/usr/bin/python3 import csv +import ipaddress import json import sys +from enum import IntEnum +from typing import NamedTuple import routeros_api +from integrationUtils import normalize_mac from liblqos_python import load_mikrotik_ipv6_routers_json, mikrotik_ipv6_config_path +class SourcePriority(IntEnum): + ARP = 0 + NEIGHBOR = 1 + DHCP = 2 + +class Ipv6Rank(IntEnum): + INVALID = -1 + LINK_LOCAL = 0 + HOST = 1 + PREFIX = 2 + +class IpRecord(NamedTuple): + source_priority: SourcePriority + address_rank: int + canonical_address: str + address: str + ambiguous: bool = False + +class ClientAddressRecord(NamedTuple): + canonical_address: str + address: str + ambiguous: bool = False + def _load_legacy_router_csv(csv_path): router_list = [] with open(csv_path) as csv_file: @@ -32,13 +59,182 @@ def _load_router_list(configPath=None): return _load_legacy_router_csv(configPath) raise ValueError("Explicit Mikrotik IPv6 config overrides must currently point to a legacy .csv file") -def pullMikrotikIPv6(configPath=None): - import routeros_api +def _parse_ip_address(address): + try: + return ipaddress.ip_address(address.split('/')[0]) + except (AttributeError, ValueError): + return None + +def _canonical_ip_text(address): + parsed_address = _parse_ip_address(address) + if parsed_address is None: + return None + return str(parsed_address) + +def _canonical_ip_network_text(address): + try: + network = ipaddress.ip_network(address, strict=False) + except (AttributeError, ValueError): + return None + return network.with_prefixlen + +def _entry_value(entry, key): + if not isinstance(entry, dict): + return None + return entry.get(key) + +def _record_address_by_mac(entry, mac_to_ipv4, mac_to_ipv6): + mac = _entry_value(entry, 'mac-address') + address = _entry_value(entry, 'address') + parsed_address = _parse_ip_address(address) + if mac is None or parsed_address is None: + return + normalized_mac = normalize_mac(mac) + if parsed_address.version == 4: + _record_ipv4_for_mac(mac_to_ipv4, normalized_mac, address, source_priority=SourcePriority.ARP) + else: + _record_ipv6_for_mac(mac_to_ipv6, normalized_mac, address, source_priority=SourcePriority.ARP) + +def _record_dhcp4_address_by_mac(entry, mac_to_ipv4): + mac = _entry_value(entry, 'mac-address') + address = _entry_value(entry, 'address') + parsed_address = _parse_ip_address(address) + if mac is None or parsed_address is None or parsed_address.version != 4: + return + _record_ipv4_for_mac(mac_to_ipv4, normalize_mac(mac), address, source_priority=SourcePriority.DHCP) + +def _mac_from_dhcpv6_duid(duid): + duid_hex = str(duid).strip().replace(":", "").replace("-", "").lower() + if duid_hex.startswith("0x"): + duid_hex = duid_hex[2:] + try: + duid_bytes = bytes.fromhex(duid_hex) + except ValueError: + return None + if len(duid_bytes) == 14 and duid_bytes[0:2] == b'\x00\x01': + return normalize_mac(duid_bytes[8:14].hex()) + if len(duid_bytes) == 10 and duid_bytes[0:2] == b'\x00\x03': + return normalize_mac(duid_bytes[4:10].hex()) + return None +def _record_ipv4_for_mac(mac_to_ipv4, mac, address, source_priority): + if not mac or not address: + return + parsed_address = _parse_ip_address(address) + if parsed_address is None: + return + current = mac_to_ipv4.get(mac) + candidate = IpRecord(source_priority, int(parsed_address), str(parsed_address), address) + if current is None or source_priority > current.source_priority: + mac_to_ipv4[mac] = candidate + elif source_priority == current.source_priority and candidate.canonical_address != current.canonical_address: + mac_to_ipv4[mac] = current._replace(ambiguous=True) + +def _ipv6_rank(address): + try: + network = ipaddress.ip_network(address, strict=False) + except ValueError: + return Ipv6Rank.INVALID + if network.version != 6: + return Ipv6Rank.INVALID + ip = network.network_address + if ip.is_unspecified or ip.is_loopback or ip.is_multicast: + return Ipv6Rank.INVALID + if ip.is_link_local: + address_priority = Ipv6Rank.LINK_LOCAL + elif network.prefixlen < 128: + address_priority = Ipv6Rank.PREFIX + else: + address_priority = Ipv6Rank.HOST + return address_priority + +def _record_ipv6_for_mac(mac_to_ipv6, mac, address, source_priority): + if not mac or not address: + return + address_rank = _ipv6_rank(address) + if address_rank in (Ipv6Rank.INVALID, Ipv6Rank.LINK_LOCAL): + return + canonical_address = _canonical_ip_network_text(address) + if canonical_address is None: + return + current = mac_to_ipv6.get(mac) + candidate = IpRecord(source_priority, address_rank, canonical_address, address) + if current is None or source_priority > current.source_priority: + mac_to_ipv6[mac] = candidate + elif source_priority == current.source_priority: + if address_rank > current.address_rank: + mac_to_ipv6[mac] = candidate + elif address_rank == current.address_rank and canonical_address != current.canonical_address: + mac_to_ipv6[mac] = current._replace(ambiguous=True) + +def _record_client_address_binding(client_address_to_ipv6, client_address, address): + if not client_address or not address or _ipv6_rank(address) in (Ipv6Rank.INVALID, Ipv6Rank.LINK_LOCAL): + return + canonical_address = _canonical_ip_network_text(address) + if canonical_address is None: + return + current = client_address_to_ipv6.get(client_address) + if current is None: + client_address_to_ipv6[client_address] = ClientAddressRecord(canonical_address, address) + elif canonical_address != current.canonical_address: + client_address_to_ipv6[client_address] = current._replace(ambiguous=True) + +def _build_ipv4_to_ipv6_map(arp_entries, dhcp4_entries, dhcp6_bindings, neighbor6_entries): + ipv4_to_ipv6 = {} + mac_to_ipv4 = {} + mac_to_ipv6 = {} + client_address_to_ipv6 = {} + + for entry in arp_entries: + _record_address_by_mac(entry, mac_to_ipv4, mac_to_ipv6) + for entry in dhcp4_entries: + _record_dhcp4_address_by_mac(entry, mac_to_ipv4) + for entry in dhcp6_bindings: + mac = _mac_from_dhcpv6_duid(_entry_value(entry, 'duid') or '') + address = _entry_value(entry, 'address') + if mac is not None and address: + _record_ipv6_for_mac(mac_to_ipv6, mac, address, source_priority=SourcePriority.DHCP) + elif _entry_value(entry, 'client-address') and address: + client_address = _canonical_ip_text(_entry_value(entry, 'client-address')) + if client_address is not None: + _record_client_address_binding(client_address_to_ipv6, client_address, address) + for entry in neighbor6_entries: + mac = _entry_value(entry, 'mac-address') + address = _entry_value(entry, 'address') + if mac is None or _parse_ip_address(address) is None: + continue + normalized_mac = normalize_mac(mac) + neighbor_address = _canonical_ip_text(address) + mapped_ipv6_record = client_address_to_ipv6.get(neighbor_address) + if mapped_ipv6_record is not None and mapped_ipv6_record.ambiguous: + print('Skipped ambiguous DHCPv6 client-address entries for ' + neighbor_address, file=sys.stderr) + _record_ipv6_for_mac(mac_to_ipv6, normalized_mac, address, source_priority=SourcePriority.NEIGHBOR) + elif mapped_ipv6_record is not None: + _record_ipv6_for_mac(mac_to_ipv6, normalized_mac, mapped_ipv6_record.address, source_priority=SourcePriority.DHCP) + else: + _record_ipv6_for_mac(mac_to_ipv6, normalized_mac, address, source_priority=SourcePriority.NEIGHBOR) + + for mac, ipv6_record in mac_to_ipv6.items(): + if ipv6_record.ambiguous: + print('Skipped ambiguous IPv6 entries for MAC ' + mac, file=sys.stderr) + continue + ipv6 = ipv6_record.address + try: + ipv4_record = mac_to_ipv4[mac] + if ipv4_record.ambiguous: + print('Skipped ambiguous IPv4 entries for MAC ' + mac, file=sys.stderr) + continue + ipv4 = ipv4_record.address + ipv4_to_ipv6[ipv4] = ipv6 + except KeyError: + print('Failed to find associated IPv4 for ' + ipv6, file=sys.stderr) + + return ipv4_to_ipv6 + +def pullMikrotikIPv6(configPath=None): ipv4ToIPv6 = {} routerList = _load_router_list(configPath) for router in routerList: - RouterName = router['name'] IP = router['host'] inputUsername = router['username'] inputPassword = router['password'] @@ -47,62 +243,18 @@ def pullMikrotikIPv6(configPath=None): plaintext_login = bool(router.get('plaintext_login', True)) connection = routeros_api.RouterOsApiPool(IP, username=inputUsername, password=inputPassword, port=apiPort, use_ssl=use_ssl, ssl_verify=False, ssl_verify_hostname=False, plaintext_login=plaintext_login) api = connection.get_api() - macToIPv4 = {} - macToIPv6 = {} - clientAddressToIPv6 = {} - # list_dhcp4 = api.get_resource('/ip/dhcp-server/lease') - # entries = list_dhcp4.get() - # for entry in entries: - # try: - # macToIPv4[entry['mac-address']] = entry['address'] - # except: - # pass list_arp4 = api.get_resource('/ip/arp') - entries = list_arp4.get() - for entry in entries: - try: - macToIPv4[entry['mac-address']] = entry['address'] - except: - pass + arp_entries = list_arp4.get() list_dhcp4 = api.get_resource('/ip/dhcp-server/lease') - entries = list_dhcp4.get() - for entry in entries: - try: - macToIPv4[entry['mac-address']] = entry['address'] - except: - pass + dhcp4_entries = list_dhcp4.get() list_binding6 = api.get_resource('/ipv6/dhcp-server/binding') - entries = list_binding6.get() - for entry in entries: - if len(entry['duid']) == 14: - mac = entry['duid'][2:14].upper() - macNew = mac[0:2] + ':' + mac[2:4] + ':' + mac[4:6] + ':' + mac[6:8] + ':' + mac[8:10] + ':' + mac[10:12] - macToIPv6[macNew] = entry['address'] - else: - try: - clientAddressToIPv6[entry['client-address']] = entry['address'] - except: - pass + dhcp6_bindings = list_binding6.get() list_neighbor6 = api.get_resource('/ipv6/neighbor') - entries = list_neighbor6.get() - for entry in entries: - try: - realIPv6 = clientAddressToIPv6[entry['address']] - macToIPv6[entry['mac-address']] = realIPv6 - except: - pass - for mac, ipv6 in macToIPv6.items(): - try: - ipv4 = macToIPv4[mac] - ipv4ToIPv6[ipv4] = ipv6 - except: - print('Failed to find associated IPv4 for ' + ipv6, file=sys.stderr) + neighbor6_entries = list_neighbor6.get() + ipv4ToIPv6.update(_build_ipv4_to_ipv6_map(arp_entries, dhcp4_entries, dhcp6_bindings, neighbor6_entries)) return json.dumps(ipv4ToIPv6) -def pullMikrotikIPv6_Mock(CsvPath): - return "{\n\"172.29.200.2\": \"2602:fdca:800:1500::/56\"\n}" - if __name__ == '__main__': # If the first argument is a string, it's treated as a legacy CSV path override. if len(sys.argv) > 1 and sys.argv[1] == '--show-config': diff --git a/src/test_mikrotik_find_ipv6.py b/src/test_mikrotik_find_ipv6.py new file mode 100644 index 00000000..932a52e4 --- /dev/null +++ b/src/test_mikrotik_find_ipv6.py @@ -0,0 +1,395 @@ +import contextlib +import io +import json +import sys +import types +import unittest + + +sys.modules.setdefault("routeros_api", types.SimpleNamespace()) +sys.modules.setdefault( + "liblqos_python", + types.SimpleNamespace( + load_mikrotik_ipv6_routers_json=lambda: "[]", + mikrotik_ipv6_config_path=lambda: "/etc/libreqos/mikrotik_ipv6.toml", + ), +) + +import mikrotikFindIPv6 +from mikrotikFindIPv6 import _build_ipv4_to_ipv6_map, _mac_from_dhcpv6_duid + + +class MikrotikFindIPv6Tests(unittest.TestCase): + def test_pull_mikrotik_ipv6_fetches_resources_and_returns_json(self): + resources = { + "/ip/arp": [ + {"mac-address": "AA:BB:CC:DD:EE:FF", "address": "192.0.2.30"}, + ], + "/ip/dhcp-server/lease": [], + "/ipv6/dhcp-server/binding": [ + {"duid": "00030001AABBCCDDEEFF", "address": "2001:db8:30::/56"}, + ], + "/ipv6/neighbor": [ + {"mac-address": "00:11:22:33:44:55", "address": "2001:db8::99"}, + ], + } + + class Resource: + def __init__(self, entries): + self.entries = entries + + def get(self): + return self.entries + + class Api: + def get_resource(self, name): + return Resource(resources[name]) + + class Pool: + def __init__(self, *args, **kwargs): + pass + + def get_api(self): + return Api() + + original_pool = getattr(mikrotikFindIPv6.routeros_api, "RouterOsApiPool", None) + original_load_router_list = mikrotikFindIPv6._load_router_list + mikrotikFindIPv6.routeros_api.RouterOsApiPool = Pool + mikrotikFindIPv6._load_router_list = lambda configPath=None: [ + { + "name": "edge", + "host": "198.51.100.1", + "username": "admin", + "password": "secret", + } + ] + stderr = io.StringIO() + try: + with contextlib.redirect_stderr(stderr): + result = json.loads(mikrotikFindIPv6.pullMikrotikIPv6()) + finally: + if original_pool is None: + delattr(mikrotikFindIPv6.routeros_api, "RouterOsApiPool") + else: + mikrotikFindIPv6.routeros_api.RouterOsApiPool = original_pool + mikrotikFindIPv6._load_router_list = original_load_router_list + + self.assertEqual(result, {"192.0.2.30": "2001:db8:30::/56"}) + self.assertIn("Failed to find associated IPv4 for 2001:db8::99", stderr.getvalue()) + + def test_dhcpv6_duid_ll_extracts_mac(self): + self.assertEqual(_mac_from_dhcpv6_duid("00030001AABBCCDDEEFF"), "AABBCCDDEEFF") + self.assertEqual(_mac_from_dhcpv6_duid("0x00030001aabbccddeeff"), "AABBCCDDEEFF") + self.assertEqual(_mac_from_dhcpv6_duid("00:03:00:01:aa:bb:cc:dd:ee:ff"), "AABBCCDDEEFF") + + def test_dhcpv6_duid_llt_extracts_mac(self): + self.assertEqual(_mac_from_dhcpv6_duid("0001000100000000AABBCCDDEEFF"), "AABBCCDDEEFF") + + def test_neighbor_ipv6_matches_ipv4_by_mac(self): + result = _build_ipv4_to_ipv6_map( + arp_entries=[ + {"mac-address": "aa:bb:cc:dd:ee:ff", "address": "192.0.2.10"}, + ], + dhcp4_entries=[], + dhcp6_bindings=[], + neighbor6_entries=[ + {"mac-address": "AA:BB:CC:DD:EE:FF", "address": "2001:db8::10"}, + ], + ) + + self.assertEqual(result, {"192.0.2.10": "2001:db8::10"}) + + def test_link_local_neighbor_ipv6_is_not_emitted(self): + result = _build_ipv4_to_ipv6_map( + arp_entries=[ + {"mac-address": "aa:bb:cc:dd:ee:ff", "address": "192.0.2.11"}, + ], + dhcp4_entries=[], + dhcp6_bindings=[], + neighbor6_entries=[ + {"mac-address": "AA:BB:CC:DD:EE:FF", "address": "fe80::11"}, + ], + ) + + self.assertEqual(result, {}) + + def test_unspecified_ipv6_prefix_is_not_emitted(self): + result = _build_ipv4_to_ipv6_map( + arp_entries=[ + {"mac-address": "aa:bb:cc:dd:ee:ff", "address": "192.0.2.12"}, + ], + dhcp4_entries=[], + dhcp6_bindings=[ + {"duid": "00030001AABBCCDDEEFF", "address": "::/64"}, + ], + neighbor6_entries=[], + ) + + self.assertEqual(result, {}) + + def test_neighbor_client_address_preserves_dhcpv6_prefix(self): + result = _build_ipv4_to_ipv6_map( + arp_entries=[ + {"mac-address": "AA:BB:CC:DD:EE:FF", "address": "192.0.2.10"}, + ], + dhcp4_entries=[], + dhcp6_bindings=[ + {"client-address": "fe80:0:0:0:0:0:0:1", "address": "2001:db8:100::/56"}, + ], + neighbor6_entries=[ + {"mac-address": "AA:BB:CC:DD:EE:FF", "address": "fe80::1"}, + ], + ) + + self.assertEqual(result, {"192.0.2.10": "2001:db8:100::/56"}) + + def test_arp_ipv6_matches_dhcp4_by_mac(self): + result = _build_ipv4_to_ipv6_map( + arp_entries=[ + {"mac-address": "AA:BB:CC:DD:EE:FF", "address": "2001:db8::20"}, + ], + dhcp4_entries=[ + {"mac-address": "aa:bb:cc:dd:ee:ff", "address": "192.0.2.20"}, + ], + dhcp6_bindings=[], + neighbor6_entries=[], + ) + + self.assertEqual(result, {"192.0.2.20": "2001:db8::20"}) + + def test_duplicate_ipv6_entries_prefer_non_link_local_prefix(self): + result = _build_ipv4_to_ipv6_map( + arp_entries=[ + {"mac-address": "AA:BB:CC:DD:EE:FF", "address": "192.0.2.40"}, + ], + dhcp4_entries=[], + dhcp6_bindings=[], + neighbor6_entries=[ + {"mac-address": "AA:BB:CC:DD:EE:FF", "address": "fe80::1"}, + {"mac-address": "AA:BB:CC:DD:EE:FF", "address": "2001:db8:40::/56"}, + {"mac-address": "AA:BB:CC:DD:EE:FF", "address": "2001:db8::40"}, + ], + ) + + self.assertEqual(result, {"192.0.2.40": "2001:db8:40::/56"}) + + def test_duplicate_same_priority_ipv6_entries_are_ambiguous(self): + neighbors = [ + {"mac-address": "AA:BB:CC:DD:EE:FF", "address": "2001:db8::50"}, + {"mac-address": "AA:BB:CC:DD:EE:FF", "address": "2001:db8::9"}, + ] + for neighbor6_entries in (neighbors, list(reversed(neighbors))): + stderr = io.StringIO() + with contextlib.redirect_stderr(stderr): + result = _build_ipv4_to_ipv6_map( + arp_entries=[ + {"mac-address": "AA:BB:CC:DD:EE:FF", "address": "192.0.2.50"}, + ], + dhcp4_entries=[], + dhcp6_bindings=[], + neighbor6_entries=neighbor6_entries, + ) + + self.assertEqual(result, {}) + self.assertIn("Skipped ambiguous IPv6 entries for MAC AABBCCDDEEFF", stderr.getvalue()) + + def test_neighbor_ipv6_recovers_from_ambiguous_arp_ipv6(self): + result = _build_ipv4_to_ipv6_map( + arp_entries=[ + {"mac-address": "AA:BB:CC:DD:EE:FF", "address": "192.0.2.51"}, + {"mac-address": "AA:BB:CC:DD:EE:FF", "address": "2001:db8::51"}, + {"mac-address": "AA:BB:CC:DD:EE:FF", "address": "2001:db8::52"}, + ], + dhcp4_entries=[], + dhcp6_bindings=[], + neighbor6_entries=[ + {"mac-address": "AA:BB:CC:DD:EE:FF", "address": "2001:db8::53"}, + ], + ) + + self.assertEqual(result, {"192.0.2.51": "2001:db8::53"}) + + def test_neighbor_ipv6_preferred_over_arp_ipv6_for_same_mac(self): + result = _build_ipv4_to_ipv6_map( + arp_entries=[ + {"mac-address": "AA:BB:CC:DD:EE:FF", "address": "192.0.2.52"}, + {"mac-address": "AA:BB:CC:DD:EE:FF", "address": "2001:db8::99"}, + ], + dhcp4_entries=[], + dhcp6_bindings=[], + neighbor6_entries=[ + {"mac-address": "AA:BB:CC:DD:EE:FF", "address": "2001:db8::52"}, + ], + ) + + self.assertEqual(result, {"192.0.2.52": "2001:db8::52"}) + + def test_neighbor_client_address_matches_cidr_text(self): + result = _build_ipv4_to_ipv6_map( + arp_entries=[ + {"mac-address": "AA:BB:CC:DD:EE:FF", "address": "192.0.2.53"}, + ], + dhcp4_entries=[], + dhcp6_bindings=[ + {"client-address": "fe80::53/128", "address": "2001:db8:53::/56"}, + ], + neighbor6_entries=[ + {"mac-address": "AA:BB:CC:DD:EE:FF", "address": "fe80:0:0:0:0:0:0:53"}, + ], + ) + + self.assertEqual(result, {"192.0.2.53": "2001:db8:53::/56"}) + + def test_bad_duid_falls_back_to_client_address(self): + result = _build_ipv4_to_ipv6_map( + arp_entries=[ + {"mac-address": "AA:BB:CC:DD:EE:FF", "address": "192.0.2.54"}, + ], + dhcp4_entries=[], + dhcp6_bindings=[ + {"duid": "not-hex", "client-address": "fe80::54", "address": "2001:db8:54::/56"}, + ], + neighbor6_entries=[ + {"mac-address": "AA:BB:CC:DD:EE:FF", "address": "fe80::54"}, + ], + ) + + self.assertEqual(result, {"192.0.2.54": "2001:db8:54::/56"}) + + def test_duplicate_client_address_bindings_are_ambiguous(self): + stderr = io.StringIO() + with contextlib.redirect_stderr(stderr): + result = _build_ipv4_to_ipv6_map( + arp_entries=[ + {"mac-address": "AA:BB:CC:DD:EE:FF", "address": "192.0.2.57"}, + ], + dhcp4_entries=[], + dhcp6_bindings=[ + {"client-address": "fe80::57", "address": "2001:db8:57::/56"}, + {"client-address": "fe80::57", "address": "2001:db8:58::/56"}, + ], + neighbor6_entries=[ + {"mac-address": "AA:BB:CC:DD:EE:FF", "address": "fe80::57/128"}, + ], + ) + + self.assertEqual(result, {}) + self.assertIn("Skipped ambiguous DHCPv6 client-address entries for fe80::57", stderr.getvalue()) + + def test_equivalent_client_address_bindings_are_not_ambiguous(self): + result = _build_ipv4_to_ipv6_map( + arp_entries=[ + {"mac-address": "AA:BB:CC:DD:EE:FF", "address": "192.0.2.58"}, + ], + dhcp4_entries=[], + dhcp6_bindings=[ + {"client-address": "fe80::58", "address": "2001:db8:58::/56"}, + {"client-address": "fe80:0:0:0:0:0:0:58", "address": "2001:db8:58:0::/56"}, + ], + neighbor6_entries=[ + {"mac-address": "AA:BB:CC:DD:EE:FF", "address": "fe80::58"}, + ], + ) + + self.assertEqual(result, {"192.0.2.58": "2001:db8:58::/56"}) + + def test_dhcpv6_binding_preferred_over_arp_and_neighbor_ipv6(self): + result = _build_ipv4_to_ipv6_map( + arp_entries=[ + {"mac-address": "AA:BB:CC:DD:EE:FF", "address": "192.0.2.55"}, + {"mac-address": "AA:BB:CC:DD:EE:FF", "address": "2001:db8::55"}, + ], + dhcp4_entries=[], + dhcp6_bindings=[ + {"duid": "00030001AABBCCDDEEFF", "address": "2001:db8:55::/56"}, + ], + neighbor6_entries=[ + {"mac-address": "AA:BB:CC:DD:EE:FF", "address": "2001:db8::56"}, + ], + ) + + self.assertEqual(result, {"192.0.2.55": "2001:db8:55::/56"}) + + def test_dhcp4_ipv4_preferred_over_arp_for_same_mac(self): + result = _build_ipv4_to_ipv6_map( + arp_entries=[ + {"mac-address": "AA:BB:CC:DD:EE:FF", "address": "192.0.2.60"}, + ], + dhcp4_entries=[ + {"mac-address": "AA:BB:CC:DD:EE:FF", "address": "192.0.2.61"}, + ], + dhcp6_bindings=[], + neighbor6_entries=[ + {"mac-address": "AA:BB:CC:DD:EE:FF", "address": "2001:db8::60"}, + ], + ) + + self.assertEqual(result, {"192.0.2.61": "2001:db8::60"}) + + def test_dhcp4_ipv4_recovers_from_ambiguous_arp_ipv4(self): + result = _build_ipv4_to_ipv6_map( + arp_entries=[ + {"mac-address": "AA:BB:CC:DD:EE:FF", "address": "192.0.2.62"}, + {"mac-address": "AA:BB:CC:DD:EE:FF", "address": "192.0.2.63"}, + ], + dhcp4_entries=[ + {"mac-address": "AA:BB:CC:DD:EE:FF", "address": "192.0.2.64"}, + ], + dhcp6_bindings=[], + neighbor6_entries=[ + {"mac-address": "AA:BB:CC:DD:EE:FF", "address": "2001:db8::64"}, + ], + ) + + self.assertEqual(result, {"192.0.2.64": "2001:db8::64"}) + + def test_duplicate_same_priority_ipv4_entries_are_ambiguous(self): + arp_entries = [ + {"mac-address": "AA:BB:CC:DD:EE:FF", "address": "192.0.2.9"}, + {"mac-address": "AA:BB:CC:DD:EE:FF", "address": "192.0.2.10"}, + ] + for entries in (arp_entries, list(reversed(arp_entries))): + stderr = io.StringIO() + with contextlib.redirect_stderr(stderr): + result = _build_ipv4_to_ipv6_map( + arp_entries=entries, + dhcp4_entries=[], + dhcp6_bindings=[], + neighbor6_entries=[ + {"mac-address": "AA:BB:CC:DD:EE:FF", "address": "2001:db8::60"}, + ], + ) + + self.assertEqual(result, {}) + self.assertIn("Skipped ambiguous IPv4 entries for MAC AABBCCDDEEFF", stderr.getvalue()) + + def test_malformed_routeros_rows_are_ignored_while_valid_rows_match(self): + result = _build_ipv4_to_ipv6_map( + arp_entries=[ + None, + {"mac-address": "AA:BB:CC:DD:EE:FF", "address": "not an address"}, + {"address": "192.0.2.70"}, + {"mac-address": "AA:BB:CC:DD:EE:FF", "address": "192.0.2.70"}, + ], + dhcp4_entries=[ + ["not", "a", "dict"], + {"mac-address": "AA:BB:CC:DD:EE:FF", "address": "still not an address"}, + ], + dhcp6_bindings=[ + {"duid": "not-hex", "address": "2001:db8:70::/56"}, + {"duid": "00030001AABBCCDDEEFF", "address": "not an address"}, + {"client-address": "not an address", "address": "2001:db8:71::/56"}, + ], + neighbor6_entries=[ + None, + {"mac-address": "AA:BB:CC:DD:EE:FF", "address": "also not an address"}, + {"address": "2001:db8::70"}, + {"mac-address": "AA:BB:CC:DD:EE:FF", "address": "2001:db8::70"}, + ], + ) + + self.assertEqual(result, {"192.0.2.70": "2001:db8::70"}) + + +if __name__ == "__main__": + unittest.main() -- knotmirror 0.0.1 From dc0f37a307bbfd83c52337a5e10a4804a805efe1 Mon Sep 17 00:00:00 2001 From: rchac Date: Tue, 5 May 2026 22:21:18 +0000 Subject: [PATCH 42/51] changes --- docs/v2.0/topology-data-flow.md | 4 + src/rust/lqos_topology/src/lib.rs | 252 +++++++++++++++++++++++++----- 2 files changed, 220 insertions(+), 36 deletions(-) diff --git a/docs/v2.0/topology-data-flow.md b/docs/v2.0/topology-data-flow.md index aedb8ad1..6dffd0e9 100644 --- a/docs/v2.0/topology-data-flow.md +++ b/docs/v2.0/topology-data-flow.md @@ -139,6 +139,10 @@ flowchart LR | `lqos_overrides.json` | operator / WebUI / CLI | scheduler / topology runtime | durable operator intent | Yes | Yes | Yes | | `topology_attachment_health_state.json` | topology probes | Topology Manager / debug pages | runtime attachment health | Runtime state | Runtime state | No | +## Runtime Fallback Warnings + +When a circuit references a parent or anchor that is not present in the queue-visible effective topology, LibreQoS still shapes the circuit under a generated parent node. Scheduler output summarizes those fallbacks by reason and includes a few example circuits instead of printing one warning per circuit. Review the examples in Topology Manager or the source integration when those circuits should attach to a specific real site, AP, or parent node. + ## Consumer Map ```{mermaid} diff --git a/src/rust/lqos_topology/src/lib.rs b/src/rust/lqos_topology/src/lib.rs index 9d773dcd..ae8a6da2 100644 --- a/src/rust/lqos_topology/src/lib.rs +++ b/src/rust/lqos_topology/src/lib.rs @@ -33,10 +33,134 @@ use std::thread; use std::time::{SystemTime, UNIX_EPOCH}; const TOPOLOGY_EFFECTIVE_PUBLISH_LOCK_FILENAME: &str = "topology_effective_publish.lock"; +const TOPOLOGY_WARNING_EXAMPLE_LIMIT: usize = 5; type EffectiveQueueAliasMap = HashMap; pub use runtime::start_topology; +#[derive(Default)] +struct TopologyFallbackWarningSummary { + unresolved_exported_anchor_count: usize, + unresolved_exported_anchor_examples: Vec, + missing_anchor_count: usize, + missing_anchor_examples: Vec, + missing_parent_count: usize, + missing_parent_examples: Vec, + non_exported_parent_count: usize, + non_exported_parent_examples: Vec, +} + +impl TopologyFallbackWarningSummary { + fn record_unresolved_exported_anchor( + &mut self, + circuit_id: &str, + anchor_id: &str, + anchor_name: &str, + ) { + self.unresolved_exported_anchor_count += 1; + push_capped_warning_example( + &mut self.unresolved_exported_anchor_examples, + format!("circuit '{circuit_id}' -> anchor '{anchor_id}' ('{anchor_name}')"), + ); + } + + fn record_missing_anchor( + &mut self, + circuit_id: &str, + anchor_id: &str, + anchor_name: Option<&str>, + ) { + self.missing_anchor_count += 1; + let example = if let Some(anchor_name) = anchor_name.filter(|value| !value.is_empty()) { + format!("circuit '{circuit_id}' -> anchor '{anchor_id}' ('{anchor_name}')") + } else { + format!("circuit '{circuit_id}' -> anchor '{anchor_id}'") + }; + push_capped_warning_example(&mut self.missing_anchor_examples, example); + } + + fn record_missing_parent(&mut self, circuit_id: &str, parent_name: &str, parent_id: &str) { + self.missing_parent_count += 1; + push_capped_warning_example( + &mut self.missing_parent_examples, + format!("circuit '{circuit_id}' -> parent '{parent_name}' ({parent_id})"), + ); + } + + fn record_non_exported_parent(&mut self, circuit_id: &str, parent_name: &str, parent_id: &str) { + self.non_exported_parent_count += 1; + push_capped_warning_example( + &mut self.non_exported_parent_examples, + format!("circuit '{circuit_id}' -> parent '{parent_name}' ({parent_id})"), + ); + } + + fn append_to(self, warnings: &mut Vec) { + push_fallback_summary_warning( + warnings, + self.unresolved_exported_anchor_count, + "anchor(s) that did not resolve to exported effective queue nodes", + &self.unresolved_exported_anchor_examples, + ); + push_fallback_summary_warning( + warnings, + self.missing_anchor_count, + "anchor(s) that were not found in the effective topology", + &self.missing_anchor_examples, + ); + push_fallback_summary_warning( + warnings, + self.missing_parent_count, + "parent reference(s) that were not found in the exported effective topology", + &self.missing_parent_examples, + ); + push_fallback_summary_warning( + warnings, + self.non_exported_parent_count, + "resolved parent(s) that were not exported effective queue nodes", + &self.non_exported_parent_examples, + ); + } +} + +fn push_capped_warning_example(examples: &mut Vec, example: String) { + if examples.len() < TOPOLOGY_WARNING_EXAMPLE_LIMIT { + examples.push(example); + } +} + +fn push_fallback_summary_warning( + warnings: &mut Vec, + count: usize, + reason: &str, + examples: &[String], +) { + if count == 0 { + return; + } + let mut warning = format!( + "{count} circuit(s) referenced {reason}. Falling back to generated parent-node shaping." + ); + if !examples.is_empty() { + warning.push_str(" Examples: "); + warning.push_str(&examples.join("; ")); + warning.push('.'); + let omitted_count = count.saturating_sub(examples.len()); + if omitted_count > 0 { + warning.push_str(&format!(" {omitted_count} more omitted.")); + } + } + warnings.push(warning); +} + +fn push_unresolved_runtime_fallback_summary(warnings: &mut Vec, count: usize) { + if count > 0 { + warnings.push(format!( + "{count} circuit(s) are unresolved in runtime topology and will be shaped under generated parent nodes." + )); + } +} + /// One unique probe pair emitted from topology state plus operator intent. #[derive(Clone, Debug, PartialEq, Eq)] pub struct AttachmentProbeSpec { @@ -547,6 +671,7 @@ fn build_shaping_inputs( let mut errors = Vec::new(); let mut warnings = Vec::new(); + let mut fallback_warning_summary = TopologyFallbackWarningSummary::default(); let mut circuits = Vec::::new(); let mut circuits_by_id = HashMap::::new(); @@ -612,12 +737,11 @@ fn build_shaping_inputs( ) { (Some(ui_node), Some(_effective_node), _) => { anchor_node_name = Some(ui_node.node_name.clone()); - warnings.push(format!( - "Circuit '{}' anchor '{}' ('{}') did not resolve to an exported effective queue node. Falling back to generated parent-node shaping.", - device.circuit_id, + fallback_warning_summary.record_unresolved_exported_anchor( + &device.circuit_id, anchor_id, - ui_node.node_name - )); + &ui_node.node_name, + ); ( String::new(), String::new(), @@ -627,15 +751,11 @@ fn build_shaping_inputs( ) } (None, None, Some(anchor)) => { - warnings.push(format!( - "Circuit '{}' anchor '{}' ('{}') was not found in the effective topology. Falling back to generated parent-node shaping.", - device.circuit_id, + fallback_warning_summary.record_missing_anchor( + &device.circuit_id, anchor_id, - anchor - .anchor_node_name - .as_deref() - .unwrap_or_default() - )); + anchor.anchor_node_name.as_deref(), + ); ( String::new(), String::new(), @@ -645,10 +765,11 @@ fn build_shaping_inputs( ) } _ => { - warnings.push(format!( - "Circuit '{}' anchor '{}' was not found in the effective topology. Falling back to generated parent-node shaping.", - device.circuit_id, anchor_id - )); + fallback_warning_summary.record_missing_anchor( + &device.circuit_id, + anchor_id, + None, + ); ( String::new(), String::new(), @@ -681,12 +802,11 @@ fn build_shaping_inputs( if optional_non_empty(&device.parent_node).is_some() || optional_non_empty_owned(device.parent_node_id.clone()).is_some() { - warnings.push(format!( - "Circuit '{}' parent reference '{}' ({}) was not found in the exported effective topology. Falling back to generated parent-node shaping.", - device.circuit_id, + fallback_warning_summary.record_missing_parent( + &device.circuit_id, device.parent_node.trim(), - device.parent_node_id.clone().unwrap_or_default().trim() - )); + device.parent_node_id.clone().unwrap_or_default().trim(), + ); } ( String::new(), @@ -707,10 +827,11 @@ fn build_shaping_inputs( &exported_effective_nodes, &exported_effective_names, ) { - warnings.push(format!( - "Circuit '{}' resolved to non-exported effective parent '{}' ({}). Falling back to generated parent-node shaping.", - device.circuit_id, effective_parent_node_name, effective_parent_node_id - )); + fallback_warning_summary.record_non_exported_parent( + &device.circuit_id, + &effective_parent_node_name, + &effective_parent_node_id, + ); effective_parent_node_id.clear(); effective_parent_node_name.clear(); effective_attachment_id = None; @@ -781,6 +902,7 @@ fn build_shaping_inputs( .devices .sort_unstable_by(|left, right| left.device_id.cmp(&right.device_id)); } + fallback_warning_summary.append_to(&mut warnings); let unresolved_runtime_fallbacks = circuits .iter() @@ -795,16 +917,7 @@ fn build_shaping_inputs( "Flat topology mode assigned {unresolved_runtime_fallbacks} circuit(s) to generated parent nodes during queue construction." )); } else { - for circuit in &circuits { - if circuit.effective_parent_node_id.trim().is_empty() - && circuit.resolution_source == TopologyShapingResolutionSource::RuntimeFallback - { - warnings.push(format!( - "Circuit '{}' is unresolved in runtime topology and will be shaped under generated parent nodes.", - circuit.circuit_id - )); - } - } + push_unresolved_runtime_fallback_summary(&mut warnings, unresolved_runtime_fallbacks); } } @@ -5399,6 +5512,73 @@ mod tests { ); } + #[test] + fn shaping_inputs_aggregate_missing_parent_warnings() { + let lqos_directory = unique_temp_dir("lqos-topology-missing-parent-summary"); + let config = Config { + lqos_directory: lqos_directory.to_string_lossy().to_string(), + state_directory: None, + ..Config::default() + }; + let mut csv = String::from( + "Circuit ID,Circuit Name,Device ID,Device Name,Parent Node,Parent Node ID,Anchor Node ID,MAC,IPv4,IPv6,Download Min Mbps,Upload Min Mbps,Download Max Mbps,Upload Max Mbps,Comment\n", + ); + for circuit_number in 1..=12 { + csv.push_str(&format!( + "\"circuit-{circuit_number}\",\"Circuit {circuit_number}\",\"device-{circuit_number}\",\"Device {circuit_number}\",\"Missing Parent\",\"missing-parent\",\"\",\"aa:bb:cc:dd:ee:{circuit_number:02x}\",\"192.0.2.{circuit_number}/32\",\"\",\"10\",\"10\",\"100\",\"100\",\"\"\n", + )); + } + fs::write(lqos_directory.join("ShapedDevices.csv"), csv) + .expect("ShapedDevices.csv should write"); + + let artifacts = EffectiveTopologyArtifacts { + effective: TopologyEffectiveStateFile { + schema_version: 1, + generated_unix: Some(1), + canonical_generated_unix: Some(1), + health_generated_unix: Some(1), + nodes: Vec::new(), + }, + ui_state: TopologyEditorStateFile { + schema_version: 1, + source: "test".to_string(), + generated_unix: Some(1), + ingress_identity: None, + nodes: Vec::new(), + }, + effective_network: Some(json!({})), + }; + + let shaping_inputs = build_shaping_inputs(&config, &artifacts) + .expect("shaping inputs should build") + .expect("shaping inputs should be present"); + assert_eq!(shaping_inputs.circuits.len(), 12); + assert!(shaping_inputs.circuits.iter().all(|circuit| { + circuit.resolution_source + == lqos_config::TopologyShapingResolutionSource::RuntimeFallback + })); + + let parent_warnings = shaping_inputs + .warnings + .iter() + .filter(|warning| warning.contains("parent reference(s)")) + .collect::>(); + assert_eq!(parent_warnings.len(), 1); + assert!(parent_warnings[0].contains("12 circuit(s)")); + assert!(parent_warnings[0].contains("circuit-1")); + assert!(parent_warnings[0].contains("circuit-5")); + assert!(!parent_warnings[0].contains("circuit-6")); + assert!(parent_warnings[0].contains("7 more omitted")); + assert_eq!( + shaping_inputs + .warnings + .iter() + .filter(|warning| warning.contains("unresolved in runtime topology")) + .count(), + 1 + ); + } + #[test] fn flat_mode_assigns_explicit_generated_parent_buckets() { let lqos_directory = unique_temp_dir("lqos-topology-flat-summary"); -- knotmirror 0.0.1 From 6fa64c431ee349bd99fb44ba6a1b1ac19c67b292 Mon Sep 17 00:00:00 2001 From: rchac Date: Tue, 5 May 2026 22:25:33 +0000 Subject: [PATCH 43/51] changes --- docs-es/v2.0/integrations-reference-es.md | 28 +++++++++++++++++++++++ docs/v2.0/integrations-netzur.md | 26 +++++++++++++++++++++ docs/v2.0/integrations-reference.md | 28 +++++++++++++++++++++++ src/mikrotik_ipv6.example.toml | 9 ++++++++ 4 files changed, 91 insertions(+) diff --git a/docs-es/v2.0/integrations-reference-es.md b/docs-es/v2.0/integrations-reference-es.md index aa8651fc..1b7cf070 100644 --- a/docs-es/v2.0/integrations-reference-es.md +++ b/docs-es/v2.0/integrations-reference-es.md @@ -153,6 +153,34 @@ use_mikrotik_ipv6 = false - `timeout_secs` permite incrementar el tiempo de espera de la petición cuando el API responde lentamente (por defecto 60 segundos). - `use_mikrotik_ipv6` agrega prefijos IPv6 obtenidos de `/etc/libreqos/mikrotik_ipv6.toml`. LibreQoS relaciona IPv4 e IPv6 por dirección MAC usando datos de ARP, DHCPv4, DHCPv6 y vecinos IPv6 de MikroTik. +### Credenciales de routers MikroTik para IPv6 + +Cuando `use_mikrotik_ipv6` o `ipv6_with_mikrotik` esté habilitado, cree `/etc/libreqos/mikrotik_ipv6.toml`. Agregue un bloque `[[router]]` por cada router MikroTik que LibreQoS deba consultar: + +```toml +version = 1 + +[[router]] +name = "core-1" +host = "100.64.0.1" +port = 8728 +username = "libreqos" +password = "secreto" +use_ssl = false +plaintext_login = true + +[[router]] +name = "core-2" +host = "100.64.0.2" +port = 8728 +username = "libreqos" +password = "secreto" +use_ssl = false +plaintext_login = true +``` + +Agregue más bloques `[[router]]` para más routers. `port`, `use_ssl` y `plaintext_login` pueden omitirse cuando los valores por defecto son correctos: puerto `8728`, SSL deshabilitado y login en texto plano habilitado. + Para una importación manual: ```bash diff --git a/docs/v2.0/integrations-netzur.md b/docs/v2.0/integrations-netzur.md index 3e18bd04..49bf7f3b 100644 --- a/docs/v2.0/integrations-netzur.md +++ b/docs/v2.0/integrations-netzur.md @@ -17,6 +17,32 @@ use_mikrotik_ipv6 = false - `timeout_secs` overrides the default HTTP timeout (60 seconds) when the API is slow. - `use_mikrotik_ipv6` enriches subscriber devices with IPv6 prefixes discovered via `/etc/libreqos/mikrotik_ipv6.toml`. LibreQoS matches IPv4 and IPv6 by MAC address using MikroTik ARP, DHCPv4, DHCPv6, and IPv6 neighbor data. +When `use_mikrotik_ipv6` is enabled, create `/etc/libreqos/mikrotik_ipv6.toml`. Add one `[[router]]` block for each MikroTik router LibreQoS should query: + +```toml +version = 1 + +[[router]] +name = "core-1" +host = "100.64.0.1" +port = 8728 +username = "libreqos" +password = "secret" +use_ssl = false +plaintext_login = true + +[[router]] +name = "core-2" +host = "100.64.0.2" +port = 8728 +username = "libreqos" +password = "secret" +use_ssl = false +plaintext_login = true +``` + +Use additional `[[router]]` blocks for additional routers. `port`, `use_ssl`, and `plaintext_login` can be omitted when the defaults are correct: port `8728`, SSL disabled, and plaintext login enabled. + Run a manual import with: ```bash diff --git a/docs/v2.0/integrations-reference.md b/docs/v2.0/integrations-reference.md index 11c79949..0cffe36f 100644 --- a/docs/v2.0/integrations-reference.md +++ b/docs/v2.0/integrations-reference.md @@ -155,6 +155,34 @@ use_mikrotik_ipv6 = false - `timeout_secs` overrides the default HTTP timeout (60 seconds) when the API is slow. - `use_mikrotik_ipv6` enriches subscriber devices with IPv6 prefixes discovered via `/etc/libreqos/mikrotik_ipv6.toml`. LibreQoS matches IPv4 and IPv6 by MAC address using MikroTik ARP, DHCPv4, DHCPv6, and IPv6 neighbor data. +### MikroTik IPv6 Router Credentials + +When `use_mikrotik_ipv6` or `ipv6_with_mikrotik` is enabled, create `/etc/libreqos/mikrotik_ipv6.toml`. Add one `[[router]]` block for each MikroTik router LibreQoS should query: + +```toml +version = 1 + +[[router]] +name = "core-1" +host = "100.64.0.1" +port = 8728 +username = "libreqos" +password = "secret" +use_ssl = false +plaintext_login = true + +[[router]] +name = "core-2" +host = "100.64.0.2" +port = 8728 +username = "libreqos" +password = "secret" +use_ssl = false +plaintext_login = true +``` + +Use additional `[[router]]` blocks for additional routers. `port`, `use_ssl`, and `plaintext_login` can be omitted when the defaults are correct: port `8728`, SSL disabled, and plaintext login enabled. + Run a manual import with: ```bash diff --git a/src/mikrotik_ipv6.example.toml b/src/mikrotik_ipv6.example.toml index 9f857a52..7b49cae1 100644 --- a/src/mikrotik_ipv6.example.toml +++ b/src/mikrotik_ipv6.example.toml @@ -8,3 +8,12 @@ username = "admin" password = "password" use_ssl = false plaintext_login = true + +[[router]] +name = "secondary" +host = "100.64.0.2" +port = 8728 +username = "admin" +password = "password" +use_ssl = false +plaintext_login = true -- knotmirror 0.0.1 From d7de13f11e5c63269672d4ebc7430f345a7b1919 Mon Sep 17 00:00:00 2001 From: rchac Date: Tue, 5 May 2026 19:23:05 -0600 Subject: [PATCH 44/51] changes --- src/rust/lqos_overrides/src/overrides_file.rs | 49 +++++++++++++++++-- 1 file changed, 46 insertions(+), 3 deletions(-) diff --git a/src/rust/lqos_overrides/src/overrides_file.rs b/src/rust/lqos_overrides/src/overrides_file.rs index 41344f35..e63eb461 100644 --- a/src/rust/lqos_overrides/src/overrides_file.rs +++ b/src/rust/lqos_overrides/src/overrides_file.rs @@ -1,5 +1,6 @@ use std::{ fs::read_to_string, + io::Write, path::{Path, PathBuf}, }; @@ -201,6 +202,9 @@ fn treeguard_read_path(config: &lqos_config::Config) -> PathBuf { fn load_from_path(path: &Path) -> Result { let raw = read_to_string(path)?; + if raw.trim().is_empty() { + anyhow::bail!("Overrides file '{}' was empty", path.display()); + } let as_json = serde_json::from_str(&raw)?; Ok(as_json) } @@ -212,13 +216,40 @@ fn ensure_exists_default(path: &Path) -> Result<()> { // Create a default empty file let new_override_file = OverrideFile::default(); let as_json = serde_json::to_string(&new_override_file)?; - std::fs::write(path, as_json.as_bytes())?; + write_atomic(path, as_json.as_bytes())?; Ok(()) } fn save_to_path(path: &Path, overrides: &OverrideFile) -> Result<()> { let as_json = serde_json::to_string_pretty(overrides)?; - std::fs::write(path, as_json.as_bytes())?; + write_atomic(path, as_json.as_bytes())?; + Ok(()) +} + +fn write_atomic(path: &Path, contents: &[u8]) -> Result<()> { + let parent = path.parent().ok_or_else(|| { + anyhow::anyhow!("Overrides path '{}' has no parent directory", path.display()) + })?; + let file_name = path.file_name().ok_or_else(|| { + anyhow::anyhow!("Overrides path '{}' has no file name", path.display()) + })?; + let pid = std::process::id(); + let nanos = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|duration| duration.as_nanos()) + .unwrap_or(0); + let tmp_name = format!("{}.tmp.{}.{}", file_name.to_string_lossy(), pid, nanos); + let tmp_path = parent.join(tmp_name); + + let mut file = std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(&tmp_path)?; + file.write_all(contents)?; + file.sync_all()?; + drop(file); + + std::fs::rename(&tmp_path, path)?; Ok(()) } @@ -1089,7 +1120,8 @@ impl OverrideStore { pub fn load_effective(apply_stormguard: bool, apply_treeguard: bool) -> Result { let lock = FileLock::new()?; let config = lqos_config::load_config()?; - let merged = Self::load_effective_for_config(&config, apply_stormguard, apply_treeguard)?; + let merged = + Self::load_effective_for_config_inner(&config, apply_stormguard, apply_treeguard)?; drop(lock); Ok(merged) } @@ -1102,6 +1134,17 @@ impl OverrideStore { config: &lqos_config::Config, apply_stormguard: bool, apply_treeguard: bool, + ) -> Result { + let lock = FileLock::new()?; + let merged = Self::load_effective_for_config_inner(config, apply_stormguard, apply_treeguard)?; + drop(lock); + Ok(merged) + } + + fn load_effective_for_config_inner( + config: &lqos_config::Config, + apply_stormguard: bool, + apply_treeguard: bool, ) -> Result { let operator_path = overrides_path(config, OverrideLayer::Operator); ensure_exists_default(&operator_path)?; -- knotmirror 0.0.1 From ae9571a5ccfd4684254aa53f86430b47f4395d5c Mon Sep 17 00:00:00 2001 From: rchac Date: Wed, 6 May 2026 11:46:43 +0000 Subject: [PATCH 45/51] changes --- src/rust/lqos_config/src/lib.rs | 16 +- .../lqos_config/src/topology_runtime_state.rs | 109 ++++++- src/rust/lqos_network_devices/README.md | 20 +- src/rust/lqos_network_devices/src/actor.rs | 279 ++++++++++++++++-- .../src/directory_watcher.rs | 17 +- src/rust/lqos_network_devices/src/lib.rs | 72 ++++- src/rust/lqos_network_devices/src/tests.rs | 16 +- src/rust/lqos_topology/src/lib.rs | 7 + src/rust/lqos_topology/src/runtime.rs | 225 +++++++++++++- src/rust/lqosd/src/main.rs | 2 +- .../src/node_manager/local_api/config.rs | 1 + .../lqosd/src/shaped_devices_tracker/mod.rs | 107 +++---- 12 files changed, 735 insertions(+), 136 deletions(-) diff --git a/src/rust/lqos_config/src/lib.rs b/src/rust/lqos_config/src/lib.rs index 2e54fd6b..cdf1f2ed 100644 --- a/src/rust/lqos_config/src/lib.rs +++ b/src/rust/lqos_config/src/lib.rs @@ -93,13 +93,15 @@ pub use topology_runtime_state::{ TOPOLOGY_IMPORT_FILENAME, TOPOLOGY_RUNTIME_STATUS_FILENAME, TOPOLOGY_SHAPING_INPUTS_FILENAME, TopologyAttachmentEndpointStatus, TopologyAttachmentHealthEntry, TopologyAttachmentHealthStateFile, TopologyEffectiveAttachmentState, - TopologyEffectiveNodeState, TopologyEffectiveStateFile, TopologyRuntimeStateError, - TopologyRuntimeStatusFile, TopologyShapingCircuitInput, TopologyShapingDeviceInput, - TopologyShapingInputsFile, TopologyShapingResolutionSource, active_runtime_shaping_inputs_path, - compute_effective_network_generation, compute_topology_source_generation, - load_active_runtime_shaping_inputs, topology_attachment_health_state_path, - topology_compiled_shaping_path, topology_effective_network_path, topology_effective_state_path, - topology_import_path, topology_runtime_status_path, topology_shaping_inputs_path, + TopologyEffectiveNodeState, TopologyEffectiveStateFile, TopologyRuntimeShapingPayloadIdentity, + TopologyRuntimeStateError, TopologyRuntimeStatusFile, TopologyShapingCircuitInput, + TopologyShapingDeviceInput, TopologyShapingInputsFile, TopologyShapingResolutionSource, + active_runtime_shaping_inputs_path, compute_effective_network_generation, + active_runtime_shaping_inputs_path_from_status, compute_topology_source_generation, + load_active_runtime_shaping_inputs, load_active_runtime_shaping_inputs_from_status, + topology_attachment_health_state_path, topology_compiled_shaping_path, + topology_effective_network_path, topology_effective_state_path, topology_import_path, + topology_runtime_status_path, topology_shaping_inputs_path, }; /// Returns whether an integration-backed topology ingress is enabled in the diff --git a/src/rust/lqos_config/src/topology_runtime_state.rs b/src/rust/lqos_config/src/topology_runtime_state.rs index 3e1c8954..02f90a9f 100644 --- a/src/rust/lqos_config/src/topology_runtime_state.rs +++ b/src/rust/lqos_config/src/topology_runtime_state.rs @@ -356,6 +356,20 @@ pub struct TopologyRuntimeStatusFile { pub error: Option, } +/// Shaping-relevant runtime status identity used by consumers that only need +/// to know whether the active shaping payload changed. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct TopologyRuntimeShapingPayloadIdentity { + /// Whether runtime outputs are ready. + pub ready: bool, + /// Stable generation hash of the source topology inputs. + pub source_generation: String, + /// Stable generation hash of the shaping payload. + pub shaping_generation: String, + /// Path to the active shaping inputs payload. + pub shaping_inputs_path: String, +} + fn default_runtime_schema_version() -> u32 { 1 } @@ -428,20 +442,33 @@ pub fn active_runtime_shaping_inputs_path( ) -> Result, TopologyRuntimeStateError> { let current_generation = compute_topology_source_generation(config)?; let status = TopologyRuntimeStatusFile::load(config)?; + Ok(active_runtime_shaping_inputs_path_from_status( + &status, + ¤t_generation, + )) +} + +/// Returns the active runtime shaping-inputs path from an already-loaded status file. +/// +/// This function is pure: it has no side effects. +pub fn active_runtime_shaping_inputs_path_from_status( + status: &TopologyRuntimeStatusFile, + current_generation: &str, +) -> Option { if !status.ready { - return Ok(None); + return None; } if status.shaping_generation.trim().is_empty() { - return Ok(None); + return None; } if status.source_generation.trim() != current_generation { - return Ok(None); + return None; } let path = status.shaping_inputs_path.trim(); if path.is_empty() { - return Ok(None); + return None; } - Ok(Some(PathBuf::from(path))) + Some(PathBuf::from(path)) } /// Loads the currently active runtime shaping-inputs file when the topology @@ -456,6 +483,20 @@ pub fn load_active_runtime_shaping_inputs( Ok(Some(serde_json::from_str(&raw)?)) } +/// Loads the active runtime shaping-inputs file from an already-loaded status file. +pub fn load_active_runtime_shaping_inputs_from_status( + config: &Config, + status: &TopologyRuntimeStatusFile, +) -> Result, TopologyRuntimeStateError> { + let current_generation = compute_topology_source_generation(config)?; + let Some(path) = active_runtime_shaping_inputs_path_from_status(status, ¤t_generation) + else { + return Ok(None); + }; + let raw = std::fs::read_to_string(&path)?; + Ok(Some(serde_json::from_str(&raw)?)) +} + /// Returns the path of the topology runtime readiness status file. pub fn topology_runtime_status_path(config: &Config) -> PathBuf { config.topology_state_read_path(TOPOLOGY_RUNTIME_STATUS_FILENAME) @@ -742,6 +783,29 @@ impl TopologyRuntimeStatusFile { self, ) } + + /// Returns true when runtime status is equal except for the generated timestamp. + pub fn semantic_equals_for_publish(&self, other: &Self) -> bool { + self.schema_version == other.schema_version + && self.source_generation == other.source_generation + && self.shaping_generation == other.shaping_generation + && self.effective_generation == other.effective_generation + && self.ready == other.ready + && self.effective_state_path == other.effective_state_path + && self.effective_network_path == other.effective_network_path + && self.shaping_inputs_path == other.shaping_inputs_path + && self.error == other.error + } + + /// Returns the shaping payload identity used by cache consumers. + pub fn shaping_payload_identity(&self) -> TopologyRuntimeShapingPayloadIdentity { + TopologyRuntimeShapingPayloadIdentity { + ready: self.ready, + source_generation: self.source_generation.clone(), + shaping_generation: self.shaping_generation.clone(), + shaping_inputs_path: self.shaping_inputs_path.clone(), + } + } } #[cfg(test)] @@ -1300,6 +1364,41 @@ mod tests { ); } + #[test] + fn topology_runtime_status_publish_compare_ignores_generated_unix() { + let first = TopologyRuntimeStatusFile { + schema_version: 1, + source_generation: "source-1".to_string(), + shaping_generation: "shape-1".to_string(), + effective_generation: "effective-1".to_string(), + ready: true, + generated_unix: Some(1), + effective_state_path: "/tmp/effective.json".to_string(), + effective_network_path: "/tmp/network.effective.json".to_string(), + shaping_inputs_path: "/tmp/shaping_inputs.json".to_string(), + error: None, + }; + let second = TopologyRuntimeStatusFile { + generated_unix: Some(2), + ..first.clone() + }; + let changed = TopologyRuntimeStatusFile { + shaping_generation: "shape-2".to_string(), + ..first.clone() + }; + + assert!(first.semantic_equals_for_publish(&second)); + assert!(!first.semantic_equals_for_publish(&changed)); + assert_eq!( + first.shaping_payload_identity(), + second.shaping_payload_identity() + ); + assert_ne!( + first.shaping_payload_identity(), + changed.shaping_payload_identity() + ); + } + #[test] fn shaping_generation_ignores_timestamp_only_changes() { let first = TopologyShapingInputsFile { diff --git a/src/rust/lqos_network_devices/README.md b/src/rust/lqos_network_devices/README.md index 4f8215e0..ec7e7583 100644 --- a/src/rust/lqos_network_devices/README.md +++ b/src/rust/lqos_network_devices/README.md @@ -11,8 +11,8 @@ Centralized, shared access to LibreQoS topology inputs: In daemon mode, this crate starts: - A single-thread actor that owns reload/apply commands. -- Watchers for the config directory and topology-state directory that coalesce - filesystem events and request reloads. +- Watchers for the config directory, topology-state directory, and shaping-state + directory that coalesce filesystem events and request reloads. Callers access state through public accessor functions; the underlying channel sender is kept in a private static. @@ -27,7 +27,7 @@ private static. - `with_network_json_write(|net_json| ...)`: mutable access to in-memory `NetworkJson` (used by runtime counters). - `resolve_parent_node_reference(parent_node, parent_node_id)`: canonicalize shaped-device parent references against `network.json`. - `request_reload_shaped_devices(reason)` / `request_reload_network_json(reason)`: ask actor to reload from disk. -- `apply_shaped_devices_snapshot(reason, shaped)`: publish a caller-provided shaped-devices snapshot via actor. +- `apply_shaped_devices_snapshot(reason, shaped, provenance)`: publish a caller-provided shaped-devices snapshot via actor. - `swap_shaped_devices_snapshot(reason, shaped_arc)`: replace shaped-devices snapshot without actor (intended for tests). ## `ShapedDevicesCatalog` helpers @@ -48,16 +48,18 @@ Runtime throughput tracking mutates the in-memory `NetworkJson` via `with_networ ## Access & update catalog -Current (2026-04) call sites and update patterns: +Call sites and update patterns: - Daemon startup: `lqosd` calls `start_daemon_mode()` once at boot and provides `DaemonHooks`. - Shaped-device updates: - - Directory watcher requests reload when `topology_runtime_status.json`, - `ShapedDevices.csv`, or `ShapedDevices.insight.csv` changes. - - Reload precedence is: ready runtime shaping inputs, then `topology_import.json`, - then `ShapedDevices.csv`. + - Directory watcher requests reload when `shaping_inputs.json`, + `topology_import.json`, `ShapedDevices.csv`, or `ShapedDevices.insight.csv` changes. + - `topology_runtime_status.json` is readiness metadata and does not trigger a shaped-device reload by itself. + - In integration-ingress mode, reload precedence is: ready runtime shaping inputs, + then `topology_import.json`, then an empty snapshot until the topology runtime publishes. + - In manual mode, reloads use `ShapedDevices.csv` or `ShapedDevices.insight.csv`. - Node manager admin edits write `ShapedDevices.csv` and immediately publish the new snapshot via - `apply_shaped_devices_snapshot()`. + `apply_shaped_devices_snapshot()` with external-snapshot provenance. - Network topology updates: - Directory watcher requests reload when `network.json`, `network.insight.json`, or `network.effective.json` changes, including the runtime topology-state copy. diff --git a/src/rust/lqos_network_devices/src/actor.rs b/src/rust/lqos_network_devices/src/actor.rs index 6b6f3069..a823d20a 100644 --- a/src/rust/lqos_network_devices/src/actor.rs +++ b/src/rust/lqos_network_devices/src/actor.rs @@ -3,12 +3,17 @@ use crate::dynamic::{ }; use crate::dynamic_store::{load_dynamic_circuits_from_disk, persist_dynamic_circuits_to_disk}; use crate::state; -use crate::{DaemonHooks, ShapedDevicesCatalog, load_network_json, load_shaped_devices}; +use crate::{ + DaemonHooks, LoadedShapedDevices, LoadedShapedDevicesSource, ShapedDevicesCatalog, + ShapedDevicesSnapshotProvenance, load_network_json, load_shaped_devices_with_source, +}; use anyhow::{Context, Result, anyhow}; use crossbeam_channel::{Receiver, Sender}; use ip_network_table::IpNetworkTable; use once_cell::sync::OnceCell; use std::collections::HashSet; +use std::collections::hash_map::DefaultHasher; +use std::hash::{Hash, Hasher}; use std::net::IpAddr; use std::sync::Arc; use std::time::Duration; @@ -69,11 +74,13 @@ pub(crate) fn request_reload_network_json(reason: &str) -> Result<()> { pub(crate) fn apply_shaped_devices_snapshot( reason: &str, shaped: lqos_config::ConfigShapedDevices, + provenance: ShapedDevicesSnapshotProvenance, ) -> Result<()> { let (reply_tx, reply_rx) = oneshot::channel(); sender()?.send(NetworkDevicesCommand::ApplyShapedDevicesSnapshot { reason: reason.to_string(), shaped: Box::new(shaped), + provenance, reply: reply_tx, })?; reply_rx @@ -128,6 +135,7 @@ enum NetworkDevicesCommand { ApplyShapedDevicesSnapshot { reason: String, shaped: Box, + provenance: ShapedDevicesSnapshotProvenance, reply: oneshot::Sender>, }, ReportObservations { @@ -145,8 +153,11 @@ enum NetworkDevicesCommand { fn actor_loop(rx: Receiver, hooks: Option>) { debug!("lqos_network_devices actor starting"); + let mut active_shaped_key = None; - if let Err(err) = reload_shaped_devices_inner("startup", hooks.as_deref()) { + if let Err(err) = + reload_shaped_devices_inner("startup", hooks.as_deref(), &mut active_shaped_key) + { warn!("Initial shaped-devices load failed: {err}"); } if let Err(err) = reload_network_json_inner("startup", hooks.as_deref()) { @@ -169,7 +180,11 @@ fn actor_loop(rx: Receiver, hooks: Option { - let result = reload_shaped_devices_inner(&reason, hooks.as_deref()); + let result = reload_shaped_devices_inner( + &reason, + hooks.as_deref(), + &mut active_shaped_key, + ); let _ = reply.send(result); } NetworkDevicesCommand::ReloadNetworkJson { reason, reply } => { @@ -179,15 +194,18 @@ fn actor_loop(rx: Receiver, hooks: Option { - debug!("Publishing shaped-devices snapshot reason={reason}"); - state::publish_shaped_devices(*shaped); - prune_dynamic_circuits_superseded_by_shaped_devices_inner(hooks.as_deref()); - if let Some(hooks) = &hooks { - hooks.on_shaped_devices_updated(); - } - let _ = reply.send(Ok(())); + let key = shaped_devices_key_for_snapshot(provenance, &shaped); + let result = publish_shaped_devices_if_changed( + &reason, + *shaped, + key, + hooks.as_deref(), + &mut active_shaped_key, + ); + let _ = reply.send(result); } NetworkDevicesCommand::ReportObservations { observations } => { handle_observations(&observations, hooks.as_deref()); @@ -224,6 +242,119 @@ fn recompute_hashes(device: &mut lqos_config::ShapedDevice) { device.parent_hash = lqos_utils::hash_to_i64(&device.parent_node); } +#[derive(Clone, Debug, PartialEq, Eq)] +enum ShapedDevicesProvenanceKey { + RuntimeTopology { + shaping_generation: String, + }, + TopologyImport { + devices_fingerprint: u64, + }, + Csv { + devices_fingerprint: u64, + }, + ExternalSnapshot { + devices_fingerprint: u64, + }, +} + +#[derive(Eq, Hash, Ord, PartialEq, PartialOrd)] +struct ShapedDeviceSemanticKey { + circuit_id: String, + circuit_name: String, + device_id: String, + device_name: String, + parent_node: String, + parent_node_id: Option, + anchor_node_id: Option, + mac: String, + ipv4: Vec<(std::net::Ipv4Addr, u32)>, + ipv6: Vec<(std::net::Ipv6Addr, u32)>, + download_min_mbps_bits: u32, + upload_min_mbps_bits: u32, + download_max_mbps_bits: u32, + upload_max_mbps_bits: u32, + comment: String, + sqm_override: Option, + circuit_hash: i64, + device_hash: i64, + parent_hash: i64, +} + +fn shaped_device_semantic_key(device: &lqos_config::ShapedDevice) -> ShapedDeviceSemanticKey { + let mut ipv4 = device.ipv4.clone(); + ipv4.sort_unstable(); + let mut ipv6 = device.ipv6.clone(); + ipv6.sort_unstable(); + + ShapedDeviceSemanticKey { + circuit_id: device.circuit_id.clone(), + circuit_name: device.circuit_name.clone(), + device_id: device.device_id.clone(), + device_name: device.device_name.clone(), + parent_node: device.parent_node.clone(), + parent_node_id: device.parent_node_id.clone(), + anchor_node_id: device.anchor_node_id.clone(), + mac: device.mac.clone(), + ipv4, + ipv6, + download_min_mbps_bits: device.download_min_mbps.to_bits(), + upload_min_mbps_bits: device.upload_min_mbps.to_bits(), + download_max_mbps_bits: device.download_max_mbps.to_bits(), + upload_max_mbps_bits: device.upload_max_mbps.to_bits(), + comment: device.comment.clone(), + sqm_override: device.sqm_override.clone(), + circuit_hash: device.circuit_hash, + device_hash: device.device_hash, + parent_hash: device.parent_hash, + } +} + +fn shaped_devices_fingerprint(devices: &[lqos_config::ShapedDevice]) -> u64 { + let mut sorted = devices + .iter() + .map(shaped_device_semantic_key) + .collect::>(); + sorted.sort_unstable(); + let mut hasher = DefaultHasher::new(); + for key in sorted { + key.hash(&mut hasher); + } + hasher.finish() +} + +fn shaped_devices_key_for_loaded(loaded: &LoadedShapedDevices) -> ShapedDevicesProvenanceKey { + match &loaded.source { + LoadedShapedDevicesSource::RuntimeTopology { + shaping_generation, + .. + } => ShapedDevicesProvenanceKey::RuntimeTopology { + shaping_generation: shaping_generation.clone(), + }, + LoadedShapedDevicesSource::TopologyImport => { + ShapedDevicesProvenanceKey::TopologyImport { + devices_fingerprint: shaped_devices_fingerprint(&loaded.shaped.devices), + } + } + LoadedShapedDevicesSource::Csv => ShapedDevicesProvenanceKey::Csv { + devices_fingerprint: shaped_devices_fingerprint(&loaded.shaped.devices), + }, + } +} + +fn shaped_devices_key_for_snapshot( + provenance: ShapedDevicesSnapshotProvenance, + shaped: &lqos_config::ConfigShapedDevices, +) -> ShapedDevicesProvenanceKey { + match provenance { + ShapedDevicesSnapshotProvenance::ExternalSnapshot => { + ShapedDevicesProvenanceKey::ExternalSnapshot { + devices_fingerprint: shaped_devices_fingerprint(&shaped.devices), + } + } + } +} + fn reload_dynamic_circuits_inner(reason: &str) { let circuits = load_dynamic_circuits_from_disk(); debug!("Loaded {} dynamic circuits reason={reason}", circuits.len()); @@ -562,17 +693,45 @@ fn shaped_device_from_unknown_ip( device } -fn reload_shaped_devices_inner(reason: &str, hooks: Option<&dyn DaemonHooks>) -> Result<()> { +fn publish_shaped_devices_if_changed( + reason: &str, + shaped: lqos_config::ConfigShapedDevices, + key: ShapedDevicesProvenanceKey, + hooks: Option<&dyn DaemonHooks>, + active_key: &mut Option, +) -> Result<()> { + if active_key.as_ref() == Some(&key) { + debug!("Skipping unchanged shaped-devices snapshot reason={reason}"); + return Ok(()); + } + + debug!("Publishing shaped-devices snapshot reason={reason}"); + state::publish_shaped_devices(shaped); + *active_key = Some(key); + prune_dynamic_circuits_superseded_by_shaped_devices_inner(hooks); + if let Some(hooks) = hooks { + hooks.on_shaped_devices_updated(); + } + Ok(()) +} + +fn reload_shaped_devices_inner( + reason: &str, + hooks: Option<&dyn DaemonHooks>, + active_key: &mut Option, +) -> Result<()> { for attempt in 1..=RELOAD_ATTEMPTS { - match load_shaped_devices() { - Ok(shaped) => { + match load_shaped_devices_with_source() { + Ok(loaded) => { debug!("Loaded shaped devices reason={reason}"); - state::publish_shaped_devices(shaped); - prune_dynamic_circuits_superseded_by_shaped_devices_inner(hooks); - if let Some(hooks) = hooks { - hooks.on_shaped_devices_updated(); - } - return Ok(()); + let key = shaped_devices_key_for_loaded(&loaded); + return publish_shaped_devices_if_changed( + reason, + loaded.shaped, + key, + hooks, + active_key, + ); } Err(err) if attempt < RELOAD_ATTEMPTS => { warn!( @@ -682,3 +841,85 @@ fn reload_network_json_inner(reason: &str, hooks: Option<&dyn DaemonHooks>) -> R } unreachable!("reload loop must return"); } + +#[cfg(test)] +mod tests { + use super::shaped_devices_fingerprint; + + fn shaped_device(circuit_id: &str, device_id: &str) -> lqos_config::ShapedDevice { + let mut device = lqos_config::ShapedDevice { + circuit_id: circuit_id.to_string(), + circuit_name: circuit_id.to_string(), + device_id: device_id.to_string(), + device_name: device_id.to_string(), + parent_node: "Tower A".to_string(), + ipv4: vec![("192.0.2.1".parse().expect("valid IP"), 32)], + download_min_mbps: 10.0, + upload_min_mbps: 10.0, + download_max_mbps: 100.0, + upload_max_mbps: 100.0, + ..lqos_config::ShapedDevice::default() + }; + device.circuit_hash = lqos_utils::hash_to_i64(&device.circuit_id); + device.device_hash = lqos_utils::hash_to_i64(&device.device_id); + device.parent_hash = lqos_utils::hash_to_i64(&device.parent_node); + device + } + + #[test] + fn shaped_devices_fingerprint_ignores_row_order() { + let first = vec![ + shaped_device("circuit-1", "device-1"), + shaped_device("circuit-2", "device-2"), + ]; + let second = vec![ + shaped_device("circuit-2", "device-2"), + shaped_device("circuit-1", "device-1"), + ]; + + assert_eq!( + shaped_devices_fingerprint(&first), + shaped_devices_fingerprint(&second) + ); + } + + #[test] + fn shaped_devices_fingerprint_ignores_address_order() { + let first = vec![shaped_device("circuit-1", "device-1")]; + let mut second = vec![shaped_device("circuit-1", "device-1")]; + second[0].ipv4 = vec![ + ("192.0.2.2".parse().expect("valid IPv4"), 32), + ("192.0.2.1".parse().expect("valid IPv4"), 32), + ]; + second[0].ipv6 = vec![ + ("2001:db8::2".parse().expect("valid IPv6"), 128), + ("2001:db8::1".parse().expect("valid IPv6"), 128), + ]; + let mut first = first; + first[0].ipv4 = vec![ + ("192.0.2.1".parse().expect("valid IPv4"), 32), + ("192.0.2.2".parse().expect("valid IPv4"), 32), + ]; + first[0].ipv6 = vec![ + ("2001:db8::1".parse().expect("valid IPv6"), 128), + ("2001:db8::2".parse().expect("valid IPv6"), 128), + ]; + + assert_eq!( + shaped_devices_fingerprint(&first), + shaped_devices_fingerprint(&second) + ); + } + + #[test] + fn shaped_devices_fingerprint_detects_payload_changes() { + let first = vec![shaped_device("circuit-1", "device-1")]; + let mut second = vec![shaped_device("circuit-1", "device-1")]; + second[0].download_max_mbps = 200.0; + + assert_ne!( + shaped_devices_fingerprint(&first), + shaped_devices_fingerprint(&second) + ); + } +} diff --git a/src/rust/lqos_network_devices/src/directory_watcher.rs b/src/rust/lqos_network_devices/src/directory_watcher.rs index e2886e4c..47d054ba 100644 --- a/src/rust/lqos_network_devices/src/directory_watcher.rs +++ b/src/rust/lqos_network_devices/src/directory_watcher.rs @@ -25,6 +25,11 @@ pub(crate) fn start_network_devices_directory_watch() -> Result<()> { "LibreQoS topology state directory", config.resolved_state_directory().join("topology"), )?; + spawn_directory_watch_thread( + "Network Devices Shaping Dir Watcher", + "LibreQoS shaping state directory", + config.resolved_state_directory().join("shaping"), + )?; Ok(()) } @@ -88,7 +93,7 @@ fn classify_changed_path(path: &Path) -> Option { "ShapedDevices.csv" | "ShapedDevices.insight.csv" | "topology_import.json" - | "topology_runtime_status.json" => Some(DirectoryReloadEvent::ShapedDevices), + | "shaping_inputs.json" => Some(DirectoryReloadEvent::ShapedDevices), "network.effective.json" | "network.insight.json" | "network.json" => { Some(DirectoryReloadEvent::NetworkJson) } @@ -118,8 +123,14 @@ mod tests { use std::path::PathBuf; #[test] - fn topology_runtime_status_triggers_shaped_device_reload() { + fn topology_runtime_status_does_not_trigger_shaped_device_reload() { let event = classify_changed_path(&PathBuf::from("/tmp/topology_runtime_status.json")); + assert_eq!(event, None); + } + + #[test] + fn shaping_inputs_triggers_shaped_device_reload() { + let event = classify_changed_path(&PathBuf::from("/tmp/shaping_inputs.json")); assert_eq!(event, Some(DirectoryReloadEvent::ShapedDevices)); } @@ -134,7 +145,7 @@ mod tests { let events = classify_changed_paths(&[ PathBuf::from("/tmp/network.json"), PathBuf::from("/tmp/network.effective.json"), - PathBuf::from("/tmp/topology_runtime_status.json"), + PathBuf::from("/tmp/shaping_inputs.json"), ]); assert_eq!( events, diff --git a/src/rust/lqos_network_devices/src/lib.rs b/src/rust/lqos_network_devices/src/lib.rs index 588381c6..6dac496b 100644 --- a/src/rust/lqos_network_devices/src/lib.rs +++ b/src/rust/lqos_network_devices/src/lib.rs @@ -20,7 +20,9 @@ mod topology; mod tests; use anyhow::{Context, Result}; -use lqos_config::{Config, ConfigShapedDevices, NetworkJson, TopologyShapingInputsFile}; +use lqos_config::{ + Config, ConfigShapedDevices, NetworkJson, TopologyShapingInputsFile, +}; use std::sync::Arc; use tracing::debug; @@ -30,6 +32,27 @@ pub use dynamic::{CircuitObservation, DynamicCircuit}; pub use hash_cache::ShapedDeviceHashCache; pub use topology::{ResolvedParentNode, resolve_parent_node, resolve_parent_node_reference}; +/// Provenance for caller-provided shaped-device snapshots. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum ShapedDevicesSnapshotProvenance { + /// Snapshot came from an external caller that already constructed a complete payload. + ExternalSnapshot, +} + +#[derive(Clone, Debug)] +pub(crate) enum LoadedShapedDevicesSource { + RuntimeTopology { + shaping_generation: String, + }, + TopologyImport, + Csv, +} + +pub(crate) struct LoadedShapedDevices { + pub(crate) shaped: ConfigShapedDevices, + pub(crate) source: LoadedShapedDevicesSource, +} + /// Hooks that `lqosd` can provide to run side effects after updates. pub trait DaemonHooks: Send + Sync + 'static { /// Called after a new `ShapedDevices.csv` snapshot is published. @@ -67,13 +90,18 @@ pub fn load_runtime_shaping_inputs_for_config( runtime_inputs::load_ready_runtime_shaping_inputs(config) } -fn load_shaped_devices_for_config(config: &lqos_config::Config) -> Result { +fn load_shaped_devices_for_config(config: &lqos_config::Config) -> Result { if lqos_config::integration_ingress_enabled(config) { if let Some(shaping_inputs) = load_runtime_shaping_inputs_for_config(config)? { let shaped_devices = runtime_inputs::shaped_devices_from_runtime_inputs(&shaping_inputs); if !shaped_devices.devices.is_empty() { - return Ok(shaped_devices); + return Ok(LoadedShapedDevices { + shaped: shaped_devices, + source: LoadedShapedDevicesSource::RuntimeTopology { + shaping_generation: shaping_inputs.shaping_generation, + }, + }); } debug!( "Active runtime shaping inputs contained 0 shaped devices; checking other integration sources" @@ -83,13 +111,19 @@ fn load_shaped_devices_for_config(config: &lqos_config::Config) -> Result { let shaped_devices = topology_import.into_imported_bundle().shaped_devices; if !shaped_devices.devices.is_empty() { - return Ok(shaped_devices); + return Ok(LoadedShapedDevices { + shaped: shaped_devices, + source: LoadedShapedDevicesSource::TopologyImport, + }); } debug!( "topology_import.json advertised shaped devices but loaded empty; keeping integration mode empty until topology is published" @@ -106,16 +140,28 @@ fn load_shaped_devices_for_config(config: &lqos_config::Config) -> Result Result { + Ok(load_shaped_devices_with_source()?.shaped) +} + +pub(crate) fn load_shaped_devices_with_source() -> Result { let config = lqos_config::load_config().context("Unable to load /etc/lqos.conf")?; load_shaped_devices_for_config(config.as_ref()) } @@ -183,8 +229,12 @@ pub fn request_reload_network_json(reason: &str) -> Result<()> { } /// Publishes a caller-provided shaped-devices snapshot through the runtime actor. -pub fn apply_shaped_devices_snapshot(reason: &str, shaped: ConfigShapedDevices) -> Result<()> { - actor::apply_shaped_devices_snapshot(reason, shaped) +pub fn apply_shaped_devices_snapshot( + reason: &str, + shaped: ConfigShapedDevices, + provenance: ShapedDevicesSnapshotProvenance, +) -> Result<()> { + actor::apply_shaped_devices_snapshot(reason, shaped, provenance) } /// Reports kernel observations that may indicate dynamic circuit activity. diff --git a/src/rust/lqos_network_devices/src/tests.rs b/src/rust/lqos_network_devices/src/tests.rs index 2d71ade6..3c1f5df0 100644 --- a/src/rust/lqos_network_devices/src/tests.rs +++ b/src/rust/lqos_network_devices/src/tests.rs @@ -431,8 +431,8 @@ fn load_shaped_devices_uses_topology_import_when_runtime_inputs_are_empty() { let loaded = load_shaped_devices_for_config(&config) .expect("preferred shaped-device source should load"); - assert_eq!(loaded.devices.len(), 1); - assert_eq!(loaded.devices[0].circuit_id, "import-circuit"); + assert_eq!(loaded.shaped.devices.len(), 1); + assert_eq!(loaded.shaped.devices[0].circuit_id, "import-circuit"); } #[test] @@ -493,8 +493,8 @@ fn load_shaped_devices_uses_topology_import_when_runtime_is_not_ready() { let loaded = load_shaped_devices_for_config(&config).expect("topology import fallback should load"); - assert_eq!(loaded.devices.len(), 1); - assert_eq!(loaded.devices[0].circuit_id, "import-circuit"); + assert_eq!(loaded.shaped.devices.len(), 1); + assert_eq!(loaded.shaped.devices[0].circuit_id, "import-circuit"); } #[test] @@ -534,7 +534,7 @@ fn load_shaped_devices_stays_empty_when_topology_import_is_empty() { let loaded = load_shaped_devices_for_config(&config).expect("integration mode should stay empty"); - assert!(loaded.devices.is_empty()); + assert!(loaded.shaped.devices.is_empty()); } #[test] @@ -582,8 +582,8 @@ fn load_shaped_devices_ignores_stale_runtime_inputs_in_manual_mode() { let loaded = load_shaped_devices_for_config(&config).expect("manual mode should use shaped devices csv"); - assert_eq!(loaded.devices.len(), 1); - assert_eq!(loaded.devices[0].circuit_id, "csv-circuit"); + assert_eq!(loaded.shaped.devices.len(), 1); + assert_eq!(loaded.shaped.devices[0].circuit_id, "csv-circuit"); } #[test] @@ -610,5 +610,5 @@ fn load_shaped_devices_stays_empty_when_runtime_status_is_malformed() { let loaded = load_shaped_devices_for_config(&config).expect("malformed status should stay empty"); - assert!(loaded.devices.is_empty()); + assert!(loaded.shaped.devices.is_empty()); } diff --git a/src/rust/lqos_topology/src/lib.rs b/src/rust/lqos_topology/src/lib.rs index ae8a6da2..29e698f5 100644 --- a/src/rust/lqos_topology/src/lib.rs +++ b/src/rust/lqos_topology/src/lib.rs @@ -1696,6 +1696,13 @@ pub fn publish_topology_runtime_status( ready, error, ); + if TopologyRuntimeStatusFile::load(config) + .ok() + .as_ref() + .is_some_and(|current| current.semantic_equals_for_publish(&status)) + { + return Ok(()); + } status.save(config).with_context(|| { format!( "Unable to publish topology runtime status at {:?}", diff --git a/src/rust/lqos_topology/src/runtime.rs b/src/rust/lqos_topology/src/runtime.rs index 1a8b763d..50a58a1d 100644 --- a/src/rust/lqos_topology/src/runtime.rs +++ b/src/rust/lqos_topology/src/runtime.rs @@ -2,12 +2,14 @@ use anyhow::{Context, Result}; use lqos_bus::{BusRequest, BusResponse, bus_request}; use lqos_config::{ TopologyAttachmentEndpointStatus, TopologyAttachmentHealthEntry, - TopologyAttachmentHealthStateFile, TopologyAttachmentHealthStatus, + TopologyAttachmentHealthStateFile, TopologyAttachmentHealthStatus, TopologyCanonicalStateFile, compute_topology_source_generation, load_config, }; use lqos_overrides::TopologyOverridesFile; use lqos_probe::{ProbeClass, ProbeRequest}; use std::collections::HashMap; +use std::collections::hash_map::DefaultHasher; +use std::hash::{Hash, Hasher}; use std::net::IpAddr; use std::time::{Duration, SystemTime, UNIX_EPOCH}; use tracing::{info, warn}; @@ -313,6 +315,61 @@ fn refresh_health_state( Ok(true) } +fn hash_health_status(status: TopologyAttachmentHealthStatus, hasher: &mut impl Hasher) { + match status { + TopologyAttachmentHealthStatus::Healthy => 0_u8.hash(hasher), + TopologyAttachmentHealthStatus::Suppressed => 1_u8.hash(hasher), + TopologyAttachmentHealthStatus::ProbeUnavailable => 2_u8.hash(hasher), + TopologyAttachmentHealthStatus::Disabled => 3_u8.hash(hasher), + } +} + +fn hash_health_effective_entry(entry: &TopologyAttachmentHealthEntry, hasher: &mut impl Hasher) { + entry.attachment_pair_id.hash(hasher); + entry.attachment_id.hash(hasher); + entry.child_node_id.hash(hasher); + entry.parent_node_id.hash(hasher); + entry.local_probe_ip.hash(hasher); + entry.remote_probe_ip.hash(hasher); + hash_health_status(entry.status, hasher); + entry.probeable.hash(hasher); + entry.enabled.hash(hasher); + entry.suppressed_until_unix.hash(hasher); +} + +fn health_effective_signature(health_state: &TopologyAttachmentHealthStateFile) -> u64 { + let mut hasher = DefaultHasher::new(); + for entry in &health_state.attachments { + hash_health_effective_entry(entry, &mut hasher); + } + hasher.finish() +} + +#[derive(Clone, Debug, Default)] +struct RuntimeBuildGate { + last_source_generation: Option, + last_overrides_generation: Option, + last_health_effective_signature: Option, + cached_probe_specs: Vec, + publish_completed: bool, + next_error_retry_after_unix: Option, +} + +fn topology_overrides_generation(config: &lqos_config::Config) -> u64 { + let path = TopologyOverridesFile::path_for_config(config); + let mut hasher = DefaultHasher::new(); + path.hash(&mut hasher); + if let Ok(contents) = std::fs::read(&path) { + match serde_json::from_slice::(&contents) + .and_then(|overrides| serde_json::to_vec(&overrides)) + { + Ok(canonical) => canonical.hash(&mut hasher), + Err(_) => contents.hash(&mut hasher), + } + } + hasher.finish() +} + #[derive(Clone, Copy, Debug, Default)] struct RoundHints { probes_enabled: bool, @@ -321,29 +378,62 @@ struct RoundHints { async fn run_round( health_state: &mut TopologyAttachmentHealthStateFile, last_effective: &mut HashMap>, + gate: &mut RuntimeBuildGate, ) -> Result { let config = load_config().context("Unable to load config for topology runtime")?; let source_generation = compute_topology_source_generation(config.as_ref()) .context("Unable to compute topology source generation")?; - let canonical = load_canonical_topology_state(config.as_ref()); - let overrides = - TopologyOverridesFile::load().context("Unable to load topology overrides file")?; - let prepared = prepare_runtime_topology_editor_state_from_canonical(&canonical, &overrides); - let specs = probe_specs_from_state(&prepared, &overrides); + let overrides_generation = topology_overrides_generation(config.as_ref()); + let source_changed = gate.last_source_generation.as_deref() != Some(source_generation.as_str()); + let overrides_changed = gate.last_overrides_generation != Some(overrides_generation); + let mut loaded_inputs: Option<(TopologyCanonicalStateFile, TopologyOverridesFile)> = None; + if source_changed || overrides_changed || gate.cached_probe_specs.is_empty() { + let canonical = load_canonical_topology_state(config.as_ref()); + let overrides = + TopologyOverridesFile::load().context("Unable to load topology overrides file")?; + let prepared = prepare_runtime_topology_editor_state_from_canonical(&canonical, &overrides); + gate.cached_probe_specs = probe_specs_from_state(&prepared, &overrides); + loaded_inputs = Some((canonical, overrides)); + } + let specs = &gate.cached_probe_specs; let probes_enabled = specs.iter().any(|spec| spec.enabled); if probes_enabled { - match probe_specs(&specs, Duration::from_millis(750)).await { + match probe_specs(specs, Duration::from_millis(750)).await { Ok(probe_results) => { - refresh_health_state(config.as_ref(), health_state, &specs, &probe_results)?; + refresh_health_state(config.as_ref(), health_state, specs, &probe_results)?; } Err(err) => { warn!("Topology probe round could not query shared probe manager: {err:#}"); } } } else { - refresh_health_state(config.as_ref(), health_state, &specs, &HashMap::new())?; + refresh_health_state(config.as_ref(), health_state, specs, &HashMap::new())?; + } + + let next_signature = health_effective_signature(health_state); + let retry_due = gate + .next_error_retry_after_unix + .is_some_and(|deadline| now_unix().is_some_and(|now| now >= deadline)); + let retry_pending = gate.next_error_retry_after_unix.is_some() && !retry_due; + let source_or_health_changed = source_changed + || overrides_changed + || gate.last_health_effective_signature.as_ref() != Some(&next_signature); + let should_publish = + source_or_health_changed || (!retry_pending && (!gate.publish_completed || retry_due)); + if !should_publish { + return Ok(RoundHints { probes_enabled }); } + let (canonical, overrides) = match loaded_inputs { + Some(inputs) => inputs, + None => { + let canonical = load_canonical_topology_state(config.as_ref()); + let overrides = + TopologyOverridesFile::load().context("Unable to load topology overrides file")?; + (canonical, overrides) + } + }; + let artifacts = build_effective_topology_artifacts_from_canonical_with_runtime_queue_context( config.as_ref(), &canonical, @@ -368,8 +458,21 @@ async fn run_round( "Unable to publish failed topology runtime status after publish error: {status_err:#}" ); } + let health = &config.integration_common.topology_attachment_health; + let retry_delay = health + .refresh_debounce_seconds + .max(health.probe_interval_seconds.max(1)); + gate.last_source_generation = Some(source_generation.clone()); + gate.last_overrides_generation = Some(overrides_generation); + gate.last_health_effective_signature = Some(next_signature); + gate.next_error_retry_after_unix = now_unix().map(|now| now.saturating_add(retry_delay)); return Err(err); } + gate.last_source_generation = Some(source_generation.clone()); + gate.last_overrides_generation = Some(overrides_generation); + gate.last_health_effective_signature = Some(next_signature); + gate.publish_completed = true; + gate.next_error_retry_after_unix = None; for node in &artifacts.effective.nodes { let next = node.effective_attachment_id.clone(); @@ -394,9 +497,12 @@ async fn run_round( pub async fn start_topology() { let mut health_state = load_starting_health(); let mut last_effective = HashMap::>::new(); + let mut build_gate = RuntimeBuildGate::default(); loop { - let round_hints = match run_round(&mut health_state, &mut last_effective).await { + let round_hints = match run_round(&mut health_state, &mut last_effective, &mut build_gate) + .await + { Ok(hints) => hints, Err(err) => { if let Ok(config) = load_config() @@ -434,3 +540,102 @@ pub async fn start_topology() { tokio::time::sleep(Duration::from_secs(sleep_seconds)).await; } } + +#[cfg(test)] +mod tests { + use super::{ + TopologyAttachmentHealthEntry, health_effective_signature, topology_overrides_generation, + }; + use lqos_config::{Config, TopologyAttachmentHealthStateFile, TopologyAttachmentHealthStatus}; + use lqos_overrides::TopologyOverridesFile; + use std::fs; + use std::time::{SystemTime, UNIX_EPOCH}; + + fn unique_temp_dir(prefix: &str) -> std::path::PathBuf { + let unique = SystemTime::now() + .duration_since(UNIX_EPOCH) + .expect("system time should be valid") + .as_nanos(); + std::env::temp_dir().join(format!("{prefix}-{}-{unique}", std::process::id())) + } + + fn health_entry() -> TopologyAttachmentHealthEntry { + TopologyAttachmentHealthEntry { + attachment_pair_id: "pair-1".to_string(), + attachment_id: Some("attachment-1".to_string()), + child_node_id: Some("child-1".to_string()), + parent_node_id: Some("parent-1".to_string()), + local_probe_ip: Some("192.0.2.1".to_string()), + remote_probe_ip: Some("192.0.2.2".to_string()), + status: TopologyAttachmentHealthStatus::Healthy, + probeable: true, + enabled: true, + consecutive_misses: 1, + consecutive_successes: 2, + last_success_unix: Some(10), + endpoint_status: vec![], + ..TopologyAttachmentHealthEntry::default() + } + } + + #[test] + fn health_effective_signature_ignores_probe_counters_and_timestamps() { + let first = TopologyAttachmentHealthStateFile { + generated_unix: Some(1), + attachments: vec![health_entry()], + ..TopologyAttachmentHealthStateFile::default() + }; + let mut second_entry = health_entry(); + second_entry.consecutive_misses = 4; + second_entry.consecutive_successes = 5; + second_entry.last_success_unix = Some(20); + second_entry.last_failure_unix = Some(21); + let second = TopologyAttachmentHealthStateFile { + generated_unix: Some(2), + attachments: vec![second_entry], + ..TopologyAttachmentHealthStateFile::default() + }; + + assert_eq!( + health_effective_signature(&first), + health_effective_signature(&second) + ); + } + + #[test] + fn health_effective_signature_tracks_suppression_status() { + let first = TopologyAttachmentHealthStateFile { + attachments: vec![health_entry()], + ..TopologyAttachmentHealthStateFile::default() + }; + let mut suppressed = health_entry(); + suppressed.status = TopologyAttachmentHealthStatus::Suppressed; + suppressed.suppressed_until_unix = Some(123); + let second = TopologyAttachmentHealthStateFile { + attachments: vec![suppressed], + ..TopologyAttachmentHealthStateFile::default() + }; + + assert_ne!( + health_effective_signature(&first), + health_effective_signature(&second) + ); + } + + #[test] + fn topology_overrides_generation_tracks_manual_override_file_changes() { + let lqos_directory = unique_temp_dir("lqos-topology-runtime-overrides"); + fs::create_dir_all(&lqos_directory).expect("temp lqos directory should exist"); + let config = Config { + lqos_directory: lqos_directory.to_string_lossy().to_string(), + ..Config::default() + }; + let path = TopologyOverridesFile::path_for_config(&config); + + let before = topology_overrides_generation(&config); + fs::write(&path, "{\"schemaVersion\":1}\n").expect("override file should write"); + let after = topology_overrides_generation(&config); + + assert_ne!(before, after); + } +} diff --git a/src/rust/lqosd/src/main.rs b/src/rust/lqosd/src/main.rs index 7b856014..6976a159 100644 --- a/src/rust/lqosd/src/main.rs +++ b/src/rust/lqosd/src/main.rs @@ -383,7 +383,7 @@ fn main() -> Result<()> { let _ = throughput_tracker::flow_data::setup_flow_analysis(); start_heimdall()?; spawn_queue_structure_monitor()?; - shaped_devices_tracker::shaping_inputs_watcher()?; + shaped_devices_tracker::topology_runtime_status_watcher()?; throughput_tracker::spawn_throughput_monitor( flow_tx, system_usage_tx.clone(), diff --git a/src/rust/lqosd/src/node_manager/local_api/config.rs b/src/rust/lqosd/src/node_manager/local_api/config.rs index a024764b..0d86926a 100644 --- a/src/rust/lqosd/src/node_manager/local_api/config.rs +++ b/src/rust/lqosd/src/node_manager/local_api/config.rs @@ -785,6 +785,7 @@ fn persist_shaped_devices(mut devices: Vec) -> Result<(), String> lqos_network_devices::apply_shaped_devices_snapshot( "node_manager:persist_shaped_devices", copied, + lqos_network_devices::ShapedDevicesSnapshotProvenance::ExternalSnapshot, ) .map_err(|e| format!("Unable to publish ShapedDevices.csv snapshot: {e}"))?; diff --git a/src/rust/lqosd/src/shaped_devices_tracker/mod.rs b/src/rust/lqosd/src/shaped_devices_tracker/mod.rs index dee9d7b5..20959e14 100644 --- a/src/rust/lqosd/src/shaped_devices_tracker/mod.rs +++ b/src/rust/lqosd/src/shaped_devices_tracker/mod.rs @@ -5,11 +5,13 @@ use arc_swap::ArcSwap; use fxhash::{FxHashMap, FxHashSet}; use lqos_bus::{BusResponse, Circuit}; use lqos_config::{ - NetworkJsonNode, NetworkJsonTransport, TopologyShapingInputsFile, load_config, + NetworkJsonNode, NetworkJsonTransport, TopologyRuntimeShapingPayloadIdentity, + TopologyRuntimeStatusFile, TopologyShapingInputsFile, + load_active_runtime_shaping_inputs_from_status, load_config, topology_runtime_status_path, }; #[cfg(test)] -use lqos_config::{TopologyRuntimeStatusFile, topology_shaping_inputs_path}; +use lqos_config::load_active_runtime_shaping_inputs; use lqos_queue_tracker::EFFECTIVE_NODE_RATES; use lqos_utils::file_watcher::FileWatcher; use lqos_utils::hash_to_i64; @@ -18,8 +20,6 @@ use lqos_utils::units::{DownUpOrder, down_up_retransmit_sample}; use lqos_utils::unix_time::time_since_boot; use once_cell::sync::Lazy; use parking_lot::Mutex; -#[cfg(test)] -use std::path::PathBuf; use std::sync::Arc; use std::sync::atomic::AtomicU64; use std::time::Duration; @@ -42,6 +42,8 @@ pub static CIRCUIT_LIVE_LAST_REFRESH_SECS: AtomicU64 = AtomicU64::new(0); pub static CIRCUIT_LIVE_REFRESH_LOCK: Lazy> = Lazy::new(|| Mutex::new(())); pub static EFFECTIVE_CIRCUIT_PARENTS: Lazy>> = Lazy::new(|| ArcSwap::new(Arc::new(FxHashMap::default()))); +static LAST_TOPOLOGY_STATUS_IDENTITY: Lazy>> = + Lazy::new(|| Mutex::new(None)); #[derive(Clone, Debug, PartialEq, Eq)] pub struct RuntimeCircuitParent { @@ -104,38 +106,16 @@ fn publish_shaping_inputs(shaping_inputs: TopologyShapingInputsFile) { invalidate_executive_cache_snapshot(); } -#[cfg(test)] -fn active_runtime_shaping_inputs_path(config: &lqos_config::Config) -> Result> { - let status = TopologyRuntimeStatusFile::load(config)?; - if !status.ready { - return Ok(None); - } - let path = status.shaping_inputs_path.trim(); - if path.is_empty() { - return Ok(None); - } - Ok(Some(PathBuf::from(path))) +fn topology_status_identity(status: &TopologyRuntimeStatusFile) -> TopologyRuntimeShapingPayloadIdentity { + status.shaping_payload_identity() } -#[cfg(test)] -fn load_active_runtime_shaping_inputs( - config: &lqos_config::Config, -) -> Result> { - if let Some(active_path) = active_runtime_shaping_inputs_path(config)? - && active_path.exists() - { - let raw = std::fs::read_to_string(&active_path)?; - let shaping_inputs = serde_json::from_str(&raw)?; - return Ok(Some(shaping_inputs)); - } +fn topology_status_identity_changed(identity: &TopologyRuntimeShapingPayloadIdentity) -> bool { + LAST_TOPOLOGY_STATUS_IDENTITY.lock().as_ref() != Some(identity) +} - let fallback_path = topology_shaping_inputs_path(config); - if !fallback_path.exists() { - return Ok(None); - } - let raw = std::fs::read_to_string(&fallback_path)?; - let shaping_inputs = serde_json::from_str(&raw)?; - Ok(Some(shaping_inputs)) +fn remember_topology_status_identity(identity: TopologyRuntimeShapingPayloadIdentity) { + *LAST_TOPOLOGY_STATUS_IDENTITY.lock() = Some(identity); } #[cfg(test)] @@ -257,21 +237,8 @@ fn integration_ingress_enabled(config: &lqos_config::Config) -> bool { fn load_ready_runtime_shaping_inputs( config: &lqos_config::Config, ) -> Result> { - let Some(active_path) = active_runtime_shaping_inputs_path(config)? else { - return Ok(None); - }; - if !active_path.exists() { - return Ok(None); - } - let raw = std::fs::read_to_string(&active_path) - .with_context(|| format!("Unable to read shaping inputs at {}", active_path.display()))?; - let shaping_inputs = serde_json::from_str(&raw).with_context(|| { - format!( - "Unable to decode shaping inputs JSON at {}", - active_path.display() - ) - })?; - Ok(Some(shaping_inputs)) + load_active_runtime_shaping_inputs(config) + .context("Unable to load active runtime shaping inputs") } #[cfg(test)] @@ -311,16 +278,28 @@ fn load_shaped_devices_from_preferred_source( ConfigShapedDevices::load_for_config(config).context("Unable to load ShapedDevices.csv")?; Ok((shaped_devices, ShapedDevicesLoadSource::ShapedDevicesCsv)) } -fn load_shaping_inputs() { +fn load_topology_runtime_status_payload() { let Ok(config) = load_config() else { - warn!("Unable to load LibreQoS config while loading shaping_inputs.json"); - publish_shaping_inputs(TopologyShapingInputsFile::default()); + warn!("Unable to load LibreQoS config while loading topology runtime status"); return; }; - match lqos_network_devices::load_runtime_shaping_inputs_for_config(config.as_ref()) { + let status = match TopologyRuntimeStatusFile::load(config.as_ref()) { + Ok(status) => status, + Err(err) => { + warn!("Unable to load topology_runtime_status.json: {err}; keeping last-known-good effective parent cache"); + return; + } + }; + let identity = topology_status_identity(&status); + if !topology_status_identity_changed(&identity) { + debug!("Topology runtime status changed without shaping payload identity change"); + return; + } + match load_active_runtime_shaping_inputs_from_status(config.as_ref(), &status) { Ok(Some(shaping_inputs)) => { debug!("Loaded shaping inputs from active runtime status"); publish_shaping_inputs(shaping_inputs); + remember_topology_status_identity(identity); } Ok(None) => { if lqos_config::integration_ingress_enabled(config.as_ref()) { @@ -329,9 +308,11 @@ fn load_shaping_inputs() { debug!( "No active runtime shaping inputs published; keeping last-known-good effective parent cache" ); + remember_topology_status_identity(identity); } else { debug!("Integration ingress disabled; clearing effective parent cache"); publish_shaping_inputs(TopologyShapingInputsFile::default()); + remember_topology_status_identity(identity); } } Err(err) => { @@ -342,31 +323,31 @@ fn load_shaping_inputs() { } } -pub fn shaping_inputs_watcher() -> Result<()> { +pub fn topology_runtime_status_watcher() -> Result<()> { std::thread::Builder::new() - .name("Shaping Inputs Watcher".to_string()) + .name("Topology Runtime Status Watcher".to_string()) .spawn(|| { - debug!("Watching for shaping_inputs.json changes"); - if let Err(e) = watch_for_shaping_inputs_changing() { - error!("Error watching for shaping_inputs.json changes: {:?}", e); + debug!("Watching for topology_runtime_status.json changes"); + if let Err(e) = watch_for_topology_runtime_status_changing() { + error!("Error watching topology_runtime_status.json: {:?}", e); } })?; Ok(()) } -fn watch_for_shaping_inputs_changing() -> Result<()> { +fn watch_for_topology_runtime_status_changing() -> Result<()> { let Ok(config) = load_config() else { - error!("Unable to load LibreQoS config to watch shaping_inputs.json"); + error!("Unable to load LibreQoS config to watch topology_runtime_status.json"); return Err(anyhow::Error::msg( - "Unable to load LibreQoS config for shaping_inputs.json", + "Unable to load LibreQoS config for topology_runtime_status.json", )); }; let watch_path = topology_runtime_status_path(config.as_ref()); let mut watcher = FileWatcher::new("topology_runtime_status.json", watch_path); - watcher.set_file_exists_callback(load_shaping_inputs); - watcher.set_file_created_callback(load_shaping_inputs); - watcher.set_file_changed_callback(load_shaping_inputs); + watcher.set_file_exists_callback(load_topology_runtime_status_payload); + watcher.set_file_created_callback(load_topology_runtime_status_payload); + watcher.set_file_changed_callback(load_topology_runtime_status_payload); loop { let result = watcher.watch(); info!("topology_runtime_status.json watcher returned: {result:?}"); -- knotmirror 0.0.1 From f9921850d1a74bba0a397a46c77e6e60dc8d11cf Mon Sep 17 00:00:00 2001 From: rchac Date: Wed, 6 May 2026 12:34:43 +0000 Subject: [PATCH 46/51] changes --- src/rust/lqos_overrides/src/file_lock.rs | 4 ++-- src/rust/lqos_overrides/src/overrides_file.rs | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/rust/lqos_overrides/src/file_lock.rs b/src/rust/lqos_overrides/src/file_lock.rs index 40cfdae6..14dcc54c 100644 --- a/src/rust/lqos_overrides/src/file_lock.rs +++ b/src/rust/lqos_overrides/src/file_lock.rs @@ -64,7 +64,7 @@ impl FileLock { } let unix_path = CString::new(LOCK_PATH)?; unsafe { - nix::libc::chmod(unix_path.as_ptr(), mode_t::from_le(666)); + nix::libc::chmod(unix_path.as_ptr(), mode_t::from_le(0o666)); } Ok(()) } @@ -77,7 +77,7 @@ impl FileLock { std::fs::create_dir(dir_path)?; let unix_path = CString::new(LOCK_DIR_PERMS)?; unsafe { - nix::libc::chmod(unix_path.as_ptr(), 777); + nix::libc::chmod(unix_path.as_ptr(), 0o777); } Ok(()) } diff --git a/src/rust/lqos_overrides/src/overrides_file.rs b/src/rust/lqos_overrides/src/overrides_file.rs index e63eb461..3d4eaebc 100644 --- a/src/rust/lqos_overrides/src/overrides_file.rs +++ b/src/rust/lqos_overrides/src/overrides_file.rs @@ -1130,15 +1130,15 @@ impl OverrideStore { /// /// This function reads override files from the config's LibreQoS directory without /// reloading `/etc/lqos.conf`. + /// + /// Side effects: reads override files from disk and may create the operator + /// overrides file if it does not exist. pub fn load_effective_for_config( config: &lqos_config::Config, apply_stormguard: bool, apply_treeguard: bool, ) -> Result { - let lock = FileLock::new()?; - let merged = Self::load_effective_for_config_inner(config, apply_stormguard, apply_treeguard)?; - drop(lock); - Ok(merged) + Self::load_effective_for_config_inner(config, apply_stormguard, apply_treeguard) } fn load_effective_for_config_inner( -- knotmirror 0.0.1 From adbdf603e522b3a467f6303f11db3d891cfc0116 Mon Sep 17 00:00:00 2001 From: rchac Date: Wed, 6 May 2026 10:39:43 -0600 Subject: [PATCH 47/51] changes --- src/build_dpkg.sh | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/src/build_dpkg.sh b/src/build_dpkg.sh index 32d8a474..06925ca7 100755 --- a/src/build_dpkg.sh +++ b/src/build_dpkg.sh @@ -157,10 +157,20 @@ install -m 0644 /opt/libreqos/src/bin/lqos_api.service.example /etc/systemd/syst install -m 0644 /opt/libreqos/src/bin/lqos_setup.service.example /etc/systemd/system/lqos_setup.service /bin/rm -f /etc/systemd/system/lqos_netplan_helper.service || true /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 stop lqos_netplan_helper || true -/bin/systemctl disable lqos_netplan_helper || true + +unit_stop_disable_if_present() { +local unit="$1" +if /bin/systemctl cat "${unit}" >/dev/null 2>&1 \ + || [ -e "/etc/systemd/system/${unit}" ] \ + || [ -e "/lib/systemd/system/${unit}" ] \ + || [ -e "/usr/lib/systemd/system/${unit}" ]; then + /bin/systemctl stop "${unit}" || true + /bin/systemctl disable "${unit}" || true +fi +} + +unit_stop_disable_if_present lqos_node_manager.service # In case it's running from a previous release +unit_stop_disable_if_present lqos_netplan_helper.service case "$(/opt/libreqos/src/bin/lqos_setup postinst-action)" in activate_runtime) /opt/libreqos/src/bin/lqos_setup activate-runtime -- knotmirror 0.0.1 From 4bea5eb05738dbb1a117785e1364f9ff418a7339 Mon Sep 17 00:00:00 2001 From: rchac Date: Wed, 6 May 2026 18:40:43 +0000 Subject: [PATCH 48/51] changes --- src/LibreQoS.py | 103 +++++++-- src/rust/lqos_bus/src/bus/protocol.rs | 13 ++ src/rust/lqos_bus/src/bus/request.rs | 8 + src/rust/lqos_python/src/lib.rs | 55 +++++ src/rust/lqos_sys/src/lib.rs | 1 + src/rust/lqos_sys/src/lqos_kernel.rs | 211 +++++++++++++----- src/rust/lqosd/src/main.rs | 34 +++ .../lqosd/src/shaped_devices_tracker/mod.rs | 15 +- src/rust/lqosd/src/urgent.rs | 80 ++++++- src/test_xdp_mapping_recovery.py | 124 ++++++++++ 10 files changed, 571 insertions(+), 73 deletions(-) create mode 100644 src/test_xdp_mapping_recovery.py diff --git a/src/LibreQoS.py b/src/LibreQoS.py index 93f17ac4..67e04899 100755 --- a/src/LibreQoS.py +++ b/src/LibreQoS.py @@ -51,13 +51,37 @@ from liblqos_python import is_lqosd_alive, clear_ip_mappings, delete_ip_mapping, shaping_cpu_count, \ Bakery -# Optional: urgent issue submission (available in newer liblqos_python) +# Optional: urgent issue helpers (available in newer liblqos_python) try: from liblqos_python import submit_urgent_issue # type: ignore except Exception: def submit_urgent_issue(*_args, **_kwargs): return False +try: + from liblqos_python import clear_urgent_issue_by_identity # type: ignore +except ImportError: + _missing_clear_urgent_issue_by_identity_warned = False + + def clear_urgent_issue_by_identity(*_args, **_kwargs): + global _missing_clear_urgent_issue_by_identity_warned + if not _missing_clear_urgent_issue_by_identity_warned: + logging.warning("Unable to clear recovered urgent issues: liblqos_python helper is unavailable") + _missing_clear_urgent_issue_by_identity_warned = True + return False + +try: + from liblqos_python import xdp_ip_mapping_ready # type: ignore +except ImportError: + _missing_xdp_ip_mapping_ready_warned = False + + def xdp_ip_mapping_ready(): + global _missing_xdp_ip_mapping_ready_warned + if not _missing_xdp_ip_mapping_ready_warned: + logging.warning("Unable to check XDP IP mapping readiness: liblqos_python helper is unavailable") + _missing_xdp_ip_mapping_ready_warned = True + return True + try: from liblqos_python import calculate_topology_source_generation # type: ignore except Exception: @@ -78,6 +102,11 @@ class ValidationFailure(RefreshFailure): pass +XDP_IP_MAPPING_APPLY_FAILED = "XDP_IP_MAPPING_APPLY_FAILED" +XDP_MAPPING_READY_TIMEOUT_SECONDS = 5.0 +XDP_MAPPING_READY_INTERVAL_SECONDS = 0.1 + + def report_refresh_failure(code, message, context=None, dedupe_key=None): logging.error(message) print("ERROR: " + message) @@ -98,6 +127,56 @@ def report_refresh_failure(code, message, context=None, dedupe_key=None): pass raise RefreshFailure(message) + +def wait_for_xdp_ip_mapping_ready( + ready=xdp_ip_mapping_ready, + sleep=time.sleep, + now=time.monotonic, + timeout_seconds=XDP_MAPPING_READY_TIMEOUT_SECONDS, + interval_seconds=XDP_MAPPING_READY_INTERVAL_SECONDS, +): + deadline = now() + timeout_seconds + while now() < deadline: + if ready(): + return + sleep(interval_seconds) + raise TimeoutError("XDP IP mapping BPF maps are not ready") + + +def apply_xdp_ip_mappings( + ip_map_batch, + context, + ready=xdp_ip_mapping_ready, + sleep=time.sleep, + report_failure=report_refresh_failure, + clear_recovered_issue=clear_urgent_issue_by_identity, +): + try: + wait_for_xdp_ip_mapping_ready(ready=ready, sleep=sleep) + except (TimeoutError, OSError) as exc: + report_failure( + XDP_IP_MAPPING_APPLY_FAILED, + "Failed to apply XDP IP mappings: " + str(exc), + context, + XDP_IP_MAPPING_APPLY_FAILED, + ) + return + try: + ip_map_batch.finish_ip_mappings() + ip_map_batch.submit() + except OSError as exc: + report_failure( + XDP_IP_MAPPING_APPLY_FAILED, + "Failed to apply XDP IP mappings: " + str(exc), + context, + XDP_IP_MAPPING_APPLY_FAILED, + ) + return + try: + clear_recovered_issue(XDP_IP_MAPPING_APPLY_FAILED, XDP_IP_MAPPING_APPLY_FAILED) + except OSError as exc: + logging.warning("Unable to clear recovered XDP IP mapping urgent issue: %s", exc) + R2Q = 10 #MAX_R2Q = 200_000 MAX_R2Q = 60_000 # See https://lartc.vger.kernel.narkive.com/NKaH1ZNG/htb-quantum-of-class-100001-is-small-consider-r2q-change @@ -2757,20 +2836,14 @@ def refreshShapers(): print("Observe mode active; skipping XDP-CPUMAP-TC IP filter apply after clearing mappings") numXdpCommands = 0 else: - ipMapBatch.finish_ip_mappings() - try: - ipMapBatch.submit() - except Exception as e: - report_refresh_failure( - "XDP_IP_MAPPING_APPLY_FAILED", - "Failed to apply XDP IP mappings: " + str(e), - { - "required_ip_mappings": requiredIpMappings, - "queued_requests": numXdpCommands, - "on_a_stick": on_a_stick(), - }, - "XDP_IP_MAPPING_APPLY_FAILED", - ) + apply_xdp_ip_mappings( + ipMapBatch, + { + "required_ip_mappings": requiredIpMappings, + "queued_requests": numXdpCommands, + "on_a_stick": on_a_stick(), + }, + ) #for command in xdpCPUmapCommands: # logging.info(command) # commands = command.split(' ') diff --git a/src/rust/lqos_bus/src/bus/protocol.rs b/src/rust/lqos_bus/src/bus/protocol.rs index ce68d635..6d48ac66 100644 --- a/src/rust/lqos_bus/src/bus/protocol.rs +++ b/src/rust/lqos_bus/src/bus/protocol.rs @@ -171,6 +171,19 @@ mod tests { assert_eq!(decoded.requests, session.requests); } + #[test] + fn cbor_round_trip_clear_urgent_issue_by_identity_request() { + let session = BusSession { + requests: vec![BusRequest::ClearUrgentIssueByIdentity { + code: "XDP_IP_MAPPING_APPLY_FAILED".to_string(), + dedupe_key: "XDP_IP_MAPPING_APPLY_FAILED".to_string(), + }], + }; + let bytes = encode_session_cbor(&session).expect("encode_session_cbor"); + let decoded = decode_session_cbor(&bytes).expect("decode_session_cbor"); + assert_eq!(decoded.requests, session.requests); + } + #[test] fn cbor_round_trip_reply() { let reply = BusReply { diff --git a/src/rust/lqos_bus/src/bus/request.rs b/src/rust/lqos_bus/src/bus/request.rs index e2561fd9..1209ed21 100644 --- a/src/rust/lqos_bus/src/bus/request.rs +++ b/src/rust/lqos_bus/src/bus/request.rs @@ -539,6 +539,14 @@ pub enum BusRequest { /// Clear a specific urgent issue by ID ClearUrgentIssue(u64), + /// Clear urgent issues matching a code and dedupe key + ClearUrgentIssueByIdentity { + /// Machine-readable issue code + code: String, + /// Dedupe key used when the issue was submitted + dedupe_key: String, + }, + /// Clear all urgent issues ClearAllUrgentIssues, diff --git a/src/rust/lqos_python/src/lib.rs b/src/rust/lqos_python/src/lib.rs index 4c2c9484..788b7cef 100644 --- a/src/rust/lqos_python/src/lib.rs +++ b/src/rust/lqos_python/src/lib.rs @@ -942,6 +942,7 @@ fn liblqos_python(m: &Bound<'_, PyModule>) -> PyResult<()> { m.add_function(wrap_pyfunction!(add_ip_mapping, m)?)?; m.add_function(wrap_pyfunction!(validate_shaped_devices, m)?)?; m.add_function(wrap_pyfunction!(wait_for_bus_ready, m)?)?; + m.add_function(wrap_pyfunction!(xdp_ip_mapping_ready, m)?)?; m.add_function(wrap_pyfunction!(is_libre_already_running, m)?)?; m.add_function(wrap_pyfunction!(create_lock_file, m)?)?; m.add_function(wrap_pyfunction!(free_lock_file, m)?)?; @@ -1084,6 +1085,7 @@ fn liblqos_python(m: &Bound<'_, PyModule>) -> PyResult<()> { m.add_function(wrap_pyfunction!(scheduler_error, m)?)?; m.add_function(wrap_pyfunction!(scheduler_output, m)?)?; m.add_function(wrap_pyfunction!(submit_urgent_issue, m)?)?; + m.add_function(wrap_pyfunction!(clear_urgent_issue_by_identity, m)?)?; m.add_function(wrap_pyfunction!(xdp_ip_mapping_capacity, m)?)?; m.add_function(wrap_pyfunction!(is_insight_enabled, m)?)?; m.add_function(wrap_pyfunction!(log_info, m)?)?; @@ -1379,6 +1381,13 @@ fn xdp_ip_mapping_capacity() -> PyResult { Ok(lqos_sys::ip_mapping_capacity()) } +/// Returns whether the pinned BPF maps required for XDP IP mapping updates are ready. +#[pyfunction] +fn xdp_ip_mapping_ready() -> PyResult { + lqos_sys::ip_mapping_subsystem_ready() + .map_err(|e| PyOSError::new_err(format!("Unable to inspect XDP IP mapping maps: {e}"))) +} + /// Requests Rust-side validation of `ShapedDevices.csv` #[pyfunction] fn validate_shaped_devices() -> PyResult { @@ -3865,6 +3874,52 @@ fn submit_urgent_issue( Ok(false) } +/// Clear urgent issues matching a code and dedupe key. +#[pyfunction] +fn clear_urgent_issue_by_identity(_py: Python, code: String, dedupe_key: String) -> PyResult { + if let Ok(reply) = run_query(vec![BusRequest::ClearUrgentIssueByIdentity { + code: code.clone(), + dedupe_key: dedupe_key.clone(), + }]) { + for resp in reply.iter() { + if let BusResponse::Ack = resp { + return Ok(true); + } + } + } + + let Ok(reply) = run_query(vec![BusRequest::GetUrgentIssues]) else { + return Ok(false); + }; + let mut ids_to_clear = Vec::new(); + for resp in reply.iter() { + if let BusResponse::UrgentIssues(issues) = resp { + ids_to_clear.extend( + issues + .iter() + .filter(|issue| { + issue.code == code + && issue.dedupe_key.as_deref().unwrap_or(&issue.code) == dedupe_key + }) + .map(|issue| issue.id), + ); + } + } + + if ids_to_clear.is_empty() { + return Ok(false); + } + + let requests = ids_to_clear + .into_iter() + .map(BusRequest::ClearUrgentIssue) + .collect::>(); + let Ok(reply) = run_query(requests) else { + return Ok(false); + }; + Ok(reply.iter().any(|resp| matches!(resp, BusResponse::Ack))) +} + /// Log an informational message via the lqosd bus (appears in lqosd logs). #[pyfunction] fn log_info(_py: Python, message: String) -> PyResult { diff --git a/src/rust/lqos_sys/src/lib.rs b/src/rust/lqos_sys/src/lib.rs index f1e10074..a284b0ce 100644 --- a/src/rust/lqos_sys/src/lib.rs +++ b/src/rust/lqos_sys/src/lib.rs @@ -34,6 +34,7 @@ pub use kernel_wrapper::LibreQoSKernels; pub use linux::num_possible_cpus; pub use lqos_kernel::interface_name_to_index; pub use lqos_kernel::ip_mapping_capacity; +pub use lqos_kernel::ip_mapping_subsystem_ready; pub use lqos_kernel::max_tracked_ips; pub use lqos_kernel::unload_xdp_from_interface; pub use tc_classify_control::{initialize_tc_classify_bypass, set_tc_classify_bypass}; diff --git a/src/rust/lqos_sys/src/lqos_kernel.rs b/src/rust/lqos_sys/src/lqos_kernel.rs index 809d05dc..c5ecfaf8 100644 --- a/src/rust/lqos_sys/src/lqos_kernel.rs +++ b/src/rust/lqos_sys/src/lqos_kernel.rs @@ -31,6 +31,13 @@ pub(crate) mod bpf { include!(concat!(env!("OUT_DIR"), "/bindings.rs")); } +#[derive(Clone, Copy)] +struct PinnedMapAbiSpec { + path: &'static str, + expected_key_size: u32, + expected_value_size: u32, +} + /// Returns the value set in the C XDP system's MAX_TRACKED_IPS /// constant. pub fn max_tracked_ips() -> usize { @@ -42,10 +49,50 @@ fn pinned_map_max_entries(path: &str) -> Result> { return Ok(None); } + Ok(pinned_map_info(path)?.map(|info| info.max_entries)) +} + +/// Returns the currently available IP-mapping capacity. +/// +/// If the live pinned map exists, this returns its `max_entries` value. +/// Otherwise, it falls back to the compiled `MAX_TRACKED_IPS` constant. +pub fn ip_mapping_capacity() -> usize { + match pinned_map_max_entries("/sys/fs/bpf/map_ip_to_cpu_and_tc") { + Ok(Some(entries)) => entries as usize, + Ok(None) => max_tracked_ips(), + Err(e) => { + warn!("Unable to determine live IP-mapping capacity: {e:?}"); + max_tracked_ips() + } + } +} + +fn ip_mapping_pinned_map_abi_specs() -> [PinnedMapAbiSpec; 3] { + let expected_key_size = std::mem::size_of::() as u32; + let expected_value_size = std::mem::size_of::() as u32; + [ + PinnedMapAbiSpec { + path: "/sys/fs/bpf/map_ip_to_cpu_and_tc", + expected_key_size, + expected_value_size, + }, + PinnedMapAbiSpec { + path: "/sys/fs/bpf/ip_to_cpu_and_tc_hotcache", + expected_key_size: std::mem::size_of::() as u32, + expected_value_size, + }, + PinnedMapAbiSpec { + path: "/sys/fs/bpf/ip_mapping_epoch", + expected_key_size: std::mem::size_of::() as u32, + expected_value_size: std::mem::size_of::() as u32, + }, + ] +} + +fn pinned_map_info(path: &str) -> Result> { let path_c = CString::new(path)?; let fd = unsafe { bpf_obj_get(path_c.as_ptr()) }; if fd < 0 { - warn!("Unable to open pinned BPF map '{path}' for capacity check (fd={fd})"); return Ok(None); } @@ -57,27 +104,116 @@ fn pinned_map_max_entries(path: &str) -> Result> { } if err != 0 { return Err(Error::msg(format!( - "Unable to query pinned BPF map '{path}' capacity (err={err})." + "Unable to query pinned BPF map '{path}' info (err={err})." ))); } - let info = unsafe { info.assume_init() }; - Ok(Some(info.max_entries)) + Ok(Some(info)) } -/// Returns the currently available IP-mapping capacity. -/// -/// If the live pinned map exists, this returns its `max_entries` value. -/// Otherwise, it falls back to the compiled `MAX_TRACKED_IPS` constant. -pub fn ip_mapping_capacity() -> usize { - match pinned_map_max_entries("/sys/fs/bpf/map_ip_to_cpu_and_tc") { - Ok(Some(entries)) => entries as usize, - Ok(None) => max_tracked_ips(), - Err(e) => { - warn!("Unable to determine live IP-mapping capacity: {e:?}"); - max_tracked_ips() +fn pinned_map_key_value_sizes(path: &str) -> Result> { + Ok(pinned_map_info(path)?.map(|info| (info.key_size, info.value_size))) +} + +fn ip_mapping_subsystem_ready_with(mut map_sizes: F) -> Result +where + F: FnMut(&str) -> Result>, +{ + for spec in ip_mapping_pinned_map_abi_specs() { + let Some((key_size, value_size)) = map_sizes(spec.path)? else { + return Ok(false); + }; + if key_size != spec.expected_key_size || value_size != spec.expected_value_size { + return Ok(false); } } + Ok(true) +} + +/// Returns whether the pinned maps required for XDP IP mapping updates are ready. +/// +/// This function has side effects: it opens the relevant pinned BPF maps and +/// queries their ABI metadata. It returns `Ok(false)` for maps that are not yet +/// pinned or have an incompatible ABI, and `Err` for unexpected inspection +/// failures. +pub fn ip_mapping_subsystem_ready() -> Result { + ip_mapping_subsystem_ready_with(pinned_map_key_value_sizes) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::collections::HashMap; + + #[test] + fn ip_mapping_ready_requires_all_expected_maps() { + let specs = ip_mapping_pinned_map_abi_specs(); + let sizes: HashMap<&str, (u32, u32)> = specs + .iter() + .map(|spec| { + ( + spec.path, + (spec.expected_key_size, spec.expected_value_size), + ) + }) + .collect(); + + let ready = ip_mapping_subsystem_ready_with(|path| Ok(sizes.get(path).copied())) + .expect("readiness check should succeed"); + + assert!(ready); + } + + #[test] + fn ip_mapping_ready_is_false_when_a_map_is_missing() { + let ready = ip_mapping_subsystem_ready_with(|path| { + if path == "/sys/fs/bpf/ip_mapping_epoch" { + Ok(None) + } else { + let spec = ip_mapping_pinned_map_abi_specs() + .into_iter() + .find(|spec| spec.path == path) + .expect("test path should be part of IP mapping ABI specs"); + Ok(Some((spec.expected_key_size, spec.expected_value_size))) + } + }) + .expect("missing map should not be an inspection error"); + + assert!(!ready); + } + + #[test] + fn ip_mapping_ready_is_false_when_a_map_abi_differs() { + let ready = ip_mapping_subsystem_ready_with(|path| { + let spec = ip_mapping_pinned_map_abi_specs() + .into_iter() + .find(|spec| spec.path == path) + .expect("test path should be part of IP mapping ABI specs"); + let value_size = if path == "/sys/fs/bpf/map_ip_to_cpu_and_tc" { + spec.expected_value_size + 1 + } else { + spec.expected_value_size + }; + Ok(Some((spec.expected_key_size, value_size))) + }) + .expect("ABI mismatch should not be an inspection error"); + + assert!(!ready); + } + + #[test] + fn ip_mapping_ready_returns_inspection_error() { + let err = ip_mapping_subsystem_ready_with(|path| { + if path == "/sys/fs/bpf/map_ip_to_cpu_and_tc" { + Err(Error::msg("map info failed")) + } else { + Ok(None) + } + }) + .expect_err("inspection errors should be returned to the caller"); + + assert!(err.to_string().contains("map info failed")); + } } pub fn check_root() -> Result<()> { @@ -99,25 +235,10 @@ fn remove_incompatible_pinned_map( return Ok(()); } - let path_c = CString::new(path)?; - let fd = unsafe { bpf_obj_get(path_c.as_ptr()) }; - if fd < 0 { - warn!("Unable to open pinned BPF map '{path}' for ABI check (fd={fd})"); + let Some(info) = pinned_map_info(path)? else { + warn!("Unable to open pinned BPF map '{path}' for ABI check"); return Ok(()); - } - - let mut info = MaybeUninit::::zeroed(); - let mut len: u32 = std::mem::size_of::() as u32; - let err = unsafe { bpf_obj_get_info_by_fd(fd, info.as_mut_ptr() as *mut c_void, &mut len) }; - unsafe { - close(fd); - } - if err != 0 { - return Err(Error::msg(format!( - "Unable to query pinned BPF map '{path}' info (err={err})." - ))); - } - let info = unsafe { info.assume_init() }; + }; if info.key_size != expected_key_size || info.value_size != expected_value_size { warn!( @@ -135,23 +256,13 @@ fn remove_incompatible_pinned_map( } fn ensure_ip_mapping_maps_abi() -> Result<()> { - let expected_key_size = std::mem::size_of::() as u32; - let expected_value_size = std::mem::size_of::() as u32; - remove_incompatible_pinned_map( - "/sys/fs/bpf/map_ip_to_cpu_and_tc", - expected_key_size, - expected_value_size, - )?; - remove_incompatible_pinned_map( - "/sys/fs/bpf/ip_to_cpu_and_tc_hotcache", - std::mem::size_of::() as u32, - expected_value_size, - )?; - remove_incompatible_pinned_map( - "/sys/fs/bpf/ip_mapping_epoch", - std::mem::size_of::() as u32, - std::mem::size_of::() as u32, - )?; + for spec in ip_mapping_pinned_map_abi_specs() { + remove_incompatible_pinned_map( + spec.path, + spec.expected_key_size, + spec.expected_value_size, + )?; + } remove_incompatible_pinned_map( "/sys/fs/bpf/tc_classify_control", std::mem::size_of::() as u32, diff --git a/src/rust/lqosd/src/main.rs b/src/rust/lqosd/src/main.rs index 6976a159..5e745fb2 100644 --- a/src/rust/lqosd/src/main.rs +++ b/src/rust/lqosd/src/main.rs @@ -1047,6 +1047,10 @@ fn handle_bus_requests(requests: &[BusRequest], responses: &mut Vec urgent::clear(*id); BusResponse::Ack } + BusRequest::ClearUrgentIssueByIdentity { code, dedupe_key } => { + urgent::clear_by_identity(code, dedupe_key); + BusResponse::Ack + } BusRequest::ClearAllUrgentIssues => { urgent::clear_all(); BusResponse::Ack @@ -1390,3 +1394,33 @@ fn search_result_to_bus(entry: node_manager::SearchResult) -> lqos_bus::SearchRe } } } + +#[cfg(test)] +mod tests { + use super::*; + use lqos_bus::{UrgentSeverity, UrgentSource}; + + #[test] + fn bus_clear_urgent_issue_by_identity_reaches_urgent_store() { + let code = "TEST_BUS_XDP_IP_MAPPING_APPLY_FAILED"; + urgent::clear_by_identity(code, code); + urgent::submit( + UrgentSource::LibreQoS, + UrgentSeverity::Error, + code.to_string(), + "mapping failed".to_string(), + None, + Some(code.to_string()), + ); + + let requests = [BusRequest::ClearUrgentIssueByIdentity { + code: code.to_string(), + dedupe_key: code.to_string(), + }]; + let mut responses = Vec::new(); + handle_bus_requests(&requests, &mut responses); + + assert!(matches!(responses.as_slice(), [BusResponse::Ack])); + assert!(!urgent::list().iter().any(|issue| issue.code == code)); + } +} diff --git a/src/rust/lqosd/src/shaped_devices_tracker/mod.rs b/src/rust/lqosd/src/shaped_devices_tracker/mod.rs index 20959e14..e1a64021 100644 --- a/src/rust/lqosd/src/shaped_devices_tracker/mod.rs +++ b/src/rust/lqosd/src/shaped_devices_tracker/mod.rs @@ -4,14 +4,13 @@ use anyhow::Result; use arc_swap::ArcSwap; use fxhash::{FxHashMap, FxHashSet}; use lqos_bus::{BusResponse, Circuit}; +#[cfg(test)] +use lqos_config::load_active_runtime_shaping_inputs; use lqos_config::{ NetworkJsonNode, NetworkJsonTransport, TopologyRuntimeShapingPayloadIdentity, TopologyRuntimeStatusFile, TopologyShapingInputsFile, - load_active_runtime_shaping_inputs_from_status, load_config, - topology_runtime_status_path, + load_active_runtime_shaping_inputs_from_status, load_config, topology_runtime_status_path, }; -#[cfg(test)] -use lqos_config::load_active_runtime_shaping_inputs; use lqos_queue_tracker::EFFECTIVE_NODE_RATES; use lqos_utils::file_watcher::FileWatcher; use lqos_utils::hash_to_i64; @@ -106,7 +105,9 @@ fn publish_shaping_inputs(shaping_inputs: TopologyShapingInputsFile) { invalidate_executive_cache_snapshot(); } -fn topology_status_identity(status: &TopologyRuntimeStatusFile) -> TopologyRuntimeShapingPayloadIdentity { +fn topology_status_identity( + status: &TopologyRuntimeStatusFile, +) -> TopologyRuntimeShapingPayloadIdentity { status.shaping_payload_identity() } @@ -286,7 +287,9 @@ fn load_topology_runtime_status_payload() { let status = match TopologyRuntimeStatusFile::load(config.as_ref()) { Ok(status) => status, Err(err) => { - warn!("Unable to load topology_runtime_status.json: {err}; keeping last-known-good effective parent cache"); + warn!( + "Unable to load topology_runtime_status.json: {err}; keeping last-known-good effective parent cache" + ); return; } }; diff --git a/src/rust/lqosd/src/urgent.rs b/src/rust/lqosd/src/urgent.rs index d8a76da0..f38b87c4 100644 --- a/src/rust/lqosd/src/urgent.rs +++ b/src/rust/lqosd/src/urgent.rs @@ -17,6 +17,10 @@ fn now_unix() -> u64 { unix_now().unwrap_or_default() } +fn urgent_identity_key(code: &str, dedupe_key: Option<&str>) -> String { + dedupe_key.unwrap_or(code).to_string() +} + fn prune_expired(q: &mut VecDeque) { let now = now_unix(); while let Some(front) = q.front() { @@ -44,8 +48,8 @@ pub fn submit( let mut guard = URGENT.lock(); prune_expired(&mut guard); - // Dedupe: same (code, dedupe_key) within window → update timestamp/message - let key = dedupe_key.clone().unwrap_or_else(|| code.clone()); + // Dedupe: same (code, dedupe_key) within window updates timestamp/message. + let key = urgent_identity_key(&code, dedupe_key.as_deref()); if let Some(existing) = guard.iter_mut().rev().find(|i| { (i.code == code) && (i.dedupe_key.as_deref().unwrap_or("") == key) @@ -90,7 +94,79 @@ pub fn clear(id: u64) -> bool { } } +/// Clears urgent issues matching the same code and dedupe key used for submission. +pub fn clear_by_identity(code: &str, dedupe_key: &str) -> usize { + let key = urgent_identity_key(code, Some(dedupe_key)); + let mut guard = URGENT.lock(); + let before = guard.len(); + guard.retain(|issue| { + issue.code != code || issue.dedupe_key.as_deref().unwrap_or("") != key.as_str() + }); + before.saturating_sub(guard.len()) +} + pub fn clear_all() { let mut guard = URGENT.lock(); guard.clear(); } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn clear_by_identity_removes_only_matching_issues() { + let code = "TEST_XDP_IP_MAPPING_APPLY_FAILED"; + let other_code = "TEST_OTHER"; + let other_dedupe = "TEST_XDP_IP_MAPPING_APPLY_FAILED_OTHER_DEDUPE"; + clear_by_identity(code, code); + clear_by_identity(code, other_dedupe); + clear_by_identity(other_code, code); + submit( + UrgentSource::LibreQoS, + UrgentSeverity::Error, + code.to_string(), + "mapping failed".to_string(), + None, + Some(code.to_string()), + ); + submit( + UrgentSource::LibreQoS, + UrgentSeverity::Error, + code.to_string(), + "same code different dedupe".to_string(), + None, + Some(other_dedupe.to_string()), + ); + submit( + UrgentSource::LibreQoS, + UrgentSeverity::Error, + other_code.to_string(), + "other failed".to_string(), + None, + Some(code.to_string()), + ); + + let cleared = clear_by_identity(code, code); + let matching_issue_survived = list() + .into_iter() + .any(|issue| issue.code == code && issue.dedupe_key.as_deref() == Some(other_dedupe)); + + assert_eq!(cleared, 1); + assert!(matching_issue_survived); + assert_eq!(clear_by_identity(code, other_dedupe), 1); + assert_eq!(clear_by_identity(other_code, code), 1); + } + + #[test] + fn urgent_identity_key_falls_back_to_code() { + assert_eq!( + urgent_identity_key("CODE_ONLY", None), + "CODE_ONLY".to_string() + ); + assert_eq!( + urgent_identity_key("CODE", Some("DEDUP")), + "DEDUP".to_string() + ); + } +} diff --git a/src/test_xdp_mapping_recovery.py b/src/test_xdp_mapping_recovery.py new file mode 100644 index 00000000..650f4bdd --- /dev/null +++ b/src/test_xdp_mapping_recovery.py @@ -0,0 +1,124 @@ +import unittest + +import LibreQoS + + +class FakeIpMapBatch: + def __init__(self, submit_error=None): + self.finished = False + self.submitted = False + self.submit_error = submit_error + + def finish_ip_mappings(self): + self.finished = True + + def submit(self): + self.submitted = True + if self.submit_error is not None: + raise self.submit_error + + +class XdpMappingRecoveryTests(unittest.TestCase): + def test_ready_on_first_check_does_not_sleep(self): + sleeps = [] + + LibreQoS.wait_for_xdp_ip_mapping_ready( + ready=lambda: True, + sleep=lambda seconds: sleeps.append(seconds), + now=lambda: 0.0, + ) + + self.assertEqual(sleeps, []) + + def test_readiness_after_one_false_check_sleeps_once(self): + checks = iter([False, True]) + sleeps = [] + times = iter([0.0, 0.0, 0.0]) + + LibreQoS.wait_for_xdp_ip_mapping_ready( + ready=lambda: next(checks), + sleep=lambda seconds: sleeps.append(seconds), + now=lambda: next(times), + timeout_seconds=5.0, + interval_seconds=0.1, + ) + + self.assertEqual(sleeps, [0.1]) + + def test_persistent_false_readiness_times_out(self): + times = iter([0.0, 0.0, 0.2]) + + with self.assertRaises(TimeoutError): + LibreQoS.wait_for_xdp_ip_mapping_ready( + ready=lambda: False, + sleep=lambda _seconds: None, + now=lambda: next(times), + timeout_seconds=0.1, + interval_seconds=0.1, + ) + + def test_readiness_os_error_reports_before_submit(self): + batch = FakeIpMapBatch() + reports = [] + + def raise_os_error(): + raise OSError("Unable to inspect XDP IP mapping maps") + + LibreQoS.apply_xdp_ip_mappings( + batch, + {"queued_requests": 1}, + ready=raise_os_error, + sleep=lambda _seconds: None, + report_failure=lambda *args: reports.append(args), + clear_recovered_issue=lambda *_args: True, + ) + + self.assertFalse(batch.finished) + self.assertFalse(batch.submitted) + self.assertEqual(reports[0][0], LibreQoS.XDP_IP_MAPPING_APPLY_FAILED) + + def test_submit_failure_reports_mapping_apply_failure(self): + batch = FakeIpMapBatch(submit_error=OSError("Unable to open BPF map")) + reports = [] + + LibreQoS.apply_xdp_ip_mappings( + batch, + {"queued_requests": 1}, + ready=lambda: True, + sleep=lambda _seconds: None, + report_failure=lambda *args: reports.append(args), + clear_recovered_issue=lambda *_args: True, + ) + + self.assertTrue(batch.finished) + self.assertTrue(batch.submitted) + self.assertEqual(reports[0][0], LibreQoS.XDP_IP_MAPPING_APPLY_FAILED) + + def test_success_clears_recovered_mapping_issue(self): + batch = FakeIpMapBatch() + cleared = [] + + LibreQoS.apply_xdp_ip_mappings( + batch, + {"queued_requests": 1}, + ready=lambda: True, + sleep=lambda _seconds: None, + report_failure=lambda *_args: self.fail("unexpected failure report"), + clear_recovered_issue=lambda code, dedupe_key: cleared.append((code, dedupe_key)) or True, + ) + + self.assertTrue(batch.finished) + self.assertTrue(batch.submitted) + self.assertEqual( + cleared, + [ + ( + LibreQoS.XDP_IP_MAPPING_APPLY_FAILED, + LibreQoS.XDP_IP_MAPPING_APPLY_FAILED, + ) + ], + ) + + +if __name__ == "__main__": + unittest.main() -- knotmirror 0.0.1 From 5cd7deb825f57d995e44402a10c128a62596fffb Mon Sep 17 00:00:00 2001 From: rchac Date: Wed, 6 May 2026 20:37:39 +0000 Subject: [PATCH 49/51] changes --- .../js_build/src/executive_utils.js | 16 +- .../js_build/src/pubsub/listeners.js | 23 ++ .../js_build/src/pubsub/ws.test.mjs | 103 +++++ .../src/node_manager/js_build/src/template.js | 382 ++++++++++++++---- .../js_build/test-node-manager.sh | 4 +- src/rust/lqosd/src/node_manager/ws.rs | 176 +++++++- .../lqosd/src/node_manager/ws/messages.rs | 21 +- 7 files changed, 634 insertions(+), 91 deletions(-) create mode 100644 src/rust/lqosd/src/node_manager/js_build/src/pubsub/listeners.js create mode 100644 src/rust/lqosd/src/node_manager/js_build/src/pubsub/ws.test.mjs diff --git a/src/rust/lqosd/src/node_manager/js_build/src/executive_utils.js b/src/rust/lqosd/src/node_manager/js_build/src/executive_utils.js index 287808de..41d8e66c 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/executive_utils.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/executive_utils.js @@ -1,17 +1,10 @@ +import {listenOnceMatchingWithTimeout} from "./pubsub/listeners"; import {get_ws_client, subscribeWS} from "./pubsub/ws"; const wsClient = get_ws_client(); const DEFAULT_EXECUTIVE_REFRESH_MS = 5000; let executiveRequestCounter = 0; -const listenOnce = (eventName, handler) => { - const wrapped = (msg) => { - wsClient.off(eventName, wrapped); - handler(msg); - }; - wsClient.on(eventName, wrapped); -}; - function normalizeEntityKinds(entityKinds) { return [...new Set((entityKinds || []).map((kind) => String(kind)))].sort(); } @@ -178,7 +171,7 @@ export function getNodeIdMap() { siteIdMap = map; resolve(map); }; - listenOnce("NetworkTreeLite", (msg) => { + listenOnceMatchingWithTimeout(wsClient, "NetworkTreeLite", 5000, () => true, (msg) => { const data = msg && msg.data ? msg.data : []; const map = new Map(); (data || []).forEach((entry) => { @@ -190,11 +183,10 @@ export function getNodeIdMap() { } }); resolveOnce(map); + }, () => { + resolveOnce(new Map()); }); wsClient.send({ NetworkTreeLite: {} }); - setTimeout(() => { - resolveOnce(new Map()); - }, 5000); }); return siteIdMapPromise; } diff --git a/src/rust/lqosd/src/node_manager/js_build/src/pubsub/listeners.js b/src/rust/lqosd/src/node_manager/js_build/src/pubsub/listeners.js new file mode 100644 index 00000000..cf0ccb8e --- /dev/null +++ b/src/rust/lqosd/src/node_manager/js_build/src/pubsub/listeners.js @@ -0,0 +1,23 @@ +export function listenOnceMatchingWithTimeout(wsClient, eventName, timeoutMs, matches, handler, onTimeout) { + let done = false; + const cleanup = wsClient.on(eventName, (msg) => { + if (done) return; + if (!matches(msg)) return; + done = true; + clearTimeout(timer); + cleanup(); + handler(msg); + }); + const timer = setTimeout(() => { + if (done) return; + done = true; + cleanup(); + onTimeout(); + }, timeoutMs); + return () => { + if (done) return; + done = true; + clearTimeout(timer); + cleanup(); + }; +} diff --git a/src/rust/lqosd/src/node_manager/js_build/src/pubsub/ws.test.mjs b/src/rust/lqosd/src/node_manager/js_build/src/pubsub/ws.test.mjs new file mode 100644 index 00000000..46622629 --- /dev/null +++ b/src/rust/lqosd/src/node_manager/js_build/src/pubsub/ws.test.mjs @@ -0,0 +1,103 @@ +import assert from "node:assert/strict"; +import test from "node:test"; + +globalThis.window = { + LQOS_UI_VERSION: "test", + location: { search: "", protocol: "http:", host: "localhost" }, + localStorage: { getItem: () => null }, + sessionStorage: { + getItem: () => null, + setItem: () => {}, + removeItem: () => {}, + }, +}; +globalThis.document = { cookie: "" }; + +const { listenOnceMatchingWithTimeout } = await import("./listeners.js"); + +function makeWsClient() { + const handlers = new Map(); + return { + on(eventName, handler) { + if (!handlers.has(eventName)) { + handlers.set(eventName, new Set()); + } + handlers.get(eventName).add(handler); + return () => this.off(eventName, handler); + }, + off(eventName, handler) { + handlers.get(eventName)?.delete(handler); + }, + emit(eventName, message) { + for (const handler of Array.from(handlers.get(eventName) || [])) { + handler(message); + } + }, + handlerCount(eventName) { + return handlers.get(eventName)?.size || 0; + }, + }; +} + +test("timeout listener ignores stale responses and resolves matching response", () => { + const wsClient = makeWsClient(); + const seen = []; + + listenOnceMatchingWithTimeout( + wsClient, + "UrgentClearResult", + 1000, + (message) => message.request_id === 2, + (message) => seen.push(message.ok), + () => seen.push("timeout"), + ); + + wsClient.emit("UrgentClearResult", { request_id: 1, ok: false }); + assert.deepEqual(seen, []); + assert.equal(wsClient.handlerCount("UrgentClearResult"), 1); + + wsClient.emit("UrgentClearResult", { request_id: 2, ok: true }); + assert.deepEqual(seen, [true]); + assert.equal(wsClient.handlerCount("UrgentClearResult"), 0); +}); + +test("timeout listener disposer removes pending handler", () => { + const wsClient = makeWsClient(); + const seen = []; + + const dispose = listenOnceMatchingWithTimeout( + wsClient, + "UrgentList", + 1000, + () => true, + () => seen.push("response"), + () => seen.push("timeout"), + ); + + assert.equal(wsClient.handlerCount("UrgentList"), 1); + dispose(); + wsClient.emit("UrgentList", { request_id: 1 }); + + assert.deepEqual(seen, []); + assert.equal(wsClient.handlerCount("UrgentList"), 0); +}); + +test("timeout listener fires timeout and removes pending handler", async () => { + const wsClient = makeWsClient(); + const seen = []; + + listenOnceMatchingWithTimeout( + wsClient, + "UrgentList", + 5, + () => false, + () => seen.push("response"), + () => seen.push("timeout"), + ); + + assert.equal(wsClient.handlerCount("UrgentList"), 1); + await new Promise((resolve) => setTimeout(resolve, 20)); + + assert.deepEqual(seen, ["timeout"]); + assert.equal(wsClient.handlerCount("UrgentList"), 0); +}); diff --git a/src/rust/lqosd/src/node_manager/js_build/src/template.js b/src/rust/lqosd/src/node_manager/js_build/src/template.js index 227ea555..cfed7976 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/template.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/template.js @@ -2,6 +2,7 @@ import {clearDiv} from "./helpers/builders"; import {initRedact} from "./helpers/redact"; import {initDayNightMode} from "./helpers/dark_mode"; import {initColorBlind} from "./helpers/colorblind"; +import {listenOnceMatchingWithTimeout as listenWsOnceMatchingWithTimeout} from "./pubsub/listeners"; import {get_ws_client} from "./pubsub/ws"; const wsClient = get_ws_client(); @@ -29,6 +30,7 @@ function escapeHtml(text) { const SCHEDULER_STATUS_POLL_MS = 2000; const SCHEDULER_STATUS_TIMEOUT_MS = 2500; +const URGENT_ISSUES_TIMEOUT_MS = 2500; const SCHEDULER_STATUS_STARTING_GRACE_MS = 30000; const SCHEDULER_MODAL_IDLE_POLL_MS = 3000; const SCHEDULER_MODAL_ACTIVE_POLL_MS = 1000; @@ -42,24 +44,6 @@ let schedulerModalInstance = null; let cachedSchedulerDetailsData = null; let cachedQueueModeConfig = null; -function listenOnceWithTimeout(eventName, timeoutMs, handler, onTimeout) { - let done = false; - const wrapped = (msg) => { - if (done) return; - done = true; - clearTimeout(timer); - wsClient.off(eventName, wrapped); - handler(msg); - }; - const timer = setTimeout(() => { - if (done) return; - done = true; - wsClient.off(eventName, wrapped); - onTimeout(); - }, timeoutMs); - wsClient.on(eventName, wrapped); -} - function clampSchedulerPercent(value) { const parsed = Number(value); if (!Number.isFinite(parsed)) return 0; @@ -526,7 +510,7 @@ function loadSchedulerStatus(force = false) { } schedulerStatusRequestInFlight = true; - listenOnceWithTimeout("SchedulerStatus", SCHEDULER_STATUS_TIMEOUT_MS, (msg) => { + listenWsOnceMatchingWithTimeout(wsClient, "SchedulerStatus", SCHEDULER_STATUS_TIMEOUT_MS, () => true, (msg) => { schedulerStatusRequestInFlight = false; if (!msg || !msg.data) { if (cachedSchedulerStatusData) { @@ -685,7 +669,7 @@ function refreshSchedulerModalDetails(showLoading = false) { renderSchedulerModalLoading(); } schedulerModalRequestInFlight = true; - listenOnceWithTimeout("SchedulerDetails", SCHEDULER_STATUS_TIMEOUT_MS, (msg) => { + listenWsOnceMatchingWithTimeout(wsClient, "SchedulerDetails", SCHEDULER_STATUS_TIMEOUT_MS, () => true, (msg) => { schedulerModalRequestInFlight = false; if (!isSchedulerModalOpen()) { stopSchedulerModalPolling(); @@ -1108,6 +1092,15 @@ function initUrgentIssues() { const containerId = 'urgentStatus'; const linkId = 'urgentStatusLink'; const badgeId = 'urgentBadge'; + let urgentClearState = null; + let urgentStatusPending = false; + let urgentStatusRefreshQueued = false; + let urgentListPending = false; + let urgentListActiveRequestId = null; + let urgentListCancel = null; + let urgentRequestId = 0; + let pendingUrgentActionError = null; + let pendingUrgentRetryMessage = null; function ensurePlaceholder() { return document.getElementById(containerId) !== null; @@ -1131,38 +1124,251 @@ function initUrgentIssues() { function poll() { if (!ensurePlaceholder()) return; - listenOnce("UrgentStatus", (msg) => { - const count = msg && msg.data ? msg.data.count : 0; - renderStatus(count || 0); + if (urgentStatusPending) { + urgentStatusRefreshQueued = true; + return; + } + urgentStatusPending = true; + const requestId = ++urgentRequestId; + listenWsOnceMatchingWithTimeout( + wsClient, + "UrgentStatus", + URGENT_ISSUES_TIMEOUT_MS, + (msg) => msg.request_id === requestId, + (msg) => { + urgentStatusPending = false; + const count = msg && msg.data ? msg.data.count : 0; + renderStatus(count || 0); + runQueuedUrgentStatusRefresh(); + }, + () => { + urgentStatusPending = false; + runQueuedUrgentStatusRefresh(); + } + ); + wsClient.send({ UrgentStatus: { request_id: requestId } }); + } + + function runQueuedUrgentStatusRefresh() { + if (!urgentStatusRefreshQueued) return false; + urgentStatusRefreshQueued = false; + poll(); + return true; + } + + function clearActionInFlight() { + return urgentClearState !== null; + } + + function clearActionBlocked() { + return clearActionInFlight() || urgentListPending; + } + + function setClearControlsDisabled(disabled) { + document.querySelectorAll('.urgent-clear').forEach((button) => { + button.disabled = disabled; }); - wsClient.send({ UrgentStatus: {} }); + const clearAllButton = document.getElementById('urgentClearAll'); + if (clearAllButton) { + clearAllButton.disabled = disabled; + } } - function showModal() { - const modalEl = document.getElementById('urgentModal'); - if (!modalEl) return; - new bootstrap.Modal(modalEl, { focus: true }).show(); + function showUrgentBusyState(message) { const holder = document.getElementById('urgentListContainer'); + if (!holder || !urgentModalIsOpen()) return; + holder.setAttribute('aria-busy', 'true'); + holder.querySelector('.urgent-busy-status')?.remove(); + holder.insertAdjacentHTML('afterbegin', ` +
+ + ${escapeHtml(message)} +
`); + holder.querySelector('.urgent-busy-status')?.focus(); + } + + function clearUrgentBusyState(holder) { + const target = holder || document.getElementById('urgentListContainer'); + if (!target) return; + target.removeAttribute('aria-busy'); + target.querySelector('.urgent-busy-status')?.remove(); + } + + function renderUrgentWarning(holder, message, { focus = false, retry = false } = {}) { if (!holder) return; - holder.innerHTML = `
Loading...
`; - listenOnce("UrgentList", (msg) => { - const items = msg && msg.data ? msg.data.items || [] : []; - if (items.length === 0) { - holder.innerHTML = '
No urgent issues.
'; - return; + holder.querySelector('.urgent-action-error')?.remove(); + const retryButton = retry + ? '' + : ''; + holder.insertAdjacentHTML('afterbegin', ` + `); + if (focus) { + holder.querySelector(retry ? '.urgent-refresh' : '.urgent-action-error')?.focus(); + } + } + + function showUrgentActionError(message) { + pendingUrgentActionError = message; + if (!urgentModalIsOpen()) return; + const holder = document.getElementById('urgentListContainer'); + if (!holder) return; + clearUrgentBusyState(holder); + renderUrgentWarning(holder, message, { focus: true }); + pendingUrgentActionError = null; + } + + function attachPendingUrgentActionError(holder) { + if (!pendingUrgentActionError || !urgentModalIsOpen() || !holder) return; + renderUrgentWarning(holder, pendingUrgentActionError); + pendingUrgentActionError = null; + } + + function showUrgentRetryState(message) { + pendingUrgentRetryMessage = message; + const holder = document.getElementById('urgentListContainer'); + if (!holder || !urgentModalIsOpen()) return; + pendingUrgentRetryMessage = null; + setClearControlsDisabled(true); + clearUrgentBusyState(holder); + holder.innerHTML = ''; + renderUrgentWarning(holder, message, { focus: true, retry: true }); + $(holder).off('click').on('click', '.urgent-refresh', function (e) { + e.preventDefault(); + showModal(); + }); + } + + function showPendingUrgentRetryState() { + if (!pendingUrgentRetryMessage || !urgentModalIsOpen()) return false; + showUrgentRetryState(pendingUrgentRetryMessage); + return true; + } + + function urgentModalIsOpen() { + return document.getElementById('urgentModal')?.classList.contains('show') === true; + } + + function focusUrgentModalFallback() { + const modalEl = document.getElementById('urgentModal'); + if (!modalEl || !urgentModalIsOpen()) return; + modalEl + .querySelector('.urgent-clear:not(:disabled), #urgentClearAll:not(:disabled), .btn-close:not(:disabled), [data-bs-dismiss="modal"]:not(:disabled)') + ?.focus(); + } + + function refreshUrgentIssues() { + showModal(); + poll(); + } + + function completeClearAction() { + urgentClearState = null; + setClearControlsDisabled(clearActionInFlight()); + refreshUrgentIssues(); + } + + function startUrgentClear({ + responseEvent, + requestPayload, + busyMessage, + failureMessage, + timeoutMessage, + }) { + if (clearActionBlocked()) { + return; + } + const requestId = ++urgentRequestId; + setClearControlsDisabled(true); + showUrgentBusyState(busyMessage); + urgentClearState = { + busyMessage, + cancel: null, + }; + urgentClearState.cancel = listenWsOnceMatchingWithTimeout( + wsClient, + responseEvent, + URGENT_ISSUES_TIMEOUT_MS, + (msg) => msg.request_id === requestId, + (msg) => { + urgentClearState = null; + if (msg && msg.ok === false) { + setClearControlsDisabled(false); + showUrgentActionError(failureMessage); + return; + } + completeClearAction(); + }, + () => { + urgentClearState = null; + setClearControlsDisabled(false); + showUrgentActionError(timeoutMessage); } - const table = document.createElement('table'); - table.className = 'lqos-table lqos-table-compact mb-0'; - const tbody = document.createElement('tbody'); - items.forEach((it) => { - const tr = document.createElement('tr'); - const td = document.createElement('td'); - const when = new Date(it.ts * 1000).toLocaleString(); - const sev = it.severity === 'Error' ? 'danger' : 'warning'; - const clearControl = it.clearable === false - ? 'Active' - : ``; - td.innerHTML = ` + ); + wsClient.send(requestPayload(requestId)); + } + + function showModal() { + const modalEl = document.getElementById('urgentModal'); + if (!modalEl) { + return; + } + bootstrap.Modal.getOrCreateInstance(modalEl, { focus: true }).show(); + const holder = document.getElementById('urgentListContainer'); + if (!holder) { + return; + } + if (showPendingUrgentRetryState()) { + return; + } + if (clearActionInFlight()) { + setClearControlsDisabled(true); + showUrgentBusyState(urgentClearState.busyMessage); + return; + } + if (urgentListPending) { + setClearControlsDisabled(true); + return; + } + urgentListPending = true; + const requestId = ++urgentRequestId; + urgentListActiveRequestId = requestId; + setClearControlsDisabled(true); + clearUrgentBusyState(holder); + holder.innerHTML = `
Loading...
`; + holder.querySelector('.urgent-loading')?.focus(); + urgentListCancel = listenWsOnceMatchingWithTimeout( + wsClient, + "UrgentList", + URGENT_ISSUES_TIMEOUT_MS, + (msg) => msg.request_id === requestId && urgentListActiveRequestId === requestId, + (msg) => { + urgentListPending = false; + urgentListActiveRequestId = null; + urgentListCancel = null; + const items = msg && msg.data ? msg.data.items || [] : []; + clearUrgentBusyState(holder); + if (items.length === 0) { + holder.innerHTML = '
No urgent issues.
'; + attachPendingUrgentActionError(holder); + setClearControlsDisabled(true); + holder.querySelector('[role="status"]')?.focus(); + return; + } + const table = document.createElement('table'); + table.className = 'lqos-table lqos-table-compact mb-0'; + const tbody = document.createElement('tbody'); + items.forEach((it) => { + const tr = document.createElement('tr'); + const td = document.createElement('td'); + const when = new Date(it.ts * 1000).toLocaleString(); + const sev = it.severity === 'Error' ? 'danger' : 'warning'; + const clearControl = it.clearable === false + ? 'Active' + : ``; + td.innerHTML = `
${it.severity} ${it.code} @@ -1173,26 +1379,44 @@ function initUrgentIssues() {
${it.message}
${it.context ? `
${it.context}
` : ''} `; - tr.appendChild(td); - tbody.appendChild(tr); - }); - table.appendChild(tbody); - holder.innerHTML = ''; - const tableWrap = document.createElement('div'); - tableWrap.className = 'table-responsive lqos-table-wrap'; - tableWrap.appendChild(table); - holder.appendChild(tableWrap); - $(holder).off('click').on('click', '.urgent-clear', function (e) { - e.preventDefault(); - const id = $(this).data('id'); - listenOnce("UrgentClearResult", () => { - showModal(); - poll(); + tr.appendChild(td); + tbody.appendChild(tr); }); - wsClient.send({ UrgentClear: { id } }); - }); - }); - wsClient.send({ UrgentList: {} }); + table.appendChild(tbody); + holder.innerHTML = ''; + const tableWrap = document.createElement('div'); + tableWrap.className = 'table-responsive lqos-table-wrap'; + tableWrap.appendChild(table); + holder.appendChild(tableWrap); + attachPendingUrgentActionError(holder); + $(holder).off('click').on('click', '.urgent-clear', function (e) { + e.preventDefault(); + const id = $(this).data('id'); + startUrgentClear({ + responseEvent: 'UrgentClearResult', + requestPayload: (requestId) => ({ UrgentClear: { id, request_id: requestId } }), + busyMessage: 'Acknowledging urgent issue...', + failureMessage: 'Unable to acknowledge urgent issue.', + timeoutMessage: 'Timed out while acknowledging urgent issue.', + }); + }); + setClearControlsDisabled(clearActionInFlight()); + focusUrgentModalFallback(); + }, + () => { + if (urgentListActiveRequestId !== requestId) return; + urgentListPending = false; + urgentListActiveRequestId = null; + urgentListCancel = null; + if (!urgentModalIsOpen()) { + setClearControlsDisabled(clearActionInFlight()); + return; + } + showUrgentRetryState('Unable to refresh urgent issues.'); + setClearControlsDisabled(true); + } + ); + wsClient.send({ UrgentList: { request_id: requestId } }); } if (!document.getElementById(containerId)) { @@ -1206,11 +1430,31 @@ function initUrgentIssues() { } $(document).off('click', '#urgentClearAll').on('click', '#urgentClearAll', () => { - listenOnce("UrgentClearAllResult", () => { - showModal(); - poll(); + startUrgentClear({ + responseEvent: 'UrgentClearAllResult', + requestPayload: (requestId) => ({ UrgentClearAll: { request_id: requestId } }), + busyMessage: 'Acknowledging urgent issues...', + failureMessage: 'Unable to acknowledge urgent issues.', + timeoutMessage: 'Timed out while acknowledging urgent issues.', }); - wsClient.send({ UrgentClearAll: {} }); + }); + + $(document).off('hidden.bs.modal', '#urgentModal').on('hidden.bs.modal', '#urgentModal', () => { + pendingUrgentRetryMessage = null; + if (urgentClearState?.cancel) { + urgentClearState.cancel(); + urgentClearState = null; + } + if (urgentListPending) { + if (urgentListCancel) { + urgentListCancel(); + urgentListCancel = null; + } + urgentListPending = false; + urgentListActiveRequestId = null; + } + clearUrgentBusyState(); + setClearControlsDisabled(clearActionInFlight()); }); poll(); diff --git a/src/rust/lqosd/src/node_manager/js_build/test-node-manager.sh b/src/rust/lqosd/src/node_manager/js_build/test-node-manager.sh index 5d093180..20456c61 100755 --- a/src/rust/lqosd/src/node_manager/js_build/test-node-manager.sh +++ b/src/rust/lqosd/src/node_manager/js_build/test-node-manager.sh @@ -9,7 +9,9 @@ if ! command -v node >/dev/null 2>&1; then fi echo "[test-node-manager] Running frontend contract tests..." -node --test "${SCRIPT_DIR}/src/config/shaped_device_wire.test.mjs" +node --test \ + "${SCRIPT_DIR}/src/config/shaped_device_wire.test.mjs" \ + "${SCRIPT_DIR}/src/pubsub/ws.test.mjs" echo "[test-node-manager] Building bundles..." "${SCRIPT_DIR}/esbuild.sh" diff --git a/src/rust/lqosd/src/node_manager/ws.rs b/src/rust/lqosd/src/node_manager/ws.rs index 6b5bb6eb..02766378 100644 --- a/src/rust/lqosd/src/node_manager/ws.rs +++ b/src/rust/lqosd/src/node_manager/ws.rs @@ -676,32 +676,37 @@ async fn receive_channel_message( return true; } } - WsRequest::UrgentStatus => { + WsRequest::UrgentStatus { request_id } => { let response = WsResponse::UrgentStatus { data: urgent::urgent_status_data(), + request_id, }; if send_ws_response(&tx, response).await { return true; } } - WsRequest::UrgentList => { + WsRequest::UrgentList { request_id } => { let response = WsResponse::UrgentList { data: urgent::urgent_list_data(), + request_id, }; if send_ws_response(&tx, response).await { return true; } } - WsRequest::UrgentClear { id } => { + WsRequest::UrgentClear { id, request_id } => { let ok = urgent::urgent_clear_id(id); - let response = WsResponse::UrgentClearResult { ok }; + let response = WsResponse::UrgentClearResult { ok, request_id }; if send_ws_response(&tx, response).await { return true; } } - WsRequest::UrgentClearAll => { + WsRequest::UrgentClearAll { request_id } => { urgent::urgent_clear_all_data(); - let response = WsResponse::UrgentClearAllResult { ok: true }; + let response = WsResponse::UrgentClearAllResult { + ok: true, + request_id, + }; if send_ws_response(&tx, response).await { return true; } @@ -2502,7 +2507,9 @@ fn payload_hint(payload: &[u8]) -> &'static str { #[cfg(test)] mod tests { use super::decode_ws_request; + use crate::node_manager::local_api::urgent::{UrgentList, UrgentStatus}; use crate::node_manager::ws::messages::WsRequest; + use crate::node_manager::ws::messages::{WsResponse, encode_ws_message}; use serde_cbor::Value as CborValue; use std::collections::BTreeMap; @@ -2567,6 +2574,163 @@ mod tests { .expect("valid update payload") } + fn encode_response_value(response: &WsResponse) -> CborValue { + let payload = encode_ws_message(response).expect("response should encode"); + serde_cbor::from_slice(payload.as_ref()).expect("response should decode as CBOR value") + } + + fn response_request_id(response: &WsResponse, event_name: &str) -> Option { + let CborValue::Map(entries) = encode_response_value(response) else { + panic!("response should encode as a CBOR map"); + }; + let event_key = text("event"); + let request_id_key = text("request_id"); + assert_eq!(entries.get(&event_key), Some(&text(event_name))); + match entries.get(&request_id_key) { + Some(CborValue::Integer(value)) => { + Some(u64::try_from(*value).expect("request_id is u64")) + } + Some(other) => panic!("unexpected request_id value: {other:?}"), + None => None, + } + } + + fn response_has_request_id(response: &WsResponse) -> bool { + let CborValue::Map(entries) = encode_response_value(response) else { + panic!("response should encode as a CBOR map"); + }; + entries.contains_key(&text("request_id")) + } + + #[test] + fn decodes_urgent_status_with_request_id() { + let payload = serde_cbor::to_vec(&map(vec![( + "UrgentStatus", + map(vec![("request_id", integer(42))]), + )])) + .expect("valid urgent status payload"); + + let request = decode_ws_request(&payload).expect("urgent status request should decode"); + match request { + WsRequest::UrgentStatus { request_id } => assert_eq!(request_id, Some(42)), + other => panic!("unexpected request: {other:?}"), + } + } + + #[test] + fn decodes_urgent_list_without_request_id() { + let payload = serde_cbor::to_vec(&map(vec![("UrgentList", map(vec![]))])) + .expect("valid urgent list payload"); + + let request = decode_ws_request(&payload).expect("urgent list request should decode"); + match request { + WsRequest::UrgentList { request_id } => assert_eq!(request_id, None), + other => panic!("unexpected request: {other:?}"), + } + } + + #[test] + fn decodes_urgent_clear_with_request_id() { + let payload = serde_cbor::to_vec(&map(vec![( + "UrgentClear", + map(vec![("id", integer(7)), ("request_id", integer(42))]), + )])) + .expect("valid urgent clear payload"); + + let request = decode_ws_request(&payload).expect("urgent clear request should decode"); + match request { + WsRequest::UrgentClear { id, request_id } => { + assert_eq!(id, 7); + assert_eq!(request_id, Some(42)); + } + other => panic!("unexpected request: {other:?}"), + } + } + + #[test] + fn decodes_urgent_clear_all_without_request_id() { + let payload = serde_cbor::to_vec(&map(vec![("UrgentClearAll", map(vec![]))])) + .expect("valid urgent clear all payload"); + + let request = decode_ws_request(&payload).expect("urgent clear all request should decode"); + match request { + WsRequest::UrgentClearAll { request_id } => assert_eq!(request_id, None), + other => panic!("unexpected request: {other:?}"), + } + } + + #[test] + fn urgent_responses_echo_request_id() { + assert_eq!( + response_request_id( + &WsResponse::UrgentStatus { + data: UrgentStatus { + has_urgent: true, + count: 1, + }, + request_id: Some(42), + }, + "UrgentStatus", + ), + Some(42), + ); + assert_eq!( + response_request_id( + &WsResponse::UrgentList { + data: UrgentList { items: Vec::new() }, + request_id: Some(43), + }, + "UrgentList", + ), + Some(43), + ); + assert_eq!( + response_request_id( + &WsResponse::UrgentClearResult { + ok: true, + request_id: Some(44), + }, + "UrgentClearResult", + ), + Some(44), + ); + assert_eq!( + response_request_id( + &WsResponse::UrgentClearAllResult { + ok: true, + request_id: Some(45), + }, + "UrgentClearAllResult", + ), + Some(45), + ); + } + + #[test] + fn urgent_responses_omit_missing_request_id() { + assert!(!response_has_request_id(&WsResponse::UrgentStatus { + data: UrgentStatus { + has_urgent: false, + count: 0, + }, + request_id: None, + })); + assert!(!response_has_request_id(&WsResponse::UrgentList { + data: UrgentList { items: Vec::new() }, + request_id: None, + })); + assert!(!response_has_request_id(&WsResponse::UrgentClearResult { + ok: true, + request_id: None, + })); + assert!(!response_has_request_id( + &WsResponse::UrgentClearAllResult { + ok: true, + request_id: None, + } + )); + } + #[test] fn decodes_create_shaped_device_with_browser_style_ipv4_bytes() { let payload = create_shaped_device_payload(device_value( diff --git a/src/rust/lqosd/src/node_manager/ws/messages.rs b/src/rust/lqosd/src/node_manager/ws/messages.rs index 37c41c7a..4a851965 100644 --- a/src/rust/lqosd/src/node_manager/ws/messages.rs +++ b/src/rust/lqosd/src/node_manager/ws/messages.rs @@ -324,12 +324,19 @@ pub enum WsRequest { ProtocolFlowTimeline { protocol: String, }, - UrgentStatus, - UrgentList, + UrgentStatus { + request_id: Option, + }, + UrgentList { + request_id: Option, + }, UrgentClear { id: u64, + request_id: Option, + }, + UrgentClearAll { + request_id: Option, }, - UrgentClearAll, UnknownIps, UnknownIpsClear, UnknownIpsCsv, @@ -626,15 +633,23 @@ pub enum WsResponse { }, UrgentStatus { data: UrgentStatus, + #[serde(skip_serializing_if = "Option::is_none")] + request_id: Option, }, UrgentList { data: UrgentList, + #[serde(skip_serializing_if = "Option::is_none")] + request_id: Option, }, UrgentClearResult { ok: bool, + #[serde(skip_serializing_if = "Option::is_none")] + request_id: Option, }, UrgentClearAllResult { ok: bool, + #[serde(skip_serializing_if = "Option::is_none")] + request_id: Option, }, UnknownIps { data: Vec, -- knotmirror 0.0.1 From 42175b269a9703084d3f173abf7e55b22328b8c6 Mon Sep 17 00:00:00 2001 From: rchac Date: Wed, 6 May 2026 21:26:24 +0000 Subject: [PATCH 50/51] changes --- docs-es/v2.0/TechnicalDocs/troubleshooting.md | 17 ++++------------- docs-es/v2.0/troubleshooting-es.md | 18 +++--------------- docs/v2.0/troubleshooting.md | 17 +++-------------- src/bin/lqos_scheduler.service.example | 2 ++ 4 files changed, 12 insertions(+), 42 deletions(-) diff --git a/docs-es/v2.0/TechnicalDocs/troubleshooting.md b/docs-es/v2.0/TechnicalDocs/troubleshooting.md index e91e2600..2f03daf7 100644 --- a/docs-es/v2.0/TechnicalDocs/troubleshooting.md +++ b/docs-es/v2.0/TechnicalDocs/troubleshooting.md @@ -67,21 +67,12 @@ sudo dpkg --configure -a sudo systemctl restart lqosd lqos_scheduler ``` -Git-based installs should use `./build_rust.sh` after pulling updates. It rebuilds the virtual environment before refreshing service files or restarting services. If systemd reports `status=203/EXEC`, rebuild the virtual environment with the command above and restart `lqos_scheduler`. +Git-based installs should use `./build_rust.sh` after pulling updates. It rebuilds the virtual environment before refreshing service files or restarting services. If systemd reports `status=203/EXEC` on `/opt/libreqos/venv/bin/python`, or a failed scheduler pre-start check, rebuild the virtual environment with the command above and restart `lqos_scheduler`. + +Older installs that predate the virtual environment may show `ModuleNotFoundError` and suggest system `pip` commands. Do not repair current installs with system `pip` or `--break-system-packages`; those packages are not used by the venv-backed scheduler service. Upgrade to a package that creates `/opt/libreqos/venv`, then use the repair command above. -### Python ModuleNotFoundError in older Ubuntu 24.04 installs -``` -pip uninstall binpacking --break-system-packages --yes -sudo pip uninstall binpacking --break-system-packages --yes -sudo pip install binpacking --break-system-packages -pip uninstall apscheduler --break-system-packages --yes -sudo pip uninstall apscheduler --break-system-packages --yes -sudo pip install apscheduler --break-system-packages -pip uninstall deepdiff --break-system-packages --yes -sudo pip uninstall deepdiff --break-system-packages --yes -sudo pip install deepdiff --break-system-packages -``` ### All customer IPs are listed under Unknown IPs, rather than Shaped Devices in GUI + ``` cd /opt/libreqos/src sudo systemctl stop lqos_scheduler diff --git a/docs-es/v2.0/troubleshooting-es.md b/docs-es/v2.0/troubleshooting-es.md index f95ea6a0..e0d60b2b 100644 --- a/docs-es/v2.0/troubleshooting-es.md +++ b/docs-es/v2.0/troubleshooting-es.md @@ -120,7 +120,9 @@ sudo dpkg --configure -a sudo systemctl restart lqosd lqos_scheduler ``` -Las instalaciones basadas en git deben usar `./build_rust.sh` después de actualizar. Ese script reconstruye el entorno virtual antes de actualizar los archivos de servicio o reiniciar servicios. Si systemd informa `status=203/EXEC`, reconstruya el entorno virtual con el comando anterior y reinicie `lqos_scheduler`. +Las instalaciones basadas en git deben usar `./build_rust.sh` después de actualizar. Ese script reconstruye el entorno virtual antes de actualizar los archivos de servicio o reiniciar servicios. Si systemd informa `status=203/EXEC` en `/opt/libreqos/venv/bin/python`, o una falla en la comprobación previa del scheduler, reconstruya el entorno virtual con el comando anterior y reinicie `lqos_scheduler`. + +Las instalaciones antiguas anteriores al entorno virtual pueden mostrar `ModuleNotFoundError` y recomendar comandos de `pip` del sistema. No repare instalaciones actuales con `pip` del sistema ni con `--break-system-packages`; esos paquetes no los usa el servicio `lqos_scheduler` respaldado por el entorno virtual. Actualice a un paquete que cree `/opt/libreqos/venv` y use el comando de reparación anterior. Si el scheduler falla inmediatamente después de un reinicio con un mensaje como `Socket (typically /run/lqos/bus) not found`, eso indica que `lqosd` todavía no había terminado de enlazar el bus local. Los builds actuales esperan brevemente la disponibilidad del bus al arrancar el scheduler en lugar de abortar de inmediato, por lo que ya no deberían aparecer panics repetidos de arranque tras un reinicio. @@ -175,20 +177,6 @@ Si `journalctl -u lqosd` muestra advertencias repetidas como `BeginIngest queue Suele indicar que no se pudo agregar correctamente qdisc MQ en la NIC (colas RX/TX insuficientes). Verifique [NICs recomendadas](requirements-es.md). -### Python ModuleNotFoundError en Ubuntu 24.04 - -```bash -pip uninstall binpacking --break-system-packages --yes -sudo pip uninstall binpacking --break-system-packages --yes -sudo pip install binpacking --break-system-packages -pip uninstall apscheduler --break-system-packages --yes -sudo pip uninstall apscheduler --break-system-packages --yes -sudo pip install apscheduler --break-system-packages -pip uninstall deepdiff --break-system-packages --yes -sudo pip uninstall deepdiff --break-system-packages --yes -sudo pip install deepdiff --break-system-packages -``` - ### Todas las IPs de clientes aparecen como Unknown IPs ```bash diff --git a/docs/v2.0/troubleshooting.md b/docs/v2.0/troubleshooting.md index fb5c21b7..2f641545 100644 --- a/docs/v2.0/troubleshooting.md +++ b/docs/v2.0/troubleshooting.md @@ -234,7 +234,7 @@ sudo dpkg --configure -a sudo systemctl restart lqosd lqos_scheduler ``` -Git-based installs should use `./build_rust.sh` after pulling updates. It rebuilds the virtual environment before refreshing service files or restarting services. If systemd reports `status=203/EXEC`, rebuild the virtual environment with the command above and restart `lqos_scheduler`. +Git-based installs should use `./build_rust.sh` after pulling updates. It rebuilds the virtual environment before refreshing service files or restarting services. If systemd reports `status=203/EXEC` on `/opt/libreqos/venv/bin/python`, or a failed scheduler pre-start check, rebuild the virtual environment with the command above and restart `lqos_scheduler`. For manual shaping tests, use the same interpreter as the service: @@ -244,21 +244,10 @@ sudo /opt/libreqos/venv/bin/python /opt/libreqos/src/LibreQoS.py sudo systemctl start lqos_scheduler ``` -Older installs that predate the virtual environment may show `ModuleNotFoundError` and suggest system `pip` commands. Upgrade to a package that creates `/opt/libreqos/venv`, then use the repair command above. +Older installs that predate the virtual environment may show `ModuleNotFoundError` and suggest system `pip` commands. Do not repair current installs with system `pip` or `--break-system-packages`; those packages are not used by the venv-backed scheduler service. Upgrade to a package that creates `/opt/libreqos/venv`, then use the repair command above. -### Python ModuleNotFoundError in older Ubuntu 24.04 installs -``` -pip uninstall binpacking --break-system-packages --yes -sudo pip uninstall binpacking --break-system-packages --yes -sudo pip install binpacking --break-system-packages -pip uninstall apscheduler --break-system-packages --yes -sudo pip uninstall apscheduler --break-system-packages --yes -sudo pip install apscheduler --break-system-packages -pip uninstall deepdiff --break-system-packages --yes -sudo pip uninstall deepdiff --break-system-packages --yes -sudo pip install deepdiff --break-system-packages -``` ### All customer IPs are listed under Unknown IPs, rather than Shaped Devices in GUI + ``` cd /opt/libreqos/src sudo systemctl stop lqos_scheduler diff --git a/src/bin/lqos_scheduler.service.example b/src/bin/lqos_scheduler.service.example index 78a42d74..9162c57c 100644 --- a/src/bin/lqos_scheduler.service.example +++ b/src/bin/lqos_scheduler.service.example @@ -5,6 +5,8 @@ Requires=lqosd.service [Service] WorkingDirectory=/opt/libreqos/src +ExecStartPre=/bin/test -x /opt/libreqos/venv/bin/python +ExecStartPre=/opt/libreqos/venv/bin/python -c "import apscheduler, chardet, deepdiff, psutil, requests" ExecStart=/opt/libreqos/venv/bin/python /opt/libreqos/src/scheduler.py Restart=always -- knotmirror 0.0.1 From 6eac4c10d4bbcdaa3f69ce2f713f0fc208c5b286 Mon Sep 17 00:00:00 2001 From: rchac Date: Wed, 6 May 2026 22:12:01 +0000 Subject: [PATCH 51/51] changes --- src/lqos.example | 2 + src/rust/lqos_bakery/src/lib.rs | 2 + src/rust/lqos_config/src/etc/migration.rs | 2 + src/rust/lqos_config/src/etc/v15/bridge.rs | 10 ++ src/rust/lqos_config/src/etc/v15/example.toml | 2 + .../lqos_config/src/etc/v15/top_config.rs | 101 ++++++++++++ src/rust/lqos_netplan_helper/src/inspect.rs | 142 ++++++++++++++-- .../lqos_netplan_helper/src/transaction.rs | 67 ++++++-- src/rust/lqos_setup/src/setup_actions.rs | 39 ++++- .../src/config/config_interface_mtu.test.mjs | 46 ++++++ .../js_build/src/config/network_mode_mtu.mjs | 29 ++++ .../js_build/src/config_interface.js | 126 +++++++++++++- .../js_build/test-node-manager.sh | 1 + .../node_manager/local_api/network_mode.rs | 156 +++++++++++++++--- .../static2/config_interface.html | 22 ++- 15 files changed, 697 insertions(+), 50 deletions(-) create mode 100644 src/rust/lqosd/src/node_manager/js_build/src/config/config_interface_mtu.test.mjs create mode 100644 src/rust/lqosd/src/node_manager/js_build/src/config/network_mode_mtu.mjs diff --git a/src/lqos.example b/src/lqos.example index 547e0ddb..c3f67847 100644 --- a/src/lqos.example +++ b/src/lqos.example @@ -25,12 +25,14 @@ disable_offload = [ "gso", "tso", "lro", "sg", "gro" ] use_xdp_bridge = false to_internet = "eth0" to_network = "eth1" +# mtu = 1500 # OR: #[single_interface] #interface = "eth0" #internet_vlan = 2 #network_vlan = 3 +# mtu = 1500 [queues] # Global default SQM is a single token list applied to both directions. diff --git a/src/rust/lqos_bakery/src/lib.rs b/src/rust/lqos_bakery/src/lib.rs index 7d4c34f1..624251b3 100644 --- a/src/rust/lqos_bakery/src/lib.rs +++ b/src/rust/lqos_bakery/src/lib.rs @@ -11294,6 +11294,7 @@ mod tests { use_xdp_bridge: false, to_internet: "lo".to_string(), to_network: "lo".to_string(), + mtu: None, }), ..lqos_config::Config::default() }; @@ -13142,6 +13143,7 @@ mod tests { use_xdp_bridge: false, to_internet: "__bakery-missing-wan__".to_string(), to_network: "__bakery-missing-lan__".to_string(), + mtu: None, }), ..Config::default() }; diff --git a/src/rust/lqos_config/src/etc/migration.rs b/src/rust/lqos_config/src/etc/migration.rs index 9686a1ef..1a6eec6a 100644 --- a/src/rust/lqos_config/src/etc/migration.rs +++ b/src/rust/lqos_config/src/etc/migration.rs @@ -182,6 +182,7 @@ fn migrate_bridge( interface: python_config.interface_a.clone(), internet_vlan: python_config.stick_vlan_a as u32, network_vlan: python_config.stick_vlan_b as u32, + mtu: None, }); } else { new_config.single_interface = None; @@ -193,6 +194,7 @@ fn migrate_bridge( .use_xdp_bridge, to_internet: python_config.interface_b.clone(), to_network: python_config.interface_a.clone(), + mtu: None, }); } Ok(()) diff --git a/src/rust/lqos_config/src/etc/v15/bridge.rs b/src/rust/lqos_config/src/etc/v15/bridge.rs index 2bec3419..aebffa91 100644 --- a/src/rust/lqos_config/src/etc/v15/bridge.rs +++ b/src/rust/lqos_config/src/etc/v15/bridge.rs @@ -16,6 +16,10 @@ pub struct BridgeConfig { /// The name of the second interface, facing the LAN pub to_network: String, + + /// Optional MTU for LibreQoS-managed Linux bridge interfaces. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub mtu: Option, } impl Default for BridgeConfig { @@ -24,6 +28,7 @@ impl Default for BridgeConfig { use_xdp_bridge: true, to_internet: "eth0".to_string(), to_network: "eth1".to_string(), + mtu: None, } } } @@ -39,6 +44,10 @@ pub struct SingleInterfaceConfig { /// The VLAN ID facing the LAN pub network_vlan: u32, + + /// Optional MTU for the LibreQoS-managed trunk interface. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub mtu: Option, } impl Default for SingleInterfaceConfig { @@ -47,6 +56,7 @@ impl Default for SingleInterfaceConfig { interface: "eth0".to_string(), internet_vlan: 2, network_vlan: 3, + mtu: None, } } } diff --git a/src/rust/lqos_config/src/etc/v15/example.toml b/src/rust/lqos_config/src/etc/v15/example.toml index 730f272d..37955997 100644 --- a/src/rust/lqos_config/src/etc/v15/example.toml +++ b/src/rust/lqos_config/src/etc/v15/example.toml @@ -26,12 +26,14 @@ disable_offload = [ "gso", "tso", "lro", "sg", "gro" ] use_xdp_bridge = true to_internet = "eth0" to_network = "eth1" +# mtu = 1500 # OR: #[single_interface] #interface = "eth0" #internet_vlan = 2 #network_vlan = 3 +# mtu = 1500 [queues] default_sqm = "cake diffserv4" 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 3d942b45..856f1075 100644 --- a/src/rust/lqos_config/src/etc/v15/top_config.rs +++ b/src/rust/lqos_config/src/etc/v15/top_config.rs @@ -15,6 +15,9 @@ fn default_true() -> bool { true } +const MIN_INTERFACE_MTU: u32 = 576; +const MAX_INTERFACE_MTU: u32 = 9216; + fn default_rtt_green_ms() -> u32 { 0 } @@ -27,6 +30,17 @@ fn default_rtt_red_ms() -> u32 { 200 } +fn validate_interface_mtu(field_name: &str, mtu: Option) -> Result<(), String> { + if let Some(mtu) = mtu + && !(MIN_INTERFACE_MTU..=MAX_INTERFACE_MTU).contains(&mtu) + { + return Err(format!( + "{field_name} must be between {MIN_INTERFACE_MTU} and {MAX_INTERFACE_MTU}" + )); + } + Ok(()) +} + /// RTT color scale thresholds (milliseconds) used by the web UI. /// /// These represent the color "anchor points" for RTT: @@ -225,6 +239,12 @@ impl Config { .to_string(), ); } + if let Some(bridge) = &self.bridge { + validate_interface_mtu("bridge.mtu", bridge.mtu)?; + } + if let Some(single_interface) = &self.single_interface { + validate_interface_mtu("single_interface.mtu", single_interface.mtu)?; + } if self.version.trim() != "1.5" { return Err(format!( "Configuration file is at version [{}], but this version of lqos only supports version 1.5.0", @@ -569,6 +589,7 @@ impl Config { #[cfg(test)] mod test { + use super::super::bridge::{BridgeConfig, SingleInterfaceConfig}; use super::{Config, RttThresholds}; fn remove_sections(raw: &str, sections: &[&str]) -> String { @@ -772,6 +793,86 @@ mod test { assert!(cfg.validate().is_err()); } + #[test] + fn bridge_mtu_defaults_to_none_when_omitted() { + let config = + Config::load_from_string(include_str!("example.toml")).expect("example should load"); + assert_eq!(config.bridge.as_ref().and_then(|bridge| bridge.mtu), None); + } + + #[test] + fn interface_mtu_values_deserialize() { + let bridge_raw = include_str!("example.toml") + .replace("to_network = \"eth1\"", "to_network = \"eth1\"\nmtu = 9000"); + let bridge_config = Config::load_from_string(&bridge_raw).expect("bridge MTU should load"); + assert_eq!( + bridge_config.bridge.as_ref().and_then(|bridge| bridge.mtu), + Some(9000) + ); + + let single_raw = remove_sections(include_str!("example.toml"), &["bridge"]) + + r#" +[single_interface] +interface = "eth0" +internet_vlan = 2 +network_vlan = 3 +mtu = 1500 +"#; + let single_config = + Config::load_from_string(&single_raw).expect("single-interface MTU should load"); + assert_eq!( + single_config + .single_interface + .as_ref() + .and_then(|single| single.mtu), + Some(1500) + ); + } + + #[test] + fn interface_mtu_validation_rejects_out_of_range_values() { + let mut bridge_config = Config { + bridge: Some(BridgeConfig { + mtu: Some(575), + ..BridgeConfig::default() + }), + ..Config::default() + }; + let bridge_error = bridge_config + .validate() + .expect_err("bridge.mtu below range should fail"); + assert!(bridge_error.contains("bridge.mtu")); + + bridge_config.bridge.as_mut().expect("bridge").mtu = Some(9217); + let bridge_error = bridge_config + .validate() + .expect_err("bridge.mtu above range should fail"); + assert!(bridge_error.contains("bridge.mtu")); + + let mut single_config = Config { + bridge: None, + single_interface: Some(SingleInterfaceConfig { + mtu: Some(575), + ..SingleInterfaceConfig::default() + }), + ..Config::default() + }; + let single_error = single_config + .validate() + .expect_err("single_interface.mtu below range should fail"); + assert!(single_error.contains("single_interface.mtu")); + + single_config + .single_interface + .as_mut() + .expect("single interface") + .mtu = Some(9217); + let single_error = single_config + .validate() + .expect_err("single_interface.mtu above range should fail"); + assert!(single_error.contains("single_interface.mtu")); + } + #[test] fn treeguard_defaults_match_default_on_rollout() { let cfg = Config::default(); diff --git a/src/rust/lqos_netplan_helper/src/inspect.rs b/src/rust/lqos_netplan_helper/src/inspect.rs index fb012324..098ef02f 100644 --- a/src/rust/lqos_netplan_helper/src/inspect.rs +++ b/src/rust/lqos_netplan_helper/src/inspect.rs @@ -68,6 +68,7 @@ enum RequestedMode { LinuxBridge { to_internet: String, to_network: String, + mtu: Option, }, XdpBridge { to_internet: String, @@ -75,6 +76,7 @@ enum RequestedMode { }, SingleInterface { interface: String, + mtu: Option, }, Unknown, } @@ -307,11 +309,13 @@ fn requested_mode(config: &Config) -> RequestedMode { RequestedMode::LinuxBridge { to_internet: bridge.to_internet.trim().to_string(), to_network: bridge.to_network.trim().to_string(), + mtu: bridge.mtu, } } } else if let Some(single) = &config.single_interface { RequestedMode::SingleInterface { interface: single.interface.trim().to_string(), + mtu: single.mtu, } } else { RequestedMode::Unknown @@ -332,6 +336,7 @@ fn selected_interfaces(mode: &RequestedMode) -> Vec { RequestedMode::LinuxBridge { to_internet, to_network, + .. } | RequestedMode::XdpBridge { to_internet, @@ -340,7 +345,7 @@ fn selected_interfaces(mode: &RequestedMode) -> Vec { .into_iter() .filter(|iface| !iface.is_empty()) .collect(), - RequestedMode::SingleInterface { interface } => { + RequestedMode::SingleInterface { interface, .. } => { if interface.is_empty() { Vec::new() } else { @@ -351,21 +356,38 @@ fn selected_interfaces(mode: &RequestedMode) -> Vec { } } +fn mtu_yaml_line(mtu: Option, indent: &str) -> String { + mtu.map(|value| format!("{indent}mtu: {value}\n")) + .unwrap_or_default() +} + +fn managed_linux_bridge_yaml(to_internet: &str, to_network: &str, mtu: Option) -> String { + let ethernet_mtu = mtu_yaml_line(mtu, " "); + let bridge_mtu = mtu_yaml_line(mtu, " "); + format!( + "network:\n version: 2\n ethernets:\n {to_internet}:\n dhcp4: false\n dhcp6: false\n{ethernet_mtu} {to_network}:\n dhcp4: false\n dhcp6: false\n{ethernet_mtu} bridges:\n br0:\n{bridge_mtu} interfaces:\n - {to_internet}\n - {to_network}\n" + ) +} + +fn managed_single_interface_yaml(interface: &str, mtu: Option) -> String { + let mtu_line = mtu_yaml_line(mtu, " "); + format!( + "network:\n version: 2\n ethernets:\n {interface}:\n dhcp4: false\n dhcp6: false\n{mtu_line}" + ) +} + fn managed_preview_yaml(mode: &RequestedMode) -> (Option, Option) { match mode { RequestedMode::LinuxBridge { to_internet, to_network, + mtu, } if !to_internet.is_empty() && !to_network.is_empty() => ( - Some(format!( - "network:\n version: 2\n ethernets:\n {to_internet}:\n dhcp4: false\n dhcp6: false\n {to_network}:\n dhcp4: false\n dhcp6: false\n bridges:\n br0:\n interfaces:\n - {to_internet}\n - {to_network}\n" - )), + Some(managed_linux_bridge_yaml(to_internet, to_network, *mtu)), None, ), - RequestedMode::SingleInterface { interface } if !interface.is_empty() => ( - Some(format!( - "network:\n version: 2\n ethernets:\n {interface}:\n dhcp4: false\n dhcp6: false\n" - )), + RequestedMode::SingleInterface { interface, mtu } if !interface.is_empty() => ( + Some(managed_single_interface_yaml(interface, *mtu)), None, ), RequestedMode::XdpBridge { .. } => ( @@ -598,6 +620,7 @@ pub(crate) fn adoption_rewrite_for_path(path: &Path, config: &Config) -> Result< RequestedMode::LinuxBridge { to_internet, to_network, + .. } => { let mut removed_bridge = false; doc.network.ethernets.remove(&to_internet); @@ -618,7 +641,7 @@ pub(crate) fn adoption_rewrite_for_path(path: &Path, config: &Config) -> Result< )); } } - RequestedMode::SingleInterface { interface } => { + RequestedMode::SingleInterface { interface, .. } => { if doc.network.ethernets.remove(&interface).is_none() { return Err(format!( "Unable to find interface {interface} in {} for adoption.", @@ -658,6 +681,7 @@ fn assess_file(path: &Path, doc: &NetplanDocument, mode: &RequestedMode) -> File RequestedMode::LinuxBridge { to_internet, to_network, + .. } => { for iface in [to_internet, to_network] { if let Some(cfg) = doc.network.ethernets.get(iface) { @@ -724,7 +748,7 @@ fn assess_file(path: &Path, doc: &NetplanDocument, mode: &RequestedMode) -> File } } } - RequestedMode::SingleInterface { interface } => { + RequestedMode::SingleInterface { interface, .. } => { if let Some(cfg) = doc.network.ethernets.get(interface) { relevant.insert(interface.clone()); if cfg.dhcp_disabled() && !cfg.has_l3_config() { @@ -1113,6 +1137,7 @@ mod tests { use_xdp_bridge: false, to_internet: "ens19".to_string(), to_network: "ens20".to_string(), + mtu: None, }), single_interface: None, ..lqos_config::Config::default() @@ -1126,6 +1151,7 @@ mod tests { interface: "ens19".to_string(), internet_vlan: 2, network_vlan: 3, + mtu: None, }), ..lqos_config::Config::default() } @@ -1144,6 +1170,102 @@ mod tests { BTreeMap::from([("ens19".to_string(), true), ("ens20".to_string(), true)]) } + #[test] + fn managed_linux_bridge_preview_includes_mtu_on_members_and_bridge() { + let mut config = linux_bridge_config(); + config.bridge.as_mut().expect("bridge").mtu = Some(9000); + let root = test_env("bridge-mtu-preview"); + + let inspection = inspect_network_mode_with_paths( + &config, + &root.join("netplan"), + &root.join("pending"), + &BTreeSet::from(["ens19".to_string(), "ens20".to_string()]), + &queue_caps(), + ); + let preview = inspection + .managed_preview_yaml + .expect("managed preview should exist"); + + assert_eq!( + preview, + "network:\n version: 2\n ethernets:\n ens19:\n dhcp4: false\n dhcp6: false\n mtu: 9000\n ens20:\n dhcp4: false\n dhcp6: false\n mtu: 9000\n bridges:\n br0:\n mtu: 9000\n interfaces:\n - ens19\n - ens20\n" + ); + let _ = std::fs::remove_dir_all(root); + } + + #[test] + fn managed_single_interface_preview_includes_mtu_on_trunk() { + let mut config = single_interface_config(); + config + .single_interface + .as_mut() + .expect("single interface") + .mtu = Some(1500); + + let root = test_env("single-mtu-preview"); + let inspection = inspect_network_mode_with_paths( + &config, + &root.join("netplan"), + &root.join("pending"), + &BTreeSet::from(["ens19".to_string()]), + &BTreeMap::from([("ens19".to_string(), true)]), + ); + let preview = inspection + .managed_preview_yaml + .expect("managed preview should exist"); + + assert_eq!( + preview, + "network:\n version: 2\n ethernets:\n ens19:\n dhcp4: false\n dhcp6: false\n mtu: 1500\n" + ); + let _ = std::fs::remove_dir_all(root); + } + + #[test] + fn managed_previews_omit_mtu_when_unset() { + let root = test_env("unset-mtu-preview"); + let inspection = inspect_network_mode_with_paths( + &linux_bridge_config(), + &root.join("netplan"), + &root.join("pending"), + &BTreeSet::from(["ens19".to_string(), "ens20".to_string()]), + &queue_caps(), + ); + let preview = inspection + .managed_preview_yaml + .expect("managed preview should exist"); + + assert!(!preview.contains("mtu:")); + let _ = std::fs::remove_dir_all(root); + } + + #[test] + fn xdp_bridge_mode_keeps_managed_preview_disabled() { + let mut config = linux_bridge_config(); + let bridge = config.bridge.as_mut().expect("bridge"); + bridge.use_xdp_bridge = true; + bridge.mtu = Some(9000); + + let root = test_env("xdp-mtu-preview"); + let inspection = inspect_network_mode_with_paths( + &config, + &root.join("netplan"), + &root.join("pending"), + &BTreeSet::from(["ens19".to_string(), "ens20".to_string()]), + &queue_caps(), + ); + + assert!(inspection.managed_preview_yaml.is_none()); + assert!( + inspection + .preview_note + .as_deref() + .is_some_and(|note| note.contains("manual workflow")) + ); + let _ = std::fs::remove_dir_all(root); + } + #[test] fn detects_external_compatible_linux_bridge() { let root = test_env("external-compatible"); diff --git a/src/rust/lqos_netplan_helper/src/transaction.rs b/src/rust/lqos_netplan_helper/src/transaction.rs index 0d4b3b2a..a785e6d9 100644 --- a/src/rust/lqos_netplan_helper/src/transaction.rs +++ b/src/rust/lqos_netplan_helper/src/transaction.rs @@ -170,7 +170,7 @@ fn system_interfaces() -> BTreeSet { default_net::get_interfaces() .into_iter() .map(|iface| iface.name) - .collect() + .collect::>() } fn supports_multi_queue(interface: &str) -> bool { @@ -195,7 +195,14 @@ fn supports_multi_queue(interface: &str) -> bool { /// Inspect the requested network mode using the helper's configured paths. pub fn inspect_with_paths(paths: &HelperPaths, config: &Config) -> NetworkModeInspection { - let system_ifaces = system_interfaces(); + inspect_with_paths_and_interfaces(paths, config, system_interfaces()) +} + +fn inspect_with_paths_and_interfaces( + paths: &HelperPaths, + config: &Config, + system_ifaces: BTreeSet, +) -> NetworkModeInspection { let queue_caps = system_ifaces .iter() .map(|iface| (iface.clone(), supports_multi_queue(iface))) @@ -750,6 +757,15 @@ pub fn apply_transaction( paths: &HelperPaths, pending_children: &mut PendingChildren, request: ApplyRequest, +) -> Result { + apply_transaction_with_interfaces(paths, pending_children, request, system_interfaces()) +} + +fn apply_transaction_with_interfaces( + paths: &HelperPaths, + pending_children: &mut PendingChildren, + request: ApplyRequest, + system_ifaces: BTreeSet, ) -> Result { normalize_pending_children(paths, pending_children)?; if !list_pending_records(paths)?.is_empty() { @@ -761,7 +777,7 @@ pub fn apply_transaction( } else { Config::default() }; - let inspection = inspect_with_paths(paths, &request.config); + let inspection = inspect_with_paths_and_interfaces(paths, &request.config, system_ifaces); validate_apply_request(&request, &inspection, &previous_config)?; let preview_yaml = inspection.managed_preview_yaml.as_ref().ok_or_else(|| { @@ -1013,7 +1029,7 @@ esac .find(|iface| iface.as_str() != "lo") .cloned() .or_else(|| interfaces.iter().next().cloned()) - .expect("test host should expose at least one interface"); + .unwrap_or_else(|| "ens19".to_string()); let secondary = interfaces .iter() .find(|iface| iface.as_str() != primary && iface.as_str() != "lo") @@ -1024,10 +1040,19 @@ esac .find(|iface| iface.as_str() != primary) .cloned() }) - .expect("test host should expose a second distinct interface"); + .unwrap_or_else(|| "ens20".to_string()); (primary, secondary) } + fn test_system_interfaces() -> BTreeSet { + let interfaces = system_interfaces(); + if interfaces.is_empty() { + BTreeSet::from(["ens19".to_string(), "ens20".to_string()]) + } else { + interfaces + } + } + fn linux_bridge_config() -> Config { let (to_internet, to_network) = test_interfaces(); Config { @@ -1035,6 +1060,7 @@ esac use_xdp_bridge: false, to_internet, to_network, + mtu: None, }), single_interface: None, ..Config::default() @@ -1058,7 +1084,13 @@ esac confirm_dangerous_changes: true, }; - let apply = apply_transaction(&paths, &mut pending, request).expect("apply should succeed"); + let apply = apply_transaction_with_interfaces( + &paths, + &mut pending, + request, + test_system_interfaces(), + ) + .expect("apply should succeed"); assert!(apply.ok); assert!(apply.operation.is_some()); @@ -1082,7 +1114,13 @@ esac mode: ApplyMode::Apply, confirm_dangerous_changes: true, }; - let apply = apply_transaction(&paths, &mut pending, request).expect("second apply"); + let apply = apply_transaction_with_interfaces( + &paths, + &mut pending, + request, + test_system_interfaces(), + ) + .expect("second apply"); let operation_id = apply .operation .as_ref() @@ -1112,10 +1150,11 @@ esac interface: test_interfaces().0, internet_vlan: 2, network_vlan: 3, + mtu: None, }); next.bridge = None; - let apply = apply_transaction( + let apply = apply_transaction_with_interfaces( &paths, &mut pending, ApplyRequest { @@ -1125,6 +1164,7 @@ esac mode: ApplyMode::Apply, confirm_dangerous_changes: true, }, + test_system_interfaces(), ) .expect("apply should succeed"); let backup_id = apply @@ -1147,6 +1187,7 @@ esac interface: test_interfaces().1, internet_vlan: 10, network_vlan: 11, + mtu: None, }), bridge: None, ..Config::default() @@ -1181,7 +1222,7 @@ esac let existing = linux_bridge_config(); write_config(&paths.config_path, &existing); - let apply = apply_transaction( + let apply = apply_transaction_with_interfaces( &paths, &mut pending, ApplyRequest { @@ -1191,6 +1232,7 @@ esac mode: ApplyMode::Apply, confirm_dangerous_changes: true, }, + test_system_interfaces(), ) .expect("apply should succeed"); let operation_id = apply @@ -1228,10 +1270,11 @@ esac interface: test_interfaces().0, internet_vlan: 2, network_vlan: 3, + mtu: None, }); next.bridge = None; - let apply = apply_transaction( + let apply = apply_transaction_with_interfaces( &paths, &mut pending, ApplyRequest { @@ -1241,6 +1284,7 @@ esac mode: ApplyMode::Apply, confirm_dangerous_changes: true, }, + test_system_interfaces(), ) .expect("apply should succeed"); let operation_id = apply @@ -1295,7 +1339,7 @@ esac let existing = linux_bridge_config(); write_config(&paths.config_path, &existing); - let err = apply_transaction( + let err = apply_transaction_with_interfaces( &paths, &mut pending, ApplyRequest { @@ -1305,6 +1349,7 @@ esac mode: ApplyMode::Apply, confirm_dangerous_changes: true, }, + test_system_interfaces(), ) .expect_err("apply should fail"); diff --git a/src/rust/lqos_setup/src/setup_actions.rs b/src/rust/lqos_setup/src/setup_actions.rs index b27c659a..2c4a398f 100644 --- a/src/rust/lqos_setup/src/setup_actions.rs +++ b/src/rust/lqos_setup/src/setup_actions.rs @@ -42,6 +42,11 @@ pub(crate) enum CommitOutcome { pub(crate) fn build_candidate_config(existing: Option) -> lqos_config::Config { let mut config = existing.unwrap_or_default(); + let existing_bridge_mtu = config.bridge.as_ref().and_then(|bridge| bridge.mtu); + let existing_single_interface_mtu = config + .single_interface + .as_ref() + .and_then(|single| single.mtu); let new_config = CURRENT_CONFIG.lock(); config.node_name = new_config.node_name.clone(); config.queues.downlink_bandwidth_mbps = new_config.mbps_to_internet; @@ -55,6 +60,7 @@ pub(crate) fn build_candidate_config(existing: Option) -> l use_xdp_bridge: false, to_internet: new_config.to_internet.clone(), to_network: new_config.to_network.clone(), + mtu: existing_bridge_mtu, }); } BridgeMode::XDP => { @@ -63,6 +69,7 @@ pub(crate) fn build_candidate_config(existing: Option) -> l use_xdp_bridge: true, to_internet: new_config.to_internet.clone(), to_network: new_config.to_network.clone(), + mtu: existing_bridge_mtu, }); } BridgeMode::Single => { @@ -70,6 +77,7 @@ pub(crate) fn build_candidate_config(existing: Option) -> l interface: new_config.to_internet.clone(), internet_vlan: new_config.internet_vlan, network_vlan: new_config.network_vlan, + mtu: existing_single_interface_mtu, }); config.bridge = None; } @@ -245,7 +253,8 @@ fn load_existing_or_default(event_log: &mut Vec) -> Result { + assert.deepEqual(parseOptionalMtu(""), { ok: true, value: null, error: "" }); + assert.deepEqual(parseOptionalMtu(" "), { ok: true, value: null, error: "" }); + assert.deepEqual(parseOptionalMtu("1500"), { ok: true, value: 1500, error: "" }); + assert.deepEqual(parseOptionalMtu("9000"), { ok: true, value: 9000, error: "" }); +}); + +test("rejects invalid MTU values", () => { + assert.equal(parseOptionalMtu("abc").ok, false); + assert.equal(parseOptionalMtu("1500.5").ok, false); + assert.equal(parseOptionalMtu("575").ok, false); + assert.equal(parseOptionalMtu("9217").ok, false); +}); + +test("returns normalized candidate values", () => { + assert.equal(parseOptionalMtu("9000").value, 9000); + assert.equal(parseOptionalMtu("").value, null); +}); + +test("hydrates pre-MTU drafts from live config", () => { + const liveConfig = { + bridge: { mtu: 9000 }, + single_interface: { mtu: 1500 }, + }; + + assert.equal(hydrateDraftMtu({ bridge: { to_internet: "eth0" } }, liveConfig).bridge.mtu, 9000); + assert.equal( + hydrateDraftMtu({ single_interface: { interface: "eth0" } }, liveConfig).single_interface.mtu, + 1500 + ); +}); + +test("keeps explicit draft MTU values", () => { + const liveConfig = { + bridge: { mtu: 9000 }, + single_interface: { mtu: 1500 }, + }; + + assert.equal(hydrateDraftMtu({ bridge: { mtu: null } }, liveConfig).bridge.mtu, null); + assert.equal(hydrateDraftMtu({ single_interface: { mtu: 1400 } }, liveConfig).single_interface.mtu, 1400); +}); diff --git a/src/rust/lqosd/src/node_manager/js_build/src/config/network_mode_mtu.mjs b/src/rust/lqosd/src/node_manager/js_build/src/config/network_mode_mtu.mjs new file mode 100644 index 00000000..193d3a5a --- /dev/null +++ b/src/rust/lqosd/src/node_manager/js_build/src/config/network_mode_mtu.mjs @@ -0,0 +1,29 @@ +export const MTU_MIN = 576; +export const MTU_MAX = 9216; + +export function parseOptionalMtu(rawValue) { + const trimmed = String(rawValue ?? "").trim(); + if (!trimmed) { + return { ok: true, value: null, error: "" }; + } + if (!/^\d+$/.test(trimmed)) { + return { ok: false, value: null, error: `MTU must be a whole number from ${MTU_MIN} through ${MTU_MAX}.` }; + } + const value = Number.parseInt(trimmed, 10); + if (value < MTU_MIN || value > MTU_MAX) { + return { ok: false, value: null, error: `MTU must be from ${MTU_MIN} through ${MTU_MAX}.` }; + } + return { ok: true, value, error: "" }; +} + +export function hydrateDraftMtu(draft, liveConfig) { + if (!draft) return null; + const hydrated = JSON.parse(JSON.stringify(draft)); + if (hydrated.bridge && hydrated.bridge.mtu === undefined) { + hydrated.bridge.mtu = liveConfig?.bridge?.mtu ?? null; + } + if (hydrated.single_interface && hydrated.single_interface.mtu === undefined) { + hydrated.single_interface.mtu = liveConfig?.single_interface?.mtu ?? null; + } + return hydrated; +} diff --git a/src/rust/lqosd/src/node_manager/js_build/src/config_interface.js b/src/rust/lqosd/src/node_manager/js_build/src/config_interface.js index 9ac5c2b7..696b1d3e 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/config_interface.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/config_interface.js @@ -1,9 +1,14 @@ import {loadConfig, renderConfigMenu} from "./config/config_helper"; +import {hydrateDraftMtu, MTU_MAX, MTU_MIN, parseOptionalMtu} from "./config/network_mode_mtu.mjs"; const DRAFT_KEY = "lqos-network-mode-draft"; const PENDING_OPERATION_KEY = "lqos-network-mode-pending"; const NETPLAN_TRY_TIMEOUT_MS = 30_000; const RECONNECT_POLL_INTERVAL_MS = 2_000; +const BRIDGE_MTU_HELP = "Applies to the bridge members and br0."; +const SINGLE_INTERFACE_MTU_HELP = "Applies to the trunk interface."; +const MTU_LOCKED_HELP = "MTU cannot be changed while a network-mode operation is pending."; +const XDP_MTU_HELP = "XDP mode keeps this value for later, but LibreQoS will not apply it."; let currentHelperStatus = null; let currentInspection = null; let currentPendingOperation = null; @@ -71,7 +76,94 @@ function postJson(url, body) { }); } +function setMtuFieldError(inputId, errorId, message) { + const input = document.getElementById(inputId); + const error = document.getElementById(errorId); + if (!input || !error) return; + input.setAttribute("aria-invalid", "true"); + input.classList.add("is-invalid"); + error.textContent = message; +} + +function clearMtuFieldError(inputId, errorId) { + const input = document.getElementById(inputId); + const error = document.getElementById(errorId); + if (!input || !error) return; + input.removeAttribute("aria-invalid"); + input.classList.remove("is-invalid"); + error.textContent = ""; +} + +function clearMtuErrors() { + clearMtuFieldError("bridgeMtu", "bridgeMtuError"); + clearMtuFieldError("singleInterfaceMtu", "singleInterfaceMtuError"); +} + +function applyMtuBounds() { + ["bridgeMtu", "singleInterfaceMtu"].forEach((id) => { + const input = document.getElementById(id); + if (!input) return; + input.min = String(MTU_MIN); + input.max = String(MTU_MAX); + }); +} + +function validateMtuField(inputId, errorId, parser) { + const input = document.getElementById(inputId); + if (!input) return true; + const parsed = parser(input.value); + if (parsed.ok) { + clearMtuFieldError(inputId, errorId); + return true; + } + setMtuFieldError(inputId, errorId, parsed.error); + input.focus(); + return false; +} + +function currentBridgeMtuValue() { + const parsed = parseOptionalMtu(document.getElementById("bridgeMtu").value); + if (parsed.ok) return parsed.value; + return window.config?.bridge?.mtu ?? null; +} + +function updateBridgeMtuState() { + const useXdpBridge = document.getElementById("useXdpBridge")?.checked ?? false; + const bridgeMtu = document.getElementById("bridgeMtu"); + const bridgeMtuHelp = document.getElementById("bridgeMtuHelp"); + if (!bridgeMtu || !bridgeMtuHelp) return; + const editingLocked = Boolean(currentInspection?.editing_locked); + bridgeMtu.disabled = useXdpBridge || editingLocked; + if (editingLocked) { + bridgeMtuHelp.textContent = MTU_LOCKED_HELP; + return; + } + if (useXdpBridge) { + clearMtuFieldError("bridgeMtu", "bridgeMtuError"); + bridgeMtuHelp.textContent = XDP_MTU_HELP; + } else { + bridgeMtuHelp.textContent = BRIDGE_MTU_HELP; + } +} + +function updateSingleInterfaceMtuState() { + const singleInterfaceMtu = document.getElementById("singleInterfaceMtu"); + const singleInterfaceMtuHelp = document.getElementById("singleInterfaceMtuHelp"); + if (!singleInterfaceMtu || !singleInterfaceMtuHelp) return; + if (currentInspection?.editing_locked) { + singleInterfaceMtuHelp.textContent = MTU_LOCKED_HELP; + } else { + singleInterfaceMtuHelp.textContent = SINGLE_INTERFACE_MTU_HELP; + } +} + +function updateMtuState() { + updateBridgeMtuState(); + updateSingleInterfaceMtuState(); +} + function validateConfig() { + clearMtuErrors(); if (document.getElementById("bridgeMode").checked) { const toInternet = document.getElementById("toInternet").value.trim(); const toNetwork = document.getElementById("toNetwork").value.trim(); @@ -83,6 +175,11 @@ function validateConfig() { alert("Bridge mode requires two different interfaces"); return false; } + if (document.getElementById("useXdpBridge").checked) { + clearMtuFieldError("bridgeMtu", "bridgeMtuError"); + } else if (!validateMtuField("bridgeMtu", "bridgeMtuError", parseOptionalMtu)) { + return false; + } } else if (document.getElementById("singleInterfaceMode").checked) { const interfaceName = document.getElementById("interface").value.trim(); const internetVlan = parseInt(document.getElementById("internetVlan").value, 10); @@ -99,6 +196,9 @@ function validateConfig() { alert("Network VLAN must be between 1 and 4094"); return false; } + if (!validateMtuField("singleInterfaceMtu", "singleInterfaceMtuError", parseOptionalMtu)) { + return false; + } } else { alert("Please select either bridge or single interface mode"); return false; @@ -116,12 +216,14 @@ function buildCandidateConfig() { use_xdp_bridge: document.getElementById("useXdpBridge").checked, to_internet: document.getElementById("toInternet").value.trim(), to_network: document.getElementById("toNetwork").value.trim(), + mtu: currentBridgeMtuValue(), }; } else { next.single_interface = { interface: document.getElementById("interface").value.trim(), internet_vlan: parseInt(document.getElementById("internetVlan").value, 10), network_vlan: parseInt(document.getElementById("networkVlan").value, 10), + mtu: parseOptionalMtu(document.getElementById("singleInterfaceMtu").value).value, }; } @@ -247,15 +349,18 @@ function populateFormFromConfig(config) { document.getElementById("useXdpBridge").checked = config.bridge.use_xdp_bridge ?? true; document.getElementById("toInternet").value = config.bridge.to_internet ?? ""; document.getElementById("toNetwork").value = config.bridge.to_network ?? ""; + document.getElementById("bridgeMtu").value = config.bridge.mtu ?? ""; } else if (config?.single_interface) { document.getElementById("singleInterfaceMode").checked = true; document.getElementById("interface").value = config.single_interface.interface ?? ""; document.getElementById("internetVlan").value = config.single_interface.internet_vlan ?? 2; document.getElementById("networkVlan").value = config.single_interface.network_vlan ?? 3; + document.getElementById("singleInterfaceMtu").value = config.single_interface.mtu ?? ""; } const event = new Event("change"); document.querySelector('input[name="networkMode"]:checked')?.dispatchEvent(event); + updateMtuState(); } function loadDraft() { @@ -590,9 +695,11 @@ function renderInspection(inspection) { "useXdpBridge", "toInternet", "toNetwork", + "bridgeMtu", "interface", "internetVlan", "networkVlan", + "singleInterfaceMtu", "saveButton", ].forEach((id) => { const element = document.getElementById(id); @@ -603,6 +710,7 @@ function renderInspection(inspection) { applyButton.disabled = !inspection?.can_apply; adoptButton.disabled = !inspection?.can_adopt; takeoverButton.disabled = !inspection?.can_take_over; + updateMtuState(); } function renderHelperStatus(status) { @@ -820,6 +928,7 @@ function retryShaping() { } function wireActions() { + applyMtuBounds(); wireReviewTabs(); [ "bridgeMode", @@ -832,6 +941,21 @@ function wireActions() { renderInterfaceSelectors(); }); }); + document.getElementById("useXdpBridge").addEventListener("change", updateMtuState); + [ + "bridgeMtu", + "singleInterfaceMtu", + ].forEach((id) => { + document.getElementById(id).addEventListener("input", () => { + if (id === "bridgeMtu") { + const parsed = parseOptionalMtu(document.getElementById("bridgeMtu").value); + if (parsed.ok) clearMtuFieldError("bridgeMtu", "bridgeMtuError"); + } else { + const parsed = parseOptionalMtu(document.getElementById("singleInterfaceMtu").value); + if (parsed.ok) clearMtuFieldError("singleInterfaceMtu", "singleInterfaceMtuError"); + } + }); + }); document.getElementById("saveButton").addEventListener("click", () => { if (!validateConfig()) return; saveDraft(); @@ -867,7 +991,7 @@ loadConfig((msg) => { renderShapingStatus(payload.shaping_status || {}); renderInspection(payload.network_mode_inspection || {}); - const draft = loadDraft(); + const draft = hydrateDraftMtu(loadDraft(), window.config); populateFormFromConfig(draft || window.config); renderRecoveryPanel(); wireActions(); diff --git a/src/rust/lqosd/src/node_manager/js_build/test-node-manager.sh b/src/rust/lqosd/src/node_manager/js_build/test-node-manager.sh index 5d093180..ff966549 100755 --- a/src/rust/lqosd/src/node_manager/js_build/test-node-manager.sh +++ b/src/rust/lqosd/src/node_manager/js_build/test-node-manager.sh @@ -10,6 +10,7 @@ fi echo "[test-node-manager] Running frontend contract tests..." node --test "${SCRIPT_DIR}/src/config/shaped_device_wire.test.mjs" +node --test "${SCRIPT_DIR}/src/config/config_interface_mtu.test.mjs" echo "[test-node-manager] Building bundles..." "${SCRIPT_DIR}/esbuild.sh" diff --git a/src/rust/lqosd/src/node_manager/local_api/network_mode.rs b/src/rust/lqosd/src/node_manager/local_api/network_mode.rs index fbda8395..5ab55238 100644 --- a/src/rust/lqosd/src/node_manager/local_api/network_mode.rs +++ b/src/rust/lqosd/src/node_manager/local_api/network_mode.rs @@ -77,7 +77,7 @@ fn unauthorized() -> (StatusCode, Json) { } fn helper_validation_error_response(message: String) -> (StatusCode, Json) { - warn!("Bridge helper request failed: {message}"); + warn!("Network-mode request failed: {message}"); ( StatusCode::BAD_REQUEST, Json(ApplyResponse { @@ -90,7 +90,7 @@ fn helper_validation_error_response(message: String) -> (StatusCode, Json (StatusCode, Json) { - error!("Bridge helper internal error: {message}"); + error!("Network-mode internal error: {message}"); ( StatusCode::INTERNAL_SERVER_ERROR, Json(ApplyResponse { @@ -102,11 +102,20 @@ fn helper_internal_error_response(message: String) -> (StatusCode, Json Result { - let live = lqos_config::load_config().map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; +#[derive(Debug, Clone, PartialEq, Eq)] +enum MergeNetworkModeError { + LoadLiveConfig, + InvalidCandidate(String), +} + +fn merge_network_mode(candidate: Config) -> Result { + let live = lqos_config::load_config().map_err(|_| MergeNetworkModeError::LoadLiveConfig)?; let mut merged = (*live).clone(); merged.bridge = candidate.bridge; merged.single_interface = candidate.single_interface; + merged + .validate() + .map_err(MergeNetworkModeError::InvalidCandidate)?; Ok(merged) } @@ -156,13 +165,23 @@ pub async fn inspect( State(state): State, Extension(login): Extension, Json(body): Json, -) -> Result, StatusCode> { +) -> Result, (StatusCode, Json)> { if login != LoginResult::Admin { - return Err(StatusCode::FORBIDDEN); + return Err(unauthorized()); } - let merged = merge_network_mode(body.config)?; - Ok(Json(run_network_mode_inspection(&state, merged).await?)) + let merged = merge_network_mode(body.config).map_err(|error| match error { + MergeNetworkModeError::InvalidCandidate(message) => { + helper_validation_error_response(message) + } + MergeNetworkModeError::LoadLiveConfig => helper_internal_error_response( + "Unable to load the live LibreQoS configuration".to_string(), + ), + })?; + run_network_mode_inspection(&state, merged) + .await + .map(Json) + .map_err(|_| helper_internal_error_response("Unable to inspect network mode".to_string())) } pub async fn apply( @@ -178,16 +197,17 @@ pub async fn apply( let username = get_username(&jar).await; let merged = match merge_network_mode(body.config) { Ok(config) => config, - Err(status) => { - return ( - status, - Json(ApplyResponse { - ok: false, - message: "Unable to load the live LibreQoS configuration".to_string(), - operation: None, - last_backup_id: None, - }), - ); + Err(error) => { + return match error { + MergeNetworkModeError::InvalidCandidate(message) => { + helper_validation_error_response(message) + } + MergeNetworkModeError::LoadLiveConfig => { + helper_internal_error_response( + "Unable to load the live LibreQoS configuration".to_string(), + ) + } + }; } }; let result = tokio::task::spawn_blocking({ @@ -212,7 +232,9 @@ pub async fn apply( match result { Ok(Ok(response)) => (StatusCode::OK, Json(response)), Ok(Err(err)) => helper_validation_error_response(err.to_string()), - Err(err) => helper_internal_error_response(format!("Bridge helper task failed: {err}")), + Err(err) => { + helper_internal_error_response(format!("Network-mode helper task failed: {err}")) + } } } @@ -238,7 +260,9 @@ pub async fn confirm( match result { Ok(Ok(response)) => (StatusCode::OK, Json(response)), Ok(Err(err)) => helper_validation_error_response(err.to_string()), - Err(err) => helper_internal_error_response(format!("Bridge helper task failed: {err}")), + Err(err) => { + helper_internal_error_response(format!("Network-mode helper task failed: {err}")) + } } } @@ -264,7 +288,9 @@ pub async fn revert( match result { Ok(Ok(response)) => (StatusCode::OK, Json(response)), Ok(Err(err)) => helper_validation_error_response(err.to_string()), - Err(err) => helper_internal_error_response(format!("Bridge helper task failed: {err}")), + Err(err) => { + helper_internal_error_response(format!("Network-mode helper task failed: {err}")) + } } } @@ -290,7 +316,9 @@ pub async fn rollback( match result { Ok(Ok(response)) => (StatusCode::OK, Json(response)), Ok(Err(err)) => helper_validation_error_response(err.to_string()), - Err(err) => helper_internal_error_response(format!("Bridge helper task failed: {err}")), + Err(err) => { + helper_internal_error_response(format!("Network-mode helper task failed: {err}")) + } } } @@ -314,6 +342,88 @@ pub async fn retry_shaping( match result { Ok(Ok(response)) => (StatusCode::OK, Json(response)), Ok(Err(err)) => helper_internal_error_response(err.to_string()), - Err(err) => helper_internal_error_response(format!("Bridge helper task failed: {err}")), + Err(err) => { + helper_internal_error_response(format!("Network-mode helper task failed: {err}")) + } + } +} + +#[cfg(test)] +mod tests { + use super::{MergeNetworkModeError, merge_network_mode}; + use lqos_config::{BridgeConfig, Config, SingleInterfaceConfig}; + use std::sync::{Mutex, OnceLock}; + + fn env_lock() -> &'static Mutex<()> { + static LOCK: OnceLock> = OnceLock::new(); + LOCK.get_or_init(|| Mutex::new(())) + } + + fn with_config_env(test_fn: impl FnOnce() -> T) -> T { + let _guard = env_lock().lock().expect("network-mode env lock"); + let old_lqos_config = std::env::var_os("LQOS_CONFIG"); + let config_path = std::env::temp_dir().join(format!( + "lqosd-network-mode-test-{}.toml", + std::process::id() + )); + let raw = include_str!("../../../../lqos_config/src/etc/v15/example.toml"); + std::fs::write(&config_path, raw).expect("write config"); + lqos_config::clear_cached_config(); + + unsafe { + std::env::set_var("LQOS_CONFIG", &config_path); + } + let result = test_fn(); + + match old_lqos_config { + Some(value) => unsafe { + std::env::set_var("LQOS_CONFIG", value); + }, + None => unsafe { + std::env::remove_var("LQOS_CONFIG"); + }, + } + lqos_config::clear_cached_config(); + let _ = std::fs::remove_file(config_path); + result + } + + #[test] + fn merge_network_mode_rejects_invalid_bridge_mtu() { + let mut candidate = Config::default(); + candidate.bridge = Some(BridgeConfig { + mtu: Some(9217), + ..BridgeConfig::default() + }); + + let error = + with_config_env(|| merge_network_mode(candidate).expect_err("invalid MTU should fail")); + + assert_eq!( + error, + MergeNetworkModeError::InvalidCandidate( + "bridge.mtu must be between 576 and 9216".to_string() + ) + ); + } + + #[test] + fn merge_network_mode_rejects_invalid_single_interface_mtu() { + let mut candidate = Config::default(); + candidate.bridge = None; + candidate.single_interface = Some(SingleInterfaceConfig { + mtu: Some(575), + ..SingleInterfaceConfig::default() + }); + + let error = + with_config_env(|| merge_network_mode(candidate).expect_err("invalid MTU should fail")); + + assert_eq!( + error, + MergeNetworkModeError::InvalidCandidate( + "single_interface.mtu must be between 576 and 9216".to_string() + ) + ); } } diff --git a/src/rust/lqosd/src/node_manager/static2/config_interface.html b/src/rust/lqosd/src/node_manager/static2/config_interface.html index 783e185e..aa04f7b1 100644 --- a/src/rust/lqosd/src/node_manager/static2/config_interface.html +++ b/src/rust/lqosd/src/node_manager/static2/config_interface.html @@ -55,12 +55,12 @@
Bridge Mode Configuration
-
Choose the two shaping interfaces for the managed Linux bridge flow, or leave XDP enabled if you are intentionally handling Netplan outside this page.
+
Choose the two shaping interfaces. Linux bridge mode can manage Netplan; XDP mode leaves Netplan alone.
- + -
Use the XDP bridge instead of the Linux Bridge. This remains a manual/power-user netplan workflow.
+
XDP does not write Netplan or apply Bridge MTU.
@@ -78,6 +78,13 @@
Pick a different eligible interface for the LAN side.
+ +
+ + +
Applies to the bridge members and br0.
+ +
@@ -87,7 +94,7 @@
Single Interface Mode Configuration
-
Pick the trunk interface and define the WAN and LAN VLAN IDs that LibreQoS should prepare in managed Netplan.
+
Pick the trunk interface and VLAN IDs for managed Netplan.
@@ -108,6 +115,13 @@
VLAN ID for LAN traffic.
+ +
+ + +
Applies to the trunk interface.
+ +