diff --git a/src/LibreQoS.py b/src/LibreQoS.py index 5492d8bc..d44e4968 100755 --- a/src/LibreQoS.py +++ b/src/LibreQoS.py @@ -1765,17 +1765,45 @@ def refreshShapers(): for device in circuit['devices']: if device['ipv4s']: for ipv4 in device['ipv4s']: - ipMapBatch.add_ip_mapping(str(ipv4), circuit['classid'], data[node]['cpuNum'], False) + ipMapBatch.add_ip_mapping( + str(ipv4), + circuit['classid'], + data[node]['cpuNum'], + False, + circuit.get('circuitID', ''), + device.get('deviceID', ''), + ) #xdpCPUmapCommands.append('./bin/xdp_iphash_to_cpu_cmdline add --ip ' + str(ipv4) + ' --cpu ' + data[node]['cpuNum'] + ' --classid ' + circuit['classid']) if on_a_stick(): - ipMapBatch.add_ip_mapping(str(ipv4), circuit['up_classid'], data[node]['up_cpuNum'], True) + ipMapBatch.add_ip_mapping( + str(ipv4), + circuit['up_classid'], + data[node]['up_cpuNum'], + True, + circuit.get('circuitID', ''), + device.get('deviceID', ''), + ) #xdpCPUmapCommands.append('./bin/xdp_iphash_to_cpu_cmdline add --ip ' + str(ipv4) + ' --cpu ' + data[node]['up_cpuNum'] + ' --classid ' + circuit['up_classid'] + ' --upload 1') if device['ipv6s']: for ipv6 in device['ipv6s']: - ipMapBatch.add_ip_mapping(str(ipv6), circuit['classid'], data[node]['cpuNum'], False) + ipMapBatch.add_ip_mapping( + str(ipv6), + circuit['classid'], + data[node]['cpuNum'], + False, + circuit.get('circuitID', ''), + device.get('deviceID', ''), + ) #xdpCPUmapCommands.append('./bin/xdp_iphash_to_cpu_cmdline add --ip ' + str(ipv6) + ' --cpu ' + data[node]['cpuNum'] + ' --classid ' + circuit['classid']) if on_a_stick(): - ipMapBatch.add_ip_mapping(str(ipv6), circuit['up_classid'], data[node]['up_cpuNum'], True) + ipMapBatch.add_ip_mapping( + str(ipv6), + circuit['up_classid'], + data[node]['up_cpuNum'], + True, + circuit.get('circuitID', ''), + device.get('deviceID', ''), + ) #xdpCPUmapCommands.append('./bin/xdp_iphash_to_cpu_cmdline add --ip ' + str(ipv6) + ' --cpu ' + data[node]['up_cpuNum'] + ' --classid ' + circuit['up_classid'] + ' --upload 1') if device['deviceName'] not in devicesShaped: devicesShaped.append(device['deviceName']) diff --git a/src/rust/lqos_bakery/src/lib.rs b/src/rust/lqos_bakery/src/lib.rs index 785cc5f1..fde6e26f 100644 --- a/src/rust/lqos_bakery/src/lib.rs +++ b/src/rust/lqos_bakery/src/lib.rs @@ -672,7 +672,7 @@ fn bakery_main(rx: Receiver, tx: Sender) { mig.shadow_minor, ) }; - let _ = lqos_sys::add_ip_to_tc(&ip_s, handle, cpu, upload); + let _ = lqos_sys::add_ip_to_tc(&ip_s, handle, cpu, upload, 0, 0); // Update local mapping view mapping_current.insert(key.clone(), MappingVal { handle, cpu }); } @@ -787,7 +787,7 @@ fn bakery_main(rx: Receiver, tx: Sender) { } else { tc_handle_from_major_minor(mig.class_major, mig.final_minor) }; - let _ = lqos_sys::add_ip_to_tc(&ip_s, handle, cpu, upload); + let _ = lqos_sys::add_ip_to_tc(&ip_s, handle, cpu, upload, 0, 0); mapping_current.insert(key.clone(), MappingVal { handle, cpu }); } } diff --git a/src/rust/lqos_bus/src/bus/request.rs b/src/rust/lqos_bus/src/bus/request.rs index 79a45c58..dd8cee08 100644 --- a/src/rust/lqos_bus/src/bus/request.rs +++ b/src/rust/lqos_bus/src/bus/request.rs @@ -114,6 +114,18 @@ pub enum BusRequest { /// The CPU on which the TC handle should be shaped. cpu: u32, + /// Hashed circuit identifier (from ShapedDevices.csv). + /// + /// Defaults to `0` for backward compatibility. + #[serde(default)] + circuit_id: u64, + + /// Hashed device identifier (from ShapedDevices.csv). + /// + /// Defaults to `0` for backward compatibility. + #[serde(default)] + device_id: u64, + /// If true, this is a *second* flow for the same IP range on /// the same NIC. Used for handling "on a stick" configurations. upload: bool, diff --git a/src/rust/lqos_bus/src/ip_stats.rs b/src/rust/lqos_bus/src/ip_stats.rs index b10b0dff..14b22899 100644 --- a/src/rust/lqos_bus/src/ip_stats.rs +++ b/src/rust/lqos_bus/src/ip_stats.rs @@ -49,6 +49,18 @@ pub struct IpMapping { /// The CPU index associated with this IP mapping. pub cpu: u32, + + /// Hashed circuit identifier (from ShapedDevices.csv). + /// + /// Defaults to `0` for backward compatibility. + #[serde(default)] + pub circuit_id: u64, + + /// Hashed device identifier (from ShapedDevices.csv). + /// + /// Defaults to `0` for backward compatibility. + #[serde(default)] + pub device_id: u64, } /// Provided for backwards compatibility with `xdp_pping`, with the intent diff --git a/src/rust/lqos_python/src/lib.rs b/src/rust/lqos_python/src/lib.rs index 954b13d5..a922970d 100644 --- a/src/rust/lqos_python/src/lib.rs +++ b/src/rust/lqos_python/src/lib.rs @@ -761,29 +761,53 @@ fn delete_ip_mapping(_py: Python, ip_address: String) -> PyResult<()> { /// Internal function /// Converts IP address arguments into an IP mapping request. -fn parse_add_ip(ip: &str, classid: &str, cpu: &str, upload: bool) -> Result { +fn parse_add_ip( + ip: &str, + classid: &str, + cpu: &str, + upload: bool, + circuit_id: Option<&str>, + device_id: Option<&str>, +) -> Result { if !classid.contains(':') { return Err(Error::msg(format!( "Class id must be in the format (major):(minor), e.g. 1:12. Provided string: {classid}" ))); } + let circuit_id = circuit_id + .and_then(|s| (!s.is_empty()).then(|| lqos_utils::hash_to_i64(s) as u64)) + .unwrap_or(0); + let device_id = device_id + .and_then(|s| (!s.is_empty()).then(|| lqos_utils::hash_to_i64(s) as u64)) + .unwrap_or(0); Ok(BusRequest::MapIpToFlow { ip_address: ip.to_string(), tc_handle: TcHandle::from_string(classid)?, cpu: read_hex_string(cpu)?, // Force HEX representation + circuit_id, + device_id, upload, }) } /// Adds an IP address mapping -#[pyfunction] +#[pyfunction(signature = (ip, classid, cpu, upload, circuit_id=None, device_id=None))] fn add_ip_mapping( ip: String, classid: String, cpu: String, // In HEX upload: bool, + circuit_id: Option, + device_id: Option, ) -> PyResult<()> { - let request = parse_add_ip(&ip, &classid, &cpu, upload); + let request = parse_add_ip( + &ip, + &classid, + &cpu, + upload, + circuit_id.as_deref(), + device_id.as_deref(), + ); if let Ok(request) = request { run_query(vec![request]).unwrap(); Ok(()) @@ -804,14 +828,24 @@ impl BatchedCommands { Ok(Self { batch: Vec::new() }) } + #[pyo3(signature = (ip, classid, cpu, upload, circuit_id=None, device_id=None))] pub fn add_ip_mapping( &mut self, ip: String, classid: String, cpu: String, upload: bool, + circuit_id: Option, + device_id: Option, ) -> PyResult<()> { - let request = parse_add_ip(&ip, &classid, &cpu, upload); + let request = parse_add_ip( + &ip, + &classid, + &cpu, + upload, + circuit_id.as_deref(), + device_id.as_deref(), + ); if let Ok(request) = request { self.batch.push(request); Ok(()) diff --git a/src/rust/lqos_sys/src/bpf/common/lpm.h b/src/rust/lqos_sys/src/bpf/common/lpm.h index 07e64046..4152770a 100644 --- a/src/rust/lqos_sys/src/bpf/common/lpm.h +++ b/src/rust/lqos_sys/src/bpf/common/lpm.h @@ -15,6 +15,8 @@ struct ip_hash_info { __u32 cpu; __u32 tc_handle; // TC handle MAJOR:MINOR combined in __u32 + __u64 circuit_id; + __u64 device_id; }; // Key type used for map_ip_hash trie @@ -128,7 +130,9 @@ static __always_inline struct ip_hash_info * setup_lookup_key_and_tc_cpu( // of repeatedly hitting queries for IPs that ARE NOT shaped. struct ip_hash_info negative_hit = { .cpu = NEGATIVE_HIT, - .tc_handle = NEGATIVE_HIT + .tc_handle = NEGATIVE_HIT, + .circuit_id = 0, + .device_id = 0, }; bpf_map_update_elem( &ip_to_cpu_and_tc_hotcache, @@ -206,4 +210,4 @@ static __always_inline struct ip_hash_info * tc_setup_lookup_key_and_tc_cpu( lookup_key ); return ip_info; -} \ No newline at end of file +} diff --git a/src/rust/lqos_sys/src/bpf_map.rs b/src/rust/lqos_sys/src/bpf_map.rs index 06adb436..ffd8b3c1 100644 --- a/src/rust/lqos_sys/src/bpf_map.rs +++ b/src/rust/lqos_sys/src/bpf_map.rs @@ -46,6 +46,32 @@ where } } + /// Lookup a value from the underlying eBPF map. + /// + /// Returns `Ok(None)` if the key does not exist. + pub fn lookup(&self, key: &mut K) -> Result> { + let key_ptr: *mut K = key; + let mut value = V::default(); + let value_ptr: *mut V = &mut value; + let err = unsafe { + bpf_map_lookup_elem( + self.fd, + key_ptr as *mut c_void, + value_ptr as *mut c_void, + ) + }; + if err != 0 { + if err == -2 { + // -ENOENT + Ok(None) + } else { + Err(Error::msg(format!("Unable to lookup map element ({err})"))) + } + } else { + Ok(Some(value)) + } + } + /// Iterates the underlying BPF map, and adds the results /// to a vector. Each entry contains a `key, value` tuple. /// diff --git a/src/rust/lqos_sys/src/ip_mapping/ip_hash_data.rs b/src/rust/lqos_sys/src/ip_mapping/ip_hash_data.rs index 8828a30c..024ba51f 100644 --- a/src/rust/lqos_sys/src/ip_mapping/ip_hash_data.rs +++ b/src/rust/lqos_sys/src/ip_mapping/ip_hash_data.rs @@ -3,4 +3,16 @@ pub struct IpHashData { pub cpu: u32, pub tc_handle: u32, + pub circuit_id: u64, + pub device_id: u64, +} + +#[cfg(test)] +mod test { + use super::IpHashData; + + #[test] + fn ip_hash_data_size() { + assert_eq!(std::mem::size_of::(), 24); + } } diff --git a/src/rust/lqos_sys/src/ip_mapping/mod.rs b/src/rust/lqos_sys/src/ip_mapping/mod.rs index 9ea10d03..baa6bc0b 100644 --- a/src/rust/lqos_sys/src/ip_mapping/mod.rs +++ b/src/rust/lqos_sys/src/ip_mapping/mod.rs @@ -6,8 +6,8 @@ use std::net::IpAddr; mod ip_hash_data; mod ip_hash_key; mod ip_to_map; -use ip_hash_data::IpHashData; -use ip_hash_key::IpHashKey; +pub(crate) use ip_hash_data::IpHashData; +pub(crate) use ip_hash_key::IpHashKey; use ip_to_map::IpToMap; /// Adds an IP address to the underlying TC map. @@ -17,7 +17,14 @@ use ip_to_map::IpToMap; /// * `address` - a string containing an IPv4 or IPv6 address, with or without a prefix-length. /// * `tc_handle` - the TC classifier handle to associate with the IP address, in (major,minor) format. /// * `cpu` - the CPU index on which the TC class should be handled. -pub fn add_ip_to_tc(address: &str, tc_handle: TcHandle, cpu: u32, upload: bool) -> Result<()> { +pub fn add_ip_to_tc( + address: &str, + tc_handle: TcHandle, + cpu: u32, + upload: bool, + circuit_id: u64, + device_id: u64, +) -> Result<()> { let bpf_path = if upload { "/sys/fs/bpf/map_ip_to_cpu_and_tc_recip" } else { @@ -31,9 +38,23 @@ pub fn add_ip_to_tc(address: &str, tc_handle: TcHandle, cpu: u32, upload: bool) prefixlen: ip_to_add.prefix, address: address.0, }; + let mut circuit_id = circuit_id; + let mut device_id = device_id; + if circuit_id == 0 || device_id == 0 { + if let Some(existing) = bpf_map.lookup(&mut key)? { + if circuit_id == 0 { + circuit_id = existing.circuit_id; + } + if device_id == 0 { + device_id = existing.device_id; + } + } + } let mut value = IpHashData { cpu: ip_to_add.cpu, tc_handle: ip_to_add.handle(), + circuit_id, + device_id, }; bpf_map.insert_or_update(&mut key, &mut value)?; // Removed because it should be cleared explicitly at the end of a batch operation diff --git a/src/rust/lqos_sys/src/lqos_kernel.rs b/src/rust/lqos_sys/src/lqos_kernel.rs index 5ba8a0fa..80cd2c17 100644 --- a/src/rust/lqos_sys/src/lqos_kernel.rs +++ b/src/rust/lqos_sys/src/lqos_kernel.rs @@ -5,18 +5,23 @@ use crate::cpu_map::CpuMapping; use anyhow::{Error, Result}; +use lqos_utils::XdpIpAddress; use libbpf_sys::{ LIBBPF_STRICT_ALL, XDP_FLAGS_DRV_MODE, XDP_FLAGS_HW_MODE, XDP_FLAGS_SKB_MODE, - XDP_FLAGS_UPDATE_IF_NOEXIST, bpf_xdp_attach, libbpf_set_strict_mode, + XDP_FLAGS_UPDATE_IF_NOEXIST, bpf_map_info, bpf_obj_get, bpf_obj_get_info_by_fd, bpf_xdp_attach, + libbpf_set_strict_mode, }; -use nix::libc::{geteuid, if_nametoindex}; +use nix::libc::{close, geteuid, if_nametoindex}; use std::{ ffi::{CString, c_void}, + fs, + mem::MaybeUninit, + path::Path, process::Command, thread, time::Duration, }; -use tracing::{debug, error, info}; +use tracing::{debug, error, info, warn}; use self::bpf::{libbpf_num_possible_cpus, lqos_kern}; @@ -41,6 +46,75 @@ pub fn check_root() -> Result<()> { } } +fn remove_incompatible_pinned_map( + path: &str, + expected_key_size: u32, + expected_value_size: u32, +) -> Result<()> { + if !Path::new(path).exists() { + return Ok(()); + } + + let path_c = CString::new(path)?; + let fd = unsafe { bpf_obj_get(path_c.as_ptr()) }; + if fd < 0 { + warn!("Unable to open pinned BPF map '{path}' for ABI check (fd={fd})"); + return Ok(()); + } + + let mut info = MaybeUninit::::zeroed(); + let mut len: u32 = std::mem::size_of::() as u32; + let err = unsafe { bpf_obj_get_info_by_fd(fd, info.as_mut_ptr() as *mut c_void, &mut len) }; + unsafe { + close(fd); + } + if err != 0 { + return Err(Error::msg(format!( + "Unable to query pinned BPF map '{path}' info (err={err})." + ))); + } + let info = unsafe { info.assume_init() }; + + if info.key_size != expected_key_size || info.value_size != expected_value_size { + warn!( + "Pinned BPF map '{}' ABI mismatch (key_size={}, value_size={}) expected (key_size={}, value_size={}). Removing pin to force recreation.", + path, + info.key_size, + info.value_size, + expected_key_size, + expected_value_size + ); + fs::remove_file(path).map_err(|e| { + Error::msg(format!( + "Unable to remove pinned BPF map '{path}' (needed for ABI upgrade): {e:?}" + )) + })?; + } + + Ok(()) +} + +fn ensure_ip_mapping_maps_abi() -> Result<()> { + let expected_key_size = std::mem::size_of::() as u32; + let expected_value_size = std::mem::size_of::() as u32; + remove_incompatible_pinned_map( + "/sys/fs/bpf/map_ip_to_cpu_and_tc", + expected_key_size, + expected_value_size, + )?; + remove_incompatible_pinned_map( + "/sys/fs/bpf/map_ip_to_cpu_and_tc_recip", + expected_key_size, + expected_value_size, + )?; + remove_incompatible_pinned_map( + "/sys/fs/bpf/ip_to_cpu_and_tc_hotcache", + std::mem::size_of::() as u32, + expected_value_size, + )?; + Ok(()) +} + /// Converts an interface name to an interface index. /// This is a wrapper around the `if_nametoindex` function. /// Returns an error if the interface does not exist. @@ -165,6 +239,9 @@ pub fn attach_xdp_and_tc_to_interface( flowbee_event_handler: bpf::ring_buffer_sample_fn, ) -> Result<*mut lqos_kern> { check_root()?; + // If ABI changes were made to pinned maps, ensure we do not silently reuse + // incompatible versions that truncate struct values. + ensure_ip_mapping_maps_abi()?; // Check the interface is valid let interface_index = interface_name_to_index(interface_name)?; set_strict_mode()?; diff --git a/src/rust/lqosd/src/ip_mapping.rs b/src/rust/lqosd/src/ip_mapping.rs index 498eb378..57de5bdd 100644 --- a/src/rust/lqosd/src/ip_mapping.rs +++ b/src/rust/lqosd/src/ip_mapping.rs @@ -15,8 +15,12 @@ pub(crate) fn map_ip_to_flow( tc_handle: &TcHandle, cpu: u32, upload: bool, + circuit_id: u64, + device_id: u64, ) -> BusResponse { - expect_ack(lqos_sys::add_ip_to_tc(ip_address, *tc_handle, cpu, upload)) + expect_ack(lqos_sys::add_ip_to_tc( + ip_address, *tc_handle, cpu, upload, circuit_id, device_id, + )) } pub(crate) fn clear_hot_cache() -> BusResponse { @@ -40,6 +44,8 @@ pub(crate) fn list_mapped_ips() -> BusResponse { prefix_length: ip_key.prefixlen, tc_handle: TcHandle::from_u32(ip_data.tc_handle), cpu: ip_data.cpu, + circuit_id: ip_data.circuit_id, + device_id: ip_data.device_id, }) .collect(); BusResponse::MappedIps(data) diff --git a/src/rust/lqosd/src/main.rs b/src/rust/lqosd/src/main.rs index f8864773..d80844fd 100644 --- a/src/rust/lqosd/src/main.rs +++ b/src/rust/lqosd/src/main.rs @@ -377,9 +377,11 @@ fn handle_bus_requests(requests: &[BusRequest], responses: &mut Vec ip_address, tc_handle, cpu, + circuit_id, + device_id, upload, } => { - let resp = map_ip_to_flow(ip_address, tc_handle, *cpu, *upload); + let resp = map_ip_to_flow(ip_address, tc_handle, *cpu, *upload, *circuit_id, *device_id); if let Some(sender) = lqos_bakery::BAKERY_SENDER.get() { let _ = sender.send(lqos_bakery::BakeryCommands::MapIp { ip_address: ip_address.clone(), diff --git a/src/rust/xdp_iphash_to_cpu_cmdline/README.md b/src/rust/xdp_iphash_to_cpu_cmdline/README.md index 52c0b8f0..cbce10cb 100644 --- a/src/rust/xdp_iphash_to_cpu_cmdline/README.md +++ b/src/rust/xdp_iphash_to_cpu_cmdline/README.md @@ -19,6 +19,7 @@ Examples: ``` xdp_iphash_to_cpu_cmdline list xdp_iphash_to_cpu_cmdline add --ip 192.168.100.1 --classid 5:3 --cpu 4 +xdp_iphash_to_cpu_cmdline add --ip 192.168.100.1 --classid 5:3 --cpu 4 --circuit-id CIRCUIT123 --device-id DEVICE456 xdp_iphash_to_cpu_cmdline del 192.168.100.1 xdp_iphash_to_cpu_cmdline clear ``` diff --git a/src/rust/xdp_iphash_to_cpu_cmdline/src/main.rs b/src/rust/xdp_iphash_to_cpu_cmdline/src/main.rs index 95ec2a08..ca4953e8 100644 --- a/src/rust/xdp_iphash_to_cpu_cmdline/src/main.rs +++ b/src/rust/xdp_iphash_to_cpu_cmdline/src/main.rs @@ -27,6 +27,14 @@ enum Commands { #[arg(long)] cpu: String, + /// Circuit ID (raw string). Hashed before being stored. + #[arg(long)] + circuit_id: Option, + + /// Device ID (raw string). Hashed before being stored. + #[arg(long)] + device_id: Option, + /// Add "--upload 1" if you are using on-a-stick and need to map upload separately #[arg(long)] upload: Option, @@ -74,16 +82,25 @@ fn print_ips(ips: &[IpMapping]) { format!("{}/{}", ip.ip_address, ip.prefix_length - 96) }; println!( - "{:<45} CPU: {:<4} TC: {}", + "{:<45} CPU: {:<4} TC: {} CIRCUIT: {} DEVICE: {}", ip_formatted, ip.cpu, - ip.tc_handle.to_string() + ip.tc_handle.to_string(), + ip.circuit_id as i64, + ip.device_id as i64 ); } println!(); } -fn parse_add_ip(ip: &str, classid: &str, cpu: &str, upload: &Option) -> Result { +fn parse_add_ip( + ip: &str, + classid: &str, + cpu: &str, + upload: &Option, + circuit_id: &Option, + device_id: &Option, +) -> Result { //if ip.parse::().is_err() { // return Err(Error::msg(format!("Unable to parse IP address: {ip}"))); //} @@ -92,10 +109,22 @@ fn parse_add_ip(ip: &str, classid: &str, cpu: &str, upload: &Option) -> "Class id must be in the format (major):(minor), e.g. 1:12. Provided string: {classid}" ))); } + let circuit_id = circuit_id + .as_deref() + .filter(|s| !s.is_empty()) + .map(|s| lqos_utils::hash_to_i64(s) as u64) + .unwrap_or(0); + let device_id = device_id + .as_deref() + .filter(|s| !s.is_empty()) + .map(|s| lqos_utils::hash_to_i64(s) as u64) + .unwrap_or(0); Ok(BusRequest::MapIpToFlow { ip_address: ip.to_string(), tc_handle: TcHandle::from_string(classid)?, cpu: read_hex_string(cpu)?, // Force HEX representation + circuit_id, + device_id, upload: upload.is_some(), }) } @@ -109,9 +138,12 @@ pub async fn main() -> Result<()> { ip, classid, cpu, + circuit_id, + device_id, upload, }) => { - talk_to_server(parse_add_ip(&ip, &classid, &cpu, &upload)?).await?; + talk_to_server(parse_add_ip(&ip, &classid, &cpu, &upload, &circuit_id, &device_id)?) + .await?; } Some(Commands::Del { ip, upload }) => { talk_to_server(BusRequest::DelIpFlow {