From 9f181e64cfd4e6496fe458716b51af3bae7ddd8a Mon Sep 17 00:00:00 2001 From: rchac Date: Sat, 14 Mar 2026 17:13:57 +0000 Subject: [PATCH] Add optional network.json node IDs across supported integrations --- docs-es/v2.0/configuration-advanced-es.md | 20 +++++++ docs-es/v2.0/integrations-es.md | 14 +++++ docs/v2.0/configuration-advanced.md | 20 +++++++ docs/v2.0/integrations.md | 14 +++++ src/integrationCommon.py | 19 +++++- src/integrationNetzur.py | 5 ++ src/integrationSonar.py | 12 ++-- src/integrationSplynx.py | 14 +++-- src/rust/Cargo.toml | 2 +- src/rust/lqos_config/src/network_json.rs | 48 +++++++++++++++ .../src/network_json/network_json_node.rs | 4 ++ .../network_json/network_json_transport.rs | 3 + .../lqosd/src/shaped_devices_tracker/mod.rs | 1 + .../src/strategies/ap_only.rs | 4 ++ .../src/strategies/ap_site.rs | 2 + .../src/strategies/full/mod.rs | 6 ++ .../src/strategies/full/network_json.rs | 60 +++++++++++++++++++ .../src/strategies/full2/graph_mapping.rs | 57 ++++++++++++++++++ .../src/strategies/full2/net_json_parent.rs | 1 + .../uisp_integration/src/strategies/mod.rs | 4 +- src/testGraph.py | 35 +++++++++++ 21 files changed, 331 insertions(+), 14 deletions(-) diff --git a/docs-es/v2.0/configuration-advanced-es.md b/docs-es/v2.0/configuration-advanced-es.md index cb182325..7753e64b 100644 --- a/docs-es/v2.0/configuration-advanced-es.md +++ b/docs-es/v2.0/configuration-advanced-es.md @@ -87,6 +87,26 @@ flowchart LR Network.json permite a los operadores de internet (ISP) definir una topología de red jerárquica o plana. +Cada nodo de topología puede incluir opcionalmente un campo `"id"`. Este campo está pensado para transportar un identificador estable del CRM/NMS de origen cuando exista. LibreQoS todavía sigue haciendo match de jerarquía y overrides por nombre de nodo, no por este ID, así que por ahora `"id"` es metadata. + +Formato recomendado: + +```json +{ + "Tower_A": { + "id": "uisp:site:abc123", + "downloadBandwidthMbps": 1000, + "uploadBandwidthMbps": 1000, + "type": "site" + } +} +``` + +Notas: +- Use IDs string con namespace como `uisp:site:`, `splynx:network_site:` o `sonar:ap:`. +- Los nodos generados solo por LibreQoS pueden usar IDs generados estables como `libreqos:generated:uisp:site:orphans`. +- También pueden aparecer campos de metadata específicos de integración como `uisp_site` y `uisp_device` junto con el campo genérico `id`. + Si planea usar las integraciones ya incluidas en LibreQoS de UISP, Splynx o Netzur, no necesita todavía crear un archivo network.json. Si planea usar la integración ya incluida de UISP, el archivo network.json se creará en automático durante la primera ejecución (siempre y cuando network.json no exista previamente). diff --git a/docs-es/v2.0/integrations-es.md b/docs-es/v2.0/integrations-es.md index 1e16ff9d..d39714c8 100644 --- a/docs-es/v2.0/integrations-es.md +++ b/docs-es/v2.0/integrations-es.md @@ -40,6 +40,20 @@ Cuando hay integraciones habilitadas: - `network.json` también puede sobrescribirse según configuración (por ejemplo `always_overwrite_network_json`). - Las ediciones manuales pueden sobrescribirse en el siguiente ciclo de refresco. +## Soporte para IDs de nodos de topología + +LibreQoS soporta un campo genérico opcional `"id"` en los nodos de `network.json`. Este campo está pensado para transportar identificadores estables del sistema de integración cuando sea posible. En la versión actual, el campo es informativo y todavía no es la clave autoritativa para shaping u overrides. + +| Integración | Soporte de ID de nodo en `network.json` | Notas | +|---|---|---| +| UISP | Sí | Sitios/dispositivos reales de UISP exportan `id` genérico más la metadata existente `uisp_site` / `uisp_device`. Los nodos sintéticos de LibreQoS usan IDs generados estables. | +| Splynx | Sí | Los nodos de topología de network sites y AP/site exportan `id` genérico. | +| Sonar | Sí | Los nodos de topología de sitios y AP exportan `id` genérico. | +| Netzur | Parcial | Se exporta solo cuando el payload upstream de zonas incluye un ID de zona estable. | +| VISP | No | El importador actual shapea servicios/dispositivos pero no construye nodos de topología en `network.json`. | +| Powercode | No | El importador actual no construye nodos de topología en `network.json`. | +| WISPGate | No | El importador actual no construye nodos de topología a partir de identificadores estables upstream. | + ## Manejo común de velocidades de cliente Para las integraciones incluidas que importan velocidades brutas de plan de suscriptor, LibreQoS aplica la misma regla compartida antes de escribir `ShapedDevices.csv`: diff --git a/docs/v2.0/configuration-advanced.md b/docs/v2.0/configuration-advanced.md index 173fccb3..b927fe7b 100644 --- a/docs/v2.0/configuration-advanced.md +++ b/docs/v2.0/configuration-advanced.md @@ -131,6 +131,26 @@ How overrides apply: Network.json allows ISP operators to define a Hierarchical Network Topology, or Flat Network Topology. +Each topology node may optionally include an `"id"` field. This is intended to carry a stable node identifier from the source CRM/NMS when one exists. LibreQoS currently still matches hierarchy and overrides by node name, not by this ID, so `"id"` is metadata for now. + +Recommended format: + +```json +{ + "Tower_A": { + "id": "uisp:site:abc123", + "downloadBandwidthMbps": 1000, + "uploadBandwidthMbps": 1000, + "type": "site" + } +} +``` + +Notes: +- Use namespaced string IDs such as `uisp:site:`, `splynx:network_site:`, or `sonar:ap:`. +- Generated LibreQoS-only nodes may use stable generated IDs such as `libreqos:generated:uisp:site:orphans`. +- Existing integration-specific metadata fields such as `uisp_site` and `uisp_device` may also appear alongside the generic `id` field. + If you plan to use the built-in UISP, Splynx, or Netzur integrations, you do not need to create a network.json file quite yet. If you plan to use the built-in UISP integration, it will create this automatically on its first run (assuming network.json is not already present). diff --git a/docs/v2.0/integrations.md b/docs/v2.0/integrations.md index 3042ce11..f7e6beaf 100644 --- a/docs/v2.0/integrations.md +++ b/docs/v2.0/integrations.md @@ -51,6 +51,20 @@ When integrations are enabled: - `network.json` may also be overwritten depending on integration settings (for example `always_overwrite_network_json`). - Manual edits may be overwritten on the next refresh cycle. +## Topology Node ID Support + +LibreQoS supports an optional generic `"id"` field on `network.json` nodes. This field is intended to carry stable node identifiers from the integration source where possible. In the current release, the field is informational and is not yet the authoritative match key for shaping or overrides. + +| Integration | `network.json` node ID support | Notes | +|---|---|---| +| UISP | Yes | Real UISP sites/devices export generic `id` plus existing `uisp_site` / `uisp_device` metadata. Synthetic LibreQoS nodes use stable generated IDs. | +| Splynx | Yes | Network sites and AP/site topology nodes export generic `id`. | +| Sonar | Yes | Site and AP topology nodes export generic `id`. | +| Netzur | Partial | Exported only when the upstream zone payload includes a stable zone ID. | +| VISP | No | Current importer shapes services/devices but does not build topology nodes in `network.json`. | +| Powercode | No | Current importer does not build topology nodes in `network.json`. | +| WISPGate | No | Current importer does not build topology nodes from stable upstream topology identifiers. | + ## Common Client Rate Handling For built-in integrations that import raw subscriber plan speeds, LibreQoS applies the same shared client-rate rule before writing `ShapedDevices.csv`: diff --git a/src/integrationCommon.py b/src/integrationCommon.py index f5d9c9a1..eb019e97 100644 --- a/src/integrationCommon.py +++ b/src/integrationCommon.py @@ -97,6 +97,16 @@ def nodeTypeToString(integer): string = 'device' return(string) +def syntheticNetworkJsonId(scope: str, nodeType: str, name: str) -> str: + parts = [] + for ch in str(name).lower(): + if ch.isalnum(): + parts.append(ch) + elif not parts or parts[-1] != '-': + parts.append('-') + slug = ''.join(parts).strip('-') + return f"libreqos:generated:{scope}:{nodeType}:{slug}" + class NetworkNode: # Defines a node on a LibreQoS network graph. # Nodes default to being disconnected, and @@ -114,8 +124,9 @@ class NetworkNode: ipv6: List address: str mac: str + networkJsonId: str - def __init__(self, id: str, displayName: str = "", parentId: str = "", type: NodeType = NodeType.site, download: int = generated_pn_download_mbps(), upload: int = generated_pn_upload_mbps(), ipv4: List = [], ipv6: List = [], address: str = "", mac: str = "", customerName: str = "") -> None: + def __init__(self, id: str, displayName: str = "", parentId: str = "", type: NodeType = NodeType.site, download: int = generated_pn_download_mbps(), upload: int = generated_pn_upload_mbps(), ipv4: List = [], ipv6: List = [], address: str = "", mac: str = "", customerName: str = "", networkJsonId: str = "") -> None: self.id = id self.parentIndex = 0 self.type = type @@ -131,6 +142,7 @@ class NetworkNode: self.address = address self.customerName = customerName self.mac = mac + self.networkJsonId = networkJsonId class NetworkGraph: @@ -319,7 +331,8 @@ class NetworkGraph: siteNode = NetworkNode( id=str(node.id) + "_gen", displayName="(Generated Site) " + node.displayName, - type=NodeType.site + type=NodeType.site, + networkJsonId=syntheticNetworkJsonId("graph", "site", node.displayName), ) siteNode.parentIndex = node.parentIndex node.parentId = siteNode.id @@ -453,6 +466,8 @@ class NetworkGraph: "uploadBandwidthMbps": self.nodes[idx].uploadMbps, 'type': nodeTypeToString(self.nodes[idx].type), } + if self.nodes[idx].networkJsonId: + node["id"] = self.nodes[idx].networkJsonId children = {} hasChildren = False diff --git a/src/integrationNetzur.py b/src/integrationNetzur.py index 172ee0b5..f22e88c2 100644 --- a/src/integrationNetzur.py +++ b/src/integrationNetzur.py @@ -78,6 +78,10 @@ def createShaper() -> NetworkGraph: continue if name not in parents: parents[name] = parent_counter + zone_id = zone.get("id", zone.get("zone_id")) + network_json_id = "" + if zone_id not in (None, ""): + network_json_id = f"netzur:zone:{zone_id}" net.addRawNode( NetworkNode( id=parent_counter, @@ -85,6 +89,7 @@ def createShaper() -> NetworkGraph: type=NodeType.site, download=_apply_rate(zone.get("capacity_download_mbps")), upload=_apply_rate(zone.get("capacity_upload_mbps")), + networkJsonId=network_json_id, ) ) parent_counter += 1 diff --git a/src/integrationSonar.py b/src/integrationSonar.py index b989ffb5..143bcfc7 100644 --- a/src/integrationSonar.py +++ b/src/integrationSonar.py @@ -123,13 +123,15 @@ def getSitesAndAps(): sites = [] aps = [] for site in sites_and_aps: + site_has_ap = False for item in site['inventory_items']['entities']: ips = findIPs(item) if ips: - aps.append({'parent': f"site_{site['id']}",'id': f"ap_{item['id']}", 'model': item['inventory_model_id'], 'ip': ips[0]}) # Using the first IP in the list here because each IP should only have 1 IP assigned. + aps.append({'parent': f"site_{site['id']}",'id': f"ap_{item['id']}", 'raw_id': item['id'], 'model': item['inventory_model_id'], 'ip': ips[0]}) # Using the first IP in the list here because each IP should only have 1 IP assigned. + site_has_ap = True - if aps: #We don't care about sites that have equipment but no IP addresses. - sites.append({'id': f"site_{site['id']}", 'name': site['name']}) + if site_has_ap: #We don't care about sites that have equipment but no IP addresses. + sites.append({'id': f"site_{site['id']}", 'raw_id': site['id'], 'name': site['name']}) return sites, aps def getAccounts(sonar_active_status_ids): @@ -298,11 +300,11 @@ def createShaper(): break for site in sites: - net.addRawNode(NetworkNode(id=site['id'], displayName=site['name'], parentId="", type=NodeType.site)) + net.addRawNode(NetworkNode(id=site['id'], displayName=site['name'], parentId="", type=NodeType.site, networkJsonId=f"sonar:site:{site['raw_id']}")) for ap in aps: if ap['cpe_macs']: # I don't think we care about Aps with no customers. - net.addRawNode(NetworkNode(id=ap['id'], displayName=ap['name'], parentId=ap['parent'], type=NodeType.ap)) + net.addRawNode(NetworkNode(id=ap['id'], displayName=ap['name'], parentId=ap['parent'], type=NodeType.ap, networkJsonId=f"sonar:ap:{ap['raw_id']}")) for account in accounts: if account['parent']: diff --git a/src/integrationSplynx.py b/src/integrationSplynx.py index 3cc19ac8..0bd8523e 100644 --- a/src/integrationSplynx.py +++ b/src/integrationSplynx.py @@ -298,7 +298,8 @@ def run_splynx_pipeline(strategy_name: str): download = siteBandwidth[nodeName]["download"] upload = siteBandwidth[nodeName]["upload"] node = NetworkNode(id=node_id, displayName=nodeName, type=NodeType.site, - parentId=None, download=download, upload=upload, address=address) + parentId=None, download=download, upload=upload, address=address, + networkJsonId=f"splynx:network_site:{site_id}") net.addRawNode(node) created_ap = 0 for ap_id, ap_device in ap_nodes.items(): @@ -313,7 +314,8 @@ def run_splynx_pipeline(strategy_name: str): if site_id in site_id_to_node_id: parent_id = site_id_to_node_id[site_id] node = NetworkNode(id=ap_node_id(ap_id), displayName=nodeName, type=NodeType.ap, - parentId=parent_id, download=download, upload=upload, address=None) + parentId=parent_id, download=download, upload=upload, address=None, + networkJsonId=f"splynx:ap:{ap_id}") net.addRawNode(node) created_ap += 1 print(f"Created {created_ap} AP nodes (Network Sites mode)") @@ -327,7 +329,7 @@ def run_splynx_pipeline(strategy_name: str): if nodeName in siteBandwidth: download = siteBandwidth[nodeName]["download"] upload = siteBandwidth[nodeName]["upload"] - node = NetworkNode(id=ap_id, displayName=nodeName, type=NodeType.ap, parentId=None, download=download, upload=upload, address=None) + node = NetworkNode(id=ap_id, displayName=nodeName, type=NodeType.ap, parentId=None, download=download, upload=upload, address=None, networkJsonId=f"splynx:ap:{ap_id}") net.addRawNode(node) return # ap_site and full @@ -663,10 +665,12 @@ def createInfrastructureNodes(net, monitoring, hardware_name, hardware_parent, h nodeType = hardware_type[device_num] if nodeType == 'AP': node = NetworkNode(id=device_num, displayName=nodeName, type=NodeType.ap, - parentId=parent_id, download=download, upload=upload, address=None) + parentId=parent_id, download=download, upload=upload, address=None, + networkJsonId=f"splynx:ap:{device_num}") else: node = NetworkNode(id=device_num, displayName=nodeName, type=NodeType.site, - parentId=parent_id, download=download, upload=upload, address=None) + parentId=parent_id, download=download, upload=upload, address=None, + networkJsonId=f"splynx:site:{device_num}") net.addRawNode(node) def findBestParentNode(serviceItem, hardware_name, ipForRouter, sectorForRouter): diff --git a/src/rust/Cargo.toml b/src/rust/Cargo.toml index 27aa52a1..895e4bad 100644 --- a/src/rust/Cargo.toml +++ b/src/rust/Cargo.toml @@ -5,7 +5,7 @@ edition = "2024" license = "GPL-2.0-only" [profile.release] -strip = yes +strip = true lto = "thin" incremental = false diff --git a/src/rust/lqos_config/src/network_json.rs b/src/rust/lqos_config/src/network_json.rs index 28a5973a..a3fdb20a 100644 --- a/src/rust/lqos_config/src/network_json.rs +++ b/src/rust/lqos_config/src/network_json.rs @@ -78,6 +78,7 @@ impl NetworkJson { pub fn load() -> Result { let mut nodes = vec![NetworkJsonNode { name: "Root".to_string(), + id: None, virtual_node: false, max_throughput: (0.0, 0.0), current_throughput: DownUpOrder::zeroed(), @@ -353,6 +354,10 @@ fn recurse_node( .unwrap_or(false); let node = NetworkJsonNode { + id: json + .get("id") + .and_then(|v| v.as_str()) + .map(std::string::ToString::to_string), parents: parents.to_vec(), max_throughput: ( json_to_mbps(json.get("downloadBandwidthMbps")), @@ -440,6 +445,7 @@ mod test { fn parse_network_json_from_value(value: Value) -> NetworkJson { let mut nodes = vec![NetworkJsonNode { name: "Root".to_string(), + id: None, virtual_node: false, max_throughput: (0.0, 0.0), current_throughput: DownUpOrder::zeroed(), @@ -552,4 +558,46 @@ mod test { let encoded = serde_json::to_value(&transport).expect("transport must serialize"); assert_eq!(encoded["max_throughput"], serde_json::json!([1.5, 0.5])); } + + #[test] + fn parses_optional_node_ids_and_preserves_them_in_transport() { + let raw = serde_json::json!({ + "Site_1": { + "id": "uisp:site:123", + "downloadBandwidthMbps": 1000, + "uploadBandwidthMbps": 1000, + "children": { + "AP_1": { + "id": "uisp:device:456", + "downloadBandwidthMbps": 500, + "uploadBandwidthMbps": 500, + "children": {} + } + } + } + }); + + let parsed = parse_network_json_from_value(raw); + let site = parsed + .nodes + .iter() + .find(|n| n.name == "Site_1") + .expect("Site_1 must be present"); + let ap = parsed + .nodes + .iter() + .find(|n| n.name == "AP_1") + .expect("AP_1 must be present"); + + assert_eq!(site.id.as_deref(), Some("uisp:site:123")); + assert_eq!(ap.id.as_deref(), Some("uisp:device:456")); + assert_eq!( + site.clone_to_transit().id.as_deref(), + Some("uisp:site:123") + ); + assert_eq!( + ap.clone_to_transit().id.as_deref(), + Some("uisp:device:456") + ); + } } diff --git a/src/rust/lqos_config/src/network_json/network_json_node.rs b/src/rust/lqos_config/src/network_json/network_json_node.rs index 2062d7c7..6cfd1cd8 100644 --- a/src/rust/lqos_config/src/network_json/network_json_node.rs +++ b/src/rust/lqos_config/src/network_json/network_json_node.rs @@ -13,6 +13,9 @@ pub struct NetworkJsonNode { /// The node name, as it appears in `network.json` pub name: String, + /// Optional stable node identifier from `network.json` metadata. + pub id: Option, + /// If true, this node is "virtual" (logical only): it exists for monitoring/aggregation /// but should be omitted from the physical HTB tree. pub virtual_node: bool, @@ -96,6 +99,7 @@ impl NetworkJsonNode { NetworkJsonTransport { name: self.name.clone(), + id: self.id.clone(), is_virtual: self.virtual_node, max_throughput: self.max_throughput, current_throughput: ( diff --git a/src/rust/lqos_config/src/network_json/network_json_transport.rs b/src/rust/lqos_config/src/network_json/network_json_transport.rs index 7455d799..b46048c2 100644 --- a/src/rust/lqos_config/src/network_json/network_json_transport.rs +++ b/src/rust/lqos_config/src/network_json/network_json_transport.rs @@ -8,6 +8,9 @@ use serde::{Deserialize, Serialize}; pub struct NetworkJsonTransport { /// Display name pub name: String, + /// Optional stable node identifier carried in network.json metadata. + #[serde(default)] + pub id: Option, /// True if this node is a "virtual" (logical-only) node. #[serde(rename = "virtual", default)] pub is_virtual: bool, diff --git a/src/rust/lqosd/src/shaped_devices_tracker/mod.rs b/src/rust/lqosd/src/shaped_devices_tracker/mod.rs index 0e181837..ab899762 100644 --- a/src/rust/lqosd/src/shaped_devices_tracker/mod.rs +++ b/src/rust/lqosd/src/shaped_devices_tracker/mod.rs @@ -209,6 +209,7 @@ pub fn get_top_n_root_queues(n_queues: usize) -> BusResponse { 0, NetworkJsonTransport { name: "Others".into(), + id: None, is_virtual: false, max_throughput: (0.0, 0.0), current_throughput: other_bw, diff --git a/src/rust/uisp_integration/src/strategies/ap_only.rs b/src/rust/uisp_integration/src/strategies/ap_only.rs index ff4c5488..1ef045ac 100644 --- a/src/rust/uisp_integration/src/strategies/ap_only.rs +++ b/src/rust/uisp_integration/src/strategies/ap_only.rs @@ -46,6 +46,10 @@ pub async fn build_ap_only_network( // Metadata ap_object.insert("type".to_string(), "AP".to_string().into()); + ap_object.insert( + "id".to_string(), + format!("uisp:device:{}", ap_device.id).into(), + ); ap_object.insert("uisp_device".to_string(), ap_device.id.clone().into()); // Save the entry diff --git a/src/rust/uisp_integration/src/strategies/ap_site.rs b/src/rust/uisp_integration/src/strategies/ap_site.rs index d2399f53..3fc333a5 100644 --- a/src/rust/uisp_integration/src/strategies/ap_site.rs +++ b/src/rust/uisp_integration/src/strategies/ap_site.rs @@ -204,6 +204,7 @@ impl Layer { site.max_down_mbps.into(), ); root.insert("uploadBandwidthMbps".to_owned(), site.max_up_mbps.into()); + root.insert("id".to_string(), format!("uisp:site:{}", site.id).into()); root.insert("uisp_site".to_string(), site.id.clone().into()); root.insert("parent_site".to_string(), name.to_string().into()); } @@ -215,6 +216,7 @@ impl Layer { if let Some(device) = uisp_data.devices.iter().find(|d| d.name == *name) { root.insert("downloadBandwidthMbps".to_owned(), device.download.into()); root.insert("uploadBandwidthMbps".to_owned(), device.upload.into()); + root.insert("id".to_string(), format!("uisp:device:{}", device.id).into()); root.insert("uisp_device".to_string(), device.id.clone().into()); } } diff --git a/src/rust/uisp_integration/src/strategies/full/mod.rs b/src/rust/uisp_integration/src/strategies/full/mod.rs index d036c2b1..b117737f 100644 --- a/src/rust/uisp_integration/src/strategies/full/mod.rs +++ b/src/rust/uisp_integration/src/strategies/full/mod.rs @@ -1,3 +1,9 @@ +//! Legacy UISP full-topology builder. +//! +//! `build_full_network` is retained for legacy reference and shared support code, +//! but current strategy dispatch does not select it. The public `"full"` strategy +//! now aliases to the `full2` backend. + #![allow(dead_code)] mod ap_promotion; pub(crate) mod bandwidth_overrides; diff --git a/src/rust/uisp_integration/src/strategies/full/network_json.rs b/src/rust/uisp_integration/src/strategies/full/network_json.rs index 567cd90d..a3f2a797 100644 --- a/src/rust/uisp_integration/src/strategies/full/network_json.rs +++ b/src/rust/uisp_integration/src/strategies/full/network_json.rs @@ -61,6 +61,10 @@ fn traverse_sites( "type".to_string(), serde_json::Value::String(sites[idx].site_type.as_network_json_string()), ); + entry.insert( + "id".to_string(), + serde_json::Value::String(generic_node_id(&sites[idx])), + ); if depth < 10 { let mut children = serde_json::Map::new(); @@ -86,3 +90,59 @@ fn traverse_sites( fn should_traverse(t: &UispSiteType) -> bool { !matches!(t, UispSiteType::Client) } + +fn generic_node_id(site: &UispSite) -> String { + if site.site_type == UispSiteType::ClientWithChildren { + format!( + "libreqos:generated:uisp:site:{}", + slugify_generated_name(&site.name) + ) + } else { + format!("uisp:site:{}", site.id) + } +} + +fn slugify_generated_name(name: &str) -> String { + let mut slug = String::with_capacity(name.len()); + let mut last_was_dash = false; + for ch in name.chars() { + if ch.is_ascii_alphanumeric() { + slug.push(ch.to_ascii_lowercase()); + last_was_dash = false; + } else if !last_was_dash { + slug.push('-'); + last_was_dash = true; + } + } + slug.trim_matches('-').to_string() +} + +#[cfg(test)] +mod test { + use super::{generic_node_id, slugify_generated_name}; + use crate::uisp_types::{UispSite, UispSiteType}; + + #[test] + fn slugifies_generated_site_names() { + assert_eq!(slugify_generated_name("Orphans"), "orphans"); + assert_eq!( + slugify_generated_name("Generated Site / Tower 1"), + "generated-site-tower-1" + ); + } + + #[test] + fn generated_site_ids_use_slugged_names() { + let site = UispSite { + id: "ignored-for-generated".to_string(), + name: "Generated Site / Tower 1".to_string(), + site_type: UispSiteType::ClientWithChildren, + ..Default::default() + }; + + assert_eq!( + generic_node_id(&site), + "libreqos:generated:uisp:site:generated-site-tower-1" + ); + } +} diff --git a/src/rust/uisp_integration/src/strategies/full2/graph_mapping.rs b/src/rust/uisp_integration/src/strategies/full2/graph_mapping.rs index b5698dbd..4998480f 100644 --- a/src/rust/uisp_integration/src/strategies/full2/graph_mapping.rs +++ b/src/rust/uisp_integration/src/strategies/full2/graph_mapping.rs @@ -31,4 +31,61 @@ impl GraphMapping { GraphMapping::AccessPoint { name, .. } => name.clone(), } } + + pub fn network_json_id(&self) -> String { + match self { + GraphMapping::Root { id, .. } | GraphMapping::Site { id, .. } => { + format!("uisp:site:{id}") + } + GraphMapping::GeneratedSite { name } => { + format!("libreqos:generated:uisp:site:{}", slugify_generated_name(name)) + } + GraphMapping::AccessPoint { id, .. } => format!("uisp:device:{id}"), + } + } +} + +fn slugify_generated_name(name: &str) -> String { + let mut slug = String::with_capacity(name.len()); + let mut last_was_dash = false; + for ch in name.chars() { + if ch.is_ascii_alphanumeric() { + slug.push(ch.to_ascii_lowercase()); + last_was_dash = false; + } else if !last_was_dash { + slug.push('-'); + last_was_dash = true; + } + } + slug.trim_matches('-').to_string() +} + +#[cfg(test)] +mod test { + use super::GraphMapping; + + #[test] + fn emits_generic_ids_for_real_and_generated_nodes() { + let root = GraphMapping::Root { + name: "Main".to_string(), + id: "site-1".to_string(), + }; + let ap = GraphMapping::AccessPoint { + name: "AP".to_string(), + id: "device-1".to_string(), + site_name: "Main".to_string(), + download_mbps: 100, + upload_mbps: 100, + }; + let generated = GraphMapping::GeneratedSite { + name: "Orphans".to_string(), + }; + + assert_eq!(root.network_json_id(), "uisp:site:site-1"); + assert_eq!(ap.network_json_id(), "uisp:device:device-1"); + assert_eq!( + generated.network_json_id(), + "libreqos:generated:uisp:site:orphans" + ); + } } diff --git a/src/rust/uisp_integration/src/strategies/full2/net_json_parent.rs b/src/rust/uisp_integration/src/strategies/full2/net_json_parent.rs index a273bd29..f0e207cd 100644 --- a/src/rust/uisp_integration/src/strategies/full2/net_json_parent.rs +++ b/src/rust/uisp_integration/src/strategies/full2/net_json_parent.rs @@ -18,6 +18,7 @@ pub fn walk_parents( let mut map = serde_json::Map::new(); // Entries are name, type, uisp_device or site, downloadBandwidthMbps, uploadBandwidthMbps, children map.insert("name".into(), name.clone().into()); + map.insert("id".into(), node_info.mapping.network_json_id().into()); map.insert("downloadBandwidthMbps".into(), node_info.download.into()); map.insert("uploadBandwidthMbps".into(), node_info.upload.into()); match node_info.mapping { diff --git a/src/rust/uisp_integration/src/strategies/mod.rs b/src/rust/uisp_integration/src/strategies/mod.rs index 38c0d240..0debe960 100644 --- a/src/rust/uisp_integration/src/strategies/mod.rs +++ b/src/rust/uisp_integration/src/strategies/mod.rs @@ -31,7 +31,9 @@ pub async fn build_with_strategy( flat::build_flat_network(config, ip_ranges).await?; Ok(()) } - /*"full" => { + /* "full" is now an alias for full2. The legacy full topology builder remains + * here only as shared support code and historical reference. + * "full" => { info!("Strategy selected: full"); full::build_full_network(config, ip_ranges).await?; Ok(()) diff --git a/src/testGraph.py b/src/testGraph.py index e2900eb1..132eb389 100644 --- a/src/testGraph.py +++ b/src/testGraph.py @@ -256,6 +256,41 @@ class TestGraph(unittest.TestCase): exampleFile = json.load(file) self.assertEqual(newFile, exampleFile) + def test_network_json_writes_optional_node_ids(self): + from integrationCommon import NetworkGraph, NetworkNode, NodeType + import json + + net = NetworkGraph() + net.addRawNode( + NetworkNode( + "Site_1", + "Site_1", + "", + NodeType.site, + 1000, + 1000, + networkJsonId="sonar:site:123", + ) + ) + net.addRawNode( + NetworkNode( + "AP_1", + "AP_1", + "Site_1", + NodeType.ap, + 500, + 500, + networkJsonId="sonar:ap:456", + ) + ) + net.prepareTree() + net.createNetworkJson() + with open('network.json') as file: + newFile = json.load(file) + + self.assertEqual(newFile["Site_1"]["id"], "sonar:site:123") + self.assertEqual(newFile["Site_1"]["children"]["AP_1"]["id"], "sonar:ap:456") + def test_ipv4_to_ipv6_map(self): """ Tests the underlying functionality of finding an IPv6 address from an IPv4 mapping -- knotmirror 0.0.1