From 0ccb2be707d5a5c8a718fe45f51ceb6077db402a Mon Sep 17 00:00:00 2001 From: rchac Date: Sat, 18 Jul 2026 01:35:48 -0600 Subject: [PATCH] changes --- src/LibreQoS.py | 93 +--- src/rust/lqos_config/src/lib.rs | 5 +- .../src/topology_canonical_state.rs | 261 ++++++++--- .../lqos_config/src/topology_runtime_state.rs | 441 +++++++++++++++--- src/rust/lqos_python/src/lib.rs | 35 ++ src/rust/lqos_topology/src/lib.rs | 4 +- src/rust/lqos_topology/src/publish.rs | 4 +- src/rust/lqos_topology/src/tests/group_01.rs | 36 ++ src/rust/lqos_topology/src/tests/group_02.rs | 94 ++++ src/rust/lqos_topology/src/tests/helpers.rs | 5 +- src/scheduler.py | 64 ++- src/test_libreqos_shaping_inputs.py | 265 ++++++----- src/test_scheduler.py | 223 +++++++++ 13 files changed, 1201 insertions(+), 329 deletions(-) diff --git a/src/LibreQoS.py b/src/LibreQoS.py index 86add2bc..1687b12c 100755 --- a/src/LibreQoS.py +++ b/src/LibreQoS.py @@ -83,9 +83,9 @@ except ImportError: return True try: - from liblqos_python import calculate_topology_source_generation # type: ignore -except Exception: - def calculate_topology_source_generation(): + from liblqos_python import validated_runtime_shaping_inputs_path # type: ignore +except ImportError: + def validated_runtime_shaping_inputs_path(): return None try: @@ -246,10 +246,6 @@ def get_shaping_inputs_path(): return get_runtime_state_path("shaping", "shaping_inputs.json") -def get_circuit_anchors_path(): - return get_runtime_state_path("topology", "circuit_anchors.json") - - def get_planner_state_path(): return get_runtime_state_path("shaping", "planner_state.json") @@ -514,75 +510,21 @@ def _validate_planned_circuit_attachment(node_name, node_data, circuit, planned_ return planned_major, planned_up_major -def _current_topology_source_generation(): - try: - generation = calculate_topology_source_generation() - except Exception: - return None - if generation is None: - return None - generation = str(generation).strip() - return generation if generation != '' else None - - -def _topology_runtime_status_supports_shaping_inputs(shaping_inputs_path): - current_generation = _current_topology_source_generation() - if current_generation is None: - return None - - status_path = get_topology_runtime_status_path() - try: - with open(status_path, 'r', encoding='utf-8') as handle: - status = json.load(handle) - except FileNotFoundError: - return None - except Exception: - return None - - if not isinstance(status, dict): - return False - - status_generation = str(status.get('source_generation', '') or '').strip() - if status_generation != current_generation: +def _runtime_shaping_inputs_are_validated(shaping_inputs_path): + if not os.path.isfile(shaping_inputs_path): return False - if not bool(status.get('ready')): + try: + active_path = validated_runtime_shaping_inputs_path() + except (OSError, RuntimeError): return False - - status_shaping_generation = str(status.get('shaping_generation', '') or '').strip() - if status_shaping_generation == '': + if active_path is None: return False - - status_shaping_inputs_path = str(status.get('shaping_inputs_path', '') or '').strip() - if status_shaping_inputs_path != '': - try: - if os.path.abspath(status_shaping_inputs_path) != os.path.abspath(shaping_inputs_path): - return False - except Exception: - return False - if not os.path.isfile(status_shaping_inputs_path): - return False - - return True - - -def _shaping_inputs_are_fresh(shaping_inputs_path, shaped_devices_file, network_json_file, circuit_anchors_file=None): - if not os.path.isfile(shaping_inputs_path): - return False - topology_runtime_ready = _topology_runtime_status_supports_shaping_inputs(shaping_inputs_path) - if topology_runtime_ready is True: - return True - if topology_runtime_ready is False: + active_path = str(active_path).strip() + if active_path == '': return False try: - shaping_inputs_mtime = os.path.getmtime(shaping_inputs_path) - if os.path.isfile(shaped_devices_file) and shaping_inputs_mtime < os.path.getmtime(shaped_devices_file): - return False - if os.path.isfile(network_json_file) and shaping_inputs_mtime < os.path.getmtime(network_json_file): - return False - if circuit_anchors_file and os.path.isfile(circuit_anchors_file) and shaping_inputs_mtime < os.path.getmtime(circuit_anchors_file): - return False - return True - except OSError: + return os.path.abspath(active_path) == os.path.abspath(shaping_inputs_path) + except Exception: return False @@ -661,10 +603,9 @@ def loadSubscriberCircuitsFromShapingInputs(shapingInputsPath): return subscriberCircuits, dictForCircuitsWithoutParentNodes -def loadSubscriberCircuitsForShaping(shapedDevicesFile, networkJSONfile): +def loadSubscriberCircuitsForShaping(shapedDevicesFile): shaping_inputs_path = get_shaping_inputs_path() - circuit_anchors_path = get_circuit_anchors_path() - if _shaping_inputs_are_fresh(shaping_inputs_path, shapedDevicesFile, networkJSONfile, circuit_anchors_path): + if _runtime_shaping_inputs_are_validated(shaping_inputs_path): try: subscriberCircuits, dictForCircuitsWithoutParentNodes = loadSubscriberCircuitsFromShapingInputs(shaping_inputs_path) print("Loaded shaping inputs from " + shaping_inputs_path) @@ -673,6 +614,8 @@ def loadSubscriberCircuitsForShaping(shapedDevicesFile, networkJSONfile): raise RefreshFailure( f"Unable to load required shaping_inputs.json at {shaping_inputs_path}: {e}" ) from e + if not topology_import_ingress_enabled(): + return loadSubscriberCircuits(shapedDevicesFile) raise RefreshFailure( "Missing or stale shaping_inputs.json. Run topology runtime before shaping." ) @@ -1438,7 +1381,7 @@ def refreshShapers(): if safeToRunRefresh == True: # Load Subscriber Circuits & Devices - subscriberCircuits, dictForCircuitsWithoutParentNodes = loadSubscriberCircuitsForShaping(shapedDevicesFile, networkJSONfile) + subscriberCircuits, dictForCircuitsWithoutParentNodes = loadSubscriberCircuitsForShaping(shapedDevicesFile) runtime_override_count = apply_effective_runtime_circuit_overrides(subscriberCircuits) if runtime_override_count > 0: print( diff --git a/src/rust/lqos_config/src/lib.rs b/src/rust/lqos_config/src/lib.rs index b1b0b08e..07c3fc7b 100644 --- a/src/rust/lqos_config/src/lib.rs +++ b/src/rust/lqos_config/src/lib.rs @@ -88,6 +88,7 @@ pub use topology_parent_candidates::{ TOPOLOGY_PARENT_CANDIDATES_FILENAME, TopologyParentCandidate, TopologyParentCandidatesError, TopologyParentCandidatesFile, TopologyParentCandidatesNode, topology_parent_candidates_path, }; +#[allow(deprecated)] pub use topology_runtime_state::{ TOPOLOGY_ATTACHMENT_HEALTH_STATE_FILENAME, TOPOLOGY_COMPILED_SHAPING_FILENAME, TOPOLOGY_EFFECTIVE_NETWORK_FILENAME, TOPOLOGY_EFFECTIVE_STATE_FILENAME, @@ -98,11 +99,13 @@ pub use topology_runtime_state::{ TopologyRuntimeStateError, TopologyRuntimeStatusFile, TopologyShapingCircuitInput, TopologyShapingDeviceInput, TopologyShapingInputsFile, TopologyShapingResolutionSource, active_runtime_shaping_inputs_path, active_runtime_shaping_inputs_path_from_status, - compute_effective_network_generation, compute_topology_source_generation, + compute_effective_network_file_generation, compute_effective_network_generation, + compute_shaping_inputs_file_generation, compute_topology_source_generation, load_active_runtime_shaping_inputs, load_active_runtime_shaping_inputs_from_status, topology_attachment_health_state_path, topology_compiled_shaping_path, topology_effective_network_path, topology_effective_state_path, topology_import_path, topology_runtime_status_path, topology_shaping_inputs_path, + validated_runtime_shaping_inputs_path, }; /// Returns whether an integration-backed topology ingress is enabled in the diff --git a/src/rust/lqos_config/src/topology_canonical_state.rs b/src/rust/lqos_config/src/topology_canonical_state.rs index 200c01f5..869b6d4b 100644 --- a/src/rust/lqos_config/src/topology_canonical_state.rs +++ b/src/rust/lqos_config/src/topology_canonical_state.rs @@ -184,22 +184,30 @@ fn empty_json_object() -> Value { } fn topology_import_ingress_enabled(config: &Config) -> bool { - config.uisp_integration.enable_uisp - || config.splynx_integration.enable_splynx - || config - .netzur_integration - .as_ref() - .is_some_and(|integration| integration.enable_netzur) - || config - .visp_integration - .as_ref() - .is_some_and(|integration| integration.enable_visp) - || config.powercode_integration.enable_powercode - || config.sonar_integration.enable_sonar - || config - .wispgate_integration - .as_ref() - .is_some_and(|integration| integration.enable_wispgate) + crate::integration_ingress_enabled(config) +} + +fn canonical_ingress_kind_matches_mode( + ingress_kind: TopologyCanonicalIngressKind, + integration_ingress: bool, +) -> bool { + matches!( + (ingress_kind, integration_ingress), + (TopologyCanonicalIngressKind::NativeIntegration, true) + | (TopologyCanonicalIngressKind::LegacyNetworkJson, false) + ) +} + +fn current_legacy_network_json_identity( + config: &Config, +) -> Result, TopologyCanonicalStateError> { + let legacy_network_path = Path::new(&config.lqos_directory).join("network.json"); + if !legacy_network_path.exists() { + return Ok(None); + } + let raw = std::fs::read_to_string(legacy_network_path)?; + let network = serde_json::from_str::(&raw)?; + Ok(topology_ingress_fingerprint_for_network_json(&network)) } pub(crate) fn topology_ingress_fingerprint_from_tokens(tokens: I) -> Option @@ -281,19 +289,21 @@ pub(crate) fn current_topology_ingress_identity( config: &Config, ) -> Result, TopologyCanonicalStateError> { let integration_ingress = topology_import_ingress_enabled(config); - if integration_ingress { - let topology_import_path = config.topology_state_file_path(TOPOLOGY_IMPORT_FILENAME); - if topology_import_path.exists() { - let raw = std::fs::read_to_string(topology_import_path)?; - let imported = serde_json::from_str::(&raw)?; - if let Some(identity) = imported - .get("ingress_identity") - .and_then(Value::as_str) - .map(str::trim) - .filter(|value| !value.is_empty()) - { - return Ok(Some(identity.to_string())); - } + if !integration_ingress { + return current_legacy_network_json_identity(config); + } + + let topology_import_path = config.topology_state_file_path(TOPOLOGY_IMPORT_FILENAME); + if topology_import_path.exists() { + let raw = std::fs::read_to_string(topology_import_path)?; + let imported = serde_json::from_str::(&raw)?; + if let Some(identity) = imported + .get("ingress_identity") + .and_then(Value::as_str) + .map(str::trim) + .filter(|value| !value.is_empty()) + { + return Ok(Some(identity.to_string())); } } @@ -311,17 +321,7 @@ pub(crate) fn current_topology_ingress_identity( return Ok(Some(identity.to_string())); } - if integration_ingress { - return Ok(None); - } - - let legacy_network_path = Path::new(&config.lqos_directory).join("network.json"); - if !legacy_network_path.exists() { - return Ok(None); - } - let raw = std::fs::read_to_string(legacy_network_path)?; - let network = serde_json::from_str::(&raw)?; - Ok(topology_ingress_fingerprint_for_network_json(&network)) + Ok(None) } fn quarantine_target_path(config: &Config, path: &Path, stamp: u64, attempt: usize) -> PathBuf { @@ -1054,16 +1054,47 @@ impl TopologyCanonicalStateFile { /// may read `network.json` from `config.lqos_directory`. pub fn load_with_legacy_fallback(config: &Config) -> Result { let state = Self::load(config)?; - if !state.nodes.is_empty() { - let is_current = match state.matches_current_ingress(config) { - Ok(is_current) => is_current, - Err(err) => { + let integration_ingress = topology_import_ingress_enabled(config); + if !integration_ingress { + let legacy_network_path = Path::new(&config.lqos_directory).join("network.json"); + if !legacy_network_path.exists() { + return Ok(state); + } + let raw = std::fs::read_to_string(legacy_network_path)?; + let network = serde_json::from_str::(&raw)?; + let imported = Self::from_legacy_network_json(&network); + let imported_identity = imported.topology_ingress_fingerprint(); + let stale_state = !state.nodes.is_empty() + && (!canonical_ingress_kind_matches_mode(state.ingress_kind, false) + || state.topology_ingress_fingerprint() != imported_identity); + if stale_state { + let quarantine_result = quarantine_stale_topology_state( + config, + &format!( + "canonical topology source '{}' is stale for current manual topology ingress", + state.source + ), + ); + if let Err(err) = quarantine_result { warn!( - "Unable to validate topology canonical state against current ingress; preserving existing state: {err}" + "Unable to quarantine stale topology state before manual network.json import; using current manual topology anyway: {err}" ); - true } - }; + } + return Ok(imported); + } + + if !state.nodes.is_empty() { + let is_current = canonical_ingress_kind_matches_mode(state.ingress_kind, true) + && match state.matches_current_ingress(config) { + Ok(is_current) => is_current, + Err(err) => { + warn!( + "Unable to validate topology canonical state against current ingress; preserving existing state: {err}" + ); + true + } + }; if is_current { return Ok(state); } @@ -1076,17 +1107,7 @@ impl TopologyCanonicalStateFile { )?; } - if topology_import_ingress_enabled(config) { - return Ok(state); - } - - let legacy_network_path = Path::new(&config.lqos_directory).join("network.json"); - if !legacy_network_path.exists() { - return Ok(state); - } - let raw = std::fs::read_to_string(legacy_network_path)?; - let network = serde_json::from_str::(&raw)?; - Ok(Self::from_legacy_network_json(&network)) + Ok(Self::default()) } /// Saves the canonical topology state atomically. @@ -2186,7 +2207,7 @@ mod tests { } #[test] - fn current_ingress_identity_prevents_quarantining_matching_native_state() { + fn manual_mode_reimports_legacy_network_even_when_native_state_identity_matches() { let lqos_directory = unique_temp_dir("lqos-config-canonical-ingress-identity"); let ingress_identity = topology_ingress_identity_from_tokens([ "import:uisp/full2".to_string(), @@ -2303,13 +2324,17 @@ mod tests { .expect("load with fallback should succeed"); assert!(loaded.find_node("uisp:device:current-ap").is_some()); + assert_eq!( + loaded.ingress_kind, + TopologyCanonicalIngressKind::LegacyNetworkJson + ); assert!( - topology_state_dir + !topology_state_dir .join(TOPOLOGY_CANONICAL_STATE_FILENAME) .exists() ); assert!( - topology_state_dir + !topology_state_dir .join(TOPOLOGY_EDITOR_STATE_FILENAME) .exists() ); @@ -2324,17 +2349,85 @@ mod tests { Vec::::new() }; assert!( - !quarantined + quarantined .iter() .any(|name| name.starts_with("topology_canonical_state.json.stale-")) ); assert!( - !quarantined + quarantined .iter() .any(|name| name.starts_with("topology_editor_state.json.stale-")) ); } + #[test] + fn manual_mode_preserves_existing_canonical_when_network_json_is_missing() { + let lqos_directory = unique_temp_dir("lqos-config-missing-manual-network-json"); + let topology_state_dir = lqos_directory.join("state/topology"); + fs::create_dir_all(&topology_state_dir).expect("topology state dir should exist"); + let canonical = TopologyCanonicalStateFile { + schema_version: 1, + source: "legacy/network.json".to_string(), + generated_unix: Some(1), + ingress_identity: Some("previous-manual-identity".to_string()), + ingress_kind: TopologyCanonicalIngressKind::LegacyNetworkJson, + nodes: vec![TopologyCanonicalNode { + node_id: "tower-1".to_string(), + node_name: "Tower 1".to_string(), + latitude: None, + longitude: None, + node_kind: "Site".to_string(), + is_virtual: false, + 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::QueueVisible, + rate_input: super::TopologyCanonicalRateInput { + intrinsic_download_mbps: Some(100), + intrinsic_upload_mbps: Some(100), + legacy_imported_download_mbps: Some(100), + legacy_imported_upload_mbps: Some(100), + source: TopologyCanonicalRateInputSource::ImportedNetworkJson, + }, + }], + compatibility_network_json: json!({ + "Tower 1": { + "id": "tower-1", + "children": {}, + "type": "Site" + } + }), + }; + fs::write( + topology_state_dir.join(TOPOLOGY_CANONICAL_STATE_FILENAME), + serde_json::to_string_pretty(&canonical).expect("canonical should serialize"), + ) + .expect("canonical should write"); + let config = Config { + lqos_directory: lqos_directory.to_string_lossy().to_string(), + state_directory: None, + ..Config::default() + }; + + let loaded = TopologyCanonicalStateFile::load_with_legacy_fallback(&config) + .expect("load with missing network.json should preserve state"); + + assert_eq!( + loaded.ingress_kind, + TopologyCanonicalIngressKind::LegacyNetworkJson + ); + assert!(loaded.find_node("tower-1").is_some()); + assert!( + topology_state_dir + .join(TOPOLOGY_CANONICAL_STATE_FILENAME) + .exists() + ); + assert!(!config.quarantine_state_directory_path().exists()); + } + #[test] fn current_topology_ingress_identity_prefers_topology_import_artifact() { let lqos_directory = unique_temp_dir("lqos-config-topology-import-identity"); @@ -2433,6 +2526,48 @@ mod tests { assert!(identity.is_none()); } + #[test] + fn current_topology_ingress_identity_uses_network_json_in_manual_mode() { + let lqos_directory = unique_temp_dir("lqos-config-manual-network-json-identity"); + let network_json = json!({ + "Legacy Tower": { + "children": {}, + "type": "Site", + "downloadBandwidthMbps": 100, + "uploadBandwidthMbps": 100 + } + }); + fs::write( + lqos_directory.join("network.json"), + serde_json::to_string_pretty(&network_json).expect("network json should serialize"), + ) + .expect("network json should write"); + fs::write( + lqos_directory.join(TOPOLOGY_PARENT_CANDIDATES_FILENAME), + serde_json::to_string_pretty(&TopologyParentCandidatesFile { + source: "uisp/ap_site".to_string(), + ingress_identity: Some("stale-parent-candidates-identity".to_string()), + nodes: Vec::new(), + }) + .expect("parent candidates should serialize"), + ) + .expect("parent candidates should write"); + let config = Config { + lqos_directory: lqos_directory.to_string_lossy().to_string(), + state_directory: None, + ..Config::default() + }; + + let identity = current_topology_ingress_identity(&config) + .expect("ingress identity should load") + .expect("manual network.json identity should exist"); + let expected = TopologyCanonicalStateFile::from_legacy_network_json(&network_json) + .topology_ingress_fingerprint() + .expect("legacy fingerprint should compute"); + + assert_eq!(identity, expected); + } + #[test] fn load_with_legacy_fallback_skips_network_json_for_integration_ingress() { let lqos_directory = unique_temp_dir("lqos-config-no-legacy-fallback-integration"); diff --git a/src/rust/lqos_config/src/topology_runtime_state.rs b/src/rust/lqos_config/src/topology_runtime_state.rs index 02f90a9f..379e36a5 100644 --- a/src/rust/lqos_config/src/topology_runtime_state.rs +++ b/src/rust/lqos_config/src/topology_runtime_state.rs @@ -356,8 +356,8 @@ pub struct TopologyRuntimeStatusFile { pub error: Option, } -/// Shaping-relevant runtime status identity used by consumers that only need -/// to know whether the active shaping payload changed. +/// Runtime status identity used by consumers that need to know whether the +/// active shaping payload or effective-network export changed. #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct TopologyRuntimeShapingPayloadIdentity { /// Whether runtime outputs are ready. @@ -366,6 +366,8 @@ pub struct TopologyRuntimeShapingPayloadIdentity { pub source_generation: String, /// Stable generation hash of the shaping payload. pub shaping_generation: String, + /// Stable generation hash of the effective network export. + pub effective_generation: String, /// Path to the active shaping inputs payload. pub shaping_inputs_path: String, } @@ -432,28 +434,51 @@ pub fn topology_shaping_inputs_path(config: &Config) -> PathBuf { config.shaping_state_read_path(TOPOLOGY_SHAPING_INPUTS_FILENAME) } -/// Returns the currently active runtime shaping-inputs path when the topology -/// runtime has published a ready generation that matches the current source -/// inputs. +/// Returns the runtime shaping-inputs path only after validating the status, +/// source generation, shaping payload generation, and effective-network generation. /// -/// This function is pure: it has no side effects. -pub fn active_runtime_shaping_inputs_path( +/// Side effects: reads `topology_runtime_status.json` and the candidate +/// `shaping_inputs.json` and `network.effective.json`. +pub fn validated_runtime_shaping_inputs_path( config: &Config, ) -> Result, TopologyRuntimeStateError> { let current_generation = compute_topology_source_generation(config)?; let status = TopologyRuntimeStatusFile::load(config)?; - Ok(active_runtime_shaping_inputs_path_from_status( - &status, - ¤t_generation, - )) + Ok( + load_active_runtime_shaping_inputs_for_status(&status, ¤t_generation)? + .map(|(path, _)| path), + ) +} + +/// Deprecated compatibility wrapper for older callers. +/// +/// Side effects: validates the same files as [`validated_runtime_shaping_inputs_path`]. +#[deprecated( + note = "use validated_runtime_shaping_inputs_path; this function validates runtime artifacts before returning a path" +)] +pub fn active_runtime_shaping_inputs_path( + config: &Config, +) -> Result, TopologyRuntimeStateError> { + validated_runtime_shaping_inputs_path(config) } -/// Returns the active runtime shaping-inputs path from an already-loaded status file. +/// Deprecated compatibility wrapper for older callers that already loaded status. /// -/// This function is pure: it has no side effects. +/// This only checks the readiness metadata in `status`; it does not validate the +/// on-disk shaping or effective-network artifacts. +#[deprecated( + note = "use validated_runtime_shaping_inputs_path or load_active_runtime_shaping_inputs for artifact validation" +)] pub fn active_runtime_shaping_inputs_path_from_status( status: &TopologyRuntimeStatusFile, current_generation: &str, +) -> Option { + ready_runtime_shaping_inputs_path_from_status(status, current_generation) +} + +fn ready_runtime_shaping_inputs_path_from_status( + status: &TopologyRuntimeStatusFile, + current_generation: &str, ) -> Option { if !status.ready { return None; @@ -471,16 +496,82 @@ pub fn active_runtime_shaping_inputs_path_from_status( Some(PathBuf::from(path)) } +fn load_shaping_inputs_at_path( + path: &Path, +) -> Result { + let raw = std::fs::read_to_string(path)?; + Ok(serde_json::from_str(&raw)?) +} + +/// Computes the semantic shaping generation for one runtime shaping-input file. +/// +/// Side effects: reads the supplied shaping-input file. +pub fn compute_shaping_inputs_file_generation( + path: &Path, +) -> Result { + load_shaping_inputs_at_path(path)?.compute_shaping_generation() +} + +/// Computes the semantic effective-network generation for one runtime effective network file. +/// +/// Side effects: reads the supplied effective-network file. +pub fn compute_effective_network_file_generation( + path: &Path, +) -> Result { + let raw = std::fs::read_to_string(path)?; + let effective_network = serde_json::from_str::(&raw)?; + compute_effective_network_generation(&effective_network) +} + +fn effective_network_generation_matches_status( + status: &TopologyRuntimeStatusFile, +) -> Result { + let path = status.effective_network_path.trim(); + let expected_generation = status.effective_generation.trim(); + if path.is_empty() { + return Ok(false); + } + let path = Path::new(path); + if !path.exists() { + return Ok(false); + } + if expected_generation.is_empty() { + return Ok(false); + } + let computed_generation = compute_effective_network_file_generation(path)?; + Ok(computed_generation == expected_generation) +} + +fn load_active_runtime_shaping_inputs_for_status( + status: &TopologyRuntimeStatusFile, + current_generation: &str, +) -> Result, TopologyRuntimeStateError> { + let Some(path) = ready_runtime_shaping_inputs_path_from_status(status, current_generation) + else { + return Ok(None); + }; + if !effective_network_generation_matches_status(status)? { + return Ok(None); + } + let shaping_inputs = load_shaping_inputs_at_path(&path)?; + let computed_generation = shaping_inputs.compute_shaping_generation()?; + if computed_generation != status.shaping_generation.trim() { + return Ok(None); + } + Ok(Some((path, shaping_inputs))) +} + /// Loads the currently active runtime shaping-inputs file when the topology /// runtime has published one. pub fn load_active_runtime_shaping_inputs( config: &Config, ) -> Result, TopologyRuntimeStateError> { - let Some(path) = active_runtime_shaping_inputs_path(config)? else { - return Ok(None); - }; - let raw = std::fs::read_to_string(&path)?; - Ok(Some(serde_json::from_str(&raw)?)) + let current_generation = compute_topology_source_generation(config)?; + let status = TopologyRuntimeStatusFile::load(config)?; + Ok( + load_active_runtime_shaping_inputs_for_status(&status, ¤t_generation)? + .map(|(_, shaping_inputs)| shaping_inputs), + ) } /// Loads the active runtime shaping-inputs file from an already-loaded status file. @@ -489,12 +580,10 @@ pub fn load_active_runtime_shaping_inputs_from_status( status: &TopologyRuntimeStatusFile, ) -> Result, TopologyRuntimeStateError> { let current_generation = compute_topology_source_generation(config)?; - let Some(path) = active_runtime_shaping_inputs_path_from_status(status, ¤t_generation) - else { - return Ok(None); - }; - let raw = std::fs::read_to_string(&path)?; - Ok(Some(serde_json::from_str(&raw)?)) + Ok( + load_active_runtime_shaping_inputs_for_status(status, ¤t_generation)? + .map(|(_, shaping_inputs)| shaping_inputs), + ) } /// Returns the path of the topology runtime readiness status file. @@ -559,16 +648,20 @@ pub fn compute_topology_source_generation( let shaped_devices_path = config.legacy_runtime_file_path("ShapedDevices.csv"); let circuit_anchors_path = config.topology_state_read_path(CIRCUIT_ANCHORS_FILENAME); - let canonical_active = if file_exists_with_nonempty_nodes(&canonical_path)? { - let canonical = TopologyCanonicalStateFile::load(config) - .map_err(|err| TopologyRuntimeStateError::SourceGeneration(err.to_string()))?; - canonical - .matches_current_ingress(config) - .map_err(|err| TopologyRuntimeStateError::SourceGeneration(err.to_string()))? - } else { - false - }; - let editor_active = if !canonical_active && file_exists_with_nonempty_nodes(&editor_path)? { + let canonical_active = + if use_topology_import && file_exists_with_nonempty_nodes(&canonical_path)? { + let canonical = TopologyCanonicalStateFile::load(config) + .map_err(|err| TopologyRuntimeStateError::SourceGeneration(err.to_string()))?; + canonical + .matches_current_ingress(config) + .map_err(|err| TopologyRuntimeStateError::SourceGeneration(err.to_string()))? + } else { + false + }; + let editor_active = if use_topology_import + && !canonical_active + && file_exists_with_nonempty_nodes(&editor_path)? + { let editor = TopologyEditorStateFile::load(config) .map_err(|err| TopologyRuntimeStateError::SourceGeneration(err.to_string()))?; editor @@ -604,32 +697,30 @@ pub fn compute_topology_source_generation( hash_file_state(&mut hasher, "ShapedDevices.csv", &shaped_devices_path)?; hash_file_state(&mut hasher, CIRCUIT_ANCHORS_FILENAME, &circuit_anchors_path)?; } - if use_topology_import { + hash_file_state( + &mut hasher, + "lqos_overrides.json", + &operator_overrides_path(config), + )?; + + if config + .stormguard + .as_ref() + .is_some_and(|stormguard| stormguard.enabled && !stormguard.dry_run) + { hash_file_state( &mut hasher, - "lqos_overrides.json", - &operator_overrides_path(config), + "lqos_overrides.stormguard.json", + &stormguard_overrides_path(config), )?; + } - if config - .stormguard - .as_ref() - .is_some_and(|stormguard| stormguard.enabled && !stormguard.dry_run) - { - hash_file_state( - &mut hasher, - "lqos_overrides.stormguard.json", - &stormguard_overrides_path(config), - )?; - } - - if config.treeguard.enabled { - hash_file_state( - &mut hasher, - "lqos_overrides.treeguard.json", - &treeguard_overrides_path(config), - )?; - } + if config.treeguard.enabled { + hash_file_state( + &mut hasher, + "lqos_overrides.treeguard.json", + &treeguard_overrides_path(config), + )?; } if canonical_active { hash_file_state( @@ -803,6 +894,7 @@ impl TopologyRuntimeStatusFile { ready: self.ready, source_generation: self.source_generation.clone(), shaping_generation: self.shaping_generation.clone(), + effective_generation: self.effective_generation.clone(), shaping_inputs_path: self.shaping_inputs_path.clone(), } } @@ -815,8 +907,10 @@ mod tests { TOPOLOGY_COMPILED_SHAPING_FILENAME, TOPOLOGY_EDITOR_STATE_FILENAME, TOPOLOGY_IMPORT_FILENAME, TOPOLOGY_RUNTIME_STATUS_FILENAME, TopologyRuntimeStatusFile, TopologyShapingCircuitInput, TopologyShapingInputsFile, - compute_effective_network_generation, compute_topology_source_generation, - topology_runtime_status_path, + compute_effective_network_file_generation, compute_effective_network_generation, + compute_shaping_inputs_file_generation, compute_topology_source_generation, + load_active_runtime_shaping_inputs, topology_runtime_status_path, + validated_runtime_shaping_inputs_path, }; use crate::{ TopologyCanonicalStateFile, TopologyEditorNode, TopologyEditorStateFile, @@ -849,6 +943,19 @@ mod tests { .expect("ShapedDevices.csv should write"); } + fn write_effective_network(config: &Config, raw: &str) -> (PathBuf, String) { + let path = super::topology_effective_network_path(config); + fs::create_dir_all( + path.parent() + .expect("effective network path should have a parent"), + ) + .expect("topology state dir should exist"); + fs::write(&path, raw).expect("effective network should write"); + let generation = compute_effective_network_file_generation(&path) + .expect("effective generation should compute"); + (path, generation) + } + #[test] fn topology_source_generation_is_stable_for_identical_inputs() { let lqos_directory = unique_temp_dir("lqos-config-topology-generation-stable"); @@ -928,7 +1035,30 @@ mod tests { .expect("topology_canonical_state.json should write"); let after_canonical = compute_topology_source_generation(&config) .expect("generation should compute after canonical change"); - assert_ne!(after_anchors, after_canonical); + assert_eq!(after_anchors, after_canonical); + } + + #[test] + fn topology_source_generation_tracks_manual_override_files() { + let lqos_directory = unique_temp_dir("lqos-config-topology-generation-manual-overrides"); + write_required_inputs(&lqos_directory); + let config = Config { + lqos_directory: lqos_directory.to_string_lossy().to_string(), + state_directory: None, + ..Config::default() + }; + + let before = compute_topology_source_generation(&config) + .expect("generation should compute before override change"); + fs::write( + lqos_directory.join("lqos_overrides.json"), + r#"{"schema_version":1,"network_adjustments":[{"node_id":"tower-1","download_mbps":100}]}"#, + ) + .expect("operator overrides should write"); + let after = compute_topology_source_generation(&config) + .expect("generation should compute after override change"); + + assert_ne!(before, after); } #[test] @@ -1386,9 +1516,14 @@ mod tests { shaping_generation: "shape-2".to_string(), ..first.clone() }; + let changed_effective = TopologyRuntimeStatusFile { + effective_generation: "effective-2".to_string(), + ..first.clone() + }; assert!(first.semantic_equals_for_publish(&second)); assert!(!first.semantic_equals_for_publish(&changed)); + assert!(!first.semantic_equals_for_publish(&changed_effective)); assert_eq!( first.shaping_payload_identity(), second.shaping_payload_identity() @@ -1397,6 +1532,194 @@ mod tests { first.shaping_payload_identity(), changed.shaping_payload_identity() ); + assert_ne!( + first.shaping_payload_identity(), + changed_effective.shaping_payload_identity() + ); + } + + #[test] + fn active_shaping_inputs_rejects_status_when_payload_generation_changed() { + let lqos_directory = unique_temp_dir("lqos-config-topology-shaping-generation-stale"); + write_required_inputs(&lqos_directory); + let config = Config { + lqos_directory: lqos_directory.to_string_lossy().to_string(), + state_directory: None, + ..Config::default() + }; + let source_generation = + compute_topology_source_generation(&config).expect("source generation should compute"); + let mut shaping_inputs = TopologyShapingInputsFile { + schema_version: 1, + generated_unix: Some(1), + circuits: vec![TopologyShapingCircuitInput { + circuit_id: "circuit-1".to_string(), + effective_parent_node_name: "Tower 1".to_string(), + effective_parent_node_id: "tower-1".to_string(), + ..TopologyShapingCircuitInput::default() + }], + ..TopologyShapingInputsFile::default() + }; + shaping_inputs.shaping_generation = shaping_inputs + .compute_shaping_generation() + .expect("shaping generation should compute"); + shaping_inputs + .save(&config) + .expect("shaping inputs should save"); + let shaping_path = super::topology_shaping_inputs_path(&config); + let (effective_path, effective_generation) = write_effective_network(&config, "{}\n"); + TopologyRuntimeStatusFile { + schema_version: 1, + source_generation, + shaping_generation: shaping_inputs.shaping_generation.clone(), + effective_generation, + ready: true, + effective_network_path: effective_path.to_string_lossy().to_string(), + shaping_inputs_path: shaping_path.to_string_lossy().to_string(), + ..TopologyRuntimeStatusFile::default() + } + .save(&config) + .expect("status should save"); + + assert!( + validated_runtime_shaping_inputs_path(&config) + .expect("active path check should succeed") + .is_some() + ); + assert!( + load_active_runtime_shaping_inputs(&config) + .expect("active shaping inputs should load") + .is_some() + ); + + let mut changed = shaping_inputs; + changed.circuits[0].effective_parent_node_name = "Tower 2".to_string(); + changed + .save(&config) + .expect("changed shaping inputs should save"); + assert_ne!( + compute_shaping_inputs_file_generation(&shaping_path) + .expect("changed generation should compute"), + changed.shaping_generation + ); + + assert!( + validated_runtime_shaping_inputs_path(&config) + .expect("active path check should succeed") + .is_none() + ); + assert!( + load_active_runtime_shaping_inputs(&config) + .expect("active shaping inputs should check") + .is_none() + ); + } + + #[test] + fn active_shaping_inputs_rejects_status_when_effective_generation_changed() { + let lqos_directory = unique_temp_dir("lqos-config-topology-effective-generation-stale"); + write_required_inputs(&lqos_directory); + let config = Config { + lqos_directory: lqos_directory.to_string_lossy().to_string(), + state_directory: None, + ..Config::default() + }; + let source_generation = + compute_topology_source_generation(&config).expect("source generation should compute"); + let mut shaping_inputs = TopologyShapingInputsFile { + schema_version: 1, + generated_unix: Some(1), + circuits: vec![TopologyShapingCircuitInput { + circuit_id: "circuit-1".to_string(), + effective_parent_node_name: "Tower 1".to_string(), + effective_parent_node_id: "tower-1".to_string(), + ..TopologyShapingCircuitInput::default() + }], + ..TopologyShapingInputsFile::default() + }; + shaping_inputs.shaping_generation = shaping_inputs + .compute_shaping_generation() + .expect("shaping generation should compute"); + shaping_inputs + .save(&config) + .expect("shaping inputs should save"); + let (effective_path, effective_generation) = write_effective_network(&config, "{}\n"); + TopologyRuntimeStatusFile { + schema_version: 1, + source_generation, + shaping_generation: shaping_inputs.shaping_generation.clone(), + effective_generation, + ready: true, + effective_network_path: effective_path.to_string_lossy().to_string(), + shaping_inputs_path: super::topology_shaping_inputs_path(&config) + .to_string_lossy() + .to_string(), + ..TopologyRuntimeStatusFile::default() + } + .save(&config) + .expect("status should save"); + + assert!( + load_active_runtime_shaping_inputs(&config) + .expect("active shaping inputs should load") + .is_some() + ); + + fs::write(&effective_path, "{\"Tower 2\":{\"children\":{}}}\n") + .expect("effective network should rewrite"); + assert!( + load_active_runtime_shaping_inputs(&config) + .expect("active shaping inputs should check") + .is_none() + ); + } + + #[test] + fn active_shaping_inputs_rejects_status_without_effective_network_metadata() { + let lqos_directory = unique_temp_dir("lqos-config-topology-effective-generation-missing"); + write_required_inputs(&lqos_directory); + let config = Config { + lqos_directory: lqos_directory.to_string_lossy().to_string(), + state_directory: None, + ..Config::default() + }; + let source_generation = + compute_topology_source_generation(&config).expect("source generation should compute"); + let mut shaping_inputs = TopologyShapingInputsFile { + schema_version: 1, + generated_unix: Some(1), + circuits: vec![TopologyShapingCircuitInput { + circuit_id: "circuit-1".to_string(), + effective_parent_node_name: "Tower 1".to_string(), + effective_parent_node_id: "tower-1".to_string(), + ..TopologyShapingCircuitInput::default() + }], + ..TopologyShapingInputsFile::default() + }; + shaping_inputs.shaping_generation = shaping_inputs + .compute_shaping_generation() + .expect("shaping generation should compute"); + shaping_inputs + .save(&config) + .expect("shaping inputs should save"); + TopologyRuntimeStatusFile { + schema_version: 1, + source_generation, + shaping_generation: shaping_inputs.shaping_generation, + ready: true, + shaping_inputs_path: super::topology_shaping_inputs_path(&config) + .to_string_lossy() + .to_string(), + ..TopologyRuntimeStatusFile::default() + } + .save(&config) + .expect("status should save"); + + assert!( + load_active_runtime_shaping_inputs(&config) + .expect("active shaping inputs should check") + .is_none() + ); } #[test] diff --git a/src/rust/lqos_python/src/lib.rs b/src/rust/lqos_python/src/lib.rs index 0a966822..5daa7c55 100644 --- a/src/rust/lqos_python/src/lib.rs +++ b/src/rust/lqos_python/src/lib.rs @@ -1082,6 +1082,9 @@ fn liblqos_python(m: &Bound<'_, PyModule>) -> PyResult<()> { m.add_function(wrap_pyfunction!(client_bandwidth_multiplier, m)?)?; m.add_function(wrap_pyfunction!(calculate_hash, m)?)?; m.add_function(wrap_pyfunction!(calculate_topology_source_generation, m)?)?; + m.add_function(wrap_pyfunction!(validated_runtime_shaping_inputs_path, m)?)?; + m.add_function(wrap_pyfunction!(calculate_shaping_inputs_generation, m)?)?; + m.add_function(wrap_pyfunction!(calculate_effective_network_generation, m)?)?; m.add_function(wrap_pyfunction!(calculate_shaping_runtime_hash, m)?)?; m.add_function(wrap_pyfunction!(scheduler_progress, m)?)?; m.add_function(wrap_pyfunction!(scheduler_alive, m)?)?; @@ -3142,6 +3145,38 @@ fn calculate_topology_source_generation() -> PyResult> { } } +#[pyfunction] +fn validated_runtime_shaping_inputs_path() -> PyResult> { + let Ok(config) = lqos_config::load_config() else { + return Ok(None); + }; + lqos_config::validated_runtime_shaping_inputs_path(config.as_ref()) + .map(|path| path.map(|path| path.to_string_lossy().to_string())) + .map_err(|err| { + PyOSError::new_err(format!( + "Unable to validate runtime shaping inputs path: {err}" + )) + }) +} + +#[pyfunction] +fn calculate_shaping_inputs_generation(path: String) -> PyResult { + lqos_config::compute_shaping_inputs_file_generation(Path::new(&path)).map_err(|err| { + PyOSError::new_err(format!( + "Unable to compute shaping inputs generation for {path}: {err}" + )) + }) +} + +#[pyfunction] +fn calculate_effective_network_generation(path: String) -> PyResult { + lqos_config::compute_effective_network_file_generation(Path::new(&path)).map_err(|err| { + PyOSError::new_err(format!( + "Unable to compute effective network generation for {path}: {err}" + )) + }) +} + fn shaping_runtime_sqm_fingerprint() -> Result { let config = lqos_config::load_config()?; let apply_stormguard = config diff --git a/src/rust/lqos_topology/src/lib.rs b/src/rust/lqos_topology/src/lib.rs index cffbd1f8..649fd2a3 100644 --- a/src/rust/lqos_topology/src/lib.rs +++ b/src/rust/lqos_topology/src/lib.rs @@ -16,8 +16,8 @@ use lqos_config::{ TopologyRuntimeStatusFile, TopologyShapingCircuitInput, TopologyShapingDeviceInput, TopologyShapingInputsFile, TopologyShapingResolutionSource, circuit_anchors_path, compute_effective_network_generation, detect_shaping_cpus, plan_top_level_assignments, - topology_effective_network_path, topology_effective_state_path, topology_runtime_status_path, - topology_auto_attachment_option, topology_shaping_inputs_path, + topology_auto_attachment_option, topology_effective_network_path, + topology_effective_state_path, topology_runtime_status_path, topology_shaping_inputs_path, }; use lqos_overrides::{ CircuitAdjustment, NetworkAdjustment, OverrideStore, TopologyAttachmentMode, diff --git a/src/rust/lqos_topology/src/publish.rs b/src/rust/lqos_topology/src/publish.rs index dfe3c504..8e3e9125 100644 --- a/src/rust/lqos_topology/src/publish.rs +++ b/src/rust/lqos_topology/src/publish.rs @@ -127,8 +127,8 @@ pub fn publish_effective_topology_artifacts( source_generation, None, effective_generation.as_deref(), - true, - None, + false, + Some("Topology runtime did not produce shaping inputs.".to_string()), )?; } } diff --git a/src/rust/lqos_topology/src/tests/group_01.rs b/src/rust/lqos_topology/src/tests/group_01.rs index 7ea53bc8..5c95a7b9 100644 --- a/src/rust/lqos_topology/src/tests/group_01.rs +++ b/src/rust/lqos_topology/src/tests/group_01.rs @@ -590,6 +590,42 @@ } + #[test] + fn publish_marks_runtime_not_ready_when_shaping_inputs_are_absent() { + let lqos_directory = unique_temp_dir("lqos-topology-publish-no-shaping-inputs"); + let config = Config { + lqos_directory: lqos_directory.to_string_lossy().to_string(), + state_directory: None, + ..Config::default() + }; + let shaping_inputs_path = topology_shaping_inputs_path(&config); + fs::create_dir_all( + shaping_inputs_path + .parent() + .expect("shaping inputs path should have a parent"), + ) + .expect("shaping state directory should exist"); + fs::write(&shaping_inputs_path, "{\"previous\":\"stale\"}\n") + .expect("stale shaping inputs should write"); + + publish_effective_topology_artifacts(&config, &sample_runtime_artifacts(), "generation-1") + .expect("runtime artifacts should publish without shaping inputs"); + + let status = TopologyRuntimeStatusFile::load(&config).expect("status should load"); + assert_eq!(status.source_generation, "generation-1"); + assert!(!status.ready); + assert!(status.shaping_generation.is_empty()); + assert!(!status.effective_generation.is_empty()); + assert_eq!( + status.error.as_deref(), + Some("Topology runtime did not produce shaping inputs.") + ); + assert!(!shaping_inputs_path.exists()); + assert!(topology_effective_state_path(&config).exists()); + assert!(topology_effective_network_path(&config).exists()); + } + + #[test] fn effective_publish_lock_rejects_live_holder_without_removing_lock() { let lqos_directory = unique_temp_dir("lqos-topology-effective-publish-lock"); diff --git a/src/rust/lqos_topology/src/tests/group_02.rs b/src/rust/lqos_topology/src/tests/group_02.rs index fb0c2356..cce2a690 100644 --- a/src/rust/lqos_topology/src/tests/group_02.rs +++ b/src/rust/lqos_topology/src/tests/group_02.rs @@ -398,6 +398,100 @@ assert!(shaping_inputs.warnings.is_empty()); } + #[test] + fn manual_runtime_import_resolves_idless_legacy_parent_names() { + let lqos_directory = unique_temp_dir("lqos-topology-manual-idless-parent-resolution"); + let config = Config { + lqos_directory: lqos_directory.to_string_lossy().to_string(), + state_directory: None, + ..Config::default() + }; + fs::write( + lqos_directory.join("network.json"), + serde_json::to_string_pretty(&json!({ + "Globe": { + "children": {}, + "type": "Site", + "downloadBandwidthMbps": 500, + "uploadBandwidthMbps": 500 + }, + "PLDT": { + "children": {}, + "type": "Site", + "downloadBandwidthMbps": 500, + "uploadBandwidthMbps": 500 + } + })) + .expect("network json should serialize"), + ) + .expect("network.json should write"); + 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", + "\"globe-1\",\"Globe 1\",\"device-1\",\"Radio 1\",\"Globe\",\"\",\"\",\"aa:bb:cc:dd:ee:01\",\"192.0.2.10/32\",\"\",\"10\",\"10\",\"100\",\"100\",\"\"\n", + "\"pldt-1\",\"PLDT 1\",\"device-2\",\"Radio 2\",\"PLDT\",\"\",\"\",\"aa:bb:cc:dd:ee:02\",\"192.0.2.11/32\",\"\",\"10\",\"10\",\"100\",\"100\",\"\"\n", + ), + ) + .expect("ShapedDevices.csv should write"); + + let canonical = TopologyCanonicalStateFile::load_with_legacy_fallback(&config) + .expect("manual runtime should import network.json"); + let globe_id = canonical + .nodes + .iter() + .find(|node| node.node_name == "Globe") + .expect("Globe should be imported") + .node_id + .clone(); + let pldt_id = canonical + .nodes + .iter() + .find(|node| node.node_name == "PLDT") + .expect("PLDT should be imported") + .node_id + .clone(); + let artifacts = build_effective_topology_artifacts_from_canonical( + &config, + &canonical, + &TopologyOverridesFile::default(), + &TopologyAttachmentHealthStateFile::default(), + ) + .expect("manual idless topology should publish"); + let shaping_inputs = build_shaping_inputs(&config, &artifacts) + .expect("shaping inputs should build") + .expect("shaping inputs should exist"); + + assert!( + shaping_inputs + .warnings + .iter() + .all(|warning| !warning.contains("unresolved in runtime topology")) + ); + let globe = shaping_inputs + .circuits + .iter() + .find(|circuit| circuit.circuit_id == "globe-1") + .expect("Globe circuit should exist"); + assert_eq!(globe.effective_parent_node_name, "Globe"); + assert_eq!(globe.effective_parent_node_id, globe_id); + assert_eq!( + globe.resolution_source, + TopologyShapingResolutionSource::LegacyParent + ); + let pldt = shaping_inputs + .circuits + .iter() + .find(|circuit| circuit.circuit_id == "pldt-1") + .expect("PLDT circuit should exist"); + assert_eq!(pldt.effective_parent_node_name, "PLDT"); + assert_eq!(pldt.effective_parent_node_id, pldt_id); + assert_eq!( + pldt.resolution_source, + TopologyShapingResolutionSource::LegacyParent + ); + } + #[test] fn shaping_inputs_skip_virtual_effective_nodes_when_resolving_physical_parent() { diff --git a/src/rust/lqos_topology/src/tests/helpers.rs b/src/rust/lqos_topology/src/tests/helpers.rs index 1543731f..625573ab 100644 --- a/src/rust/lqos_topology/src/tests/helpers.rs +++ b/src/rust/lqos_topology/src/tests/helpers.rs @@ -18,8 +18,9 @@ TopologyCanonicalRateInputSource, TopologyCanonicalStateFile, TopologyEditorNode, TopologyEditorStateFile, TopologyEffectiveAttachmentState, TopologyEffectiveNodeState, TopologyEffectiveStateFile, TopologyQueueVisibilityPolicy, TopologyRuntimeStatusFile, - topology_auto_attachment_option as auto_attachment_option, topology_effective_network_path, - topology_effective_state_path, topology_runtime_status_path, topology_shaping_inputs_path, + TopologyShapingResolutionSource, topology_auto_attachment_option as auto_attachment_option, + topology_effective_network_path, topology_effective_state_path, topology_runtime_status_path, + topology_shaping_inputs_path, }; use lqos_overrides::{TopologyAttachmentMode, TopologyOverridesFile}; use serde_json::{Value, json}; diff --git a/src/scheduler.py b/src/scheduler.py index 9f3b0d62..f0ccbd33 100644 --- a/src/scheduler.py +++ b/src/scheduler.py @@ -13,7 +13,7 @@ from liblqos_python import automatic_import_uisp, automatic_import_splynx, queue automatic_import_powercode, automatic_import_sonar, influx_db_enabled, get_libreqos_directory, \ blackboard_finish, blackboard_submit, automatic_import_wispgate, enable_insight_topology, insight_topology_role, \ automatic_import_netzur, automatic_import_visp, calculate_shaping_runtime_hash, efficiency_core_ids, scheduler_alive as _scheduler_alive_native, scheduler_error as _scheduler_error_native, \ - calculate_topology_source_generation, topology_import_ingress_enabled, \ + calculate_topology_source_generation, calculate_shaping_inputs_generation, calculate_effective_network_generation, topology_import_ingress_enabled, \ scheduler_progress as _scheduler_progress_native, overrides_network_adjustments_materialized, \ overrides_materialized, \ scheduler_output as _scheduler_output_native, wait_for_bus_ready @@ -1271,6 +1271,68 @@ def topology_runtime_readiness_detail(): current_generation, ) + effective_generation = str(status.get("effective_generation") or "").strip() + effective_network_path = str(status.get("effective_network_path") or "").strip() + if not effective_network_path: + return ( + False, + "Topology runtime did not publish an effective network path for the current source generation.", + current_generation, + ) + if not os.path.isfile(effective_network_path): + return ( + False, + f"Topology runtime effective network is not available at {effective_network_path}.", + current_generation, + ) + if not effective_generation: + return ( + False, + "Topology runtime did not publish an effective network generation for the current source generation.", + current_generation, + ) + try: + computed_effective_generation = calculate_effective_network_generation(effective_network_path) + except Exception as e: + return ( + False, + f"Topology runtime effective network generation could not be verified: {e}", + current_generation, + ) + if computed_effective_generation is None: + return ( + False, + "Topology runtime effective network generation could not be verified.", + current_generation, + ) + if str(computed_effective_generation).strip() != effective_generation: + return ( + False, + "Topology runtime effective network does not match the published runtime generation.", + current_generation, + ) + + try: + computed_shaping_generation = calculate_shaping_inputs_generation(shaping_inputs_path) + except Exception as e: + return ( + False, + f"Topology runtime shaping inputs generation could not be verified: {e}", + current_generation, + ) + if computed_shaping_generation is None: + return ( + False, + "Topology runtime shaping inputs generation could not be verified.", + current_generation, + ) + if str(computed_shaping_generation).strip() != shaping_generation: + return ( + False, + "Topology runtime shaping inputs do not match the published runtime generation.", + current_generation, + ) + return (True, "", current_generation) diff --git a/src/test_libreqos_shaping_inputs.py b/src/test_libreqos_shaping_inputs.py index e56d5998..5a0f2b37 100644 --- a/src/test_libreqos_shaping_inputs.py +++ b/src/test_libreqos_shaping_inputs.py @@ -4,7 +4,6 @@ import json import os import sys import tempfile -import time import types import unittest from unittest.mock import patch @@ -72,6 +71,9 @@ def install_libreqos_stubs(): lqlib.automatic_import_visp = lambda: False lqlib.topology_import_ingress_enabled = lambda: False lqlib.calculate_topology_source_generation = lambda: "test-generation" + lqlib.validated_runtime_shaping_inputs_path = lambda: None + lqlib.calculate_shaping_inputs_generation = lambda _path: "shape-1" + lqlib.calculate_effective_network_generation = lambda _path: "effective-1" lqlib.plan_top_level_cpu_bins = lambda *_args, **_kwargs: {} lqlib.plan_class_identities = lambda *_args, **_kwargs: {} lqlib.fast_queues_fq_codel = lambda: False @@ -199,130 +201,51 @@ class TestLibreQoSShapingInputs(unittest.TestCase): }, ) - def test_shaping_inputs_freshness_tracks_circuit_anchors(self): + def test_shaping_inputs_freshness_requires_active_runtime_path(self): with tempfile.TemporaryDirectory() as temp_dir: shaping_inputs = os.path.join(temp_dir, "shaping_inputs.json") - shaped_devices = os.path.join(temp_dir, "ShapedDevices.csv") - network_json = os.path.join(temp_dir, "network.json") - circuit_anchors = os.path.join(temp_dir, "circuit_anchors.json") - - for path in (shaping_inputs, shaped_devices, network_json, circuit_anchors): - with open(path, "w", encoding="utf-8") as handle: - handle.write("{}\n") - - now = time.time() - os.utime(shaped_devices, (now - 20, now - 20)) - os.utime(network_json, (now - 20, now - 20)) - os.utime(shaping_inputs, (now - 10, now - 10)) - os.utime(circuit_anchors, (now - 5, now - 5)) - - self.assertFalse( - LibreQoS._shaping_inputs_are_fresh( - shaping_inputs, shaped_devices, network_json, circuit_anchors - ) - ) + with open(shaping_inputs, "w", encoding="utf-8") as handle: + handle.write("{}\n") - def test_shaping_inputs_freshness_accepts_ready_topology_runtime_status(self): + self.assertFalse(LibreQoS._runtime_shaping_inputs_are_validated(shaping_inputs)) + + def test_shaping_inputs_freshness_accepts_matching_active_runtime_path(self): with tempfile.TemporaryDirectory() as temp_dir: shaping_inputs = os.path.join(temp_dir, "shaping_inputs.json") - shaped_devices = os.path.join(temp_dir, "ShapedDevices.csv") - network_json = os.path.join(temp_dir, "network.effective.json") - topology_state = os.path.join(temp_dir, "state", "topology") - os.makedirs(topology_state, exist_ok=True) - status_path = os.path.join(topology_state, "topology_runtime_status.json") - - for path in (shaping_inputs, shaped_devices, network_json): - with open(path, "w", encoding="utf-8") as handle: - handle.write("{}\n") - - now = time.time() - os.utime(shaped_devices, (now - 20, now - 20)) - os.utime(shaping_inputs, (now - 10, now - 10)) - os.utime(network_json, (now - 5, now - 5)) - - with open(status_path, "w", encoding="utf-8") as handle: - json.dump( - { - "source_generation": "test-generation", - "shaping_generation": "shape-1", - "ready": True, - "shaping_inputs_path": shaping_inputs, - }, - handle, - ) + with open(shaping_inputs, "w", encoding="utf-8") as handle: + handle.write("{}\n") - with patch.object(LibreQoS, "get_libreqos_directory", return_value=temp_dir): - self.assertTrue( - LibreQoS._shaping_inputs_are_fresh( - shaping_inputs, shaped_devices, network_json - ) - ) + with patch.object( + LibreQoS, + "validated_runtime_shaping_inputs_path", + return_value=shaping_inputs, + ): + self.assertTrue(LibreQoS._runtime_shaping_inputs_are_validated(shaping_inputs)) - def test_shaping_inputs_freshness_rejects_stale_topology_runtime_status_generation(self): + def test_shaping_inputs_freshness_rejects_mismatched_active_runtime_path(self): with tempfile.TemporaryDirectory() as temp_dir: shaping_inputs = os.path.join(temp_dir, "shaping_inputs.json") - shaped_devices = os.path.join(temp_dir, "ShapedDevices.csv") - network_json = os.path.join(temp_dir, "network.effective.json") - topology_state = os.path.join(temp_dir, "state", "topology") - os.makedirs(topology_state, exist_ok=True) - status_path = os.path.join(topology_state, "topology_runtime_status.json") - - for path in (shaping_inputs, shaped_devices, network_json): - with open(path, "w", encoding="utf-8") as handle: - handle.write("{}\n") - - now = time.time() - os.utime(shaped_devices, (now - 20, now - 20)) - os.utime(shaping_inputs, (now - 10, now - 10)) - os.utime(network_json, (now - 5, now - 5)) - - with open(status_path, "w", encoding="utf-8") as handle: - json.dump( - { - "source_generation": "old-generation", - "shaping_generation": "shape-1", - "ready": True, - "shaping_inputs_path": shaping_inputs, - }, - handle, - ) - - with patch.object(LibreQoS, "get_libreqos_directory", return_value=temp_dir): - self.assertFalse( - LibreQoS._shaping_inputs_are_fresh( - shaping_inputs, shaped_devices, network_json - ) - ) + other_inputs = os.path.join(temp_dir, "other_shaping_inputs.json") + with open(shaping_inputs, "w", encoding="utf-8") as handle: + handle.write("{}\n") + with patch.object( + LibreQoS, + "validated_runtime_shaping_inputs_path", + return_value=other_inputs, + ): + self.assertFalse(LibreQoS._runtime_shaping_inputs_are_validated(shaping_inputs)) - def test_shaping_inputs_freshness_rejects_ready_status_without_shaping_generation(self): + def test_shaping_inputs_freshness_rejects_runtime_gate_errors(self): with tempfile.TemporaryDirectory() as temp_dir: shaping_inputs = os.path.join(temp_dir, "shaping_inputs.json") - shaped_devices = os.path.join(temp_dir, "ShapedDevices.csv") - network_json = os.path.join(temp_dir, "network.effective.json") - topology_state = os.path.join(temp_dir, "state", "topology") - os.makedirs(topology_state, exist_ok=True) - status_path = os.path.join(topology_state, "topology_runtime_status.json") - - for path in (shaping_inputs, shaped_devices, network_json): - with open(path, "w", encoding="utf-8") as handle: - handle.write("{}\n") - - with open(status_path, "w", encoding="utf-8") as handle: - json.dump( - { - "source_generation": "test-generation", - "ready": True, - "shaping_inputs_path": shaping_inputs, - }, - handle, - ) - - with patch.object(LibreQoS, "get_libreqos_directory", return_value=temp_dir): - self.assertFalse( - LibreQoS._shaping_inputs_are_fresh( - shaping_inputs, shaped_devices, network_json - ) - ) + with open(shaping_inputs, "w", encoding="utf-8") as handle: + handle.write("{}\n") + with patch.object( + LibreQoS, + "validated_runtime_shaping_inputs_path", + side_effect=OSError("bad status"), + ): + self.assertFalse(LibreQoS._runtime_shaping_inputs_are_validated(shaping_inputs)) def test_load_subscriber_circuits_accepts_diy_id_alias(self): header = [ @@ -374,27 +297,121 @@ class TestLibreQoSShapingInputs(unittest.TestCase): self.assertEqual(len(circuits), 1) self.assertEqual(circuits[0]["AnchorNodeID"], "uisp:site:site-100") - def test_load_subscriber_circuits_for_shaping_requires_runtime_artifacts_for_diy(self): - with patch.object(LibreQoS, "_shaping_inputs_are_fresh", return_value=False): - with self.assertRaises(LibreQoS.RefreshFailure): - LibreQoS.loadSubscriberCircuitsForShaping( - "/tmp/ShapedDevices.csv", # nosec B108 - "/tmp/network.json", # nosec B108 - ) + def test_load_subscriber_circuits_for_shaping_requires_runtime_artifacts_for_integration(self): + with patch.object(LibreQoS, "_runtime_shaping_inputs_are_validated", return_value=False): + with patch.object(LibreQoS, "topology_import_ingress_enabled", return_value=True): + with self.assertRaises(LibreQoS.RefreshFailure): + LibreQoS.loadSubscriberCircuitsForShaping("/tmp/ShapedDevices.csv") # nosec B108 def test_load_subscriber_circuits_for_shaping_requires_valid_runtime_payload(self): - with patch.object(LibreQoS, "_shaping_inputs_are_fresh", return_value=True): + with patch.object(LibreQoS, "_runtime_shaping_inputs_are_validated", return_value=True): with patch.object( LibreQoS, "loadSubscriberCircuitsFromShapingInputs", side_effect=ValueError("bad payload"), ): with self.assertRaises(LibreQoS.RefreshFailure): - LibreQoS.loadSubscriberCircuitsForShaping( - "/tmp/ShapedDevices.csv", # nosec B108 - "/tmp/network.json", # nosec B108 + LibreQoS.loadSubscriberCircuitsForShaping("/tmp/ShapedDevices.csv") # nosec B108 + + def test_load_subscriber_circuits_for_shaping_consumes_fresh_runtime_payload(self): + with tempfile.TemporaryDirectory() as temp_dir: + shaping_dir = os.path.join(temp_dir, "state", "shaping") + os.makedirs(shaping_dir, exist_ok=True) + shaping_inputs = os.path.join(shaping_dir, "shaping_inputs.json") + with open(shaping_inputs, "w", encoding="utf-8") as handle: + json.dump( + { + "shaping_generation": "shape-1", + "circuits": [ + { + "circuit_id": "circuit-1", + "circuit_name": "Circuit 1", + "effective_parent_node_name": "Globe", + "effective_parent_node_id": "libreqos:legacy-network-json:node:1", + "download_min_mbps": 10, + "upload_min_mbps": 10, + "download_max_mbps": 100, + "upload_max_mbps": 100, + "devices": [], + } + ], + }, + handle, + ) + + with patch.object( + LibreQoS, + "validated_runtime_shaping_inputs_path", + return_value=shaping_inputs, + ): + with patch.object( + LibreQoS, + "get_shaping_inputs_path", + return_value=shaping_inputs, + ): + circuits, missing_parents = LibreQoS.loadSubscriberCircuitsForShaping( + "/tmp/ShapedDevices.csv" # nosec B108 ) + self.assertEqual(len(circuits), 1) + self.assertEqual(circuits[0]["circuitID"], "circuit-1") + self.assertEqual(circuits[0]["ParentNode"], "Globe") + self.assertEqual(missing_parents, {}) + + def test_load_subscriber_circuits_for_shaping_falls_back_to_manual_csv(self): + with tempfile.TemporaryDirectory() as temp_dir: + shaped_devices = os.path.join(temp_dir, "ShapedDevices.csv") + with open(shaped_devices, "w", encoding="utf-8", newline="") as handle: + writer = csv.writer(handle) + writer.writerow( + [ + "Circuit ID", + "Circuit Name", + "Device ID", + "Device Name", + "Parent Node", + "MAC", + "IPv4", + "IPv6", + "Download Min Mbps", + "Upload Min Mbps", + "Download Max Mbps", + "Upload Max Mbps", + "Comment", + ] + ) + writer.writerow( + [ + "manual-1", + "Manual 1", + "device-1", + "Radio 1", + "Globe", + "aa:bb:cc:dd:ee:ff", + "192.0.2.10/32", + "", + "10", + "10", + "100", + "100", + "", + ] + ) + + with patch.object( + LibreQoS, + "validated_runtime_shaping_inputs_path", + return_value=None, + ): + circuits, missing_parents = LibreQoS.loadSubscriberCircuitsForShaping( + shaped_devices + ) + + self.assertEqual(len(circuits), 1) + self.assertEqual(circuits[0]["circuitID"], "manual-1") + self.assertEqual(circuits[0]["ParentNode"], "Globe") + self.assertEqual(missing_parents, {}) + if __name__ == "__main__": unittest.main() diff --git a/src/test_scheduler.py b/src/test_scheduler.py index 3e4528ac..c79319ec 100644 --- a/src/test_scheduler.py +++ b/src/test_scheduler.py @@ -51,6 +51,8 @@ def install_scheduler_stubs(): lqlib.calculate_hash = lambda: 0 lqlib.calculate_shaping_runtime_hash = lambda: 0 lqlib.calculate_topology_source_generation = lambda: "test-generation" + lqlib.calculate_shaping_inputs_generation = lambda _path: "shape-1" + lqlib.calculate_effective_network_generation = lambda _path: "effective-1" lqlib.topology_import_ingress_enabled = lambda: False lqlib.efficiency_core_ids = lambda: [] lqlib.scheduler_alive = Mock() @@ -952,6 +954,29 @@ class TestSchedulerLogging(unittest.TestCase): class TestTopologyRuntimeReadiness(unittest.TestCase): + def _write_ready_runtime_status(self, tempdir): + shaping_inputs = os.path.join(tempdir, "shaping_inputs.json") + effective_network = os.path.join(tempdir, "network.effective.json") + topology_state = os.path.join(tempdir, "state", "topology") + os.makedirs(topology_state, exist_ok=True) + with open(shaping_inputs, "w", encoding="utf-8") as handle: + handle.write("{}\n") + with open(effective_network, "w", encoding="utf-8") as handle: + handle.write("{}\n") + with open(os.path.join(topology_state, "topology_runtime_status.json"), "w", encoding="utf-8") as handle: + json.dump( + { + "source_generation": "generation-1", + "shaping_generation": "shape-1", + "effective_generation": "effective-1", + "shaping_inputs_path": shaping_inputs, + "effective_network_path": effective_network, + "ready": True, + }, + handle, + ) + return shaping_inputs, effective_network + def test_missing_status_is_not_ready(self): with tempfile.TemporaryDirectory() as tempdir: with patch.object(scheduler, "get_libreqos_directory", return_value=tempdir): @@ -1017,16 +1042,21 @@ class TestTopologyRuntimeReadiness(unittest.TestCase): def test_ready_true_matching_status_allows_current_generation(self): with tempfile.TemporaryDirectory() as tempdir: shaping_inputs = os.path.join(tempdir, "shaping_inputs.json") + effective_network = os.path.join(tempdir, "network.effective.json") topology_state = os.path.join(tempdir, "state", "topology") os.makedirs(topology_state, exist_ok=True) with open(shaping_inputs, "w", encoding="utf-8") as handle: handle.write("{}\n") + with open(effective_network, "w", encoding="utf-8") as handle: + handle.write("{}\n") with open(os.path.join(topology_state, "topology_runtime_status.json"), "w", encoding="utf-8") as handle: json.dump( { "source_generation": "generation-1", "shaping_generation": "shape-1", + "effective_generation": "effective-1", "shaping_inputs_path": shaping_inputs, + "effective_network_path": effective_network, "ready": True, "error": None, }, @@ -1047,14 +1077,18 @@ class TestTopologyRuntimeReadiness(unittest.TestCase): def test_ready_true_without_shaping_generation_is_not_ready(self): with tempfile.TemporaryDirectory() as tempdir: shaping_inputs = os.path.join(tempdir, "shaping_inputs.json") + effective_network = os.path.join(tempdir, "network.effective.json") topology_state = os.path.join(tempdir, "state", "topology") os.makedirs(topology_state, exist_ok=True) with open(shaping_inputs, "w", encoding="utf-8") as handle: handle.write("{}\n") + with open(effective_network, "w", encoding="utf-8") as handle: + handle.write("{}\n") with open(os.path.join(topology_state, "topology_runtime_status.json"), "w", encoding="utf-8") as handle: json.dump( { "source_generation": "generation-1", + "effective_network_path": effective_network, "shaping_inputs_path": shaping_inputs, "ready": True, }, @@ -1099,6 +1133,195 @@ class TestTopologyRuntimeReadiness(unittest.TestCase): self.assertEqual(generation, "generation-1") self.assertIn("shaping inputs are not available", detail) + def test_ready_true_with_stale_shaping_inputs_generation_is_not_ready(self): + with tempfile.TemporaryDirectory() as tempdir: + shaping_inputs = os.path.join(tempdir, "shaping_inputs.json") + effective_network = os.path.join(tempdir, "network.effective.json") + topology_state = os.path.join(tempdir, "state", "topology") + os.makedirs(topology_state, exist_ok=True) + with open(shaping_inputs, "w", encoding="utf-8") as handle: + handle.write("{}\n") + with open(effective_network, "w", encoding="utf-8") as handle: + handle.write("{}\n") + with open(os.path.join(topology_state, "topology_runtime_status.json"), "w", encoding="utf-8") as handle: + json.dump( + { + "source_generation": "generation-1", + "shaping_generation": "shape-1", + "effective_generation": "effective-1", + "shaping_inputs_path": shaping_inputs, + "effective_network_path": effective_network, + "ready": True, + }, + handle, + ) + with patch.object(scheduler, "get_libreqos_directory", return_value=tempdir): + with patch.object( + scheduler, + "calculate_topology_source_generation", + return_value="generation-1", + ): + with patch.object( + scheduler, + "calculate_shaping_inputs_generation", + return_value="shape-2", + ): + ready, detail, generation = scheduler.topology_runtime_readiness_detail() + + self.assertFalse(ready) + self.assertEqual(generation, "generation-1") + self.assertIn("do not match", detail) + + def test_ready_true_with_stale_effective_generation_is_not_ready(self): + with tempfile.TemporaryDirectory() as tempdir: + shaping_inputs = os.path.join(tempdir, "shaping_inputs.json") + effective_network = os.path.join(tempdir, "network.effective.json") + topology_state = os.path.join(tempdir, "state", "topology") + os.makedirs(topology_state, exist_ok=True) + with open(shaping_inputs, "w", encoding="utf-8") as handle: + handle.write("{}\n") + with open(effective_network, "w", encoding="utf-8") as handle: + handle.write("{}\n") + with open(os.path.join(topology_state, "topology_runtime_status.json"), "w", encoding="utf-8") as handle: + json.dump( + { + "source_generation": "generation-1", + "shaping_generation": "shape-1", + "effective_generation": "effective-1", + "shaping_inputs_path": shaping_inputs, + "effective_network_path": effective_network, + "ready": True, + }, + handle, + ) + with patch.object(scheduler, "get_libreqos_directory", return_value=tempdir): + with patch.object( + scheduler, + "calculate_topology_source_generation", + return_value="generation-1", + ): + with patch.object( + scheduler, + "calculate_effective_network_generation", + return_value="effective-2", + ): + ready, detail, generation = scheduler.topology_runtime_readiness_detail() + + self.assertFalse(ready) + self.assertEqual(generation, "generation-1") + self.assertIn("effective network does not match", detail) + + def test_ready_true_without_effective_network_path_is_not_ready(self): + with tempfile.TemporaryDirectory() as tempdir: + shaping_inputs = os.path.join(tempdir, "shaping_inputs.json") + topology_state = os.path.join(tempdir, "state", "topology") + os.makedirs(topology_state, exist_ok=True) + with open(shaping_inputs, "w", encoding="utf-8") as handle: + handle.write("{}\n") + with open(os.path.join(topology_state, "topology_runtime_status.json"), "w", encoding="utf-8") as handle: + json.dump( + { + "source_generation": "generation-1", + "shaping_generation": "shape-1", + "shaping_inputs_path": shaping_inputs, + "ready": True, + }, + handle, + ) + with patch.object(scheduler, "get_libreqos_directory", return_value=tempdir): + with patch.object( + scheduler, + "calculate_topology_source_generation", + return_value="generation-1", + ): + ready, detail, generation = scheduler.topology_runtime_readiness_detail() + + self.assertFalse(ready) + self.assertEqual(generation, "generation-1") + self.assertIn("effective network path", detail) + + def test_effective_generation_exception_is_not_ready(self): + with tempfile.TemporaryDirectory() as tempdir: + self._write_ready_runtime_status(tempdir) + with patch.object(scheduler, "get_libreqos_directory", return_value=tempdir): + with patch.object( + scheduler, + "calculate_topology_source_generation", + return_value="generation-1", + ): + with patch.object( + scheduler, + "calculate_effective_network_generation", + side_effect=OSError("bad effective network"), + ): + ready, detail, generation = scheduler.topology_runtime_readiness_detail() + + self.assertFalse(ready) + self.assertEqual(generation, "generation-1") + self.assertIn("effective network generation could not be verified", detail) + self.assertIn("bad effective network", detail) + + def test_effective_generation_none_is_not_ready(self): + with tempfile.TemporaryDirectory() as tempdir: + self._write_ready_runtime_status(tempdir) + with patch.object(scheduler, "get_libreqos_directory", return_value=tempdir): + with patch.object( + scheduler, + "calculate_topology_source_generation", + return_value="generation-1", + ): + with patch.object( + scheduler, + "calculate_effective_network_generation", + return_value=None, + ): + ready, detail, generation = scheduler.topology_runtime_readiness_detail() + + self.assertFalse(ready) + self.assertEqual(generation, "generation-1") + self.assertIn("effective network generation could not be verified", detail) + + def test_shaping_generation_exception_is_not_ready(self): + with tempfile.TemporaryDirectory() as tempdir: + self._write_ready_runtime_status(tempdir) + with patch.object(scheduler, "get_libreqos_directory", return_value=tempdir): + with patch.object( + scheduler, + "calculate_topology_source_generation", + return_value="generation-1", + ): + with patch.object( + scheduler, + "calculate_shaping_inputs_generation", + side_effect=OSError("bad shaping inputs"), + ): + ready, detail, generation = scheduler.topology_runtime_readiness_detail() + + self.assertFalse(ready) + self.assertEqual(generation, "generation-1") + self.assertIn("shaping inputs generation could not be verified", detail) + self.assertIn("bad shaping inputs", detail) + + def test_shaping_generation_none_is_not_ready(self): + with tempfile.TemporaryDirectory() as tempdir: + self._write_ready_runtime_status(tempdir) + with patch.object(scheduler, "get_libreqos_directory", return_value=tempdir): + with patch.object( + scheduler, + "calculate_topology_source_generation", + return_value="generation-1", + ): + with patch.object( + scheduler, + "calculate_shaping_inputs_generation", + return_value=None, + ): + ready, detail, generation = scheduler.topology_runtime_readiness_detail() + + self.assertFalse(ready) + self.assertEqual(generation, "generation-1") + self.assertIn("shaping inputs generation could not be verified", detail) + class TestTopologyRuntimeGating(unittest.TestCase): def setUp(self): -- knotmirror 0.0.1