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
? `
${escapeHtml(schedulerSetupMessage(data) || "Choose a topology source in Complete Setup before expecting scheduler activity.")}
`
: "";
- const alertMarkup = data?.error
- ? `${escapeHtml(String(data.error).trim())}
`
+ const alertMarkup = liveError
+ ? `${escapeHtml(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
? `${escapeHtml(schedulerSetupMessage(data) || "Choose a topology source in Complete Setup before expecting scheduler activity.")}
`
: "";
+ const transportWarningMarkup = options.transportWarning
+ ? `${escapeHtml(options.transportWarning)}
`
+ : "";
const alertMarkup = liveError
? `${escapeHtml(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(`
-
- ${escapeHtml(message)}
-
`);
-}
-
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(`
+
+ ${escapeHtml("Failed to load scheduler details. Retrying in the background.")}
+
`);
+ }
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(`
+
+ ${escapeHtml("Timed out while loading scheduler details. Retrying in the background.")}
+
`);
+ }
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
-
+
-
Optional site identifier in UISP.
+
Required only for full topology mode. Leave blank in other modes to let LibreQoS choose the import root.