diff --git a/src/rust/lqos_config/src/etc/mod.rs b/src/rust/lqos_config/src/etc/mod.rs index b95aba32..109d9ea6 100644 --- a/src/rust/lqos_config/src/etc/mod.rs +++ b/src/rust/lqos_config/src/etc/mod.rs @@ -18,7 +18,9 @@ mod python_migration; pub mod test_data; mod v15; pub use v15::{ - BridgeConfig, LazyQueueMode, RttThresholds, SingleInterfaceConfig, StormguardConfig, Tunables, + BridgeConfig, LazyQueueMode, RttThresholds, SingleInterfaceConfig, StormguardConfig, + TreeguardCircuitsConfig, TreeguardConfig, TreeguardCpuConfig, TreeguardCpuMode, + TreeguardLinksConfig, TreeguardQooConfig, Tunables, }; static CONFIG: Lazy>>> = Lazy::new(|| ArcSwap::from_pointee(None)); diff --git a/src/rust/lqos_config/src/etc/v15/example.toml b/src/rust/lqos_config/src/etc/v15/example.toml index 0a75c23f..31df4a26 100644 --- a/src/rust/lqos_config/src/etc/v15/example.toml +++ b/src/rust/lqos_config/src/etc/v15/example.toml @@ -42,6 +42,48 @@ sudo = false #override_available_queues = 12 # This can be omitted and be 0 for Python use_binpacking = false +[treeguard] +enabled = true +dry_run = false +tick_seconds = 1 + +[treeguard.cpu] +mode = "traffic_rtt_only" +cpu_high_pct = 75 +cpu_low_pct = 55 + +[treeguard.links] +enabled = true +all_nodes = true +nodes = [] +idle_util_pct = 2.0 +idle_min_minutes = 15 +rtt_missing_seconds = 120 +unvirtualize_util_pct = 5.0 +min_state_dwell_minutes = 30 +max_link_changes_per_hour = 4 +reload_cooldown_minutes = 10 +top_level_auto_virtualize = true +top_level_safe_util_pct = 85.0 + +[treeguard.circuits] +enabled = true +all_circuits = true +circuits = [] +switching_enabled = true +independent_directions = true +idle_util_pct = 2.0 +idle_min_minutes = 15 +rtt_missing_seconds = 120 +upgrade_util_pct = 5.0 +min_switch_dwell_minutes = 30 +max_switches_per_hour = 4 +persist_sqm_overrides = true + +[treeguard.qoo] +enabled = true +min_score = 80.0 + [long_term_stats] gather_stats = true collation_period_seconds = 10 diff --git a/src/rust/lqos_config/src/etc/v15/mod.rs b/src/rust/lqos_config/src/etc/v15/mod.rs index 1b2c1f61..a4f8306b 100644 --- a/src/rust/lqos_config/src/etc/v15/mod.rs +++ b/src/rust/lqos_config/src/etc/v15/mod.rs @@ -15,6 +15,7 @@ mod queues; mod sonar_integration; mod splynx_integration; mod stormguard; +mod treeguard; mod tuning; mod uisp_integration; mod visp_integration; @@ -24,4 +25,8 @@ pub use bridge::*; pub use long_term_stats::LongTermStats; pub use queues::LazyQueueMode; pub use stormguard::StormguardConfig; +pub use treeguard::{ + TreeguardCircuitsConfig, TreeguardConfig, TreeguardCpuConfig, TreeguardCpuMode, + TreeguardLinksConfig, TreeguardQooConfig, +}; pub use tuning::Tunables; 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 7bf8dfc5..662e3dde 100644 --- a/src/rust/lqos_config/src/etc/v15/top_config.rs +++ b/src/rust/lqos_config/src/etc/v15/top_config.rs @@ -2,6 +2,7 @@ use super::tuning::Tunables; use crate::etc::v15::stormguard; +use crate::etc::v15::treeguard; use allocative::Allocative; use serde::{Deserialize, Serialize}; use sha2::Digest; @@ -152,6 +153,10 @@ pub struct Config { /// Support for Tornado/Auto-rate. pub stormguard: Option, + /// TreeGuard intelligent node management. + #[serde(default)] + pub treeguard: treeguard::TreeguardConfig, + /// Disable ICMP Ping Monitoring for Devices in the hosts view pub disable_icmp_ping: Option, @@ -218,6 +223,7 @@ impl Config { if self.queues.default_sqm.trim().is_empty() { return Err("default_sqm cannot be empty. Please specify a qdisc type (e.g., 'cake diffserv4' or 'fq_codel')".to_string()); } + self.treeguard.validate()?; Ok(()) } @@ -305,6 +311,7 @@ impl Default for Config { disable_webserver: None, webserver_listen: None, stormguard: None, + treeguard: treeguard::TreeguardConfig::default(), disable_icmp_ping: Some(false), exclude_efficiency_cores: true, enable_circuit_heatmaps: true, @@ -364,7 +371,12 @@ mod test { let trimmed = line.trim(); if trimmed.starts_with('[') && trimmed.ends_with(']') { let section_name = &trimmed[1..trimmed.len() - 1]; - skip_section = sections.contains(§ion_name); + skip_section = sections.iter().any(|section| { + section_name == *section + || section_name + .strip_prefix(&format!("{section}.")) + .is_some() + }); } if !skip_section { @@ -484,4 +496,44 @@ mod test { }); assert!(cfg.validate().is_err()); } + + #[test] + fn treeguard_defaults_match_default_on_rollout() { + let cfg = Config::default(); + assert!(cfg.treeguard.enabled); + assert!(!cfg.treeguard.dry_run); + assert_eq!( + cfg.treeguard.cpu.mode, + crate::etc::v15::treeguard::TreeguardCpuMode::TrafficRttOnly + ); + assert!(cfg.treeguard.links.enabled); + assert!(cfg.treeguard.links.all_nodes); + assert!(cfg.treeguard.links.top_level_auto_virtualize); + assert!(cfg.treeguard.circuits.enabled); + assert!(cfg.treeguard.circuits.all_circuits); + } + + #[test] + fn load_example_without_treeguard_section_uses_defaults() { + let stripped = remove_sections(include_str!("example.toml"), &["treeguard"]); + let config = Config::load_from_string(&stripped) + .expect("Config without treeguard should still deserialize"); + assert!(config.treeguard.enabled); + assert!(!config.treeguard.dry_run); + assert!(config.treeguard.links.all_nodes); + assert!(config.treeguard.circuits.all_circuits); + } + + #[test] + fn treeguard_validation_rejects_invalid_thresholds() { + let mut cfg = Config::default(); + cfg.treeguard.cpu.cpu_low_pct = 90; + cfg.treeguard.cpu.cpu_high_pct = 80; + assert!(cfg.validate().is_err()); + + cfg = Config::default(); + cfg.treeguard.circuits.idle_util_pct = 10.0; + cfg.treeguard.circuits.upgrade_util_pct = 5.0; + assert!(cfg.validate().is_err()); + } } diff --git a/src/rust/lqos_config/src/etc/v15/treeguard.rs b/src/rust/lqos_config/src/etc/v15/treeguard.rs new file mode 100644 index 00000000..dd4f1493 --- /dev/null +++ b/src/rust/lqos_config/src/etc/v15/treeguard.rs @@ -0,0 +1,363 @@ +//! TreeGuard configuration definitions. + +use allocative::Allocative; +use serde::{Deserialize, Serialize}; + +fn default_enabled() -> bool { + true +} + +fn default_false() -> bool { + false +} + +fn default_tick_seconds() -> u64 { + 1 +} + +fn default_cpu_high_pct() -> u8 { + 75 +} + +fn default_cpu_low_pct() -> u8 { + 55 +} + +fn default_idle_util_pct() -> f32 { + 2.0 +} + +fn default_idle_min_minutes() -> u32 { + 15 +} + +fn default_rtt_missing_seconds() -> u32 { + 120 +} + +fn default_unvirtualize_util_pct() -> f32 { + 5.0 +} + +fn default_min_state_dwell_minutes() -> u32 { + 30 +} + +fn default_max_link_changes_per_hour() -> u32 { + 4 +} + +fn default_reload_cooldown_minutes() -> u32 { + 10 +} + +fn default_top_level_safe_util_pct() -> f32 { + 85.0 +} + +fn default_upgrade_util_pct() -> f32 { + 5.0 +} + +fn default_min_switch_dwell_minutes() -> u32 { + 30 +} + +fn default_max_switches_per_hour() -> u32 { + 4 +} + +fn default_min_score() -> f32 { + 80.0 +} + +/// CPU modes supported by TreeGuard. +#[derive(Clone, Copy, Serialize, Deserialize, Debug, PartialEq, Eq, Default, Allocative)] +#[serde(rename_all = "snake_case")] +pub enum TreeguardCpuMode { + /// Consider CPU thresholds when making decisions. + CpuAware, + /// Use only traffic and RTT signals. + #[default] + TrafficRttOnly, +} + +/// Top-level TreeGuard configuration. +#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Allocative)] +#[serde(default)] +pub struct TreeguardConfig { + /// Enables TreeGuard globally. + #[serde(default = "default_enabled")] + pub enabled: bool, + /// If true, TreeGuard records intended actions but does not apply them. + #[serde(default = "default_false")] + pub dry_run: bool, + /// Decision cadence. + #[serde(default = "default_tick_seconds")] + pub tick_seconds: u64, + /// CPU guardrail settings. + pub cpu: TreeguardCpuConfig, + /// Link/node virtualization settings. + pub links: TreeguardLinksConfig, + /// Circuit SQM switching settings. + pub circuits: TreeguardCircuitsConfig, + /// QoO guardrail settings. + pub qoo: TreeguardQooConfig, +} + +impl Default for TreeguardConfig { + fn default() -> Self { + Self { + enabled: default_enabled(), + dry_run: default_false(), + tick_seconds: default_tick_seconds(), + cpu: TreeguardCpuConfig::default(), + links: TreeguardLinksConfig::default(), + circuits: TreeguardCircuitsConfig::default(), + qoo: TreeguardQooConfig::default(), + } + } +} + +/// TreeGuard CPU guardrails. +#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Allocative)] +#[serde(default)] +pub struct TreeguardCpuConfig { + /// How CPU participates in decision making. + pub mode: TreeguardCpuMode, + /// High watermark for CPU pressure. + #[serde(default = "default_cpu_high_pct")] + pub cpu_high_pct: u8, + /// Low watermark for reverting CPU-saving actions. + #[serde(default = "default_cpu_low_pct")] + pub cpu_low_pct: u8, +} + +impl Default for TreeguardCpuConfig { + fn default() -> Self { + Self { + mode: TreeguardCpuMode::default(), + cpu_high_pct: default_cpu_high_pct(), + cpu_low_pct: default_cpu_low_pct(), + } + } +} + +/// TreeGuard node virtualization settings. +#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Allocative)] +#[serde(default)] +pub struct TreeguardLinksConfig { + /// Enables TreeGuard management of node virtualization. + #[serde(default = "default_enabled")] + pub enabled: bool, + /// Apply to all eligible nodes instead of an allowlist. + #[serde(default = "default_enabled")] + pub all_nodes: bool, + /// Explicit allowlist when `all_nodes` is false. + pub nodes: Vec, + /// Utilization threshold below which a link is considered idle. + #[serde(default = "default_idle_util_pct")] + pub idle_util_pct: f32, + /// Required duration for idle classification. + #[serde(default = "default_idle_min_minutes")] + pub idle_min_minutes: u32, + /// RTT freshness timeout. + #[serde(default = "default_rtt_missing_seconds")] + pub rtt_missing_seconds: u32, + /// Utilization threshold to unvirtualize. + #[serde(default = "default_unvirtualize_util_pct")] + pub unvirtualize_util_pct: f32, + /// Minimum state dwell before another change. + #[serde(default = "default_min_state_dwell_minutes")] + pub min_state_dwell_minutes: u32, + /// Rate limit on link changes. + #[serde(default = "default_max_link_changes_per_hour")] + pub max_link_changes_per_hour: u32, + /// Cooldown between topology reloads. + #[serde(default = "default_reload_cooldown_minutes")] + pub reload_cooldown_minutes: u32, + /// Allow TreeGuard to virtualize top-level nodes. + #[serde(default = "default_enabled")] + pub top_level_auto_virtualize: bool, + /// Utilization ceiling for safe top-level virtualization. + #[serde(default = "default_top_level_safe_util_pct")] + pub top_level_safe_util_pct: f32, +} + +impl Default for TreeguardLinksConfig { + fn default() -> Self { + Self { + enabled: default_enabled(), + all_nodes: default_enabled(), + nodes: Vec::new(), + idle_util_pct: default_idle_util_pct(), + idle_min_minutes: default_idle_min_minutes(), + rtt_missing_seconds: default_rtt_missing_seconds(), + unvirtualize_util_pct: default_unvirtualize_util_pct(), + min_state_dwell_minutes: default_min_state_dwell_minutes(), + max_link_changes_per_hour: default_max_link_changes_per_hour(), + reload_cooldown_minutes: default_reload_cooldown_minutes(), + top_level_auto_virtualize: default_enabled(), + top_level_safe_util_pct: default_top_level_safe_util_pct(), + } + } +} + +/// TreeGuard circuit management settings. +#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Allocative)] +#[serde(default)] +pub struct TreeguardCircuitsConfig { + /// Enables TreeGuard circuit management. + #[serde(default = "default_enabled")] + pub enabled: bool, + /// Apply to all circuits instead of an allowlist. + #[serde(default = "default_enabled")] + pub all_circuits: bool, + /// Explicit allowlist when `all_circuits` is false. + pub circuits: Vec, + /// Enables SQM switching actions. + #[serde(default = "default_enabled")] + pub switching_enabled: bool, + /// Manage upload/download directions independently. + #[serde(default = "default_enabled")] + pub independent_directions: bool, + /// Utilization threshold below which a circuit is considered idle. + #[serde(default = "default_idle_util_pct")] + pub idle_util_pct: f32, + /// Required duration for idle classification. + #[serde(default = "default_idle_min_minutes")] + pub idle_min_minutes: u32, + /// RTT freshness timeout. + #[serde(default = "default_rtt_missing_seconds")] + pub rtt_missing_seconds: u32, + /// Utilization threshold to switch back to CAKE. + #[serde(default = "default_upgrade_util_pct")] + pub upgrade_util_pct: f32, + /// Minimum dwell before another SQM switch. + #[serde(default = "default_min_switch_dwell_minutes")] + pub min_switch_dwell_minutes: u32, + /// Rate limit on SQM switches. + #[serde(default = "default_max_switches_per_hour")] + pub max_switches_per_hour: u32, + /// Persist overrides to avoid scheduler fights. + #[serde(default = "default_enabled")] + pub persist_sqm_overrides: bool, +} + +impl Default for TreeguardCircuitsConfig { + fn default() -> Self { + Self { + enabled: default_enabled(), + all_circuits: default_enabled(), + circuits: Vec::new(), + switching_enabled: default_enabled(), + independent_directions: default_enabled(), + idle_util_pct: default_idle_util_pct(), + idle_min_minutes: default_idle_min_minutes(), + rtt_missing_seconds: default_rtt_missing_seconds(), + upgrade_util_pct: default_upgrade_util_pct(), + min_switch_dwell_minutes: default_min_switch_dwell_minutes(), + max_switches_per_hour: default_max_switches_per_hour(), + persist_sqm_overrides: default_enabled(), + } + } +} + +/// TreeGuard QoO protection settings. +#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Allocative)] +#[serde(default)] +pub struct TreeguardQooConfig { + /// Enables QoO protection. + #[serde(default = "default_enabled")] + pub enabled: bool, + /// Minimum QoO score required to take CPU-saving actions. + #[serde(default = "default_min_score")] + pub min_score: f32, +} + +impl Default for TreeguardQooConfig { + fn default() -> Self { + Self { + enabled: default_enabled(), + min_score: default_min_score(), + } + } +} + +impl TreeguardConfig { + /// Validates TreeGuard configuration values and cross-field relationships. + pub fn validate(&self) -> Result<(), String> { + validate_percent_u8("treeguard.cpu.cpu_high_pct", self.cpu.cpu_high_pct)?; + validate_percent_u8("treeguard.cpu.cpu_low_pct", self.cpu.cpu_low_pct)?; + if self.cpu.cpu_low_pct > self.cpu.cpu_high_pct { + return Err( + "treeguard.cpu.cpu_low_pct must be less than or equal to treeguard.cpu.cpu_high_pct" + .to_string(), + ); + } + + validate_non_zero("treeguard.tick_seconds", self.tick_seconds)?; + + self.links.validate()?; + self.circuits.validate()?; + self.qoo.validate()?; + + Ok(()) + } +} + +impl TreeguardLinksConfig { + fn validate(&self) -> Result<(), String> { + validate_percent_f32("treeguard.links.idle_util_pct", self.idle_util_pct)?; + validate_percent_f32( + "treeguard.links.unvirtualize_util_pct", + self.unvirtualize_util_pct, + )?; + validate_percent_f32( + "treeguard.links.top_level_safe_util_pct", + self.top_level_safe_util_pct, + )?; + Ok(()) + } +} + +impl TreeguardCircuitsConfig { + fn validate(&self) -> Result<(), String> { + validate_percent_f32("treeguard.circuits.idle_util_pct", self.idle_util_pct)?; + validate_percent_f32("treeguard.circuits.upgrade_util_pct", self.upgrade_util_pct)?; + if self.upgrade_util_pct < self.idle_util_pct { + return Err( + "treeguard.circuits.upgrade_util_pct must be greater than or equal to treeguard.circuits.idle_util_pct" + .to_string(), + ); + } + Ok(()) + } +} + +impl TreeguardQooConfig { + fn validate(&self) -> Result<(), String> { + validate_percent_f32("treeguard.qoo.min_score", self.min_score) + } +} + +fn validate_percent_u8(name: &str, value: u8) -> Result<(), String> { + if value > 100 { + return Err(format!("{name} must be between 0 and 100")); + } + Ok(()) +} + +fn validate_percent_f32(name: &str, value: f32) -> Result<(), String> { + if !value.is_finite() || !(0.0..=100.0).contains(&value) { + return Err(format!("{name} must be between 0 and 100")); + } + Ok(()) +} + +fn validate_non_zero(name: &str, value: u64) -> Result<(), String> { + if value == 0 { + return Err(format!("{name} must be greater than 0")); + } + Ok(()) +} diff --git a/src/rust/lqos_config/src/lib.rs b/src/rust/lqos_config/src/lib.rs index a1574cc9..9cf0200a 100644 --- a/src/rust/lqos_config/src/lib.rs +++ b/src/rust/lqos_config/src/lib.rs @@ -21,7 +21,9 @@ pub use cpu_topology::{ }; pub use etc::{ BridgeConfig, Config, LazyQueueMode, RttThresholds, SingleInterfaceConfig, StormguardConfig, - Tunables, disable_xdp_bridge, enable_long_term_stats, load_config, update_config, + TreeguardCircuitsConfig, TreeguardConfig, TreeguardCpuConfig, TreeguardCpuMode, + TreeguardLinksConfig, TreeguardQooConfig, Tunables, disable_xdp_bridge, + enable_long_term_stats, load_config, update_config, }; pub use network_json::{NetworkJson, NetworkJsonNode, NetworkJsonTransport}; pub use program_control::load_libreqos; diff --git a/src/rust/lqosd/dev_build.sh b/src/rust/lqosd/dev_build.sh index 55e5fe02..c4a3d3a6 100755 --- a/src/rust/lqosd/dev_build.sh +++ b/src/rust/lqosd/dev_build.sh @@ -12,9 +12,11 @@ pushd "$SCRIPT_DIR/src/node_manager/js_build" >/dev/null ./esbuild.sh popd >/dev/null -echo "[dev_build] Copying bundles to bin/static2..." +echo "[dev_build] Copying static HTML/CSS assets to bin/static2..." mkdir -p "$SCRIPT_DIR/../../bin/static2" +cp -R "$SCRIPT_DIR/src/node_manager/static2/"* "$SCRIPT_DIR/../../bin/static2/" + +echo "[dev_build] Copying bundles to bin/static2..." cp -R "$SCRIPT_DIR/src/node_manager/js_build/out/"* "$SCRIPT_DIR/../../bin/static2/" echo "[dev_build] Done. Hard refresh your browser (Ctrl/Cmd+Shift+R)." - diff --git a/src/rust/lqosd/src/node_manager/js_build/esbuild.sh b/src/rust/lqosd/src/node_manager/js_build/esbuild.sh index bda36a49..7550819f 100755 --- a/src/rust/lqosd/src/node_manager/js_build/esbuild.sh +++ b/src/rust/lqosd/src/node_manager/js_build/esbuild.sh @@ -9,7 +9,7 @@ set -e chmod a+x /tmp/esbuild/esbuild ESBUILD_BIN="/tmp/esbuild/esbuild" #fi -scripts=( index.js template.js login.js first-run.js shaped-devices.js tree.js help.js unknown-ips.js configuration.js circuit.js flow_map.js all_tree_sankey.js asn_explorer.js lts_trial.js config_general.js config_rtt.js config_tuning.js config_queues.js config_stormguard.js config_lts.js config_iprange.js config_flows.js config_integration.js config_splynx.js config_netzur.js config_visp.js config_uisp.js config_powercode.js config_sonar.js config_interface.js config_network.js config_devices.js config_users.js config_wispgate.js chatbot.js cpu_weights.js cpu_tree.js executive_worst_sites.js executive_oversubscribed_sites.js executive_sites_due_upgrade.js executive_circuits_due_upgrade.js executive_top_asns.js executive_heatmap_rtt.js executive_heatmap_retransmit.js executive_heatmap_download.js executive_heatmap_upload.js) +scripts=( index.js template.js login.js first-run.js shaped-devices.js tree.js help.js unknown-ips.js configuration.js circuit.js flow_map.js all_tree_sankey.js asn_explorer.js lts_trial.js config_general.js config_rtt.js config_tuning.js config_queues.js config_stormguard.js config_treeguard.js config_lts.js config_iprange.js config_flows.js config_integration.js config_splynx.js config_netzur.js config_visp.js config_uisp.js config_powercode.js config_sonar.js config_interface.js config_network.js config_devices.js config_users.js config_wispgate.js chatbot.js cpu_weights.js cpu_tree.js executive_worst_sites.js executive_oversubscribed_sites.js executive_sites_due_upgrade.js executive_circuits_due_upgrade.js executive_top_asns.js executive_heatmap_rtt.js executive_heatmap_retransmit.js executive_heatmap_download.js executive_heatmap_upload.js) for script in "${scripts[@]}" do echo "Building {$script}" diff --git a/src/rust/lqosd/src/node_manager/js_build/src/config/treeguard_defaults.js b/src/rust/lqosd/src/node_manager/js_build/src/config/treeguard_defaults.js new file mode 100644 index 00000000..7ca9cf89 --- /dev/null +++ b/src/rust/lqosd/src/node_manager/js_build/src/config/treeguard_defaults.js @@ -0,0 +1,73 @@ +export function defaultTreeguardConfig() { + return { + enabled: true, + dry_run: false, + tick_seconds: 1, + cpu: { + mode: "traffic_rtt_only", + cpu_high_pct: 75, + cpu_low_pct: 55, + }, + links: { + enabled: true, + all_nodes: true, + nodes: [], + idle_util_pct: 2.0, + idle_min_minutes: 15, + rtt_missing_seconds: 120, + unvirtualize_util_pct: 5.0, + min_state_dwell_minutes: 30, + max_link_changes_per_hour: 4, + reload_cooldown_minutes: 10, + top_level_auto_virtualize: true, + top_level_safe_util_pct: 85.0, + }, + circuits: { + enabled: true, + all_circuits: true, + circuits: [], + switching_enabled: true, + independent_directions: true, + idle_util_pct: 2.0, + idle_min_minutes: 15, + rtt_missing_seconds: 120, + upgrade_util_pct: 5.0, + min_switch_dwell_minutes: 30, + max_switches_per_hour: 4, + persist_sqm_overrides: true, + }, + qoo: { + enabled: true, + min_score: 80.0, + }, + }; +} + +export function ensureTreeguardConfig(config) { + const defaults = defaultTreeguardConfig(); + if (!config || typeof config !== "object") { + return defaults; + } + + const current = config.treeguard || {}; + return { + ...defaults, + ...current, + cpu: { + ...defaults.cpu, + ...(current.cpu || {}), + }, + links: { + ...defaults.links, + ...(current.links || {}), + }, + circuits: { + ...defaults.circuits, + ...(current.circuits || {}), + }, + qoo: { + ...defaults.qoo, + ...(current.qoo || {}), + }, + }; +} diff --git a/src/rust/lqosd/src/node_manager/js_build/src/config_treeguard.js b/src/rust/lqosd/src/node_manager/js_build/src/config_treeguard.js new file mode 100644 index 00000000..25e0fe28 --- /dev/null +++ b/src/rust/lqosd/src/node_manager/js_build/src/config_treeguard.js @@ -0,0 +1,517 @@ +import { + loadAllShapedDevices, + loadConfig, + loadNetworkJson, + renderConfigMenu, + saveConfig, +} from "./config/config_helper"; +import {defaultTreeguardConfig, ensureTreeguardConfig} from "./config/treeguard_defaults"; + +let networkData = null; +let shapedDevices = null; +let selectedNodes = []; +let selectedCircuits = []; + +function updateLinksEnrollmentUi() { + const allNodes = document.getElementById("linksAllNodes")?.checked ?? true; + const section = document.getElementById("nodesAllowlistSection"); + if (section) { + section.style.display = allNodes ? "none" : ""; + } +} + +function updateCircuitsEnrollmentUi() { + const allCircuits = document.getElementById("circuitsAllCircuits")?.checked ?? true; + const section = document.getElementById("circuitsAllowlistSection"); + if (section) { + section.style.display = allCircuits ? "none" : ""; + } +} + +function loadNetworkData() { + return new Promise((resolve, reject) => { + loadNetworkJson( + (data) => { + if (typeof data === "string" && data === "Not done yet") { + console.error("Network.json file not found on server"); + alert("Network configuration not found. Please ensure network.json exists."); + resolve(); + return; + } + networkData = data; + populateNodeSelector(); + resolve(); + }, + (err) => { + console.error("Error loading network data:", err); + alert("Failed to load network nodes. You can still add nodes manually."); + reject(err); + }, + ); + }); +} + +function loadCircuitsData() { + return new Promise((resolve, reject) => { + loadAllShapedDevices( + (data) => { + if (!Array.isArray(data)) { + console.warn("Shaped devices response was not an array:", data); + shapedDevices = []; + } else { + shapedDevices = data; + } + populateCircuitSelector(); + resolve(); + }, + (err) => { + console.error("Error loading shaped devices:", err); + alert("Failed to load circuit list. You can still add circuits manually."); + reject(err); + }, + ); + }); +} + +function populateNodeSelector() { + const selector = document.getElementById("nodeSelector"); + selector.innerHTML = ''; + + function iterate(data, level = 0) { + if (typeof data !== "object" || data === null) { + return; + } + + for (const [key, value] of Object.entries(data)) { + const option = document.createElement("option"); + option.value = key; + + let prefix = ""; + for (let i = 0; i < level; i++) { + prefix += "- "; + } + option.textContent = prefix + key; + selector.appendChild(option); + + if (value && typeof value === "object" && value.children != null) { + iterate(value.children, level + 1); + } + } + } + + if (networkData) { + iterate(networkData); + } +} + +function populateCircuitSelector() { + const selector = document.getElementById("circuitSelector"); + selector.innerHTML = ''; + + const circuits = new Set(); + if (Array.isArray(shapedDevices)) { + shapedDevices.forEach((device) => { + if (device && typeof device.circuit_id === "string" && device.circuit_id.trim() !== "") { + circuits.add(device.circuit_id.trim()); + } + }); + } + + Array.from(circuits) + .sort((a, b) => a.localeCompare(b)) + .forEach((circuitId) => { + const option = document.createElement("option"); + option.value = circuitId; + option.textContent = circuitId; + selector.appendChild(option); + }); +} + +function addNode() { + const selector = document.getElementById("nodeSelector"); + const selected = selector.value; + if (!selected) { + alert("Please select a node to add"); + return; + } + if (selectedNodes.includes(selected)) { + alert("This node is already allowlisted"); + return; + } + selectedNodes.push(selected); + selectedNodes.sort((a, b) => a.localeCompare(b)); + updateNodesList(); + selector.value = ""; +} + +function removeNode(nodeName) { + const index = selectedNodes.indexOf(nodeName); + if (index > -1) { + selectedNodes.splice(index, 1); + updateNodesList(); + } +} + +function updateNodesList() { + const listContainer = document.getElementById("selectedNodesList"); + listContainer.innerHTML = ""; + + if (selectedNodes.length === 0) { + listContainer.innerHTML = '
No nodes selected
'; + return; + } + + selectedNodes.forEach((node) => { + const listItem = document.createElement("div"); + listItem.className = "list-group-item d-flex justify-content-between align-items-center"; + + const nodeName = document.createElement("span"); + nodeName.textContent = node; + + const removeBtn = document.createElement("button"); + removeBtn.className = "btn btn-sm btn-outline-danger"; + removeBtn.innerHTML = ''; + removeBtn.onclick = () => removeNode(node); + + listItem.appendChild(nodeName); + listItem.appendChild(removeBtn); + listContainer.appendChild(listItem); + }); +} + +function addCircuitFromSelector() { + const selector = document.getElementById("circuitSelector"); + const selected = selector.value; + if (!selected) { + alert("Please select a circuit to add"); + return; + } + addCircuitId(selected); + selector.value = ""; +} + +function addCircuitFromManual() { + const input = document.getElementById("circuitManual"); + const circuitId = input.value.trim(); + if (!circuitId) { + alert("Please enter a circuit ID"); + return; + } + addCircuitId(circuitId); + input.value = ""; +} + +function addCircuitId(circuitId) { + if (selectedCircuits.includes(circuitId)) { + alert("This circuit is already allowlisted"); + return; + } + selectedCircuits.push(circuitId); + selectedCircuits.sort((a, b) => a.localeCompare(b)); + updateCircuitsList(); +} + +function removeCircuit(circuitId) { + const index = selectedCircuits.indexOf(circuitId); + if (index > -1) { + selectedCircuits.splice(index, 1); + updateCircuitsList(); + } +} + +function updateCircuitsList() { + const listContainer = document.getElementById("selectedCircuitsList"); + listContainer.innerHTML = ""; + + if (selectedCircuits.length === 0) { + listContainer.innerHTML = '
No circuits selected
'; + return; + } + + selectedCircuits.forEach((circuitId) => { + const listItem = document.createElement("div"); + listItem.className = "list-group-item d-flex justify-content-between align-items-center"; + + const circuitName = document.createElement("span"); + circuitName.textContent = circuitId; + + const removeBtn = document.createElement("button"); + removeBtn.className = "btn btn-sm btn-outline-danger"; + removeBtn.innerHTML = ''; + removeBtn.onclick = () => removeCircuit(circuitId); + + listItem.appendChild(circuitName); + listItem.appendChild(removeBtn); + listContainer.appendChild(listItem); + }); +} + +function validatePercent(name, value, min = 0, max = 100) { + if (Number.isNaN(value) || value < min || value > max) { + alert(`${name} must be between ${min} and ${max}`); + return false; + } + return true; +} + +function validateNonNegativeInt(name, value) { + if (Number.isNaN(value) || value < 0) { + alert(`${name} must be a number >= 0`); + return false; + } + return true; +} + +function validateConfig() { + const tickSeconds = parseInt(document.getElementById("tickSeconds").value, 10); + if (Number.isNaN(tickSeconds) || tickSeconds < 1) { + alert("Tick Interval must be at least 1 second"); + return false; + } + + const cpuHighPct = parseInt(document.getElementById("cpuHighPct").value, 10); + const cpuLowPct = parseInt(document.getElementById("cpuLowPct").value, 10); + if (!validatePercent("CPU High Threshold", cpuHighPct)) return false; + if (!validatePercent("CPU Low Threshold", cpuLowPct)) return false; + if (cpuLowPct > cpuHighPct) { + alert("CPU Low Threshold must be less than or equal to CPU High Threshold"); + return false; + } + + const idleUtilPct = parseFloat(document.getElementById("idleUtilPct").value); + if (!validatePercent("Idle Utilization", idleUtilPct)) return false; + + const unvirtualizeUtilPct = parseFloat(document.getElementById("unvirtualizeUtilPct").value); + if (!validatePercent("Unvirtualize Utilization", unvirtualizeUtilPct)) return false; + + const topLevelSafeUtilPct = parseFloat(document.getElementById("topLevelSafeUtilPct").value); + if (!validatePercent("Top-Level Safe Utilization", topLevelSafeUtilPct)) return false; + + const idleMinMinutes = parseInt(document.getElementById("idleMinMinutes").value, 10); + if (!validateNonNegativeInt("Idle Minimum Duration", idleMinMinutes)) return false; + + const linksRttMissingSeconds = parseInt( + document.getElementById("linksRttMissingSeconds").value, + 10, + ); + if (!validateNonNegativeInt("Links RTT Missing Timeout", linksRttMissingSeconds)) return false; + + const minStateDwellMinutes = parseInt( + document.getElementById("minStateDwellMinutes").value, + 10, + ); + if (!validateNonNegativeInt("Minimum State Dwell", minStateDwellMinutes)) return false; + + const maxLinkChangesPerHour = parseInt( + document.getElementById("maxLinkChangesPerHour").value, + 10, + ); + if (!validateNonNegativeInt("Max Link Changes Per Hour", maxLinkChangesPerHour)) return false; + + const reloadCooldownMinutes = parseInt( + document.getElementById("reloadCooldownMinutes").value, + 10, + ); + if (!validateNonNegativeInt("Reload Cooldown", reloadCooldownMinutes)) return false; + + const circuitsRttMissingSeconds = parseInt( + document.getElementById("circuitsRttMissingSeconds").value, + 10, + ); + if (!validateNonNegativeInt("Circuits RTT Missing Timeout", circuitsRttMissingSeconds)) return false; + + const circuitsIdleUtilPct = parseFloat(document.getElementById("circuitsIdleUtilPct").value); + if (!validatePercent("Circuits Idle Utilization", circuitsIdleUtilPct)) return false; + + const circuitsIdleMinMinutes = parseInt( + document.getElementById("circuitsIdleMinMinutes").value, + 10, + ); + if (!validateNonNegativeInt("Circuits Idle Minimum Duration", circuitsIdleMinMinutes)) return false; + + const circuitsUpgradeUtilPct = parseFloat( + document.getElementById("circuitsUpgradeUtilPct").value, + ); + if (!validatePercent("Circuits Upgrade Utilization", circuitsUpgradeUtilPct)) return false; + if (circuitsUpgradeUtilPct < circuitsIdleUtilPct) { + alert("Circuits Upgrade Utilization must be greater than or equal to Circuits Idle Utilization"); + return false; + } + + const minSwitchDwellMinutes = parseInt( + document.getElementById("minSwitchDwellMinutes").value, + 10, + ); + if (!validateNonNegativeInt("Minimum Switch Dwell", minSwitchDwellMinutes)) return false; + + const maxSwitchesPerHour = parseInt(document.getElementById("maxSwitchesPerHour").value, 10); + if (!validateNonNegativeInt("Max Switches Per Hour", maxSwitchesPerHour)) return false; + + const minScore = parseFloat(document.getElementById("minScore").value); + if (!validatePercent("Minimum QoO Score", minScore)) return false; + + return true; +} + +function updateConfig() { + window.config.treeguard = { + enabled: document.getElementById("enabled").checked, + dry_run: document.getElementById("dryRun").checked, + tick_seconds: parseInt(document.getElementById("tickSeconds").value, 10), + cpu: { + mode: document.getElementById("cpuMode").value, + cpu_high_pct: parseInt(document.getElementById("cpuHighPct").value, 10), + cpu_low_pct: parseInt(document.getElementById("cpuLowPct").value, 10), + }, + links: { + enabled: document.getElementById("linksEnabled").checked, + all_nodes: document.getElementById("linksAllNodes").checked, + nodes: selectedNodes, + idle_util_pct: parseFloat(document.getElementById("idleUtilPct").value), + idle_min_minutes: parseInt(document.getElementById("idleMinMinutes").value, 10), + rtt_missing_seconds: parseInt( + document.getElementById("linksRttMissingSeconds").value, + 10, + ), + unvirtualize_util_pct: parseFloat(document.getElementById("unvirtualizeUtilPct").value), + min_state_dwell_minutes: parseInt( + document.getElementById("minStateDwellMinutes").value, + 10, + ), + max_link_changes_per_hour: parseInt( + document.getElementById("maxLinkChangesPerHour").value, + 10, + ), + reload_cooldown_minutes: parseInt( + document.getElementById("reloadCooldownMinutes").value, + 10, + ), + top_level_auto_virtualize: document.getElementById("topLevelAutoVirtualize").checked, + top_level_safe_util_pct: parseFloat(document.getElementById("topLevelSafeUtilPct").value), + }, + circuits: { + enabled: document.getElementById("circuitsEnabled").checked, + all_circuits: document.getElementById("circuitsAllCircuits").checked, + circuits: selectedCircuits, + switching_enabled: document.getElementById("switchingEnabled").checked, + independent_directions: document.getElementById("independentDirections").checked, + idle_util_pct: parseFloat(document.getElementById("circuitsIdleUtilPct").value), + idle_min_minutes: parseInt(document.getElementById("circuitsIdleMinMinutes").value, 10), + rtt_missing_seconds: parseInt( + document.getElementById("circuitsRttMissingSeconds").value, + 10, + ), + upgrade_util_pct: parseFloat(document.getElementById("circuitsUpgradeUtilPct").value), + min_switch_dwell_minutes: parseInt( + document.getElementById("minSwitchDwellMinutes").value, + 10, + ), + max_switches_per_hour: parseInt( + document.getElementById("maxSwitchesPerHour").value, + 10, + ), + persist_sqm_overrides: document.getElementById("persistSqmOverrides").checked, + }, + qoo: { + enabled: document.getElementById("qooEnabled").checked, + min_score: parseFloat(document.getElementById("minScore").value), + }, + }; +} + +renderConfigMenu("treeguard"); + +Promise.all([ + loadNetworkData().catch(() => null), + loadCircuitsData().catch(() => null), + new Promise((resolve) => { + loadConfig(() => resolve()); + }), +]).then(() => { + const tg = ensureTreeguardConfig(window.config); + const cpu = tg.cpu; + const links = tg.links; + const circuits = tg.circuits; + const qoo = tg.qoo; + + document.getElementById("enabled").checked = tg.enabled; + document.getElementById("dryRun").checked = tg.dry_run; + document.getElementById("tickSeconds").value = tg.tick_seconds; + + document.getElementById("cpuMode").value = cpu.mode; + document.getElementById("cpuHighPct").value = cpu.cpu_high_pct; + document.getElementById("cpuLowPct").value = cpu.cpu_low_pct; + + document.getElementById("linksEnabled").checked = links.enabled; + document.getElementById("linksAllNodes").checked = links.all_nodes; + document.getElementById("topLevelAutoVirtualize").checked = links.top_level_auto_virtualize; + document.getElementById("topLevelSafeUtilPct").value = links.top_level_safe_util_pct; + document.getElementById("idleUtilPct").value = links.idle_util_pct; + document.getElementById("idleMinMinutes").value = links.idle_min_minutes; + document.getElementById("linksRttMissingSeconds").value = links.rtt_missing_seconds; + document.getElementById("unvirtualizeUtilPct").value = links.unvirtualize_util_pct; + document.getElementById("minStateDwellMinutes").value = links.min_state_dwell_minutes; + document.getElementById("maxLinkChangesPerHour").value = links.max_link_changes_per_hour; + document.getElementById("reloadCooldownMinutes").value = links.reload_cooldown_minutes; + + selectedNodes = Array.isArray(links.nodes) ? links.nodes.slice() : []; + selectedNodes.sort((a, b) => a.localeCompare(b)); + updateNodesList(); + updateLinksEnrollmentUi(); + + document.getElementById("circuitsEnabled").checked = circuits.enabled; + document.getElementById("circuitsAllCircuits").checked = circuits.all_circuits; + document.getElementById("switchingEnabled").checked = circuits.switching_enabled; + document.getElementById("independentDirections").checked = circuits.independent_directions; + document.getElementById("circuitsIdleUtilPct").value = circuits.idle_util_pct; + document.getElementById("circuitsIdleMinMinutes").value = circuits.idle_min_minutes; + document.getElementById("circuitsRttMissingSeconds").value = circuits.rtt_missing_seconds; + document.getElementById("circuitsUpgradeUtilPct").value = circuits.upgrade_util_pct; + document.getElementById("minSwitchDwellMinutes").value = circuits.min_switch_dwell_minutes; + document.getElementById("maxSwitchesPerHour").value = circuits.max_switches_per_hour; + document.getElementById("persistSqmOverrides").checked = circuits.persist_sqm_overrides; + + selectedCircuits = Array.isArray(circuits.circuits) ? circuits.circuits.slice() : []; + selectedCircuits.sort((a, b) => a.localeCompare(b)); + updateCircuitsList(); + updateCircuitsEnrollmentUi(); + + document.getElementById("qooEnabled").checked = qoo.enabled; + document.getElementById("minScore").value = qoo.min_score; + + document.getElementById("addNodeBtn").addEventListener("click", addNode); + document.getElementById("linksAllNodes").addEventListener("change", updateLinksEnrollmentUi); + document.getElementById("nodeSelector").addEventListener("keypress", (e) => { + if (e.key === "Enter") { + e.preventDefault(); + addNode(); + } + }); + + document.getElementById("addCircuitBtn").addEventListener("click", addCircuitFromSelector); + document.getElementById("circuitsAllCircuits").addEventListener("change", updateCircuitsEnrollmentUi); + document.getElementById("circuitSelector").addEventListener("keypress", (e) => { + if (e.key === "Enter") { + e.preventDefault(); + addCircuitFromSelector(); + } + }); + + document.getElementById("addCircuitManualBtn").addEventListener("click", addCircuitFromManual); + document.getElementById("circuitManual").addEventListener("keypress", (e) => { + if (e.key === "Enter") { + e.preventDefault(); + addCircuitFromManual(); + } + }); + + document.getElementById("saveButton").addEventListener("click", () => { + if (!validateConfig()) { + return; + } + updateConfig(); + saveConfig(() => { + alert("TreeGuard configuration saved successfully!"); + }); + }); +}); diff --git a/src/rust/lqosd/src/node_manager/js_build/src/dashlets/dashlet_index.js b/src/rust/lqosd/src/node_manager/js_build/src/dashlets/dashlet_index.js index 21b9c35d..f82bda58 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/dashlets/dashlet_index.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/dashlets/dashlet_index.js @@ -28,6 +28,7 @@ import {LtsLast24Hours} from "./ltsLast24Hours"; import {TcpRetransmitsDash} from "./total_retransmits"; import {StormguardStatusDashlet} from "./stormguard_status"; import {BakeryStatusDashlet} from "./bakery_status"; +import {TreeguardStatusDashlet} from "./treeguard_status"; import {Top10UploadersVisual} from "./top10_uploads_graphic"; import {Top10Uploaders} from "./top10_uploaders"; // New Traffic Overview dashlets @@ -79,6 +80,7 @@ export const DashletMenu = [ { name: "(Insight) Shaper Status", tag: "ltsShaperStatus", size: 3, category: "Insight" }, { name: "(Insight) Last 24 Hours", tag: "ltsLast24", size: 3, category: "Insight" }, { name: "Stormguard Bandwidth Adjustments", tag: "stormguardStatus", size: 6, category: "Queue Management" }, + { name: "TreeGuard Status", tag: "treeguardStatus", size: 12, category: "Queue Management" }, { name: "Bakery Circuit Activity", tag: "bakeryStatus", size: 6, category: "Queue Management" }, // Traffic Overview (Insight-like) { name: "Shaper Top ASN (Download)", tag: "shaperTopAsnDown", size: 6, category: "Traffic" }, @@ -130,6 +132,7 @@ export function widgetFactory(widgetName, count) { case "ltsShaperStatus" : widget = new LtsShaperStatus(count); break; case "ltsLast24" : widget = new LtsLast24Hours(count); break; case "stormguardStatus" : widget = new StormguardStatusDashlet(count); break; + case "treeguardStatus" : widget = new TreeguardStatusDashlet(count); break; case "bakeryStatus" : widget = new BakeryStatusDashlet(count); break; // Traffic Overview case "shaperTopAsnDown" : widget = new ShaperTopAsnDownload(count); break; diff --git a/src/rust/lqosd/src/node_manager/js_build/src/dashlets/treeguard_status.js b/src/rust/lqosd/src/node_manager/js_build/src/dashlets/treeguard_status.js new file mode 100644 index 00000000..f9bd0357 --- /dev/null +++ b/src/rust/lqosd/src/node_manager/js_build/src/dashlets/treeguard_status.js @@ -0,0 +1,166 @@ +import {loadConfig, saveConfig} from "../config/config_helper"; +import {defaultTreeguardConfig, ensureTreeguardConfig} from "../config/treeguard_defaults"; +import {BaseDashlet} from "../lq_js_common/dashboard/base_dashlet"; + +export class TreeguardStatusDashlet extends BaseDashlet { + constructor(slot) { + super(slot); + this.treeguard = defaultTreeguardConfig(); + this.isSaving = false; + } + + title() { + return "TreeGuard"; + } + + tooltip() { + return "
TreeGuard

