From 0ab34b98524a4e367ee8b2bb83399db46e0ebc7d Mon Sep 17 00:00:00 2001 From: rchac Date: Thu, 26 Mar 2026 04:41:02 +0000 Subject: [PATCH] changes --- src/LibreQoS.py | 184 +++++------ src/lqos.example | 2 +- src/rust/lqos_bakery/src/commands.rs | 309 +++++++++++++++--- src/rust/lqos_bakery/src/lib.rs | 144 ++++++-- src/rust/lqos_config/src/etc/migration.rs | 8 +- src/rust/lqos_config/src/etc/mod.rs | 2 +- src/rust/lqos_config/src/etc/v15/example.toml | 2 +- src/rust/lqos_config/src/etc/v15/mod.rs | 2 +- src/rust/lqos_config/src/etc/v15/queues.rs | 154 ++++++++- src/rust/lqos_config/src/lib.rs | 10 +- src/rust/lqos_python/src/lib.rs | 9 +- .../js_build/src/config_queues.js | 5 +- .../js_build/src/configuration.js | 7 +- .../src/node_manager/js_build/src/template.js | 135 +++++++- .../node_manager/static2/config_queues.html | 11 +- .../node_manager/static2/configuration.html | 11 +- .../src/node_manager/static2/template.html | 11 + 17 files changed, 789 insertions(+), 217 deletions(-) diff --git a/src/LibreQoS.py b/src/LibreQoS.py index a2328fd7..78665ef9 100755 --- a/src/LibreQoS.py +++ b/src/LibreQoS.py @@ -36,7 +36,7 @@ from shaping_skip_report import ( from liblqos_python import is_lqosd_alive, clear_ip_mappings, delete_ip_mapping, validate_shaped_devices, \ is_libre_already_running, create_lock_file, free_lock_file, add_ip_mapping, BatchedCommands, \ check_config, sqm, upstream_bandwidth_capacity_download_mbps, upstream_bandwidth_capacity_upload_mbps, \ - interface_a, interface_b, enable_actual_shell_commands, use_bin_packing_to_balance_cpu, monitor_mode_only, \ + interface_a, interface_b, enable_actual_shell_commands, use_bin_packing_to_balance_cpu, queue_mode, \ run_shell_commands_as_sudo, generated_pn_download_mbps, generated_pn_upload_mbps, queues_available_override, \ on_a_stick, get_tree_weights, get_weights, is_network_flat, get_libreqos_directory, enable_insight_topology, \ is_insight_enabled, scheduler_error, xdp_ip_mapping_capacity, \ @@ -120,6 +120,10 @@ def get_planner_state_path(): return os.path.join(get_libreqos_directory(), "planner_state.json") +def observe_mode_enabled(): + return queue_mode() == "observe" + + def _load_json_dict(path): try: with open(path, "r") as infile: @@ -599,12 +603,6 @@ def loadSubscriberCircuits(shapedDevicesFile): token = left + '/' + right sqm_override_token = token circuitID, circuitName, deviceID, deviceName, ParentNode, mac, ipv4_input, ipv6_input, downloadMin, uploadMin, downloadMax, uploadMax, comment = row[0:13] - # If in monitorOnlyMode, override bandwidth rates to where no shaping will actually occur - if monitor_mode_only() == True: - downloadMin = 10000 - uploadMin = 10000 - downloadMax = 10000 - uploadMax = 10000 ipv4_subnets_and_hosts = [] # Each entry in ShapedDevices.csv can have multiple IPv4s or IPv6s separated by commas. Split them up and parse each if ipv4_input != "": @@ -633,13 +631,11 @@ def loadSubscriberCircuits(shapedDevicesFile): if circuit['ParentNode'] != ParentNode: errorMessageString = "Device " + deviceName + " with deviceID " + deviceID + " had different Parent Node from other devices of circuit ID #" + circuitID raise ValueError(errorMessageString) - # Check if bandwidth parameters match other cdevices of this same circuit ID, but only check if monitorOnlyMode is Off - if monitor_mode_only() == False: - if ((circuit['minDownload'] != float(downloadMin)) - or (circuit['minUpload'] != float(uploadMin)) - or (circuit['maxDownload'] != float(downloadMax)) - or (circuit['maxUpload'] != float(uploadMax))): - warnings.warn("Device " + deviceName + " with ID " + deviceID + " had different bandwidth parameters than other devices on this circuit. Will instead use the bandwidth parameters defined by the first device added to its circuit.", stacklevel=2) + if ((circuit['minDownload'] != float(downloadMin)) + or (circuit['minUpload'] != float(uploadMin)) + or (circuit['maxDownload'] != float(downloadMax)) + or (circuit['maxUpload'] != float(uploadMax))): + warnings.warn("Device " + deviceName + " with ID " + deviceID + " had different bandwidth parameters than other devices on this circuit. Will instead use the bandwidth parameters defined by the first device added to its circuit.", stacklevel=2) # If this row specifies an SQM override, but the circuit already has a different one, warn and keep the first. if sqm_override_token != '': if 'sqm' in circuit: @@ -764,6 +760,7 @@ def refreshShapers(): # Starting print("refreshShapers starting at " + datetime.now().strftime("%d/%m/%Y %H:%M:%S")) + observe_mode = observe_mode_enabled() # Create a single batch of xdp update commands to execute together ipMapBatch = BatchedCommands() requiredIpMappings = 0 @@ -771,9 +768,8 @@ def refreshShapers(): # Warn user if enableActualShellCommands is False, because that would mean no actual commands are executing if enable_actual_shell_commands() == False: warnings.warn("enableActualShellCommands is set to False. None of the commands below will actually be executed. Simulated run.", stacklevel=2) - # Warn user if monitorOnlyMode is True, because that would mean no actual shaping is happening - if monitor_mode_only() == True: - warnings.warn("monitorOnlyMode is set to True. Shaping will not occur.", stacklevel=2) + if observe_mode: + warnings.warn("queue_mode is set to observe. LibreQoS will keep root MQ but will not apply the shaping tree.", stacklevel=2) # Check if first run since boot @@ -937,27 +933,12 @@ def refreshShapers(): queuesAvailable = math.floor(queuesAvailable / 2) stickOffset = queuesAvailable - # If in monitorOnlyMode, override network.json bandwidth rates to where no shaping will actually occur - if monitor_mode_only() == True: - def overrideNetworkBandwidths(data): - for elem in data: - if 'children' in data[elem]: - overrideNetworkBandwidths(data[elem]['children']) - data[elem]['downloadBandwidthMbpsMin'] = 100000 - data[elem]['uploadBandwidthMbpsMin'] = 100000 - overrideNetworkBandwidths(network) - # Generate Parent Nodes. Spread ShapedDevices.csv which lack defined ParentNode across these (balance across CPUs) print("Generating parent nodes") generatedPNs = [] numberOfGeneratedPNs = queuesAvailable - # If in monitorOnlyMode, override bandwidth rates to where no shaping will actually occur - if monitor_mode_only() == True: - chosenDownloadMbps = 10000 - chosenUploadMbps = 10000 - else: - chosenDownloadMbps = generated_pn_download_mbps() - chosenUploadMbps = generated_pn_upload_mbps() + chosenDownloadMbps = generated_pn_download_mbps() + chosenUploadMbps = generated_pn_upload_mbps() for x in range(numberOfGeneratedPNs): genPNname = "Generated_PN_" + str(x+1) network[genPNname] = { @@ -1039,7 +1020,7 @@ def refreshShapers(): "salt": state.get("salt", "default_salt") if isinstance(state, dict) else "default_salt", "last_change_ts_by_item": last_change_ts, } - if monitor_mode_only() == True: + if observe_mode: params["move_budget_per_run"] = 0 if bin_planner is not None: @@ -1351,7 +1332,7 @@ def refreshShapers(): last_change_ts = {iid: last_change_ts.get(iid, 0.0) for iid in item_ids} move_budget = max(1, min(32, int(0.01 * max(1, len(items))))) - if monitor_mode_only() == True: + if observe_mode: move_budget = 0 planner_mode = "stable_greedy" if insight_enabled else "round_robin" @@ -1568,16 +1549,10 @@ def refreshShapers(): current_up_parent_classid = hex(up_major) + ':' data[node]['parentClassID'] = current_parent_classid data[node]['up_parentClassID'] = current_up_parent_classid - if monitor_mode_only() == True: - data[node]['downloadBandwidthMbps'] = 100000 - data[node]['uploadBandwidthMbps'] = 100000 - data[node]['downloadBandwidthMbpsMin'] = 100000 - data[node]['uploadBandwidthMbpsMin'] = 100000 - else: - data[node]['downloadBandwidthMbps'] = min(data[node]['downloadBandwidthMbps'], parentMaxDL) - data[node]['uploadBandwidthMbps'] = min(data[node]['uploadBandwidthMbps'], parentMaxUL) - data[node]['downloadBandwidthMbpsMin'] = min(data[node]['downloadBandwidthMbpsMin'], data[node]['downloadBandwidthMbps'], parentMinDL) - data[node]['uploadBandwidthMbpsMin'] = min(data[node]['uploadBandwidthMbpsMin'], data[node]['uploadBandwidthMbps'], parentMinUL) + data[node]['downloadBandwidthMbps'] = min(data[node]['downloadBandwidthMbps'], parentMaxDL) + data[node]['uploadBandwidthMbps'] = min(data[node]['uploadBandwidthMbps'], parentMaxUL) + data[node]['downloadBandwidthMbpsMin'] = min(data[node]['downloadBandwidthMbpsMin'], data[node]['downloadBandwidthMbps'], parentMinDL) + data[node]['uploadBandwidthMbpsMin'] = min(data[node]['uploadBandwidthMbpsMin'], data[node]['uploadBandwidthMbps'], parentMinUL) data[node]['classMajor'] = hex(major) data[node]['up_classMajor'] = hex(up_major) data[node]['classMinor'] = hex(assigned_site_minor) @@ -1637,23 +1612,21 @@ def refreshShapers(): if node in circuits_by_parent_node: override_min_down = None override_min_up = None - if monitor_mode_only() == False: - if (circuit_min_down_combined_by_parent_node[node] > node_data['downloadBandwidthMbpsMin']) or (circuit_min_up_combined_by_parent_node[node] > node_data['uploadBandwidthMbpsMin']): - override_min_down = 1 - override_min_up = 1 - logging.info("The combined minimums of circuits in Parent Node [" + node + "] exceeded that of the parent node. Reducing these circuits' minimums to 1 now.", stacklevel=2) - if ((override_min_down * len(circuits_by_parent_node[node])) > node_data['downloadBandwidthMbpsMin']) or ((override_min_up * len(circuits_by_parent_node[node])) > node_data['uploadBandwidthMbpsMin']): - logging.info("Even with this change, minimums will exceed the min rate of the parent node. Using 10 kbps as the minimum for these circuits instead.", stacklevel=2) - nodes_requiring_min_squashing[node] = True + if (circuit_min_down_combined_by_parent_node[node] > node_data['downloadBandwidthMbpsMin']) or (circuit_min_up_combined_by_parent_node[node] > node_data['uploadBandwidthMbpsMin']): + override_min_down = 1 + override_min_up = 1 + logging.info("The combined minimums of circuits in Parent Node [" + node + "] exceeded that of the parent node. Reducing these circuits' minimums to 1 now.", stacklevel=2) + if ((override_min_down * len(circuits_by_parent_node[node])) > node_data['downloadBandwidthMbpsMin']) or ((override_min_up * len(circuits_by_parent_node[node])) > node_data['uploadBandwidthMbpsMin']): + logging.info("Even with this change, minimums will exceed the min rate of the parent node. Using 10 kbps as the minimum for these circuits instead.", stacklevel=2) + nodes_requiring_min_squashing[node] = True sorted_circuits = sorted(circuits_by_parent_node[node], key=lambda c: c.get('circuitName', c.get('circuitID', ''))) for circuit in sorted_circuits: if node != circuit['ParentNode']: continue - if monitor_mode_only() == False: - if circuit['maxDownload'] > node_data['downloadBandwidthMbps']: - logging.info("downloadMax of Circuit ID [" + circuit['circuitID'] + "] exceeded that of its parent node. Reducing to that of its parent node now.", stacklevel=2) - if circuit['maxUpload'] > node_data['uploadBandwidthMbps']: - logging.info("uploadMax of Circuit ID [" + circuit['circuitID'] + "] exceeded that of its parent node. Reducing to that of its parent node now.", stacklevel=2) + if circuit['maxDownload'] > node_data['downloadBandwidthMbps']: + logging.info("downloadMax of Circuit ID [" + circuit['circuitID'] + "] exceeded that of its parent node. Reducing to that of its parent node now.", stacklevel=2) + if circuit['maxUpload'] > node_data['uploadBandwidthMbps']: + logging.info("uploadMax of Circuit ID [" + circuit['circuitID'] + "] exceeded that of its parent node. Reducing to that of its parent node now.", stacklevel=2) planner_key = planner_circuit_identity_key(circuit) planned_identity = circuit_assignment_by_key.get(planner_key) if planned_identity is None: @@ -1907,57 +1880,52 @@ def refreshShapers(): ) command = 'class add dev ' + interface_a() + ' parent ' + data[node]['classid'] + ' classid ' + circuit['classMinor'] + ' htb rate '+ format_rate_for_tc(min_down) + ' ceil '+ format_rate_for_tc(circuit['maxDownload']) + ' prio 3' + quantum(circuit['maxDownload']) + tcComment linuxTCcommands.append(command) - # Only add CAKE / fq_codel qdisc if monitorOnlyMode is Off - if monitor_mode_only() == False: - # SQM Fixup for lower rates (and per-circuit override) - def effective_sqm_str(rate, override, direction): - base = sqm() - # Resolve per-direction token from override string - chosen = None - if override: - try: - ov = str(override).strip().lower() - if '/' in ov: - left, right = ov.split('/', 1) - left = left.strip() - right = right.strip() - chosen = left if direction == 'down' else right - else: - chosen = ov - except Exception: - chosen = None - # If no explicit token for this direction, use default behavior - if not chosen: - try: - thresh = fast_queues_fq_codel() - except Exception: - thresh = 1000.0 - if rate >= thresh: - return 'fq_codel' - return sqmFixupRate(rate, base) - if chosen == 'none': - return '' - if chosen == 'fq_codel': + # SQM Fixup for lower rates (and per-circuit override) + def effective_sqm_str(rate, override, direction): + base = sqm() + # Resolve per-direction token from override string + chosen = None + if override: + try: + ov = str(override).strip().lower() + if '/' in ov: + left, right = ov.split('/', 1) + left = left.strip() + right = right.strip() + chosen = left if direction == 'down' else right + else: + chosen = ov + except Exception: + chosen = None + # If no explicit token for this direction, use default behavior + if not chosen: + try: + thresh = fast_queues_fq_codel() + except Exception: + thresh = 1000.0 + if rate >= thresh: return 'fq_codel' - if chosen == 'cake': - cake_base = base if base.startswith('cake') else 'cake diffserv4' - return sqmFixupRate(rate, cake_base) return sqmFixupRate(rate, base) - sqm_override = circuit['sqm'] if 'sqm' in circuit else None - useSqm = effective_sqm_str(circuit['maxDownload'], sqm_override, 'down') - if useSqm != '': - command = 'qdisc add dev ' + interface_a() + ' parent ' + circuit['classMajor'] + ':' + circuit['classMinor'] + ' ' + useSqm - linuxTCcommands.append(command) + if chosen == 'none': + return '' + if chosen == 'fq_codel': + return 'fq_codel' + if chosen == 'cake': + cake_base = base if base.startswith('cake') else 'cake diffserv4' + return sqmFixupRate(rate, cake_base) + return sqmFixupRate(rate, base) + sqm_override = circuit['sqm'] if 'sqm' in circuit else None + useSqm = effective_sqm_str(circuit['maxDownload'], sqm_override, 'down') + if useSqm != '': + command = 'qdisc add dev ' + interface_a() + ' parent ' + circuit['classMajor'] + ':' + circuit['classMinor'] + ' ' + useSqm + linuxTCcommands.append(command) command = 'class add dev ' + interface_b() + ' parent ' + data[node]['up_classid'] + ' classid ' + circuit['classMinor'] + ' htb rate '+ format_rate_for_tc(min_up) + ' ceil '+ format_rate_for_tc(circuit['maxUpload']) + ' prio 3' + quantum(circuit['maxUpload']) linuxTCcommands.append(command) - # Only add CAKE / fq_codel qdisc if monitorOnlyMode is Off - if monitor_mode_only() == False: - # SQM Fixup for lower rates (and per-circuit override) - sqm_override = circuit['sqm'] if 'sqm' in circuit else None - useSqm = effective_sqm_str(circuit['maxUpload'], sqm_override, 'up') - if useSqm != '': - command = 'qdisc add dev ' + interface_b() + ' parent ' + circuit['up_classMajor'] + ':' + circuit['classMinor'] + ' ' + useSqm - linuxTCcommands.append(command) + sqm_override = circuit['sqm'] if 'sqm' in circuit else None + useSqm = effective_sqm_str(circuit['maxUpload'], sqm_override, 'up') + if useSqm != '': + command = 'qdisc add dev ' + interface_b() + ' parent ' + circuit['up_classMajor'] + ':' + circuit['classMinor'] + ' ' + useSqm + linuxTCcommands.append(command) for device in circuit['devices']: if device['ipv4s']: for ipv4 in device['ipv4s']: @@ -2058,7 +2026,7 @@ def refreshShapers(): "memory_total_bytes": qdiscBudgetEstimate.get("memory_total_bytes"), "memory_available_bytes": qdiscBudgetEstimate.get("memory_available_bytes"), "on_a_stick": on_a_stick(), - "monitor_only": monitor_mode_only(), + "queue_mode": queue_mode(), "shaped_devices_file": shapedDevicesFile, "network_json_file": networkJSONfile, }, @@ -2104,6 +2072,8 @@ def refreshShapers(): # Execute actual Linux TC commands tcStartTime = datetime.now() # print("Executing linux TC class/qdisc commands") + if observe_mode: + linuxTCcommands = [] with open('linux_tc.txt', 'w') as f: for command in linuxTCcommands: logging.info(command) diff --git a/src/lqos.example b/src/lqos.example index 1e5b486a..533e4f69 100644 --- a/src/lqos.example +++ b/src/lqos.example @@ -35,7 +35,7 @@ to_network = "eth1" # Per-circuit overrides in ShapedDevices.csv may specify directional tokens # as "down_sqm/up_sqm" (see ShapedDevices.example.csv and INTEGRATION_HOWTO.md). default_sqm = "cake diffserv4" -monitor_only = false +queue_mode = "shape" uplink_bandwidth_mbps = 100000 downlink_bandwidth_mbps = 100000 generated_pn_download_mbps = 100000 diff --git a/src/rust/lqos_bakery/src/commands.rs b/src/rust/lqos_bakery/src/commands.rs index 4146eb70..78dff0e8 100644 --- a/src/rust/lqos_bakery/src/commands.rs +++ b/src/rust/lqos_bakery/src/commands.rs @@ -6,7 +6,7 @@ use crate::queue_math::{ use allocative::Allocative; use lqos_bus::TcHandle; use lqos_config::LazyQueueMode; -use std::collections::HashSet; +use std::collections::{BTreeSet, HashSet}; use std::sync::Arc; use std::sync::mpsc::Sender as ReplySender; use tracing::{debug, info}; @@ -339,30 +339,71 @@ impl BakeryCommands { stick_offset: usize, ) -> Option>> { let mut result = Vec::new(); - info!("Clearing prior root qdiscs before MQ setup"); - if config.on_a_stick_mode() { - result.push(vec![ - "qdisc".to_string(), - "del".to_string(), - "dev".to_string(), - config.isp_interface(), - "root".to_string(), - ]); - } else { - result.push(vec![ - "qdisc".to_string(), - "del".to_string(), - "dev".to_string(), - config.isp_interface(), - "root".to_string(), - ]); - result.push(vec![ - "qdisc".to_string(), - "del".to_string(), - "dev".to_string(), - config.internet_interface(), - "root".to_string(), - ]); + let observe_only = config.queues.queue_mode.is_observe(); + let mq_already_created = MQ_CREATED.load(std::sync::atomic::Ordering::Relaxed); + if !observe_only { + info!("Clearing prior root qdiscs before MQ setup"); + if config.on_a_stick_mode() { + result.push(vec![ + "qdisc".to_string(), + "del".to_string(), + "dev".to_string(), + config.isp_interface(), + "root".to_string(), + ]); + } else { + result.push(vec![ + "qdisc".to_string(), + "del".to_string(), + "dev".to_string(), + config.isp_interface(), + "root".to_string(), + ]); + result.push(vec![ + "qdisc".to_string(), + "del".to_string(), + "dev".to_string(), + config.internet_interface(), + "root".to_string(), + ]); + } + } + + if observe_only { + if mq_already_created { + let mut shared_slots = BTreeSet::new(); + for queue in 0..queues_available { + shared_slots.insert(queue + 1); + } + if config.on_a_stick_mode() { + for queue in 0..queues_available { + shared_slots.insert(queue + stick_offset + 1); + } + append_mq_child_prune_commands( + &mut result, + config.isp_interface(), + shared_slots, + ); + } else { + append_mq_child_prune_commands( + &mut result, + config.isp_interface(), + shared_slots, + ); + append_mq_child_prune_commands( + &mut result, + config.internet_interface(), + (0..queues_available).map(|queue| queue + stick_offset + 1), + ); + } + } else { + result.push(root_mq_replace_command(config.isp_interface())); + if !config.on_a_stick_mode() { + result.push(root_mq_replace_command(config.internet_interface())); + } + } + MQ_CREATED.store(true, std::sync::atomic::Ordering::Relaxed); + return Some(result); } info!( @@ -377,16 +418,7 @@ impl BakeryCommands { )); // ISP-facing interface (interface_a in Python) - result.push(vec![ - "qdisc".to_string(), - "replace".to_string(), - "dev".to_string(), - config.isp_interface(), - "root".to_string(), - "handle".to_string(), - "7FFF:".to_string(), - "mq".to_string(), - ]); + result.push(root_mq_replace_command(config.isp_interface())); /* for queue in range(queuesAvailable): @@ -630,6 +662,10 @@ impl BakeryCommands { config: &Arc, params: AddSiteParams, ) -> Option>> { + if config.queues.queue_mode.is_observe() { + return None; + } + let mut result = Vec::new(); // Derive major IDs from parent handles so classids are fully qualified // and consistent with queuingStructure.json (classMajor/classMinor). @@ -700,6 +736,10 @@ impl BakeryCommands { config: &Arc, params: AddCircuitParams, ) -> Option>> { + if config.queues.queue_mode.is_observe() { + return None; + } + if let Some(ref s) = params.sqm_override && s.eq_ignore_ascii_case("fq_codel") { @@ -809,7 +849,7 @@ impl BakeryCommands { ), ]); } - if !config.queues.monitor_only + if !config.queues.queue_mode.is_observe() && do_sqm && !matches!(down_override_opt.as_deref(), Some(s) if s.eq_ignore_ascii_case("none")) { @@ -860,7 +900,7 @@ impl BakeryCommands { ]); } - if !config.queues.monitor_only + if !config.queues.queue_mode.is_observe() && do_sqm && !config.on_a_stick_mode() && !matches!(up_override_opt.as_deref(), Some(s) if s.eq_ignore_ascii_case("none")) @@ -1035,9 +1075,43 @@ impl BakeryCommands { } } +fn root_mq_replace_command(interface_name: String) -> Vec { + vec![ + "qdisc".to_string(), + "replace".to_string(), + "dev".to_string(), + interface_name, + "root".to_string(), + "handle".to_string(), + "7FFF:".to_string(), + "mq".to_string(), + ] +} + +fn append_mq_child_prune_commands( + result: &mut Vec>, + interface_name: String, + queue_slots: I, +) where + I: IntoIterator, +{ + for queue_slot in queue_slots { + result.push(vec![ + "qdisc".to_string(), + "del".to_string(), + "dev".to_string(), + interface_name.clone(), + "parent".to_string(), + format!("7FFF:0x{:x}", queue_slot), + ]); + } +} + #[cfg(test)] mod tests { use super::{BakeryCommands, ExecutionMode}; + use crate::MQ_CREATED; + use crate::test_state_lock; use lqos_config::{Config, SingleInterfaceConfig}; use std::sync::Arc; @@ -1062,6 +1136,16 @@ mod tests { && cmd[7] == "mq" } + fn is_mq_child_prune(cmd: &[String], interface: &str, band: usize) -> bool { + cmd.len() == 6 + && cmd[0] == "qdisc" + && cmd[1] == "del" + && cmd[2] == "dev" + && cmd[3] == interface + && cmd[4] == "parent" + && cmd[5] == format!("7FFF:0x{:x}", band) + } + #[test] fn mq_setup_bridge_mode_emits_root_delete_before_replace() { let config = Arc::new(Config::default()); @@ -1119,4 +1203,155 @@ mod tests { "expected a single root replace on the shared interface" ); } + + #[test] + fn mq_setup_observe_mode_bootstraps_root_mq_when_runtime_state_is_empty() { + let _guard = test_state_lock().lock().expect("lock"); + let mut cfg = Config::default(); + cfg.queues.set_queue_mode(lqos_config::QueueMode::Observe); + let config = Arc::new(cfg); + MQ_CREATED.store(false, std::sync::atomic::Ordering::Relaxed); + + let commands = BakeryCommands::MqSetup { + queues_available: 1, + stick_offset: 0, + } + .to_commands(&config, ExecutionMode::Builder) + .expect("mq setup should emit commands in observe mode"); + + assert!( + commands + .iter() + .all(|cmd| !is_root_delete(cmd, &config.isp_interface())) + ); + assert!( + commands + .iter() + .all(|cmd| !is_root_delete(cmd, &config.internet_interface())) + ); + assert!( + commands + .iter() + .any(|cmd| is_root_replace_mq(cmd, &config.isp_interface())) + ); + assert!( + commands + .iter() + .any(|cmd| is_root_replace_mq(cmd, &config.internet_interface())) + ); + assert_eq!( + commands.len(), + 2, + "observe mode should bootstrap root mq when runtime state is empty" + ); + MQ_CREATED.store(false, std::sync::atomic::Ordering::Relaxed); + } + + #[test] + fn mq_setup_observe_mode_prunes_only_child_qdiscs_when_mq_exists() { + let _guard = test_state_lock().lock().expect("lock"); + let mut cfg = Config::default(); + cfg.queues.set_queue_mode(lqos_config::QueueMode::Observe); + let config = Arc::new(cfg); + MQ_CREATED.store(true, std::sync::atomic::Ordering::Relaxed); + + let commands = BakeryCommands::MqSetup { + queues_available: 2, + stick_offset: 0, + } + .to_commands(&config, ExecutionMode::Builder) + .expect("mq setup should emit commands in observe mode"); + + assert!( + commands + .iter() + .all(|cmd| !is_root_delete(cmd, &config.isp_interface())) + ); + assert!( + commands + .iter() + .all(|cmd| !is_root_delete(cmd, &config.internet_interface())) + ); + assert!( + commands + .iter() + .all(|cmd| !is_root_replace_mq(cmd, &config.isp_interface())) + ); + assert!( + commands + .iter() + .all(|cmd| !is_root_replace_mq(cmd, &config.internet_interface())) + ); + assert!( + commands + .iter() + .any(|cmd| is_mq_child_prune(cmd, &config.isp_interface(), 1)) + ); + assert!( + commands + .iter() + .any(|cmd| is_mq_child_prune(cmd, &config.isp_interface(), 2)) + ); + assert!( + commands + .iter() + .any(|cmd| is_mq_child_prune(cmd, &config.internet_interface(), 1)) + ); + assert!( + commands + .iter() + .any(|cmd| is_mq_child_prune(cmd, &config.internet_interface(), 2)) + ); + assert_eq!( + commands.len(), + 4, + "observe mode should prune only child qdiscs beneath the retained root mq" + ); + MQ_CREATED.store(false, std::sync::atomic::Ordering::Relaxed); + } + + #[test] + fn mq_setup_observe_mode_prunes_both_band_ranges_on_a_stick() { + let _guard = test_state_lock().lock().expect("lock"); + let mut cfg = Config { + bridge: None, + single_interface: Some(SingleInterfaceConfig::default()), + ..Config::default() + }; + cfg.queues.set_queue_mode(lqos_config::QueueMode::Observe); + let config = Arc::new(cfg); + MQ_CREATED.store(true, std::sync::atomic::Ordering::Relaxed); + + let commands = BakeryCommands::MqSetup { + queues_available: 2, + stick_offset: 2, + } + .to_commands(&config, ExecutionMode::Builder) + .expect("mq setup should emit commands in observe on-a-stick mode"); + + assert!( + commands + .iter() + .all(|cmd| !is_root_delete(cmd, &config.isp_interface())) + ); + assert!( + commands + .iter() + .all(|cmd| !is_root_replace_mq(cmd, &config.isp_interface())) + ); + for band in [1usize, 2, 3, 4] { + assert!( + commands + .iter() + .any(|cmd| is_mq_child_prune(cmd, &config.isp_interface(), band)), + "expected observe mode to prune retained on-a-stick band {band}" + ); + } + assert_eq!( + commands.len(), + 4, + "observe mode should prune both download and upload mq child bands on-a-stick" + ); + MQ_CREATED.store(false, std::sync::atomic::Ordering::Relaxed); + } } diff --git a/src/rust/lqos_bakery/src/lib.rs b/src/rust/lqos_bakery/src/lib.rs index 54dacd04..d089f89a 100644 --- a/src/rust/lqos_bakery/src/lib.rs +++ b/src/rust/lqos_bakery/src/lib.rs @@ -696,6 +696,11 @@ fn circuits_with_pending_migration_targets( pub static ACTIVE_CIRCUITS: AtomicUsize = AtomicUsize::new(0); /// True while Bakery is applying a full reload batch to `tc`. static FULL_RELOAD_IN_PROGRESS: AtomicBool = AtomicBool::new(false); +#[cfg(test)] +pub(crate) fn test_state_lock() -> &'static std::sync::Mutex<()> { + static LOCK: OnceLock> = OnceLock::new(); + LOCK.get_or_init(|| std::sync::Mutex::new(())) +} /// Hard kernel limit for auto-allocated qdisc handles on a single network interface. pub const HARD_QDISC_HANDLE_LIMIT_PER_INTERFACE: usize = 65_534; /// Conservative operational limit used to fail a full reload before qdisc handle exhaustion. @@ -1122,6 +1127,7 @@ static BAKERY_TELEMETRY: OnceLock> = OnceLock::new( /// Message Queue sender for the bakery pub static BAKERY_SENDER: OnceLock> = OnceLock::new(); static MQ_CREATED: AtomicBool = AtomicBool::new(false); +static SHAPING_TREE_ACTIVE: AtomicBool = AtomicBool::new(false); /// Indicates that at least one command batch has been processed and applied. /// Used to avoid racing live activation against initial class creation. static FIRST_COMMIT_APPLIED: AtomicBool = AtomicBool::new(false); @@ -1668,6 +1674,10 @@ pub fn estimate_full_reload_auto_qdisc_budget( } } +fn desired_shaping_tree_active(config: &Arc) -> bool { + !config.queues.queue_mode.is_observe() +} + fn current_mq_layout( batch: &[Arc], config: &Arc, @@ -1711,7 +1721,7 @@ fn with_assigned_qdisc_handles_reserved( return Arc::clone(command); }; - if config.queues.monitor_only { + if config.queues.queue_mode.is_observe() { return Arc::clone(command); } @@ -1811,7 +1821,7 @@ fn effective_directional_sqm_kinds( return (None, None); }; - if config.queues.monitor_only { + if config.queues.queue_mode.is_observe() { return (None, None); } @@ -1842,7 +1852,7 @@ fn effective_directional_qdisc_parents( return (None, None); }; - if config.queues.monitor_only { + if config.queues.queue_mode.is_observe() { return (None, None); } @@ -3165,11 +3175,12 @@ fn handle_commit_batch( runtime_node_operations, summary, ); - MQ_CREATED.store(true, std::sync::atomic::Ordering::Relaxed); return; } let has_mq_been_setup = MQ_CREATED.load(std::sync::atomic::Ordering::Relaxed); + let shaping_tree_active = SHAPING_TREE_ACTIVE.load(std::sync::atomic::Ordering::Relaxed); + let desired_tree_active = desired_shaping_tree_active(&config); if !has_mq_been_setup { push_bakery_event( "baseline_rebuild_required", @@ -3214,7 +3225,52 @@ fn handle_commit_batch( runtime_node_operations, summary, ); - MQ_CREATED.store(true, std::sync::atomic::Ordering::Relaxed); + return; + } + + if shaping_tree_active != desired_tree_active { + let (new_batch, mapped_limit_stats) = filter_batch_by_mapped_circuit_limit( + raw_batch.clone(), + &baseline_circuits, + effective_limit, + ); + log_mapped_limit_decision("queue-mode rebuild", mapped_limit, mapped_limit_stats); + if mapped_limit_stats.dropped_mapped > 0 { + warn!( + "Bakery mapped circuit cap enforced (queue-mode rebuild): requested={}, allowed={}, dropped={}, limit={} (licensed={}, max_circuits={:?})", + mapped_limit_stats.requested_mapped, + mapped_limit_stats.allowed_mapped, + mapped_limit_stats.dropped_mapped, + limit_label, + mapped_limit.licensed, + mapped_limit.max_circuits + ); + maybe_emit_mapped_circuit_limit_urgent(&mapped_limit_stats); + } + let summary = format!( + "Bakery full reload triggered by queue mode transition to {}.", + if desired_tree_active { + "shape" + } else { + "observe" + } + ); + announce_full_reload(&summary); + full_reload( + batch, + sites, + circuits, + live_circuits, + mq_layout, + qdisc_handles, + &config, + new_batch, + resolved_mq_layout, + stormguard_overrides, + virtualized_sites, + runtime_node_operations, + summary, + ); return; } @@ -3256,7 +3312,6 @@ fn handle_commit_batch( runtime_node_operations, summary.clone(), ); - MQ_CREATED.store(true, std::sync::atomic::Ordering::Relaxed); return; } @@ -3326,7 +3381,6 @@ fn handle_commit_batch( runtime_node_operations, summary, ); - MQ_CREATED.store(true, std::sync::atomic::Ordering::Relaxed); return; } @@ -3640,7 +3694,6 @@ fn handle_commit_batch( runtime_node_operations, summary, ); - MQ_CREATED.store(true, std::sync::atomic::Ordering::Relaxed); return; } @@ -6222,28 +6275,26 @@ fn build_final_qdisc_handle_rotation_invariant_error_with_live_reservations( return Some(summary); } - if let Some(live_down_reserved) = live_down_reserved_handles { - if let Some(down_handle) = *down_qdisc_handle - && live_down_reserved.contains(&down_handle) - && Some(down_handle) != mig.old_down_qdisc_handle - { - return Some(format!( - "build-final command used downlink qdisc handle {:?}, but that handle is already live on the interface under another parent", - down_handle - )); - } + if let Some(live_down_reserved) = live_down_reserved_handles + && let Some(down_handle) = *down_qdisc_handle + && live_down_reserved.contains(&down_handle) + && Some(down_handle) != mig.old_down_qdisc_handle + { + return Some(format!( + "build-final command used downlink qdisc handle {:?}, but that handle is already live on the interface under another parent", + down_handle + )); } - if let Some(live_up_reserved) = live_up_reserved_handles { - if let Some(up_handle) = *up_qdisc_handle - && live_up_reserved.contains(&up_handle) - && Some(up_handle) != mig.old_up_qdisc_handle - { - return Some(format!( - "build-final command used uplink qdisc handle {:?}, but that handle is already live on the interface under another parent", - up_handle - )); - } + if let Some(live_up_reserved) = live_up_reserved_handles + && let Some(up_handle) = *up_qdisc_handle + && live_up_reserved.contains(&up_handle) + && Some(up_handle) != mig.old_up_qdisc_handle + { + return Some(format!( + "build-final command used uplink qdisc handle {:?}, but that handle is already live on the interface under another parent", + up_handle + )); } None @@ -8337,6 +8388,8 @@ fn full_reload( let previous_circuits = circuits.clone(); let previous_live_circuits = live_circuits.clone(); let previous_mq_layout = mq_layout.clone(); + let previous_mq_created = MQ_CREATED.load(Ordering::Relaxed); + let previous_shaping_tree_active = SHAPING_TREE_ACTIVE.load(Ordering::Relaxed); let live_reserved_handles = match snapshot_live_qdisc_handle_majors(config) { Ok(handles) => handles, @@ -8383,6 +8436,8 @@ fn full_reload( live_circuits.clear(); *qdisc_handles = working_qdisc_handles; qdisc_handles.save(config); + MQ_CREATED.store(true, Ordering::Relaxed); + SHAPING_TREE_ACTIVE.store(desired_shaping_tree_active(config), Ordering::Relaxed); if resolved_mq_layout.is_some() { *mq_layout = resolved_mq_layout; } @@ -8399,6 +8454,8 @@ fn full_reload( *circuits = previous_circuits; *live_circuits = previous_live_circuits; *mq_layout = previous_mq_layout; + MQ_CREATED.store(previous_mq_created, Ordering::Relaxed); + SHAPING_TREE_ACTIVE.store(previous_shaping_tree_active, Ordering::Relaxed); } if result.ok { refresh_live_capacity_snapshot(config, true); @@ -8533,17 +8590,16 @@ fn apply_stormguard_overrides( mod tests { use super::*; use lqos_config::Config; - use std::sync::{Mutex, OnceLock}; use std::time::{SystemTime, UNIX_EPOCH}; - fn bakery_test_lock() -> &'static Mutex<()> { - static LOCK: OnceLock> = OnceLock::new(); - LOCK.get_or_init(|| Mutex::new(())) + fn bakery_test_lock() -> &'static std::sync::Mutex<()> { + crate::test_state_lock() } fn reset_bakery_test_state() { *telemetry_state().write() = BakeryTelemetryState::default(); MQ_CREATED.store(false, Ordering::Relaxed); + SHAPING_TREE_ACTIVE.store(false, Ordering::Relaxed); FIRST_COMMIT_APPLIED.store(false, Ordering::Relaxed); FULL_RELOAD_IN_PROGRESS.store(false, Ordering::Relaxed); } @@ -10453,9 +10509,11 @@ mod tests { } #[test] - fn qdisc_budget_estimate_skips_circuit_leaf_qdiscs_in_monitor_only_mode() { + fn qdisc_budget_estimate_counts_only_root_mq_in_observe_mode() { + let _guard = bakery_test_lock().lock().expect("lock"); + reset_bakery_test_state(); let mut cfg = Config::default(); - cfg.queues.monitor_only = true; + cfg.queues.set_queue_mode(lqos_config::QueueMode::Observe); let config = Arc::new(cfg); let queue = vec![ BakeryCommands::MqSetup { @@ -10481,8 +10539,22 @@ mod tests { ]; let estimate = estimate_full_reload_auto_qdisc_budget(&config, &queue); - assert_eq!(estimate.interfaces.get("eth1"), Some(&4)); - assert_eq!(estimate.interfaces.get("eth0"), Some(&4)); + assert_eq!(estimate.interfaces.get("eth1"), Some(&1)); + assert_eq!(estimate.interfaces.get("eth0"), Some(&1)); + assert_eq!( + estimate + .interface_details + .get("eth0") + .map(|d| d.infra_qdiscs), + Some(1) + ); + assert_eq!( + estimate + .interface_details + .get("eth1") + .map(|d| d.infra_qdiscs), + Some(1) + ); assert_eq!( estimate .interface_details diff --git a/src/rust/lqos_config/src/etc/migration.rs b/src/rust/lqos_config/src/etc/migration.rs index fa272d54..4e04c636 100644 --- a/src/rust/lqos_config/src/etc/migration.rs +++ b/src/rust/lqos_config/src/etc/migration.rs @@ -202,7 +202,13 @@ fn migrate_queues( new_config: &mut Config, ) -> Result<(), MigrationError> { new_config.queues.default_sqm = python_config.sqm.clone(); - new_config.queues.monitor_only = python_config.monitor_only_mode; + new_config + .queues + .set_queue_mode(if python_config.monitor_only_mode { + super::QueueMode::Observe + } else { + super::QueueMode::Shape + }); new_config.queues.uplink_bandwidth_mbps = python_config.upstream_bandwidth_capacity_upload_mbps as u64; new_config.queues.downlink_bandwidth_mbps = diff --git a/src/rust/lqos_config/src/etc/mod.rs b/src/rust/lqos_config/src/etc/mod.rs index 30cdc635..244a3ef6 100644 --- a/src/rust/lqos_config/src/etc/mod.rs +++ b/src/rust/lqos_config/src/etc/mod.rs @@ -19,7 +19,7 @@ mod python_migration; pub mod test_data; mod v15; pub use v15::{ - BridgeConfig, LazyQueueMode, RttThresholds, SingleInterfaceConfig, StormguardConfig, + BridgeConfig, LazyQueueMode, QueueMode, RttThresholds, SingleInterfaceConfig, StormguardConfig, StormguardStrategy, TreeguardCircuitsConfig, TreeguardConfig, TreeguardCpuConfig, TreeguardCpuMode, TreeguardLinksConfig, TreeguardQooConfig, Tunables, }; diff --git a/src/rust/lqos_config/src/etc/v15/example.toml b/src/rust/lqos_config/src/etc/v15/example.toml index a3fc61b1..f697a2d8 100644 --- a/src/rust/lqos_config/src/etc/v15/example.toml +++ b/src/rust/lqos_config/src/etc/v15/example.toml @@ -32,7 +32,7 @@ to_network = "eth1" [queues] default_sqm = "cake diffserv4" -monitor_only = false +queue_mode = "shape" uplink_bandwidth_mbps = 1000 downlink_bandwidth_mbps = 1000 generated_pn_download_mbps = 1000 diff --git a/src/rust/lqos_config/src/etc/v15/mod.rs b/src/rust/lqos_config/src/etc/v15/mod.rs index 316d7f3d..68b9b3c5 100644 --- a/src/rust/lqos_config/src/etc/v15/mod.rs +++ b/src/rust/lqos_config/src/etc/v15/mod.rs @@ -23,7 +23,7 @@ mod wispgate; pub use bridge::*; pub use long_term_stats::LongTermStats; -pub use queues::LazyQueueMode; +pub use queues::{LazyQueueMode, QueueMode}; pub use stormguard::{StormguardConfig, StormguardStrategy}; pub use treeguard::{ TreeguardCircuitsConfig, TreeguardConfig, TreeguardCpuConfig, TreeguardCpuMode, diff --git a/src/rust/lqos_config/src/etc/v15/queues.rs b/src/rust/lqos_config/src/etc/v15/queues.rs index 9acaac8a..69512345 100644 --- a/src/rust/lqos_config/src/etc/v15/queues.rs +++ b/src/rust/lqos_config/src/etc/v15/queues.rs @@ -1,15 +1,33 @@ //! Queue Generation definitions (originally from ispConfig.py) use allocative::Allocative; -use serde::{Deserialize, Serialize}; +use serde::{Deserialize, Deserializer, Serialize}; -#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Allocative)] +/// Queue application mode. +#[derive(Clone, Copy, Serialize, Deserialize, Debug, PartialEq, Eq, Default, Allocative)] +#[serde(rename_all = "snake_case")] +pub enum QueueMode { + /// Apply LibreQoS queueing and shaping. + #[default] + Shape, + /// Observe only; do not apply managed TC objects. + Observe, +} + +impl QueueMode { + /// Returns `true` when the queue mode is observe-only. + pub const fn is_observe(self) -> bool { + matches!(self, Self::Observe) + } +} + +#[derive(Clone, Serialize, Debug, PartialEq, Allocative)] pub struct QueueConfig { /// Which SQM to use by default pub default_sqm: String, - /// Should we monitor only, and not shape traffic? - pub monitor_only: bool, + /// Queue application mode. + pub queue_mode: QueueMode, /// Upstream bandwidth total - download pub uplink_bandwidth_mbps: u64, @@ -49,6 +67,26 @@ pub struct QueueConfig { pub fast_queues_fq_codel: Option, } +#[derive(Deserialize)] +#[serde(default)] +struct QueueConfigCompat { + default_sqm: String, + queue_mode: Option, + monitor_only: bool, + uplink_bandwidth_mbps: u64, + downlink_bandwidth_mbps: u64, + generated_pn_download_mbps: u64, + generated_pn_upload_mbps: u64, + dry_run: bool, + sudo: bool, + override_available_queues: Option, + use_binpacking: bool, + lazy_queues: Option, + lazy_expire_seconds: Option, + lazy_threshold_bytes: Option, + fast_queues_fq_codel: Option, +} + /// Lazy queue creation modes #[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Default, Allocative)] pub enum LazyQueueMode { @@ -65,7 +103,7 @@ impl Default for QueueConfig { fn default() -> Self { Self { default_sqm: "cake diffserv4".to_string(), - monitor_only: false, + queue_mode: QueueMode::Shape, uplink_bandwidth_mbps: 1_000, downlink_bandwidth_mbps: 1_000, generated_pn_download_mbps: 1_000, @@ -81,3 +119,109 @@ impl Default for QueueConfig { } } } + +impl QueueConfig { + /// Sets the queue application mode. + pub fn set_queue_mode(&mut self, queue_mode: QueueMode) { + self.queue_mode = queue_mode; + } +} + +impl Default for QueueConfigCompat { + fn default() -> Self { + let defaults = QueueConfig::default(); + Self { + default_sqm: defaults.default_sqm.clone(), + queue_mode: None, + monitor_only: false, + uplink_bandwidth_mbps: defaults.uplink_bandwidth_mbps, + downlink_bandwidth_mbps: defaults.downlink_bandwidth_mbps, + generated_pn_download_mbps: defaults.generated_pn_download_mbps, + generated_pn_upload_mbps: defaults.generated_pn_upload_mbps, + dry_run: defaults.dry_run, + sudo: defaults.sudo, + override_available_queues: defaults.override_available_queues, + use_binpacking: defaults.use_binpacking, + lazy_queues: defaults.lazy_queues.clone(), + lazy_expire_seconds: defaults.lazy_expire_seconds, + lazy_threshold_bytes: defaults.lazy_threshold_bytes, + fast_queues_fq_codel: defaults.fast_queues_fq_codel, + } + } +} + +impl<'de> Deserialize<'de> for QueueConfig { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + let compat = QueueConfigCompat::deserialize(deserializer)?; + let queue_mode = compat.queue_mode.unwrap_or({ + if compat.monitor_only { + QueueMode::Observe + } else { + QueueMode::Shape + } + }); + + let mut cfg = Self { + default_sqm: compat.default_sqm, + queue_mode, + uplink_bandwidth_mbps: compat.uplink_bandwidth_mbps, + downlink_bandwidth_mbps: compat.downlink_bandwidth_mbps, + generated_pn_download_mbps: compat.generated_pn_download_mbps, + generated_pn_upload_mbps: compat.generated_pn_upload_mbps, + dry_run: compat.dry_run, + sudo: compat.sudo, + override_available_queues: compat.override_available_queues, + use_binpacking: compat.use_binpacking, + lazy_queues: compat.lazy_queues, + lazy_expire_seconds: compat.lazy_expire_seconds, + lazy_threshold_bytes: compat.lazy_threshold_bytes, + fast_queues_fq_codel: compat.fast_queues_fq_codel, + }; + cfg.set_queue_mode(queue_mode); + Ok(cfg) + } +} + +#[cfg(test)] +mod tests { + use super::{QueueConfig, QueueMode}; + + #[test] + fn deserialize_legacy_monitor_only_maps_to_observe() { + let parsed: QueueConfig = + toml::from_str("default_sqm = \"cake diffserv4\"\nmonitor_only = true\n") + .expect("legacy monitor_only config should deserialize"); + assert_eq!(parsed.queue_mode, QueueMode::Observe); + } + + #[test] + fn deserialize_without_queue_mode_defaults_to_shape() { + let parsed: QueueConfig = toml::from_str("default_sqm = \"cake diffserv4\"\n") + .expect("queue config without queue_mode should deserialize"); + assert_eq!(parsed.queue_mode, QueueMode::Shape); + } + + #[test] + fn deserialize_prefers_queue_mode_over_legacy_monitor_only() { + let parsed: QueueConfig = toml::from_str( + "default_sqm = \"cake diffserv4\"\nqueue_mode = \"shape\"\nmonitor_only = true\n", + ) + .expect("mixed config should deserialize"); + assert_eq!(parsed.queue_mode, QueueMode::Shape); + } + + #[test] + fn serialize_queue_config_omits_legacy_monitor_only_field() { + let mut config = QueueConfig::default(); + config.set_queue_mode(QueueMode::Observe); + let serialized = toml::to_string(&config).expect("queue config should serialize"); + assert!(serialized.contains("queue_mode = \"observe\"")); + assert!( + !serialized.contains("monitor_only"), + "serialized config should not re-emit deprecated monitor_only" + ); + } +} diff --git a/src/rust/lqos_config/src/lib.rs b/src/rust/lqos_config/src/lib.rs index 558d3bda..10793053 100644 --- a/src/rust/lqos_config/src/lib.rs +++ b/src/rust/lqos_config/src/lib.rs @@ -21,11 +21,11 @@ pub use cpu_topology::{ CpuListParseError, ShapingCpuDetection, ShapingCpuSource, detect_shaping_cpus, }; pub use etc::{ - BridgeConfig, Config, LazyQueueMode, RttThresholds, SingleInterfaceConfig, StormguardConfig, - StormguardStrategy, TreeguardCircuitsConfig, TreeguardConfig, TreeguardCpuConfig, - TreeguardCpuMode, TreeguardLinksConfig, TreeguardQooConfig, Tunables, clear_cached_config, - disable_xdp_bridge, enable_long_term_stats, load_config, treeguard_cpu_mode_migration_notice, - update_config, + BridgeConfig, Config, LazyQueueMode, QueueMode, RttThresholds, SingleInterfaceConfig, + StormguardConfig, StormguardStrategy, TreeguardCircuitsConfig, TreeguardConfig, + TreeguardCpuConfig, TreeguardCpuMode, TreeguardLinksConfig, TreeguardQooConfig, Tunables, + clear_cached_config, disable_xdp_bridge, enable_long_term_stats, load_config, + treeguard_cpu_mode_migration_notice, update_config, }; pub use network_json::{NetworkJson, NetworkJsonNode, NetworkJsonTransport}; pub use planner::{ diff --git a/src/rust/lqos_python/src/lib.rs b/src/rust/lqos_python/src/lib.rs index 638bf770..59af3e81 100644 --- a/src/rust/lqos_python/src/lib.rs +++ b/src/rust/lqos_python/src/lib.rs @@ -876,7 +876,7 @@ fn liblqos_python(m: &Bound<'_, PyModule>) -> PyResult<()> { m.add_function(wrap_pyfunction!(interface_b, m)?)?; m.add_function(wrap_pyfunction!(enable_actual_shell_commands, m)?)?; m.add_function(wrap_pyfunction!(use_bin_packing_to_balance_cpu, m)?)?; - m.add_function(wrap_pyfunction!(monitor_mode_only, m)?)?; + m.add_function(wrap_pyfunction!(queue_mode, m)?)?; m.add_function(wrap_pyfunction!(shaping_cpu_count, m)?)?; m.add_function(wrap_pyfunction!(efficiency_core_ids, m)?)?; m.add_function(wrap_pyfunction!(run_shell_commands_as_sudo, m)?)?; @@ -1931,9 +1931,12 @@ fn use_bin_packing_to_balance_cpu() -> PyResult { } #[pyfunction] -fn monitor_mode_only() -> PyResult { +fn queue_mode() -> PyResult { let config = lqos_config::load_config().unwrap(); - Ok(config.queues.monitor_only) + Ok(match config.queues.queue_mode { + lqos_config::QueueMode::Shape => "shape".to_string(), + lqos_config::QueueMode::Observe => "observe".to_string(), + }) } /// Returns the number of CPUs that should be used for shaping / binning. diff --git a/src/rust/lqosd/src/node_manager/js_build/src/config_queues.js b/src/rust/lqosd/src/node_manager/js_build/src/config_queues.js index df3080c6..70ebf62a 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/config_queues.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/config_queues.js @@ -51,9 +51,10 @@ function validateConfig() { function updateConfig() { // Update only the queues section + const queueMode = document.getElementById("queueMode").value; window.config.queues = { default_sqm: document.getElementById("defaultSqm").value, - monitor_only: document.getElementById("monitorOnly").checked, + queue_mode: queueMode, uplink_bandwidth_mbps: parseInt(document.getElementById("uplinkBandwidth").value), downlink_bandwidth_mbps: parseInt(document.getElementById("downlinkBandwidth").value), generated_pn_download_mbps: parseInt(document.getElementById("generatedPnDownload").value), @@ -82,9 +83,9 @@ loadConfig(() => { // Select field document.getElementById("defaultSqm").value = queues.default_sqm; + document.getElementById("queueMode").value = queues.queue_mode ?? ((queues.monitor_only ?? false) ? "observe" : "shape"); // Boolean fields - document.getElementById("monitorOnly").checked = queues.monitor_only ?? false; document.getElementById("dryRun").checked = queues.dry_run ?? false; document.getElementById("sudo").checked = queues.sudo ?? false; document.getElementById("useBinpacking").checked = queues.use_binpacking ?? false; diff --git a/src/rust/lqosd/src/node_manager/js_build/src/configuration.js b/src/rust/lqosd/src/node_manager/js_build/src/configuration.js index c724f3e7..53993d5e 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/configuration.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/configuration.js @@ -78,7 +78,7 @@ const bindings = [ // Queues { field: "bindSqm", path: ".queues.default_sqm", data: "select-premade", editable: true }, - { field: "bindMonitorMode", path: ".queues.monitor_only", data: "bool", editable: true }, + { field: "bindQueueMode", path: ".queues.queue_mode", data: "select-premade", editable: true }, { field: "bindUplinkMbps", path: ".queues.uplink_bandwidth_mbps", data: "integer", editable: true }, { field: "bindDownlinkMbps", path: ".queues.downlink_bandwidth_mbps", data: "integer", editable: true }, { field: "bindGeneratedDownlinkMbps", path: ".queues.generated_pn_download_mbps", data: "integer", editable: true }, @@ -477,11 +477,12 @@ function getFinalValue(target) { function updateSavedConfig(changes) { for (let i=0; i { - const myModal = new bootstrap.Modal(document.getElementById('reloadModal'), { focus: true }); - myModal.show(); - $("#reloadLibreResult").html(" Reloading LibreQoS..."); - listenOnce("ReloadResult", (msg) => { - if (!msg) { - $("#reloadLibreResult").text("Failed to reload LibreQoS"); + triggerReloadLibreQoS("Reloading LibreQoS..."); + } +} + +function inferQueueMode(config) { + const queues = config && config.queues ? config.queues : {}; + if (queues.queue_mode === "observe" || queues.queue_mode === "shape") { + return queues.queue_mode; + } + return queues.monitor_only ? "observe" : "shape"; +} + +function renderQueueModeState(mode, busy = false) { + const nav = document.getElementById("observeShapeNav"); + const badge = document.getElementById("queueModeBadge"); + const observeBtn = document.getElementById("btnQueueModeObserve"); + const shapeBtn = document.getElementById("btnQueueModeShape"); + if (!nav || !badge || !observeBtn || !shapeBtn) return; + + badge.className = `badge ${mode === "observe" ? "text-bg-warning" : "text-bg-success"}`; + badge.textContent = mode === "observe" ? "Observe" : "Shape"; + + observeBtn.disabled = busy || mode === "observe"; + shapeBtn.disabled = busy || mode === "shape"; + observeBtn.className = `btn btn-sm ${mode === "observe" ? "btn-warning" : "btn-outline-secondary"}`; + shapeBtn.className = `btn btn-sm ${mode === "shape" ? "btn-success" : "btn-outline-secondary"}`; +} + +function triggerReloadLibreQoS(loadingMessage) { + const myModal = new bootstrap.Modal(document.getElementById('reloadModal'), { focus: true }); + myModal.show(); + $("#reloadLibreResult").html(` ${loadingMessage}`); + listenOnce("ReloadResult", (msg) => { + if (!msg) { + $("#reloadLibreResult").text("Failed to reload LibreQoS"); + return; + } + $("#reloadLibreResult").text(msg.message || ""); + }); + wsClient.send({ ReloadLibreQoS: {} }); +} + +function loadObserveShapeControl() { + const nav = document.getElementById("observeShapeNav"); + if (!nav) return; + + listenOnce("AdminCheck", (msg) => { + if (!msg || !msg.ok) { + nav.classList.add("d-none"); + return; + } + + listenOnce("GetConfig", (cfgMsg) => { + if (!cfgMsg || !cfgMsg.data) { + nav.classList.add("d-none"); return; } - $("#reloadLibreResult").text(msg.message || ""); + cachedQueueModeConfig = cfgMsg.data; + const mode = inferQueueMode(cachedQueueModeConfig); + nav.classList.remove("d-none"); + renderQueueModeState(mode, false); }); - wsClient.send({ ReloadLibreQoS: {} }); + wsClient.send({ GetConfig: {} }); + }); + wsClient.send({ AdminCheck: {} }); +} + +function saveQueueModeAndReload(nextMode) { + if (!cachedQueueModeConfig || !cachedQueueModeConfig.queues) { + alert("Unable to load current configuration"); + return; + } + + const currentMode = inferQueueMode(cachedQueueModeConfig); + if (currentMode === nextMode) { + return; + } + + const confirmed = window.confirm( + nextMode === "observe" + ? "Switch LibreQoS to Observe mode? This will keep root MQ active, remove the shaping tree on reload, and stop active shaping." + : "Switch LibreQoS to Shape mode? This will rebuild the shaping tree on reload and begin active shaping." + ); + if (!confirmed) { + return; } + + renderQueueModeState(currentMode, true); + const updated = JSON.parse(JSON.stringify(cachedQueueModeConfig)); + updated.queues.queue_mode = nextMode; + + let done = false; + const cleanup = () => { + wsClient.off("UpdateConfigResult", onSuccess); + wsClient.off("Error", onError); + }; + const onSuccess = (msg) => { + if (done) return; + done = true; + cleanup(); + if (!msg || !msg.ok) { + renderQueueModeState(currentMode, false); + alert((msg && msg.message) ? msg.message : "Failed to update configuration"); + return; + } + cachedQueueModeConfig = updated; + renderQueueModeState(nextMode, false); + triggerReloadLibreQoS(`Saving queue mode '${nextMode}' and reloading LibreQoS...`); + }; + const onError = (msg) => { + if (done) return; + done = true; + cleanup(); + renderQueueModeState(currentMode, false); + alert((msg && msg.message) ? msg.message : "Failed to update configuration"); + }; + wsClient.on("UpdateConfigResult", onSuccess); + wsClient.on("Error", onError); + wsClient.send({ UpdateConfig: { config: updated } }); +} + +function initObserveShapeToggle() { + $(document).off("click", "#btnQueueModeObserve").on("click", "#btnQueueModeObserve", () => { + saveQueueModeAndReload("observe"); + }); + $(document).off("click", "#btnQueueModeShape").on("click", "#btnQueueModeShape", () => { + saveQueueModeAndReload("shape"); + }); + loadObserveShapeControl(); } function setupDynamicUrls() { @@ -538,6 +656,7 @@ initColorBlind(); getDeviceCounts(); setupSearch(); setupReload(); +initObserveShapeToggle(); setupDynamicUrls(); window.lqosInitUrgentIssues = initUrgentIssues; initSchedulerTooltips(); diff --git a/src/rust/lqosd/src/node_manager/static2/config_queues.html b/src/rust/lqosd/src/node_manager/static2/config_queues.html index 6dabc1df..b142ecf9 100644 --- a/src/rust/lqosd/src/node_manager/static2/config_queues.html +++ b/src/rust/lqosd/src/node_manager/static2/config_queues.html @@ -12,10 +12,13 @@
Queue management algorithm to use by default
-
- - -
Monitor traffic without shaping
+
+ + +
Observe keeps root MQ active for the transparent bridge, but does not apply the LibreQoS shaping tree.
diff --git a/src/rust/lqosd/src/node_manager/static2/configuration.html b/src/rust/lqosd/src/node_manager/static2/configuration.html index 7481d7f2..1f5f0d77 100644 --- a/src/rust/lqosd/src/node_manager/static2/configuration.html +++ b/src/rust/lqosd/src/node_manager/static2/configuration.html @@ -242,8 +242,15 @@ - - + + + +
+ Observe keeps root MQ active for the transparent bridge, but removes the LibreQoS shaping tree. + diff --git a/src/rust/lqosd/src/node_manager/static2/template.html b/src/rust/lqosd/src/node_manager/static2/template.html index 8b1d2339..3e595a7a 100644 --- a/src/rust/lqosd/src/node_manager/static2/template.html +++ b/src/rust/lqosd/src/node_manager/static2/template.html @@ -168,6 +168,17 @@
+ + -- knotmirror 0.0.1