From df5aacc0b65fc7868a36fcdda9ee6c504c8c75bd Mon Sep 17 00:00:00 2001 From: Robert Chacon Date: Wed, 11 Mar 2026 16:16:46 -0600 Subject: [PATCH 1/4] changes --- src/rust/Cargo.lock | 60 ++ src/rust/Cargo.toml | 1 + .../lqos_config/src/etc/v15/stormguard.rs | 18 +- .../lqos_config/src/etc/v15/top_config.rs | 8 +- src/rust/lqos_overrides/src/overrides_file.rs | 112 ++-- src/rust/lqos_python/src/lib.rs | 31 +- src/rust/lqos_stormguard/src/active_ping.rs | 1 - .../lqos_stormguard/src/adaptive_actions.rs | 47 +- src/rust/lqos_stormguard/src/config.rs | 29 +- src/rust/lqos_stormguard/src/datalog.rs | 5 +- src/rust/lqos_stormguard/src/lib.rs | 4 +- .../lqos_stormguard/src/queue_structure.rs | 7 +- src/rust/lqos_stormguard/src/site_state.rs | 95 ++- .../lqos_stormguard/src/site_state/site.rs | 16 +- src/rust/lqos_utils/Cargo.toml | 1 + src/rust/lqos_utils/src/lib.rs | 2 + src/rust/lqos_utils/src/rustls.rs | 37 ++ src/rust/lqosd/src/main.rs | 5 +- src/rust/lqosd/src/node_manager/ws/ticker.rs | 2 +- .../src/node_manager/ws/ticker/treeguard.rs | 6 +- src/rust/lqosd/src/reload_lock.rs | 1 - src/rust/lqosd/src/treeguard/actor.rs | 607 +++++++++--------- src/rust/lqosd/src/treeguard/bakery.rs | 21 +- src/rust/lqosd/src/treeguard/decisions.rs | 15 +- src/rust/lqosd/src/treeguard/overrides.rs | 28 +- src/rust/lqosd/src/treeguard/reload.rs | 2 +- src/rust/lqosd/src/treeguard/state.rs | 7 +- src/rust/lqosd/src/treeguard/status.rs | 14 +- src/rust/uisp/Cargo.toml | 1 + src/rust/uisp/src/rest.rs | 47 +- src/rust/uisp_integration/Cargo.toml | 1 + src/rust/uisp_integration/src/main.rs | 6 + 32 files changed, 705 insertions(+), 532 deletions(-) create mode 100644 src/rust/lqos_utils/src/rustls.rs diff --git a/src/rust/Cargo.lock b/src/rust/Cargo.lock index 7b74b983..2bd1d56a 100644 --- a/src/rust/Cargo.lock +++ b/src/rust/Cargo.lock @@ -205,6 +205,28 @@ version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" +[[package]] +name = "aws-lc-rs" +version = "1.15.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b7b6141e96a8c160799cc2d5adecd5cbbe5054cb8c7c4af53da0f83bb7ad256" +dependencies = [ + "aws-lc-sys", + "zeroize", +] + +[[package]] +name = "aws-lc-sys" +version = "0.37.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c34dda4df7017c8db52132f0f8a2e0f8161649d15723ed63fc00c82d0f2081a" +dependencies = [ + "cc", + "cmake", + "dunce", + "fs_extra", +] + [[package]] name = "axum" version = "0.7.9" @@ -398,6 +420,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "47b26a0954ae34af09b50f0de26458fa95369a0d478d8236d3f93082b219bd29" dependencies = [ "find-msvc-tools", + "jobserver", + "libc", "shlex", ] @@ -541,6 +565,15 @@ version = "0.7.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3e64b0cc0439b12df2fa678eae89a1c56a529fd067a9115f7827f1fffd22b32" +[[package]] +name = "cmake" +version = "0.1.57" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75443c44cd6b379beb8c5b45d85d0773baf31cce901fe7bb252f4eff3008ef7d" +dependencies = [ + "cc", +] + [[package]] name = "colorchoice" version = "1.0.4" @@ -1051,6 +1084,12 @@ dependencies = [ "zeroize", ] +[[package]] +name = "dunce" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" + [[package]] name = "either" version = "1.15.0" @@ -1204,6 +1243,12 @@ dependencies = [ "percent-encoding", ] +[[package]] +name = "fs_extra" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" + [[package]] name = "fsevent-sys" version = "4.1.0" @@ -1810,6 +1855,16 @@ version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8eaf4bc02d17cbdd7ff4c7438cafcdf7fb9a4613313ad11b4f8fefe7d3fa0130" +[[package]] +name = "jobserver" +version = "0.1.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9afb3de4395d6b3e67a780b6de64b51c978ecf11cb9a462c66be7d4ca9039d33" +dependencies = [ + "getrandom 0.3.4", + "libc", +] + [[package]] name = "js-sys" version = "0.3.85" @@ -2124,6 +2179,7 @@ dependencies = [ "nix", "notify", "num-traits", + "rustls", "serde", "serde_json", "smallvec", @@ -3180,6 +3236,7 @@ version = "0.23.36" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c665f33d38cea657d9614f766881e4d510e0eda4239891eea56b4cadcf01801b" dependencies = [ + "aws-lc-rs", "log", "once_cell", "ring", @@ -3243,6 +3300,7 @@ version = "0.103.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d7df23109aa6c1567d1c575b9952556388da57401e4ace1d15f79eedad0d8f53" dependencies = [ + "aws-lc-rs", "ring", "rustls-pki-types", "untrusted", @@ -4136,6 +4194,7 @@ dependencies = [ "allocative", "anyhow", "lqos_config", + "lqos_utils", "reqwest", "serde", "serde_json", @@ -4152,6 +4211,7 @@ dependencies = [ "lqos_bus", "lqos_config", "lqos_overrides", + "lqos_utils", "petgraph", "serde", "serde_cbor", diff --git a/src/rust/Cargo.toml b/src/rust/Cargo.toml index 4096e2f8..fd2f241d 100644 --- a/src/rust/Cargo.toml +++ b/src/rust/Cargo.toml @@ -61,6 +61,7 @@ zerocopy = {version = "0.8.5", features = [ "derive", "zerocopy-derive", "simd" sysinfo = { version = "0", default-features = false, features = [ "system" ] } default-net = "0" reqwest = { version = "0.13", default-features = false, features = ["blocking", "json", "rustls-no-provider", "charset", "http2", "system-proxy"] } +rustls = "0.23" pyo3 = "0.25.1" colored = "2" miniz_oxide = "0.8" diff --git a/src/rust/lqos_config/src/etc/v15/stormguard.rs b/src/rust/lqos_config/src/etc/v15/stormguard.rs index abff45c5..a55bd8b0 100644 --- a/src/rust/lqos_config/src/etc/v15/stormguard.rs +++ b/src/rust/lqos_config/src/etc/v15/stormguard.rs @@ -264,14 +264,8 @@ impl StormguardConfig { "stormguard.increase_fast_multiplier", self.increase_fast_multiplier, )?; - validate_multiplier_gt_one( - "stormguard.increase_multiplier", - self.increase_multiplier, - )?; - validate_multiplier_lt_one( - "stormguard.decrease_multiplier", - self.decrease_multiplier, - )?; + validate_multiplier_gt_one("stormguard.increase_multiplier", self.increase_multiplier)?; + validate_multiplier_lt_one("stormguard.decrease_multiplier", self.decrease_multiplier)?; validate_multiplier_lt_one( "stormguard.decrease_fast_multiplier", self.decrease_fast_multiplier, @@ -297,12 +291,14 @@ impl StormguardConfig { let sqm = self.circuit_fallback_sqm.trim().to_ascii_lowercase(); if self.circuit_fallback_enabled && !matches!(sqm.as_str(), "fq_codel" | "cake") { return Err( - "stormguard.circuit_fallback_sqm must be either 'fq_codel' or 'cake'" - .to_string(), + "stormguard.circuit_fallback_sqm must be either 'fq_codel' or 'cake'".to_string(), ); } - validate_positive_seconds("stormguard.probe_interval_seconds", self.probe_interval_seconds)?; + validate_positive_seconds( + "stormguard.probe_interval_seconds", + self.probe_interval_seconds, + )?; validate_positive("stormguard.delay_threshold_ms", self.delay_threshold_ms)?; validate_ratio_gt_one( "stormguard.delay_threshold_ratio", diff --git a/src/rust/lqos_config/src/etc/v15/top_config.rs b/src/rust/lqos_config/src/etc/v15/top_config.rs index 24f0f920..19f85bd1 100644 --- a/src/rust/lqos_config/src/etc/v15/top_config.rs +++ b/src/rust/lqos_config/src/etc/v15/top_config.rs @@ -377,9 +377,7 @@ mod test { let section_name = &trimmed[1..trimmed.len() - 1]; skip_section = sections.iter().any(|section| { section_name == *section - || section_name - .strip_prefix(&format!("{section}.")) - .is_some() + || section_name.strip_prefix(&format!("{section}.")).is_some() }); } @@ -619,8 +617,8 @@ minimum_download_percentage = 0.5 minimum_upload_percentage = 0.5 "#, ); - let cfg = Config::load_from_string(&raw) - .expect("legacy stormguard config should deserialize"); + let cfg = + Config::load_from_string(&raw).expect("legacy stormguard config should deserialize"); let stormguard = cfg.stormguard.expect("stormguard section missing"); assert!(!stormguard.all_sites); diff --git a/src/rust/lqos_overrides/src/overrides_file.rs b/src/rust/lqos_overrides/src/overrides_file.rs index 4739b6f7..58f9f5c4 100644 --- a/src/rust/lqos_overrides/src/overrides_file.rs +++ b/src/rust/lqos_overrides/src/overrides_file.rs @@ -3,9 +3,9 @@ use std::{ path::{Path, PathBuf}, }; -use serde::{Deserialize, Serialize}; use anyhow::Result; use lqos_config::ShapedDevice; +use serde::{Deserialize, Serialize}; use crate::overrides_file::file_lock::FileLock; @@ -47,9 +47,16 @@ pub enum CircuitAdjustment { min_upload_bandwidth: Option, max_upload_bandwidth: Option, }, - RemoveCircuit { circuit_id: String }, - RemoveDevice { device_id: String }, - ReparentCircuit { circuit_id: String, parent_node: String }, + RemoveCircuit { + circuit_id: String, + }, + RemoveDevice { + device_id: String, + }, + ReparentCircuit { + circuit_id: String, + parent_node: String, + }, } #[derive(Serialize, Deserialize, Clone, Debug)] @@ -118,11 +125,7 @@ fn treeguard_read_path(config: &lqos_config::Config) -> PathBuf { return canonical; } let legacy = Path::new(&config.lqos_directory).join(LEGACY_AUTOPILOT_OVERRIDES_FILE); - if legacy.exists() { - legacy - } else { - canonical - } + if legacy.exists() { legacy } else { canonical } } fn load_from_path(path: &Path) -> Result { @@ -303,7 +306,8 @@ fn merge_network_adjustments_owned( if operator_site_speed_seen.contains(name) { continue; } - let Some((download_bandwidth_mbps, upload_bandwidth_mbps)) = stormguard_site_speeds.get(name) + let Some((download_bandwidth_mbps, upload_bandwidth_mbps)) = + stormguard_site_speeds.get(name) else { continue; }; @@ -465,8 +469,7 @@ impl OverrideFile { /// Remove all devices matching `device_id`. Returns number removed. pub fn remove_persistent_shaped_device_by_device_count(&mut self, device_id: &str) -> usize { let before = self.persistent_devices.len(); - self.persistent_devices - .retain(|d| d.device_id != device_id); + self.persistent_devices.retain(|d| d.device_id != device_id); before.saturating_sub(self.persistent_devices.len()) } @@ -497,21 +500,26 @@ impl OverrideFile { upload_bandwidth_mbps: Option, ) { self.network_adjustments.retain(|adj| match adj { - NetworkAdjustment::AdjustSiteSpeed { site_name: current, .. } => current != &site_name, + NetworkAdjustment::AdjustSiteSpeed { + site_name: current, .. + } => current != &site_name, _ => true, }); - self.network_adjustments.push(NetworkAdjustment::AdjustSiteSpeed { - site_name, - download_bandwidth_mbps, - upload_bandwidth_mbps, - }); + self.network_adjustments + .push(NetworkAdjustment::AdjustSiteSpeed { + site_name, + download_bandwidth_mbps, + upload_bandwidth_mbps, + }); } /// Remove any site bandwidth overrides for `site_name`. Returns number removed. pub fn remove_site_bandwidth_override_by_name_count(&mut self, site_name: &str) -> usize { let before = self.network_adjustments.len(); self.network_adjustments.retain(|adj| match adj { - NetworkAdjustment::AdjustSiteSpeed { site_name: current, .. } => current != site_name, + NetworkAdjustment::AdjustSiteSpeed { + site_name: current, .. + } => current != site_name, _ => true, }); before.saturating_sub(self.network_adjustments.len()) @@ -523,10 +531,11 @@ impl OverrideFile { NetworkAdjustment::SetNodeVirtual { node_name: n, .. } => n != &node_name, _ => true, }); - self.network_adjustments.push(NetworkAdjustment::SetNodeVirtual { - node_name, - virtual_node, - }); + self.network_adjustments + .push(NetworkAdjustment::SetNodeVirtual { + node_name, + virtual_node, + }); } /// Remove any virtual-node overrides for `node_name`. Returns number removed. @@ -567,7 +576,11 @@ impl OverrideFile { pub fn add_uisp_route_override(&mut self, from_site: String, to_site: String, cost: u32) { let uisp = self.ensure_uisp_mut(); - uisp.route_overrides.push(UispRouteOverride { from_site, to_site, cost }); + uisp.route_overrides.push(UispRouteOverride { + from_site, + to_site, + cost, + }); } pub fn remove_uisp_route_by_index(&mut self, index: usize) -> bool { @@ -673,14 +686,18 @@ mod tests { #[test] fn effective_merge_treeguard_wins_for_persistent_devices() { let mut operator = OverrideFile::default(); - operator.add_persistent_shaped_device_return_changed(shaped_device_with_sqm("dev1", "cake")); - operator.add_persistent_shaped_device_return_changed(shaped_device_with_sqm("dev2", "cake")); + operator + .add_persistent_shaped_device_return_changed(shaped_device_with_sqm("dev1", "cake")); + operator + .add_persistent_shaped_device_return_changed(shaped_device_with_sqm("dev2", "cake")); let mut stormguard = OverrideFile::default(); - stormguard - .add_persistent_shaped_device_return_changed(shaped_device_with_sqm("dev1", "fq_codel")); - stormguard - .add_persistent_shaped_device_return_changed(shaped_device_with_sqm("dev3", "fq_codel")); + stormguard.add_persistent_shaped_device_return_changed(shaped_device_with_sqm( + "dev1", "fq_codel", + )); + stormguard.add_persistent_shaped_device_return_changed(shaped_device_with_sqm( + "dev3", "fq_codel", + )); let mut treeguard = OverrideFile::default(); treeguard @@ -692,7 +709,11 @@ mod tests { let sqm_by_id: std::collections::HashMap<&str, &str> = merged .persistent_devices .iter() - .filter_map(|d| d.sqm_override.as_deref().map(|sqm| (d.device_id.as_str(), sqm))) + .filter_map(|d| { + d.sqm_override + .as_deref() + .map(|sqm| (d.device_id.as_str(), sqm)) + }) .collect(); assert_eq!(sqm_by_id.get("dev1"), Some(&"cake")); @@ -725,20 +746,27 @@ mod tests { let merged = merge_owned_sections(operator, stormguard, treeguard); - let node_a_virtual = merged.network_adjustments().iter().find_map(|adj| match adj { - NetworkAdjustment::SetNodeVirtual { - node_name, - virtual_node, - } if node_name == "NodeA" => Some(*virtual_node), - _ => None, - }); + let node_a_virtual = merged + .network_adjustments() + .iter() + .find_map(|adj| match adj { + NetworkAdjustment::SetNodeVirtual { + node_name, + virtual_node, + } if node_name == "NodeA" => Some(*virtual_node), + _ => None, + }); assert_eq!(node_a_virtual, Some(true)); // Operator site speed should beat StormGuard; TreeGuard site speed should be ignored. - let site_speed_names: Vec<&str> = merged.network_adjustments().iter().filter_map(|adj| match adj { - NetworkAdjustment::AdjustSiteSpeed { site_name, .. } => Some(site_name.as_str()), - _ => None, - }).collect(); + let site_speed_names: Vec<&str> = merged + .network_adjustments() + .iter() + .filter_map(|adj| match adj { + NetworkAdjustment::AdjustSiteSpeed { site_name, .. } => Some(site_name.as_str()), + _ => None, + }) + .collect(); assert_eq!(site_speed_names, vec!["Site1", "Site2"]); } diff --git a/src/rust/lqos_python/src/lib.rs b/src/rust/lqos_python/src/lib.rs index fdbdaac7..70e6238e 100644 --- a/src/rust/lqos_python/src/lib.rs +++ b/src/rust/lqos_python/src/lib.rs @@ -2,6 +2,7 @@ #![allow(unsafe_op_in_unsafe_fn)] use lqos_bus::{BlackboardSystem, BusRequest, BusResponse, TcHandle, UrgentSeverity, UrgentSource}; use lqos_utils::hex_string::read_hex_string; +use lqos_utils::rustls::ensure_rustls_crypto_provider; use nix::libc::getpid; use pyo3::exceptions::PyOSError; use pyo3::prelude::*; @@ -568,6 +569,7 @@ const LOCK_FILE: &str = "/run/lqos/libreqos.lock"; /// All exported functions have to be listed here. #[pymodule] fn liblqos_python(m: &Bound<'_, PyModule>) -> PyResult<()> { + ensure_rustls_crypto_provider().map_err(|e| PyOSError::new_err(e.to_string()))?; m.add_class::()?; m.add_class::()?; m.add_class::()?; @@ -664,7 +666,10 @@ fn liblqos_python(m: &Bound<'_, PyModule>) -> PyResult<()> { m.add_function(wrap_pyfunction!(overrides_persistent_devices_effective, m)?)?; m.add_function(wrap_pyfunction!(overrides_circuit_adjustments, m)?)?; m.add_function(wrap_pyfunction!(overrides_network_adjustments, m)?)?; - m.add_function(wrap_pyfunction!(overrides_network_adjustments_effective, m)?)?; + m.add_function(wrap_pyfunction!( + overrides_network_adjustments_effective, + m + )?)?; m.add_function(wrap_pyfunction!(is_network_flat, m)?)?; m.add_function(wrap_pyfunction!(blackboard_finish, m)?)?; m.add_function(wrap_pyfunction!(blackboard_submit, m)?)?; @@ -961,13 +966,11 @@ fn overrides_persistent_devices_effective(py: Python<'_>) -> PyResult o, - Err(e) => return Err(PyOSError::new_err(e.to_string())), - }; + let overrides = + match lqos_overrides::OverrideStore::load_effective(apply_stormguard, apply_treeguard) { + Ok(o) => o, + Err(e) => return Err(PyOSError::new_err(e.to_string())), + }; let mut out: Vec = Vec::new(); for dev in overrides.persistent_devices().iter() { @@ -1143,13 +1146,11 @@ fn overrides_network_adjustments_effective(py: Python<'_>) -> PyResult o, - Err(e) => return Err(PyOSError::new_err(e.to_string())), - }; + let overrides = + match lqos_overrides::OverrideStore::load_effective(apply_stormguard, apply_treeguard) { + Ok(o) => o, + Err(e) => return Err(PyOSError::new_err(e.to_string())), + }; let mut out: Vec = Vec::new(); for adj in overrides.network_adjustments().iter() { diff --git a/src/rust/lqos_stormguard/src/active_ping.rs b/src/rust/lqos_stormguard/src/active_ping.rs index 3e0ffaf7..488c33c3 100644 --- a/src/rust/lqos_stormguard/src/active_ping.rs +++ b/src/rust/lqos_stormguard/src/active_ping.rs @@ -141,4 +141,3 @@ async fn ping_once(ip: IpAddr, timeout: Duration) -> Option { _ => None, } } - diff --git a/src/rust/lqos_stormguard/src/adaptive_actions.rs b/src/rust/lqos_stormguard/src/adaptive_actions.rs index af3cbf3a..2c07e9ce 100644 --- a/src/rust/lqos_stormguard/src/adaptive_actions.rs +++ b/src/rust/lqos_stormguard/src/adaptive_actions.rs @@ -34,10 +34,7 @@ pub fn apply_site_override_updates(updates: &[SiteOverrideUpdate]) -> Result 0 { @@ -126,7 +123,11 @@ pub fn clear_circuit_fallback( }); } - let device_ids: Vec = fallback.devices.iter().map(|d| d.device_id.clone()).collect(); + let device_ids: Vec = fallback + .devices + .iter() + .map(|d| d.device_id.clone()) + .collect(); let persisted = clear_device_overrides(&device_ids)?; apply_circuit_sqm_override_live(circuit_id, &fallback.devices, None, bakery_sender)?; Ok(CircuitFallbackOutcome::Cleared { persisted }) @@ -141,14 +142,17 @@ fn current_site_override( overrides: &OverrideFile, site_name: &str, ) -> Option<(Option, Option)> { - overrides.network_adjustments().iter().find_map(|adj| match adj { - lqos_overrides::NetworkAdjustment::AdjustSiteSpeed { - site_name: current, - download_bandwidth_mbps, - upload_bandwidth_mbps, - } if current == site_name => Some((*download_bandwidth_mbps, *upload_bandwidth_mbps)), - _ => None, - }) + overrides + .network_adjustments() + .iter() + .find_map(|adj| match adj { + lqos_overrides::NetworkAdjustment::AdjustSiteSpeed { + site_name: current, + download_bandwidth_mbps, + upload_bandwidth_mbps, + } if current == site_name => Some((*download_bandwidth_mbps, *upload_bandwidth_mbps)), + _ => None, + }) } fn load_devices_for_circuit(circuit_id: &str) -> Result> { @@ -272,7 +276,9 @@ fn apply_circuit_sqm_override_live( } let Some(node) = found else { - return Err(anyhow!("circuit not found in queue structure: {circuit_id}")); + return Err(anyhow!( + "circuit not found in queue structure: {circuit_id}" + )); }; let class_minor = u16::try_from(node.class_minor) @@ -325,12 +331,13 @@ fn group_circuit_fallbacks(devices: &[ShapedDevice]) -> HashMap, path: Option) eprintln!("Failed to create log file: {}", e); } else { // Write the header to the file - if let Err(e) = std::fs::write( - path, - "Time,Site,Download,Upload,Summary\n", - ) { + if let Err(e) = std::fs::write(path, "Time,Site,Download,Upload,Summary\n") { eprintln!("Failed to write header to log file: {}", e); } } diff --git a/src/rust/lqos_stormguard/src/lib.rs b/src/rust/lqos_stormguard/src/lib.rs index e4fa96a0..d54eba33 100644 --- a/src/rust/lqos_stormguard/src/lib.rs +++ b/src/rust/lqos_stormguard/src/lib.rs @@ -16,12 +16,12 @@ use parking_lot::Mutex; use std::time::Duration; use tracing::{debug, info}; +mod active_ping; +mod adaptive_actions; mod config; mod datalog; mod queue_structure; mod site_state; -mod adaptive_actions; -mod active_ping; const READING_ACCUMULATOR_SIZE: usize = 15; const MOVING_AVERAGE_BUFFER_SIZE: usize = 15; diff --git a/src/rust/lqos_stormguard/src/queue_structure.rs b/src/rust/lqos_stormguard/src/queue_structure.rs index 8f4d76b8..6f8b8430 100644 --- a/src/rust/lqos_stormguard/src/queue_structure.rs +++ b/src/rust/lqos_stormguard/src/queue_structure.rs @@ -40,10 +40,9 @@ pub fn find_queue_dependents(parent_name: &str) -> Result warn!("Failed to load persisted StormGuard circuit fallbacks: {}", e), + Err(e) => warn!( + "Failed to load persisted StormGuard circuit fallbacks: {}", + e + ), } for (name, site) in &self.sites { - let Some(queue) = queues.iter().find(|n| n.name.as_deref() == Some(name.as_str())) else { + let Some(queue) = queues + .iter() + .find(|n| n.name.as_deref() == Some(name.as_str())) + else { continue; }; @@ -287,7 +293,9 @@ impl SiteStateTracker { } pub fn check_state(&mut self, config: &StormguardConfig) { - self.sites.iter_mut().for_each(|(_, s)| s.check_state(config)); + self.sites + .iter_mut() + .for_each(|(_, s)| s.check_state(config)); } pub fn recommendations(&mut self, config: &StormguardConfig) -> Vec<(Recommendation, String)> { @@ -322,7 +330,9 @@ impl SiteStateTracker { }; let baseline_rtt_ms = site.rtt_baseline_ms; - let rtt_now = site.current_rtt_ms.or_else(|| site.round_trip_time.average()); + let rtt_now = site + .current_rtt_ms + .or_else(|| site.round_trip_time.average()); let delay_ms = match (rtt_now, baseline_rtt_ms) { (Some(rtt), Some(baseline)) => Some((rtt - baseline).max(0.0)), _ => None, @@ -383,12 +393,16 @@ impl SiteStateTracker { RecommendationDirection::Download => site.last_action_download, RecommendationDirection::Upload => site.last_action_upload, } - .map(|(action, at)| (Some(action_string(action).to_string()), Some(at.elapsed().as_secs_f32()))) + .map(|(action, at)| { + ( + Some(action_string(action).to_string()), + Some(at.elapsed().as_secs_f32()), + ) + }) .unwrap_or((None, None)); - let saturation_max = SaturationLevel::from_throughput( - throughput_mbps, max_mbps as f64, - ); + let saturation_max = + SaturationLevel::from_throughput(throughput_mbps, max_mbps as f64); let saturation_current = SaturationLevel::from_throughput(throughput_mbps, queue_mbps as f64); @@ -684,7 +698,10 @@ impl SiteStateTracker { "StormGuard cleared circuit fallback for {} ({})", recommendation.site, circuit_id ); - (format!("circuit_fallback=cleared persisted={persisted}"), true) + ( + format!("circuit_fallback=cleared persisted={persisted}"), + true, + ) } CircuitFallbackOutcome::DryRun { action } => { info!( @@ -703,7 +720,12 @@ impl SiteStateTracker { }; if Self::circuit_outcome_enters_cooldown(&enters_cooldown) { - Self::enter_cooldown(site, recommendation.direction, cooldown_secs, recommendation.action); + Self::enter_cooldown( + site, + recommendation.direction, + cooldown_secs, + recommendation.action, + ); } let _ = log_sender.send(LogCommand::SpeedChange { site: recommendation.site.clone(), @@ -761,28 +783,24 @@ impl SiteStateTracker { fn set_site_rate(site: &mut SiteState, direction: RecommendationDirection, new_rate: u64) { match direction { - RecommendationDirection::Download => { - site.queue_download_mbps = new_rate; - site.ticks_since_last_probe_download = 0; - let mut lock = crate::STORMGUARD_STATS.lock(); - if let Some(entry) = - lock.iter_mut().find(|(n, _, _)| n == &site.config.name) - { - entry.1 = new_rate; - } + RecommendationDirection::Download => { + site.queue_download_mbps = new_rate; + site.ticks_since_last_probe_download = 0; + let mut lock = crate::STORMGUARD_STATS.lock(); + if let Some(entry) = lock.iter_mut().find(|(n, _, _)| n == &site.config.name) { + entry.1 = new_rate; } - RecommendationDirection::Upload => { - site.queue_upload_mbps = new_rate; - site.ticks_since_last_probe_upload = 0; - let mut lock = crate::STORMGUARD_STATS.lock(); - if let Some(entry) = - lock.iter_mut().find(|(n, _, _)| n == &site.config.name) - { - entry.2 = new_rate; - } + } + RecommendationDirection::Upload => { + site.queue_upload_mbps = new_rate; + site.ticks_since_last_probe_upload = 0; + let mut lock = crate::STORMGUARD_STATS.lock(); + if let Some(entry) = lock.iter_mut().find(|(n, _, _)| n == &site.config.name) { + entry.2 = new_rate; } } } + } fn apply_dependents( site: &crate::config::WatchingSite, @@ -911,8 +929,8 @@ impl SiteStateTracker { #[cfg(test)] mod tests { use super::*; - use crate::config::WatchingSite; use crate::config::StormguardConfig as RuntimeStormguardConfig; + use crate::config::WatchingSite; use lqos_config::StormguardStrategy; use std::collections::HashMap; @@ -1043,7 +1061,10 @@ mod tests { site.recommendations(&mut recs, &cfg); assert!(recs.iter().any(|(r, _)| { r.direction == RecommendationDirection::Download - && matches!(r.action, RecommendationAction::DecreaseFast | RecommendationAction::Decrease) + && matches!( + r.action, + RecommendationAction::DecreaseFast | RecommendationAction::Decrease + ) })); } @@ -1060,7 +1081,10 @@ mod tests { site.recommendations(&mut recs, &cfg); assert!(recs.iter().any(|(r, _)| { r.direction == RecommendationDirection::Download - && matches!(r.action, RecommendationAction::Increase | RecommendationAction::IncreaseFast) + && matches!( + r.action, + RecommendationAction::Increase | RecommendationAction::IncreaseFast + ) })); } @@ -1076,7 +1100,10 @@ mod tests { site.recommendations(&mut recs, &cfg); assert!(recs.iter().any(|(r, _)| { r.direction == RecommendationDirection::Upload - && matches!(r.action, RecommendationAction::DecreaseFast | RecommendationAction::Decrease) + && matches!( + r.action, + RecommendationAction::DecreaseFast | RecommendationAction::Decrease + ) })); } } diff --git a/src/rust/lqos_stormguard/src/site_state/site.rs b/src/rust/lqos_stormguard/src/site_state/site.rs index 64fa2031..d735afa8 100644 --- a/src/rust/lqos_stormguard/src/site_state/site.rs +++ b/src/rust/lqos_stormguard/src/site_state/site.rs @@ -210,7 +210,10 @@ impl SiteState { } fn moving_averages_rtt(&mut self) { - Self::push_moving_average(&self.round_trip_time, &mut self.round_trip_time_moving_average); + Self::push_moving_average( + &self.round_trip_time, + &mut self.round_trip_time_moving_average, + ); } fn recommendation_matrix( @@ -356,7 +359,8 @@ impl SiteState { }; let saturation_max = SaturationLevel::from_throughput(throughput_mbps, max_mbps as f64); - let saturation_current = SaturationLevel::from_throughput(throughput_mbps, queue_mbps as f64); + let saturation_current = + SaturationLevel::from_throughput(throughput_mbps, queue_mbps as f64); let retransmit_state = RetransmitState::new(retransmits_ma, retransmits); let abs_retransmit = retransmits_ma.average(); let rtt_state = RttState::new(&self.round_trip_time_moving_average, &self.round_trip_time); @@ -454,8 +458,7 @@ impl SiteState { let Some(delay_ratio) = delay_ratio else { return; }; - let good_delay = - delay_ms <= good_threshold_ms && delay_ratio <= good_threshold_ratio; + let good_delay = delay_ms <= good_threshold_ms && delay_ratio <= good_threshold_ratio; let load_ratio = if queue_mbps > 0 { throughput_mbps / queue_mbps as f64 } else { @@ -480,10 +483,7 @@ impl SiteState { let summary = format!( "{direction},{action:?},queue={queue_mbps},tp={throughput_mbps:.3},retx={retransmits_avg:?},rtt={:?},baseline={:?},delay_ms={:?},delay_ratio={:?},bloat={bloat},severe={severe_bloat}", - self.current_rtt_ms, - self.rtt_baseline_ms, - delay_ms, - delay_ratio, + self.current_rtt_ms, self.rtt_baseline_ms, delay_ms, delay_ratio, ); recommendations.push(( diff --git a/src/rust/lqos_utils/Cargo.toml b/src/rust/lqos_utils/Cargo.toml index df57348a..f29a5c96 100644 --- a/src/rust/lqos_utils/Cargo.toml +++ b/src/rust/lqos_utils/Cargo.toml @@ -14,6 +14,7 @@ byteorder = { workspace = true } zerocopy = { workspace = true } num-traits = { workspace = true } crossbeam-channel = { workspace = true } +rustls = { workspace = true } smallvec = "1" serde_json.workspace = true diff --git a/src/rust/lqos_utils/src/lib.rs b/src/rust/lqos_utils/src/lib.rs index c389d22c..c7867a89 100644 --- a/src/rust/lqos_utils/src/lib.rs +++ b/src/rust/lqos_utils/src/lib.rs @@ -27,6 +27,8 @@ pub mod qoo; pub mod qoq_heatmap; /// RTT histograms and strongly-typed RTT units. pub mod rtt; +/// Helpers for initializing the process-wide Rustls crypto provider. +pub mod rustls; /// Helpers for units of measurement pub mod units; /// Utilities dealing with Unix Timestamps diff --git a/src/rust/lqos_utils/src/rustls.rs b/src/rust/lqos_utils/src/rustls.rs new file mode 100644 index 00000000..50e58547 --- /dev/null +++ b/src/rust/lqos_utils/src/rustls.rs @@ -0,0 +1,37 @@ +//! Helpers for configuring the Rustls crypto provider used by HTTPS clients. + +use std::sync::OnceLock; + +use thiserror::Error; + +/// Errors returned while initializing the process-wide Rustls crypto provider. +#[derive(Debug, Error)] +pub enum RustlsProviderError { + /// Installing the selected Rustls provider failed before one was available. + #[error("failed to install the Rustls crypto provider")] + InstallFailed, +} + +/// Ensure a process-wide Rustls crypto provider is installed. +/// +/// Side effects: +/// installs the default AWS-LC Rustls provider for the current process if one +/// has not already been installed. +pub fn ensure_rustls_crypto_provider() -> Result<(), RustlsProviderError> { + static INIT: OnceLock<()> = OnceLock::new(); + + if INIT.get().is_some() || rustls::crypto::CryptoProvider::get_default().is_some() { + let _ = INIT.get_or_init(|| ()); + return Ok(()); + } + + if rustls::crypto::aws_lc_rs::default_provider() + .install_default() + .is_err() + && rustls::crypto::CryptoProvider::get_default().is_none() + { + return Err(RustlsProviderError::InstallFailed); + } + let _ = INIT.get_or_init(|| ()); + Ok(()) +} diff --git a/src/rust/lqosd/src/main.rs b/src/rust/lqosd/src/main.rs index 54758871..8ed82470 100644 --- a/src/rust/lqosd/src/main.rs +++ b/src/rust/lqosd/src/main.rs @@ -4,7 +4,6 @@ #![deny(clippy::unwrap_used)] mod blackboard; -mod treeguard; mod file_lock; mod ip_mapping; #[cfg(feature = "equinix_tests")] @@ -23,6 +22,7 @@ mod stick; mod system_stats; mod throughput_tracker; mod tool_status; +mod treeguard; mod tuning; mod urgent; mod validation; @@ -47,6 +47,7 @@ use lqos_queue_tracker::{ add_watched_queue, get_raw_circuit_data, spawn_queue_monitor, spawn_queue_structure_monitor, }; use lqos_sys::LibreQoSKernels; +use lqos_utils::rustls::ensure_rustls_crypto_provider; use signal_hook::{ consts::{SIGHUP, SIGINT, SIGTERM}, iterator::Signals, @@ -188,6 +189,8 @@ fn main() -> Result<()> { let config = lqos_config::load_config()?; let stick_offset = stick::recompute_stick_offset(&config)?; + ensure_rustls_crypto_provider()?; + if let Err(e) = lts2_sys::license_grant::init_license_storage(&config) { warn!("Failed to initialize Insight license storage: {e:?}"); } diff --git a/src/rust/lqosd/src/node_manager/ws/ticker.rs b/src/rust/lqosd/src/node_manager/ws/ticker.rs index 0f4f0dc9..09e0003f 100644 --- a/src/rust/lqosd/src/node_manager/ws/ticker.rs +++ b/src/rust/lqosd/src/node_manager/ws/ticker.rs @@ -22,7 +22,6 @@ mod queue_stats_total; mod retransmits; mod rtt_histogram; mod stormguard; -mod treeguard; pub mod system_info; mod throughput; mod top_10; @@ -30,6 +29,7 @@ mod top_flows; mod tree_capacity; mod tree_summary; mod tree_summary_l2; +mod treeguard; use crate::system_stats::SystemStats; pub use network_tree::all_circuits; diff --git a/src/rust/lqosd/src/node_manager/ws/ticker/treeguard.rs b/src/rust/lqosd/src/node_manager/ws/ticker/treeguard.rs index 12b841b3..4faf4275 100644 --- a/src/rust/lqosd/src/node_manager/ws/ticker/treeguard.rs +++ b/src/rust/lqosd/src/node_manager/ws/ticker/treeguard.rs @@ -1,7 +1,7 @@ -use crate::treeguard::status::{treeguard_activity_snapshot, treeguard_status_snapshot}; use crate::node_manager::ws::messages::WsResponse; use crate::node_manager::ws::publish_subscribe::PubSub; use crate::node_manager::ws::published_channels::PublishedChannels; +use crate::treeguard::status::{treeguard_activity_snapshot, treeguard_status_snapshot}; use std::sync::Arc; pub async fn treeguard_status(pubsub: Arc) { @@ -27,7 +27,5 @@ pub async fn treeguard_activity(pubsub: Arc) { let data = treeguard_activity_snapshot().await; let msg = WsResponse::TreeGuardActivity { data }; - pubsub - .send(PublishedChannels::TreeGuardActivity, msg) - .await; + pubsub.send(PublishedChannels::TreeGuardActivity, msg).await; } diff --git a/src/rust/lqosd/src/reload_lock.rs b/src/rust/lqosd/src/reload_lock.rs index fb1ee5a2..2596422a 100644 --- a/src/rust/lqosd/src/reload_lock.rs +++ b/src/rust/lqosd/src/reload_lock.rs @@ -34,4 +34,3 @@ pub(crate) fn try_reload_libreqos_locked() -> ReloadExecOutcome { Err(e) => ReloadExecOutcome::Failed(e.to_string()), } } - diff --git a/src/rust/lqosd/src/treeguard/actor.rs b/src/rust/lqosd/src/treeguard/actor.rs index 6156b67d..01970f56 100644 --- a/src/rust/lqosd/src/treeguard/actor.rs +++ b/src/rust/lqosd/src/treeguard/actor.rs @@ -4,16 +4,16 @@ //! and applying (or dry-running) any decisions. use crate::node_manager::ws::messages::{TreeguardActivityEntry, TreeguardStatusData}; +use crate::shaped_devices_tracker::{NETWORK_JSON, SHAPED_DEVICES}; +use crate::system_stats::SystemStats; +use crate::throughput_tracker::{CIRCUIT_RTT_BUFFERS, THROUGHPUT_TRACKER}; use crate::treeguard::TreeguardError; use crate::treeguard::reload::{ReloadController, ReloadOutcome, ReloadPriority}; use crate::treeguard::state::{ - is_sustained_idle, is_sustained_window, CircuitSqmState, CircuitState, LinkState, - LinkVirtualState, + CircuitSqmState, CircuitState, LinkState, LinkVirtualState, is_sustained_idle, + is_sustained_window, }; use crate::treeguard::{bakery, decisions, overrides}; -use crate::shaped_devices_tracker::{NETWORK_JSON, SHAPED_DEVICES}; -use crate::system_stats::SystemStats; -use crate::throughput_tracker::{CIRCUIT_RTT_BUFFERS, THROUGHPUT_TRACKER}; use crate::urgent; use crossbeam_channel::{Receiver, Sender}; use fxhash::{FxHashMap, FxHashSet}; @@ -353,9 +353,7 @@ fn run_tick( o.network_adjustments() .iter() .filter_map(|adj| match adj { - NetworkAdjustment::SetNodeVirtual { node_name, .. } => { - Some(node_name.clone()) - } + NetworkAdjustment::SetNodeVirtual { node_name, .. } => Some(node_name.clone()), _ => None, }) .collect() @@ -388,9 +386,7 @@ fn run_tick( .network_adjustments() .iter() .filter_map(|adj| match adj { - NetworkAdjustment::SetNodeVirtual { node_name, .. } => { - Some(node_name.clone()) - } + NetworkAdjustment::SetNodeVirtual { node_name, .. } => Some(node_name.clone()), _ => None, }) .collect(), @@ -599,21 +595,19 @@ fn run_tick( let util_down_pct = (mbps_down / cap_down) * 100.0; let util_up_pct = (mbps_up / cap_up) * 100.0; - let state = link_states - .entry(node_name.to_string()) - .or_insert_with(|| { - let mut state = LinkState::default(); - if let Some(overrides) = treeguard_overrides_snapshot.as_ref() { - if let Some(v) = overrides_node_virtual(overrides, node_name) { - state.desired = if v { - LinkVirtualState::Virtual - } else { - LinkVirtualState::Physical - }; - } + let state = link_states.entry(node_name.to_string()).or_insert_with(|| { + let mut state = LinkState::default(); + if let Some(overrides) = treeguard_overrides_snapshot.as_ref() { + if let Some(v) = overrides_node_virtual(overrides, node_name) { + state.desired = if v { + LinkVirtualState::Virtual + } else { + LinkVirtualState::Physical + }; } - state - }); + } + state + }); prune_recent_changes(&mut state.recent_changes_unix, now_unix); let ewma_down = state @@ -698,8 +692,7 @@ fn run_tick( }; let decision = if is_top_level { - let dwell_secs = - u64::from(tg.links.min_state_dwell_minutes).saturating_mul(60); + let dwell_secs = u64::from(tg.links.min_state_dwell_minutes).saturating_mul(60); let in_dwell_window = state .last_change_unix .is_some_and(|last| now_unix.saturating_sub(last) < dwell_secs); @@ -866,15 +859,15 @@ fn run_tick( "TreeGuard links: node '{node_name}' has an operator virtual override; TreeGuard will not manage it." )); match overrides::clear_node_virtual(node_name) { - Ok(changed) => { - if changed { - reload_controller.request_reload( + Ok(changed) => { + if changed { + reload_controller.request_reload( ReloadPriority::Normal, format!( "Cleared virtual override for node '{node_name}' due to operator conflict" ), ); - push_activity( + push_activity( activity, TreeguardActivityEntry { time: now_unix.to_string(), @@ -885,57 +878,55 @@ fn run_tick( reason: "Operator override present; TreeGuard will not manage this node.".to_string(), }, ); + } } - } - Err(e) => { - status.warnings.push(format!( + Err(e) => { + status.warnings.push(format!( "TreeGuard links: failed to clear virtual override for node '{node_name}' during conflict cleanup: {e}" )); + } } + managed_nodes.remove(node_name); + link_states.remove(node_name); + continue; } - managed_nodes.remove(node_name); - link_states.remove(node_name); - continue; - } - let Some(index) = reader.get_index_for_name(node_name) else { - status.warnings.push(format!( - "TreeGuard links allowlist: node '{node_name}' not found in network.json." - )); - continue; - }; - let Some(node) = reader.get_nodes_when_ready().get(index) else { - status.warnings.push(format!( - "TreeGuard links allowlist: node '{node_name}' index not present." - )); - continue; - }; + let Some(index) = reader.get_index_for_name(node_name) else { + status.warnings.push(format!( + "TreeGuard links allowlist: node '{node_name}' not found in network.json." + )); + continue; + }; + let Some(node) = reader.get_nodes_when_ready().get(index) else { + status.warnings.push(format!( + "TreeGuard links allowlist: node '{node_name}' index not present." + )); + continue; + }; - if node.virtual_node { - status.warnings.push(format!( + if node.virtual_node { + status.warnings.push(format!( "TreeGuard links: node '{node_name}' is marked virtual in base network.json; TreeGuard will not manage it." )); - continue; - } + continue; + } - let cap_down = node.max_throughput.0; - let cap_up = node.max_throughput.1; - if cap_down <= 0.0 || cap_up <= 0.0 { - status.warnings.push(format!( + let cap_down = node.max_throughput.0; + let cap_up = node.max_throughput.1; + if cap_down <= 0.0 || cap_up <= 0.0 { + status.warnings.push(format!( "TreeGuard links: node '{node_name}' has unknown capacity; no changes will be made." )); - continue; - } + continue; + } - let bytes_down = node.current_throughput.get_down() as f64; - let bytes_up = node.current_throughput.get_up() as f64; - let mbps_down = (bytes_down * 8.0) / 1_000_000.0; - let mbps_up = (bytes_up * 8.0) / 1_000_000.0; - let util_down_pct = (mbps_down / cap_down) * 100.0; - let util_up_pct = (mbps_up / cap_up) * 100.0; + let bytes_down = node.current_throughput.get_down() as f64; + let bytes_up = node.current_throughput.get_up() as f64; + let mbps_down = (bytes_down * 8.0) / 1_000_000.0; + let mbps_up = (bytes_up * 8.0) / 1_000_000.0; + let util_down_pct = (mbps_down / cap_down) * 100.0; + let util_up_pct = (mbps_up / cap_up) * 100.0; - let state = link_states - .entry(node_name.clone()) - .or_insert_with(|| { + let state = link_states.entry(node_name.clone()).or_insert_with(|| { let mut state = LinkState::default(); if let Some(overrides) = treeguard_overrides_snapshot.as_ref() { if let Some(v) = overrides_node_virtual(overrides, node_name) { @@ -948,243 +939,244 @@ fn run_tick( } state }); - prune_recent_changes(&mut state.recent_changes_unix, now_unix); - - let ewma_down = state - .down - .util_ewma_pct - .update(util_down_pct, UTIL_EWMA_ALPHA); - let ewma_up = state.up.util_ewma_pct.update(util_up_pct, UTIL_EWMA_ALPHA); - - // Per-direction idle tracking (sustained-idle is evaluated across both directions). - update_idle_since( - &mut state.down.idle_since_unix, - now_unix, - ewma_down, - tg.links.idle_util_pct as f64, - ); - update_idle_since( - &mut state.up.idle_since_unix, - now_unix, - ewma_up, - tg.links.idle_util_pct as f64, - ); + prune_recent_changes(&mut state.recent_changes_unix, now_unix); - let sustained_idle = is_sustained_idle( - now_unix, - state.down.idle_since_unix, - state.up.idle_since_unix, - tg.links.idle_min_minutes, - ); + let ewma_down = state + .down + .util_ewma_pct + .update(util_down_pct, UTIL_EWMA_ALPHA); + let ewma_up = state.up.util_ewma_pct.update(util_up_pct, UTIL_EWMA_ALPHA); - let is_top_level = top_level_auto_virtualize && node.immediate_parent == Some(0); - let top_level_safe_util_pct = - tg.links.top_level_safe_util_pct.clamp(0.0, 100.0) as f64; - if is_top_level { - update_below_since( - &mut state.down.top_level_safe_since_unix, + // Per-direction idle tracking (sustained-idle is evaluated across both directions). + update_idle_since( + &mut state.down.idle_since_unix, now_unix, ewma_down, - top_level_safe_util_pct, + tg.links.idle_util_pct as f64, ); - update_below_since( - &mut state.up.top_level_safe_since_unix, + update_idle_since( + &mut state.up.idle_since_unix, now_unix, ewma_up, - top_level_safe_util_pct, + tg.links.idle_util_pct as f64, ); - } - let rtt_missing = match now_nanos_since_boot { - None => true, - Some(now_nanos) => { - if node.rtt_buffer.last_seen == 0 { - true - } else { - let age_nanos = now_nanos.saturating_sub(node.rtt_buffer.last_seen); - age_nanos - >= u64::from(tg.links.rtt_missing_seconds) - .saturating_mul(1_000_000_000) - } + let sustained_idle = is_sustained_idle( + now_unix, + state.down.idle_since_unix, + state.up.idle_since_unix, + tg.links.idle_min_minutes, + ); + + let is_top_level = top_level_auto_virtualize && node.immediate_parent == Some(0); + let top_level_safe_util_pct = + tg.links.top_level_safe_util_pct.clamp(0.0, 100.0) as f64; + if is_top_level { + update_below_since( + &mut state.down.top_level_safe_since_unix, + now_unix, + ewma_down, + top_level_safe_util_pct, + ); + update_below_since( + &mut state.up.top_level_safe_since_unix, + now_unix, + ewma_up, + top_level_safe_util_pct, + ); } - }; - // QoO (when available) from the node heatmap blocks (latest non-None sample). - let qoo = node - .qoq_heatmap - .as_ref() - .map(|heatmap| { - let blocks = heatmap.blocks(); - let latest = |values: &[Option]| values.iter().rev().find_map(|v| *v); - DownUpOrder { - down: latest(&blocks.download_total), - up: latest(&blocks.upload_total), + let rtt_missing = match now_nanos_since_boot { + None => true, + Some(now_nanos) => { + if node.rtt_buffer.last_seen == 0 { + true + } else { + let age_nanos = now_nanos.saturating_sub(node.rtt_buffer.last_seen); + age_nanos + >= u64::from(tg.links.rtt_missing_seconds) + .saturating_mul(1_000_000_000) + } } - }) - .unwrap_or(DownUpOrder { - down: None, - up: None, - }); + }; - let util_ewma_pct = DownUpOrder { - down: ewma_down, - up: ewma_up, - }; + // QoO (when available) from the node heatmap blocks (latest non-None sample). + let qoo = node + .qoq_heatmap + .as_ref() + .map(|heatmap| { + let blocks = heatmap.blocks(); + let latest = |values: &[Option]| values.iter().rev().find_map(|v| *v); + DownUpOrder { + down: latest(&blocks.download_total), + up: latest(&blocks.upload_total), + } + }) + .unwrap_or(DownUpOrder { + down: None, + up: None, + }); - let decision = if is_top_level { - let dwell_secs = u64::from(tg.links.min_state_dwell_minutes).saturating_mul(60); - let in_dwell_window = state - .last_change_unix - .is_some_and(|last| now_unix.saturating_sub(last) < dwell_secs); - let rate_limited = if tg.links.max_link_changes_per_hour == 0 { - true - } else { - state.recent_changes_unix.len() >= tg.links.max_link_changes_per_hour as usize + let util_ewma_pct = DownUpOrder { + down: ewma_down, + up: ewma_up, }; - if in_dwell_window || rate_limited { - decisions::LinkVirtualDecision::NoChange - } else { - let sustained_safe = is_sustained_window( - now_unix, - state.down.top_level_safe_since_unix, - state.up.top_level_safe_since_unix, - TOP_LEVEL_SAFE_SUSTAIN_MINUTES, - ); - let util_high = util_ewma_pct.down >= top_level_safe_util_pct - || util_ewma_pct.up >= top_level_safe_util_pct; - match state.desired { - LinkVirtualState::Physical => { - if sustained_safe { - decisions::LinkVirtualDecision::Set(LinkVirtualState::Virtual) - } else { - decisions::LinkVirtualDecision::NoChange + + let decision = if is_top_level { + let dwell_secs = u64::from(tg.links.min_state_dwell_minutes).saturating_mul(60); + let in_dwell_window = state + .last_change_unix + .is_some_and(|last| now_unix.saturating_sub(last) < dwell_secs); + let rate_limited = if tg.links.max_link_changes_per_hour == 0 { + true + } else { + state.recent_changes_unix.len() + >= tg.links.max_link_changes_per_hour as usize + }; + if in_dwell_window || rate_limited { + decisions::LinkVirtualDecision::NoChange + } else { + let sustained_safe = is_sustained_window( + now_unix, + state.down.top_level_safe_since_unix, + state.up.top_level_safe_since_unix, + TOP_LEVEL_SAFE_SUSTAIN_MINUTES, + ); + let util_high = util_ewma_pct.down >= top_level_safe_util_pct + || util_ewma_pct.up >= top_level_safe_util_pct; + match state.desired { + LinkVirtualState::Physical => { + if sustained_safe { + decisions::LinkVirtualDecision::Set(LinkVirtualState::Virtual) + } else { + decisions::LinkVirtualDecision::NoChange + } } - } - LinkVirtualState::Virtual => { - if util_high { - decisions::LinkVirtualDecision::Set(LinkVirtualState::Physical) - } else { - decisions::LinkVirtualDecision::NoChange + LinkVirtualState::Virtual => { + if util_high { + decisions::LinkVirtualDecision::Set(LinkVirtualState::Physical) + } else { + decisions::LinkVirtualDecision::NoChange + } } } } - } - } else { - decisions::decide_link_virtualization( - now_unix, - allowlisted_nodes.contains(node_name), - cpu_max_pct, - &tg.cpu, - &tg.links, - &tg.qoo, - rtt_missing, - qoo, - util_ewma_pct, - sustained_idle, - state, - ) - }; + } else { + decisions::decide_link_virtualization( + now_unix, + allowlisted_nodes.contains(node_name), + cpu_max_pct, + &tg.cpu, + &tg.links, + &tg.qoo, + rtt_missing, + qoo, + util_ewma_pct, + sustained_idle, + state, + ) + }; - if let decisions::LinkVirtualDecision::Set(target) = decision { - if target == state.desired { - continue; - } + if let decisions::LinkVirtualDecision::Set(target) = decision { + if target == state.desired { + continue; + } - let persist = !tg.dry_run; - let mut persisted_ok = false; - let mut override_changed = false; + let persist = !tg.dry_run; + let mut persisted_ok = false; + let mut override_changed = false; - if persist { - let new_virtual = target == LinkVirtualState::Virtual; - match overrides::set_node_virtual(node_name, new_virtual) { - Ok(changed) => { - persisted_ok = true; - override_changed = changed; - } - Err(e) => { - status.warnings.push(format!( + if persist { + let new_virtual = target == LinkVirtualState::Virtual; + match overrides::set_node_virtual(node_name, new_virtual) { + Ok(changed) => { + persisted_ok = true; + override_changed = changed; + } + Err(e) => { + status.warnings.push(format!( "TreeGuard links: failed to persist virtual override for node '{node_name}': {e}" )); - managed_nodes.insert(node_name.clone()); - push_activity( - activity, - TreeguardActivityEntry { - time: now_unix.to_string(), - entity_type: "node".to_string(), - entity_id: node_name.clone(), - action: "set_virtual_override_failed".to_string(), - persisted: false, - reason: format!("Overrides write failed: {e}"), - }, - ); - continue; + managed_nodes.insert(node_name.clone()); + push_activity( + activity, + TreeguardActivityEntry { + time: now_unix.to_string(), + entity_type: "node".to_string(), + entity_id: node_name.clone(), + action: "set_virtual_override_failed".to_string(), + persisted: false, + reason: format!("Overrides write failed: {e}"), + }, + ); + continue; + } } } - } - if override_changed { - let priority = if target == LinkVirtualState::Physical { - ReloadPriority::Urgent - } else { - ReloadPriority::Normal - }; - reload_controller.request_reload( - priority, - format!("Node '{}' virtualization changed", node_name.clone()), - ); - } + if override_changed { + let priority = if target == LinkVirtualState::Physical { + ReloadPriority::Urgent + } else { + ReloadPriority::Normal + }; + reload_controller.request_reload( + priority, + format!("Node '{}' virtualization changed", node_name.clone()), + ); + } - state.desired = target; - state.last_change_unix = Some(now_unix); - state.recent_changes_unix.push_back(now_unix); - prune_recent_changes(&mut state.recent_changes_unix, now_unix); - managed_nodes.insert(node_name.clone()); + state.desired = target; + state.last_change_unix = Some(now_unix); + state.recent_changes_unix.push_back(now_unix); + prune_recent_changes(&mut state.recent_changes_unix, now_unix); + managed_nodes.insert(node_name.clone()); - push_activity( - activity, - TreeguardActivityEntry { - time: now_unix.to_string(), - entity_type: "node".to_string(), - entity_id: node_name.clone(), - action: match target { - LinkVirtualState::Physical => "unvirtualize".to_string(), - LinkVirtualState::Virtual => "virtualize".to_string(), + push_activity( + activity, + TreeguardActivityEntry { + time: now_unix.to_string(), + entity_type: "node".to_string(), + entity_id: node_name.clone(), + action: match target { + LinkVirtualState::Physical => "unvirtualize".to_string(), + LinkVirtualState::Virtual => "virtualize".to_string(), + }, + persisted: persist && persisted_ok, + reason: if is_top_level { + match target { + LinkVirtualState::Virtual => format!( + "Top-level safe: sustained utilization below {:.1}% for {} minutes", + top_level_safe_util_pct, TOP_LEVEL_SAFE_SUSTAIN_MINUTES + ), + LinkVirtualState::Physical => format!( + "Top-level unsafe: utilization above {:.1}%", + top_level_safe_util_pct + ), + } + } else { + "Decision policy matched".to_string() + }, }, - persisted: persist && persisted_ok, - reason: if is_top_level { - match target { - LinkVirtualState::Virtual => format!( - "Top-level safe: sustained utilization below {:.1}% for {} minutes", - top_level_safe_util_pct, TOP_LEVEL_SAFE_SUSTAIN_MINUTES - ), - LinkVirtualState::Physical => format!( - "Top-level unsafe: utilization above {:.1}%", - top_level_safe_util_pct - ), - } + ); + status.last_action_summary = Some(format!( + "{} node '{}'", + if target == LinkVirtualState::Virtual { + "Virtualized" } else { - "Decision policy matched".to_string() + "Unvirtualized" }, - }, - ); - status.last_action_summary = Some(format!( - "{} node '{}'", - if target == LinkVirtualState::Virtual { - "Virtualized" - } else { - "Unvirtualized" - }, - node_name - )); - } else { - managed_nodes.insert(node_name.clone()); - } + node_name + )); + } else { + managed_nodes.insert(node_name.clone()); + } - if state.desired == LinkVirtualState::Virtual { - virtualized_nodes += 1; + if state.desired == LinkVirtualState::Virtual { + virtualized_nodes += 1; + } } } - } } if let Some(attempt) = reload_controller.poll_reload(now_unix, tg.links.reload_cooldown_minutes) @@ -1237,7 +1229,9 @@ fn run_tick( let extra = next_allowed_unix .map(|t| format!(" next_allowed_unix={t}")) .unwrap_or_default(); - status.warnings.push(format!("TreeGuard reload failed: {error}.{extra}")); + status + .warnings + .push(format!("TreeGuard reload failed: {error}.{extra}")); push_activity( activity, TreeguardActivityEntry { @@ -1349,7 +1343,12 @@ fn run_tick( // Reconcile device IDs removed from allowlisted circuits. let treeguard_device_ids_with_overrides: FxHashSet = treeguard_overrides_snapshot .as_ref() - .map(|of| of.persistent_devices().iter().map(|d| d.device_id.clone()).collect()) + .map(|of| { + of.persistent_devices() + .iter() + .map(|d| d.device_id.clone()) + .collect() + }) .unwrap_or_default(); let removed: Vec = treeguard_device_ids_with_overrides .iter() @@ -1430,32 +1429,32 @@ fn run_tick( slot.down = min_opt_f32(slot.down, down); slot.up = min_opt_f32(slot.up, up); - let bps = bps_by_circuit.entry(ch).or_insert(DownUpOrder { down: 0, up: 0 }); + let bps = bps_by_circuit + .entry(ch) + .or_insert(DownUpOrder { down: 0, up: 0 }); bps.down = bps.down.saturating_add(entry.bytes_per_second.down); bps.up = bps.up.saturating_add(entry.bytes_per_second.up); } } for circuit_id in enrolled_circuits.iter() { - let state = circuit_states - .entry(circuit_id.clone()) - .or_insert_with(|| { - let mut state = CircuitState::default(); - if let Some(token) = infer_circuit_sqm_override_token( - circuit_id, - &shaped.devices, - treeguard_overrides_snapshot.as_ref(), - ) { - let parsed = decisions::parse_directional_sqm_override(&token); - if let Some(down) = parsed.down { - state.down.desired = down; - } - if let Some(up) = parsed.up { - state.up.desired = up; - } + let state = circuit_states.entry(circuit_id.clone()).or_insert_with(|| { + let mut state = CircuitState::default(); + if let Some(token) = infer_circuit_sqm_override_token( + circuit_id, + &shaped.devices, + treeguard_overrides_snapshot.as_ref(), + ) { + let parsed = decisions::parse_directional_sqm_override(&token); + if let Some(down) = parsed.down { + state.down.desired = down; } - state - }); + if let Some(up) = parsed.up { + state.up.desired = up; + } + } + state + }); prune_recent_changes(&mut state.down.recent_changes_unix, now_unix); prune_recent_changes(&mut state.up.recent_changes_unix, now_unix); @@ -1624,8 +1623,7 @@ fn run_tick( } if changed && !devices.is_empty() { - let token = - decisions::format_directional_sqm_override(proposed_down, proposed_up); + let token = decisions::format_directional_sqm_override(proposed_down, proposed_up); if tg.dry_run { if changed_down { @@ -1685,11 +1683,8 @@ fn run_tick( } let live_ok = if can_apply_live { - match bakery::apply_circuit_sqm_override_live( - circuit_id, - &devices, - &token, - ) { + match bakery::apply_circuit_sqm_override_live(circuit_id, &devices, &token) + { Ok(()) => true, Err(e) => { status.warnings.push(format!( @@ -1736,14 +1731,12 @@ fn run_tick( "set_sqm_override".to_string(), "Persisted (live apply failed)".to_string(), ), - (false, true) => ( - "set_sqm_live".to_string(), - "Applied live".to_string(), - ), - (false, false) => ( - "set_sqm_live".to_string(), - "Not applied".to_string(), - ), + (false, true) => { + ("set_sqm_live".to_string(), "Applied live".to_string()) + } + (false, false) => { + ("set_sqm_live".to_string(), "Not applied".to_string()) + } }; push_activity( activity, diff --git a/src/rust/lqosd/src/treeguard/bakery.rs b/src/rust/lqosd/src/treeguard/bakery.rs index 99c563f0..d64a755d 100644 --- a/src/rust/lqosd/src/treeguard/bakery.rs +++ b/src/rust/lqosd/src/treeguard/bakery.rs @@ -58,21 +58,18 @@ pub(crate) fn apply_circuit_sqm_override_live( }); }; - let class_minor = u16::try_from(node.class_minor).map_err(|_| { - TreeguardError::InvalidClassId { + let class_minor = + u16::try_from(node.class_minor).map_err(|_| TreeguardError::InvalidClassId { details: format!("class_minor too large: {}", node.class_minor), - } - })?; - let class_major = u16::try_from(node.class_major).map_err(|_| { - TreeguardError::InvalidClassId { + })?; + let class_major = + u16::try_from(node.class_major).map_err(|_| TreeguardError::InvalidClassId { details: format!("class_major too large: {}", node.class_major), - } - })?; - let up_class_major = u16::try_from(node.up_class_major).map_err(|_| { - TreeguardError::InvalidClassId { + })?; + let up_class_major = + u16::try_from(node.up_class_major).map_err(|_| TreeguardError::InvalidClassId { details: format!("up_class_major too large: {}", node.up_class_major), - } - })?; + })?; let circuit_hash = hash_to_i64(circuit_id); let ip_addresses = ip_list(devices); diff --git a/src/rust/lqosd/src/treeguard/decisions.rs b/src/rust/lqosd/src/treeguard/decisions.rs index 1142edd5..f2a07d4c 100644 --- a/src/rust/lqosd/src/treeguard/decisions.rs +++ b/src/rust/lqosd/src/treeguard/decisions.rs @@ -325,7 +325,10 @@ pub fn parse_directional_sqm_override(token: &str) -> DownUpOrder Result { - let mut overrides = - OverrideStore::load_layer(OverrideLayer::Treeguard).map_err(|e| TreeguardError::OverridesLoad { - details: e.to_string(), + let mut overrides = OverrideStore::load_layer(OverrideLayer::Treeguard).map_err(|e| { + TreeguardError::OverridesLoad { + details: e.to_string(), + } })?; if current_node_virtual_override(&overrides, node_name) == Some(virtual_node) { @@ -55,9 +56,10 @@ pub(crate) fn set_node_virtual( /// /// Returns `Ok(true)` if the file was changed, `Ok(false)` if no change was needed. pub(crate) fn clear_node_virtual(node_name: &str) -> Result { - let mut overrides = - OverrideStore::load_layer(OverrideLayer::Treeguard).map_err(|e| TreeguardError::OverridesLoad { - details: e.to_string(), + let mut overrides = OverrideStore::load_layer(OverrideLayer::Treeguard).map_err(|e| { + TreeguardError::OverridesLoad { + details: e.to_string(), + } })?; let removed = overrides.remove_network_node_virtual_by_name_count(node_name); @@ -83,9 +85,10 @@ pub(crate) fn set_devices_sqm_override( base_devices: &[ShapedDevice], sqm_override: &str, ) -> Result { - let mut overrides = - OverrideStore::load_layer(OverrideLayer::Treeguard).map_err(|e| TreeguardError::OverridesLoad { - details: e.to_string(), + let mut overrides = OverrideStore::load_layer(OverrideLayer::Treeguard).map_err(|e| { + TreeguardError::OverridesLoad { + details: e.to_string(), + } })?; let mut changed = false; @@ -115,9 +118,10 @@ pub(crate) fn set_devices_sqm_override( /// /// Returns `Ok(true)` if the file was changed, `Ok(false)` if no change was needed. pub(crate) fn clear_device_overrides(device_ids: &[String]) -> Result { - let mut overrides = - OverrideStore::load_layer(OverrideLayer::Treeguard).map_err(|e| TreeguardError::OverridesLoad { - details: e.to_string(), + let mut overrides = OverrideStore::load_layer(OverrideLayer::Treeguard).map_err(|e| { + TreeguardError::OverridesLoad { + details: e.to_string(), + } })?; let mut removed_any = false; diff --git a/src/rust/lqosd/src/treeguard/reload.rs b/src/rust/lqosd/src/treeguard/reload.rs index b1215381..4654b3d2 100644 --- a/src/rust/lqosd/src/treeguard/reload.rs +++ b/src/rust/lqosd/src/treeguard/reload.rs @@ -3,7 +3,7 @@ //! Link virtualization changes require a scheduler reload to take effect. This module provides a //! simple cooldown + exponential backoff controller to avoid flapping reloads. -use crate::reload_lock::{try_reload_libreqos_locked, ReloadExecOutcome}; +use crate::reload_lock::{ReloadExecOutcome, try_reload_libreqos_locked}; const MIN_COOLDOWN_SECONDS: u64 = 60; const MAX_BACKOFF_SECONDS: u64 = 2 * 60 * 60; // 2 hours diff --git a/src/rust/lqosd/src/treeguard/state.rs b/src/rust/lqosd/src/treeguard/state.rs index 01ebcad3..f4699c79 100644 --- a/src/rust/lqosd/src/treeguard/state.rs +++ b/src/rust/lqosd/src/treeguard/state.rs @@ -156,7 +156,12 @@ mod tests { fn sustained_idle_requires_full_duration() { let now = 1_000_000u64; // 14:59 is not enough for 15 minutes - assert!(!is_sustained_idle(now, Some(now - 899), Some(now - 899), 15)); + assert!(!is_sustained_idle( + now, + Some(now - 899), + Some(now - 899), + 15 + )); // Exactly 15 minutes is enough assert!(is_sustained_idle(now, Some(now - 900), Some(now - 900), 15)); } diff --git a/src/rust/lqosd/src/treeguard/status.rs b/src/rust/lqosd/src/treeguard/status.rs index d5398c43..f2562abd 100644 --- a/src/rust/lqosd/src/treeguard/status.rs +++ b/src/rust/lqosd/src/treeguard/status.rs @@ -23,7 +23,9 @@ pub async fn treeguard_status_snapshot() -> TreeguardStatusData { virtualized_nodes: 0, fq_codel_circuits: 0, last_action_summary: None, - warnings: vec!["Unable to load configuration; TreeGuard status unavailable.".to_string()], + warnings: vec![ + "Unable to load configuration; TreeGuard status unavailable.".to_string(), + ], }; }; @@ -47,7 +49,11 @@ pub async fn treeguard_status_snapshot() -> TreeguardStatusData { enabled: tg.enabled, dry_run: tg.dry_run, cpu_max_pct: None, - managed_nodes: if tg.links.all_nodes { 0 } else { tg.links.nodes.len() }, + managed_nodes: if tg.links.all_nodes { + 0 + } else { + tg.links.nodes.len() + }, managed_circuits: if tg.circuits.all_circuits { 0 } else { @@ -65,7 +71,5 @@ pub async fn treeguard_status_snapshot() -> TreeguardStatusData { /// This function is not pure: it sends a request to the TreeGuard actor. /// If the actor isn't available, it returns an empty list. pub async fn treeguard_activity_snapshot() -> Vec { - actor::request_activity_snapshot() - .await - .unwrap_or_default() + actor::request_activity_snapshot().await.unwrap_or_default() } diff --git a/src/rust/uisp/Cargo.toml b/src/rust/uisp/Cargo.toml index a697e85a..0d119c7c 100644 --- a/src/rust/uisp/Cargo.toml +++ b/src/rust/uisp/Cargo.toml @@ -5,6 +5,7 @@ edition = "2024" [dependencies] lqos_config = { path = "../lqos_config" } +lqos_utils = { path = "../lqos_utils" } serde = { workspace = true } serde_json.workspace = true reqwest = { workspace = true } diff --git a/src/rust/uisp/src/rest.rs b/src/rust/uisp/src/rest.rs index fe654ee7..7e4c6970 100644 --- a/src/rust/uisp/src/rest.rs +++ b/src/rust/uisp/src/rest.rs @@ -1,4 +1,5 @@ use anyhow::Result; +use lqos_utils::rustls::ensure_rustls_crypto_provider; use serde::de::DeserializeOwned; fn url_fixup(base: &str) -> String { @@ -71,13 +72,14 @@ mod tests { } } -async fn get_client() -> Result { +async fn get_client() -> Result { let mut ignore_ssl_errors = false; if let Ok(cfg) = lqos_config::load_config() { if let Some(ssl) = cfg.uisp_integration.insecure_ssl { ignore_ssl_errors = ssl; } } + ensure_rustls_crypto_provider()?; Ok(reqwest::Client::builder() .danger_accept_invalid_certs(ignore_ssl_errors) .danger_accept_invalid_hostnames(ignore_ssl_errors) @@ -87,11 +89,7 @@ async fn get_client() -> Result { /// Submits a request to the UNMS API and returns the result as unprocessed text. /// This is a debug function: it doesn't do any parsing #[allow(dead_code)] -pub async fn nms_request_get_text( - url: &str, - key: &str, - api: &str, -) -> Result { +pub async fn nms_request_get_text(url: &str, key: &str, api: &str) -> Result { let full_url = format!("{}/{}", url_fixup(api), url); //println!("{full_url}"); let client = get_client().await?; @@ -101,19 +99,14 @@ pub async fn nms_request_get_text( .header("'Content-Type", "application/json") .header("X-Auth-Token", key) .send() - .await - .unwrap(); + .await?; - res.text().await + Ok(res.text().await?) } /// Submits a request to the UNMS API, returning a deserialized vector of type T. #[allow(dead_code)] -pub async fn nms_request_get_vec( - url: &str, - key: &str, - api: &str, -) -> Result, reqwest::Error> +pub async fn nms_request_get_vec(url: &str, key: &str, api: &str) -> Result> where T: DeserializeOwned, { @@ -128,11 +121,11 @@ where .send() .await?; - res.json::>().await + Ok(res.json::>().await?) } #[allow(dead_code)] -pub async fn nms_request_get_one(url: &str, key: &str, api: &str) -> Result +pub async fn nms_request_get_one(url: &str, key: &str, api: &str) -> Result where T: DeserializeOwned, { @@ -147,16 +140,12 @@ where .send() .await?; - res.json::().await + Ok(res.json::().await?) } /// This is a debug function: it doesn't do any parsing #[allow(dead_code)] -pub async fn crm_request_get_text( - api: &str, - key: &str, - url: &str, -) -> Result { +pub async fn crm_request_get_text(api: &str, key: &str, url: &str) -> Result { let full_url = format!("{}/{}", url_fixup(api), url); let client = get_client().await?; @@ -167,15 +156,11 @@ pub async fn crm_request_get_text( .send() .await?; - res.text().await + Ok(res.text().await?) } #[allow(dead_code)] -pub async fn crm_request_get_vec( - api: &str, - key: &str, - url: &str, -) -> Result, reqwest::Error> +pub async fn crm_request_get_vec(api: &str, key: &str, url: &str) -> Result> where T: DeserializeOwned, { @@ -189,11 +174,11 @@ where .send() .await?; - res.json::>().await + Ok(res.json::>().await?) } #[allow(dead_code)] -pub async fn crm_request_get_one(api: &str, key: &str, url: &str) -> Result +pub async fn crm_request_get_one(api: &str, key: &str, url: &str) -> Result where T: DeserializeOwned, { @@ -207,5 +192,5 @@ where .send() .await?; - res.json::().await + Ok(res.json::().await?) } diff --git a/src/rust/uisp_integration/Cargo.toml b/src/rust/uisp_integration/Cargo.toml index e2395413..b7de1961 100644 --- a/src/rust/uisp_integration/Cargo.toml +++ b/src/rust/uisp_integration/Cargo.toml @@ -11,6 +11,7 @@ tokio = { workspace = true } tracing = "0.1.40" tracing-subscriber = "0.3.18" lqos_config = { path = "../lqos_config" } +lqos_utils = { path = "../lqos_utils" } uisp = { path = "../uisp" } thiserror = { workspace = true } serde = { workspace = true } diff --git a/src/rust/uisp_integration/src/main.rs b/src/rust/uisp_integration/src/main.rs index 419f706e..dd486f8a 100644 --- a/src/rust/uisp_integration/src/main.rs +++ b/src/rust/uisp_integration/src/main.rs @@ -13,6 +13,7 @@ use crate::errors::UispIntegrationError; use crate::ip_ranges::IpRanges; pub use blackboard::*; use lqos_config::Config; +use lqos_utils::rustls::ensure_rustls_crypto_provider; use tokio::time::Instant; use tracing::{error, info}; @@ -39,6 +40,11 @@ fn check_enabled_status(config: &Config) -> Result<(), UispIntegrationError> { async fn main() -> Result<(), UispIntegrationError> { let now = Instant::now(); init_tracing(); + ensure_rustls_crypto_provider().map_err(|e| { + error!("Unable to initialize Rustls crypto provider"); + error!("{e}"); + UispIntegrationError::UispConnectError + })?; info!("UISP Integration 2.0-rust"); // Load the configuration -- knotmirror 0.0.1 From fb39086ee902afb020535d58c71951fd94b1d060 Mon Sep 17 00:00:00 2001 From: Robert Chacon Date: Wed, 11 Mar 2026 16:51:44 -0600 Subject: [PATCH 2/4] changes --- src/rust/lqosd/src/treeguard/actor.rs | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/src/rust/lqosd/src/treeguard/actor.rs b/src/rust/lqosd/src/treeguard/actor.rs index 01970f56..218caa0c 100644 --- a/src/rust/lqosd/src/treeguard/actor.rs +++ b/src/rust/lqosd/src/treeguard/actor.rs @@ -572,7 +572,11 @@ fn run_tick( continue; } - if node.virtual_node { + let treeguard_virtual_override = treeguard_overrides_snapshot + .as_ref() + .and_then(|overrides| overrides_node_virtual(overrides, node_name)); + + if node.virtual_node && treeguard_virtual_override.is_none() { status.warnings.push(format!( "TreeGuard links: node '{node_name}' is marked virtual in base network.json; TreeGuard will not manage it." )); @@ -903,7 +907,11 @@ fn run_tick( continue; }; - if node.virtual_node { + let treeguard_virtual_override = treeguard_overrides_snapshot + .as_ref() + .and_then(|overrides| overrides_node_virtual(overrides, node_name)); + + if node.virtual_node && treeguard_virtual_override.is_none() { status.warnings.push(format!( "TreeGuard links: node '{node_name}' is marked virtual in base network.json; TreeGuard will not manage it." )); -- knotmirror 0.0.1 From 13543dd88bbd0933809409d6ee649871f808a31e Mon Sep 17 00:00:00 2001 From: Robert Chacon Date: Wed, 11 Mar 2026 17:10:29 -0600 Subject: [PATCH 3/4] changes --- src/scheduler.py | 10 ++++--- src/test_scheduler.py | 67 +++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 71 insertions(+), 6 deletions(-) diff --git a/src/scheduler.py b/src/scheduler.py index 5ca74684..eb7b3158 100644 --- a/src/scheduler.py +++ b/src/scheduler.py @@ -23,6 +23,11 @@ ads = BlockingScheduler(executors={'default': ThreadPoolExecutor(1)}) network_hash = 0 +def clear_scheduler_error(): + """Clear the scheduler error status shown in the Web UI.""" + scheduler_error("") + + def get_integration_affinity_cpus(): """Return efficiency-core CPU IDs to prefer for integration subprocesses.""" try: @@ -108,7 +113,6 @@ def capture_output_and_run(func): output = captured_output.getvalue() if output: print(output) - scheduler_error(output) def run_python_integration(module_name: str, func_name: str, label: str = ""): @@ -129,7 +133,6 @@ def run_python_integration(module_name: str, func_name: str, label: str = ""): output = (result.stdout or "") + (result.stderr or "") if output: print(output) - scheduler_error(output) if result.returncode != 0: # Non-zero exit shouldn't stop scheduling; log and continue msg = f"Integration {friendly} exited with code {result.returncode}. Continuing." @@ -141,6 +144,7 @@ def run_python_integration(module_name: str, func_name: str, label: str = ""): scheduler_error(err) def importFromCRM(): + clear_scheduler_error() # CRM Hooks if automatic_import_uisp(): try: @@ -155,8 +159,6 @@ def importFromCRM(): output = (result.stdout or "") + (result.stderr or "") if output: print(output) - # Report UISP output to error channel regardless of return code. - scheduler_error(output) if result.returncode != 0: msg = f"UISP integration exited with code {result.returncode}. Continuing." print(msg) diff --git a/src/test_scheduler.py b/src/test_scheduler.py index 3dcaf41f..42b7d890 100644 --- a/src/test_scheduler.py +++ b/src/test_scheduler.py @@ -30,9 +30,9 @@ def install_scheduler_stubs(): lqlib.efficiency_core_ids = lambda: [] lqlib.scheduler_alive = Mock() lqlib.scheduler_error = Mock() - lqlib.overrides_persistent_devices = lambda: [] + lqlib.overrides_persistent_devices_effective = lambda: [] lqlib.overrides_circuit_adjustments = lambda: [] - lqlib.overrides_network_adjustments = lambda: [] + lqlib.overrides_network_adjustments_effective = lambda: [] sys.modules["liblqos_python"] = lqlib apscheduler_pkg = types.ModuleType("apscheduler") @@ -150,5 +150,68 @@ class TestSchedulerAffinity(unittest.TestCase): ) +class TestSchedulerErrorReporting(unittest.TestCase): + def test_python_integration_output_does_not_set_scheduler_error(self): + result = types.SimpleNamespace(returncode=0, stdout="normal info\n", stderr="") + + with patch.object(scheduler, "run_integration_subprocess", return_value=result): + with patch.object(scheduler, "scheduler_error") as mock_scheduler_error: + with patch("builtins.print"): + scheduler.run_python_integration( + "integrationExample", + "importExample", + label="Example", + ) + + mock_scheduler_error.assert_not_called() + + def test_python_integration_nonzero_exit_sets_scheduler_error(self): + result = types.SimpleNamespace(returncode=2, stdout="normal info\n", stderr="") + + with patch.object(scheduler, "run_integration_subprocess", return_value=result): + with patch.object(scheduler, "scheduler_error") as mock_scheduler_error: + with patch("builtins.print"): + scheduler.run_python_integration( + "integrationExample", + "importExample", + label="Example", + ) + + mock_scheduler_error.assert_called_once_with( + "Integration Example exited with code 2. Continuing." + ) + + def test_import_from_crm_clears_error_and_keeps_success_output_non_error(self): + result = types.SimpleNamespace(returncode=0, stdout="uisp info\n", stderr="") + + with patch.object(scheduler, "automatic_import_uisp", return_value=True): + with patch.object(scheduler, "get_libreqos_directory", return_value="/tmp/libreqos"): + with patch.object(scheduler, "run_integration_subprocess", return_value=result): + with patch.object(scheduler, "apply_lqos_overrides"): + with patch.object(scheduler.os.path, "isfile", return_value=False): + with patch.object(scheduler, "scheduler_error") as mock_scheduler_error: + with patch("builtins.print"): + scheduler.importFromCRM() + + self.assertEqual(mock_scheduler_error.call_args_list, [(( "",),)]) + + def test_import_from_crm_reports_nonzero_exit(self): + result = types.SimpleNamespace(returncode=1, stdout="uisp info\n", stderr="") + + with patch.object(scheduler, "automatic_import_uisp", return_value=True): + with patch.object(scheduler, "get_libreqos_directory", return_value="/tmp/libreqos"): + with patch.object(scheduler, "run_integration_subprocess", return_value=result): + with patch.object(scheduler, "apply_lqos_overrides"): + with patch.object(scheduler.os.path, "isfile", return_value=False): + with patch.object(scheduler, "scheduler_error") as mock_scheduler_error: + with patch("builtins.print"): + scheduler.importFromCRM() + + self.assertEqual( + mock_scheduler_error.call_args_list, + [(( "",),), (("UISP integration exited with code 1. Continuing.",),)], + ) + + if __name__ == "__main__": unittest.main() -- knotmirror 0.0.1 From e67be7f19d10be91a4b9fb0f8f01125ffcd0b65f Mon Sep 17 00:00:00 2001 From: Robert Chacon Date: Wed, 11 Mar 2026 18:07:17 -0600 Subject: [PATCH 4/4] changes --- src/rust/lqos_bus/src/bus/request.rs | 3 ++ src/rust/lqos_python/src/lib.rs | 14 ++++++ src/rust/lqosd/src/main.rs | 4 ++ .../src/node_manager/local_api/scheduler.rs | 27 ++++++++++- src/rust/lqosd/src/tool_status.rs | 17 +++++++ src/scheduler.py | 12 ++++- src/test_scheduler.py | 47 ++++++++++++------- 7 files changed, 106 insertions(+), 18 deletions(-) diff --git a/src/rust/lqos_bus/src/bus/request.rs b/src/rust/lqos_bus/src/bus/request.rs index c669ebca..af02e55d 100644 --- a/src/rust/lqos_bus/src/bus/request.rs +++ b/src/rust/lqos_bus/src/bus/request.rs @@ -372,6 +372,9 @@ pub enum BusRequest { /// Announce a scheduler error SchedulerError(String), + /// Announce informational scheduler output + SchedulerOutput(String), + /// Write an informational message to the lqosd logs LogInfo(String), diff --git a/src/rust/lqos_python/src/lib.rs b/src/rust/lqos_python/src/lib.rs index 70e6238e..3c91cd71 100644 --- a/src/rust/lqos_python/src/lib.rs +++ b/src/rust/lqos_python/src/lib.rs @@ -683,6 +683,7 @@ fn liblqos_python(m: &Bound<'_, PyModule>) -> PyResult<()> { m.add_function(wrap_pyfunction!(calculate_hash, m)?)?; m.add_function(wrap_pyfunction!(scheduler_alive, m)?)?; m.add_function(wrap_pyfunction!(scheduler_error, m)?)?; + m.add_function(wrap_pyfunction!(scheduler_output, m)?)?; m.add_function(wrap_pyfunction!(submit_urgent_issue, m)?)?; m.add_function(wrap_pyfunction!(is_insight_enabled, m)?)?; m.add_function(wrap_pyfunction!(log_info, m)?)?; @@ -2144,6 +2145,19 @@ fn scheduler_error(_py: Python, error: String) -> PyResult { Ok(false) } +/// Report informational scheduler output for display in the Web UI. +#[pyfunction] +fn scheduler_output(_py: Python, output: String) -> PyResult { + if let Ok(reply) = run_query(vec![BusRequest::SchedulerOutput(output)]) { + for resp in reply.iter() { + if let BusResponse::Ack = resp { + return Ok(true); + } + } + } + Ok(false) +} + /// Submit an urgent issue for prominent display in the Node Manager UI. /// /// Parameters: diff --git a/src/rust/lqosd/src/main.rs b/src/rust/lqosd/src/main.rs index 8ed82470..376a7f9f 100644 --- a/src/rust/lqosd/src/main.rs +++ b/src/rust/lqosd/src/main.rs @@ -748,6 +748,10 @@ fn handle_bus_requests(requests: &[BusRequest], responses: &mut Vec tool_status::scheduler_error(Some(error.clone())); BusResponse::Ack } + BusRequest::SchedulerOutput(output) => { + tool_status::scheduler_output(Some(output.clone())); + BusResponse::Ack + } BusRequest::LogInfo(msg) => { info!("BUS LOG: {}", msg); BusResponse::Ack diff --git a/src/rust/lqosd/src/node_manager/local_api/scheduler.rs b/src/rust/lqosd/src/node_manager/local_api/scheduler.rs index 09d1cca0..4448d6e9 100644 --- a/src/rust/lqosd/src/node_manager/local_api/scheduler.rs +++ b/src/rust/lqosd/src/node_manager/local_api/scheduler.rs @@ -1,6 +1,6 @@ use serde::Serialize; -use crate::tool_status::{is_scheduler_available, scheduler_error_message}; +use crate::tool_status::{is_scheduler_available, scheduler_error_message, scheduler_output_message}; // Remove ANSI escape sequences (basic CSI/OSC handling) for browser display fn strip_ansi(input: &str) -> String { @@ -68,6 +68,7 @@ pub struct SchedulerStatus { pub struct SchedulerDetails { pub available: bool, pub error: Option, + pub output: Option, pub details: String, } @@ -82,6 +83,17 @@ fn scheduler_error() -> Option { }) } +fn scheduler_output() -> Option { + scheduler_output_message().and_then(|s| { + let t = s.trim().to_string(); + if t.is_empty() { + None + } else { + Some(strip_ansi(&t)) + } + }) +} + pub fn scheduler_status_data() -> SchedulerStatus { let available = is_scheduler_available(); let error = scheduler_error(); @@ -90,6 +102,7 @@ pub fn scheduler_status_data() -> SchedulerStatus { pub fn scheduler_details_data() -> SchedulerDetails { let status = scheduler_status_data(); + let output = scheduler_output(); let mut body = String::new(); body.push_str(&format!("Scheduler available: {}\n\n", status.available)); match status.error.as_ref() { @@ -102,11 +115,23 @@ pub fn scheduler_details_data() -> SchedulerDetails { body.push_str("No scheduler error reported.\n"); } } + body.push('\n'); + match output.as_ref() { + Some(text) => { + body.push_str("Recent output:\n"); + body.push_str(text); + body.push('\n'); + } + None => { + body.push_str("No recent scheduler output recorded.\n"); + } + } body.push_str("\n(Additional scheduler diagnostics not available.)\n"); SchedulerDetails { available: status.available, error: status.error, + output, details: body, } } diff --git a/src/rust/lqosd/src/tool_status.rs b/src/rust/lqosd/src/tool_status.rs index 660301b0..ae1101f6 100644 --- a/src/rust/lqosd/src/tool_status.rs +++ b/src/rust/lqosd/src/tool_status.rs @@ -7,6 +7,7 @@ static API_LAST_SEEN: AtomicU64 = AtomicU64::new(0); static CHATBOT_LAST_SEEN: AtomicU64 = AtomicU64::new(0); static SCHEDULER_LAST_SEEN: AtomicU64 = AtomicU64::new(0); static SCHEDULER_ERROR: Mutex> = Mutex::new(None); +static SCHEDULER_OUTPUT: Mutex> = Mutex::new(None); /// Updates the last seen timestamp for the API. pub fn api_seen() { @@ -41,6 +42,15 @@ pub fn scheduler_error(err: Option) { *guard = err; } +/// Sets the latest scheduler output message. +/// +/// # Arguments +/// * `output` - An optional string containing informational scheduler output +pub fn scheduler_output(output: Option) { + let mut guard = SCHEDULER_OUTPUT.lock(); + *guard = output; +} + /// Checks if the API is available. /// /// Returns `true` if the API has been seen within the last 5 minutes. @@ -71,3 +81,10 @@ pub fn scheduler_error_message() -> Option { SCHEDULER_ERROR.lock(); guard.clone() } + +/// Returns the current scheduler output message, if any. +pub fn scheduler_output_message() -> Option { + let guard: parking_lot::lock_api::MutexGuard<'_, parking_lot::RawMutex, Option> = + SCHEDULER_OUTPUT.lock(); + guard.clone() +} diff --git a/src/scheduler.py b/src/scheduler.py index eb7b3158..08c65bdf 100644 --- a/src/scheduler.py +++ b/src/scheduler.py @@ -12,7 +12,8 @@ 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_hash, efficiency_core_ids, scheduler_alive, scheduler_error, \ - overrides_persistent_devices_effective, overrides_circuit_adjustments, overrides_network_adjustments_effective + overrides_persistent_devices_effective, overrides_circuit_adjustments, overrides_network_adjustments_effective, \ + scheduler_output from apscheduler.schedulers.background import BlockingScheduler from apscheduler.executors.pool import ThreadPoolExecutor @@ -28,6 +29,11 @@ def clear_scheduler_error(): scheduler_error("") +def clear_scheduler_output(): + """Clear the scheduler output shown in the Web UI.""" + scheduler_output("") + + def get_integration_affinity_cpus(): """Return efficiency-core CPU IDs to prefer for integration subprocesses.""" try: @@ -113,6 +119,7 @@ def capture_output_and_run(func): output = captured_output.getvalue() if output: print(output) + scheduler_output(output) def run_python_integration(module_name: str, func_name: str, label: str = ""): @@ -133,6 +140,7 @@ def run_python_integration(module_name: str, func_name: str, label: str = ""): output = (result.stdout or "") + (result.stderr or "") if output: print(output) + scheduler_output(output) if result.returncode != 0: # Non-zero exit shouldn't stop scheduling; log and continue msg = f"Integration {friendly} exited with code {result.returncode}. Continuing." @@ -145,6 +153,7 @@ def run_python_integration(module_name: str, func_name: str, label: str = ""): def importFromCRM(): clear_scheduler_error() + clear_scheduler_output() # CRM Hooks if automatic_import_uisp(): try: @@ -159,6 +168,7 @@ def importFromCRM(): output = (result.stdout or "") + (result.stderr or "") if output: print(output) + scheduler_output(output) if result.returncode != 0: msg = f"UISP integration exited with code {result.returncode}. Continuing." print(msg) diff --git a/src/test_scheduler.py b/src/test_scheduler.py index 42b7d890..76e0f1fc 100644 --- a/src/test_scheduler.py +++ b/src/test_scheduler.py @@ -30,6 +30,7 @@ def install_scheduler_stubs(): lqlib.efficiency_core_ids = lambda: [] lqlib.scheduler_alive = Mock() lqlib.scheduler_error = Mock() + lqlib.scheduler_output = Mock() lqlib.overrides_persistent_devices_effective = lambda: [] lqlib.overrides_circuit_adjustments = lambda: [] lqlib.overrides_network_adjustments_effective = lambda: [] @@ -156,30 +157,34 @@ class TestSchedulerErrorReporting(unittest.TestCase): with patch.object(scheduler, "run_integration_subprocess", return_value=result): with patch.object(scheduler, "scheduler_error") as mock_scheduler_error: - with patch("builtins.print"): - scheduler.run_python_integration( - "integrationExample", - "importExample", - label="Example", - ) + with patch.object(scheduler, "scheduler_output") as mock_scheduler_output: + with patch("builtins.print"): + scheduler.run_python_integration( + "integrationExample", + "importExample", + label="Example", + ) mock_scheduler_error.assert_not_called() + mock_scheduler_output.assert_called_once_with("normal info\n") def test_python_integration_nonzero_exit_sets_scheduler_error(self): result = types.SimpleNamespace(returncode=2, stdout="normal info\n", stderr="") with patch.object(scheduler, "run_integration_subprocess", return_value=result): with patch.object(scheduler, "scheduler_error") as mock_scheduler_error: - with patch("builtins.print"): - scheduler.run_python_integration( - "integrationExample", - "importExample", - label="Example", - ) + with patch.object(scheduler, "scheduler_output") as mock_scheduler_output: + with patch("builtins.print"): + scheduler.run_python_integration( + "integrationExample", + "importExample", + label="Example", + ) mock_scheduler_error.assert_called_once_with( "Integration Example exited with code 2. Continuing." ) + mock_scheduler_output.assert_called_once_with("normal info\n") def test_import_from_crm_clears_error_and_keeps_success_output_non_error(self): result = types.SimpleNamespace(returncode=0, stdout="uisp info\n", stderr="") @@ -190,10 +195,15 @@ class TestSchedulerErrorReporting(unittest.TestCase): with patch.object(scheduler, "apply_lqos_overrides"): with patch.object(scheduler.os.path, "isfile", return_value=False): with patch.object(scheduler, "scheduler_error") as mock_scheduler_error: - with patch("builtins.print"): - scheduler.importFromCRM() + with patch.object(scheduler, "scheduler_output") as mock_scheduler_output: + with patch("builtins.print"): + scheduler.importFromCRM() self.assertEqual(mock_scheduler_error.call_args_list, [(( "",),)]) + self.assertEqual( + mock_scheduler_output.call_args_list, + [(( "",),), (("uisp info\n",),)], + ) def test_import_from_crm_reports_nonzero_exit(self): result = types.SimpleNamespace(returncode=1, stdout="uisp info\n", stderr="") @@ -204,13 +214,18 @@ class TestSchedulerErrorReporting(unittest.TestCase): with patch.object(scheduler, "apply_lqos_overrides"): with patch.object(scheduler.os.path, "isfile", return_value=False): with patch.object(scheduler, "scheduler_error") as mock_scheduler_error: - with patch("builtins.print"): - scheduler.importFromCRM() + with patch.object(scheduler, "scheduler_output") as mock_scheduler_output: + with patch("builtins.print"): + scheduler.importFromCRM() self.assertEqual( mock_scheduler_error.call_args_list, [(( "",),), (("UISP integration exited with code 1. Continuing.",),)], ) + self.assertEqual( + mock_scheduler_output.call_args_list, + [(( "",),), (("uisp info\n",),)], + ) if __name__ == "__main__": -- knotmirror 0.0.1