Quick access to the default TreeGuard controls plus the current config-derived rollout status.

"; + } + + subscribeTo() { + return []; + } + + statusLineId() { + return `${this.id}_status`; + } + + controlsId() { + return `${this.id}_controls`; + } + + saveStateId() { + return `${this.id}_save_state`; + } + + enabledId() { + return `${this.id}_enabled`; + } + + dryRunId() { + return `${this.id}_dry_run`; + } + + buildContainer() { + const base = super.buildContainer(); + + const statusLine = document.createElement("div"); + statusLine.id = this.statusLineId(); + statusLine.className = "text-muted small mb-3"; + statusLine.innerText = "Loading TreeGuard status..."; + base.appendChild(statusLine); + + const controls = document.createElement("div"); + controls.id = this.controlsId(); + controls.className = "d-flex flex-column flex-md-row gap-3 align-items-start align-items-md-center"; + controls.innerHTML = ` +
+ + +
+
+ + +
+ `; + base.appendChild(controls); + + const saveState = document.createElement("div"); + saveState.id = this.saveStateId(); + saveState.className = "small mt-2 text-muted"; + base.appendChild(saveState); + + return base; + } + + setup() { + this.bindControls(); + this.refreshConfig(); + } + + bindControls() { + const enabled = document.getElementById(this.enabledId()); + const dryRun = document.getElementById(this.dryRunId()); + enabled.addEventListener("change", () => this.persistToggle("enabled", enabled.checked)); + dryRun.addEventListener("change", () => this.persistToggle("dry_run", dryRun.checked)); + } + + refreshConfig() { + this.setSaveState("Loading config...", false); + loadConfig( + () => { + this.treeguard = ensureTreeguardConfig(window.config); + this.syncControls(); + this.renderStatusLine(); + this.setSaveState("", false); + }, + () => { + this.treeguard = ensureTreeguardConfig(window.config || {}); + this.syncControls(); + this.renderStatusLine(); + this.setSaveState("Unable to refresh TreeGuard config.", true); + }, + ); + } + + syncControls() { + const enabled = document.getElementById(this.enabledId()); + const dryRun = document.getElementById(this.dryRunId()); + enabled.checked = !!this.treeguard.enabled; + dryRun.checked = !!this.treeguard.dry_run; + enabled.disabled = this.isSaving; + dryRun.disabled = this.isSaving; + } + + renderStatusLine() { + const statusLine = document.getElementById(this.statusLineId()); + const liveState = this.treeguard.dry_run ? "dry run" : "live"; + const mode = this.treeguard.cpu?.mode === "cpu_aware" ? "CPU-aware" : "Traffic/RTT only"; + const linkScope = this.treeguard.links?.all_nodes ? "all links" : "allowlisted links"; + const circuitScope = this.treeguard.circuits?.all_circuits ? "all circuits" : "allowlisted circuits"; + const enabled = this.treeguard.enabled ? "Enabled" : "Disabled"; + statusLine.innerHTML = ` + Status: ${enabled}, ${liveState}, ${mode}, ${linkScope}, ${circuitScope}. + Open configuration + `; + } + + persistToggle(field, nextValue) { + const previousValue = this.treeguard[field]; + this.treeguard[field] = nextValue; + window.config = window.config || {}; + window.config.treeguard = ensureTreeguardConfig(window.config); + window.config.treeguard[field] = nextValue; + this.isSaving = true; + this.syncControls(); + this.renderStatusLine(); + this.setSaveState("Saving...", false); + + saveConfig( + () => { + this.isSaving = false; + this.syncControls(); + this.renderStatusLine(); + this.setSaveState("Saved.", false); + }, + () => { + this.treeguard[field] = previousValue; + window.config.treeguard[field] = previousValue; + this.isSaving = false; + this.syncControls(); + this.renderStatusLine(); + this.setSaveState("Save failed.", true); + }, + ); + } + + setSaveState(message, isError) { + const saveState = document.getElementById(this.saveStateId()); + if (!saveState) { + return; + } + saveState.innerText = message; + saveState.classList.toggle("text-danger", !!message && isError); + saveState.classList.toggle("text-muted", !message || !isError); + } +} diff --git a/src/rust/lqosd/src/node_manager/js_build/src/index.js b/src/rust/lqosd/src/node_manager/js_build/src/index.js index c95331c6..d3c80254 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/index.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/index.js @@ -71,6 +71,12 @@ const defaultLayout = { { tag: "ipProtocols", size: 6 }, { tag: "totalCakeStats", size: 6 } ] + }, + { + name: "TreeGuard", + dashlets: [ + { tag: "treeguardStatus", size: 12 } + ] } ] }; diff --git a/src/rust/lqosd/src/node_manager/static2/config_treeguard.html b/src/rust/lqosd/src/node_manager/static2/config_treeguard.html new file mode 100644 index 00000000..622b1eff --- /dev/null +++ b/src/rust/lqosd/src/node_manager/static2/config_treeguard.html @@ -0,0 +1,271 @@ +
+
+
+ + + +
+ +
+ + +
Enable intelligent node management (virtualization + SQM switching)
+
+ + +
+ + +
Test mode - record actions without applying persistent or live changes
+
+ + +
+ + +
How often TreeGuard evaluates telemetry and makes decisions
+
+ +
+
CPU
+ +
+ + +
Controls how CPU usage influences TreeGuard decisions
+
+ +
+ + +
At/above this CPU%, TreeGuard may take CPU-saving actions
+
+ +
+ + +
At/below this CPU%, TreeGuard should revert CPU-saving actions
+
+ +
+
Links (Node Virtualization)
+ +
+ + +
Allow TreeGuard to mark enrolled nodes as virtual/unvirtual
+
+ +
+ + +
+ + +
If enabled, TreeGuard manages all non-root nodes in network.json (allowlist ignored)
+
+ +
+
TreeGuard will only manage nodes explicitly listed here
+ +
+ + +
+ +
+ +
+
+
+ +
+ + +
+ + +
+ Top-level nodes are keys of the root object in network.json (e.g. Site_1). If enabled, + TreeGuard may virtualize them even if not allowlisted. +
+
+ +
+ + +
If sustained below this threshold for 15 minutes, TreeGuard may virtualize top-level nodes.
+
+
+ +
+ + +
Utilization below which a link is considered idle (after smoothing)
+
+ +
+ + +
How long a link must remain idle before virtualizing
+
+ +
+ + +
RTT sample age after which RTT is treated as missing/unsafe
+
+ +
+ + +
If utilization rises above this threshold, TreeGuard should unvirtualize
+
+ +
+ + +
Minimum time before a node may change state again
+
+ +
+ + +
Rate limit to prevent flapping
+
+ +
+ + +
Minimum time between topology reload attempts
+
+ +
+
Circuits (SQM Switching)
+ +
+ + +
Allow TreeGuard to manage per-circuit SQM for enrolled circuits
+
+ +
+ + +
+ + +
If enabled, TreeGuard manages all circuits found in ShapedDevices (allowlist ignored)
+
+ +
+
Circuit IDs as in ShapedDevices.csv
+ +
+ + +
+ +
+ + +
+ +
+ +
+
+
+ +
+ + +
Allow TreeGuard to switch CAKE ↔ fq_codel
+
+ +
+ + +
Allow different SQM tokens for down vs up
+
+ +
+ + +
Utilization below which a circuit direction is considered idle (after smoothing)
+
+ +
+ + +
How long a circuit direction must remain idle before downgrading SQM
+
+ +
+ + +
+ +
+ + +
Utilization above which a downgraded direction upgrades back to CAKE
+
+ +
+ + +
+ +
+ + +
+ +
+ + +
Write SQM overrides to lqos_overrides.treeguard.json to avoid scheduler fights
+
+ +
+
QoO Guardrail
+ +
+ + +
If QoO is available and below the threshold, do not take CPU-saving actions
+
+ +
+ + +
0..100; enforced only when QoO is available
+
+ + +
+
+
+ + diff --git a/src/rust/lqosd/src/node_manager/static_pages.rs b/src/rust/lqosd/src/node_manager/static_pages.rs index 70b7d572..d8683e12 100644 --- a/src/rust/lqosd/src/node_manager/static_pages.rs +++ b/src/rust/lqosd/src/node_manager/static_pages.rs @@ -73,6 +73,7 @@ pub(super) fn static_routes() -> Result { "config_users.html", "config_wispgate.html", "config_stormguard.html", + "config_treeguard.html", "stormguard_debug.html", "api.html", "cpu_weights.html", -- knotmirror 0.0.1 From 00ccecfb08f750fd7d24c38eb314d690606c0b40 Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Mon, 9 Mar 2026 14:09:11 -0500 Subject: [PATCH 2/5] Feat: restore TreeGuard status and activity dashlets --- .../js_build/src/dashlets/dashlet_index.js | 12 +- .../src/dashlets/treeguard_activity.js | 366 +++++++++++++ .../src/dashlets/treeguard_controls.js | 167 ++++++ .../js_build/src/dashlets/treeguard_status.js | 506 +++++++++++++----- .../src/node_manager/js_build/src/index.js | 4 +- 5 files changed, 925 insertions(+), 130 deletions(-) create mode 100644 src/rust/lqosd/src/node_manager/js_build/src/dashlets/treeguard_activity.js create mode 100644 src/rust/lqosd/src/node_manager/js_build/src/dashlets/treeguard_controls.js diff --git a/src/rust/lqosd/src/node_manager/js_build/src/dashlets/dashlet_index.js b/src/rust/lqosd/src/node_manager/js_build/src/dashlets/dashlet_index.js index f82bda58..68211401 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/dashlets/dashlet_index.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/dashlets/dashlet_index.js @@ -28,7 +28,9 @@ import {LtsLast24Hours} from "./ltsLast24Hours"; import {TcpRetransmitsDash} from "./total_retransmits"; import {StormguardStatusDashlet} from "./stormguard_status"; import {BakeryStatusDashlet} from "./bakery_status"; -import {TreeguardStatusDashlet} from "./treeguard_status"; +import {TreeGuardStatusDashlet} from "./treeguard_status"; +import {TreeGuardActivityDashlet} from "./treeguard_activity"; +import {TreeguardControlsDashlet} from "./treeguard_controls"; import {Top10UploadersVisual} from "./top10_uploads_graphic"; import {Top10Uploaders} from "./top10_uploaders"; // New Traffic Overview dashlets @@ -80,8 +82,10 @@ export const DashletMenu = [ { name: "(Insight) Shaper Status", tag: "ltsShaperStatus", size: 3, category: "Insight" }, { name: "(Insight) Last 24 Hours", tag: "ltsLast24", size: 3, category: "Insight" }, { name: "Stormguard Bandwidth Adjustments", tag: "stormguardStatus", size: 6, category: "Queue Management" }, - { name: "TreeGuard Status", tag: "treeguardStatus", size: 12, category: "Queue Management" }, { name: "Bakery Circuit Activity", tag: "bakeryStatus", size: 6, category: "Queue Management" }, + { name: "TreeGuard Controls", tag: "treeguardControls", size: 6, category: "TreeGuard" }, + { name: "TreeGuard Status", tag: "treeguardStatus", size: 6, category: "TreeGuard" }, + { name: "TreeGuard Activity", tag: "treeguardActivity", size: 12, category: "TreeGuard" }, // Traffic Overview (Insight-like) { name: "Shaper Top ASN (Download)", tag: "shaperTopAsnDown", size: 6, category: "Traffic" }, { name: "Shaper Top ASN (Upload)", tag: "shaperTopAsnUp", size: 6, category: "Traffic" }, @@ -132,8 +136,10 @@ export function widgetFactory(widgetName, count) { case "ltsShaperStatus" : widget = new LtsShaperStatus(count); break; case "ltsLast24" : widget = new LtsLast24Hours(count); break; case "stormguardStatus" : widget = new StormguardStatusDashlet(count); break; - case "treeguardStatus" : widget = new TreeguardStatusDashlet(count); break; case "bakeryStatus" : widget = new BakeryStatusDashlet(count); break; + case "treeguardControls": widget = new TreeguardControlsDashlet(count); break; + case "treeguardStatus" : widget = new TreeGuardStatusDashlet(count); break; + case "treeguardActivity": widget = new TreeGuardActivityDashlet(count); break; // Traffic Overview case "shaperTopAsnDown" : widget = new ShaperTopAsnDownload(count); break; case "shaperTopAsnUp" : widget = new ShaperTopAsnUpload(count); break; diff --git a/src/rust/lqosd/src/node_manager/js_build/src/dashlets/treeguard_activity.js b/src/rust/lqosd/src/node_manager/js_build/src/dashlets/treeguard_activity.js new file mode 100644 index 00000000..cf6ef397 --- /dev/null +++ b/src/rust/lqosd/src/node_manager/js_build/src/dashlets/treeguard_activity.js @@ -0,0 +1,366 @@ +import {BaseDashlet} from "../lq_js_common/dashboard/base_dashlet"; +import {get_ws_client} from "../pubsub/ws"; + +function formatUnixSecondsToLocalTime(unixSeconds) { + const n = typeof unixSeconds === "number" ? unixSeconds : parseInt(unixSeconds, 10); + if (!Number.isFinite(n) || n <= 0) { + return ""; + } + return new Date(n * 1000).toLocaleTimeString(undefined, { + hour: "2-digit", + minute: "2-digit", + second: "2-digit", + }); +} + +function parseCircuitEntityId(entityIdRaw) { + const s = (entityIdRaw ?? "").toString().trim(); + if (!s) return { circuitId: "", display: "", hasName: false }; + + const m = s.match(/^(.*)\s*\(([^)]+)\)\s*$/); + if (m) { + const name = (m[1] ?? "").toString().trim(); + const id = (m[2] ?? "").toString().trim(); + if (id) { + return { circuitId: id, display: name || id, hasName: !!name }; + } + } + + return { circuitId: s, display: s, hasName: false }; +} + +function splitOnce(s, sep) { + const str = (s ?? "").toString(); + const idx = str.indexOf(sep); + if (idx === -1) return [str, ""]; + return [str.slice(0, idx), str.slice(idx + sep.length)]; +} + +function parseDirectionalSqmToken(token) { + const t = (token ?? "").toString().trim(); + if (!t) return { down: "", up: "" }; + if (!t.includes("/")) return { down: t, up: t }; + const [down, up] = splitOnce(t, "/"); + return { down: (down ?? "").toString().trim(), up: (up ?? "").toString().trim() }; +} + +function formatSqmLabel(prefix, token) { + const { down, up } = parseDirectionalSqmToken(token); + if (!down && !up) return prefix; + if (down === up) return `${prefix}: ${down}`; + return `${prefix}: DL ${down}, UL ${up}`; +} + +function mkIcon(iconClass, extraClasses = []) { + const icon = document.createElement("i"); + icon.classList.add("fa", "fa-fw", iconClass); + extraClasses.forEach((c) => icon.classList.add(c)); + return icon; +} + +function formatReason(reasonRaw) { + const raw = (reasonRaw ?? "").toString().trim(); + if (!raw) return { label: "", title: "" }; + + const lower = raw.toLowerCase(); + if (!lower.includes("next_allowed_unix=")) { + return { label: raw, title: "" }; + } + + const m = raw.match(/next_allowed_unix=(\d+)/i); + if (!m) return { label: raw, title: "" }; + + const next = formatUnixSecondsToLocalTime(parseInt(m[1], 10)); + if (!next) return { label: raw, title: "" }; + + if (lower.startsWith("reload cooldown active")) { + return { label: `Reload on cooldown - next allowed ${next}`, title: raw }; + } + + return { label: raw.replace(m[0], `next allowed ${next}`), title: raw }; +} + +function renderAction(actionRaw) { + const raw = (actionRaw ?? "").toString(); + const [verbRaw, payloadRaw] = splitOnce(raw, ":"); + const verb = (verbRaw ?? "").toString().trim(); + const payload = (payloadRaw ?? "").toString().trim(); + + const lowerVerb = verb.toLowerCase(); + let iconClass = "fa-question-circle"; + let iconExtra = ["text-muted"]; + let label = raw; + + const isFailed = lowerVerb.endsWith("_failed") || lowerVerb.includes("failed"); + + if (lowerVerb === "virtualize") { + iconClass = "fa-compress"; + iconExtra = []; + label = "Virtualize"; + } else if (lowerVerb === "unvirtualize") { + iconClass = "fa-expand"; + iconExtra = []; + label = "Unvirtualize"; + } else if (lowerVerb === "dry_run_toggled") { + iconClass = "fa-toggle-on"; + iconExtra = ["text-muted"]; + label = "Dry-run toggled"; + } else if (lowerVerb === "reload_success") { + iconClass = "fa-refresh"; + iconExtra = ["text-success"]; + label = "Reload success"; + } else if (lowerVerb === "reload_skipped") { + iconClass = "fa-refresh"; + iconExtra = ["text-muted"]; + label = "Reload skipped"; + } else if (lowerVerb === "reload_failed") { + iconClass = "fa-refresh"; + iconExtra = ["text-danger"]; + label = "Reload failed"; + } else if (lowerVerb.startsWith("clear_virtual_override")) { + iconClass = "fa-eraser"; + iconExtra = ["text-warning"]; + label = "Clear virtual override"; + if (lowerVerb.endsWith("_conflict")) label += " (conflict)"; + if (lowerVerb.endsWith("_failed")) label += " failed"; + } else if (lowerVerb.startsWith("set_virtual_override")) { + iconClass = "fa-compress"; + iconExtra = isFailed ? ["text-danger"] : []; + label = isFailed ? "Set virtual override failed" : "Set virtual override"; + } else if (lowerVerb.startsWith("clear_sqm_overrides")) { + iconClass = "fa-eraser"; + iconExtra = ["text-warning"]; + label = "Clear SQM overrides"; + if (lowerVerb.endsWith("_conflict")) label += " (conflict)"; + } else if (lowerVerb === "set_sqm_override_failed") { + iconClass = "fa-exclamation-circle"; + iconExtra = ["text-danger"]; + label = "SQM override failed"; + } else if (lowerVerb === "apply_sqm_live_failed") { + iconClass = "fa-exclamation-circle"; + iconExtra = ["text-danger"]; + label = formatSqmLabel("SQM live apply failed", payload); + } else if (lowerVerb === "would_set_sqm_override") { + iconClass = "fa-eye"; + iconExtra = ["text-muted"]; + label = formatSqmLabel("Dry-run SQM override", payload); + } else if (lowerVerb === "set_sqm_override") { + if (payload.toLowerCase().includes("cake")) { + iconClass = "fa-birthday-cake"; + } else if (payload.toLowerCase().includes("fq_codel")) { + iconClass = "fa-tachometer"; + } else { + iconClass = "fa-sliders"; + } + iconExtra = []; + label = formatSqmLabel("SQM override", payload); + } else if (lowerVerb === "set_sqm_live") { + iconClass = "fa-bolt"; + iconExtra = []; + label = formatSqmLabel("SQM live apply", payload); + } else if (isFailed) { + iconClass = "fa-exclamation-circle"; + iconExtra = ["text-danger"]; + label = verb; + } + + return { raw, label, iconClass, iconExtra }; +} + +export class TreeGuardActivityDashlet extends BaseDashlet { + constructor(slot) { + super(slot); + this.size = 12; + this.circuitNameById = new Map(); + this.nodeIdByName = new Map(); + } + + title() { + return "TreeGuard Activity"; + } + + tooltip() { + return "
TreeGuard Activity

Recent TreeGuard actions, including dry-run entries and persisted changes.

"; + } + + subscribeTo() { + return ["TreeGuardActivity"]; + } + + setup() { + const wsClient = get_ws_client(); + const shapedWrapped = (msg) => { + wsClient.off("AllShapedDevices", shapedWrapped); + const devices = msg && Array.isArray(msg.data) ? msg.data : []; + devices.forEach((d) => { + const id = (d && d.circuit_id ? String(d.circuit_id) : "").trim(); + const name = (d && d.circuit_name ? String(d.circuit_name) : "").trim(); + if (!id || !name) return; + if (!this.circuitNameById.has(id)) { + this.circuitNameById.set(id, name); + } + }); + }; + wsClient.on("AllShapedDevices", shapedWrapped); + wsClient.send({ AllShapedDevices: {} }); + + const treeWrapped = (msg) => { + wsClient.off("NetworkTree", treeWrapped); + const data = msg && Array.isArray(msg.data) ? msg.data : []; + data.forEach((entry) => { + if (!Array.isArray(entry) || entry.length < 2) return; + const id = entry[0]; + const node = entry[1]; + const name = (node && node.name ? String(node.name) : "").trim(); + if (!name) return; + if (!this.nodeIdByName.has(name)) { + this.nodeIdByName.set(name, id); + } + }); + }; + wsClient.on("NetworkTree", treeWrapped); + wsClient.send({ NetworkTree: {} }); + } + + buildContainer() { + const base = super.buildContainer(); + const wrap = document.createElement("div"); + wrap.classList.add("p-2"); + + const table = document.createElement("table"); + table.classList.add("table", "table-sm", "table-striped", "mb-0", "small"); + + const thead = document.createElement("thead"); + thead.classList.add("small"); + const headRow = document.createElement("tr"); + ["Local Time", "Entity", "Action", "Persisted", "Reason"].forEach((header) => { + const th = document.createElement("th"); + th.textContent = header; + headRow.appendChild(th); + }); + thead.appendChild(headRow); + + this.tbody = document.createElement("tbody"); + table.appendChild(thead); + table.appendChild(this.tbody); + wrap.appendChild(table); + base.appendChild(wrap); + return base; + } + + onMessage(msg) { + if (msg.event !== "TreeGuardActivity") { + return; + } + + const entries = Array.isArray(msg.data) ? msg.data : []; + this.tbody.innerHTML = ""; + + if (entries.length === 0) { + const tr = document.createElement("tr"); + const td = document.createElement("td"); + td.colSpan = 5; + td.classList.add("text-muted"); + td.textContent = "No recent activity"; + tr.appendChild(td); + this.tbody.appendChild(tr); + return; + } + + entries.slice(0, 50).forEach((entry) => { + const tr = document.createElement("tr"); + tr.classList.add("small"); + + const tdTime = document.createElement("td"); + tdTime.textContent = formatUnixSecondsToLocalTime(entry.time); + + const tdEntity = document.createElement("td"); + const entityTypeRaw = (entry.entity_type ?? "").toString(); + const entityIdRaw = (entry.entity_id ?? "").toString(); + const entityType = entityTypeRaw.toLowerCase().trim(); + const entityId = entityIdRaw.trim(); + + const prefix = document.createElement("span"); + prefix.classList.add("text-muted"); + prefix.textContent = entityTypeRaw ? `${entityTypeRaw}: ` : ""; + tdEntity.appendChild(prefix); + + const mkLink = (href, text, title = "") => { + const a = document.createElement("a"); + a.href = href; + a.textContent = text; + a.classList.add("redactable"); + if (title) a.title = title; + return a; + }; + + if (entityType === "circuit" && entityId) { + const parsed = parseCircuitEntityId(entityId); + const circuitId = parsed.circuitId; + let display = parsed.display; + let title = parsed.hasName ? circuitId : ""; + if (!parsed.hasName && circuitId) { + const name = this.circuitNameById.get(circuitId); + if (name) { + display = name; + title = circuitId; + } + } + tdEntity.appendChild( + mkLink(`circuit.html?id=${encodeURIComponent(circuitId)}`, display, title), + ); + } else if (entityType === "node" && entityId) { + const nodeId = this.nodeIdByName.get(entityId); + if (nodeId !== undefined && nodeId !== null) { + tdEntity.appendChild( + mkLink( + `tree.html?parent=${encodeURIComponent(String(nodeId))}`, + entityId, + `Node ID: ${nodeId}`, + ), + ); + } else { + const span = document.createElement("span"); + span.textContent = entityId; + span.classList.add("redactable"); + tdEntity.appendChild(span); + } + } else { + const span = document.createElement("span"); + span.textContent = entityId || entityTypeRaw || ""; + span.classList.add("redactable"); + tdEntity.appendChild(span); + } + + const tdAction = document.createElement("td"); + const action = renderAction(entry.action); + tdAction.title = action.raw; + tdAction.appendChild(mkIcon(action.iconClass, action.iconExtra)); + const actionText = document.createElement("span"); + actionText.textContent = ` ${action.label}`; + tdAction.appendChild(actionText); + + const tdPersisted = document.createElement("td"); + tdPersisted.classList.add("text-center"); + const persisted = !!entry.persisted; + const persistedIcon = persisted + ? mkIcon("fa-check", ["text-success"]) + : mkIcon("fa-times", ["text-muted"]); + persistedIcon.setAttribute("aria-label", persisted ? "Persisted" : "Not persisted"); + persistedIcon.title = persisted ? "Persisted" : "Not persisted"; + tdPersisted.appendChild(persistedIcon); + + const tdReason = document.createElement("td"); + const reason = formatReason(entry.reason); + tdReason.textContent = reason.label; + if (reason.title) tdReason.title = reason.title; + + tr.appendChild(tdTime); + tr.appendChild(tdEntity); + tr.appendChild(tdAction); + tr.appendChild(tdPersisted); + tr.appendChild(tdReason); + this.tbody.appendChild(tr); + }); + } +} diff --git a/src/rust/lqosd/src/node_manager/js_build/src/dashlets/treeguard_controls.js b/src/rust/lqosd/src/node_manager/js_build/src/dashlets/treeguard_controls.js new file mode 100644 index 00000000..c4d672d1 --- /dev/null +++ b/src/rust/lqosd/src/node_manager/js_build/src/dashlets/treeguard_controls.js @@ -0,0 +1,167 @@ +import {loadConfig, saveConfig} from "../config/config_helper"; +import {defaultTreeguardConfig, ensureTreeguardConfig} from "../config/treeguard_defaults"; +import {BaseDashlet} from "../lq_js_common/dashboard/base_dashlet"; + +export class TreeguardControlsDashlet extends BaseDashlet { + constructor(slot) { + super(slot); + this.size = 6; + this.treeguard = defaultTreeguardConfig(); + this.isSaving = false; + } + + title() { + return "TreeGuard Controls"; + } + + tooltip() { + return "
TreeGuard Controls

Quick access to the default TreeGuard controls plus the current config-derived rollout status.

"; + } + + subscribeTo() { + return []; + } + + statusLineId() { + return `${this.id}_status`; + } + + controlsId() { + return `${this.id}_controls`; + } + + saveStateId() { + return `${this.id}_save_state`; + } + + enabledId() { + return `${this.id}_enabled`; + } + + dryRunId() { + return `${this.id}_dry_run`; + } + + buildContainer() { + const base = super.buildContainer(); + + const statusLine = document.createElement("div"); + statusLine.id = this.statusLineId(); + statusLine.className = "text-muted small mb-3"; + statusLine.innerText = "Loading TreeGuard status..."; + base.appendChild(statusLine); + + const controls = document.createElement("div"); + controls.id = this.controlsId(); + controls.className = "d-flex flex-column flex-md-row gap-3 align-items-start align-items-md-center"; + controls.innerHTML = ` +
+ + +
+
+ + +
+ `; + base.appendChild(controls); + + const saveState = document.createElement("div"); + saveState.id = this.saveStateId(); + saveState.className = "small mt-2 text-muted"; + base.appendChild(saveState); + + return base; + } + + setup() { + this.bindControls(); + this.refreshConfig(); + } + + bindControls() { + const enabled = document.getElementById(this.enabledId()); + const dryRun = document.getElementById(this.dryRunId()); + enabled.addEventListener("change", () => this.persistToggle("enabled", enabled.checked)); + dryRun.addEventListener("change", () => this.persistToggle("dry_run", dryRun.checked)); + } + + refreshConfig() { + this.setSaveState("Loading config...", false); + loadConfig( + () => { + this.treeguard = ensureTreeguardConfig(window.config); + this.syncControls(); + this.renderStatusLine(); + this.setSaveState("", false); + }, + () => { + this.treeguard = ensureTreeguardConfig(window.config || {}); + this.syncControls(); + this.renderStatusLine(); + this.setSaveState("Unable to refresh TreeGuard config.", true); + }, + ); + } + + syncControls() { + const enabled = document.getElementById(this.enabledId()); + const dryRun = document.getElementById(this.dryRunId()); + enabled.checked = !!this.treeguard.enabled; + dryRun.checked = !!this.treeguard.dry_run; + enabled.disabled = this.isSaving; + dryRun.disabled = this.isSaving; + } + + renderStatusLine() { + const statusLine = document.getElementById(this.statusLineId()); + const liveState = this.treeguard.dry_run ? "dry run" : "live"; + const mode = this.treeguard.cpu?.mode === "cpu_aware" ? "CPU-aware" : "Traffic/RTT only"; + const linkScope = this.treeguard.links?.all_nodes ? "all links" : "allowlisted links"; + const circuitScope = this.treeguard.circuits?.all_circuits ? "all circuits" : "allowlisted circuits"; + const enabled = this.treeguard.enabled ? "Enabled" : "Disabled"; + statusLine.innerHTML = ` + Status: ${enabled}, ${liveState}, ${mode}, ${linkScope}, ${circuitScope}. + Open configuration + `; + } + + persistToggle(field, nextValue) { + const previousValue = this.treeguard[field]; + this.treeguard[field] = nextValue; + window.config = window.config || {}; + window.config.treeguard = ensureTreeguardConfig(window.config); + window.config.treeguard[field] = nextValue; + this.isSaving = true; + this.syncControls(); + this.renderStatusLine(); + this.setSaveState("Saving...", false); + + saveConfig( + () => { + this.isSaving = false; + this.syncControls(); + this.renderStatusLine(); + this.setSaveState("Saved.", false); + }, + () => { + this.treeguard[field] = previousValue; + window.config.treeguard[field] = previousValue; + this.isSaving = false; + this.syncControls(); + this.renderStatusLine(); + this.setSaveState("Save failed.", true); + }, + ); + } + + setSaveState(message, isError) { + const saveState = document.getElementById(this.saveStateId()); + if (!saveState) { + return; + } + saveState.innerText = message; + saveState.classList.toggle("text-danger", !!message && isError); + saveState.classList.toggle("text-muted", !message || !isError); + } +} diff --git a/src/rust/lqosd/src/node_manager/js_build/src/dashlets/treeguard_status.js b/src/rust/lqosd/src/node_manager/js_build/src/dashlets/treeguard_status.js index f9bd0357..9a0870dc 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/dashlets/treeguard_status.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/dashlets/treeguard_status.js @@ -1,166 +1,420 @@ -import {loadConfig, saveConfig} from "../config/config_helper"; -import {defaultTreeguardConfig, ensureTreeguardConfig} from "../config/treeguard_defaults"; import {BaseDashlet} from "../lq_js_common/dashboard/base_dashlet"; +import {get_ws_client} from "../pubsub/ws"; -export class TreeguardStatusDashlet extends BaseDashlet { +function clamp(n, min, max) { + return Math.min(Math.max(n, min), max); +} + +function splitOnce(s, sep) { + const str = (s ?? "").toString(); + const idx = str.indexOf(sep); + if (idx === -1) return [str, ""]; + return [str.slice(0, idx), str.slice(idx + sep.length)]; +} + +function parseDirectionalSqmToken(token) { + const t = (token ?? "").toString().trim(); + if (!t) return { down: "", up: "" }; + if (!t.includes("/")) return { down: t, up: t }; + const [down, up] = splitOnce(t, "/"); + return { down: (down ?? "").toString().trim(), up: (up ?? "").toString().trim() }; +} + +function formatSqmLabel(token) { + const { down, up } = parseDirectionalSqmToken(token); + if (!down && !up) return ""; + if (down === up) return down; + return `DL ${down}, UL ${up}`; +} + +function mkIcon(iconClass, extraClasses = []) { + const icon = document.createElement("i"); + icon.classList.add("fa", "fa-fw", iconClass); + extraClasses.forEach((c) => icon.classList.add(c)); + return icon; +} + +function setBgClass(el, cls) { + [ + "bg-primary", + "bg-secondary", + "bg-success", + "bg-info", + "bg-warning", + "bg-danger", + "bg-light", + "bg-dark", + ].forEach((c) => el.classList.remove(c)); + if (cls) el.classList.add(cls); +} + +function mkProgressMetric() { + const container = document.createElement("div"); + container.classList.add("d-flex", "align-items-center", "gap-2"); + + const progress = document.createElement("div"); + progress.classList.add("progress", "flex-grow-1"); + progress.style.height = "0.6rem"; + + const bar = document.createElement("div"); + bar.classList.add("progress-bar"); + bar.setAttribute("role", "progressbar"); + bar.style.width = "0%"; + progress.appendChild(bar); + + const text = document.createElement("span"); + text.classList.add("small"); + text.textContent = "—"; + + container.appendChild(progress); + container.appendChild(text); + + return { container, progress, bar, text }; +} + +function updateProgressMetric(metric, { value, max, text, bgClass, title }) { + const safeMax = Number.isFinite(max) && max > 0 ? max : 1; + const safeValue = Number.isFinite(value) ? value : 0; + const pct = clamp((safeValue / safeMax) * 100.0, 0, 100); + + metric.bar.style.width = `${pct.toFixed(1)}%`; + metric.bar.setAttribute("aria-valuemin", "0"); + metric.bar.setAttribute("aria-valuemax", safeMax.toString()); + metric.bar.setAttribute("aria-valuenow", safeValue.toString()); + setBgClass(metric.bar, bgClass); + + metric.text.textContent = text ?? "—"; + metric.container.title = title ?? ""; +} + +function renderLastAction(summaryRaw) { + const raw = (summaryRaw ?? "").toString().trim(); + + const wrap = document.createElement("div"); + wrap.classList.add("d-flex", "align-items-start", "gap-2"); + wrap.style.whiteSpace = "normal"; + wrap.style.wordBreak = "break-word"; + + if (!raw) { + wrap.appendChild(mkIcon("fa-minus-circle", ["text-muted"])); + const span = document.createElement("span"); + span.textContent = "—"; + wrap.appendChild(span); + return wrap; + } + + wrap.title = raw; + + let iconClass = "fa-info-circle"; + let iconExtra = ["text-muted"]; + let label = raw; + + let m = raw.match(/^Reloaded LibreQoS:\s*(.+)$/); + if (m) { + iconClass = "fa-refresh"; + iconExtra = ["text-success"]; + label = `Reloaded LibreQoS: ${m[1]}`; + } + + m = raw.match(/^(Virtualized|Unvirtualized) node '(.+)'$/); + if (m) { + iconClass = m[1] === "Virtualized" ? "fa-compress" : "fa-expand"; + iconExtra = []; + label = `${m[1]} node: ${m[2]}`; + } + + m = raw.match(/^Would set SQM override for circuit '(.+)' -> (.+)$/); + if (m) { + iconClass = "fa-eye"; + iconExtra = ["text-muted"]; + const tokenLabel = formatSqmLabel(m[2]); + label = tokenLabel + ? `Dry-run SQM override: ${m[1]} → ${tokenLabel}` + : `Dry-run SQM override: ${m[1]}`; + } + + m = raw.match(/^SQM override for circuit '(.+)' -> (.+)$/); + if (m) { + const token = (m[2] ?? "").toString(); + const tokenLower = token.toLowerCase(); + if (tokenLower.includes("cake")) { + iconClass = "fa-birthday-cake"; + iconExtra = []; + } else if (tokenLower.includes("fq_codel")) { + iconClass = "fa-tachometer"; + iconExtra = []; + } else { + iconClass = "fa-sliders"; + iconExtra = []; + } + const tokenLabel = formatSqmLabel(token); + label = tokenLabel ? `SQM override: ${m[1]} → ${tokenLabel}` : `SQM override: ${m[1]}`; + } + + wrap.appendChild(mkIcon(iconClass, iconExtra)); + const span = document.createElement("span"); + span.textContent = label; + wrap.appendChild(span); + return wrap; +} + +export class TreeGuardStatusDashlet extends BaseDashlet { constructor(slot) { super(slot); - this.treeguard = defaultTreeguardConfig(); - this.isSaving = false; + this.size = 6; + this.totalNodes = null; + this.totalCircuits = null; + this.estimatedVirtualizedNodes = null; + this.estimatedFqCodelCircuits = null; + this.lastStatusData = null; } title() { - return "TreeGuard"; + return "TreeGuard Status"; } tooltip() { - return "
TreeGuard

Quick access to the default TreeGuard controls plus the current config-derived rollout status.

"; + return "
TreeGuard Status

Shows TreeGuard enablement, dry-run state, CPU pressure, managed allowlists, current virtualization/SQM states, and warnings.

"; } subscribeTo() { - return []; + return ["TreeGuardStatus"]; } - statusLineId() { - return `${this.id}_status`; - } + setup() { + const wsClient = get_ws_client(); - controlsId() { - return `${this.id}_controls`; - } + const treeWrapped = (msg) => { + wsClient.off("NetworkTree", treeWrapped); + const data = msg && Array.isArray(msg.data) ? msg.data : []; + let count = 0; + let virtualCount = 0; + data.forEach((entry) => { + if (!Array.isArray(entry) || entry.length < 2) return; + const node = entry[1]; + const name = (node && node.name ? String(node.name) : "").trim(); + if (!name || name === "Root") return; + count += 1; + if (node && (node.virtual === true || node.is_virtual === true)) { + virtualCount += 1; + } + }); + this.totalNodes = count; + this.estimatedVirtualizedNodes = virtualCount; + this.rerenderWithEstimates(); + }; + wsClient.on("NetworkTree", treeWrapped); + wsClient.send({ NetworkTree: {} }); - saveStateId() { - return `${this.id}_save_state`; - } + const shapedWrapped = (msg) => { + wsClient.off("AllShapedDevices", shapedWrapped); + const devices = msg && Array.isArray(msg.data) ? msg.data : []; + const circuits = new Set(); + const fqCodelCircuits = new Set(); + devices.forEach((d) => { + const id = (d && d.circuit_id ? String(d.circuit_id) : "").trim(); + if (id) circuits.add(id); - enabledId() { - return `${this.id}_enabled`; + const override = (d && d.sqm_override !== undefined ? String(d.sqm_override) : "").trim(); + if (!override || !id) return; + const { down, up } = parseDirectionalSqmToken(override); + const downLower = (down ?? "").toString().trim().toLowerCase(); + const upLower = (up ?? "").toString().trim().toLowerCase(); + if (downLower === "fq_codel" || upLower === "fq_codel") { + fqCodelCircuits.add(id); + } + }); + this.totalCircuits = circuits.size; + this.estimatedFqCodelCircuits = fqCodelCircuits.size; + this.rerenderWithEstimates(); + }; + wsClient.on("AllShapedDevices", shapedWrapped); + wsClient.send({ AllShapedDevices: {} }); } - dryRunId() { - return `${this.id}_dry_run`; + rerenderWithEstimates() { + if (this.lastStatusData) { + this.renderStatus(this.lastStatusData); + } } buildContainer() { const base = super.buildContainer(); + const wrap = document.createElement("div"); + wrap.classList.add("p-2"); + + const table = document.createElement("table"); + table.classList.add("table", "table-sm", "mb-2"); + const tbody = document.createElement("tbody"); + + const mkRow = (label, valueEl) => { + const tr = document.createElement("tr"); + const tdL = document.createElement("td"); + tdL.classList.add("text-muted"); + tdL.style.width = "45%"; + tdL.textContent = label; + const tdV = document.createElement("td"); + tdV.appendChild(valueEl); + tr.appendChild(tdL); + tr.appendChild(tdV); + return tr; + }; + + this.enabledEl = document.createElement("span"); + this.dryRunEl = document.createElement("span"); + this.cpuMetric = mkProgressMetric(); + this.nodesMetric = mkProgressMetric(); + this.circuitsMetric = mkProgressMetric(); + this.virtualizedMetric = mkProgressMetric(); + this.fqCodelMetric = mkProgressMetric(); + this.lastActionEl = document.createElement("div"); + this.lastActionEl.classList.add("small"); + + tbody.appendChild(mkRow("Enabled", this.enabledEl)); + tbody.appendChild(mkRow("Dry Run", this.dryRunEl)); + tbody.appendChild(mkRow("CPU Max", this.cpuMetric.container)); + tbody.appendChild(mkRow("Managed Nodes", this.nodesMetric.container)); + tbody.appendChild(mkRow("Managed Circuits", this.circuitsMetric.container)); + tbody.appendChild(mkRow("Virtualized Nodes", this.virtualizedMetric.container)); + tbody.appendChild(mkRow("fq_codel Circuits", this.fqCodelMetric.container)); + tbody.appendChild(mkRow("Last Action", this.lastActionEl)); + + table.appendChild(tbody); + wrap.appendChild(table); + + const warningsHeader = document.createElement("div"); + warningsHeader.classList.add("text-muted", "small", "mb-1"); + warningsHeader.textContent = "Warnings"; + wrap.appendChild(warningsHeader); - const statusLine = document.createElement("div"); - statusLine.id = this.statusLineId(); - statusLine.className = "text-muted small mb-3"; - statusLine.innerText = "Loading TreeGuard status..."; - base.appendChild(statusLine); - - const controls = document.createElement("div"); - controls.id = this.controlsId(); - controls.className = "d-flex flex-column flex-md-row gap-3 align-items-start align-items-md-center"; - controls.innerHTML = ` -
- - -
-
- - -
- `; - base.appendChild(controls); - - const saveState = document.createElement("div"); - saveState.id = this.saveStateId(); - saveState.className = "small mt-2 text-muted"; - base.appendChild(saveState); + this.warningsEl = document.createElement("div"); + this.warningsEl.classList.add("small"); + wrap.appendChild(this.warningsEl); + base.appendChild(wrap); return base; } - setup() { - this.bindControls(); - this.refreshConfig(); - } + onMessage(msg) { + if (msg.event !== "TreeGuardStatus") { + return; + } - bindControls() { - const enabled = document.getElementById(this.enabledId()); - const dryRun = document.getElementById(this.dryRunId()); - enabled.addEventListener("change", () => this.persistToggle("enabled", enabled.checked)); - dryRun.addEventListener("change", () => this.persistToggle("dry_run", dryRun.checked)); + const data = msg.data || {}; + this.lastStatusData = data; + this.renderStatus(data); } - refreshConfig() { - this.setSaveState("Loading config...", false); - loadConfig( - () => { - this.treeguard = ensureTreeguardConfig(window.config); - this.syncControls(); - this.renderStatusLine(); - this.setSaveState("", false); - }, - () => { - this.treeguard = ensureTreeguardConfig(window.config || {}); - this.syncControls(); - this.renderStatusLine(); - this.setSaveState("Unable to refresh TreeGuard config.", true); - }, - ); - } + renderStatus(data) { + this.enabledEl.textContent = data.enabled ? "Yes" : "No"; + this.dryRunEl.textContent = data.dry_run ? "Yes" : "No"; - syncControls() { - const enabled = document.getElementById(this.enabledId()); - const dryRun = document.getElementById(this.dryRunId()); - enabled.checked = !!this.treeguard.enabled; - dryRun.checked = !!this.treeguard.dry_run; - enabled.disabled = this.isSaving; - dryRun.disabled = this.isSaving; - } + const cpuRaw = data.cpu_max_pct; + if (cpuRaw === null || cpuRaw === undefined) { + updateProgressMetric(this.cpuMetric, { + value: 0, + max: 100, + text: "N/A", + bgClass: "bg-secondary", + title: "CPU usage unavailable", + }); + } else { + const cpu = clamp(Number(cpuRaw), 0, 100); + const bg = cpu >= 90 ? "bg-danger" : cpu >= 70 ? "bg-warning" : "bg-success"; + updateProgressMetric(this.cpuMetric, { + value: cpu, + max: 100, + text: `${cpu.toFixed(0)}%`, + bgClass: bg, + title: `CPU max: ${cpu.toFixed(0)}%`, + }); + } - renderStatusLine() { - const statusLine = document.getElementById(this.statusLineId()); - const liveState = this.treeguard.dry_run ? "dry run" : "live"; - const mode = this.treeguard.cpu?.mode === "cpu_aware" ? "CPU-aware" : "Traffic/RTT only"; - const linkScope = this.treeguard.links?.all_nodes ? "all links" : "allowlisted links"; - const circuitScope = this.treeguard.circuits?.all_circuits ? "all circuits" : "allowlisted circuits"; - const enabled = this.treeguard.enabled ? "Enabled" : "Disabled"; - statusLine.innerHTML = ` - Status: ${enabled}, ${liveState}, ${mode}, ${linkScope}, ${circuitScope}. - Open configuration - `; - } + const managedNodes = Math.max(0, Math.trunc(Number(data.managed_nodes ?? 0) || 0)); + const managedCircuits = Math.max(0, Math.trunc(Number(data.managed_circuits ?? 0) || 0)); + const virtualizedNodesExact = Math.max(0, Math.trunc(Number(data.virtualized_nodes ?? 0) || 0)); + const fqCodelCircuitsExact = Math.max(0, Math.trunc(Number(data.fq_codel_circuits ?? 0) || 0)); - persistToggle(field, nextValue) { - const previousValue = this.treeguard[field]; - this.treeguard[field] = nextValue; - window.config = window.config || {}; - window.config.treeguard = ensureTreeguardConfig(window.config); - window.config.treeguard[field] = nextValue; - this.isSaving = true; - this.syncControls(); - this.renderStatusLine(); - this.setSaveState("Saving...", false); - - saveConfig( - () => { - this.isSaving = false; - this.syncControls(); - this.renderStatusLine(); - this.setSaveState("Saved.", false); - }, - () => { - this.treeguard[field] = previousValue; - window.config.treeguard[field] = previousValue; - this.isSaving = false; - this.syncControls(); - this.renderStatusLine(); - this.setSaveState("Save failed.", true); - }, - ); - } + const virtualizedEstimate = Math.max(0, Math.trunc(Number(this.estimatedVirtualizedNodes ?? 0) || 0)); + const fqCodelEstimate = Math.max(0, Math.trunc(Number(this.estimatedFqCodelCircuits ?? 0) || 0)); - setSaveState(message, isError) { - const saveState = document.getElementById(this.saveStateId()); - if (!saveState) { + const usingVirtualEstimate = virtualizedNodesExact === 0 && virtualizedEstimate > 0; + const usingFqCodelEstimate = fqCodelCircuitsExact === 0 && fqCodelEstimate > 0; + + const virtualizedNodes = usingVirtualEstimate ? virtualizedEstimate : virtualizedNodesExact; + const fqCodelCircuits = usingFqCodelEstimate ? fqCodelEstimate : fqCodelCircuitsExact; + + const totalNodes = Number(this.totalNodes ?? 0); + const nodesMax = totalNodes > 0 ? totalNodes : Math.max(1, managedNodes); + const nodesPct = nodesMax ? clamp((managedNodes / nodesMax) * 100, 0, 100) : 0; + updateProgressMetric(this.nodesMetric, { + value: managedNodes, + max: nodesMax, + text: managedNodes.toString(), + bgClass: "bg-info", + title: totalNodes > 0 ? `${managedNodes} / ${totalNodes} (${nodesPct.toFixed(0)}%)` : `${managedNodes}`, + }); + + const totalCircuits = Number(this.totalCircuits ?? 0); + const circuitsMax = totalCircuits > 0 ? totalCircuits : Math.max(1, managedCircuits); + const circuitsPct = circuitsMax ? clamp((managedCircuits / circuitsMax) * 100, 0, 100) : 0; + updateProgressMetric(this.circuitsMetric, { + value: managedCircuits, + max: circuitsMax, + text: managedCircuits.toString(), + bgClass: "bg-info", + title: totalCircuits > 0 + ? `${managedCircuits} / ${totalCircuits} (${circuitsPct.toFixed(0)}%)` + : `${managedCircuits}`, + }); + + const virtMax = Math.max(1, managedNodes); + const virtPct = managedNodes > 0 ? clamp((virtualizedNodes / virtMax) * 100, 0, 100) : 0; + updateProgressMetric(this.virtualizedMetric, { + value: virtualizedNodes, + max: virtMax, + text: usingVirtualEstimate ? `≈${virtualizedNodes}` : virtualizedNodes.toString(), + bgClass: "bg-primary", + title: (() => { + const core = managedNodes > 0 + ? `${virtualizedNodes} / ${managedNodes} (${virtPct.toFixed(0)}%)` + : `${virtualizedNodes}`; + return usingVirtualEstimate ? `Estimated from NetworkTree snapshot: ${core}` : core; + })(), + }); + + const fqMax = Math.max(1, managedCircuits); + const fqPct = managedCircuits > 0 ? clamp((fqCodelCircuits / fqMax) * 100, 0, 100) : 0; + updateProgressMetric(this.fqCodelMetric, { + value: fqCodelCircuits, + max: fqMax, + text: usingFqCodelEstimate ? `≈${fqCodelCircuits}` : fqCodelCircuits.toString(), + bgClass: "bg-warning", + title: (() => { + const core = managedCircuits > 0 + ? `${fqCodelCircuits} / ${managedCircuits} (${fqPct.toFixed(0)}%)` + : `${fqCodelCircuits}`; + return usingFqCodelEstimate ? `Estimated from ShapedDevices SQM overrides: ${core}` : core; + })(), + }); + + this.lastActionEl.innerHTML = ""; + this.lastActionEl.appendChild(renderLastAction(data.last_action_summary)); + + const warnings = Array.isArray(data.warnings) ? data.warnings : []; + if (warnings.length === 0) { + this.warningsEl.textContent = "—"; return; } - saveState.innerText = message; - saveState.classList.toggle("text-danger", !!message && isError); - saveState.classList.toggle("text-muted", !message || !isError); + + const ul = document.createElement("ul"); + ul.classList.add("mb-0"); + warnings.slice(0, 8).forEach((warning) => { + const li = document.createElement("li"); + li.textContent = warning; + ul.appendChild(li); + }); + this.warningsEl.innerHTML = ""; + this.warningsEl.appendChild(ul); } } diff --git a/src/rust/lqosd/src/node_manager/js_build/src/index.js b/src/rust/lqosd/src/node_manager/js_build/src/index.js index d3c80254..03e58ea6 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/index.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/index.js @@ -75,7 +75,9 @@ const defaultLayout = { { name: "TreeGuard", dashlets: [ - { tag: "treeguardStatus", size: 12 } + { tag: "treeguardControls", size: 6 }, + { tag: "treeguardStatus", size: 6 }, + { tag: "treeguardActivity", size: 12 } ] } ] -- knotmirror 0.0.1 From c55ac0c7a38d86f4cd680281d3b9aabb21b828ec Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Mon, 9 Mar 2026 14:33:02 -0500 Subject: [PATCH 3/5] Feat: restore TreeGuard runtime backend --- src/rust/Cargo.lock | 1 + src/rust/lqos_overrides/src/lib.rs | 3 +- src/rust/lqos_overrides/src/overrides_file.rs | 390 +++- src/rust/lqos_python/src/lib.rs | 101 + src/rust/lqosd/Cargo.toml | 1 + src/rust/lqosd/src/main.rs | 7 + src/rust/lqosd/src/node_manager.rs | 2 +- .../lqosd/src/node_manager/ws/messages.rs | 29 + .../src/node_manager/ws/published_channels.rs | 2 + src/rust/lqosd/src/node_manager/ws/ticker.rs | 9 + .../src/node_manager/ws/ticker/treeguard.rs | 33 + src/rust/lqosd/src/reload_lock.rs | 37 + src/rust/lqosd/src/treeguard/actor.rs | 1898 +++++++++++++++++ src/rust/lqosd/src/treeguard/bakery.rs | 118 + src/rust/lqosd/src/treeguard/decisions.rs | 783 +++++++ src/rust/lqosd/src/treeguard/errors.rs | 39 + src/rust/lqosd/src/treeguard/mod.rs | 17 + src/rust/lqosd/src/treeguard/overrides.rs | 141 ++ src/rust/lqosd/src/treeguard/reload.rs | 219 ++ src/rust/lqosd/src/treeguard/state.rs | 163 ++ src/rust/lqosd/src/treeguard/status.rs | 71 + src/scheduler.py | 4 +- 22 files changed, 4026 insertions(+), 42 deletions(-) create mode 100644 src/rust/lqosd/src/node_manager/ws/ticker/treeguard.rs create mode 100644 src/rust/lqosd/src/reload_lock.rs create mode 100644 src/rust/lqosd/src/treeguard/actor.rs create mode 100644 src/rust/lqosd/src/treeguard/bakery.rs create mode 100644 src/rust/lqosd/src/treeguard/decisions.rs create mode 100644 src/rust/lqosd/src/treeguard/errors.rs create mode 100644 src/rust/lqosd/src/treeguard/mod.rs create mode 100644 src/rust/lqosd/src/treeguard/overrides.rs create mode 100644 src/rust/lqosd/src/treeguard/reload.rs create mode 100644 src/rust/lqosd/src/treeguard/state.rs create mode 100644 src/rust/lqosd/src/treeguard/status.rs diff --git a/src/rust/Cargo.lock b/src/rust/Cargo.lock index 1d5a2903..9943e969 100644 --- a/src/rust/Cargo.lock +++ b/src/rust/Cargo.lock @@ -2250,6 +2250,7 @@ dependencies = [ "strum", "surge-ping", "sysinfo", + "thiserror 1.0.69", "timerfd", "tokio", "tokio-tungstenite 0.28.0", diff --git a/src/rust/lqos_overrides/src/lib.rs b/src/rust/lqos_overrides/src/lib.rs index eb1ddc26..787fbcde 100644 --- a/src/rust/lqos_overrides/src/lib.rs +++ b/src/rust/lqos_overrides/src/lib.rs @@ -1,4 +1,5 @@ mod overrides_file; pub use overrides_file::{ - CircuitAdjustment, NetworkAdjustment, OverrideFile, UispOverrides, UispRouteOverride, + CircuitAdjustment, NetworkAdjustment, OverrideFile, OverrideLayer, OverrideStore, + UispOverrides, UispRouteOverride, }; diff --git a/src/rust/lqos_overrides/src/overrides_file.rs b/src/rust/lqos_overrides/src/overrides_file.rs index 0c305139..324ec72a 100644 --- a/src/rust/lqos_overrides/src/overrides_file.rs +++ b/src/rust/lqos_overrides/src/overrides_file.rs @@ -1,13 +1,32 @@ -use std::{fs::read_to_string, path::Path}; +use std::{ + fs::read_to_string, + 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; mod file_lock; +const OPERATOR_OVERRIDES_FILE: &str = "lqos_overrides.json"; +const TREEGUARD_OVERRIDES_FILE: &str = "lqos_overrides.treeguard.json"; +const LEGACY_AUTOPILOT_OVERRIDES_FILE: &str = "lqos_overrides.autopilot.json"; + +/// Selects which overrides file to load/save. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum OverrideLayer { + /// Operator-owned overrides (`lqos_overrides.json`). + Operator, + /// TreeGuard-owned overrides (`lqos_overrides.treeguard.json`). + Treeguard, +} + +/// Helper for working with layered override files. +pub struct OverrideStore; + #[derive(Serialize, Deserialize, Clone, Debug)] #[serde(tag = "type", rename_all = "snake_case")] pub enum CircuitAdjustment { @@ -25,16 +44,9 @@ 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)] @@ -88,19 +100,189 @@ pub struct OverrideFile { uisp: Option, } +fn overrides_path(config: &lqos_config::Config, layer: OverrideLayer) -> PathBuf { + let file = match layer { + OverrideLayer::Operator => OPERATOR_OVERRIDES_FILE, + OverrideLayer::Treeguard => TREEGUARD_OVERRIDES_FILE, + }; + Path::new(&config.lqos_directory).join(file) +} + +fn treeguard_read_path(config: &lqos_config::Config) -> PathBuf { + let canonical = Path::new(&config.lqos_directory).join(TREEGUARD_OVERRIDES_FILE); + if canonical.exists() { + return canonical; + } + let legacy = Path::new(&config.lqos_directory).join(LEGACY_AUTOPILOT_OVERRIDES_FILE); + if legacy.exists() { + legacy + } else { + canonical + } +} + +fn load_from_path(path: &Path) -> Result { + let raw = read_to_string(path)?; + let as_json = serde_json::from_str(&raw)?; + Ok(as_json) +} + +fn ensure_exists_default(path: &Path) -> Result<()> { + if path.exists() { + return Ok(()); + } + // Create a default empty file + let new_override_file = OverrideFile::default(); + let as_json = serde_json::to_string(&new_override_file)?; + std::fs::write(path, as_json.as_bytes())?; + Ok(()) +} + +fn save_to_path(path: &Path, overrides: &OverrideFile) -> Result<()> { + let as_json = serde_json::to_string_pretty(overrides)?; + std::fs::write(path, as_json.as_bytes())?; + Ok(()) +} + +fn merge_persistent_devices_by_id( + operator_devices: &[ShapedDevice], + treeguard_devices: &[ShapedDevice], +) -> Vec { + use std::collections::{HashMap, HashSet}; + + let mut by_id: HashMap<&str, ShapedDevice> = HashMap::new(); + for dev in operator_devices { + by_id.insert(dev.device_id.as_str(), dev.clone()); + } + for dev in treeguard_devices { + by_id.insert(dev.device_id.as_str(), dev.clone()); + } + + let mut out = Vec::new(); + let mut seen: HashSet<&str> = HashSet::new(); + + for dev in operator_devices { + let did = dev.device_id.as_str(); + if seen.contains(did) { + continue; + } + if let Some(merged) = by_id.get(did) { + out.push(merged.clone()); + seen.insert(did); + } + } + + for dev in treeguard_devices { + let did = dev.device_id.as_str(); + if seen.contains(did) { + continue; + } + if let Some(merged) = by_id.get(did) { + out.push(merged.clone()); + seen.insert(did); + } + } + + out +} + +fn merge_network_adjustments_owned( + operator_adjustments: &[NetworkAdjustment], + treeguard_adjustments: &[NetworkAdjustment], +) -> Vec { + use std::collections::{HashMap, HashSet}; + + let mut treeguard_virtual: HashMap<&str, bool> = HashMap::new(); + let mut treeguard_virtual_order: Vec<&str> = Vec::new(); + let mut treeguard_virtual_seen: HashSet<&str> = HashSet::new(); + + for adj in treeguard_adjustments { + if let NetworkAdjustment::SetNodeVirtual { + node_name, + virtual_node, + } = adj + { + let name = node_name.as_str(); + treeguard_virtual.insert(name, *virtual_node); + if !treeguard_virtual_seen.contains(name) { + treeguard_virtual_order.push(name); + treeguard_virtual_seen.insert(name); + } + } + } + + let mut out = Vec::new(); + let mut used_treeguard_virtual: HashSet<&str> = HashSet::new(); + let mut operator_virtual_seen: HashSet<&str> = HashSet::new(); + + for adj in operator_adjustments { + match adj { + NetworkAdjustment::SetNodeVirtual { + node_name, + virtual_node, + } => { + let name = node_name.as_str(); + if operator_virtual_seen.contains(name) { + continue; + } + operator_virtual_seen.insert(name); + + if let Some(v) = treeguard_virtual.get(name) { + out.push(NetworkAdjustment::SetNodeVirtual { + node_name: node_name.clone(), + virtual_node: *v, + }); + used_treeguard_virtual.insert(name); + } else { + out.push(NetworkAdjustment::SetNodeVirtual { + node_name: node_name.clone(), + virtual_node: *virtual_node, + }); + } + } + NetworkAdjustment::AdjustSiteSpeed { .. } => { + // Operator-only. Preserve as-is. + out.push(adj.clone()); + } + } + } + + // Append TreeGuard-only virtual-node entries (ignore other network adjustments). + for name in treeguard_virtual_order { + if used_treeguard_virtual.contains(name) { + continue; + } + let Some(v) = treeguard_virtual.get(name) else { + continue; + }; + out.push(NetworkAdjustment::SetNodeVirtual { + node_name: name.to_string(), + virtual_node: *v, + }); + } + + out +} + +fn merge_owned_sections(mut operator: OverrideFile, treeguard: OverrideFile) -> OverrideFile { + let operator_devices = std::mem::take(&mut operator.persistent_devices); + operator.persistent_devices = + merge_persistent_devices_by_id(&operator_devices, &treeguard.persistent_devices); + + let operator_network = std::mem::take(&mut operator.network_adjustments); + operator.network_adjustments = + merge_network_adjustments_owned(&operator_network, &treeguard.network_adjustments); + + operator +} + impl OverrideFile { pub fn load() -> Result { let lock = FileLock::new()?; let config = lqos_config::load_config()?; - let path = Path::new(&config.lqos_directory).join("lqos_overrides.json"); - if !path.exists() { - // Create a default empty file - let new_override_file = OverrideFile::default(); - let as_json = serde_json::to_string(&new_override_file)?; - std::fs::write(&path, as_json.as_bytes())?; - } - let raw = read_to_string(path)?; - let as_json = serde_json::from_str(&raw)?; + let path = overrides_path(&config, OverrideLayer::Operator); + ensure_exists_default(&path)?; + let as_json = load_from_path(&path)?; drop(lock); // Explicitly drop for clarity. RAII does it anyway. Ok(as_json) } @@ -108,9 +290,8 @@ impl OverrideFile { pub fn save(&self) -> Result<()> { let lock = FileLock::new()?; let config = lqos_config::load_config()?; - let path = Path::new(&config.lqos_directory).join("lqos_overrides.json"); - let as_json = serde_json::to_string_pretty(self)?; - std::fs::write(&path, as_json.as_bytes())?; + let path = overrides_path(&config, OverrideLayer::Operator); + save_to_path(&path, self)?; drop(lock); // Explicitly drop for clarity. RAII does it anyway. Ok(()) } @@ -163,7 +344,6 @@ impl OverrideFile { .count(); if excluded { - // Already excluded exactly once -> idempotent no-op. if matches == 1 { return false; } @@ -208,7 +388,8 @@ 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()) } @@ -237,11 +418,10 @@ 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. @@ -282,11 +462,7 @@ 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 { @@ -299,9 +475,148 @@ impl OverrideFile { } } +impl OverrideStore { + /// Loads a single overrides layer. + /// + /// Side effects: acquires the global overrides lock and may create the operator overrides file. + pub fn load_layer(layer: OverrideLayer) -> Result { + let lock = FileLock::new()?; + let config = lqos_config::load_config()?; + let path = match layer { + OverrideLayer::Operator => overrides_path(&config, layer), + OverrideLayer::Treeguard => treeguard_read_path(&config), + }; + let overrides = match layer { + OverrideLayer::Operator => { + ensure_exists_default(&path)?; + load_from_path(&path)? + } + OverrideLayer::Treeguard => { + if !path.exists() { + OverrideFile::default() + } else { + load_from_path(&path)? + } + } + }; + drop(lock); + Ok(overrides) + } + + /// Saves a single overrides layer. + /// + /// Side effects: acquires the global overrides lock and writes the selected overrides file. + pub fn save_layer(layer: OverrideLayer, overrides: &OverrideFile) -> Result<()> { + let lock = FileLock::new()?; + let config = lqos_config::load_config()?; + let path = overrides_path(&config, layer); + save_to_path(&path, overrides)?; + drop(lock); + Ok(()) + } + + /// Loads the effective overrides view used during shaping. + /// + /// When `apply_treeguard` is false, this is equivalent to loading the operator layer only. + /// + /// Side effects: acquires the global overrides lock and may create the operator overrides file. + pub fn load_effective(apply_treeguard: bool) -> Result { + let lock = FileLock::new()?; + let config = lqos_config::load_config()?; + + let operator_path = overrides_path(&config, OverrideLayer::Operator); + ensure_exists_default(&operator_path)?; + let operator = load_from_path(&operator_path)?; + + if !apply_treeguard { + drop(lock); + return Ok(operator); + } + + let treeguard_path = treeguard_read_path(&config); + let treeguard = if !treeguard_path.exists() { + OverrideFile::default() + } else { + load_from_path(&treeguard_path)? + }; + + let merged = merge_owned_sections(operator, treeguard); + drop(lock); + Ok(merged) + } +} + #[cfg(test)] mod tests { - use super::OverrideFile; + use super::*; + + fn shaped_device_with_sqm(device_id: &str, sqm: &str) -> ShapedDevice { + let mut dev = ShapedDevice::default(); + dev.device_id = device_id.to_string(); + dev.sqm_override = Some(sqm.to_string()); + dev + } + + #[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")); + + let mut treeguard = OverrideFile::default(); + treeguard + .add_persistent_shaped_device_return_changed(shaped_device_with_sqm("dev1", "fq_codel")); + treeguard + .add_persistent_shaped_device_return_changed(shaped_device_with_sqm("dev3", "fq_codel")); + + let merged = merge_owned_sections(operator, treeguard); + 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))) + .collect(); + + assert_eq!(sqm_by_id.get("dev1"), Some(&"fq_codel")); + assert_eq!(sqm_by_id.get("dev2"), Some(&"cake")); + assert_eq!(sqm_by_id.get("dev3"), Some(&"fq_codel")); + } + + #[test] + fn effective_merge_treeguard_wins_for_node_virtual_only() { + let mut operator = OverrideFile::default(); + operator.set_network_node_virtual("NodeA".to_string(), false); + operator.add_network_adjustment(NetworkAdjustment::AdjustSiteSpeed { + site_name: "Site1".to_string(), + download_bandwidth_mbps: Some(100), + upload_bandwidth_mbps: Some(50), + }); + + let mut treeguard = OverrideFile::default(); + treeguard.set_network_node_virtual("NodeA".to_string(), true); + treeguard.add_network_adjustment(NetworkAdjustment::AdjustSiteSpeed { + site_name: "Site2".to_string(), + download_bandwidth_mbps: Some(200), + upload_bandwidth_mbps: Some(100), + }); + + let merged = merge_owned_sections(operator, 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, + }); + assert_eq!(node_a_virtual, Some(true)); + + // Operator-only site speed should remain; 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(); + assert_eq!(site_speed_names, vec!["Site1"]); + } #[test] fn override_file_defaults_accept_empty_json() { @@ -318,7 +633,6 @@ mod tests { assert!(of.is_circuit_rtt_excluded("C1")); assert!(!of.set_circuit_rtt_excluded_return_changed("C1", true)); - assert!(of.is_circuit_rtt_excluded("C1")); assert!(of.set_circuit_rtt_excluded_return_changed("C1", false)); assert!(!of.is_circuit_rtt_excluded("C1")); diff --git a/src/rust/lqos_python/src/lib.rs b/src/rust/lqos_python/src/lib.rs index 4dcdb53f..ab2fa2f6 100644 --- a/src/rust/lqos_python/src/lib.rs +++ b/src/rust/lqos_python/src/lib.rs @@ -661,8 +661,10 @@ fn liblqos_python(m: &Bound<'_, PyModule>) -> PyResult<()> { m.add_function(wrap_pyfunction!(get_tree_weights, m)?)?; m.add_function(wrap_pyfunction!(get_libreqos_directory, m)?)?; m.add_function(wrap_pyfunction!(overrides_persistent_devices, m)?)?; + 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!(is_network_flat, m)?)?; m.add_function(wrap_pyfunction!(blackboard_finish, m)?)?; m.add_function(wrap_pyfunction!(blackboard_submit, m)?)?; @@ -948,6 +950,59 @@ fn overrides_persistent_devices(py: Python<'_>) -> PyResult> { Ok(out) } +/// Returns a Python list of dictionaries representing persistent devices for ShapedDevices.csv, +/// using the effective overrides view (operator + TreeGuard layers when enabled). +#[pyfunction] +fn overrides_persistent_devices_effective(py: Python<'_>) -> PyResult> { + let config = lqos_config::load_config().map_err(|e| PyOSError::new_err(e.to_string()))?; + let apply_treeguard = config.treeguard.enabled; + + let overrides = match lqos_overrides::OverrideStore::load_effective(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() { + let ipv4s: Vec = dev + .ipv4 + .iter() + .map(|(ip, prefix)| format!("{}/{}", ip, prefix)) + .collect(); + let ipv6s: Vec = dev + .ipv6 + .iter() + .map(|(ip, prefix)| format!("{}/{}", ip, prefix)) + .collect(); + + let d = PyDict::new(py); + d.set_item("circuitID", dev.circuit_id.clone())?; + d.set_item("circuitName", dev.circuit_name.clone())?; + d.set_item("deviceID", dev.device_id.clone())?; + d.set_item("deviceName", dev.device_name.clone())?; + d.set_item("ParentNode", dev.parent_node.clone())?; + d.set_item("mac", dev.mac.clone())?; + d.set_item("ipv4s", ipv4s)?; + d.set_item("ipv6s", ipv6s)?; + d.set_item("minDownload", dev.download_min_mbps)?; + d.set_item("minUpload", dev.upload_min_mbps)?; + d.set_item("maxDownload", dev.download_max_mbps)?; + d.set_item("maxUpload", dev.upload_max_mbps)?; + d.set_item("comment", dev.comment.clone())?; + d.set_item( + "sqm", + dev.sqm_override + .as_ref() + .map(|s| s.to_string()) + .unwrap_or_default(), + )?; + let obj: PyObject = d.unbind().into(); + out.push(obj); + } + + Ok(out) +} + /// Returns the list of circuit adjustments as Python dicts. #[pyfunction] fn overrides_circuit_adjustments(py: Python<'_>) -> PyResult> { @@ -1070,6 +1125,52 @@ fn overrides_network_adjustments(py: Python<'_>) -> PyResult> { Ok(out) } +/// Returns the list of network adjustments as Python dicts, using the effective overrides view +/// (operator + TreeGuard layers when enabled). +#[pyfunction] +fn overrides_network_adjustments_effective(py: Python<'_>) -> PyResult> { + let config = lqos_config::load_config().map_err(|e| PyOSError::new_err(e.to_string()))?; + let apply_treeguard = config.treeguard.enabled; + + let overrides = match lqos_overrides::OverrideStore::load_effective(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() { + let d = PyDict::new(py); + match adj { + lqos_overrides::NetworkAdjustment::AdjustSiteSpeed { + site_name, + download_bandwidth_mbps, + upload_bandwidth_mbps, + } => { + d.set_item("type", "adjust_site_speed")?; + d.set_item("site_name", site_name.clone())?; + if let Some(v) = download_bandwidth_mbps { + d.set_item("download_bandwidth_mbps", *v)?; + } + if let Some(v) = upload_bandwidth_mbps { + d.set_item("upload_bandwidth_mbps", *v)?; + } + } + lqos_overrides::NetworkAdjustment::SetNodeVirtual { + node_name, + virtual_node, + } => { + d.set_item("type", "set_node_virtual")?; + d.set_item("node_name", node_name.clone())?; + d.set_item("virtual", *virtual_node)?; + } + } + let obj: PyObject = d.unbind().into(); + out.push(obj); + } + + Ok(out) +} + #[pyfunction] fn is_libre_already_running() -> PyResult { let lock_path = Path::new(LOCK_FILE); diff --git a/src/rust/lqosd/Cargo.toml b/src/rust/lqosd/Cargo.toml index 23115e22..4ec7c4d8 100644 --- a/src/rust/lqosd/Cargo.toml +++ b/src/rust/lqosd/Cargo.toml @@ -53,6 +53,7 @@ sha256 = "1.5.0" uuid = { version = "1.10.0", features = ["v4", "fast-rng", "serde"] } dryoc = { version ="0.6.0", features = ["serde"] } miniz_oxide = "0.8.0" +thiserror = { workspace = true } tungstenite = { version = "0", features = [ "native-tls" ] } # For WebSockets tokio-tungstenite = { version = "0", features = [ "native-tls" ] } native-tls = "0.2" diff --git a/src/rust/lqosd/src/main.rs b/src/rust/lqosd/src/main.rs index b0b1792e..54758871 100644 --- a/src/rust/lqosd/src/main.rs +++ b/src/rust/lqosd/src/main.rs @@ -4,6 +4,7 @@ #![deny(clippy::unwrap_used)] mod blackboard; +mod treeguard; mod file_lock; mod ip_mapping; #[cfg(feature = "equinix_tests")] @@ -12,6 +13,7 @@ pub mod lts2_sys; mod node_manager; mod preflight_checks; mod program_control; +mod reload_lock; mod remote_commands; mod rtt_exclusions; mod scheduler_control; @@ -249,6 +251,11 @@ fn main() -> Result<()> { bakery_sender.clone(), )?; spawn_queue_monitor()?; + + if let Err(err) = treeguard::actor::start_treeguard_actor(system_usage_tx.clone()) { + warn!("Failed to start TreeGuard actor: {err}"); + } + lqos_sys::bpf_garbage_collector(); version_checks::start_version_check()?; diff --git a/src/rust/lqosd/src/node_manager.rs b/src/rust/lqosd/src/node_manager.rs index 2d946e86..72077653 100644 --- a/src/rust/lqosd/src/node_manager.rs +++ b/src/rust/lqosd/src/node_manager.rs @@ -5,7 +5,7 @@ mod shaper_queries_actor; mod static_pages; mod template; mod warnings; -mod ws; +pub(crate) mod ws; pub use local_api::circuit_count::circuit_count_data; pub use local_api::device_counts::device_count; diff --git a/src/rust/lqosd/src/node_manager/ws/messages.rs b/src/rust/lqosd/src/node_manager/ws/messages.rs index 2c629dbc..99c84815 100644 --- a/src/rust/lqosd/src/node_manager/ws/messages.rs +++ b/src/rust/lqosd/src/node_manager/ws/messages.rs @@ -271,6 +271,29 @@ pub struct BakeryStatusData { pub current_state: BakeryStatusState, } +#[derive(Clone, Debug, Serialize)] +pub struct TreeguardStatusData { + pub enabled: bool, + pub dry_run: bool, + pub cpu_max_pct: Option, + pub managed_nodes: usize, + pub managed_circuits: usize, + pub virtualized_nodes: usize, + pub fq_codel_circuits: usize, + pub last_action_summary: Option, + pub warnings: Vec, +} + +#[derive(Clone, Debug, Serialize)] +pub struct TreeguardActivityEntry { + pub time: String, + pub entity_type: String, + pub entity_id: String, + pub action: String, + pub persisted: bool, + pub reason: String, +} + #[derive(Debug, Serialize)] pub struct TopAsnRow { pub name: String, @@ -648,6 +671,12 @@ pub enum WsResponse { BakeryStatus { data: BakeryStatusData, }, + TreeGuardStatus { + data: TreeguardStatusData, + }, + TreeGuardActivity { + data: Vec, + }, ExecutiveHeatmaps { data: ExecutiveHeatmapsData, }, diff --git a/src/rust/lqosd/src/node_manager/ws/published_channels.rs b/src/rust/lqosd/src/node_manager/ws/published_channels.rs index 4b984e3e..648d983e 100644 --- a/src/rust/lqosd/src/node_manager/ws/published_channels.rs +++ b/src/rust/lqosd/src/node_manager/ws/published_channels.rs @@ -45,6 +45,8 @@ pub enum PublishedChannels { StormguardStatus, StormguardDebug, BakeryStatus, + TreeGuardStatus, + TreeGuardActivity, EndpointLatLon, AsnTopDownload, AsnTopUpload, diff --git a/src/rust/lqosd/src/node_manager/ws/ticker.rs b/src/rust/lqosd/src/node_manager/ws/ticker.rs index 4b5584bb..0f4f0dc9 100644 --- a/src/rust/lqosd/src/node_manager/ws/ticker.rs +++ b/src/rust/lqosd/src/node_manager/ws/ticker.rs @@ -22,6 +22,7 @@ mod queue_stats_total; mod retransmits; mod rtt_histogram; mod stormguard; +mod treeguard; pub mod system_info; mod throughput; mod top_10; @@ -192,6 +193,14 @@ async fn one_second_cadence( "bakery", bakery::bakery_ticker(channels.clone(), bus_tx.clone()) ), + ticker_with_timeout( + "treeguard_status", + treeguard::treeguard_status(channels.clone()) + ), + ticker_with_timeout( + "treeguard_activity", + treeguard::treeguard_activity(channels.clone()) + ), ticker_with_timeout( "executive_heatmaps", executive_heatmaps::executive_heatmaps(channels.clone(), bus_tx.clone()) diff --git a/src/rust/lqosd/src/node_manager/ws/ticker/treeguard.rs b/src/rust/lqosd/src/node_manager/ws/ticker/treeguard.rs new file mode 100644 index 00000000..12b841b3 --- /dev/null +++ b/src/rust/lqosd/src/node_manager/ws/ticker/treeguard.rs @@ -0,0 +1,33 @@ +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 std::sync::Arc; + +pub async fn treeguard_status(pubsub: Arc) { + if !pubsub + .is_channel_alive(PublishedChannels::TreeGuardStatus) + .await + { + return; + } + + let data = treeguard_status_snapshot().await; + let msg = WsResponse::TreeGuardStatus { data }; + pubsub.send(PublishedChannels::TreeGuardStatus, msg).await; +} + +pub async fn treeguard_activity(pubsub: Arc) { + if !pubsub + .is_channel_alive(PublishedChannels::TreeGuardActivity) + .await + { + return; + } + + let data = treeguard_activity_snapshot().await; + let msg = WsResponse::TreeGuardActivity { data }; + pubsub + .send(PublishedChannels::TreeGuardActivity, msg) + .await; +} diff --git a/src/rust/lqosd/src/reload_lock.rs b/src/rust/lqosd/src/reload_lock.rs new file mode 100644 index 00000000..fb1ee5a2 --- /dev/null +++ b/src/rust/lqosd/src/reload_lock.rs @@ -0,0 +1,37 @@ +use std::sync::atomic::{AtomicBool, Ordering}; + +static RELOAD_BUSY: AtomicBool = AtomicBool::new(false); + +pub(crate) struct ReloadGuard; + +impl Drop for ReloadGuard { + fn drop(&mut self) { + RELOAD_BUSY.store(false, Ordering::Release); + } +} + +pub(crate) enum ReloadExecOutcome { + Busy, + Success(String), + Failed(String), +} + +fn try_acquire_reload_guard() -> Option { + RELOAD_BUSY + .compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed) + .ok() + .map(|_| ReloadGuard) +} + +/// Attempts to reload LibreQoS, returning `Busy` if another reload is already running. +pub(crate) fn try_reload_libreqos_locked() -> ReloadExecOutcome { + let Some(_guard) = try_acquire_reload_guard() else { + return ReloadExecOutcome::Busy; + }; + + match lqos_config::load_libreqos() { + Ok(message) => ReloadExecOutcome::Success(message), + 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 new file mode 100644 index 00000000..6156b67d --- /dev/null +++ b/src/rust/lqosd/src/treeguard/actor.rs @@ -0,0 +1,1898 @@ +//! TreeGuard actor loop. +//! +//! The actor is responsible for sampling telemetry, maintaining state machines, +//! and applying (or dry-running) any decisions. + +use crate::node_manager::ws::messages::{TreeguardActivityEntry, TreeguardStatusData}; +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, +}; +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}; +use lqos_bus::{UrgentSeverity, UrgentSource}; +use lqos_config::load_config; +use lqos_overrides::{NetworkAdjustment, OverrideFile, OverrideLayer, OverrideStore}; +use lqos_utils::hash_to_i64; +use lqos_utils::units::DownUpOrder; +use lqos_utils::unix_time::{time_since_boot, unix_now}; +use std::collections::VecDeque; +use std::sync::OnceLock; +use std::time::{Duration, Instant}; +use tracing::{debug, warn}; + +static TREEGUARD_SENDER: OnceLock> = OnceLock::new(); + +const ACTIVITY_RING_CAPACITY: usize = 200; +const UTIL_EWMA_ALPHA: f64 = 0.1; +const TOP_LEVEL_SAFE_SUSTAIN_MINUTES: u32 = 15; + +/// A message sent to the TreeGuard actor. +#[derive(Debug)] +pub(crate) enum TreeguardCommand { + /// Request a status snapshot. + GetStatus { + /// One-shot reply channel. Side effect: sends a snapshot to the requester. + reply: tokio::sync::oneshot::Sender, + }, + /// Request an activity snapshot. + GetActivity { + /// One-shot reply channel. Side effect: sends a snapshot to the requester. + reply: tokio::sync::oneshot::Sender>, + }, +} + +/// Starts the TreeGuard actor. +/// +/// This function has side effects: it spawns the TreeGuard background thread and registers a +/// global sender used for UI snapshot requests. +pub(crate) fn start_treeguard_actor( + system_usage_tx: Sender>, +) -> Result<(), TreeguardError> { + if TREEGUARD_SENDER.get().is_some() { + return Ok(()); + } + + let (tx, rx) = crossbeam_channel::bounded::(64); + let _ = TREEGUARD_SENDER.set(tx); + + std::thread::Builder::new() + .name("TreeGuard".to_string()) + .spawn(move || treeguard_actor_loop(rx, system_usage_tx))?; + + Ok(()) +} + +/// Requests a status snapshot from the TreeGuard actor. +/// +/// This function is not pure: it sends a message to the TreeGuard actor thread. +pub(crate) async fn request_status_snapshot() -> Option { + let sender = TREEGUARD_SENDER.get()?; + let (tx, rx) = tokio::sync::oneshot::channel(); + if sender + .try_send(TreeguardCommand::GetStatus { reply: tx }) + .is_err() + { + return None; + } + rx.await.ok() +} + +/// Requests an activity snapshot from the TreeGuard actor. +/// +/// This function is not pure: it sends a message to the TreeGuard actor thread. +pub(crate) async fn request_activity_snapshot() -> Option> { + let sender = TREEGUARD_SENDER.get()?; + let (tx, rx) = tokio::sync::oneshot::channel(); + if sender + .try_send(TreeguardCommand::GetActivity { reply: tx }) + .is_err() + { + return None; + } + rx.await.ok() +} + +/// Runs the TreeGuard actor loop, processing commands and periodic ticks. +/// +/// This function has side effects: it blocks the current thread, samples telemetry, and may write +/// persistent changes (via overrides) depending on configuration. +fn treeguard_actor_loop( + rx: Receiver, + system_usage_tx: Sender>, +) { + debug!("TreeGuard actor started"); + + let mut status = TreeguardStatusData { + enabled: false, + dry_run: true, + cpu_max_pct: None, + managed_nodes: 0, + managed_circuits: 0, + virtualized_nodes: 0, + fq_codel_circuits: 0, + last_action_summary: None, + warnings: Vec::new(), + }; + let mut activity: VecDeque = VecDeque::new(); + + let mut link_states: FxHashMap = FxHashMap::default(); + let mut circuit_states: FxHashMap = FxHashMap::default(); + let mut managed_nodes: FxHashSet = FxHashSet::default(); + let mut managed_device_ids: FxHashSet = FxHashSet::default(); + let mut last_dry_run: Option = None; + let mut reload_controller = ReloadController::default(); + + let mut tick_seconds: u64 = 1; + let mut last_tick = Instant::now(); + + loop { + let next_tick = last_tick + Duration::from_secs(tick_seconds); + let timeout = next_tick.saturating_duration_since(Instant::now()); + + match rx.recv_timeout(timeout) { + Ok(cmd) => handle_command(cmd, &status, &activity), + Err(crossbeam_channel::RecvTimeoutError::Timeout) => { + last_tick = Instant::now(); + run_tick( + &mut status, + &mut activity, + &system_usage_tx, + &mut tick_seconds, + &mut link_states, + &mut circuit_states, + &mut managed_nodes, + &mut managed_device_ids, + &mut last_dry_run, + &mut reload_controller, + ); + } + Err(crossbeam_channel::RecvTimeoutError::Disconnected) => { + warn!("TreeGuard actor command channel disconnected; exiting actor"); + return; + } + } + } +} + +/// Handles a command received by the actor. +/// +/// This function has side effects: it sends a snapshot reply over the provided one-shot channel. +fn handle_command( + cmd: TreeguardCommand, + status: &TreeguardStatusData, + activity: &VecDeque, +) { + match cmd { + TreeguardCommand::GetStatus { reply } => { + let _ = reply.send(status.clone()); + } + TreeguardCommand::GetActivity { reply } => { + let data: Vec = activity.iter().cloned().rev().collect(); + let _ = reply.send(data); + } + } +} + +/// Executes a single TreeGuard tick. +/// +/// This function has side effects: it samples telemetry, may read/write `lqos_overrides.treeguard.json`, +/// and appends to the activity ring buffer. +fn run_tick( + status: &mut TreeguardStatusData, + activity: &mut VecDeque, + system_usage_tx: &Sender>, + tick_seconds: &mut u64, + link_states: &mut FxHashMap, + circuit_states: &mut FxHashMap, + managed_nodes: &mut FxHashSet, + managed_device_ids: &mut FxHashSet, + last_dry_run: &mut Option, + reload_controller: &mut ReloadController, +) { + let now_unix = unix_now().unwrap_or(0); + let now_nanos_since_boot = time_since_boot() + .ok() + .map(Duration::from) + .map(|d| d.as_nanos() as u64); + + let mut warnings = Vec::new(); + + let Ok(config) = load_config() else { + status.enabled = false; + status.dry_run = true; + status.cpu_max_pct = None; + status.managed_nodes = 0; + status.managed_circuits = 0; + status.virtualized_nodes = 0; + status.fq_codel_circuits = 0; + status.last_action_summary = None; + status.warnings = vec!["Unable to load configuration; TreeGuard inactive.".to_string()]; + return; + }; + + let tg = &config.treeguard; + *tick_seconds = tg.tick_seconds.max(1); + + if last_dry_run.is_some_and(|prev| prev != tg.dry_run) { + link_states.clear(); + circuit_states.clear(); + push_activity( + activity, + TreeguardActivityEntry { + time: now_unix.to_string(), + entity_type: "treeguard".to_string(), + entity_id: "treeguard".to_string(), + action: "dry_run_toggled".to_string(), + persisted: false, + reason: "Dry-run mode changed; state machines reset.".to_string(), + }, + ); + } + *last_dry_run = Some(tg.dry_run); + + let mut virtualized_nodes: usize = 0; + let mut fq_codel_circuits: usize = 0; + + let top_level_auto_virtualize = tg.links.enabled && tg.links.top_level_auto_virtualize; + if tg.enabled + && !tg.links.all_nodes + && tg.links.nodes.is_empty() + && !top_level_auto_virtualize + && !tg.circuits.all_circuits + && tg.circuits.circuits.is_empty() + { + warnings.push( + "TreeGuard is enabled but no nodes/circuits are allowlisted. No actions will occur." + .to_string(), + ); + } else if tg.enabled + && !tg.links.all_nodes + && tg.links.nodes.is_empty() + && top_level_auto_virtualize + && !tg.circuits.all_circuits + && tg.circuits.circuits.is_empty() + { + warnings.push( + "TreeGuard is enabled with empty allowlists; only top-level auto-virtualization may occur." + .to_string(), + ); + } + + let cpu_max_pct = (|| -> Option { + let (tx, rx) = tokio::sync::oneshot::channel(); + system_usage_tx.send(tx).ok()?; + let reply = rx.blocking_recv().ok()?; + let max = reply.cpu_usage.iter().copied().max()?; + Some(max.min(100) as u8) + })(); + + if tg.enabled && cpu_max_pct.is_none() { + warnings + .push("Unable to sample CPU usage; CPU-aware behavior may be degraded.".to_string()); + } + + let managed_nodes_count: usize = if tg.links.all_nodes { + let reader = NETWORK_JSON.read(); + reader + .get_nodes_when_ready() + .iter() + .filter(|n| n.name != "Root") + .count() + } else { + let mut enrolled: FxHashSet = tg.links.nodes.iter().cloned().collect(); + if top_level_auto_virtualize { + let reader = NETWORK_JSON.read(); + for node in reader.get_nodes_when_ready().iter() { + if node.name != "Root" && node.immediate_parent == Some(0) { + enrolled.insert(node.name.clone()); + } + } + } + enrolled.len() + }; + + let managed_circuits_count: usize = if tg.circuits.all_circuits { + let shaped = SHAPED_DEVICES.load(); + let mut circuits: FxHashSet<&str> = FxHashSet::default(); + for d in shaped.devices.iter() { + let id = d.circuit_id.trim(); + if !id.is_empty() { + circuits.insert(id); + } + } + circuits.len() + } else { + tg.circuits.circuits.len() + }; + + status.enabled = tg.enabled; + status.dry_run = tg.dry_run; + status.cpu_max_pct = cpu_max_pct; + status.managed_nodes = managed_nodes_count; + status.managed_circuits = managed_circuits_count; + status.warnings = warnings; + + let (operator_overrides_snapshot, treeguard_overrides_snapshot) = + if tg.enabled && (tg.links.enabled || tg.circuits.enabled) { + let operator = match OverrideStore::load_layer(OverrideLayer::Operator) { + Ok(o) => Some(o), + Err(e) => { + status.warnings.push(format!( + "TreeGuard: unable to load operator overrides file: {e}" + )); + None + } + }; + let treeguard = match OverrideStore::load_layer(OverrideLayer::Treeguard) { + Ok(o) => Some(o), + Err(e) => { + status.warnings.push(format!( + "TreeGuard: unable to load TreeGuard overrides file: {e}" + )); + None + } + }; + (operator, treeguard) + } else { + (None, None) + }; + + // Conflict detection: if operator-defined overrides exist for an enrolled entity, TreeGuard + // will refuse to manage it to avoid fights/surprises. + let operator_virtual_node_overrides: FxHashSet = operator_overrides_snapshot + .as_ref() + .map(|o| { + o.network_adjustments() + .iter() + .filter_map(|adj| match adj { + NetworkAdjustment::SetNodeVirtual { node_name, .. } => { + Some(node_name.clone()) + } + _ => None, + }) + .collect() + }) + .unwrap_or_default(); + + let operator_sqm_device_overrides: FxHashSet = operator_overrides_snapshot + .as_ref() + .map(|o| { + o.persistent_devices() + .iter() + .filter(|d| { + d.sqm_override + .as_deref() + .is_some_and(|t| !t.trim().is_empty()) + }) + .map(|d| d.device_id.clone()) + .collect() + }) + .unwrap_or_default(); + + // --- Link sampling + decisions (virtualization) --- + let manage_links = tg.enabled && tg.links.enabled; + let allowlisted_nodes: FxHashSet = tg.links.nodes.iter().cloned().collect(); + + // Cleanup for removed nodes or disabled links. + if !manage_links { + let removed: Vec = match OverrideStore::load_layer(OverrideLayer::Treeguard) { + Ok(of) => of + .network_adjustments() + .iter() + .filter_map(|adj| match adj { + NetworkAdjustment::SetNodeVirtual { node_name, .. } => { + Some(node_name.clone()) + } + _ => None, + }) + .collect(), + Err(e) => { + status.warnings.push(format!( + "TreeGuard links: unable to load TreeGuard overrides for cleanup: {e}" + )); + Vec::new() + } + }; + for node_name in removed { + match overrides::clear_node_virtual(&node_name) { + Ok(changed) => { + if changed { + reload_controller.request_reload( + ReloadPriority::Normal, + format!("Cleared virtual override for node '{node_name}'"), + ); + push_activity( + activity, + TreeguardActivityEntry { + time: now_unix.to_string(), + entity_type: "node".to_string(), + entity_id: node_name.clone(), + action: "clear_virtual_override".to_string(), + persisted: true, + reason: "TreeGuard disabled or links disabled".to_string(), + }, + ); + } + managed_nodes.remove(&node_name); + link_states.remove(&node_name); + } + Err(e) => { + status.warnings.push(format!( + "TreeGuard links: failed to clear virtual override for node '{node_name}': {e}" + )); + push_activity( + activity, + TreeguardActivityEntry { + time: now_unix.to_string(), + entity_type: "node".to_string(), + entity_id: node_name, + action: "clear_virtual_override_failed".to_string(), + persisted: false, + reason: format!("Overrides write failed: {e}"), + }, + ); + } + } + } + } else { + let reader = NETWORK_JSON.read(); + let top_level_nodes: FxHashSet = if top_level_auto_virtualize && !tg.links.all_nodes + { + reader + .get_nodes_when_ready() + .iter() + .filter(|n| n.name != "Root" && n.immediate_parent == Some(0)) + .map(|n| n.name.clone()) + .collect() + } else { + FxHashSet::default() + }; + + // Reconcile nodes removed from allowlist, or removed from network.json. + let treeguard_nodes_with_overrides: FxHashSet = treeguard_overrides_snapshot + .as_ref() + .map(|of| { + of.network_adjustments() + .iter() + .filter_map(|adj| match adj { + NetworkAdjustment::SetNodeVirtual { node_name, .. } => { + Some(node_name.clone()) + } + _ => None, + }) + .collect() + }) + .unwrap_or_default(); + + let removed: Vec = if tg.links.all_nodes { + let current: FxHashSet<&str> = reader + .get_nodes_when_ready() + .iter() + .filter(|n| n.name != "Root") + .map(|n| n.name.as_str()) + .collect(); + treeguard_nodes_with_overrides + .iter() + .filter(|n| !current.contains(n.as_str())) + .cloned() + .collect() + } else { + treeguard_nodes_with_overrides + .iter() + .filter(|n| !allowlisted_nodes.contains(*n) && !top_level_nodes.contains(*n)) + .cloned() + .collect() + }; + for node_name in removed { + match overrides::clear_node_virtual(&node_name) { + Ok(changed) => { + if changed { + reload_controller.request_reload( + ReloadPriority::Normal, + format!("Cleared virtual override for node '{node_name}'"), + ); + push_activity( + activity, + TreeguardActivityEntry { + time: now_unix.to_string(), + entity_type: "node".to_string(), + entity_id: node_name.clone(), + action: "clear_virtual_override".to_string(), + persisted: true, + reason: "Node removed from allowlist".to_string(), + }, + ); + } + managed_nodes.remove(&node_name); + link_states.remove(&node_name); + } + Err(e) => { + status.warnings.push(format!( + "TreeGuard links: failed to clear virtual override for node '{node_name}': {e}" + )); + push_activity( + activity, + TreeguardActivityEntry { + time: now_unix.to_string(), + entity_type: "node".to_string(), + entity_id: node_name, + action: "clear_virtual_override_failed".to_string(), + persisted: false, + reason: format!("Overrides write failed: {e}"), + }, + ); + } + } + } + if tg.links.all_nodes { + for node in reader.get_nodes_when_ready().iter() { + let node_name = node.name.as_str(); + if node_name == "Root" { + continue; + } + + if operator_virtual_node_overrides.contains(node_name) { + status.warnings.push(format!( + "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( + ReloadPriority::Normal, + format!( + "Cleared virtual override for node '{node_name}' due to operator conflict" + ), + ); + push_activity( + activity, + TreeguardActivityEntry { + time: now_unix.to_string(), + entity_type: "node".to_string(), + entity_id: node_name.to_string(), + action: "clear_virtual_override_conflict".to_string(), + persisted: true, + reason: "Operator override present; TreeGuard will not manage this node.".to_string(), + }, + ); + } + } + 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; + } + + 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; + } + + 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; + } + + 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.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 + }); + 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, + ); + + 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, + ); + } + + 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) + } + } + }; + + // 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 util_ewma_pct = DownUpOrder { + down: ewma_down, + up: ewma_up, + }; + + 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 + } + } + } + } + } else { + decisions::decide_link_virtualization( + now_unix, + true, + 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; + } + + 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!( + "TreeGuard links: failed to persist virtual override for node '{node_name}': {e}" + )); + managed_nodes.insert(node_name.to_string()); + push_activity( + activity, + TreeguardActivityEntry { + time: now_unix.to_string(), + entity_type: "node".to_string(), + entity_id: node_name.to_string(), + 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.to_string()), + ); + } + + 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.to_string()); + + push_activity( + activity, + TreeguardActivityEntry { + time: now_unix.to_string(), + entity_type: "node".to_string(), + entity_id: node_name.to_string(), + 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() + }, + }, + ); + status.last_action_summary = Some(format!( + "{} node '{}'", + if target == LinkVirtualState::Virtual { + "Virtualized" + } else { + "Unvirtualized" + }, + node_name + )); + } else { + managed_nodes.insert(node_name.to_string()); + } + + if state.desired == LinkVirtualState::Virtual { + virtualized_nodes += 1; + } + } + } else { + let mut enrolled_nodes: Vec = tg.links.nodes.clone(); + if top_level_auto_virtualize { + enrolled_nodes.extend(top_level_nodes.iter().cloned()); + } + enrolled_nodes.sort(); + enrolled_nodes.dedup(); + + for node_name in enrolled_nodes.iter() { + if operator_virtual_node_overrides.contains(node_name) { + status.warnings.push(format!( + "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( + ReloadPriority::Normal, + format!( + "Cleared virtual override for node '{node_name}' due to operator conflict" + ), + ); + push_activity( + activity, + TreeguardActivityEntry { + time: now_unix.to_string(), + entity_type: "node".to_string(), + entity_id: node_name.clone(), + action: "clear_virtual_override_conflict".to_string(), + persisted: true, + reason: "Operator override present; TreeGuard will not manage this node.".to_string(), + }, + ); + } + } + 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; + } + 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!( + "TreeGuard links: node '{node_name}' is marked virtual in base network.json; TreeGuard will not manage it." + )); + 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!( + "TreeGuard links: node '{node_name}' has unknown capacity; no changes will be made." + )); + 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 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) { + state.desired = if v { + LinkVirtualState::Virtual + } else { + LinkVirtualState::Physical + }; + } + } + 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, + ); + + 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, + ); + } + + 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) + } + } + }; + + // 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 util_ewma_pct = DownUpOrder { + down: ewma_down, + up: ewma_up, + }; + + 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 + } + } + } + } + } 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; + } + + 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!( + "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; + } + } + } + + 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()); + + 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() + }, + }, + ); + status.last_action_summary = Some(format!( + "{} node '{}'", + if target == LinkVirtualState::Virtual { + "Virtualized" + } else { + "Unvirtualized" + }, + node_name + )); + } else { + managed_nodes.insert(node_name.clone()); + } + + if state.desired == LinkVirtualState::Virtual { + virtualized_nodes += 1; + } + } + } + } + + if let Some(attempt) = reload_controller.poll_reload(now_unix, tg.links.reload_cooldown_minutes) + { + let crate::treeguard::reload::ReloadAttempt { + outcome, + request_reason, + } = attempt; + + match outcome { + ReloadOutcome::Success { message: _ } => { + let why = request_reason.unwrap_or_else(|| "Topology change".to_string()); + push_activity( + activity, + TreeguardActivityEntry { + time: now_unix.to_string(), + entity_type: "treeguard".to_string(), + entity_id: "reload".to_string(), + action: "reload_success".to_string(), + persisted: true, + reason: why.clone(), + }, + ); + status.last_action_summary = Some(format!("Reloaded LibreQoS: {why}")); + } + ReloadOutcome::Skipped { + reason, + next_allowed_unix, + } => { + let extra = next_allowed_unix + .map(|t| format!(" next_allowed_unix={t}")) + .unwrap_or_default(); + push_activity( + activity, + TreeguardActivityEntry { + time: now_unix.to_string(), + entity_type: "treeguard".to_string(), + entity_id: "reload".to_string(), + action: "reload_skipped".to_string(), + persisted: false, + reason: format!("{reason}.{extra}"), + }, + ); + } + ReloadOutcome::Failed { + error, + next_allowed_unix, + } => { + let why = request_reason.unwrap_or_else(|| "Topology change".to_string()); + let extra = next_allowed_unix + .map(|t| format!(" next_allowed_unix={t}")) + .unwrap_or_default(); + status.warnings.push(format!("TreeGuard reload failed: {error}.{extra}")); + push_activity( + activity, + TreeguardActivityEntry { + time: now_unix.to_string(), + entity_type: "treeguard".to_string(), + entity_id: "reload".to_string(), + action: "reload_failed".to_string(), + persisted: false, + reason: format!("{error}.{extra}"), + }, + ); + urgent::submit( + UrgentSource::System, + UrgentSeverity::Error, + "treeguard_reload_failed".to_string(), + format!("TreeGuard failed to reload LibreQoS: {error}"), + Some(why), + Some("treeguard_reload".to_string()), + ); + } + } + } + + // --- Circuit sampling + decisions (SQM switching) --- + let manage_circuits = tg.enabled && tg.circuits.enabled; + + // Snapshot shaped devices so we can compute the enrolled circuit set. + let shaped = SHAPED_DEVICES.load(); + + let enrolled_circuits: Vec = if tg.circuits.all_circuits { + let mut set: FxHashSet = FxHashSet::default(); + for d in shaped.devices.iter() { + let id = d.circuit_id.trim(); + if !id.is_empty() { + set.insert(id.to_string()); + } + } + let mut v: Vec = set.into_iter().collect(); + v.sort(); + v + } else { + let mut v = tg.circuits.circuits.clone(); + v.sort(); + v.dedup(); + v + }; + + let allowlisted_circuits: FxHashSet = enrolled_circuits.iter().cloned().collect(); + status.managed_circuits = enrolled_circuits.len(); + + // Compute desired device_id set from enrolled circuits. + let desired_device_ids: FxHashSet = if manage_circuits { + if tg.circuits.all_circuits { + shaped.devices.iter().map(|d| d.device_id.clone()).collect() + } else { + shaped + .devices + .iter() + .filter(|d| allowlisted_circuits.contains(&d.circuit_id)) + .map(|d| d.device_id.clone()) + .collect() + } + } else { + FxHashSet::default() + }; + + // Cleanup for removed circuits or disabled circuits/TreeGuard. + if !manage_circuits { + let removed: Vec = match OverrideStore::load_layer(OverrideLayer::Treeguard) { + Ok(of) => of + .persistent_devices() + .iter() + .map(|d| d.device_id.clone()) + .collect(), + Err(e) => { + status.warnings.push(format!( + "TreeGuard circuits: unable to load TreeGuard overrides for cleanup: {e}" + )); + Vec::new() + } + }; + if !removed.is_empty() { + match overrides::clear_device_overrides(&removed) { + Ok(changed) => { + if changed { + push_activity( + activity, + TreeguardActivityEntry { + time: now_unix.to_string(), + entity_type: "circuits".to_string(), + entity_id: "*".to_string(), + action: "clear_sqm_overrides".to_string(), + persisted: true, + reason: "TreeGuard disabled or circuits disabled".to_string(), + }, + ); + } + } + Err(e) => { + status.warnings.push(format!( + "TreeGuard circuits: failed to clear TreeGuard SQM overlays during cleanup: {e}" + )); + } + } + } + managed_device_ids.clear(); + circuit_states.clear(); + } else { + // 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()) + .unwrap_or_default(); + let removed: Vec = treeguard_device_ids_with_overrides + .iter() + .filter(|d| !desired_device_ids.contains(*d)) + .cloned() + .collect(); + if !removed.is_empty() { + match overrides::clear_device_overrides(&removed) { + Ok(changed) => { + if changed { + push_activity( + activity, + TreeguardActivityEntry { + time: now_unix.to_string(), + entity_type: "circuits".to_string(), + entity_id: "*".to_string(), + action: "clear_sqm_overrides".to_string(), + persisted: true, + reason: "Device removed from allowlisted circuits".to_string(), + }, + ); + } + } + Err(e) => { + status.warnings.push(format!( + "TreeGuard circuits: failed to clear TreeGuard SQM overlays for removed devices: {e}" + )); + } + } + for device_id in removed.iter() { + managed_device_ids.remove(device_id); + } + } + + // Snapshot RTT buffers by circuit hash. + let rtt_snapshot = CIRCUIT_RTT_BUFFERS.load(); + + let allow_hashes: Option> = if tg.circuits.all_circuits { + None + } else { + Some(enrolled_circuits.iter().map(|id| hash_to_i64(id)).collect()) + }; + + // Capacity lookup by circuit hash (max down/up Mbps across devices in the circuit). + let mut capacity_by_circuit: FxHashMap = FxHashMap::default(); + capacity_by_circuit.reserve(shaped.devices.len()); + for device in shaped.devices.iter() { + let entry = capacity_by_circuit + .entry(device.circuit_hash) + .or_insert((device.download_max_mbps, device.upload_max_mbps)); + if device.download_max_mbps > entry.0 { + entry.0 = device.download_max_mbps; + } + if device.upload_max_mbps > entry.1 { + entry.1 = device.upload_max_mbps; + } + } + + // Aggregate worst (minimum) QoO and throughput per circuit hash across devices/hosts. + let mut qoo_by_circuit: FxHashMap>> = FxHashMap::default(); + let mut bps_by_circuit: FxHashMap> = FxHashMap::default(); + { + let raw = THROUGHPUT_TRACKER.raw_data.lock(); + for entry in raw.values() { + let Some(ch) = entry.circuit_hash else { + continue; + }; + if allow_hashes.as_ref().is_some_and(|h| !h.contains(&ch)) { + continue; + } + + let down = entry.qoq.download_total_f32(); + let up = entry.qoq.upload_total_f32(); + let slot = qoo_by_circuit.entry(ch).or_insert(DownUpOrder { + down: None, + up: None, + }); + 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 }); + 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; + } + } + state + }); + prune_recent_changes(&mut state.down.recent_changes_unix, now_unix); + prune_recent_changes(&mut state.up.recent_changes_unix, now_unix); + + let circuit_hash = hash_to_i64(circuit_id); + let (cap_down, cap_up) = capacity_by_circuit + .get(&circuit_hash) + .copied() + .unwrap_or((0.0, 0.0)); + let capacity_known = cap_down > 0.0 && cap_up > 0.0; + if !capacity_known { + status.warnings.push(format!( + "TreeGuard circuits: circuit '{circuit_id}' has unknown capacity; no changes will be made." + )); + state.down.idle_since_unix = None; + state.up.idle_since_unix = None; + } else { + let bps = bps_by_circuit + .get(&circuit_hash) + .copied() + .unwrap_or(DownUpOrder { down: 0, up: 0 }); + let mbps_down = (bps.down as f64 * 8.0) / 1_000_000.0; + let mbps_up = (bps.up as f64 * 8.0) / 1_000_000.0; + let util_down_pct = (mbps_down / cap_down as f64) * 100.0; + let util_up_pct = (mbps_up / cap_up as f64) * 100.0; + + 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); + + update_idle_since( + &mut state.down.idle_since_unix, + now_unix, + ewma_down, + tg.circuits.idle_util_pct as f64, + ); + update_idle_since( + &mut state.up.idle_since_unix, + now_unix, + ewma_up, + tg.circuits.idle_util_pct as f64, + ); + } + + let rtt_missing = match now_nanos_since_boot { + None => true, + Some(now_nanos) => match rtt_snapshot.get(&circuit_hash) { + None => true, + Some(buf) => { + if buf.last_seen == 0 { + true + } else { + let age_nanos = now_nanos.saturating_sub(buf.last_seen); + age_nanos + >= u64::from(tg.circuits.rtt_missing_seconds) + .saturating_mul(1_000_000_000) + } + } + }, + }; + + let qoo = qoo_by_circuit + .get(&circuit_hash) + .cloned() + .unwrap_or(DownUpOrder { + down: None, + up: None, + }); + + let devices: Vec = shaped + .devices + .iter() + .filter(|d| d.circuit_id == circuit_id.as_str()) + .cloned() + .collect(); + + let circuit_name: Option = devices.iter().find_map(|d| { + let name = d.circuit_name.trim(); + if name.is_empty() { + None + } else { + Some(name.to_string()) + } + }); + let circuit_entity_id: String = match circuit_name.as_deref() { + Some(name) => format!("{name} ({circuit_id})"), + None => circuit_id.clone(), + }; + let circuit_label: String = circuit_name.unwrap_or_else(|| circuit_id.clone()); + + let mut circuit_device_ids: Vec = + devices.iter().map(|d| d.device_id.clone()).collect(); + circuit_device_ids.sort(); + circuit_device_ids.dedup(); + let operator_conflict = circuit_device_ids + .iter() + .any(|did| operator_sqm_device_overrides.contains(did)); + if operator_conflict { + status.warnings.push(format!( + "TreeGuard circuits: circuit '{circuit_id}' has operator SQM overrides; TreeGuard will not manage it." + )); + if !circuit_device_ids.is_empty() { + match overrides::clear_device_overrides(&circuit_device_ids) { + Ok(changed) => { + if changed { + push_activity( + activity, + TreeguardActivityEntry { + time: now_unix.to_string(), + entity_type: "circuit".to_string(), + entity_id: circuit_entity_id.clone(), + action: "clear_sqm_overrides_conflict".to_string(), + persisted: true, + reason: "Operator SQM overrides present; cleared TreeGuard SQM overlays.".to_string(), + }, + ); + } + } + Err(e) => { + status.warnings.push(format!( + "TreeGuard circuits: failed to clear TreeGuard SQM overlays for circuit '{circuit_id}' during conflict cleanup: {e}" + )); + } + } + for did in circuit_device_ids.iter() { + managed_device_ids.remove(did); + } + } + continue; + } + + let decision = decisions::decide_circuit_sqm( + now_unix, + allowlisted_circuits.contains(circuit_id) && capacity_known, + cpu_max_pct, + &tg.cpu, + &tg.circuits, + &tg.qoo, + rtt_missing, + qoo, + state, + ); + + let mut proposed_down = state.down.desired; + let mut proposed_up = state.up.desired; + if let Some(down) = decision.down { + proposed_down = down; + } + if let Some(up) = decision.up { + proposed_up = up; + } + + let changed_down = proposed_down != state.down.desired; + let changed_up = proposed_up != state.up.desired; + let changed = changed_down || changed_up; + + if devices.is_empty() { + status.warnings.push(format!( + "TreeGuard circuits: circuit '{circuit_id}' has no devices in ShapedDevices.csv." + )); + } else { + for dev in devices.iter() { + managed_device_ids.insert(dev.device_id.clone()); + } + } + + if changed && !devices.is_empty() { + let token = + decisions::format_directional_sqm_override(proposed_down, proposed_up); + + if tg.dry_run { + if changed_down { + state.down.desired = proposed_down; + state.down.last_change_unix = Some(now_unix); + state.down.recent_changes_unix.push_back(now_unix); + prune_recent_changes(&mut state.down.recent_changes_unix, now_unix); + } + if changed_up { + state.up.desired = proposed_up; + state.up.last_change_unix = Some(now_unix); + state.up.recent_changes_unix.push_back(now_unix); + prune_recent_changes(&mut state.up.recent_changes_unix, now_unix); + } + + push_activity( + activity, + TreeguardActivityEntry { + time: now_unix.to_string(), + entity_type: "circuit".to_string(), + entity_id: circuit_entity_id.clone(), + action: format!("would_set_sqm_override:{token}"), + persisted: false, + reason: "Dry-run".to_string(), + }, + ); + status.last_action_summary = Some(format!( + "Would set SQM override for circuit '{}' -> {}", + circuit_label, token + )); + } else { + let mut persisted_ok = false; + let mut can_apply_live = true; + if tg.circuits.persist_sqm_overrides { + match overrides::set_devices_sqm_override(&devices, &token) { + Ok(_) => { + persisted_ok = true; + } + Err(e) => { + can_apply_live = false; + status.warnings.push(format!( + "TreeGuard circuits: failed to persist SQM overrides for circuit '{circuit_id}': {e}" + )); + push_activity( + activity, + TreeguardActivityEntry { + time: now_unix.to_string(), + entity_type: "circuit".to_string(), + entity_id: circuit_entity_id.clone(), + action: "set_sqm_override_failed".to_string(), + persisted: false, + reason: format!("Overrides write failed: {e}"), + }, + ); + } + } + } + + let live_ok = if can_apply_live { + match bakery::apply_circuit_sqm_override_live( + circuit_id, + &devices, + &token, + ) { + Ok(()) => true, + Err(e) => { + status.warnings.push(format!( + "TreeGuard circuits: live SQM apply failed for circuit '{circuit_id}': {e}" + )); + push_activity( + activity, + TreeguardActivityEntry { + time: now_unix.to_string(), + entity_type: "circuit".to_string(), + entity_id: circuit_entity_id.clone(), + action: format!("apply_sqm_live_failed:{token}"), + persisted: persisted_ok, + reason: format!("Bakery live apply failed: {e}"), + }, + ); + false + } + } + } else { + false + }; + + if live_ok || persisted_ok { + if changed_down { + state.down.desired = proposed_down; + state.down.last_change_unix = Some(now_unix); + state.down.recent_changes_unix.push_back(now_unix); + prune_recent_changes(&mut state.down.recent_changes_unix, now_unix); + } + if changed_up { + state.up.desired = proposed_up; + state.up.last_change_unix = Some(now_unix); + state.up.recent_changes_unix.push_back(now_unix); + prune_recent_changes(&mut state.up.recent_changes_unix, now_unix); + } + + let (action, reason) = match (persisted_ok, live_ok) { + (true, true) => ( + "set_sqm_override".to_string(), + "Applied live + persisted".to_string(), + ), + (true, false) => ( + "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(), + ), + }; + push_activity( + activity, + TreeguardActivityEntry { + time: now_unix.to_string(), + entity_type: "circuit".to_string(), + entity_id: circuit_entity_id.clone(), + action: format!("{action}:{token}"), + persisted: persisted_ok, + reason, + }, + ); + + status.last_action_summary = Some(format!( + "SQM override for circuit '{}' -> {}", + circuit_label, token + )); + } + } + } + + if state.down.desired == CircuitSqmState::FqCodel + || state.up.desired == CircuitSqmState::FqCodel + { + fq_codel_circuits += 1; + } + } + } + + status.virtualized_nodes = virtualized_nodes; + status.fq_codel_circuits = fq_codel_circuits; +} + +/// Returns the current `set_node_virtual` override value for `node_name`, if present. +/// +/// This function is pure: it has no side effects. +fn overrides_node_virtual(overrides: &OverrideFile, node_name: &str) -> Option { + overrides + .network_adjustments() + .iter() + .find_map(|adj| match adj { + NetworkAdjustment::SetNodeVirtual { + node_name: n, + virtual_node, + } if n == node_name => Some(*virtual_node), + _ => None, + }) +} + +/// Infers an SQM override token for a circuit, preferring persisted device overlays. +/// +/// This function is pure: it has no side effects. +fn infer_circuit_sqm_override_token( + circuit_id: &str, + shaped_devices: &[lqos_config::ShapedDevice], + overrides: Option<&OverrideFile>, +) -> Option { + let circuit_device_ids: FxHashSet<&str> = shaped_devices + .iter() + .filter(|d| d.circuit_id == circuit_id) + .map(|d| d.device_id.as_str()) + .collect(); + + if let Some(overrides) = overrides { + for dev in overrides.persistent_devices() { + if !circuit_device_ids.contains(dev.device_id.as_str()) { + continue; + } + if let Some(token) = dev.sqm_override.as_deref() { + let token = token.trim(); + if !token.is_empty() { + return Some(token.to_string()); + } + } + } + } + + for dev in shaped_devices.iter().filter(|d| d.circuit_id == circuit_id) { + if let Some(token) = dev.sqm_override.as_deref() { + let token = token.trim(); + if !token.is_empty() { + return Some(token.to_string()); + } + } + } + + None +} + +/// Appends an entry to the activity ring buffer. +/// +/// This function is not pure: it mutates `activity`. +fn push_activity(activity: &mut VecDeque, entry: TreeguardActivityEntry) { + if activity.len() >= ACTIVITY_RING_CAPACITY { + activity.pop_front(); + } + activity.push_back(entry); +} + +/// Removes entries older than one hour from a recent-changes ring buffer. +/// +/// This function is not pure: it mutates `recent_changes`. +fn prune_recent_changes(recent_changes: &mut VecDeque, now_unix: u64) { + while recent_changes + .front() + .is_some_and(|t| now_unix.saturating_sub(*t) > 3600) + { + recent_changes.pop_front(); + } +} + +/// Updates an "idle since" timestamp based on utilization and an idle threshold. +/// +/// This function is not pure: it mutates `idle_since`. +fn update_idle_since(idle_since: &mut Option, now_unix: u64, util_pct: f64, idle_pct: f64) { + if util_pct < idle_pct { + if idle_since.is_none() { + *idle_since = Some(now_unix); + } + } else { + *idle_since = None; + } +} + +/// Updates a "below threshold since" timestamp based on utilization and a threshold. +/// +/// This function is not pure: it mutates `below_since`. +fn update_below_since( + below_since: &mut Option, + now_unix: u64, + util_pct: f64, + threshold_pct: f64, +) { + if util_pct < threshold_pct { + if below_since.is_none() { + *below_since = Some(now_unix); + } + } else { + *below_since = None; + } +} + +/// Returns the minimum of two optional floats, treating `None` as "unknown". +/// +/// This function is pure: it has no side effects. +fn min_opt_f32(a: Option, b: Option) -> Option { + match (a, b) { + (Some(x), Some(y)) => Some(x.min(y)), + (Some(x), None) | (None, Some(x)) => Some(x), + (None, None) => None, + } +} diff --git a/src/rust/lqosd/src/treeguard/bakery.rs b/src/rust/lqosd/src/treeguard/bakery.rs new file mode 100644 index 00000000..99c563f0 --- /dev/null +++ b/src/rust/lqosd/src/treeguard/bakery.rs @@ -0,0 +1,118 @@ +//! Bakery live-update helpers for TreeGuard. +//! +//! This module implements live SQM switching via Bakery commands. + +use crate::treeguard::TreeguardError; +use lqos_bakery::BakeryCommands; +use lqos_config::ShapedDevice; +use lqos_queue_tracker::QUEUE_STRUCTURE; +use lqos_utils::hash_to_i64; + +/// Applies a per-circuit SQM override token live via Bakery. +/// +/// This function has side effects: it reads the in-memory queue structure snapshot and sends a +/// `BakeryCommands::AddCircuit` update to the Bakery thread. +pub(crate) fn apply_circuit_sqm_override_live( + circuit_id: &str, + devices: &[ShapedDevice], + sqm_override: &str, +) -> Result<(), TreeguardError> { + let Some(sender) = lqos_bakery::BAKERY_SENDER.get() else { + return Err(TreeguardError::BakeryNotReady); + }; + + let snapshot = QUEUE_STRUCTURE.load(); + let Some(queues) = snapshot.maybe_queues.as_ref() else { + return Err(TreeguardError::QueueStructureUnavailable { + details: "queueingStructure.json not loaded".to_string(), + }); + }; + + // Find the circuit node in the queue structure. + let mut stack = Vec::new(); + for q in queues.iter() { + stack.push(q); + } + + let mut found = None; + while let Some(node) = stack.pop() { + if node.circuit_id.as_deref() == Some(circuit_id) && node.device_id.is_none() { + found = Some(node); + break; + } + + for c in node.children.iter() { + stack.push(c); + } + for c in node.circuits.iter() { + stack.push(c); + } + for d in node.devices.iter() { + stack.push(d); + } + } + + let Some(node) = found else { + return Err(TreeguardError::CircuitNotFound { + circuit_id: circuit_id.to_string(), + }); + }; + + 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 { + details: format!("class_major too large: {}", node.class_major), + } + })?; + 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); + + sender + .send(BakeryCommands::AddCircuit { + circuit_hash, + parent_class_id: node.parent_class_id, + up_parent_class_id: node.up_parent_class_id, + class_minor, + download_bandwidth_min: node.download_bandwidth_mbps_min as f32, + upload_bandwidth_min: node.upload_bandwidth_mbps_min as f32, + download_bandwidth_max: node.download_bandwidth_mbps as f32, + upload_bandwidth_max: node.upload_bandwidth_mbps as f32, + class_major, + up_class_major, + ip_addresses, + sqm_override: Some(sqm_override.to_string()), + }) + .map_err(|e| TreeguardError::BakerySend { + details: e.to_string(), + })?; + + Ok(()) +} + +/// Builds a comma-separated IP list string from a circuit's shaped devices. +/// +/// This function is pure: it has no side effects. +fn ip_list(devices: &[ShapedDevice]) -> String { + let mut ips = Vec::new(); + for dev in devices { + for (ip, prefix) in dev.ipv4.iter() { + ips.push(format!("{ip}/{prefix}")); + } + for (ip, prefix) in dev.ipv6.iter() { + ips.push(format!("{ip}/{prefix}")); + } + } + ips.sort(); + ips.dedup(); + ips.join(",") +} diff --git a/src/rust/lqosd/src/treeguard/decisions.rs b/src/rust/lqosd/src/treeguard/decisions.rs new file mode 100644 index 00000000..1142edd5 --- /dev/null +++ b/src/rust/lqosd/src/treeguard/decisions.rs @@ -0,0 +1,783 @@ +//! Pure decision logic for TreeGuard. +//! +//! Functions in this module should be pure: they must not perform I/O, mutate globals, +//! or have side effects beyond returning a decision. + +use crate::treeguard::state::{CircuitSqmState, CircuitState, LinkState, LinkVirtualState}; +use lqos_config::{ + TreeguardCircuitsConfig, TreeguardCpuConfig, TreeguardCpuMode, TreeguardLinksConfig, + TreeguardQooConfig, +}; +use lqos_utils::units::DownUpOrder; + +/// A virtualization decision for a managed link/node. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum LinkVirtualDecision { + /// No state change is required. + NoChange, + /// Set the node's desired virtualization state. + Set(LinkVirtualState), +} + +/// A per-circuit SQM switching decision. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct CircuitSqmDecision { + /// Desired download direction SQM state change, if any. + pub down: Option, + /// Desired upload direction SQM state change, if any. + pub up: Option, +} + +/// Returns true if CPU pressure permits taking CPU-saving actions. +/// +/// This function is pure: it has no side effects. +fn cpu_allows_saving(cpu: &TreeguardCpuConfig, cpu_max_pct: Option) -> bool { + match cpu.mode { + TreeguardCpuMode::CpuAware => cpu_max_pct.is_some_and(|pct| pct >= cpu.cpu_high_pct), + TreeguardCpuMode::TrafficRttOnly => true, + } +} + +/// Returns true if CPU headroom calls for reverting CPU-saving actions. +/// +/// This function is pure: it has no side effects. +fn cpu_calls_for_revert(cpu: &TreeguardCpuConfig, cpu_max_pct: Option) -> bool { + match cpu.mode { + TreeguardCpuMode::CpuAware => cpu_max_pct.is_some_and(|pct| pct <= cpu.cpu_low_pct), + TreeguardCpuMode::TrafficRttOnly => false, + } +} + +/// Returns true if QoO (when available) is below the configured threshold for any direction. +/// +/// This function is pure: it has no side effects. +fn qoo_below_threshold(qoo_cfg: &TreeguardQooConfig, qoo: DownUpOrder>) -> bool { + if !qoo_cfg.enabled { + return false; + } + + let below = |v: Option| v.is_some_and(|score| score < qoo_cfg.min_score); + below(qoo.down) || below(qoo.up) +} + +/// Returns true if the given timestamp is within the configured dwell time window. +/// +/// This function is pure: it has no side effects. +fn in_dwell_window(now_unix: u64, last_change_unix: Option, dwell_minutes: u32) -> bool { + let Some(last) = last_change_unix else { + return false; + }; + let dwell_secs = u64::from(dwell_minutes).saturating_mul(60); + now_unix.saturating_sub(last) < dwell_secs +} + +/// Returns true if the number of recent state changes exceeds a configured limit. +/// +/// This function is pure: it has no side effects. +fn rate_limited(recent_changes: usize, max_changes_per_hour: u32) -> bool { + if max_changes_per_hour == 0 { + return true; + } + recent_changes >= max_changes_per_hour as usize +} + +/// Decide whether to virtualize/unvirtualize a managed node. +/// +/// This function is pure: it has no side effects. +pub fn decide_link_virtualization( + now_unix: u64, + allowlisted: bool, + cpu_max_pct: Option, + cpu_cfg: &TreeguardCpuConfig, + links_cfg: &TreeguardLinksConfig, + qoo_cfg: &TreeguardQooConfig, + rtt_missing: bool, + qoo: DownUpOrder>, + util_ewma_pct: DownUpOrder, + sustained_idle: bool, + state: &LinkState, +) -> LinkVirtualDecision { + if !allowlisted { + return LinkVirtualDecision::NoChange; + } + + if in_dwell_window( + now_unix, + state.last_change_unix, + links_cfg.min_state_dwell_minutes, + ) { + return LinkVirtualDecision::NoChange; + } + + if rate_limited( + state.recent_changes_unix.len(), + links_cfg.max_link_changes_per_hour, + ) { + return LinkVirtualDecision::NoChange; + } + + let qoo_bad = qoo_below_threshold(qoo_cfg, qoo); + + match state.desired { + LinkVirtualState::Physical => { + if !cpu_allows_saving(cpu_cfg, cpu_max_pct) { + return LinkVirtualDecision::NoChange; + } + if sustained_idle && !qoo_bad { + LinkVirtualDecision::Set(LinkVirtualState::Virtual) + } else { + LinkVirtualDecision::NoChange + } + } + LinkVirtualState::Virtual => { + let util_high = util_ewma_pct.down >= links_cfg.unvirtualize_util_pct as f64 + || util_ewma_pct.up >= links_cfg.unvirtualize_util_pct as f64; + if util_high || qoo_bad || (rtt_missing && !sustained_idle) { + LinkVirtualDecision::Set(LinkVirtualState::Physical) + } else { + LinkVirtualDecision::NoChange + } + } + } +} + +/// Decide whether to switch a managed circuit's SQM profile per direction. +/// +/// This function is pure: it has no side effects. +pub fn decide_circuit_sqm( + now_unix: u64, + allowlisted: bool, + cpu_max_pct: Option, + cpu_cfg: &TreeguardCpuConfig, + circuits_cfg: &TreeguardCircuitsConfig, + qoo_cfg: &TreeguardQooConfig, + rtt_missing: bool, + qoo: DownUpOrder>, + state: &CircuitState, +) -> CircuitSqmDecision { + if !allowlisted { + return CircuitSqmDecision::default(); + } + + if !circuits_cfg.switching_enabled { + return CircuitSqmDecision::default(); + } + + let mut decision = CircuitSqmDecision::default(); + + let decide_direction = |dir_qoo: Option, + dir_state: &crate::treeguard::state::CircuitDirectionState| + -> Option { + let sustained_idle = dir_state.idle_since_unix.is_some_and(|since| { + let min_secs = u64::from(circuits_cfg.idle_min_minutes).saturating_mul(60); + now_unix.saturating_sub(since) >= min_secs + }); + + let util_pct = dir_state.util_ewma_pct.current().unwrap_or(0.0); + let util_high = util_pct >= circuits_cfg.upgrade_util_pct as f64; + + if in_dwell_window( + now_unix, + dir_state.last_change_unix, + circuits_cfg.min_switch_dwell_minutes, + ) { + return None; + } + + if rate_limited( + dir_state.recent_changes_unix.len(), + circuits_cfg.max_switches_per_hour, + ) { + return None; + } + + let qoo_bad = if qoo_cfg.enabled { + dir_qoo.is_some_and(|score| score < qoo_cfg.min_score) + } else { + false + }; + + match dir_state.desired { + CircuitSqmState::Cake => { + if !sustained_idle { + None + } else if cpu_allows_saving(cpu_cfg, cpu_max_pct) && !qoo_bad { + Some(CircuitSqmState::FqCodel) + } else { + None + } + } + CircuitSqmState::FqCodel => { + if util_high + || qoo_bad + || cpu_calls_for_revert(cpu_cfg, cpu_max_pct) + || (rtt_missing && !sustained_idle) + { + Some(CircuitSqmState::Cake) + } else { + None + } + } + } + }; + + if circuits_cfg.independent_directions { + decision.down = decide_direction(qoo.down, &state.down); + decision.up = decide_direction(qoo.up, &state.up); + } else { + // Non-independent: decide using worst-direction QoO, apply to both directions. + let worst_qoo = match (qoo.down, qoo.up) { + (Some(d), Some(u)) => Some(d.min(u)), + (Some(v), None) | (None, Some(v)) => Some(v), + (None, None) => None, + }; + + let sustained_idle = crate::treeguard::state::is_sustained_idle( + now_unix, + state.down.idle_since_unix, + state.up.idle_since_unix, + circuits_cfg.idle_min_minutes, + ); + let util_down = state.down.util_ewma_pct.current().unwrap_or(0.0); + let util_up = state.up.util_ewma_pct.current().unwrap_or(0.0); + let util_high = util_down >= circuits_cfg.upgrade_util_pct as f64 + || util_up >= circuits_cfg.upgrade_util_pct as f64; + + let qoo_bad = if qoo_cfg.enabled { + worst_qoo.is_some_and(|score| score < qoo_cfg.min_score) + } else { + false + }; + + let desired = if state.down.desired == CircuitSqmState::FqCodel + && state.up.desired == CircuitSqmState::FqCodel + { + CircuitSqmState::FqCodel + } else { + CircuitSqmState::Cake + }; + + let proposed = match desired { + CircuitSqmState::Cake => { + if sustained_idle && cpu_allows_saving(cpu_cfg, cpu_max_pct) && !qoo_bad { + Some(CircuitSqmState::FqCodel) + } else { + None + } + } + CircuitSqmState::FqCodel => { + if util_high + || qoo_bad + || cpu_calls_for_revert(cpu_cfg, cpu_max_pct) + || (rtt_missing && !sustained_idle) + { + Some(CircuitSqmState::Cake) + } else { + None + } + } + }; + + if let Some(s) = proposed { + decision.down = Some(s); + decision.up = Some(s); + } + } + + decision +} + +/// Formats an SQM override token from per-direction desired states. +/// +/// This function is pure: it has no side effects. +pub fn format_directional_sqm_override(down: CircuitSqmState, up: CircuitSqmState) -> String { + let down_s = match down { + CircuitSqmState::Cake => "cake", + CircuitSqmState::FqCodel => "fq_codel", + }; + let up_s = match up { + CircuitSqmState::Cake => "cake", + CircuitSqmState::FqCodel => "fq_codel", + }; + format!("{down_s}/{up_s}") +} + +/// Parses an SQM override token into per-direction SQM states. +/// +/// The token may be a single value (applies to both directions) or a `down/up` token. +/// Empty and `"none"` tokens map to `None` for that direction. +/// +/// This function is pure: it has no side effects. +pub fn parse_directional_sqm_override(token: &str) -> DownUpOrder> { + fn parse_one(t: &str) -> Option { + let t = t.trim(); + if t.is_empty() || t.eq_ignore_ascii_case("none") { + return None; + } + if t.eq_ignore_ascii_case("cake") { + return Some(CircuitSqmState::Cake); + } + if t.eq_ignore_ascii_case("fq_codel") { + return Some(CircuitSqmState::FqCodel); + } + None + } + + let token = token.trim(); + if token.is_empty() { + return DownUpOrder { down: None, up: None }; + } + + if let Some((down, up)) = token.split_once('/') { + return DownUpOrder { + down: parse_one(down), + up: parse_one(up), + }; + } + + let v = parse_one(token); + DownUpOrder { down: v, up: v } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::treeguard::state::{CircuitDirectionState, CircuitState, LinkState}; + use std::collections::VecDeque; + + #[test] + fn link_decision_requires_allowlist() { + let cpu = TreeguardCpuConfig::default(); + let links = TreeguardLinksConfig::default(); + let qoo_cfg = TreeguardQooConfig::default(); + let state = LinkState::default(); + let decision = decide_link_virtualization( + 1000, + false, + Some(90), + &cpu, + &links, + &qoo_cfg, + false, + DownUpOrder { + down: Some(100.0), + up: Some(100.0), + }, + DownUpOrder { down: 0.5, up: 0.5 }, + true, + &state, + ); + assert_eq!(decision, LinkVirtualDecision::NoChange); + } + + #[test] + fn link_virtualizes_when_idle_and_cpu_high() { + let cpu = TreeguardCpuConfig::default(); + let links = TreeguardLinksConfig::default(); + let qoo_cfg = TreeguardQooConfig::default(); + let state = LinkState::default(); + let decision = decide_link_virtualization( + 1000, + true, + Some(90), + &cpu, + &links, + &qoo_cfg, + false, + DownUpOrder { + down: Some(100.0), + up: Some(100.0), + }, + DownUpOrder { down: 1.0, up: 1.0 }, + true, + &state, + ); + assert_eq!(decision, LinkVirtualDecision::Set(LinkVirtualState::Virtual)); + } + + #[test] + fn link_does_not_virtualize_when_cpu_low() { + let cpu = TreeguardCpuConfig::default(); + let links = TreeguardLinksConfig::default(); + let qoo_cfg = TreeguardQooConfig::default(); + let state = LinkState::default(); + let decision = decide_link_virtualization( + 1000, + true, + Some(10), + &cpu, + &links, + &qoo_cfg, + false, + DownUpOrder { + down: Some(100.0), + up: Some(100.0), + }, + DownUpOrder { down: 1.0, up: 1.0 }, + true, + &state, + ); + assert_eq!(decision, LinkVirtualDecision::NoChange); + } + + #[test] + fn link_unvirtualizes_on_util_spike() { + let cpu = TreeguardCpuConfig::default(); + let links = TreeguardLinksConfig::default(); + let qoo_cfg = TreeguardQooConfig::default(); + let mut state = LinkState::default(); + state.desired = LinkVirtualState::Virtual; + + let decision = decide_link_virtualization( + 1000, + true, + Some(90), + &cpu, + &links, + &qoo_cfg, + false, + DownUpOrder { + down: Some(100.0), + up: Some(100.0), + }, + DownUpOrder { down: 10.0, up: 1.0 }, + false, + &state, + ); + assert_eq!( + decision, + LinkVirtualDecision::Set(LinkVirtualState::Physical) + ); + } + + #[test] + fn link_unvirtualizes_when_rtt_missing() { + let cpu = TreeguardCpuConfig::default(); + let links = TreeguardLinksConfig::default(); + let qoo_cfg = TreeguardQooConfig::default(); + let mut state = LinkState::default(); + state.desired = LinkVirtualState::Virtual; + + let decision = decide_link_virtualization( + 1000, + true, + Some(90), + &cpu, + &links, + &qoo_cfg, + true, + DownUpOrder { + down: Some(100.0), + up: Some(100.0), + }, + DownUpOrder { down: 1.0, up: 1.0 }, + false, + &state, + ); + assert_eq!( + decision, + LinkVirtualDecision::Set(LinkVirtualState::Physical) + ); + } + + #[test] + fn link_stays_virtual_when_idle_even_if_rtt_missing() { + let cpu = TreeguardCpuConfig::default(); + let links = TreeguardLinksConfig::default(); + let qoo_cfg = TreeguardQooConfig::default(); + let mut state = LinkState::default(); + state.desired = LinkVirtualState::Virtual; + + let decision = decide_link_virtualization( + 1000, + true, + Some(90), + &cpu, + &links, + &qoo_cfg, + true, + DownUpOrder { + down: Some(100.0), + up: Some(100.0), + }, + DownUpOrder { down: 1.0, up: 1.0 }, + true, + &state, + ); + assert_eq!(decision, LinkVirtualDecision::NoChange); + } + + #[test] + fn link_dwell_time_blocks_changes() { + let cpu = TreeguardCpuConfig::default(); + let links = TreeguardLinksConfig::default(); + let qoo_cfg = TreeguardQooConfig::default(); + let mut state = LinkState::default(); + state.last_change_unix = Some(1000 - 60); + + let decision = decide_link_virtualization( + 1000, + true, + Some(90), + &cpu, + &links, + &qoo_cfg, + false, + DownUpOrder { + down: Some(100.0), + up: Some(100.0), + }, + DownUpOrder { down: 1.0, up: 1.0 }, + true, + &state, + ); + assert_eq!(decision, LinkVirtualDecision::NoChange); + } + + #[test] + fn link_rate_limit_blocks_changes() { + let cpu = TreeguardCpuConfig::default(); + let links = TreeguardLinksConfig::default(); + let qoo_cfg = TreeguardQooConfig::default(); + let mut state = LinkState::default(); + state.recent_changes_unix = VecDeque::from(vec![1, 2, 3, 4]); + + let decision = decide_link_virtualization( + 1000, + true, + Some(90), + &cpu, + &links, + &qoo_cfg, + false, + DownUpOrder { + down: Some(100.0), + up: Some(100.0), + }, + DownUpOrder { down: 1.0, up: 1.0 }, + true, + &state, + ); + assert_eq!(decision, LinkVirtualDecision::NoChange); + } + + #[test] + fn circuit_decision_requires_allowlist() { + let cpu = TreeguardCpuConfig::default(); + let circuits = TreeguardCircuitsConfig::default(); + let qoo_cfg = TreeguardQooConfig::default(); + let state = CircuitState::default(); + let decision = decide_circuit_sqm( + 1000, + false, + Some(90), + &cpu, + &circuits, + &qoo_cfg, + false, + DownUpOrder { + down: Some(90.0), + up: Some(90.0), + }, + &state, + ); + assert_eq!(decision, CircuitSqmDecision::default()); + } + + #[test] + fn circuit_downgrades_when_sustained_idle_and_cpu_high() { + let cpu = TreeguardCpuConfig::default(); + let circuits = TreeguardCircuitsConfig::default(); + let qoo_cfg = TreeguardQooConfig::default(); + let mut state = CircuitState::default(); + state.down.idle_since_unix = Some(1000 - 900); + state.up.idle_since_unix = Some(1000 - 900); + state.down.util_ewma_pct.update(1.0, 0.1); + state.up.util_ewma_pct.update(1.0, 0.1); + let decision = decide_circuit_sqm( + 1000, + true, + Some(90), + &cpu, + &circuits, + &qoo_cfg, + false, + DownUpOrder { + down: Some(90.0), + up: Some(90.0), + }, + &state, + ); + assert_eq!(decision.down, Some(CircuitSqmState::FqCodel)); + assert_eq!(decision.up, Some(CircuitSqmState::FqCodel)); + } + + #[test] + fn circuit_independent_directions_respect_qoo() { + let cpu = TreeguardCpuConfig::default(); + let circuits = TreeguardCircuitsConfig::default(); + let qoo_cfg = TreeguardQooConfig::default(); + let mut state = CircuitState::default(); + state.down.idle_since_unix = Some(1000 - 900); + state.up.idle_since_unix = Some(1000 - 900); + state.down.util_ewma_pct.update(1.0, 0.1); + state.up.util_ewma_pct.update(1.0, 0.1); + let decision = decide_circuit_sqm( + 1000, + true, + Some(90), + &cpu, + &circuits, + &qoo_cfg, + false, + DownUpOrder { + down: Some(90.0), + up: Some(50.0), + }, + &state, + ); + assert_eq!(decision.down, Some(CircuitSqmState::FqCodel)); + assert_eq!(decision.up, None); + } + + #[test] + fn circuit_reverts_when_cpu_low() { + let cpu = TreeguardCpuConfig::default(); + let circuits = TreeguardCircuitsConfig::default(); + let qoo_cfg = TreeguardQooConfig::default(); + let mut state = CircuitState::default(); + state.down = CircuitDirectionState { + desired: CircuitSqmState::FqCodel, + ..Default::default() + }; + state.up = CircuitDirectionState { + desired: CircuitSqmState::FqCodel, + ..Default::default() + }; + + let decision = decide_circuit_sqm( + 1000, + true, + Some(10), + &cpu, + &circuits, + &qoo_cfg, + false, + DownUpOrder { + down: Some(90.0), + up: Some(90.0), + }, + &state, + ); + assert_eq!(decision.down, Some(CircuitSqmState::Cake)); + assert_eq!(decision.up, Some(CircuitSqmState::Cake)); + } + + #[test] + fn circuit_missing_rtt_does_not_block_downgrade_when_idle() { + let cpu = TreeguardCpuConfig::default(); + let circuits = TreeguardCircuitsConfig::default(); + let qoo_cfg = TreeguardQooConfig::default(); + let mut state = CircuitState::default(); + state.down.idle_since_unix = Some(1000 - 900); + state.up.idle_since_unix = Some(1000 - 900); + state.down.util_ewma_pct.update(1.0, 0.1); + state.up.util_ewma_pct.update(1.0, 0.1); + + let decision = decide_circuit_sqm( + 1000, + true, + Some(90), + &cpu, + &circuits, + &qoo_cfg, + true, + DownUpOrder { + down: Some(90.0), + up: Some(90.0), + }, + &state, + ); + assert_eq!(decision.down, Some(CircuitSqmState::FqCodel)); + assert_eq!(decision.up, Some(CircuitSqmState::FqCodel)); + } + + #[test] + fn circuit_reverts_when_utilization_rises() { + let cpu = TreeguardCpuConfig::default(); + let circuits = TreeguardCircuitsConfig::default(); + let qoo_cfg = TreeguardQooConfig::default(); + let mut state = CircuitState::default(); + state.down.desired = CircuitSqmState::FqCodel; + state.up.desired = CircuitSqmState::FqCodel; + state.down.util_ewma_pct.update(10.0, 0.1); + state.up.util_ewma_pct.update(10.0, 0.1); + + let decision = decide_circuit_sqm( + 1000, + true, + Some(90), + &cpu, + &circuits, + &qoo_cfg, + false, + DownUpOrder { + down: Some(90.0), + up: Some(90.0), + }, + &state, + ); + assert_eq!(decision.down, Some(CircuitSqmState::Cake)); + assert_eq!(decision.up, Some(CircuitSqmState::Cake)); + } + + #[test] + fn circuit_dwell_time_blocks_switch() { + let cpu = TreeguardCpuConfig::default(); + let circuits = TreeguardCircuitsConfig::default(); + let qoo_cfg = TreeguardQooConfig::default(); + let mut state = CircuitState::default(); + state.down.last_change_unix = Some(1000 - 60); + state.up.last_change_unix = Some(1000 - 60); + + let decision = decide_circuit_sqm( + 1000, + true, + Some(90), + &cpu, + &circuits, + &qoo_cfg, + false, + DownUpOrder { + down: Some(90.0), + up: Some(90.0), + }, + &state, + ); + assert_eq!(decision, CircuitSqmDecision::default()); + } + + #[test] + fn directional_token_format_and_parse() { + assert_eq!( + format_directional_sqm_override(CircuitSqmState::Cake, CircuitSqmState::FqCodel), + "cake/fq_codel" + ); + + let parsed = parse_directional_sqm_override("cake/fq_codel"); + assert_eq!(parsed.down, Some(CircuitSqmState::Cake)); + assert_eq!(parsed.up, Some(CircuitSqmState::FqCodel)); + + let parsed = parse_directional_sqm_override("fq_codel"); + assert_eq!(parsed.down, Some(CircuitSqmState::FqCodel)); + assert_eq!(parsed.up, Some(CircuitSqmState::FqCodel)); + + let parsed = parse_directional_sqm_override("none"); + assert_eq!(parsed.down, None); + assert_eq!(parsed.up, None); + + let parsed = parse_directional_sqm_override("/fq_codel"); + assert_eq!(parsed.down, None); + assert_eq!(parsed.up, Some(CircuitSqmState::FqCodel)); + } +} diff --git a/src/rust/lqosd/src/treeguard/errors.rs b/src/rust/lqosd/src/treeguard/errors.rs new file mode 100644 index 00000000..e4f2bb81 --- /dev/null +++ b/src/rust/lqosd/src/treeguard/errors.rs @@ -0,0 +1,39 @@ +//! TreeGuard error types. + +use thiserror::Error; + +/// Errors returned by TreeGuard APIs. +#[derive(Error, Debug)] +pub enum TreeguardError { + /// The TreeGuard actor thread could not be spawned. + #[error("failed to spawn TreeGuard actor thread: {0}")] + SpawnThread(#[from] std::io::Error), + + /// The overrides file could not be loaded. + #[error("failed to load overrides file: {details}")] + OverridesLoad { details: String }, + + /// The overrides file could not be saved. + #[error("failed to save overrides file: {details}")] + OverridesSave { details: String }, + + /// Bakery is not initialized. + #[error("bakery is not initialized")] + BakeryNotReady, + + /// Failed to send a command to Bakery. + #[error("failed to send command to bakery: {details}")] + BakerySend { details: String }, + + /// The queue structure snapshot was unavailable. + #[error("queue structure snapshot unavailable: {details}")] + QueueStructureUnavailable { details: String }, + + /// The circuit was not found in the queue structure snapshot. + #[error("circuit not found in queue structure: {circuit_id}")] + CircuitNotFound { circuit_id: String }, + + /// A queue structure class identifier was invalid. + #[error("invalid queue structure class id: {details}")] + InvalidClassId { details: String }, +} diff --git a/src/rust/lqosd/src/treeguard/mod.rs b/src/rust/lqosd/src/treeguard/mod.rs new file mode 100644 index 00000000..41868a0f --- /dev/null +++ b/src/rust/lqosd/src/treeguard/mod.rs @@ -0,0 +1,17 @@ +//! TreeGuard subsystem for intelligent node management. +//! +//! This module provides an actor-driven control loop that can: +//! - monitor link utilization and RTT, +//! - virtualize/unvirtualize selected network nodes, and +//! - adjust per-circuit shaping behavior to reduce CPU load. + +pub(crate) mod actor; +pub(crate) mod bakery; +pub(crate) mod decisions; +pub(crate) mod errors; +pub(crate) mod overrides; +pub(crate) mod reload; +pub(crate) mod state; +pub(crate) mod status; + +pub(crate) use errors::TreeguardError; diff --git a/src/rust/lqosd/src/treeguard/overrides.rs b/src/rust/lqosd/src/treeguard/overrides.rs new file mode 100644 index 00000000..7f266630 --- /dev/null +++ b/src/rust/lqosd/src/treeguard/overrides.rs @@ -0,0 +1,141 @@ +//! Persistence helpers for TreeGuard. +//! +//! This module writes TreeGuard-owned changes to `lqos_overrides.treeguard.json`. + +use crate::treeguard::TreeguardError; +use lqos_config::ShapedDevice; +use lqos_overrides::{NetworkAdjustment, OverrideFile, OverrideLayer, OverrideStore}; + +/// Returns the current virtual override value for `node_name`, if present. +/// +/// This function is pure: it does not perform I/O and has no side effects. +fn current_node_virtual_override(overrides: &OverrideFile, node_name: &str) -> Option { + overrides + .network_adjustments() + .iter() + .find_map(|adj| match adj { + NetworkAdjustment::SetNodeVirtual { + node_name: n, + virtual_node, + } if n == node_name => Some(*virtual_node), + _ => None, + }) +} + +/// Sets (adds or replaces) a node-virtualization override for a `network.json` node. +/// +/// This function is not pure: it reads and writes `lqos_overrides.treeguard.json`. +/// +/// Returns `Ok(true)` if the file was changed, `Ok(false)` if no change was needed. +pub(crate) fn set_node_virtual( + node_name: &str, + virtual_node: bool, +) -> Result { + 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) { + return Ok(false); + } + + overrides.set_network_node_virtual(node_name.to_string(), virtual_node); + OverrideStore::save_layer(OverrideLayer::Treeguard, &overrides).map_err(|e| { + TreeguardError::OverridesSave { + details: e.to_string(), + } + })?; + Ok(true) +} + +/// Removes any node-virtualization overrides for a `network.json` node. +/// +/// This function is not pure: it reads and writes `lqos_overrides.treeguard.json`. +/// +/// 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 removed = overrides.remove_network_node_virtual_by_name_count(node_name); + if removed == 0 { + return Ok(false); + } + + OverrideStore::save_layer(OverrideLayer::Treeguard, &overrides).map_err(|e| { + TreeguardError::OverridesSave { + details: e.to_string(), + } + })?; + Ok(true) +} + +/// Persists a per-device SQM override token for a list of devices by storing persistent shaped +/// device overlays. +/// +/// This function is not pure: it reads and writes `lqos_overrides.treeguard.json`. +/// +/// Returns `Ok(true)` if the file was changed, `Ok(false)` if no change was needed. +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 changed = false; + for base_device in base_devices { + let mut device = base_device.clone(); + device.sqm_override = Some(sqm_override.to_string()); + if overrides.add_persistent_shaped_device_return_changed(device) { + changed = true; + } + } + + if !changed { + return Ok(false); + } + + OverrideStore::save_layer(OverrideLayer::Treeguard, &overrides).map_err(|e| { + TreeguardError::OverridesSave { + details: e.to_string(), + } + })?; + Ok(true) +} + +/// Removes any persistent shaped device overlay entries for a list of device IDs. +/// +/// This function is not pure: it reads and writes `lqos_overrides.treeguard.json`. +/// +/// 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 removed_any = false; + for device_id in device_ids { + let removed = overrides.remove_persistent_shaped_device_by_device_count(device_id); + if removed > 0 { + removed_any = true; + } + } + + if !removed_any { + return Ok(false); + } + + OverrideStore::save_layer(OverrideLayer::Treeguard, &overrides).map_err(|e| { + TreeguardError::OverridesSave { + details: e.to_string(), + } + })?; + Ok(true) +} diff --git a/src/rust/lqosd/src/treeguard/reload.rs b/src/rust/lqosd/src/treeguard/reload.rs new file mode 100644 index 00000000..b1215381 --- /dev/null +++ b/src/rust/lqosd/src/treeguard/reload.rs @@ -0,0 +1,219 @@ +//! Topology reload helpers for TreeGuard. +//! +//! 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}; + +const MIN_COOLDOWN_SECONDS: u64 = 60; +const MAX_BACKOFF_SECONDS: u64 = 2 * 60 * 60; // 2 hours + +/// Reload request priority. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) enum ReloadPriority { + /// Normal reload requests obey cooldown/backoff. + #[default] + Normal, + /// Urgent reload requests bypass cooldown (but still respect backoff). + Urgent, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum SkipKind { + Backoff, + Cooldown, + Busy, +} + +/// Result of polling the reload controller. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct ReloadAttempt { + pub(crate) outcome: ReloadOutcome, + pub(crate) request_reason: Option, +} + +/// Result of a reload attempt. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) enum ReloadOutcome { + /// Reload succeeded. + Success { + /// Output from the reload command. + message: String, + }, + /// Reload was skipped because cooldown/backoff is active. + Skipped { + /// Human-readable reason for skipping. + reason: String, + /// Next UNIX timestamp when a reload may be attempted. + next_allowed_unix: Option, + }, + /// Reload failed (and backoff has been applied). + Failed { + /// Human-readable error. + error: String, + /// Next UNIX timestamp when a reload may be attempted. + next_allowed_unix: Option, + }, +} + +/// Cooldown/backoff controller for topology reload requests. +#[derive(Clone, Debug, Default)] +pub(crate) struct ReloadController { + last_attempt_unix: Option, + consecutive_failures: u32, + backoff_until_unix: Option, + pending: bool, + pending_priority: ReloadPriority, + pending_reason: Option, + last_reported_skip: Option<(SkipKind, Option)>, +} + +impl ReloadController { + /// Enqueues a reload request with a given priority and human-readable reason. + /// + /// This function is not pure: it mutates internal pending state. + pub(crate) fn request_reload(&mut self, priority: ReloadPriority, reason: String) { + if !self.pending { + self.pending = true; + self.pending_priority = priority; + self.pending_reason = Some(reason); + } else { + if priority == ReloadPriority::Urgent { + self.pending_priority = ReloadPriority::Urgent; + } + match self.pending_reason.as_deref() { + None => self.pending_reason = Some(reason), + Some(existing) => { + if existing != reason && existing != "Multiple node topology changes" { + self.pending_reason = Some("Multiple node topology changes".to_string()); + } + } + } + } + // Ensure we emit at least one skip outcome for a newly requested reload. + self.last_reported_skip = None; + } + + /// Polls for a pending reload request and attempts it if allowed. + /// + /// Returns `Some(...)` when an outcome should be surfaced to the activity log; repeated + /// skip outcomes are suppressed to avoid flooding the activity ring. + pub(crate) fn poll_reload( + &mut self, + now_unix: u64, + cooldown_minutes: u32, + ) -> Option { + if !self.pending { + return None; + } + + let cooldown_seconds = u64::from(cooldown_minutes) + .saturating_mul(60) + .max(MIN_COOLDOWN_SECONDS); + + if let Some(until) = self.backoff_until_unix { + if now_unix < until { + return self.maybe_report_skip( + SkipKind::Backoff, + Some(until), + "Reload backoff active".to_string(), + Some(until), + ); + } + } + + if self.pending_priority == ReloadPriority::Normal { + if let Some(last) = self.last_attempt_unix { + let next = last.saturating_add(cooldown_seconds); + if now_unix < next { + return self.maybe_report_skip( + SkipKind::Cooldown, + Some(next), + "Reload cooldown active".to_string(), + Some(next), + ); + } + } + } + + match try_reload_libreqos_locked() { + ReloadExecOutcome::Busy => self.maybe_report_skip( + SkipKind::Busy, + None, + "Reload already in progress".to_string(), + None, + ), + ReloadExecOutcome::Success(message) => { + self.last_attempt_unix = Some(now_unix); + self.consecutive_failures = 0; + self.backoff_until_unix = None; + self.pending = false; + self.pending_priority = ReloadPriority::Normal; + let why = self + .pending_reason + .take() + .unwrap_or_else(|| "Topology change".to_string()); + self.last_reported_skip = None; + Some(ReloadAttempt { + outcome: ReloadOutcome::Success { message }, + request_reason: Some(why), + }) + } + ReloadExecOutcome::Failed(error) => { + self.last_attempt_unix = Some(now_unix); + self.consecutive_failures = self.consecutive_failures.saturating_add(1); + let backoff_seconds = backoff_seconds(cooldown_seconds, self.consecutive_failures); + let next = now_unix.saturating_add(backoff_seconds); + self.backoff_until_unix = Some(next); + self.last_reported_skip = None; + let why = self + .pending_reason + .clone() + .unwrap_or_else(|| "Topology change".to_string()); + Some(ReloadAttempt { + outcome: ReloadOutcome::Failed { + error, + next_allowed_unix: Some(next), + }, + request_reason: Some(why), + }) + } + } + } + + fn maybe_report_skip( + &mut self, + kind: SkipKind, + key_next_allowed_unix: Option, + reason: String, + next_allowed_unix: Option, + ) -> Option { + let key = (kind, key_next_allowed_unix); + if self.last_reported_skip == Some(key) { + return None; + } + self.last_reported_skip = Some(key); + Some(ReloadAttempt { + outcome: ReloadOutcome::Skipped { + reason, + next_allowed_unix, + }, + request_reason: None, + }) + } +} + +/// Computes the backoff window in seconds given a cooldown and consecutive failure count. +/// +/// This function is pure: it has no side effects. +fn backoff_seconds(cooldown_seconds: u64, consecutive_failures: u32) -> u64 { + if consecutive_failures == 0 { + return cooldown_seconds; + } + + let exp = consecutive_failures.saturating_sub(1).min(10); // cap exponent + let mult = 1u64 << exp; + cooldown_seconds + .saturating_mul(mult) + .min(MAX_BACKOFF_SECONDS) +} diff --git a/src/rust/lqosd/src/treeguard/state.rs b/src/rust/lqosd/src/treeguard/state.rs new file mode 100644 index 00000000..01ebcad3 --- /dev/null +++ b/src/rust/lqosd/src/treeguard/state.rs @@ -0,0 +1,163 @@ +//! TreeGuard per-entity state. +//! +//! This module will hold per-node and per-circuit state such as dwell timers, +//! last-seen timestamps, and smoothed telemetry. + +use std::collections::VecDeque; + +/// Smoothed state using an exponential weighted moving average (EWMA). +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct Ewma { + initialized: bool, + value: f64, +} + +impl Ewma { + /// Updates the EWMA with a new sample and returns the updated value. + /// + /// This function is not pure: it mutates `self`. + pub fn update(&mut self, sample: f64, alpha: f64) -> f64 { + if !self.initialized { + self.initialized = true; + self.value = sample; + return self.value; + } + + self.value = (alpha * sample) + ((1.0 - alpha) * self.value); + self.value + } + + /// Returns the current EWMA value if it has been initialized. + /// + /// This function is pure: it has no side effects. + pub fn current(&self) -> Option { + if self.initialized { + Some(self.value) + } else { + None + } + } +} + +/// Virtualization state for a managed link/node. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] +pub enum LinkVirtualState { + /// Node should be present in the physical shaping tree. + #[default] + Physical, + /// Node should be marked virtual (logical-only). + Virtual, +} + +/// SQM profile state for a managed circuit direction. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] +pub enum CircuitSqmState { + /// Use CAKE (higher CPU cost, higher quality). + #[default] + Cake, + /// Use fq_codel (lower CPU cost). + FqCodel, +} + +/// Per-direction link tracking state. +#[derive(Clone, Debug, Default)] +pub struct LinkDirectionState { + /// Smoothed utilization percentage. + pub util_ewma_pct: Ewma, + /// When the link first went idle (seconds since UNIX epoch), if currently idle. + pub idle_since_unix: Option, + /// When the link first went below the configured top-level safe-util threshold (seconds since + /// UNIX epoch), if currently below. + pub top_level_safe_since_unix: Option, +} + +/// Per-node link virtualization tracking state. +#[derive(Clone, Debug, Default)] +pub struct LinkState { + /// Current desired virtualization state as managed by TreeGuard. + pub desired: LinkVirtualState, + /// Last state change time (seconds since UNIX epoch), if any. + pub last_change_unix: Option, + /// History of recent state changes (seconds since UNIX epoch), newest at the back. + pub recent_changes_unix: VecDeque, + /// Download direction tracking state. + pub down: LinkDirectionState, + /// Upload direction tracking state. + pub up: LinkDirectionState, +} + +/// Per-direction circuit SQM switching tracking state. +#[derive(Clone, Debug, Default)] +pub struct CircuitDirectionState { + /// Current desired SQM profile for this direction. + pub desired: CircuitSqmState, + /// Last state change time (seconds since UNIX epoch), if any. + pub last_change_unix: Option, + /// History of recent SQM switches (seconds since UNIX epoch), newest at the back. + pub recent_changes_unix: VecDeque, + /// Smoothed utilization percentage. + pub util_ewma_pct: Ewma, + /// When the circuit direction first went idle (seconds since UNIX epoch), if currently idle. + pub idle_since_unix: Option, +} + +/// Per-circuit SQM switching tracking state. +#[derive(Clone, Debug, Default)] +pub struct CircuitState { + /// Download direction SQM state. + pub down: CircuitDirectionState, + /// Upload direction SQM state. + pub up: CircuitDirectionState, +} + +/// Returns true if both directions have been idle for at least `idle_min_minutes`. +/// +/// This function is pure: it has no side effects. +pub fn is_sustained_window( + now_unix: u64, + down_since_unix: Option, + up_since_unix: Option, + min_minutes: u32, +) -> bool { + let (Some(down_since), Some(up_since)) = (down_since_unix, up_since_unix) else { + return false; + }; + + let min_secs = u64::from(min_minutes).saturating_mul(60); + now_unix.saturating_sub(down_since) >= min_secs && now_unix.saturating_sub(up_since) >= min_secs +} + +pub fn is_sustained_idle( + now_unix: u64, + down_idle_since_unix: Option, + up_idle_since_unix: Option, + idle_min_minutes: u32, +) -> bool { + is_sustained_window( + now_unix, + down_idle_since_unix, + up_idle_since_unix, + idle_min_minutes, + ) +} + +#[cfg(test)] +mod tests { + use super::is_sustained_idle; + + #[test] + fn sustained_idle_requires_both_directions() { + assert!(!is_sustained_idle(1000, Some(0), None, 15)); + assert!(!is_sustained_idle(1000, None, Some(0), 15)); + assert!(!is_sustained_idle(1000, None, None, 15)); + } + + #[test] + 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)); + // 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 new file mode 100644 index 00000000..d5398c43 --- /dev/null +++ b/src/rust/lqosd/src/treeguard/status.rs @@ -0,0 +1,71 @@ +//! TreeGuard status snapshots for UI visibility. + +use crate::node_manager::ws::messages::{TreeguardActivityEntry, TreeguardStatusData}; +use crate::treeguard::actor; +use lqos_config::load_config; + +/// Takes a snapshot of TreeGuard status for UI publication. +/// +/// This function is not pure: it sends a request to the TreeGuard actor, and may fall back to +/// reading the current configuration from disk (via the config cache). +pub async fn treeguard_status_snapshot() -> TreeguardStatusData { + if let Some(snapshot) = actor::request_status_snapshot().await { + return snapshot; + } + + let Ok(config) = load_config() else { + return TreeguardStatusData { + enabled: false, + dry_run: true, + cpu_max_pct: None, + managed_nodes: 0, + managed_circuits: 0, + virtualized_nodes: 0, + fq_codel_circuits: 0, + last_action_summary: None, + warnings: vec!["Unable to load configuration; TreeGuard status unavailable.".to_string()], + }; + }; + + let tg = &config.treeguard; + let mut warnings = Vec::new(); + + if tg.enabled + && !tg.links.all_nodes + && tg.links.nodes.is_empty() + && !tg.links.top_level_auto_virtualize + && !tg.circuits.all_circuits + && tg.circuits.circuits.is_empty() + { + warnings.push( + "TreeGuard is enabled but no nodes/circuits are allowlisted. No actions will occur." + .to_string(), + ); + } + + 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_circuits: if tg.circuits.all_circuits { + 0 + } else { + tg.circuits.circuits.len() + }, + virtualized_nodes: 0, + fq_codel_circuits: 0, + last_action_summary: None, + warnings, + } +} + +/// Takes a snapshot of recent TreeGuard activity for UI publication. +/// +/// 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() +} diff --git a/src/scheduler.py b/src/scheduler.py index 6603cb37..e8137ed9 100644 --- a/src/scheduler.py +++ b/src/scheduler.py @@ -321,7 +321,7 @@ def apply_lqos_overrides(): header, rows = read_shaped_devices_csv(path) # 1) Persistent devices: replace by device_id or append - extra = overrides_persistent_devices() + extra = overrides_persistent_devices_effective() override_rows = override_devices_to_rows(extra or []) merged_rows, changed = merge_rows_replace_by_device_id(rows, override_rows) @@ -424,7 +424,7 @@ def apply_network_adjustments(network: dict) -> bool: Returns True if any changes were applied. """ try: - adjustments = overrides_network_adjustments() + adjustments = overrides_network_adjustments_effective() except Exception as e: print(f"Failed to read network adjustments: {e}") return False -- knotmirror 0.0.1 From 61556de8ff53b489e98d4e7064c16d292bcccaa1 Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Mon, 9 Mar 2026 16:01:10 -0500 Subject: [PATCH 4/5] Feat: harden StormGuard and TreeGuard coexistence --- STORMGUARD_TREEGUARD.md | 139 +++++ src/lqos.example | 21 +- src/rust/Cargo.lock | 1 + .../lqos_config/src/etc/v15/stormguard.rs | 219 ++++++- .../lqos_config/src/etc/v15/top_config.rs | 71 +++ src/rust/lqos_overrides/src/overrides_file.rs | 168 +++++- src/rust/lqos_python/src/lib.rs | 22 +- src/rust/lqos_stormguard/Cargo.toml | 3 +- src/rust/lqos_stormguard/README.md | 36 +- .../lqos_stormguard/src/adaptive_actions.rs | 386 ++++++++++++ src/rust/lqos_stormguard/src/config.rs | 95 ++- src/rust/lqos_stormguard/src/lib.rs | 6 +- .../lqos_stormguard/src/queue_structure.rs | 43 +- src/rust/lqos_stormguard/src/site_state.rs | 569 ++++++++++++++---- .../js_build/src/config_stormguard.js | 402 ++++++++++--- .../static2/config_stormguard.html | 149 ++++- 16 files changed, 2051 insertions(+), 279 deletions(-) create mode 100644 STORMGUARD_TREEGUARD.md create mode 100644 src/rust/lqos_stormguard/src/adaptive_actions.rs diff --git a/STORMGUARD_TREEGUARD.md b/STORMGUARD_TREEGUARD.md new file mode 100644 index 00000000..e0037215 --- /dev/null +++ b/STORMGUARD_TREEGUARD.md @@ -0,0 +1,139 @@ +# StormGuard and TreeGuard + +## Current Relationship + +StormGuard and TreeGuard overlap in intent, but not yet in implementation. + +- StormGuard is a live runtime component that watches telemetry and changes top-level HTB ceilings dynamically. +- TreeGuard, in the current branch, is primarily config, defaults, dashboard, and UI/schema work. +- TreeGuard does not yet appear to have a backend worker in this repo comparable to `lqos_stormguard`. + +That means the immediate reuse opportunity is not "replace StormGuard with TreeGuard", but "reuse the better TreeGuard control model and persistence contract to improve StormGuard". + +## What StormGuard Does Today + +StormGuard: + +- loads a configured allowlist of site names from `[stormguard].targets` +- resolves those names into queue nodes and dependent child nodes +- monitors throughput, retransmits, and RTT once per second +- applies multiplicative HTB ceiling changes through the bakery +- keeps an in-memory override map in the bakery so limits can be replayed after queue rebuilds in the same process + +Relevant code: + +- `src/rust/lqos_stormguard/src/lib.rs` +- `src/rust/lqos_stormguard/src/config.rs` +- `src/rust/lqos_stormguard/src/site_state.rs` +- `src/rust/lqos_bakery/src/lib.rs` + +## What TreeGuard Adds Conceptually + +TreeGuard introduces a more operationally useful model: + +- broad scope controls such as `all_nodes` and `all_circuits` +- explicit allowlists only when narrowing scope +- configurable dwell times, rate limits, and cooldowns +- explicit dry-run and enable toggles +- a persistence concept for scheduler-safe SQM overrides + +Relevant code: + +- `src/rust/lqos_config/src/etc/v15/treeguard.rs` +- `src/rust/lqosd/src/node_manager/static2/config_treeguard.html` + +## Best Opportunities + +### 1. Move StormGuard to persistent overrides + +This is the biggest improvement. + +Today StormGuard writes live HTB changes and the bakery stores them in an in-memory `stormguard_overrides` map. That lets the bakery replay them after queue rebuilds while `lqosd` remains alive, but it is still not a durable source of truth across restart. + +TreeGuard already establishes the right direction: persist adaptive changes so scheduler and rebuild flows do not fight them. + +Recommended direction: + +- replace StormGuard's in-memory-only override map with a persisted override file or persisted override store +- replay persisted overrides at bakery rebuild time +- keep dry-run behavior unchanged +- expose override state in debug UI so operators can see what is active + +This would directly address the historical "it is overwritten on scheduler run" problem more cleanly than the current in-memory replay. + +## 2. Give StormGuard TreeGuard-style scope controls + +StormGuard currently depends on a manual `targets` list of site names. + +TreeGuard's scope model is better: + +- apply to all eligible objects by default +- optionally narrow scope with an allowlist + +Recommended direction: + +- add `all_sites = true/false` to StormGuard +- keep `targets` only as an allowlist when `all_sites = false` +- consider a small exclusion list if operators want broad enablement with a few carve-outs + +This would make StormGuard much easier to deploy at scale. + +## 3. Move StormGuard policy constants into config + +StormGuard currently hardcodes: + +- increase/decrease multipliers +- cooldown timing +- some effective policy behavior thresholds + +TreeGuard's config model is more release-friendly because operators can tune behavior without code changes. + +Recommended direction: + +- expose StormGuard multipliers in config +- expose cooldowns and rate limits in config +- expose optional per-direction behavior controls +- validate these values in `lqos_config` the same way TreeGuard now validates its ranges and relationships + +This would reduce risk and make StormGuard easier to support. + +## 4. Use TreeGuard-style circuit actions when StormGuard cannot safely touch HTB + +StormGuard explicitly skips circuit-level queues that host a qdisc, because changing HTB at that level is unsafe. + +TreeGuard's circuit model suggests a better fallback: + +- when StormGuard detects instability on a queue it should not modify directly +- hand off a per-circuit mitigation action instead of doing nothing +- the obvious candidate is TreeGuard-style SQM switching such as CAKE to fq_codel for CPU savings or recovery behavior + +This is likely the cleanest place where TreeGuard extends StormGuard rather than replaces it. + +## 5. Build one shared adaptive-override substrate + +Longer term, StormGuard and TreeGuard probably should not each own their own action plumbing. + +Better structure: + +- StormGuard remains the congestion/instability policy +- TreeGuard remains the topology/SQM policy +- both emit actions into one shared override layer +- the bakery owns persistence, replay, and application of overrides +- the UI/debug layer reports active overrides and why they were applied + +That would avoid duplicated action paths and make adaptive behavior easier to reason about. + +## Practical Recommendation Order + +If we want the highest value with the least disruption: + +1. Add persistent StormGuard overrides first. +2. Add TreeGuard-style scope controls to StormGuard. +3. Move StormGuard tuning constants into config. +4. Add a handoff path where StormGuard can trigger TreeGuard-style circuit actions for qdisc-hosting queues. +5. Only after that, consider unifying both systems under a single adaptive framework. + +## One Caution + +While reviewing StormGuard, the dependent-node discovery in `src/rust/lqos_stormguard/src/queue_structure.rs` looks worth re-checking before building more behavior on top of it. The descendant filter logic is compact and may be more fragile than intended. + diff --git a/src/lqos.example b/src/lqos.example index 81f9c4a5..754929bd 100644 --- a/src/lqos.example +++ b/src/lqos.example @@ -130,7 +130,20 @@ token = "" [stormguard] enabled = false -targets = [ ] -dry_run = false -minimum_download_percentage = 0.25 -minimum_upload_percentage = 0.25 +dry_run = true +all_sites = false +targets = [] +exclude_sites = [] +minimum_download_percentage = 0.5 +minimum_upload_percentage = 0.5 +increase_fast_multiplier = 1.30 +increase_multiplier = 1.15 +decrease_multiplier = 0.95 +decrease_fast_multiplier = 0.88 +increase_fast_cooldown_seconds = 2.0 +increase_cooldown_seconds = 1.0 +decrease_cooldown_seconds = 3.75 +decrease_fast_cooldown_seconds = 7.5 +circuit_fallback_enabled = false +circuit_fallback_persist = true +circuit_fallback_sqm = "fq_codel" diff --git a/src/rust/Cargo.lock b/src/rust/Cargo.lock index 9943e969..03ff809a 100644 --- a/src/rust/Cargo.lock +++ b/src/rust/Cargo.lock @@ -2155,6 +2155,7 @@ dependencies = [ "lqos_bakery", "lqos_bus", "lqos_config", + "lqos_overrides", "lqos_queue_tracker", "lqos_utils", "parking_lot", diff --git a/src/rust/lqos_config/src/etc/v15/stormguard.rs b/src/rust/lqos_config/src/etc/v15/stormguard.rs index 96b49899..4e46e014 100644 --- a/src/rust/lqos_config/src/etc/v15/stormguard.rs +++ b/src/rust/lqos_config/src/etc/v15/stormguard.rs @@ -3,32 +3,229 @@ use allocative::Allocative; use serde::{Deserialize, Serialize}; -/// Configuration for the Tornado module (auto-rate) +fn default_false() -> bool { + false +} + +fn default_true() -> bool { + true +} + +fn default_minimum_pct() -> f32 { + 0.5 +} + +fn default_increase_fast_multiplier() -> f32 { + 1.30 +} + +fn default_increase_multiplier() -> f32 { + 1.15 +} + +fn default_decrease_multiplier() -> f32 { + 0.95 +} + +fn default_decrease_fast_multiplier() -> f32 { + 0.88 +} + +fn default_increase_fast_cooldown_seconds() -> f32 { + 2.0 +} + +fn default_increase_cooldown_seconds() -> f32 { + 1.0 +} + +fn default_decrease_cooldown_seconds() -> f32 { + 3.75 +} + +fn default_decrease_fast_cooldown_seconds() -> f32 { + 7.5 +} + +fn default_fallback_sqm() -> String { + "fq_codel".to_string() +} + +/// Configuration for the StormGuard module (auto-rate). #[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Allocative)] +#[serde(default)] pub struct StormguardConfig { - /// Whether Tornado is enabled or not + /// Whether StormGuard is enabled. + #[serde(default = "default_false")] pub enabled: bool, - /// List of targets (site names) to monitor + /// Apply to all eligible top-level sites in the queue structure. + #[serde(default = "default_false")] + pub all_sites: bool, + /// Optional site allowlist when `all_sites = false`. pub targets: Vec, - /// Whether to run in dry run mode (no actual changes) + /// Optional site exclusion list, primarily for `all_sites = true`. + pub exclude_sites: Vec, + /// Whether to run in dry run mode (no actual changes). + #[serde(default = "default_true")] pub dry_run: bool, - /// Optional log file path - emits a CSV of site and rates + /// Optional log file path - emits a CSV of site and rates. pub log_file: Option, - /// Minimum Percentage (e.g. 0.5 for 50%) Download + /// Minimum percentage (e.g. 0.5 for 50%) download. + #[serde(default = "default_minimum_pct")] pub minimum_download_percentage: f32, - /// Minimum Percentage (e.g. 0.5 for 50%) Upload + /// Minimum percentage (e.g. 0.5 for 50%) upload. + #[serde(default = "default_minimum_pct")] pub minimum_upload_percentage: f32, + /// Multiplier used for aggressive increase actions. + #[serde(default = "default_increase_fast_multiplier")] + pub increase_fast_multiplier: f32, + /// Multiplier used for normal increase actions. + #[serde(default = "default_increase_multiplier")] + pub increase_multiplier: f32, + /// Multiplier used for normal decrease actions. + #[serde(default = "default_decrease_multiplier")] + pub decrease_multiplier: f32, + /// Multiplier used for aggressive decrease actions. + #[serde(default = "default_decrease_fast_multiplier")] + pub decrease_fast_multiplier: f32, + /// Cooldown applied after aggressive increase actions. + #[serde(default = "default_increase_fast_cooldown_seconds")] + pub increase_fast_cooldown_seconds: f32, + /// Cooldown applied after normal increase actions. + #[serde(default = "default_increase_cooldown_seconds")] + pub increase_cooldown_seconds: f32, + /// Cooldown applied after normal decrease actions. + #[serde(default = "default_decrease_cooldown_seconds")] + pub decrease_cooldown_seconds: f32, + /// Cooldown applied after aggressive decrease actions. + #[serde(default = "default_decrease_fast_cooldown_seconds")] + pub decrease_fast_cooldown_seconds: f32, + /// Whether StormGuard may fall back to a per-circuit SQM action when direct HTB changes are unsafe. + #[serde(default = "default_false")] + pub circuit_fallback_enabled: bool, + /// Whether fallback SQM actions should be persisted into the StormGuard override layer. + #[serde(default = "default_true")] + pub circuit_fallback_persist: bool, + /// SQM token to apply during fallback (for now, `fq_codel` or `cake`). + #[serde(default = "default_fallback_sqm")] + pub circuit_fallback_sqm: String, } impl Default for StormguardConfig { fn default() -> Self { Self { - enabled: false, + enabled: default_false(), + all_sites: default_false(), targets: Vec::new(), - dry_run: true, + exclude_sites: Vec::new(), + dry_run: default_true(), log_file: None, - minimum_download_percentage: 0.5, - minimum_upload_percentage: 0.5, + minimum_download_percentage: default_minimum_pct(), + minimum_upload_percentage: default_minimum_pct(), + increase_fast_multiplier: default_increase_fast_multiplier(), + increase_multiplier: default_increase_multiplier(), + decrease_multiplier: default_decrease_multiplier(), + decrease_fast_multiplier: default_decrease_fast_multiplier(), + increase_fast_cooldown_seconds: default_increase_fast_cooldown_seconds(), + increase_cooldown_seconds: default_increase_cooldown_seconds(), + decrease_cooldown_seconds: default_decrease_cooldown_seconds(), + decrease_fast_cooldown_seconds: default_decrease_fast_cooldown_seconds(), + circuit_fallback_enabled: default_false(), + circuit_fallback_persist: default_true(), + circuit_fallback_sqm: default_fallback_sqm(), + } + } +} + +impl StormguardConfig { + /// Validates StormGuard configuration values and relationships. + pub fn validate(&self) -> Result<(), String> { + if self.enabled && !self.all_sites && self.targets.is_empty() { + return Err( + "stormguard.targets must not be empty when stormguard.enabled = true and stormguard.all_sites = false" + .to_string(), + ); + } + + validate_percentage( + "stormguard.minimum_download_percentage", + self.minimum_download_percentage, + )?; + validate_percentage( + "stormguard.minimum_upload_percentage", + self.minimum_upload_percentage, + )?; + + validate_multiplier_gt_one( + "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_lt_one( + "stormguard.decrease_fast_multiplier", + self.decrease_fast_multiplier, + )?; + + validate_positive_seconds( + "stormguard.increase_fast_cooldown_seconds", + self.increase_fast_cooldown_seconds, + )?; + validate_positive_seconds( + "stormguard.increase_cooldown_seconds", + self.increase_cooldown_seconds, + )?; + validate_positive_seconds( + "stormguard.decrease_cooldown_seconds", + self.decrease_cooldown_seconds, + )?; + validate_positive_seconds( + "stormguard.decrease_fast_cooldown_seconds", + self.decrease_fast_cooldown_seconds, + )?; + + 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(), + ); } + + Ok(()) + } +} + +fn validate_percentage(name: &str, value: f32) -> Result<(), String> { + if !(0.0..=1.0).contains(&value) || value <= 0.0 { + return Err(format!("{name} must be > 0.0 and <= 1.0")); + } + Ok(()) +} + +fn validate_multiplier_gt_one(name: &str, value: f32) -> Result<(), String> { + if !value.is_finite() || value <= 1.0 { + return Err(format!("{name} must be > 1.0")); + } + Ok(()) +} + +fn validate_multiplier_lt_one(name: &str, value: f32) -> Result<(), String> { + if !value.is_finite() || !(0.0..1.0).contains(&value) { + return Err(format!("{name} must be > 0.0 and < 1.0")); + } + Ok(()) +} + +fn validate_positive_seconds(name: &str, value: f32) -> Result<(), String> { + if !value.is_finite() || value <= 0.0 { + return Err(format!("{name} must be > 0.0")); } + Ok(()) } 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 662e3dde..46e33a97 100644 --- a/src/rust/lqos_config/src/etc/v15/top_config.rs +++ b/src/rust/lqos_config/src/etc/v15/top_config.rs @@ -223,6 +223,9 @@ impl Config { if self.queues.default_sqm.trim().is_empty() { return Err("default_sqm cannot be empty. Please specify a qdisc type (e.g., 'cake diffserv4' or 'fq_codel')".to_string()); } + if let Some(stormguard) = &self.stormguard { + stormguard.validate()?; + } self.treeguard.validate()?; Ok(()) } @@ -536,4 +539,72 @@ mod test { cfg.treeguard.circuits.upgrade_util_pct = 5.0; assert!(cfg.validate().is_err()); } + + #[test] + fn stormguard_defaults_preserve_legacy_behavior() { + let cfg = crate::etc::v15::stormguard::StormguardConfig::default(); + assert!(!cfg.enabled); + assert!(!cfg.all_sites); + assert!(cfg.targets.is_empty()); + assert!(cfg.exclude_sites.is_empty()); + assert!(cfg.dry_run); + assert_eq!(cfg.minimum_download_percentage, 0.5); + assert_eq!(cfg.minimum_upload_percentage, 0.5); + assert_eq!(cfg.increase_fast_multiplier, 1.30); + assert_eq!(cfg.increase_multiplier, 1.15); + assert_eq!(cfg.decrease_multiplier, 0.95); + assert_eq!(cfg.decrease_fast_multiplier, 0.88); + assert_eq!(cfg.increase_fast_cooldown_seconds, 2.0); + assert_eq!(cfg.increase_cooldown_seconds, 1.0); + assert_eq!(cfg.decrease_cooldown_seconds, 3.75); + assert_eq!(cfg.decrease_fast_cooldown_seconds, 7.5); + assert!(!cfg.circuit_fallback_enabled); + assert!(cfg.circuit_fallback_persist); + assert_eq!(cfg.circuit_fallback_sqm, "fq_codel"); + } + + #[test] + fn stormguard_validation_rejects_invalid_ranges() { + let mut cfg = Config::default(); + cfg.stormguard = Some(crate::etc::v15::stormguard::StormguardConfig { + enabled: true, + targets: vec!["Site A".to_string()], + ..Default::default() + }); + + let stormguard = cfg.stormguard.as_mut().unwrap(); + stormguard.minimum_download_percentage = 0.0; + assert!(cfg.validate().is_err()); + + let stormguard = cfg.stormguard.as_mut().unwrap(); + stormguard.minimum_download_percentage = 0.5; + stormguard.decrease_multiplier = 1.1; + assert!(cfg.validate().is_err()); + } + + #[test] + fn legacy_stormguard_config_loads_with_new_defaults() { + let mut raw = include_str!("example.toml").to_string(); + raw.push_str( + r#" + +[stormguard] +enabled = true +targets = ["Site A"] +dry_run = true +minimum_download_percentage = 0.5 +minimum_upload_percentage = 0.5 +"#, + ); + 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); + assert!(stormguard.exclude_sites.is_empty()); + assert_eq!(stormguard.increase_fast_multiplier, 1.30); + assert_eq!(stormguard.decrease_fast_cooldown_seconds, 7.5); + assert!(!stormguard.circuit_fallback_enabled); + assert_eq!(stormguard.circuit_fallback_sqm, "fq_codel"); + } } diff --git a/src/rust/lqos_overrides/src/overrides_file.rs b/src/rust/lqos_overrides/src/overrides_file.rs index 324ec72a..4739b6f7 100644 --- a/src/rust/lqos_overrides/src/overrides_file.rs +++ b/src/rust/lqos_overrides/src/overrides_file.rs @@ -12,6 +12,7 @@ use crate::overrides_file::file_lock::FileLock; mod file_lock; const OPERATOR_OVERRIDES_FILE: &str = "lqos_overrides.json"; +const STORMGUARD_OVERRIDES_FILE: &str = "lqos_overrides.stormguard.json"; const TREEGUARD_OVERRIDES_FILE: &str = "lqos_overrides.treeguard.json"; const LEGACY_AUTOPILOT_OVERRIDES_FILE: &str = "lqos_overrides.autopilot.json"; @@ -20,6 +21,8 @@ const LEGACY_AUTOPILOT_OVERRIDES_FILE: &str = "lqos_overrides.autopilot.json"; pub enum OverrideLayer { /// Operator-owned overrides (`lqos_overrides.json`). Operator, + /// StormGuard-owned overrides (`lqos_overrides.stormguard.json`). + Stormguard, /// TreeGuard-owned overrides (`lqos_overrides.treeguard.json`). Treeguard, } @@ -103,6 +106,7 @@ pub struct OverrideFile { fn overrides_path(config: &lqos_config::Config, layer: OverrideLayer) -> PathBuf { let file = match layer { OverrideLayer::Operator => OPERATOR_OVERRIDES_FILE, + OverrideLayer::Stormguard => STORMGUARD_OVERRIDES_FILE, OverrideLayer::Treeguard => TREEGUARD_OVERRIDES_FILE, }; Path::new(&config.lqos_directory).join(file) @@ -146,6 +150,7 @@ fn save_to_path(path: &Path, overrides: &OverrideFile) -> Result<()> { fn merge_persistent_devices_by_id( operator_devices: &[ShapedDevice], + stormguard_devices: &[ShapedDevice], treeguard_devices: &[ShapedDevice], ) -> Vec { use std::collections::{HashMap, HashSet}; @@ -154,6 +159,9 @@ fn merge_persistent_devices_by_id( for dev in operator_devices { by_id.insert(dev.device_id.as_str(), dev.clone()); } + for dev in stormguard_devices { + by_id.insert(dev.device_id.as_str(), dev.clone()); + } for dev in treeguard_devices { by_id.insert(dev.device_id.as_str(), dev.clone()); } @@ -172,6 +180,17 @@ fn merge_persistent_devices_by_id( } } + for dev in stormguard_devices { + let did = dev.device_id.as_str(); + if seen.contains(did) { + continue; + } + if let Some(merged) = by_id.get(did) { + out.push(merged.clone()); + seen.insert(did); + } + } + for dev in treeguard_devices { let did = dev.device_id.as_str(); if seen.contains(did) { @@ -188,10 +207,30 @@ fn merge_persistent_devices_by_id( fn merge_network_adjustments_owned( operator_adjustments: &[NetworkAdjustment], + stormguard_adjustments: &[NetworkAdjustment], treeguard_adjustments: &[NetworkAdjustment], ) -> Vec { use std::collections::{HashMap, HashSet}; + let mut stormguard_site_speeds: HashMap<&str, (Option, Option)> = HashMap::new(); + let mut stormguard_site_order: Vec<&str> = Vec::new(); + let mut stormguard_site_seen: HashSet<&str> = HashSet::new(); + for adj in stormguard_adjustments { + if let NetworkAdjustment::AdjustSiteSpeed { + site_name, + download_bandwidth_mbps, + upload_bandwidth_mbps, + } = adj + { + let name = site_name.as_str(); + stormguard_site_speeds.insert(name, (*download_bandwidth_mbps, *upload_bandwidth_mbps)); + if !stormguard_site_seen.contains(name) { + stormguard_site_order.push(name); + stormguard_site_seen.insert(name); + } + } + } + let mut treeguard_virtual: HashMap<&str, bool> = HashMap::new(); let mut treeguard_virtual_order: Vec<&str> = Vec::new(); let mut treeguard_virtual_seen: HashSet<&str> = HashSet::new(); @@ -214,6 +253,7 @@ fn merge_network_adjustments_owned( let mut out = Vec::new(); let mut used_treeguard_virtual: HashSet<&str> = HashSet::new(); let mut operator_virtual_seen: HashSet<&str> = HashSet::new(); + let mut operator_site_speed_seen: HashSet<&str> = HashSet::new(); for adj in operator_adjustments { match adj { @@ -240,13 +280,40 @@ fn merge_network_adjustments_owned( }); } } - NetworkAdjustment::AdjustSiteSpeed { .. } => { - // Operator-only. Preserve as-is. - out.push(adj.clone()); + NetworkAdjustment::AdjustSiteSpeed { + site_name, + download_bandwidth_mbps, + upload_bandwidth_mbps, + } => { + let name = site_name.as_str(); + if operator_site_speed_seen.contains(name) { + continue; + } + operator_site_speed_seen.insert(name); + out.push(NetworkAdjustment::AdjustSiteSpeed { + site_name: site_name.clone(), + download_bandwidth_mbps: *download_bandwidth_mbps, + upload_bandwidth_mbps: *upload_bandwidth_mbps, + }); } } } + for name in stormguard_site_order { + if operator_site_speed_seen.contains(name) { + continue; + } + let Some((download_bandwidth_mbps, upload_bandwidth_mbps)) = stormguard_site_speeds.get(name) + else { + continue; + }; + out.push(NetworkAdjustment::AdjustSiteSpeed { + site_name: name.to_string(), + download_bandwidth_mbps: *download_bandwidth_mbps, + upload_bandwidth_mbps: *upload_bandwidth_mbps, + }); + } + // Append TreeGuard-only virtual-node entries (ignore other network adjustments). for name in treeguard_virtual_order { if used_treeguard_virtual.contains(name) { @@ -264,14 +331,24 @@ fn merge_network_adjustments_owned( out } -fn merge_owned_sections(mut operator: OverrideFile, treeguard: OverrideFile) -> OverrideFile { +fn merge_owned_sections( + mut operator: OverrideFile, + stormguard: OverrideFile, + treeguard: OverrideFile, +) -> OverrideFile { let operator_devices = std::mem::take(&mut operator.persistent_devices); - operator.persistent_devices = - merge_persistent_devices_by_id(&operator_devices, &treeguard.persistent_devices); + operator.persistent_devices = merge_persistent_devices_by_id( + &operator_devices, + &stormguard.persistent_devices, + &treeguard.persistent_devices, + ); let operator_network = std::mem::take(&mut operator.network_adjustments); - operator.network_adjustments = - merge_network_adjustments_owned(&operator_network, &treeguard.network_adjustments); + operator.network_adjustments = merge_network_adjustments_owned( + &operator_network, + &stormguard.network_adjustments, + &treeguard.network_adjustments, + ); operator } @@ -412,6 +489,34 @@ impl OverrideFile { self.network_adjustments.push(adj); } + /// Add or replace a site bandwidth override for `site_name`. + pub fn set_site_bandwidth_override( + &mut self, + site_name: String, + download_bandwidth_mbps: Option, + upload_bandwidth_mbps: Option, + ) { + self.network_adjustments.retain(|adj| match adj { + NetworkAdjustment::AdjustSiteSpeed { site_name: current, .. } => current != &site_name, + _ => true, + }); + 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, + _ => true, + }); + before.saturating_sub(self.network_adjustments.len()) + } + /// Add or replace a virtual-node flag for a specific network.json node name. pub fn set_network_node_virtual(&mut self, node_name: String, virtual_node: bool) { self.network_adjustments.retain(|adj| match adj { @@ -484,6 +589,7 @@ impl OverrideStore { let config = lqos_config::load_config()?; let path = match layer { OverrideLayer::Operator => overrides_path(&config, layer), + OverrideLayer::Stormguard => overrides_path(&config, layer), OverrideLayer::Treeguard => treeguard_read_path(&config), }; let overrides = match layer { @@ -491,7 +597,7 @@ impl OverrideStore { ensure_exists_default(&path)?; load_from_path(&path)? } - OverrideLayer::Treeguard => { + OverrideLayer::Stormguard | OverrideLayer::Treeguard => { if !path.exists() { OverrideFile::default() } else { @@ -517,10 +623,10 @@ impl OverrideStore { /// Loads the effective overrides view used during shaping. /// - /// When `apply_treeguard` is false, this is equivalent to loading the operator layer only. + /// When adaptive layers are disabled, this is equivalent to loading the operator layer only. /// /// Side effects: acquires the global overrides lock and may create the operator overrides file. - pub fn load_effective(apply_treeguard: bool) -> Result { + pub fn load_effective(apply_stormguard: bool, apply_treeguard: bool) -> Result { let lock = FileLock::new()?; let config = lqos_config::load_config()?; @@ -528,19 +634,26 @@ impl OverrideStore { ensure_exists_default(&operator_path)?; let operator = load_from_path(&operator_path)?; - if !apply_treeguard { + if !apply_stormguard && !apply_treeguard { drop(lock); return Ok(operator); } + let stormguard_path = overrides_path(&config, OverrideLayer::Stormguard); + let stormguard = if !apply_stormguard || !stormguard_path.exists() { + OverrideFile::default() + } else { + load_from_path(&stormguard_path)? + }; + let treeguard_path = treeguard_read_path(&config); - let treeguard = if !treeguard_path.exists() { + let treeguard = if !apply_treeguard || !treeguard_path.exists() { OverrideFile::default() } else { load_from_path(&treeguard_path)? }; - let merged = merge_owned_sections(operator, treeguard); + let merged = merge_owned_sections(operator, stormguard, treeguard); drop(lock); Ok(merged) } @@ -563,22 +676,29 @@ mod tests { 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")); + let mut treeguard = OverrideFile::default(); treeguard - .add_persistent_shaped_device_return_changed(shaped_device_with_sqm("dev1", "fq_codel")); + .add_persistent_shaped_device_return_changed(shaped_device_with_sqm("dev1", "cake")); treeguard - .add_persistent_shaped_device_return_changed(shaped_device_with_sqm("dev3", "fq_codel")); + .add_persistent_shaped_device_return_changed(shaped_device_with_sqm("dev4", "cake")); - let merged = merge_owned_sections(operator, treeguard); + let merged = merge_owned_sections(operator, stormguard, treeguard); 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))) .collect(); - assert_eq!(sqm_by_id.get("dev1"), Some(&"fq_codel")); + assert_eq!(sqm_by_id.get("dev1"), Some(&"cake")); assert_eq!(sqm_by_id.get("dev2"), Some(&"cake")); assert_eq!(sqm_by_id.get("dev3"), Some(&"fq_codel")); + assert_eq!(sqm_by_id.get("dev4"), Some(&"cake")); } #[test] @@ -591,15 +711,19 @@ mod tests { upload_bandwidth_mbps: Some(50), }); + let mut stormguard = OverrideFile::default(); + stormguard.set_site_bandwidth_override("Site1".to_string(), Some(80), Some(40)); + stormguard.set_site_bandwidth_override("Site2".to_string(), Some(150), Some(75)); + let mut treeguard = OverrideFile::default(); treeguard.set_network_node_virtual("NodeA".to_string(), true); treeguard.add_network_adjustment(NetworkAdjustment::AdjustSiteSpeed { - site_name: "Site2".to_string(), + site_name: "Site3".to_string(), download_bandwidth_mbps: Some(200), upload_bandwidth_mbps: Some(100), }); - let merged = merge_owned_sections(operator, treeguard); + let merged = merge_owned_sections(operator, stormguard, treeguard); let node_a_virtual = merged.network_adjustments().iter().find_map(|adj| match adj { NetworkAdjustment::SetNodeVirtual { @@ -610,12 +734,12 @@ mod tests { }); assert_eq!(node_a_virtual, Some(true)); - // Operator-only site speed should remain; TreeGuard site speed should be ignored. + // 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(); - assert_eq!(site_speed_names, vec!["Site1"]); + assert_eq!(site_speed_names, vec!["Site1", "Site2"]); } #[test] diff --git a/src/rust/lqos_python/src/lib.rs b/src/rust/lqos_python/src/lib.rs index ab2fa2f6..fdbdaac7 100644 --- a/src/rust/lqos_python/src/lib.rs +++ b/src/rust/lqos_python/src/lib.rs @@ -951,13 +951,20 @@ fn overrides_persistent_devices(py: Python<'_>) -> PyResult> { } /// Returns a Python list of dictionaries representing persistent devices for ShapedDevices.csv, -/// using the effective overrides view (operator + TreeGuard layers when enabled). +/// using the effective overrides view (operator + adaptive layers when enabled). #[pyfunction] fn overrides_persistent_devices_effective(py: Python<'_>) -> PyResult> { let config = lqos_config::load_config().map_err(|e| PyOSError::new_err(e.to_string()))?; + let apply_stormguard = config + .stormguard + .as_ref() + .is_some_and(|sg| sg.enabled && !sg.dry_run); let apply_treeguard = config.treeguard.enabled; - let overrides = match lqos_overrides::OverrideStore::load_effective(apply_treeguard) { + 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())), }; @@ -1126,13 +1133,20 @@ fn overrides_network_adjustments(py: Python<'_>) -> PyResult> { } /// Returns the list of network adjustments as Python dicts, using the effective overrides view -/// (operator + TreeGuard layers when enabled). +/// (operator + adaptive layers when enabled). #[pyfunction] fn overrides_network_adjustments_effective(py: Python<'_>) -> PyResult> { let config = lqos_config::load_config().map_err(|e| PyOSError::new_err(e.to_string()))?; + let apply_stormguard = config + .stormguard + .as_ref() + .is_some_and(|sg| sg.enabled && !sg.dry_run); let apply_treeguard = config.treeguard.enabled; - let overrides = match lqos_overrides::OverrideStore::load_effective(apply_treeguard) { + 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())), }; diff --git a/src/rust/lqos_stormguard/Cargo.toml b/src/rust/lqos_stormguard/Cargo.toml index 24db5374..f7c62b5f 100644 --- a/src/rust/lqos_stormguard/Cargo.toml +++ b/src/rust/lqos_stormguard/Cargo.toml @@ -13,9 +13,10 @@ tokio.workspace = true lqos_queue_tracker = { path = "../lqos_queue_tracker" } lqos_utils = { path = "../lqos_utils" } lqos_bakery = { path = "../lqos_bakery" } +lqos_overrides = { path = "../lqos_overrides" } crossbeam-channel.workspace = true parking_lot.workspace = true # For memory debugging allocative.workspace = true -allocative_derive.workspace = true \ No newline at end of file +allocative_derive.workspace = true diff --git a/src/rust/lqos_stormguard/README.md b/src/rust/lqos_stormguard/README.md index 853c7388..c85c509a 100644 --- a/src/rust/lqos_stormguard/README.md +++ b/src/rust/lqos_stormguard/README.md @@ -15,29 +15,49 @@ Add the following to your `lqos.conf`: enabled = true dry_run = true log_file = "/tmp/stormguard.csv" # Optional +all_sites = false targets = [ "CALVIN 1" ] +exclude_sites = [] minimum_download_percentage = 0.5 # For 50% of download as minimum minimum_upload_percentage = 0.5 # For 50% of upload as minimum +increase_fast_multiplier = 1.30 +increase_multiplier = 1.15 +decrease_multiplier = 0.95 +decrease_fast_multiplier = 0.88 +increase_fast_cooldown_seconds = 2.0 +increase_cooldown_seconds = 1.0 +decrease_cooldown_seconds = 3.75 +decrease_fast_cooldown_seconds = 7.5 +circuit_fallback_enabled = false +circuit_fallback_persist = true +circuit_fallback_sqm = "fq_codel" ``` | **Entry Name** | **Description** | |----------------|-----------------------------------------------------------------------------------------------------------| -| `enabled` | Enable or disable Tornado. Default: `false` | -| `dry_run` | If true, Tornado will not change the rate. It will only log what it *would* have done. Default: `false` | +| `enabled` | Enable or disable StormGuard. Default: `false` | +| `dry_run` | If true, StormGuard will not change or persist the rate. It only logs what it would have done. Default: `true` | | `log_file` | If set, a CSV will be appended with time (unix secs), download rate, upload rate entries. Default: absent | +| `all_sites` | Monitor all eligible top-level sites. If `false`, only the `targets` allowlist is monitored. | +| `targets` | Site allowlist used when `all_sites = false`. | +| `exclude_sites`| Sites to skip when `all_sites = true`. | +| `*_multiplier` | Per-action rate multipliers used when StormGuard increases or decreases a site cap. | +| `*_cooldown_seconds` | Per-action cooldowns that suppress repeated adjustments after a change. | +| `circuit_fallback_*` | Optional TreeGuard-style per-circuit SQM fallback for circuit queues StormGuard cannot safely change with HTB. | -You can list as many sites as you want in the `targets` array. I strongly recommend `dry_run` for now, which just -emits what it *would* have done to the console! +You can list as many sites as you want in `targets`, or turn on `all_sites` and carve out exceptions with `exclude_sites`. +`dry_run` is the recommended starting point while tuning the thresholds for a network. ## How it works StormGuard maintains a ring-buffer of recent throughput, TCP retransmits and TCP round-trip times for each target site. These are updated once per second, when `lqosd` "ticks". A second buffer maintains a moving average of a larger time period. -Each circuit also maintains a "current queue bandwidth", which is adjusted dynamically. If `dry_run` is not set, -this is applied directly to the HTB queue associated with the monitoring. +Each site also maintains a current queue bandwidth, which is adjusted dynamically. In live mode, StormGuard persists +those adaptive site caps into its own override layer so scheduler rebuilds preserve the current StormGuard state. -> *Warning*: Do not apply this to HTB circuits that have a directly attached CAKE instance. +> *Warning*: StormGuard will not directly change HTB on qdisc-hosting circuit queues. When circuit fallback is enabled, +> it can request a per-circuit SQM override instead. Periodically: @@ -53,4 +73,4 @@ This is to prevent oscillation between two states. ## Running StormGuard -StormGuard is integrated into `lqosd`. If it is enabled, it will run automatically when `lqosd` is started. \ No newline at end of file +StormGuard is integrated into `lqosd`. If it is enabled, it will run automatically when `lqosd` is started. diff --git a/src/rust/lqos_stormguard/src/adaptive_actions.rs b/src/rust/lqos_stormguard/src/adaptive_actions.rs new file mode 100644 index 00000000..af3cbf3a --- /dev/null +++ b/src/rust/lqos_stormguard/src/adaptive_actions.rs @@ -0,0 +1,386 @@ +use anyhow::{Result, anyhow}; +use lqos_bakery::BakeryCommands; +use lqos_config::{ConfigShapedDevices, ShapedDevice}; +use lqos_overrides::{OverrideFile, OverrideLayer, OverrideStore}; +use lqos_queue_tracker::QUEUE_STRUCTURE; +use lqos_utils::hash_to_i64; +use std::collections::{BTreeMap, HashMap, HashSet}; + +pub enum CircuitFallbackOutcome { + Applied { persisted: bool }, + Cleared { persisted: bool }, + DryRun { action: String }, + Skipped { reason: String }, +} + +pub struct SiteOverrideUpdate { + pub site_name: String, + pub download_bandwidth_mbps: Option, + pub upload_bandwidth_mbps: Option, +} + +#[derive(Clone)] +pub struct PersistedCircuitFallback { + pub sqm_override: String, + pub devices: Vec, +} + +pub fn apply_site_override_updates(updates: &[SiteOverrideUpdate]) -> Result { + if updates.is_empty() { + return Ok(false); + } + + let mut overrides = OverrideStore::load_layer(OverrideLayer::Stormguard)?; + let mut changed = false; + + for update in updates { + let desired = ( + update.download_bandwidth_mbps, + update.upload_bandwidth_mbps, + ); + if desired == (None, None) { + let removed = overrides.remove_site_bandwidth_override_by_name_count(&update.site_name); + if removed > 0 { + changed = true; + } + continue; + } + + if current_site_override(&overrides, &update.site_name) == Some(desired) { + continue; + } + + overrides.set_site_bandwidth_override( + update.site_name.clone(), + update.download_bandwidth_mbps, + update.upload_bandwidth_mbps, + ); + changed = true; + } + + if !changed { + return Ok(false); + } + + OverrideStore::save_layer(OverrideLayer::Stormguard, &overrides)?; + Ok(true) +} + +pub fn apply_circuit_fallback( + circuit_id: &str, + sqm_override: &str, + persist: bool, + dry_run: bool, + bakery_sender: crossbeam_channel::Sender, +) -> Result { + let devices = load_devices_for_circuit(circuit_id)?; + if devices.is_empty() { + return Ok(CircuitFallbackOutcome::Skipped { + reason: "No ShapedDevices rows found for circuit.".to_string(), + }); + } + + if let Some(reason) = conflicting_sqm_owner(&devices)? { + return Ok(CircuitFallbackOutcome::Skipped { reason }); + } + + if dry_run { + return Ok(CircuitFallbackOutcome::DryRun { + action: format!("Would set SQM override to '{sqm_override}'"), + }); + } + + let persisted = if persist { + set_devices_sqm_override(&devices, sqm_override)? + } else { + false + }; + apply_circuit_sqm_override_live(circuit_id, &devices, Some(sqm_override), bakery_sender)?; + Ok(CircuitFallbackOutcome::Applied { persisted }) +} + +pub fn clear_circuit_fallback( + circuit_id: &str, + dry_run: bool, + bakery_sender: crossbeam_channel::Sender, +) -> Result { + let fallback = load_persisted_circuit_fallbacks()? + .remove(circuit_id) + .unwrap_or(PersistedCircuitFallback { + sqm_override: String::new(), + devices: load_devices_for_circuit(circuit_id)?, + }); + if fallback.devices.is_empty() { + return Ok(CircuitFallbackOutcome::Skipped { + reason: "No ShapedDevices rows found for circuit.".to_string(), + }); + } + + if let Some(reason) = conflicting_sqm_owner(&fallback.devices)? { + return Ok(CircuitFallbackOutcome::Skipped { reason }); + } + + if dry_run { + return Ok(CircuitFallbackOutcome::DryRun { + action: "Would clear SQM fallback override".to_string(), + }); + } + + 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 }) +} + +pub fn load_persisted_circuit_fallbacks() -> Result> { + let overrides = OverrideStore::load_layer(OverrideLayer::Stormguard)?; + Ok(group_circuit_fallbacks(overrides.persistent_devices())) +} + +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, + }) +} + +fn load_devices_for_circuit(circuit_id: &str) -> Result> { + let shaped_devices = ConfigShapedDevices::load()?; + Ok(shaped_devices + .devices + .into_iter() + .filter(|device| device.circuit_id == circuit_id) + .collect()) +} + +fn conflicting_sqm_owner(devices: &[ShapedDevice]) -> Result> { + let device_ids: HashSet<&str> = devices.iter().map(|d| d.device_id.as_str()).collect(); + + let operator = OverrideStore::load_layer(OverrideLayer::Operator)?; + if has_sqm_override_for_device_ids(&operator, &device_ids) { + return Ok(Some( + "Operator SQM overrides are present for this circuit.".to_string(), + )); + } + + let treeguard = OverrideStore::load_layer(OverrideLayer::Treeguard)?; + if has_sqm_override_for_device_ids(&treeguard, &device_ids) { + return Ok(Some( + "TreeGuard SQM overrides are present for this circuit.".to_string(), + )); + } + + Ok(None) +} + +fn has_sqm_override_for_device_ids(overrides: &OverrideFile, device_ids: &HashSet<&str>) -> bool { + overrides.persistent_devices().iter().any(|device| { + device_ids.contains(device.device_id.as_str()) + && device + .sqm_override + .as_deref() + .is_some_and(|token| !token.trim().is_empty()) + }) +} + +fn set_devices_sqm_override(base_devices: &[ShapedDevice], sqm_override: &str) -> Result { + let mut overrides = OverrideStore::load_layer(OverrideLayer::Stormguard)?; + let effective = OverrideStore::load_effective(false, true)?; + let effective_devices: HashMap<&str, &ShapedDevice> = effective + .persistent_devices() + .iter() + .map(|device| (device.device_id.as_str(), device)) + .collect(); + let mut changed = false; + for base_device in base_devices { + let mut device = effective_devices + .get(base_device.device_id.as_str()) + .copied() + .cloned() + .unwrap_or_else(|| base_device.clone()); + device.sqm_override = Some(sqm_override.to_string()); + if overrides.add_persistent_shaped_device_return_changed(device) { + changed = true; + } + } + + if !changed { + return Ok(false); + } + + OverrideStore::save_layer(OverrideLayer::Stormguard, &overrides)?; + Ok(true) +} + +fn clear_device_overrides(device_ids: &[String]) -> Result { + let mut overrides = OverrideStore::load_layer(OverrideLayer::Stormguard)?; + let mut removed_any = false; + for device_id in device_ids { + let removed = overrides.remove_persistent_shaped_device_by_device_count(device_id); + if removed > 0 { + removed_any = true; + } + } + + if !removed_any { + return Ok(false); + } + + OverrideStore::save_layer(OverrideLayer::Stormguard, &overrides)?; + Ok(true) +} + +fn apply_circuit_sqm_override_live( + circuit_id: &str, + devices: &[ShapedDevice], + sqm_override: Option<&str>, + bakery_sender: crossbeam_channel::Sender, +) -> Result<()> { + let snapshot = QUEUE_STRUCTURE.load(); + let Some(queues) = snapshot.maybe_queues.as_ref() else { + return Err(anyhow!("queueingStructure.json not loaded")); + }; + + let mut stack = Vec::new(); + for queue in queues.iter() { + stack.push(queue); + } + + let mut found = None; + while let Some(node) = stack.pop() { + if node.circuit_id.as_deref() == Some(circuit_id) && node.device_id.is_none() { + found = Some(node); + break; + } + + for child in node.children.iter() { + stack.push(child); + } + for circuit in node.circuits.iter() { + stack.push(circuit); + } + for device in node.devices.iter() { + stack.push(device); + } + } + + let Some(node) = found else { + return Err(anyhow!("circuit not found in queue structure: {circuit_id}")); + }; + + let class_minor = u16::try_from(node.class_minor) + .map_err(|_| anyhow!("class_minor too large: {}", node.class_minor))?; + let class_major = u16::try_from(node.class_major) + .map_err(|_| anyhow!("class_major too large: {}", node.class_major))?; + let up_class_major = u16::try_from(node.up_class_major) + .map_err(|_| anyhow!("up_class_major too large: {}", node.up_class_major))?; + + bakery_sender.send(BakeryCommands::AddCircuit { + circuit_hash: hash_to_i64(circuit_id), + parent_class_id: node.parent_class_id, + up_parent_class_id: node.up_parent_class_id, + class_minor, + download_bandwidth_min: node.download_bandwidth_mbps_min as f32, + upload_bandwidth_min: node.upload_bandwidth_mbps_min as f32, + download_bandwidth_max: node.download_bandwidth_mbps as f32, + upload_bandwidth_max: node.upload_bandwidth_mbps as f32, + class_major, + up_class_major, + ip_addresses: ip_list(devices), + sqm_override: sqm_override.map(|value| value.to_string()), + })?; + + Ok(()) +} + +fn ip_list(devices: &[ShapedDevice]) -> String { + let mut ips = Vec::new(); + for dev in devices { + for (ip, prefix) in dev.ipv4.iter() { + ips.push(format!("{ip}/{prefix}")); + } + for (ip, prefix) in dev.ipv6.iter() { + ips.push(format!("{ip}/{prefix}")); + } + } + ips.sort(); + ips.dedup(); + ips.join(",") +} + +fn group_circuit_fallbacks(devices: &[ShapedDevice]) -> HashMap { + let mut grouped: BTreeMap = BTreeMap::new(); + for device in devices { + let Some(token) = device.sqm_override.as_deref().map(str::trim) else { + continue; + }; + if token.is_empty() || device.circuit_id.trim().is_empty() { + continue; + } + + let entry = grouped + .entry(device.circuit_id.clone()) + .or_insert_with(|| PersistedCircuitFallback { + sqm_override: token.to_string(), + devices: Vec::new(), + }); + + if entry.sqm_override != token { + continue; + } + entry.devices.push(device.clone()); + } + grouped.into_iter().collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn sample_device(device_id: &str, circuit_id: &str) -> ShapedDevice { + ShapedDevice { + device_id: device_id.to_string(), + circuit_id: circuit_id.to_string(), + comment: "operator-comment".to_string(), + download_max_mbps: 123.0, + ..Default::default() + } + } + + #[test] + fn group_circuit_fallbacks_groups_by_circuit_and_token() { + let mut d1 = sample_device("dev1", "c1"); + d1.sqm_override = Some("fq_codel".to_string()); + let mut d2 = sample_device("dev2", "c1"); + d2.sqm_override = Some("fq_codel".to_string()); + let mut d3 = sample_device("dev3", "c2"); + d3.sqm_override = Some("cake".to_string()); + + let grouped = group_circuit_fallbacks(&[d1, d2, d3]); + assert_eq!(grouped.len(), 2); + assert_eq!(grouped.get("c1").unwrap().sqm_override, "fq_codel"); + assert_eq!(grouped.get("c1").unwrap().devices.len(), 2); + assert_eq!(grouped.get("c2").unwrap().sqm_override, "cake"); + } + + #[test] + fn group_circuit_fallbacks_ignores_blank_or_mixed_tokens() { + let mut d1 = sample_device("dev1", "c1"); + d1.sqm_override = Some("fq_codel".to_string()); + let mut d2 = sample_device("dev2", "c1"); + d2.sqm_override = Some("cake".to_string()); + let mut d3 = sample_device("dev3", "c2"); + d3.sqm_override = Some(" ".to_string()); + + let grouped = group_circuit_fallbacks(&[d1, d2, d3]); + assert_eq!(grouped.get("c1").unwrap().devices.len(), 1); + assert!(!grouped.contains_key("c2")); + } +} diff --git a/src/rust/lqos_stormguard/src/config.rs b/src/rust/lqos_stormguard/src/config.rs index 375672f5..e1de56b4 100644 --- a/src/rust/lqos_stormguard/src/config.rs +++ b/src/rust/lqos_stormguard/src/config.rs @@ -1,9 +1,10 @@ use crate::STORMGUARD_STATS; -use crate::queue_structure::{find_queue_bandwidth, find_queue_dependents}; +use crate::queue_structure::{all_candidate_site_names, find_queue_bandwidth, find_queue_dependents}; use allocative::Allocative; use lqos_bus::TcHandle; -use std::collections::HashMap; -use tracing::{debug, info}; +use lqos_overrides::{NetworkAdjustment, OverrideLayer, OverrideStore}; +use std::collections::{HashMap, HashSet}; +use tracing::{debug, info, warn}; #[derive(Allocative, Clone)] pub struct WatchingSite { @@ -13,6 +14,8 @@ pub struct WatchingSite { pub min_download_mbps: u64, pub min_upload_mbps: u64, pub dependent_nodes: Vec, + pub current_download_mbps: u64, + pub current_upload_mbps: u64, } #[derive(Allocative, Clone)] @@ -29,6 +32,17 @@ pub struct StormguardConfig { pub upload_interface: String, pub dry_run: bool, pub log_filename: Option, + pub increase_fast_multiplier: f64, + pub increase_multiplier: f64, + pub decrease_multiplier: f64, + pub decrease_fast_multiplier: f64, + pub increase_fast_cooldown_seconds: f32, + pub increase_cooldown_seconds: f32, + pub decrease_cooldown_seconds: f32, + pub decrease_fast_cooldown_seconds: f32, + pub circuit_fallback_enabled: bool, + pub circuit_fallback_persist: bool, + pub circuit_fallback_sqm: String, } impl StormguardConfig { @@ -61,7 +75,12 @@ pub fn configure() -> anyhow::Result { )); } - let sites = get_sites_from_queueing_structure(&sg_config); + let persisted_site_overrides = if sg_config.dry_run { + HashMap::new() + } else { + load_stormguard_site_overrides() + }; + let sites = get_sites_from_queueing_structure(sg_config, &persisted_site_overrides); let result = StormguardConfig { sites, @@ -69,16 +88,72 @@ pub fn configure() -> anyhow::Result { upload_interface: config.internet_interface().clone(), dry_run: sg_config.dry_run, log_filename: sg_config.log_file.clone(), + increase_fast_multiplier: sg_config.increase_fast_multiplier as f64, + increase_multiplier: sg_config.increase_multiplier as f64, + decrease_multiplier: sg_config.decrease_multiplier as f64, + decrease_fast_multiplier: sg_config.decrease_fast_multiplier as f64, + increase_fast_cooldown_seconds: sg_config.increase_fast_cooldown_seconds, + increase_cooldown_seconds: sg_config.increase_cooldown_seconds, + decrease_cooldown_seconds: sg_config.decrease_cooldown_seconds, + decrease_fast_cooldown_seconds: sg_config.decrease_fast_cooldown_seconds, + circuit_fallback_enabled: sg_config.circuit_fallback_enabled, + circuit_fallback_persist: sg_config.circuit_fallback_persist, + circuit_fallback_sqm: sg_config.circuit_fallback_sqm.trim().to_ascii_lowercase(), }; Ok(result) } +fn load_stormguard_site_overrides() -> HashMap, Option)> { + let Ok(overrides) = OverrideStore::load_layer(OverrideLayer::Stormguard) else { + warn!("Unable to load StormGuard override layer; starting from planned rates."); + return HashMap::new(); + }; + + overrides + .network_adjustments() + .iter() + .filter_map(|adj| match adj { + NetworkAdjustment::AdjustSiteSpeed { + site_name, + download_bandwidth_mbps, + upload_bandwidth_mbps, + } => Some(( + site_name.clone(), + (*download_bandwidth_mbps, *upload_bandwidth_mbps), + )), + _ => None, + }) + .collect() +} + fn get_sites_from_queueing_structure( sg_config: &lqos_config::StormguardConfig, + persisted_site_overrides: &HashMap, Option)>, ) -> HashMap { + let mut selected: Vec = if sg_config.all_sites { + all_candidate_site_names() + } else { + sg_config.targets.clone() + }; + + let excluded: HashSet<&str> = sg_config + .exclude_sites + .iter() + .map(|site| site.as_str()) + .collect(); + + selected.retain(|site| !excluded.contains(site.as_str())); + selected.sort(); + selected.dedup(); + let mut sites = HashMap::new(); - for target in &sg_config.targets { + { + let mut lock = STORMGUARD_STATS.lock(); + lock.clear(); + } + + for target in selected { let Ok((max_down, max_up)) = find_queue_bandwidth(&target) else { debug!("Error finding queue bandwidth for {}", target); continue; @@ -89,6 +164,12 @@ fn get_sites_from_queueing_structure( }; let min_down = (max_down as f32 * sg_config.minimum_download_percentage) as u64; let min_up = (max_up as f32 * sg_config.minimum_upload_percentage) as u64; + let persisted = persisted_site_overrides.get(&target).copied().unwrap_or((None, None)); + let current_download_mbps = + persisted.0.map(u64::from).unwrap_or(max_down).clamp(min_down, max_down); + let current_upload_mbps = + persisted.1.map(u64::from).unwrap_or(max_up).clamp(min_up, max_up); + let site = WatchingSite { name: target.to_owned(), max_download_mbps: max_down, @@ -96,11 +177,13 @@ fn get_sites_from_queueing_structure( min_download_mbps: min_down, min_upload_mbps: min_up, dependent_nodes: dependencies, + current_download_mbps, + current_upload_mbps, }; sites.insert(target.to_owned(), site); { let mut lock = STORMGUARD_STATS.lock(); - lock.push((target.to_owned(), max_down, max_up)); + lock.push((target.to_owned(), current_download_mbps, current_upload_mbps)); } } sites diff --git a/src/rust/lqos_stormguard/src/lib.rs b/src/rust/lqos_stormguard/src/lib.rs index 00ee0f90..85c71603 100644 --- a/src/rust/lqos_stormguard/src/lib.rs +++ b/src/rust/lqos_stormguard/src/lib.rs @@ -20,6 +20,7 @@ mod config; mod datalog; mod queue_structure; mod site_state; +mod adaptive_actions; const READING_ACCUMULATOR_SIZE: usize = 15; const MOVING_AVERAGE_BUFFER_SIZE: usize = 15; @@ -68,8 +69,9 @@ pub async fn start_stormguard( if log_sender.is_none() { log_sender = datalog::start_datalog(&new_config).ok(); } - site_state_tracker = - Some(site_state::SiteStateTracker::from_config(&new_config)); + let mut tracker = site_state::SiteStateTracker::from_config(&new_config); + tracker.replay_persisted_adjustments(&new_config, bakery.clone()); + site_state_tracker = Some(tracker); config = Some(new_config); } } diff --git a/src/rust/lqos_stormguard/src/queue_structure.rs b/src/rust/lqos_stormguard/src/queue_structure.rs index e2971fab..8f4d76b8 100644 --- a/src/rust/lqos_stormguard/src/queue_structure.rs +++ b/src/rust/lqos_stormguard/src/queue_structure.rs @@ -1,6 +1,7 @@ use crate::config::WatchingSiteDependency; use anyhow::{Result, bail}; use lqos_queue_tracker::QUEUE_STRUCTURE; +use std::collections::HashSet; pub fn find_queue_bandwidth(name: &str) -> Result<(u64, u64)> { let Some(queues) = &QUEUE_STRUCTURE.load().maybe_queues else { @@ -36,18 +37,18 @@ pub fn find_queue_dependents(parent_name: &str) -> Result Result Vec { + let Some(queues) = &QUEUE_STRUCTURE.load().maybe_queues else { + return Vec::new(); + }; + + let parent_ids: HashSet<_> = queues + .iter() + .filter(|q| q.circuit_id.is_none()) + .map(|q| q.parent_class_id) + .collect(); + + let mut names: Vec = queues + .iter() + .filter(|q| q.circuit_id.is_none()) + .filter_map(|q| { + let name = q.name.as_ref()?; + if parent_ids.contains(&q.class_id) { + None + } else { + Some(name.clone()) + } + }) + .collect(); + names.sort(); + names.dedup(); + names +} diff --git a/src/rust/lqos_stormguard/src/site_state.rs b/src/rust/lqos_stormguard/src/site_state.rs index 4262cbf6..89447276 100644 --- a/src/rust/lqos_stormguard/src/site_state.rs +++ b/src/rust/lqos_stormguard/src/site_state.rs @@ -6,6 +6,10 @@ mod stormguard_state; use crate::config::StormguardConfig; use crate::datalog::LogCommand; +use crate::adaptive_actions::{ + CircuitFallbackOutcome, SiteOverrideUpdate, apply_circuit_fallback, + apply_site_override_updates, clear_circuit_fallback, load_persisted_circuit_fallbacks, +}; use crate::site_state::analysis::SaturationLevel; use crate::site_state::recommendation::{ Recommendation, RecommendationAction, RecommendationDirection, @@ -18,11 +22,12 @@ use crossbeam_channel::Sender; use lqos_bakery::BakeryCommands; use lqos_bus::{BusRequest, BusResponse, StormguardDebugDirection, StormguardDebugEntry, TcHandle}; use lqos_queue_tracker::QUEUE_STRUCTURE; -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use tracing::{debug, info, warn}; pub struct SiteStateTracker { sites: HashMap, + active_circuit_fallbacks: HashSet, } impl SiteStateTracker { @@ -45,15 +50,96 @@ impl SiteStateTracker { retransmits_down_moving_average: RingBuffer::new(MOVING_AVERAGE_BUFFER_SIZE), retransmits_up_moving_average: RingBuffer::new(MOVING_AVERAGE_BUFFER_SIZE), round_trip_time_moving_average: RingBuffer::new(MOVING_AVERAGE_BUFFER_SIZE), - queue_download_mbps: site.max_download_mbps, - queue_upload_mbps: site.max_upload_mbps, + queue_download_mbps: site.current_download_mbps, + queue_upload_mbps: site.current_upload_mbps, current_throughput: (0.0, 0.0), ticks_since_last_probe_download: 0, ticks_since_last_probe_upload: 0, }, ); } - Self { sites } + Self { + sites, + active_circuit_fallbacks: HashSet::new(), + } + } + + pub fn replay_persisted_adjustments( + &mut self, + config: &StormguardConfig, + bakery_sender: Sender, + ) { + if config.dry_run { + return; + } + + let Some(queues) = &QUEUE_STRUCTURE.load().maybe_queues else { + info!("No queue structure - cannot replay StormGuard adjustments"); + return; + }; + + match load_persisted_circuit_fallbacks() { + Ok(fallbacks) => { + for (circuit_id, fallback) in fallbacks { + self.active_circuit_fallbacks.insert(circuit_id.clone()); + if let Err(e) = apply_circuit_fallback( + &circuit_id, + &fallback.sqm_override, + false, + false, + bakery_sender.clone(), + ) { + warn!( + "Failed to replay persisted StormGuard circuit fallback for {}: {}", + circuit_id, 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 { + continue; + }; + + if queue.circuit_id.is_some() { + continue; + } + + for direction in [ + RecommendationDirection::Download, + RecommendationDirection::Upload, + ] { + let current_rate = Self::site_rate(site, direction); + let planned_rate = Self::planned_rate(&site.config, direction); + if current_rate == planned_rate { + continue; + } + + let interface_name = Self::interface_name(config, direction); + info!( + "Replaying persisted StormGuard {} override for {}: {} -> {}", + direction, name, planned_rate, current_rate + ); + Self::apply_dependents( + &site.config, + direction, + current_rate, + config, + &interface_name, + bakery_sender.clone(), + ); + Self::apply_htb_change( + config, + &interface_name, + queue.class_id, + current_rate, + bakery_sender.clone(), + ); + } + } } pub async fn read_new_tick_data(&mut self) { @@ -243,6 +329,7 @@ impl SiteStateTracker { info!("No queue structure - cannot get stats"); return; }; + let mut pending_site_updates: HashSet = HashSet::new(); for (recommendation, summary) in recommendations { // Find the Site Object @@ -265,51 +352,40 @@ impl SiteStateTracker { info!("Queue {} not found in queue structure", recommendation.site); continue; }; - // Skip circuit-level queues that host a qdisc (CAKE/fq_codel). Changing HTB at that - // level can deadlock the kernel; only adjust parent branch nodes. - if queue.circuit_id.is_some() { - warn!( - "StormGuard skipped {} because it resolves to a circuit queue (qdisc host).", - recommendation.site + let cooldown_secs = Self::cooldown_for_action(config, &recommendation.action); + debug!( + "Cooldown for {:?} set to {:.1}s", + recommendation.action, cooldown_secs + ); + + // Circuit queues host qdiscs; prefer the TreeGuard-style fallback path. + if let Some(circuit_id) = queue.circuit_id.as_deref() { + Self::handle_circuit_queue_recommendation( + &mut self.active_circuit_fallbacks, + site, + config, + &recommendation, + &summary, + circuit_id, + cooldown_secs, + &log_sender, + bakery_sender.clone(), ); continue; } - // Find the interface - let interface_name = match recommendation.direction { - RecommendationDirection::Download => config.download_interface.clone(), - RecommendationDirection::Upload => config.upload_interface.clone(), - }; + let interface_name = Self::interface_name(config, recommendation.direction); // Find the TC class let class_handle = queue.class_id; // Find the new bandwidth - let current_rate = match recommendation.direction { - RecommendationDirection::Download => site.queue_download_mbps, - RecommendationDirection::Upload => site.queue_upload_mbps, - } as f64; - - let max_rate = match recommendation.direction { - RecommendationDirection::Download => site_config.max_download_mbps, - RecommendationDirection::Upload => site_config.max_upload_mbps, - } as f64; - let min_rate = match recommendation.direction { - RecommendationDirection::Download => site_config.min_download_mbps, - RecommendationDirection::Upload => site_config.min_upload_mbps, - } as f64; - - let new_rate_multiplier = match recommendation.action { - RecommendationAction::Increase => 1.15, - RecommendationAction::IncreaseFast => 1.30, - RecommendationAction::Decrease => 0.95, - RecommendationAction::DecreaseFast => 0.88, - }; - let new_rate = match recommendation.direction { - RecommendationDirection::Download => site.queue_download_mbps, - RecommendationDirection::Upload => site.queue_upload_mbps, - } as f64 - * new_rate_multiplier; + let current_rate = Self::site_rate(site, recommendation.direction) as f64; + let max_rate = Self::planned_rate(site_config, recommendation.direction) as f64; + let min_rate = Self::minimum_rate(site_config, recommendation.direction) as f64; + + let new_rate_multiplier = Self::multiplier_for_action(config, &recommendation.action); + let new_rate = current_rate * new_rate_multiplier; let new_rate = new_rate.round(); // Are we allowed to do it? @@ -327,67 +403,44 @@ impl SiteStateTracker { continue; } - let cooldown_secs = match recommendation.action { - RecommendationAction::IncreaseFast => { - // Halved to allow quicker follow-up increases. - (READING_ACCUMULATOR_SIZE as f32 * 0.05).max(2.0) - } - RecommendationAction::Increase => { - (READING_ACCUMULATOR_SIZE as f32 * 0.025).max(1.0) - } - RecommendationAction::Decrease => READING_ACCUMULATOR_SIZE as f32 * 0.25, - RecommendationAction::DecreaseFast => READING_ACCUMULATOR_SIZE as f32 * 0.5, - }; - debug!( - "Cooldown for {:?} set to {:.1}s", - recommendation.action, cooldown_secs - ); - - // Apply to the site - match recommendation.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(site) = lock.iter_mut().find(|(n, _, _)| n == &recommendation.site) - { - site.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(site) = lock.iter_mut().find(|(n, _, _)| n == &recommendation.site) - { - site.2 = new_rate; - } - } - } - - // Apply for dependents - for dependent in &site.config.dependent_nodes { - let max_rate = match recommendation.direction { - RecommendationDirection::Download => dependent.original_max_download_mbps, - RecommendationDirection::Upload => dependent.original_max_upload_mbps, - }; - if max_rate < new_rate { - continue; - } - info!( - "Applying rate change to dependent {}: {} -> {}", - dependent.name, dependent.original_max_download_mbps, new_rate + if config.dry_run { + Self::apply_dependents( + &site.config, + recommendation.direction, + new_rate, + config, + &interface_name, + bakery_sender.clone(), ); Self::apply_htb_change( config, &interface_name, - dependent.class_id, + class_handle, new_rate, bakery_sender.clone(), ); + Self::enter_cooldown(site, recommendation.direction, cooldown_secs); + let _ = log_sender.send(LogCommand::SpeedChange { + site: recommendation.site.clone(), + download: site.queue_download_mbps, + upload: site.queue_upload_mbps, + state: format!("{summary}; dry_run_target={new_rate}"), + }); + continue; } + // Apply to the site + Self::set_site_rate(site, recommendation.direction, new_rate); + // Actually make the change + Self::apply_dependents( + &site.config, + recommendation.direction, + new_rate, + config, + &interface_name, + bakery_sender.clone(), + ); Self::apply_htb_change( config, &interface_name, @@ -395,23 +448,11 @@ impl SiteStateTracker { new_rate, bakery_sender.clone(), ); + pending_site_updates.insert(site.config.name.clone()); // Finish Up by entering cooldown debug!("Recommendation applied: entering cooldown"); - match recommendation.direction { - RecommendationDirection::Download => { - site.download_state = StormguardState::Cooldown { - start: std::time::Instant::now(), - duration_secs: cooldown_secs, - }; - } - RecommendationDirection::Upload => { - site.upload_state = StormguardState::Cooldown { - start: std::time::Instant::now(), - duration_secs: cooldown_secs, - }; - } - } + Self::enter_cooldown(site, recommendation.direction, cooldown_secs); // Report let _ = log_sender.send(LogCommand::SpeedChange { @@ -421,6 +462,264 @@ impl SiteStateTracker { state: summary, }); } + + if !pending_site_updates.is_empty() { + let updates: Vec = pending_site_updates + .into_iter() + .filter_map(|site_name| { + self.sites + .get(&site_name) + .map(Self::site_override_update_from_state) + }) + .collect(); + if let Err(e) = apply_site_override_updates(&updates) { + warn!("Failed to batch StormGuard site override updates: {}", e); + } + } + } + + fn handle_circuit_queue_recommendation( + active_circuit_fallbacks: &mut HashSet, + site: &mut SiteState, + config: &StormguardConfig, + recommendation: &Recommendation, + summary: &str, + circuit_id: &str, + cooldown_secs: f32, + log_sender: &std::sync::mpsc::Sender, + bakery_sender: Sender, + ) { + let outcome = if !config.circuit_fallback_enabled { + CircuitFallbackOutcome::Skipped { + reason: "Circuit fallback disabled in config.".to_string(), + } + } else if matches!( + recommendation.action, + RecommendationAction::Increase | RecommendationAction::IncreaseFast + ) && !active_circuit_fallbacks.contains(circuit_id) + { + CircuitFallbackOutcome::Skipped { + reason: "No active StormGuard circuit fallback to clear.".to_string(), + } + } else { + match recommendation.action { + RecommendationAction::Decrease | RecommendationAction::DecreaseFast => { + match apply_circuit_fallback( + circuit_id, + &config.circuit_fallback_sqm, + config.circuit_fallback_persist, + config.dry_run, + bakery_sender, + ) { + Ok(outcome) => outcome, + Err(e) => { + warn!( + "StormGuard fallback failed for circuit {} ({}): {}", + circuit_id, recommendation.site, e + ); + CircuitFallbackOutcome::Skipped { + reason: format!("Fallback error: {e}"), + } + } + } + } + RecommendationAction::Increase | RecommendationAction::IncreaseFast => { + match clear_circuit_fallback(circuit_id, config.dry_run, bakery_sender) { + Ok(outcome) => outcome, + Err(e) => { + warn!( + "StormGuard fallback clear failed for circuit {} ({}): {}", + circuit_id, recommendation.site, e + ); + CircuitFallbackOutcome::Skipped { + reason: format!("Fallback clear error: {e}"), + } + } + } + } + } + }; + + let (outcome_text, enters_cooldown) = match outcome { + CircuitFallbackOutcome::Applied { persisted } => { + active_circuit_fallbacks.insert(circuit_id.to_string()); + info!( + "StormGuard applied circuit fallback for {} ({})", + recommendation.site, circuit_id + ); + ( + format!( + "circuit_fallback=applied sqm={} persisted={persisted}", + config.circuit_fallback_sqm + ), + true, + ) + } + CircuitFallbackOutcome::Cleared { persisted } => { + active_circuit_fallbacks.remove(circuit_id); + info!( + "StormGuard cleared circuit fallback for {} ({})", + recommendation.site, circuit_id + ); + (format!("circuit_fallback=cleared persisted={persisted}"), true) + } + CircuitFallbackOutcome::DryRun { action } => { + info!( + "StormGuard dry-run circuit fallback for {} ({}): {}", + recommendation.site, circuit_id, action + ); + (format!("circuit_fallback=dry_run {action}"), true) + } + CircuitFallbackOutcome::Skipped { reason } => { + warn!( + "StormGuard skipped circuit fallback for {} ({}): {}", + recommendation.site, circuit_id, reason + ); + (format!("circuit_fallback=skipped reason={reason}"), false) + } + }; + + if Self::circuit_outcome_enters_cooldown(&enters_cooldown) { + Self::enter_cooldown(site, recommendation.direction, cooldown_secs); + } + let _ = log_sender.send(LogCommand::SpeedChange { + site: recommendation.site.clone(), + download: site.queue_download_mbps, + upload: site.queue_upload_mbps, + state: format!("{summary}; {outcome_text}"), + }); + } + + fn site_rate(site: &SiteState, direction: RecommendationDirection) -> u64 { + match direction { + RecommendationDirection::Download => site.queue_download_mbps, + RecommendationDirection::Upload => site.queue_upload_mbps, + } + } + + fn planned_rate(site: &crate::config::WatchingSite, direction: RecommendationDirection) -> u64 { + match direction { + RecommendationDirection::Download => site.max_download_mbps, + RecommendationDirection::Upload => site.max_upload_mbps, + } + } + + fn minimum_rate(site: &crate::config::WatchingSite, direction: RecommendationDirection) -> u64 { + match direction { + RecommendationDirection::Download => site.min_download_mbps, + RecommendationDirection::Upload => site.min_upload_mbps, + } + } + + fn interface_name(config: &StormguardConfig, direction: RecommendationDirection) -> String { + match direction { + RecommendationDirection::Download => config.download_interface.clone(), + RecommendationDirection::Upload => config.upload_interface.clone(), + } + } + + fn multiplier_for_action(config: &StormguardConfig, action: &RecommendationAction) -> f64 { + match action { + RecommendationAction::IncreaseFast => config.increase_fast_multiplier, + RecommendationAction::Increase => config.increase_multiplier, + RecommendationAction::Decrease => config.decrease_multiplier, + RecommendationAction::DecreaseFast => config.decrease_fast_multiplier, + } + } + + fn cooldown_for_action(config: &StormguardConfig, action: &RecommendationAction) -> f32 { + match action { + RecommendationAction::IncreaseFast => config.increase_fast_cooldown_seconds, + RecommendationAction::Increase => config.increase_cooldown_seconds, + RecommendationAction::Decrease => config.decrease_cooldown_seconds, + RecommendationAction::DecreaseFast => config.decrease_fast_cooldown_seconds, + } + } + + 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::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, + direction: RecommendationDirection, + new_rate: u64, + config: &StormguardConfig, + interface_name: &str, + bakery_sender: Sender, + ) { + for dependent in &site.dependent_nodes { + let max_rate = match direction { + RecommendationDirection::Download => dependent.original_max_download_mbps, + RecommendationDirection::Upload => dependent.original_max_upload_mbps, + }; + if max_rate < new_rate { + continue; + } + info!( + "Applying rate change to dependent {}: {} -> {}", + dependent.name, max_rate, new_rate + ); + Self::apply_htb_change( + config, + interface_name, + dependent.class_id, + new_rate, + bakery_sender.clone(), + ); + } + } + + fn site_override_update_from_state(site: &SiteState) -> SiteOverrideUpdate { + SiteOverrideUpdate { + site_name: site.config.name.clone(), + download_bandwidth_mbps: (site.queue_download_mbps != site.config.max_download_mbps) + .then_some(site.queue_download_mbps as u32), + upload_bandwidth_mbps: (site.queue_upload_mbps != site.config.max_upload_mbps) + .then_some(site.queue_upload_mbps as u32), + } + } + + fn circuit_outcome_enters_cooldown(enters_cooldown: &bool) -> bool { + *enters_cooldown + } + + fn enter_cooldown(site: &mut SiteState, direction: RecommendationDirection, cooldown_secs: f32) { + match direction { + RecommendationDirection::Download => { + site.download_state = StormguardState::Cooldown { + start: std::time::Instant::now(), + duration_secs: cooldown_secs, + }; + } + RecommendationDirection::Upload => { + site.upload_state = StormguardState::Cooldown { + start: std::time::Instant::now(), + duration_secs: cooldown_secs, + }; + } + } } fn apply_htb_change( @@ -475,3 +774,63 @@ impl SiteStateTracker { // } } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::config::WatchingSite; + + fn site_state(download: u64, upload: u64, max_down: u64, max_up: u64) -> SiteState { + SiteState { + config: WatchingSite { + name: "Site A".to_string(), + max_download_mbps: max_down, + max_upload_mbps: max_up, + min_download_mbps: 10, + min_upload_mbps: 10, + dependent_nodes: Vec::new(), + current_download_mbps: download, + current_upload_mbps: upload, + }, + download_state: StormguardState::Running, + upload_state: StormguardState::Running, + throughput_down: RingBuffer::new(READING_ACCUMULATOR_SIZE), + throughput_up: RingBuffer::new(READING_ACCUMULATOR_SIZE), + retransmits_down: RingBuffer::new(READING_ACCUMULATOR_SIZE), + retransmits_up: RingBuffer::new(READING_ACCUMULATOR_SIZE), + round_trip_time: RingBuffer::new(READING_ACCUMULATOR_SIZE), + throughput_down_moving_average: RingBuffer::new(MOVING_AVERAGE_BUFFER_SIZE), + throughput_up_moving_average: RingBuffer::new(MOVING_AVERAGE_BUFFER_SIZE), + retransmits_down_moving_average: RingBuffer::new(MOVING_AVERAGE_BUFFER_SIZE), + retransmits_up_moving_average: RingBuffer::new(MOVING_AVERAGE_BUFFER_SIZE), + round_trip_time_moving_average: RingBuffer::new(MOVING_AVERAGE_BUFFER_SIZE), + queue_download_mbps: download, + queue_upload_mbps: upload, + current_throughput: (0.0, 0.0), + ticks_since_last_probe_download: 0, + ticks_since_last_probe_upload: 0, + } + } + + #[test] + fn site_override_update_omits_baseline_rates() { + let site = site_state(100, 50, 100, 50); + let update = SiteStateTracker::site_override_update_from_state(&site); + assert_eq!(update.download_bandwidth_mbps, None); + assert_eq!(update.upload_bandwidth_mbps, None); + } + + #[test] + fn site_override_update_keeps_only_changed_directions() { + let site = site_state(75, 50, 100, 50); + let update = SiteStateTracker::site_override_update_from_state(&site); + assert_eq!(update.download_bandwidth_mbps, Some(75)); + assert_eq!(update.upload_bandwidth_mbps, None); + } + + #[test] + fn skipped_circuit_outcomes_do_not_enter_cooldown() { + assert!(!SiteStateTracker::circuit_outcome_enters_cooldown(&false)); + assert!(SiteStateTracker::circuit_outcome_enters_cooldown(&true)); + } +} diff --git a/src/rust/lqosd/src/node_manager/js_build/src/config_stormguard.js b/src/rust/lqosd/src/node_manager/js_build/src/config_stormguard.js index f9674a3a..833d4035 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/config_stormguard.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/config_stormguard.js @@ -7,6 +7,50 @@ import { let networkData = null; let selectedTargets = []; +let excludedSites = []; + +function defaultStormguardConfig() { + return { + enabled: false, + dry_run: true, + log_file: null, + all_sites: false, + targets: [], + exclude_sites: [], + minimum_download_percentage: 0.5, + minimum_upload_percentage: 0.5, + increase_fast_multiplier: 1.30, + increase_multiplier: 1.15, + decrease_multiplier: 0.95, + decrease_fast_multiplier: 0.88, + increase_fast_cooldown_seconds: 2, + increase_cooldown_seconds: 1, + decrease_cooldown_seconds: 3.75, + decrease_fast_cooldown_seconds: 7.5, + circuit_fallback_enabled: false, + circuit_fallback_persist: true, + circuit_fallback_sqm: "fq_codel", + }; +} + +const VALID_FALLBACK_SQMS = ['fq_codel', 'cake']; + +function ensureStormguardConfig(config) { + return { + ...defaultStormguardConfig(), + ...(config || {}), + targets: Array.isArray(config?.targets) ? [...config.targets] : [], + exclude_sites: Array.isArray(config?.exclude_sites) ? [...config.exclude_sites] : [], + }; +} + +function updateTargetsUi() { + const allSites = document.getElementById("allSites")?.checked ?? false; + const section = document.getElementById("targetsSection"); + if (section) { + section.style.display = allSites ? "none" : ""; + } +} // Load network.json for site dropdown function loadNetworkData() { @@ -22,7 +66,7 @@ function loadNetworkData() { } networkData = data; console.log('Network data loaded:', networkData); - populateSiteSelector(); + populateSiteSelectors(); resolve(); }, (err) => { @@ -34,129 +78,260 @@ function loadNetworkData() { }); } -// Build dropdown options from network tree -function populateSiteSelector() { - const selector = document.getElementById('siteSelector'); +function setSelectorOptions(selectorId) { + const selector = document.getElementById(selectorId); selector.innerHTML = ''; - + function iterate(data, level = 0) { - // Handle case where data might be a string or other non-object if (typeof data !== 'object' || data === null) { - console.warn('Data is not an object:', data); return; } - + for (const [key, value] of Object.entries(data)) { const option = document.createElement('option'); option.value = key; - - // Add indentation for hierarchy + let prefix = ''; for (let i = 0; i < level; i++) { prefix += '- '; } option.textContent = prefix + key; - + selector.appendChild(option); - - // Recursively add children + if (value && typeof value === 'object' && value.children != null) { iterate(value.children, level + 1); } } } - + if (networkData) { - console.log('Populating site selector with:', networkData); iterate(networkData); - } else { - console.error('Network data is null or undefined'); } } -// Add site to targets list -function addSite() { - const selector = document.getElementById('siteSelector'); +function populateSiteSelectors() { + setSelectorOptions("targetSiteSelector"); + setSelectorOptions("excludeSiteSelector"); +} + +function addItemToList(listName, value, duplicateMessage) { + if (!value) { + return false; + } + + const list = listName === "targets" ? selectedTargets : excludedSites; + if (list.includes(value)) { + alert(duplicateMessage); + return false; + } + + list.push(value); + list.sort((a, b) => a.localeCompare(b)); + return true; +} + +function addTargetFromSelector() { + const selector = document.getElementById("targetSiteSelector"); const selectedSite = selector.value; - + if (!selectedSite) { alert('Please select a site to add'); return; } - - // Check if already in list - if (selectedTargets.includes(selectedSite)) { - alert('This site is already being monitored'); + + if (addItemToList("targets", selectedSite, 'This site is already in the allowlist')) { + selector.value = ''; + updateTargetsList(); + } +} + +function addTargetFromManual() { + const input = document.getElementById("targetSiteManual"); + const siteName = input.value.trim(); + if (!siteName) { + alert('Please enter a site name'); return; } - - selectedTargets.push(selectedSite); - updateTargetsList(); - - // Reset selector - selector.value = ''; + + if (addItemToList("targets", siteName, 'This site is already in the allowlist')) { + input.value = ''; + updateTargetsList(); + } } -// Remove site from targets list -function removeSite(siteName) { - const index = selectedTargets.indexOf(siteName); +function addExcludeFromSelector() { + const selector = document.getElementById("excludeSiteSelector"); + const selectedSite = selector.value; + if (!selectedSite) { + alert('Please select a site to exclude'); + return; + } + + if (addItemToList("exclude", selectedSite, 'This site is already excluded')) { + selector.value = ''; + updateExcludedSitesList(); + } +} + +function addExcludeFromManual() { + const input = document.getElementById("excludeSiteManual"); + const siteName = input.value.trim(); + if (!siteName) { + alert('Please enter a site name'); + return; + } + + if (addItemToList("exclude", siteName, 'This site is already excluded')) { + input.value = ''; + updateExcludedSitesList(); + } +} + +function removeItem(listName, itemName) { + const list = listName === "targets" ? selectedTargets : excludedSites; + const index = list.indexOf(itemName); if (index > -1) { - selectedTargets.splice(index, 1); - updateTargetsList(); + list.splice(index, 1); } } -// Update the targets list UI -function updateTargetsList() { - const listContainer = document.getElementById('selectedSitesList'); +// Add site to targets list +function removeTarget(siteName) { + removeItem("targets", siteName); + updateTargetsList(); +} + +function removeExcludedSite(siteName) { + removeItem("exclude", siteName); + updateExcludedSitesList(); +} + +function updateList(listId, emptyMessage, items, removeHandler) { + const listContainer = document.getElementById(listId); listContainer.innerHTML = ''; - - if (selectedTargets.length === 0) { - listContainer.innerHTML = '
No sites selected
'; + + if (items.length === 0) { + listContainer.innerHTML = `
${emptyMessage}
`; return; } - - selectedTargets.forEach(site => { + + items.forEach((site) => { const listItem = document.createElement('div'); listItem.className = 'list-group-item d-flex justify-content-between align-items-center'; - + const siteName = document.createElement('span'); siteName.textContent = site; - + const removeBtn = document.createElement('button'); removeBtn.className = 'btn btn-sm btn-outline-danger'; removeBtn.innerHTML = ''; - removeBtn.onclick = () => removeSite(site); - + removeBtn.onclick = () => removeHandler(site); + listItem.appendChild(siteName); listItem.appendChild(removeBtn); listContainer.appendChild(listItem); }); } +function updateTargetsList() { + updateList("selectedTargetsList", "No allowlisted sites", selectedTargets, removeTarget); +} + +function updateExcludedSitesList() { + updateList("excludedSitesList", "No excluded sites", excludedSites, removeExcludedSite); +} + +function parseNumber(id) { + return parseFloat(document.getElementById(id).value); +} + +function validatePercent(name, value) { + if (Number.isNaN(value) || value < 1 || value > 100) { + alert(`${name} must be between 1 and 100`); + return false; + } + return true; +} + +function validatePositiveNumber(name, value, min, relationText) { + if (Number.isNaN(value) || value < min) { + alert(`${name} must be ${relationText}`); + return false; + } + return true; +} + // Validate configuration function validateConfig() { const enabled = document.getElementById('enabled').checked; - const minDownloadPct = parseInt(document.getElementById('minDownloadPct').value); - const minUploadPct = parseInt(document.getElementById('minUploadPct').value); - - // Validate percentage values - if (isNaN(minDownloadPct) || minDownloadPct < 1 || minDownloadPct > 100) { - alert('Minimum Download Percentage must be between 1 and 100'); + const allSites = document.getElementById('allSites').checked; + const minDownloadPct = parseNumber('minDownloadPct'); + const minUploadPct = parseNumber('minUploadPct'); + + if (!validatePercent('Minimum Download Percentage', minDownloadPct)) { return false; } - - if (isNaN(minUploadPct) || minUploadPct < 1 || minUploadPct > 100) { - alert('Minimum Upload Percentage must be between 1 and 100'); + + if (!validatePercent('Minimum Upload Percentage', minUploadPct)) { return false; } - - // If enabled, must have at least one target - if (enabled && selectedTargets.length === 0) { + + if (enabled && !allSites && selectedTargets.length === 0) { alert('Please select at least one site to monitor when StormGuard is enabled'); return false; } - + + const increaseFastMultiplier = parseNumber('increaseFastMultiplier'); + const increaseMultiplier = parseNumber('increaseMultiplier'); + const decreaseMultiplier = parseNumber('decreaseMultiplier'); + const decreaseFastMultiplier = parseNumber('decreaseFastMultiplier'); + + if (!validatePositiveNumber('Increase Fast Multiplier', increaseFastMultiplier, 0.01, 'greater than 1.0')) return false; + if (!validatePositiveNumber('Increase Multiplier', increaseMultiplier, 0.01, 'greater than 1.0')) return false; + if (!validatePositiveNumber('Decrease Multiplier', decreaseMultiplier, 0.01, 'greater than 0')) return false; + if (!validatePositiveNumber('Decrease Fast Multiplier', decreaseFastMultiplier, 0.01, 'greater than 0')) return false; + + if (increaseFastMultiplier <= 1) { + alert('Increase Fast Multiplier must be greater than 1.0'); + return false; + } + + if (increaseMultiplier <= 1) { + alert('Increase Multiplier must be greater than 1.0'); + return false; + } + + if (decreaseMultiplier > 1) { + alert('Decrease Multiplier must be less than or equal to 1.0'); + return false; + } + + if (decreaseFastMultiplier > 1) { + alert('Decrease Fast Multiplier must be less than or equal to 1.0'); + return false; + } + + const cooldownFields = [ + ['Increase Fast Cooldown', 'increaseFastCooldownSeconds'], + ['Increase Cooldown', 'increaseCooldownSeconds'], + ['Decrease Cooldown', 'decreaseCooldownSeconds'], + ['Decrease Fast Cooldown', 'decreaseFastCooldownSeconds'], + ]; + + for (const [name, id] of cooldownFields) { + if (!validatePositiveNumber(name, parseNumber(id), 0.01, 'greater than 0 seconds')) { + return false; + } + } + + const fallbackEnabled = document.getElementById('circuitFallbackEnabled').checked; + const fallbackSqm = document.getElementById('circuitFallbackSqm').value.trim(); + if (fallbackEnabled && !VALID_FALLBACK_SQMS.includes(fallbackSqm)) { + alert('Circuit Fallback SQM must be one of: fq_codel, cake'); + return false; + } + return true; } @@ -166,11 +341,24 @@ function updateConfig() { window.config.stormguard = { enabled: document.getElementById('enabled').checked, - targets: selectedTargets, dry_run: document.getElementById('dryRun').checked, log_file: logFilePath === '' ? null : logFilePath, - minimum_download_percentage: parseInt(document.getElementById('minDownloadPct').value) / 100, - minimum_upload_percentage: parseInt(document.getElementById('minUploadPct').value) / 100 + all_sites: document.getElementById('allSites').checked, + targets: [...selectedTargets], + exclude_sites: [...excludedSites], + minimum_download_percentage: parseNumber('minDownloadPct') / 100, + minimum_upload_percentage: parseNumber('minUploadPct') / 100, + increase_fast_multiplier: parseNumber('increaseFastMultiplier'), + increase_multiplier: parseNumber('increaseMultiplier'), + decrease_multiplier: parseNumber('decreaseMultiplier'), + decrease_fast_multiplier: parseNumber('decreaseFastMultiplier'), + increase_fast_cooldown_seconds: parseNumber('increaseFastCooldownSeconds'), + increase_cooldown_seconds: parseNumber('increaseCooldownSeconds'), + decrease_cooldown_seconds: parseNumber('decreaseCooldownSeconds'), + decrease_fast_cooldown_seconds: parseNumber('decreaseFastCooldownSeconds'), + circuit_fallback_enabled: document.getElementById('circuitFallbackEnabled').checked, + circuit_fallback_persist: document.getElementById('circuitFallbackPersist').checked, + circuit_fallback_sqm: document.getElementById('circuitFallbackSqm').value.trim() || 'fq_codel', }; } @@ -185,37 +373,69 @@ Promise.all([ }) ]).then(() => { console.log('Both network data and config loaded'); - - // Now populate the UI with config data - if (window.config && window.config.stormguard) { - const sg = window.config.stormguard; - - // Set form values - document.getElementById('enabled').checked = sg.enabled || false; - document.getElementById('dryRun').checked = sg.dry_run || false; - document.getElementById('logFile').value = sg.log_file || ''; - - // Convert decimal to percentage for display - document.getElementById('minDownloadPct').value = Math.round((sg.minimum_download_percentage || 0.5) * 100); - document.getElementById('minUploadPct').value = Math.round((sg.minimum_upload_percentage || 0.5) * 100); - - // Load targets - selectedTargets = sg.targets || []; - updateTargetsList(); - } - - // Set up event handlers - document.getElementById('addSiteBtn').addEventListener('click', addSite); - - // Allow Enter key in site selector to add site - document.getElementById('siteSelector').addEventListener('keypress', (e) => { + + const sg = ensureStormguardConfig(window.config?.stormguard); + + document.getElementById('enabled').checked = sg.enabled; + document.getElementById('dryRun').checked = sg.dry_run; + document.getElementById('logFile').value = sg.log_file || ''; + document.getElementById('allSites').checked = sg.all_sites; + document.getElementById('minDownloadPct').value = Math.round(sg.minimum_download_percentage * 100); + document.getElementById('minUploadPct').value = Math.round(sg.minimum_upload_percentage * 100); + document.getElementById('increaseFastMultiplier').value = sg.increase_fast_multiplier; + document.getElementById('increaseMultiplier').value = sg.increase_multiplier; + document.getElementById('decreaseMultiplier').value = sg.decrease_multiplier; + document.getElementById('decreaseFastMultiplier').value = sg.decrease_fast_multiplier; + document.getElementById('increaseFastCooldownSeconds').value = sg.increase_fast_cooldown_seconds; + document.getElementById('increaseCooldownSeconds').value = sg.increase_cooldown_seconds; + document.getElementById('decreaseCooldownSeconds').value = sg.decrease_cooldown_seconds; + document.getElementById('decreaseFastCooldownSeconds').value = sg.decrease_fast_cooldown_seconds; + document.getElementById('circuitFallbackEnabled').checked = sg.circuit_fallback_enabled; + document.getElementById('circuitFallbackPersist').checked = sg.circuit_fallback_persist; + document.getElementById('circuitFallbackSqm').value = VALID_FALLBACK_SQMS.includes(sg.circuit_fallback_sqm) + ? sg.circuit_fallback_sqm + : 'fq_codel'; + + selectedTargets = [...sg.targets].sort((a, b) => a.localeCompare(b)); + excludedSites = [...sg.exclude_sites].sort((a, b) => a.localeCompare(b)); + updateTargetsUi(); + updateTargetsList(); + updateExcludedSitesList(); + + document.getElementById('allSites').addEventListener('change', updateTargetsUi); + document.getElementById('addTargetBtn').addEventListener('click', addTargetFromSelector); + document.getElementById('addTargetManualBtn').addEventListener('click', addTargetFromManual); + document.getElementById('addExcludeBtn').addEventListener('click', addExcludeFromSelector); + document.getElementById('addExcludeManualBtn').addEventListener('click', addExcludeFromManual); + + document.getElementById('targetSiteSelector').addEventListener('keypress', (e) => { if (e.key === 'Enter') { e.preventDefault(); - addSite(); + addTargetFromSelector(); } }); - - // Save button handler + + document.getElementById('targetSiteManual').addEventListener('keypress', (e) => { + if (e.key === 'Enter') { + e.preventDefault(); + addTargetFromManual(); + } + }); + + document.getElementById('excludeSiteSelector').addEventListener('keypress', (e) => { + if (e.key === 'Enter') { + e.preventDefault(); + addExcludeFromSelector(); + } + }); + + document.getElementById('excludeSiteManual').addEventListener('keypress', (e) => { + if (e.key === 'Enter') { + e.preventDefault(); + addExcludeFromManual(); + } + }); + document.getElementById('saveButton').addEventListener('click', () => { if (validateConfig()) { updateConfig(); diff --git a/src/rust/lqosd/src/node_manager/static2/config_stormguard.html b/src/rust/lqosd/src/node_manager/static2/config_stormguard.html index ce88ac75..fd517c5f 100644 --- a/src/rust/lqosd/src/node_manager/static2/config_stormguard.html +++ b/src/rust/lqosd/src/node_manager/static2/config_stormguard.html @@ -17,23 +17,78 @@
Enable automatic rate adjustment based on network conditions
+ +
+ + +
Test mode - log changes without applying them
+
+ + +
+ + +
Path to CSV file for logging site rates (leave empty to disable)
+
+ +
+
Site Enrollment
+ +
+ + +
If enabled, StormGuard monitors all sites except those in the exclude list
+
+
- -
Select sites to monitor for automatic rate adjustment
- - + +
Used only when Monitor All Sites is unchecked
+ +
+
+ + +
+ +
+ + +
+ +
+ +
+
+
+ +
+ +
Sites to exclude when Monitor All Sites is enabled
+
- -
- - -
+ +
+ + +
+ +
@@ -51,18 +106,76 @@
Minimum percentage of advertised upload speed (e.g., 50 for 50%)
- +
+
Adjustment Multipliers
+ +
+
+ + +
Used for aggressive recovery when conditions improve quickly
+
+
+ + +
Used for normal recovery when capacity can be raised
+
+
+ + +
Used for normal reductions when instability is detected
+
+
+ + +
Used for aggressive reductions when conditions deteriorate quickly
+
+
+ +
+
Cooldowns
+ +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ +
+
Circuit Fallback
+
- - -
Test mode - log changes without applying them
+ + +
Allow StormGuard to request a circuit-level fallback action when direct site adjustment is not appropriate
+
+ +
+ + +
Keep fallback overrides across scheduler runs when supported by the backend
-
- - -
Path to CSV file for logging site rates (leave empty to disable)
+ + +
SQM token to request for fallback actions
@@ -70,4 +183,4 @@ - \ No newline at end of file + -- knotmirror 0.0.1 From 927c220d1922b2ce6f9c1aff985b26ac9ace8484 Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Mon, 9 Mar 2026 16:19:49 -0500 Subject: [PATCH 5/5] Chore: remove StormGuard TreeGuard design note --- STORMGUARD_TREEGUARD.md | 139 ---------------------------------------- 1 file changed, 139 deletions(-) delete mode 100644 STORMGUARD_TREEGUARD.md diff --git a/STORMGUARD_TREEGUARD.md b/STORMGUARD_TREEGUARD.md deleted file mode 100644 index e0037215..00000000 --- a/STORMGUARD_TREEGUARD.md +++ /dev/null @@ -1,139 +0,0 @@ -# StormGuard and TreeGuard - -## Current Relationship - -StormGuard and TreeGuard overlap in intent, but not yet in implementation. - -- StormGuard is a live runtime component that watches telemetry and changes top-level HTB ceilings dynamically. -- TreeGuard, in the current branch, is primarily config, defaults, dashboard, and UI/schema work. -- TreeGuard does not yet appear to have a backend worker in this repo comparable to `lqos_stormguard`. - -That means the immediate reuse opportunity is not "replace StormGuard with TreeGuard", but "reuse the better TreeGuard control model and persistence contract to improve StormGuard". - -## What StormGuard Does Today - -StormGuard: - -- loads a configured allowlist of site names from `[stormguard].targets` -- resolves those names into queue nodes and dependent child nodes -- monitors throughput, retransmits, and RTT once per second -- applies multiplicative HTB ceiling changes through the bakery -- keeps an in-memory override map in the bakery so limits can be replayed after queue rebuilds in the same process - -Relevant code: - -- `src/rust/lqos_stormguard/src/lib.rs` -- `src/rust/lqos_stormguard/src/config.rs` -- `src/rust/lqos_stormguard/src/site_state.rs` -- `src/rust/lqos_bakery/src/lib.rs` - -## What TreeGuard Adds Conceptually - -TreeGuard introduces a more operationally useful model: - -- broad scope controls such as `all_nodes` and `all_circuits` -- explicit allowlists only when narrowing scope -- configurable dwell times, rate limits, and cooldowns -- explicit dry-run and enable toggles -- a persistence concept for scheduler-safe SQM overrides - -Relevant code: - -- `src/rust/lqos_config/src/etc/v15/treeguard.rs` -- `src/rust/lqosd/src/node_manager/static2/config_treeguard.html` - -## Best Opportunities - -### 1. Move StormGuard to persistent overrides - -This is the biggest improvement. - -Today StormGuard writes live HTB changes and the bakery stores them in an in-memory `stormguard_overrides` map. That lets the bakery replay them after queue rebuilds while `lqosd` remains alive, but it is still not a durable source of truth across restart. - -TreeGuard already establishes the right direction: persist adaptive changes so scheduler and rebuild flows do not fight them. - -Recommended direction: - -- replace StormGuard's in-memory-only override map with a persisted override file or persisted override store -- replay persisted overrides at bakery rebuild time -- keep dry-run behavior unchanged -- expose override state in debug UI so operators can see what is active - -This would directly address the historical "it is overwritten on scheduler run" problem more cleanly than the current in-memory replay. - -## 2. Give StormGuard TreeGuard-style scope controls - -StormGuard currently depends on a manual `targets` list of site names. - -TreeGuard's scope model is better: - -- apply to all eligible objects by default -- optionally narrow scope with an allowlist - -Recommended direction: - -- add `all_sites = true/false` to StormGuard -- keep `targets` only as an allowlist when `all_sites = false` -- consider a small exclusion list if operators want broad enablement with a few carve-outs - -This would make StormGuard much easier to deploy at scale. - -## 3. Move StormGuard policy constants into config - -StormGuard currently hardcodes: - -- increase/decrease multipliers -- cooldown timing -- some effective policy behavior thresholds - -TreeGuard's config model is more release-friendly because operators can tune behavior without code changes. - -Recommended direction: - -- expose StormGuard multipliers in config -- expose cooldowns and rate limits in config -- expose optional per-direction behavior controls -- validate these values in `lqos_config` the same way TreeGuard now validates its ranges and relationships - -This would reduce risk and make StormGuard easier to support. - -## 4. Use TreeGuard-style circuit actions when StormGuard cannot safely touch HTB - -StormGuard explicitly skips circuit-level queues that host a qdisc, because changing HTB at that level is unsafe. - -TreeGuard's circuit model suggests a better fallback: - -- when StormGuard detects instability on a queue it should not modify directly -- hand off a per-circuit mitigation action instead of doing nothing -- the obvious candidate is TreeGuard-style SQM switching such as CAKE to fq_codel for CPU savings or recovery behavior - -This is likely the cleanest place where TreeGuard extends StormGuard rather than replaces it. - -## 5. Build one shared adaptive-override substrate - -Longer term, StormGuard and TreeGuard probably should not each own their own action plumbing. - -Better structure: - -- StormGuard remains the congestion/instability policy -- TreeGuard remains the topology/SQM policy -- both emit actions into one shared override layer -- the bakery owns persistence, replay, and application of overrides -- the UI/debug layer reports active overrides and why they were applied - -That would avoid duplicated action paths and make adaptive behavior easier to reason about. - -## Practical Recommendation Order - -If we want the highest value with the least disruption: - -1. Add persistent StormGuard overrides first. -2. Add TreeGuard-style scope controls to StormGuard. -3. Move StormGuard tuning constants into config. -4. Add a handoff path where StormGuard can trigger TreeGuard-style circuit actions for qdisc-hosting queues. -5. Only after that, consider unifying both systems under a single adaptive framework. - -## One Caution - -While reviewing StormGuard, the dependent-node discovery in `src/rust/lqos_stormguard/src/queue_structure.rs` looks worth re-checking before building more behavior on top of it. The descendant filter logic is compact and may be more fragile than intended. -