diff --git a/src/rust/Cargo.lock b/src/rust/Cargo.lock index 2a721c9e..52ce281a 100644 --- a/src/rust/Cargo.lock +++ b/src/rust/Cargo.lock @@ -1320,6 +1320,23 @@ dependencies = [ "tokio", ] +[[package]] +name = "lqos_queue_tracker" +version = "0.1.0" +dependencies = [ + "anyhow", + "criterion", + "lazy_static", + "log", + "lqos_bus", + "lqos_config", + "notify", + "parking_lot 0.11.2", + "serde", + "serde_json", + "tokio", +] + [[package]] name = "lqos_rs" version = "0.1.0" @@ -1343,12 +1360,12 @@ name = "lqosd" version = "0.1.0" dependencies = [ "anyhow", - "criterion", "env_logger", "lazy_static", "log", "lqos_bus", "lqos_config", + "lqos_queue_tracker", "lqos_sys", "nix", "notify", diff --git a/src/rust/lqos_queue_tracker/Cargo.toml b/src/rust/lqos_queue_tracker/Cargo.toml new file mode 100644 index 00000000..03fa1fd7 --- /dev/null +++ b/src/rust/lqos_queue_tracker/Cargo.toml @@ -0,0 +1,23 @@ +[package] +name = "lqos_queue_tracker" +version = "0.1.0" +edition = "2021" + +[dependencies] +anyhow = "1" +serde = "1" +serde_json = "1" +lqos_bus = { path = "../lqos_bus" } +lqos_config = { path = "../lqos_config" } +log = "0" +lazy_static = "1.4" +parking_lot = "0" +notify = { version = "5.0.0", default-features = false, feature=["macos_kqueue"] } # Not using crossbeam because of Tokio +tokio = { version = "1.22", features = [ "full", "parking_lot" ] } + +[dev-dependencies] +criterion = { version = "0.3", features = [ "html_reports"] } + +[[bench]] +name = "json" +harness = false diff --git a/src/rust/lqosd/benches/example_json.txt b/src/rust/lqos_queue_tracker/benches/example_json.txt similarity index 100% rename from src/rust/lqosd/benches/example_json.txt rename to src/rust/lqos_queue_tracker/benches/example_json.txt diff --git a/src/rust/lqosd/benches/json.rs b/src/rust/lqos_queue_tracker/benches/json.rs similarity index 99% rename from src/rust/lqosd/benches/json.rs rename to src/rust/lqos_queue_tracker/benches/json.rs index 6081487e..e2a07934 100644 --- a/src/rust/lqosd/benches/json.rs +++ b/src/rust/lqos_queue_tracker/benches/json.rs @@ -4,7 +4,7 @@ //! TC queues - so don't select an interface that you need! use criterion::{criterion_group, criterion_main, Criterion, black_box}; -use lqosd::*; +use lqos_queue_tracker::*; use std::process::Command; const EXAMPLE_JSON: &str = include_str!("./example_json.txt"); diff --git a/src/rust/lqosd/benches/test_interface.txt b/src/rust/lqos_queue_tracker/benches/test_interface.txt similarity index 100% rename from src/rust/lqosd/benches/test_interface.txt rename to src/rust/lqos_queue_tracker/benches/test_interface.txt diff --git a/src/rust/lqos_queue_tracker/src/bus.rs b/src/rust/lqos_queue_tracker/src/bus.rs new file mode 100644 index 00000000..d08c1343 --- /dev/null +++ b/src/rust/lqos_queue_tracker/src/bus.rs @@ -0,0 +1,15 @@ +use lqos_bus::BusResponse; +use crate::circuit_to_queue::CIRCUIT_TO_QUEUE; + +pub fn get_raw_circuit_data(circuit_id: &str) -> BusResponse { + let reader = CIRCUIT_TO_QUEUE.read(); + if let Some(circuit) = reader.get(circuit_id) { + if let Ok(json) = serde_json::to_string(circuit) { + BusResponse::RawQueueData(json) + } else { + BusResponse::RawQueueData(String::new()) + } + } else { + BusResponse::RawQueueData(String::new()) + } +} diff --git a/src/rust/lqos_queue_tracker/src/circuit_to_queue.rs b/src/rust/lqos_queue_tracker/src/circuit_to_queue.rs new file mode 100644 index 00000000..e9bd4d4e --- /dev/null +++ b/src/rust/lqos_queue_tracker/src/circuit_to_queue.rs @@ -0,0 +1,9 @@ +use lazy_static::*; +use parking_lot::RwLock; +use std::collections::HashMap; +use crate::queue_store::QueueStore; + +lazy_static! { + pub(crate) static ref CIRCUIT_TO_QUEUE: RwLock> = + RwLock::new(HashMap::new()); +} \ No newline at end of file diff --git a/src/rust/lqos_queue_tracker/src/interval.rs b/src/rust/lqos_queue_tracker/src/interval.rs new file mode 100644 index 00000000..426ca183 --- /dev/null +++ b/src/rust/lqos_queue_tracker/src/interval.rs @@ -0,0 +1,10 @@ +use std::sync::atomic::AtomicU64; +use lazy_static::*; + +lazy_static! { + pub(crate) static ref QUEUE_MONITOR_INTERVAL: AtomicU64 = AtomicU64::new(1000); +} + +pub fn set_queue_refresh_interval(interval_ms: u64) { + QUEUE_MONITOR_INTERVAL.store(interval_ms, std::sync::atomic::Ordering::Relaxed); +} \ No newline at end of file diff --git a/src/rust/lqos_queue_tracker/src/lib.rs b/src/rust/lqos_queue_tracker/src/lib.rs new file mode 100644 index 00000000..1e272169 --- /dev/null +++ b/src/rust/lqos_queue_tracker/src/lib.rs @@ -0,0 +1,17 @@ +mod queue_store; +mod queue_types; +mod queue_diff; +mod circuit_to_queue; +mod queue_structure; +mod tracking; +mod interval; +mod bus; + +/// How many history items do we store? +const NUM_QUEUE_HISTORY: usize = 600; + +pub use queue_structure::spawn_queue_structure_monitor; +pub use tracking::spawn_queue_monitor; +pub use bus::get_raw_circuit_data; +pub use queue_types::deserialize_tc_tree; // Exported for the benchmarker +pub use interval::set_queue_refresh_interval; \ No newline at end of file diff --git a/src/rust/lqosd/src/queue_tracker/queue_reader/queue_diff/mod.rs b/src/rust/lqos_queue_tracker/src/queue_diff.rs similarity index 98% rename from src/rust/lqosd/src/queue_tracker/queue_reader/queue_diff/mod.rs rename to src/rust/lqos_queue_tracker/src/queue_diff.rs index 33c1f7b3..c62fcc33 100644 --- a/src/rust/lqosd/src/queue_tracker/queue_reader/queue_diff/mod.rs +++ b/src/rust/lqos_queue_tracker/src/queue_diff.rs @@ -1,6 +1,6 @@ -use super::QueueType; use anyhow::Result; use serde::Serialize; +use crate::queue_types::QueueType; #[derive(Debug, Clone, Serialize)] pub enum QueueDiff { diff --git a/src/rust/lqos_queue_tracker/src/queue_store.rs b/src/rust/lqos_queue_tracker/src/queue_store.rs new file mode 100644 index 00000000..a5dd5dc8 --- /dev/null +++ b/src/rust/lqos_queue_tracker/src/queue_store.rs @@ -0,0 +1,42 @@ +use serde::Serialize; +use crate::{queue_diff::{QueueDiff, make_queue_diff}, queue_types::QueueType, NUM_QUEUE_HISTORY}; + +#[derive(Debug, Serialize)] +pub struct QueueStore { + history: Vec<(QueueDiff, QueueDiff)>, + history_head: usize, + prev_download: Option, + prev_upload: Option, + current_download: QueueType, + current_upload: QueueType, +} + +impl QueueStore { + pub(crate) fn new(download: QueueType, upload: QueueType) -> Self { + Self { + history: vec![(QueueDiff::None, QueueDiff::None); NUM_QUEUE_HISTORY], + history_head: 0, + prev_upload: None, + prev_download: None, + current_download: download, + current_upload: upload, + } + } + + pub(crate) fn update(&mut self, download: &QueueType, upload: &QueueType) { + self.prev_upload = Some(self.current_upload.clone()); + self.prev_download = Some(self.current_download.clone()); + self.current_download = download.clone(); + self.current_upload = upload.clone(); + let new_diff_up = make_queue_diff(self.prev_upload.as_ref().unwrap(), &self.current_upload); + let new_diff_dn = + make_queue_diff(self.prev_download.as_ref().unwrap(), &self.current_download); + if new_diff_dn.is_ok() && new_diff_up.is_ok() { + self.history[self.history_head] = (new_diff_dn.unwrap(), new_diff_up.unwrap()); + self.history_head += 1; + if self.history_head >= NUM_QUEUE_HISTORY { + self.history_head = 0; + } + } + } +} diff --git a/src/rust/lqos_queue_tracker/src/queue_structure/mod.rs b/src/rust/lqos_queue_tracker/src/queue_structure/mod.rs new file mode 100644 index 00000000..1a19b032 --- /dev/null +++ b/src/rust/lqos_queue_tracker/src/queue_structure/mod.rs @@ -0,0 +1,17 @@ +mod queue_node; +mod queue_network; +mod queing_structure_json_monitor; +use anyhow::Result; +use queue_node::QueueNode; +use queue_network::QueueNetwork; +pub use queing_structure_json_monitor::spawn_queue_structure_monitor; +pub(crate) use queing_structure_json_monitor::QUEUE_STRUCTURE; + +fn read_hex_string(s: &str) -> Result { + Ok(u32::from_str_radix(&s.replace("0x", ""), 16)?) +} + +pub(crate) fn read_queueing_structure() -> Result> { + let network = QueueNetwork::from_json()?; + Ok(network.to_flat()) +} \ No newline at end of file diff --git a/src/rust/lqosd/src/libreqos_tracker/shaped_devices.rs b/src/rust/lqos_queue_tracker/src/queue_structure/queing_structure_json_monitor.rs similarity index 51% rename from src/rust/lqosd/src/libreqos_tracker/shaped_devices.rs rename to src/rust/lqos_queue_tracker/src/queue_structure/queing_structure_json_monitor.rs index 76f9330e..3ac61740 100644 --- a/src/rust/lqosd/src/libreqos_tracker/shaped_devices.rs +++ b/src/rust/lqos_queue_tracker/src/queue_structure/queing_structure_json_monitor.rs @@ -1,19 +1,19 @@ -//! Tracks changes to the ShapedDevices.csv file in LibreQoS. - use lazy_static::*; -use lqos_config::ConfigShapedDevices; use parking_lot::RwLock; use anyhow::Result; use tokio::task::spawn_blocking; +use crate::queue_structure::{queue_node::QueueNode, read_queueing_structure, queue_network::QueueNetwork}; lazy_static! { /// Global storage of the shaped devices csv data. /// Updated by the file system watcher whenever /// the underlying file changes. - pub(crate) static ref SHAPED_DEVICES : RwLock = RwLock::new(ConfigShapedDevices::load().unwrap()); + pub(crate) static ref QUEUE_STRUCTURE : RwLock>> = RwLock::new(read_queueing_structure()); } -pub async fn spawn_shaped_devices_monitor() { +/// Global file watched for `queueStructure.json`. +/// Reloads the queue structure when it is available. +pub async fn spawn_queue_structure_monitor() { spawn_blocking(|| { let _ = watch_for_shaped_devices_changing(); }); @@ -22,17 +22,16 @@ pub async fn spawn_shaped_devices_monitor() { /// Fires up a Linux file system watcher than notifies /// when `ShapedDevices.csv` changes, and triggers a reload. fn watch_for_shaped_devices_changing() -> Result<()> { - use notify::{Watcher, RecursiveMode, Config}; + use notify::{Config, RecursiveMode, Watcher}; let (tx, rx) = std::sync::mpsc::channel(); let mut watcher = notify::RecommendedWatcher::new(tx, Config::default())?; - watcher.watch(&ConfigShapedDevices::path()?, RecursiveMode::NonRecursive)?; + watcher.watch(&QueueNetwork::path()?, RecursiveMode::NonRecursive)?; loop { let _ = rx.recv(); - if let Ok(new_file) = ConfigShapedDevices::load() { - println!("ShapedDevices.csv changed"); - *SHAPED_DEVICES.write() = new_file; - } + let new_file = read_queueing_structure(); + log::info!("queuingStructure.csv changed"); + *QUEUE_STRUCTURE.write() = new_file; } -} \ No newline at end of file +} diff --git a/src/rust/lqos_queue_tracker/src/queue_structure/queue_network.rs b/src/rust/lqos_queue_tracker/src/queue_structure/queue_network.rs new file mode 100644 index 00000000..97c88a5c --- /dev/null +++ b/src/rust/lqos_queue_tracker/src/queue_structure/queue_network.rs @@ -0,0 +1,70 @@ +use std::path::{PathBuf, Path}; +use super::queue_node::QueueNode; +use anyhow::{Result, Error}; +use lqos_config::EtcLqos; +use serde_json::Value; + +pub struct QueueNetwork { + cpu_node: Vec, +} + +impl QueueNetwork { + pub fn path() -> Result { + let cfg = EtcLqos::load()?; + let base_path = Path::new(&cfg.lqos_directory); + Ok(base_path.join("queuingStructure.json")) + } + + fn exists() -> bool { + if let Ok(path) = QueueNetwork::path() { + path.exists() + } else { + false + } + } + + pub(crate) fn from_json() -> Result { + let path = QueueNetwork::path()?; + if !QueueNetwork::exists() { + return Err(Error::msg( + "queueStructure.json does not exist yet. Try running LibreQoS?", + )); + } + let raw_string = std::fs::read_to_string(path)?; + let mut result = Self { + cpu_node: Vec::new(), + }; + let json: Value = serde_json::from_str(&raw_string)?; + if let Value::Object(map) = &json { + if let Some(network) = map.get("Network") { + if let Value::Object(map) = network { + for (key, value) in map.iter() { + result.cpu_node.push(QueueNode::from_json(&key, value)?); + } + } else { + return Err(Error::msg("Unable to parse network object structure")); + } + } else { + return Err(Error::msg("Network entry not found")); + } + } else { + return Err(Error::msg("Unable to parse queueStructure.json")); + } + + Ok(result) + } + + pub fn to_flat(&self) -> Vec { + let mut result = Vec::new(); + for cpu in self.cpu_node.iter() { + result.push(cpu.clone()); + let children = cpu.to_flat(); + result.extend_from_slice(&children); + } + for c in result.iter_mut() { + c.circuits.clear(); + c.devices.clear(); + } + result + } +} diff --git a/src/rust/lqosd/src/libreqos_tracker/queueing_structure/reader.rs b/src/rust/lqos_queue_tracker/src/queue_structure/queue_node.rs similarity index 70% rename from src/rust/lqosd/src/libreqos_tracker/queueing_structure/reader.rs rename to src/rust/lqos_queue_tracker/src/queue_structure/queue_node.rs index 92519aa2..476870fb 100644 --- a/src/rust/lqosd/src/libreqos_tracker/queueing_structure/reader.rs +++ b/src/rust/lqos_queue_tracker/src/queue_structure/queue_node.rs @@ -1,12 +1,7 @@ -use anyhow::{Error, Result}; use lqos_bus::TcHandle; -use lqos_config::EtcLqos; +use anyhow::{Result, Error}; use serde_json::Value; -use std::path::{Path, PathBuf}; - -pub struct QueueNetwork { - cpu_node: Vec, -} +use super::read_hex_string; #[derive(Default, Clone, Debug)] pub struct QueueNode { @@ -34,73 +29,8 @@ pub struct QueueNode { pub mac: Option, } -fn read_hex_string(s: &str) -> Result { - Ok(u32::from_str_radix(&s.replace("0x", ""), 16)?) -} - -impl QueueNetwork { - pub fn path() -> Result { - let cfg = EtcLqos::load()?; - let base_path = Path::new(&cfg.lqos_directory); - Ok(base_path.join("queuingStructure.json")) - } - - fn exists() -> bool { - if let Ok(path) = QueueNetwork::path() { - path.exists() - } else { - false - } - } - - pub(crate) fn from_json() -> Result { - let path = QueueNetwork::path()?; - if !QueueNetwork::exists() { - return Err(Error::msg( - "queueStructure.json does not exist yet. Try running LibreQoS?", - )); - } - let raw_string = std::fs::read_to_string(path)?; - let mut result = Self { - cpu_node: Vec::new(), - }; - let json: Value = serde_json::from_str(&raw_string)?; - if let Value::Object(map) = &json { - if let Some(network) = map.get("Network") { - if let Value::Object(map) = network { - for (key, value) in map.iter() { - result.cpu_node.push(QueueNode::from_json(&key, value)?); - } - } else { - return Err(Error::msg("Unable to parse network object structure")); - } - } else { - return Err(Error::msg("Network entry not found")); - } - } else { - return Err(Error::msg("Unable to parse queueStructure.json")); - } - - Ok(result) - } - - pub fn to_flat(&self) -> Vec { - let mut result = Vec::new(); - for cpu in self.cpu_node.iter() { - result.push(cpu.clone()); - let children = cpu.to_flat(); - result.extend_from_slice(&children); - } - for c in result.iter_mut() { - c.circuits.clear(); - c.devices.clear(); - } - result - } -} - impl QueueNode { - fn from_json(key: &str, value: &Value) -> Result { + pub(crate) fn from_json(key: &str, value: &Value) -> Result { let mut result = Self::default(); if let Value::Object(map) = value { for (key, value) in map.iter() { @@ -182,7 +112,7 @@ impl QueueNode { Ok(result) } - fn to_flat(&self) -> Vec { + pub(crate) fn to_flat(&self) -> Vec { let mut result = Vec::new(); for c in self.circuits.iter() { result.push(c.clone()); diff --git a/src/rust/lqosd/src/queue_tracker/queue_reader/CAKE.md b/src/rust/lqos_queue_tracker/src/queue_types/CAKE.md similarity index 100% rename from src/rust/lqosd/src/queue_tracker/queue_reader/CAKE.md rename to src/rust/lqos_queue_tracker/src/queue_types/CAKE.md diff --git a/src/rust/lqosd/src/queue_tracker/queue_reader/mod.rs b/src/rust/lqos_queue_tracker/src/queue_types/mod.rs similarity index 92% rename from src/rust/lqosd/src/queue_tracker/queue_reader/mod.rs rename to src/rust/lqos_queue_tracker/src/queue_types/mod.rs index cdd41aa7..521ed819 100644 --- a/src/rust/lqosd/src/queue_tracker/queue_reader/mod.rs +++ b/src/rust/lqos_queue_tracker/src/queue_types/mod.rs @@ -5,10 +5,7 @@ mod tc_mq; use anyhow::{Error, Result}; use serde::Serialize; use serde_json::Value; -mod queue_diff; -pub(crate) use queue_diff::make_queue_diff; -pub use queue_diff::QueueDiff; -use tokio::process::Command; +use std::process::Command; #[derive(Debug, Clone, Serialize)] pub enum QueueType { @@ -60,8 +57,7 @@ pub fn deserialize_tc_tree(json: &str) -> Result> { pub(crate) async fn read_tc_queues(interface: &str) -> Result> { let command_output = Command::new("/sbin/tc") .args(["-s", "-j", "qdisc", "show", "dev", interface]) - .output() - .await?; + .output()?; let json = String::from_utf8(command_output.stdout)?; let result = deserialize_tc_tree(&json)?; Ok(result) diff --git a/src/rust/lqosd/src/queue_tracker/queue_reader/tc_cake.rs b/src/rust/lqos_queue_tracker/src/queue_types/tc_cake.rs similarity index 100% rename from src/rust/lqosd/src/queue_tracker/queue_reader/tc_cake.rs rename to src/rust/lqos_queue_tracker/src/queue_types/tc_cake.rs diff --git a/src/rust/lqosd/src/queue_tracker/queue_reader/tc_fq_codel.rs b/src/rust/lqos_queue_tracker/src/queue_types/tc_fq_codel.rs similarity index 100% rename from src/rust/lqosd/src/queue_tracker/queue_reader/tc_fq_codel.rs rename to src/rust/lqos_queue_tracker/src/queue_types/tc_fq_codel.rs diff --git a/src/rust/lqosd/src/queue_tracker/queue_reader/tc_htb.rs b/src/rust/lqos_queue_tracker/src/queue_types/tc_htb.rs similarity index 100% rename from src/rust/lqosd/src/queue_tracker/queue_reader/tc_htb.rs rename to src/rust/lqos_queue_tracker/src/queue_types/tc_htb.rs diff --git a/src/rust/lqosd/src/queue_tracker/queue_reader/tc_mq.rs b/src/rust/lqos_queue_tracker/src/queue_types/tc_mq.rs similarity index 100% rename from src/rust/lqosd/src/queue_tracker/queue_reader/tc_mq.rs rename to src/rust/lqos_queue_tracker/src/queue_types/tc_mq.rs diff --git a/src/rust/lqosd/src/queue_tracker/mod.rs b/src/rust/lqos_queue_tracker/src/tracking.rs similarity index 65% rename from src/rust/lqosd/src/queue_tracker/mod.rs rename to src/rust/lqos_queue_tracker/src/tracking.rs index 756c229e..4add0e56 100644 --- a/src/rust/lqosd/src/queue_tracker/mod.rs +++ b/src/rust/lqos_queue_tracker/src/tracking.rs @@ -1,76 +1,20 @@ -use self::queue_reader::{make_queue_diff, QueueDiff, QueueType}; -use crate::libreqos_tracker::QUEUE_STRUCTURE; -use lqos_bus::BusResponse; +use std::time::{Duration, Instant}; +use tokio::time; use lqos_config::LibreQoSConfig; -use serde::Serialize; -use std::{ - collections::HashMap, - time::{Duration, Instant}, sync::atomic::AtomicU64, -}; -use tokio::{join, task, time}; -mod queue_reader; -use lazy_static::*; -use parking_lot::RwLock; use anyhow::Result; -pub use queue_reader::deserialize_tc_tree; - -const NUM_QUEUE_HISTORY: usize = 600; - -#[derive(Debug, Serialize)] -pub struct QueueStore { - history: Vec<(QueueDiff, QueueDiff)>, - history_head: usize, - prev_download: Option, - prev_upload: Option, - current_download: QueueType, - current_upload: QueueType, -} - -impl QueueStore { - fn new(download: QueueType, upload: QueueType) -> Self { - Self { - history: vec![(QueueDiff::None, QueueDiff::None); NUM_QUEUE_HISTORY], - history_head: 0, - prev_upload: None, - prev_download: None, - current_download: download, - current_upload: upload, - } - } - - fn update(&mut self, download: &QueueType, upload: &QueueType) { - self.prev_upload = Some(self.current_upload.clone()); - self.prev_download = Some(self.current_download.clone()); - self.current_download = download.clone(); - self.current_upload = upload.clone(); - let new_diff_up = make_queue_diff(self.prev_upload.as_ref().unwrap(), &self.current_upload); - let new_diff_dn = - make_queue_diff(self.prev_download.as_ref().unwrap(), &self.current_download); - if new_diff_dn.is_ok() && new_diff_up.is_ok() { - self.history[self.history_head] = (new_diff_dn.unwrap(), new_diff_up.unwrap()); - self.history_head += 1; - if self.history_head >= NUM_QUEUE_HISTORY { - self.history_head = 0; - } - } - } -} - -lazy_static! { - pub(crate) static ref CIRCUIT_TO_QUEUE: RwLock> = - RwLock::new(HashMap::new()); -} +use tokio::{join, task}; +use crate::{queue_types::{read_tc_queues, QueueType}, circuit_to_queue::CIRCUIT_TO_QUEUE, queue_structure::QUEUE_STRUCTURE, queue_store::QueueStore, interval::QUEUE_MONITOR_INTERVAL}; async fn track_queues() -> Result<()> { let config = LibreQoSConfig::load()?; let queues = if config.on_a_stick_mode { - let queues = queue_reader::read_tc_queues(&config.internet_interface) + let queues = read_tc_queues(&config.internet_interface) .await?; vec![queues] } else { let (isp, internet) = join! { - queue_reader::read_tc_queues(&config.isp_interface), - queue_reader::read_tc_queues(&config.internet_interface), + read_tc_queues(&config.isp_interface), + read_tc_queues(&config.internet_interface), }; vec![isp?, internet?] }; @@ -157,10 +101,6 @@ async fn track_queues() -> Result<()> { Ok(()) } -lazy_static! { - pub(crate) static ref QUEUE_MONITOR_INTERVAL: AtomicU64 = AtomicU64::new(1000); -} - pub async fn spawn_queue_monitor() { let _ = task::spawn(async { QUEUE_MONITOR_INTERVAL.store(lqos_config::EtcLqos::load().unwrap().queue_check_period_ms, std::sync::atomic::Ordering::Relaxed); @@ -181,17 +121,4 @@ pub async fn spawn_queue_monitor() { } } }); -} - -pub fn get_raw_circuit_data(circuit_id: &str) -> BusResponse { - let reader = CIRCUIT_TO_QUEUE.read(); - if let Some(circuit) = reader.get(circuit_id) { - if let Ok(json) = serde_json::to_string(circuit) { - BusResponse::RawQueueData(json) - } else { - BusResponse::RawQueueData(String::new()) - } - } else { - BusResponse::RawQueueData(String::new()) - } -} +} \ No newline at end of file diff --git a/src/rust/lqosd/Cargo.toml b/src/rust/lqosd/Cargo.toml index 5c85679e..c96549fd 100644 --- a/src/rust/lqosd/Cargo.toml +++ b/src/rust/lqosd/Cargo.toml @@ -11,6 +11,7 @@ equinix_tests = [] anyhow = "1" lqos_config = { path = "../lqos_config" } lqos_sys = { path = "../lqos_sys" } +lqos_queue_tracker = { path = "../lqos_queue_tracker" } tokio = { version = "1.22", features = [ "full", "parking_lot" ] } lazy_static = "1.4" parking_lot = "0.12" @@ -23,10 +24,3 @@ env_logger = "0" log = "0" nix = "0" rayon = "1" - -[dev-dependencies] -criterion = { version = "0.3", features = [ "html_reports"] } - -[[bench]] -name = "json" -harness = false diff --git a/src/rust/lqosd/src/lib.rs b/src/rust/lqosd/src/lib.rs deleted file mode 100644 index a71add2f..00000000 --- a/src/rust/lqosd/src/lib.rs +++ /dev/null @@ -1,163 +0,0 @@ -//! Provides a secondary option to build this crate as a library, -//! utilized by the benchmarking system. -//! -//! This file includes "main.rs"'s contents, but isn't used. The objective -//! is to ensure that it uses the same codepoints as `main.rs` - to avoid -//! confusing the unused code warning system. - -// Export for the benchmark program -pub use queue_tracker::deserialize_tc_tree; - -mod ip_mapping; -mod libreqos_tracker; -#[cfg(feature = "equinix_tests")] -mod lqos_daht_test; -mod tuning; -mod program_control; -mod queue_tracker; -mod throughput_tracker; -use crate::{ip_mapping::{clear_ip_flows, del_ip_flow, list_mapped_ips, map_ip_to_flow}}; -use anyhow::Result; -use log::{info, warn}; -use lqos_bus::{ - cookie_value, decode_request, encode_response, BusReply, BusRequest, BUS_BIND_ADDRESS, -}; -use lqos_config::LibreQoSConfig; -use lqos_sys::LibreQoSKernels; -use signal_hook::{consts::{SIGINT, SIGHUP, SIGTERM }, iterator::Signals}; -use tokio::{ - io::{AsyncReadExt, AsyncWriteExt}, - join, - net::{TcpListener, TcpStream} -}; - -//#[tokio::main] -pub async fn lib_main() -> Result<()> { - // Configure log level with RUST_LOG environment variable, - // defaulting to "info" - env_logger::init_from_env( - env_logger::Env::default().filter_or(env_logger::DEFAULT_FILTER_ENV, "warn") - ); - info!("LibreQoS Daemon Starting"); - let config = LibreQoSConfig::load()?; - tuning::tune_lqosd_from_config_file(&config)?; - - // Start the XDP/TC kernels - let kernels = if config.on_a_stick_mode { - LibreQoSKernels::on_a_stick_mode( - &config.internet_interface, - config.stick_vlans.1, - config.stick_vlans.0, - )? - } else { - LibreQoSKernels::new(&config.internet_interface, &config.isp_interface)? - }; - - // Spawn tracking sub-systems - join!( - throughput_tracker::spawn_throughput_monitor(), - queue_tracker::spawn_queue_monitor(), - //libreqos_tracker::spawn_shaped_devices_monitor(), - libreqos_tracker::spawn_queue_structure_monitor(), - ); - - // Handle signals - let mut signals = Signals::new(&[SIGINT, SIGHUP, SIGTERM ])?; - std::thread::spawn(move || { - for sig in signals.forever() { - match sig { - SIGINT | SIGTERM => { - match sig { - SIGINT => warn!("Terminating on SIGINT"), - SIGTERM => warn!("Terminating on SIGTERM"), - _ => warn!("This should never happen - terminating on unknown signal"), - } - std::mem::drop(kernels); - std::process::exit(0); - } - SIGHUP => { - warn!("Reloading configuration because of SIGHUP"); - if let Ok(config) = LibreQoSConfig::load() { - let result = tuning::tune_lqosd_from_config_file(&config); - match result { - Err(err) => { warn!("Unable to HUP tunables: {:?}", err) }, - Ok(..) => {} - } - } else { - warn!("Unable to reload configuration"); - } - } - _ => warn!("No handler for signal: {sig}"), - } - } - }); - - // Main bus listen loop - let listener = TcpListener::bind(BUS_BIND_ADDRESS).await?; - warn!("Listening on: {}", BUS_BIND_ADDRESS); - loop { - let (mut socket, _) = listener.accept().await?; - tokio::spawn(async move { - let mut buf = vec![0; 1024]; - - let _ = socket - .read(&mut buf) - .await - .expect("failed to read data from socket"); - - if let Ok(request) = decode_request(&buf) { - if request.auth_cookie == cookie_value() { - let mut response = BusReply { - auth_cookie: request.auth_cookie, - responses: Vec::new(), - }; - for req in request.requests.iter() { - //println!("Request: {:?}", req); - response.responses.push(match req { - BusRequest::Ping => lqos_bus::BusResponse::Ack, - BusRequest::GetCurrentThroughput => { - throughput_tracker::current_throughput() - } - BusRequest::GetHostCounter => throughput_tracker::host_counters(), - BusRequest::GetTopNDownloaders(n) => throughput_tracker::top_n(*n), - BusRequest::GetWorstRtt(n) => throughput_tracker::worst_n(*n), - BusRequest::MapIpToFlow { - ip_address, - tc_handle, - cpu, - upload, - } => map_ip_to_flow(ip_address, tc_handle, *cpu, *upload), - BusRequest::DelIpFlow { ip_address, upload } => { - del_ip_flow(&ip_address, *upload) - } - BusRequest::ClearIpFlow => clear_ip_flows(), - BusRequest::ListIpFlow => list_mapped_ips(), - BusRequest::XdpPping => throughput_tracker::xdp_pping_compat(), - BusRequest::RttHistogram => throughput_tracker::rtt_histogram(), - BusRequest::HostCounts => throughput_tracker::host_counts(), - BusRequest::AllUnknownIps => throughput_tracker::all_unknown_ips(), - BusRequest::ReloadLibreQoS => program_control::reload_libre_qos(), - BusRequest::GetRawQueueData(circuit_id) => { - queue_tracker::get_raw_circuit_data(&circuit_id) - } - BusRequest::UpdateLqosDTuning(..) => { - tuning::tune_lqosd_from_bus(&req).await - } - #[cfg(feature = "equinix_tests")] - BusRequest::RequestLqosEquinixTest => { - lqos_daht_test::lqos_daht_test().await - } - }); - } - //println!("{:?}", response); - let _ = reply(&encode_response(&response).unwrap(), &mut socket).await; - } - } - }); - } -} - -async fn reply(response: &[u8], socket: &mut TcpStream) -> Result<()> { - socket.write_all(&response).await?; - Ok(()) -} diff --git a/src/rust/lqosd/src/libreqos_tracker/mod.rs b/src/rust/lqosd/src/libreqos_tracker/mod.rs deleted file mode 100644 index fe767713..00000000 --- a/src/rust/lqosd/src/libreqos_tracker/mod.rs +++ /dev/null @@ -1,7 +0,0 @@ -//mod shaped_devices; -mod queue_structure; -mod queueing_structure; - -//pub(crate) use shaped_devices::spawn_shaped_devices_monitor; -pub(crate) use queue_structure::spawn_queue_structure_monitor; -pub(crate) use queue_structure::QUEUE_STRUCTURE; diff --git a/src/rust/lqosd/src/libreqos_tracker/queue_structure.rs b/src/rust/lqosd/src/libreqos_tracker/queue_structure.rs deleted file mode 100644 index a8de3803..00000000 --- a/src/rust/lqosd/src/libreqos_tracker/queue_structure.rs +++ /dev/null @@ -1,39 +0,0 @@ -//! Tracks changes to the ShapedDevices.csv file in LibreQoS. - -use crate::libreqos_tracker::queueing_structure::{ - read_queueing_structure, QueueNetwork, QueueNode, -}; -use anyhow::Result; -use lazy_static::*; -use parking_lot::RwLock; -use tokio::task::spawn_blocking; - -lazy_static! { - /// Global storage of the shaped devices csv data. - /// Updated by the file system watcher whenever - /// the underlying file changes. - pub(crate) static ref QUEUE_STRUCTURE : RwLock>> = RwLock::new(read_queueing_structure()); -} - -pub async fn spawn_queue_structure_monitor() { - spawn_blocking(|| { - let _ = watch_for_shaped_devices_changing(); - }); -} - -/// Fires up a Linux file system watcher than notifies -/// when `ShapedDevices.csv` changes, and triggers a reload. -fn watch_for_shaped_devices_changing() -> Result<()> { - use notify::{Config, RecursiveMode, Watcher}; - - let (tx, rx) = std::sync::mpsc::channel(); - let mut watcher = notify::RecommendedWatcher::new(tx, Config::default())?; - - watcher.watch(&QueueNetwork::path()?, RecursiveMode::NonRecursive)?; - loop { - let _ = rx.recv(); - let new_file = read_queueing_structure(); - log::info!("queuingStructure.csv changed"); - *QUEUE_STRUCTURE.write() = new_file; - } -} diff --git a/src/rust/lqosd/src/libreqos_tracker/queueing_structure/mod.rs b/src/rust/lqosd/src/libreqos_tracker/queueing_structure/mod.rs deleted file mode 100644 index c419c5d2..00000000 --- a/src/rust/lqosd/src/libreqos_tracker/queueing_structure/mod.rs +++ /dev/null @@ -1,9 +0,0 @@ -mod reader; -use anyhow::Result; - -pub use reader::{QueueNetwork, QueueNode}; - -pub fn read_queueing_structure() -> Result> { - let network = reader::QueueNetwork::from_json()?; - Ok(network.to_flat()) -} diff --git a/src/rust/lqosd/src/main.rs b/src/rust/lqosd/src/main.rs index 01fb2b95..33ab3877 100644 --- a/src/rust/lqosd/src/main.rs +++ b/src/rust/lqosd/src/main.rs @@ -1,11 +1,9 @@ mod ip_mapping; -mod libreqos_tracker; #[cfg(feature = "equinix_tests")] mod lqos_daht_test; +mod throughput_tracker; mod tuning; mod program_control; -mod queue_tracker; -mod throughput_tracker; use crate::{ip_mapping::{clear_ip_flows, del_ip_flow, list_mapped_ips, map_ip_to_flow}}; use anyhow::Result; use log::{info, warn}; @@ -13,6 +11,7 @@ use lqos_bus::{ cookie_value, decode_request, encode_response, BusReply, BusRequest, BUS_BIND_ADDRESS, }; use lqos_config::LibreQoSConfig; +use lqos_queue_tracker::{spawn_queue_monitor, spawn_queue_structure_monitor, get_raw_circuit_data}; use lqos_sys::LibreQoSKernels; use signal_hook::{consts::{SIGINT, SIGHUP, SIGTERM }, iterator::Signals}; use tokio::{ @@ -46,9 +45,8 @@ async fn main() -> Result<()> { // Spawn tracking sub-systems join!( throughput_tracker::spawn_throughput_monitor(), - queue_tracker::spawn_queue_monitor(), - //libreqos_tracker::spawn_shaped_devices_monitor(), - libreqos_tracker::spawn_queue_structure_monitor(), + spawn_queue_monitor(), + spawn_queue_structure_monitor(), ); // Handle signals @@ -128,7 +126,7 @@ async fn main() -> Result<()> { BusRequest::AllUnknownIps => throughput_tracker::all_unknown_ips(), BusRequest::ReloadLibreQoS => program_control::reload_libre_qos(), BusRequest::GetRawQueueData(circuit_id) => { - queue_tracker::get_raw_circuit_data(&circuit_id) + get_raw_circuit_data(&circuit_id) } BusRequest::UpdateLqosDTuning(..) => { tuning::tune_lqosd_from_bus(&req).await diff --git a/src/rust/lqosd/src/tuning/mod.rs b/src/rust/lqosd/src/tuning/mod.rs index 88fa85e4..5f44ebe5 100644 --- a/src/rust/lqosd/src/tuning/mod.rs +++ b/src/rust/lqosd/src/tuning/mod.rs @@ -2,7 +2,7 @@ mod offloads; use anyhow::Result; use lqos_bus::{BusRequest, BusResponse}; use lqos_config::{EtcLqos, LibreQoSConfig}; -use crate::queue_tracker::QUEUE_MONITOR_INTERVAL; +use lqos_queue_tracker::set_queue_refresh_interval; pub fn tune_lqosd_from_config_file(config: &LibreQoSConfig) -> Result<()> { let etc_lqos = EtcLqos::load()?; @@ -18,7 +18,7 @@ pub fn tune_lqosd_from_config_file(config: &LibreQoSConfig) -> Result<()> { offloads::ethtool_tweaks(&config.isp_interface, tuning); } let interval = etc_lqos.queue_check_period_ms; - QUEUE_MONITOR_INTERVAL.store(interval, std::sync::atomic::Ordering::Relaxed); + set_queue_refresh_interval(interval); Ok(()) } @@ -34,7 +34,7 @@ pub async fn tune_lqosd_from_bus(request: &BusRequest) -> BusResponse { offloads::ethtool_tweaks(&config.internet_interface, tuning); offloads::ethtool_tweaks(&config.isp_interface, tuning); } - QUEUE_MONITOR_INTERVAL.store(*interval, std::sync::atomic::Ordering::Relaxed); + set_queue_refresh_interval(*interval); lqos_bus::BusResponse::Ack } _ => BusResponse::Fail("That wasn't a tuning request".to_string())