From 0f513229c2c6567a35713ca8c50835b9c17a2e5e Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Wed, 17 Jun 2026 15:51:08 -0500 Subject: [PATCH] Refactor Rust file locks into shared helper --- src/rust/Cargo.lock | 2 +- src/rust/lqos_overrides/Cargo.toml | 2 +- src/rust/lqos_overrides/src/file_lock.rs | 561 ++---------- src/rust/lqos_utils/src/lib.rs | 2 + src/rust/lqos_utils/src/process_lock.rs | 1062 ++++++++++++++++++++++ src/rust/lqosd/src/file_lock.rs | 219 +++-- 6 files changed, 1289 insertions(+), 559 deletions(-) create mode 100644 src/rust/lqos_utils/src/process_lock.rs diff --git a/src/rust/Cargo.lock b/src/rust/Cargo.lock index 1ae74993..fc223adc 100644 --- a/src/rust/Cargo.lock +++ b/src/rust/Cargo.lock @@ -2332,7 +2332,7 @@ dependencies = [ "clap", "lqos_bus", "lqos_config", - "nix", + "lqos_utils", "serde", "serde_json", "tokio", diff --git a/src/rust/lqos_overrides/Cargo.toml b/src/rust/lqos_overrides/Cargo.toml index 1a343db2..4d23a67d 100644 --- a/src/rust/lqos_overrides/Cargo.toml +++ b/src/rust/lqos_overrides/Cargo.toml @@ -7,8 +7,8 @@ edition = "2024" serde.workspace = true serde_json.workspace = true anyhow.workspace = true -nix.workspace = true lqos_config = { path = "../lqos_config" } lqos_bus = { path = "../lqos_bus" } +lqos_utils = { path = "../lqos_utils" } clap = { workspace = true, features = ["derive"] } tokio.workspace = true diff --git a/src/rust/lqos_overrides/src/file_lock.rs b/src/rust/lqos_overrides/src/file_lock.rs index 996e7166..40c6eb8a 100644 --- a/src/rust/lqos_overrides/src/file_lock.rs +++ b/src/rust/lqos_overrides/src/file_lock.rs @@ -1,339 +1,63 @@ -use anyhow::{Error, Result}; -use nix::{ - errno::Errno, - libc::{getpid, mode_t}, -}; -use std::{ - ffi::CString, - fs::{File, OpenOptions, hard_link, remove_file}, - io::{ErrorKind, Read, Write}, - os::fd::AsRawFd, - path::{Path, PathBuf}, - sync::atomic::{AtomicU64, Ordering}, - time::{SystemTime, UNIX_EPOCH}, -}; +use anyhow::Result; +use lqos_utils::process_lock::{ProcessFileLock, ProcessLockConfig}; +#[cfg(test)] +use std::cell::RefCell; const LOCK_PATH: &str = "/run/lqos/lqos_overrides.lock"; const LOCK_DIR: &str = "/run/lqos"; -const LOCK_DIR_PERMS: &str = "/run/lqos"; const LOCK_GUARD_PATH: &str = "/run/lqos/lqos_overrides.lock.guard"; -const STALE_LOCK_REPLACE_ATTEMPTS: usize = 3; -const LOCK_TEMP_CREATE_ATTEMPTS: usize = 8; const LOCK_CONTENTION_CODE: &str = "LQOS_OVERRIDES_LOCKED"; -static TEMP_LOCK_SEQUENCE: AtomicU64 = AtomicU64::new(0); +#[cfg(test)] +thread_local! { + static TEST_LOCK_CONFIG: RefCell> = const { RefCell::new(None) }; +} /// Cross-process lock used while mutating operator-owned override files. +/// +/// Dropping this guard removes `/run/lqos/lqos_overrides.lock`. #[derive(Debug)] pub struct FileLock { - lock_path: PathBuf, -} - -struct AcquisitionGuard { - file: File, -} - -#[derive(Clone, Debug, PartialEq, Eq)] -struct LockMetadata { - pid: i32, - process: Option, - operation: Option, - created_unix: Option, -} - -impl LockMetadata { - fn current(operation: &str) -> Self { - Self { - pid: unsafe { getpid() }, - process: current_process_name(), - operation: Some(sanitize_lock_field(operation)), - created_unix: SystemTime::now() - .duration_since(UNIX_EPOCH) - .ok() - .map(|duration| duration.as_secs()), - } - } - - fn parse(contents: &str) -> Result { - let trimmed = contents.trim(); - if let Ok(pid) = trimmed.parse::() { - return Ok(Self { - pid, - process: None, - operation: None, - created_unix: None, - }); - } - - let mut pid = None; - let mut process = None; - let mut operation = None; - let mut created_unix = None; - for line in contents.lines() { - let Some((key, value)) = line.split_once('=') else { - continue; - }; - match key.trim() { - "pid" => pid = Some(value.trim().parse::()?), - "process" => process = Some(value.trim().to_string()), - "operation" => operation = Some(value.trim().to_string()), - "created_unix" => created_unix = Some(value.trim().parse::()?), - _ => {} - } - } - - let Some(pid) = pid else { - return Err(Error::msg( - "The LibreQoS overrides lock file does not contain a process id.", - )); - }; - - Ok(Self { - pid, - process, - operation, - created_unix, - }) - } - - fn serialize(&self) -> String { - let process = self.process.as_deref().unwrap_or("unknown"); - let operation = self.operation.as_deref().unwrap_or("unknown"); - let created_unix = self - .created_unix - .map(|seconds| seconds.to_string()) - .unwrap_or_else(|| "unknown".to_string()); - format!( - "pid={}\nprocess={}\noperation={}\ncreated_unix={}\n", - self.pid, process, operation, created_unix - ) - } - - fn describe_holder(&self) -> String { - let mut parts = vec![format!("pid={}", self.pid)]; - if let Some(process) = self.process.as_deref().filter(|value| !value.is_empty()) { - parts.push(format!("process={process}")); - } - if let Some(operation) = self.operation.as_deref().filter(|value| !value.is_empty()) { - parts.push(format!("operation={operation}")); - } - if let Some(created_unix) = self.created_unix { - parts.push(format!("created_unix={created_unix}")); - } - parts.join(", ") - } + _lock: ProcessFileLock, } impl FileLock { /// Acquires the lock and records the caller operation for diagnostics. pub fn new_for_operation(operation: &str) -> Result { - Self::new_at( - operation, - Path::new(LOCK_PATH), - Path::new(LOCK_DIR), - Path::new(LOCK_DIR_PERMS), - Path::new(LOCK_GUARD_PATH), - ) - } - - fn new_at( - operation: &str, - lock_path: &Path, - lock_dir: &Path, - lock_dir_perms: &Path, - guard_path: &Path, - ) -> Result { - Self::check_directory_at(lock_dir, lock_dir_perms)?; - let _guard = Self::acquire_guard(guard_path)?; - for _ in 0..STALE_LOCK_REPLACE_ATTEMPTS { - if Self::create_lock(lock_path, lock_dir, operation)? { - return Ok(Self { - lock_path: lock_path.to_path_buf(), - }); - } - - let metadata = match Self::read_lock_metadata(lock_path) { - Ok(metadata) => metadata, - Err(err) if Self::is_not_found_error(&err) => continue, - Err(err) => { - return Err(Error::msg(format!( - "{LOCK_CONTENTION_CODE}: The LibreQoS overrides files are locked by another process (lock metadata unreadable: {err})." - ))); - } - }; - if Self::is_lock_valid(&metadata) { - return Err(Error::msg(format!( - "{LOCK_CONTENTION_CODE}: The LibreQoS overrides files are locked by another process ({}).", - metadata.describe_holder() - ))); - } - - match remove_file(lock_path) { - Ok(()) => {} - Err(err) if err.kind() == ErrorKind::NotFound => {} - Err(err) => return Err(err.into()), - } - } - - Err(Error::msg( - "Unable to acquire the LibreQoS overrides lock after replacing a stale lock.", - )) + let config = lock_config(operation); + Self::new_with_config(&config) } - fn acquire_guard(guard_path: &Path) -> Result { - let file = OpenOptions::new() - .read(true) - .write(true) - .create(true) - .truncate(false) - .open(guard_path)?; - let unix_path = CString::new(guard_path.to_string_lossy().as_bytes())?; - unsafe { - nix::libc::chmod(unix_path.as_ptr(), mode_t::from_le(0o666)); - } - let ret = unsafe { nix::libc::flock(file.as_raw_fd(), nix::libc::LOCK_EX) }; - if ret == 0 { - Ok(AcquisitionGuard { file }) - } else { - Err(Error::msg(format!( - "Unable to acquire LibreQoS overrides lock guard: {}", - Errno::last() - ))) - } - } - - fn read_lock_metadata(lock_path: &Path) -> Result { - let mut f = File::open(lock_path)?; - let mut contents = String::new(); - f.read_to_string(&mut contents)?; - LockMetadata::parse(&contents) - } - - fn is_not_found_error(err: &Error) -> bool { - err.downcast_ref::() - .is_some_and(|io_err| io_err.kind() == ErrorKind::NotFound) - } - - fn is_lock_valid(metadata: &LockMetadata) -> bool { - let ret = unsafe { nix::libc::kill(metadata.pid, 0) }; - if ret == 0 { - return true; - } - let err = Errno::last(); - err != Errno::ESRCH - } - - fn create_lock(lock_path: &Path, lock_dir: &Path, operation: &str) -> Result { - let metadata = LockMetadata::current(operation); - let (mut f, temp_path) = Self::create_temp_lock_file(lock_dir)?; - f.write_all(metadata.serialize().as_bytes())?; - f.sync_all()?; - drop(f); - let link_result = hard_link(&temp_path, lock_path); - let _ = remove_file(&temp_path); - match link_result { - Ok(()) => {} - Err(err) if err.kind() == ErrorKind::AlreadyExists => return Ok(false), - Err(err) => return Err(err.into()), - } - let unix_path = CString::new(lock_path.to_string_lossy().as_bytes())?; - unsafe { - nix::libc::chmod(unix_path.as_ptr(), mode_t::from_le(0o666)); - } - Ok(true) - } - - fn create_temp_lock_file(lock_dir: &Path) -> Result<(File, PathBuf)> { - let nanos = SystemTime::now() - .duration_since(UNIX_EPOCH) - .ok() - .map(|duration| duration.as_nanos()) - .unwrap_or_default(); - for _ in 0..LOCK_TEMP_CREATE_ATTEMPTS { - let sequence = TEMP_LOCK_SEQUENCE.fetch_add(1, Ordering::Relaxed); - let temp_path = lock_dir.join(format!( - ".lqos_overrides.lock.{}.{}.{}.tmp", - std::process::id(), - nanos, - sequence - )); - match OpenOptions::new() - .write(true) - .create_new(true) - .open(&temp_path) - { - Ok(file) => return Ok((file, temp_path)), - Err(err) if err.kind() == ErrorKind::AlreadyExists => continue, - Err(err) => return Err(err.into()), - } - } - - Err(Error::msg(format!( - "Unable to create a unique temporary LibreQoS overrides lock file after {LOCK_TEMP_CREATE_ATTEMPTS} attempts." - ))) - } - - fn check_directory_at(lock_dir: &Path, lock_dir_perms: &Path) -> Result<()> { - if lock_dir.exists() && lock_dir.is_dir() { - Ok(()) - } else { - std::fs::create_dir(lock_dir)?; - let unix_path = CString::new(lock_dir_perms.to_string_lossy().as_bytes())?; - unsafe { - nix::libc::chmod(unix_path.as_ptr(), 0o777); - } - Ok(()) - } - } -} - -impl Drop for FileLock { - fn drop(&mut self) { - let _ = remove_file(&self.lock_path); + fn new_with_config(config: &ProcessLockConfig) -> Result { + let lock = ProcessFileLock::acquire(config)?; + Ok(Self { _lock: lock }) } } -impl Drop for AcquisitionGuard { - fn drop(&mut self) { - let _ = unsafe { nix::libc::flock(self.file.as_raw_fd(), nix::libc::LOCK_UN) }; +fn lock_config(operation: &str) -> ProcessLockConfig { + #[cfg(test)] + if let Some(config) = TEST_LOCK_CONFIG.with(|config| config.borrow().clone()) { + return config; } -} - -fn current_process_name() -> Option { - std::fs::read_to_string("/proc/self/comm") - .ok() - .and_then(|name| { - let trimmed = sanitize_lock_field(name.trim()); - if trimmed.is_empty() { - None - } else { - Some(trimmed) - } - }) - .or_else(|| { - std::env::args().next().and_then(|arg| { - let trimmed = sanitize_lock_field(&arg); - if trimmed.is_empty() { - None - } else { - Some(trimmed) - } - }) - }) -} -fn sanitize_lock_field(value: &str) -> String { - value - .chars() - .filter(|character| *character != '\n' && *character != '\r') - .collect() + ProcessLockConfig::new( + LOCK_PATH, + LOCK_DIR, + LOCK_GUARD_PATH, + operation, + LOCK_CONTENTION_CODE, + "The LibreQoS overrides file lock", + ) } #[cfg(test)] mod tests { - use super::{FileLock, LockMetadata}; + use super::{ + FileLock, LOCK_CONTENTION_CODE, LOCK_DIR, LOCK_GUARD_PATH, LOCK_PATH, lock_config, + }; + use lqos_utils::process_lock::ProcessLockConfig; use std::{ - fs::{create_dir_all, read_to_string, remove_dir_all, write}, + fs::{read_to_string, remove_dir_all}, path::PathBuf, time::{SystemTime, UNIX_EPOCH}, }; @@ -344,209 +68,74 @@ mod tests { .expect("system clock before UNIX_EPOCH") .as_nanos(); std::env::temp_dir().join(format!( - "lqos-overrides-lock-test-{}-{nanos}", + "libreqos-overrides-lock-test-{}-{nanos}", std::process::id() )) } - #[test] - fn parses_legacy_pid_only_lock_file() { - let metadata = LockMetadata::parse("12345\n").expect("legacy pid lock should parse"); - - assert_eq!(metadata.pid, 12345); - assert_eq!(metadata.process, None); - assert_eq!(metadata.operation, None); - assert_eq!(metadata.created_unix, None); - } - - #[test] - fn parses_metadata_lock_file() { - let metadata = LockMetadata::parse( - "pid=12345\nprocess=lqosd\noperation=load effective overrides\ncreated_unix=1800000000\n", - ) - .expect("metadata lock should parse"); - - assert_eq!(metadata.pid, 12345); - assert_eq!(metadata.process.as_deref(), Some("lqosd")); - assert_eq!( - metadata.operation.as_deref(), - Some("load effective overrides") - ); - assert_eq!(metadata.created_unix, Some(1_800_000_000)); - } - - #[test] - fn holder_description_includes_available_metadata() { - let metadata = LockMetadata::parse( - "pid=12345\nprocess=node_manager\noperation=save overrides\ncreated_unix=1800000000\n", + fn test_config_for(dir: &std::path::Path, operation: &str) -> ProcessLockConfig { + ProcessLockConfig::new( + dir.join("lqos_overrides.lock"), + dir, + dir.join("lqos_overrides.lock.guard"), + operation, + LOCK_CONTENTION_CODE, + "The LibreQoS overrides file lock", ) - .expect("metadata lock should parse"); - - assert_eq!( - metadata.describe_holder(), - "pid=12345, process=node_manager, operation=save overrides, created_unix=1800000000" - ); } - #[test] - fn lock_file_records_operation_metadata_and_cleans_up_on_drop() { - let dir = unique_test_dir(); - create_dir_all(&dir).expect("failed to create temp test dir"); - let path = dir.join("lqos_overrides.lock"); - - { - let _lock = FileLock::new_at( - "load effective overrides", - &path, - &dir, - &dir, - &dir.join("lqos_overrides.lock.guard"), - ) - .expect("failed to create lock in temp dir"); - let contents = read_to_string(&path).expect("failed to read temp lock"); + struct TestLockConfigGuard; - assert!(contents.contains(&format!("pid={}", std::process::id()))); - assert!(contents.contains("operation=load effective overrides")); - assert!(contents.contains("created_unix=")); + impl TestLockConfigGuard { + fn set(config: ProcessLockConfig) -> Self { + super::TEST_LOCK_CONFIG.with(|stored| { + *stored.borrow_mut() = Some(config); + }); + Self } - - assert!(!path.exists()); - remove_dir_all(&dir).expect("failed to clean up temp test dir"); - } - - #[test] - fn live_lock_error_reports_existing_holder_metadata() { - let dir = unique_test_dir(); - create_dir_all(&dir).expect("failed to create temp test dir"); - let path = dir.join("lqos_overrides.lock"); - write( - &path, - format!( - "pid={}\nprocess=test-holder\noperation=save overrides\ncreated_unix=1800000000\n", - std::process::id() - ), - ) - .expect("failed to write temp lock"); - - let error = FileLock::new_at( - "load effective overrides", - &path, - &dir, - &dir, - &dir.join("lqos_overrides.lock.guard"), - ) - .expect_err("live lock should reject a second holder"); - let message = error.to_string(); - - assert!(message.contains("pid=")); - assert!(message.contains("process=test-holder")); - assert!(message.contains("operation=save overrides")); - assert!(message.contains("created_unix=1800000000")); - - remove_dir_all(&dir).expect("failed to clean up temp test dir"); } - #[test] - fn malformed_lock_file_is_reported_as_lock_contention() { - let dir = unique_test_dir(); - create_dir_all(&dir).expect("failed to create temp test dir"); - let path = dir.join("lqos_overrides.lock"); - write(&path, "pid=").expect("failed to write malformed temp lock"); - - let error = FileLock::new_at( - "load effective overrides", - &path, - &dir, - &dir, - &dir.join("lqos_overrides.lock.guard"), - ) - .expect_err("malformed lock metadata should be reported as contention"); - let message = error.to_string(); - - assert!(message.contains("locked by another process")); - assert!(message.contains("lock metadata unreadable")); - - remove_dir_all(&dir).expect("failed to clean up temp test dir"); - } - - #[test] - fn truncated_metadata_lock_missing_pid_is_reported_as_contention() { - let dir = unique_test_dir(); - create_dir_all(&dir).expect("failed to create temp test dir"); - let path = dir.join("lqos_overrides.lock"); - write( - &path, - "process=test-holder\noperation=save overrides\ncreated_unix=1800000000\n", - ) - .expect("failed to write truncated temp lock"); - - let error = FileLock::new_at( - "load effective overrides", - &path, - &dir, - &dir, - &dir.join("lqos_overrides.lock.guard"), - ) - .expect_err("truncated lock metadata should be reported as contention"); - let message = error.to_string(); - - assert!(message.contains("locked by another process")); - assert!(message.contains("lock metadata unreadable")); - - remove_dir_all(&dir).expect("failed to clean up temp test dir"); + impl Drop for TestLockConfigGuard { + fn drop(&mut self) { + super::TEST_LOCK_CONFIG.with(|stored| { + *stored.borrow_mut() = None; + }); + } } #[test] - fn stale_legacy_lock_is_replaced_with_metadata_lock() { - let dir = unique_test_dir(); - create_dir_all(&dir).expect("failed to create temp test dir"); - let path = dir.join("lqos_overrides.lock"); - write(&path, "2147483647\n").expect("failed to write stale temp lock"); - - { - let _lock = FileLock::new_at( - "load effective overrides", - &path, - &dir, - &dir, - &dir.join("lqos_overrides.lock.guard"), - ) - .expect("stale legacy lock should be replaceable"); - let contents = read_to_string(&path).expect("failed to read temp lock"); - - assert!(contents.contains(&format!("pid={}", std::process::id()))); - assert!(contents.contains("operation=load effective overrides")); - } + fn lock_config_preserves_overrides_contract() { + let config = lock_config("save operator overrides"); - remove_dir_all(&dir).expect("failed to clean up temp test dir"); + assert_eq!(config.lock_path.to_string_lossy(), LOCK_PATH); + assert_eq!(config.lock_dir.to_string_lossy(), LOCK_DIR); + assert_eq!(config.guard_path.to_string_lossy(), LOCK_GUARD_PATH); + assert_eq!(config.operation, "save operator overrides"); + assert_eq!(config.contention_code, LOCK_CONTENTION_CODE); + assert_eq!(config.resource_name, "The LibreQoS overrides file lock"); + assert_eq!(config.valid_process_name_contains, None); + assert!(!config.write_pid_only); + assert!(config.metadata_errors_are_contention); } #[test] - fn stale_structured_lock_is_replaced_with_metadata_lock() { + fn file_lock_new_records_structured_operation_metadata() { let dir = unique_test_dir(); - create_dir_all(&dir).expect("failed to create temp test dir"); let path = dir.join("lqos_overrides.lock"); - write( - &path, - "pid=2147483647\nprocess=old-holder\noperation=save overrides\ncreated_unix=1800000000\n", - ) - .expect("failed to write stale structured temp lock"); + let _config_guard = + TestLockConfigGuard::set(test_config_for(&dir, "save operator overrides")); { - let _lock = FileLock::new_at( - "load effective overrides", - &path, - &dir, - &dir, - &dir.join("lqos_overrides.lock.guard"), - ) - .expect("stale structured lock should be replaceable"); - let contents = read_to_string(&path).expect("failed to read temp lock"); + let _lock = FileLock::new_for_operation("save operator overrides") + .expect("failed to create overrides temp lock"); + let contents = read_to_string(&path).expect("failed to read overrides temp lock"); assert!(contents.contains(&format!("pid={}", std::process::id()))); - assert!(contents.contains("operation=load effective overrides")); + assert!(contents.contains("operation=save operator overrides")); + assert!(contents.contains("created_unix=")); } + assert!(!path.exists()); remove_dir_all(&dir).expect("failed to clean up temp test dir"); } } diff --git a/src/rust/lqos_utils/src/lib.rs b/src/rust/lqos_utils/src/lib.rs index 781a3a41..9eac26d7 100644 --- a/src/rust/lqos_utils/src/lib.rs +++ b/src/rust/lqos_utils/src/lib.rs @@ -18,6 +18,8 @@ pub mod hex_string; /// Utilities for scaling bits and packets to human-readable format pub mod packet_scale; +/// Cross-process PID-file locking helpers. +pub mod process_lock; mod string_table_enum; /// Rolling heatmap data storage for executive summary views. diff --git a/src/rust/lqos_utils/src/process_lock.rs b/src/rust/lqos_utils/src/process_lock.rs new file mode 100644 index 00000000..cfe8e855 --- /dev/null +++ b/src/rust/lqos_utils/src/process_lock.rs @@ -0,0 +1,1062 @@ +//! Cross-process PID-file locking helpers. + +use nix::{ + errno::Errno, + libc::{getpid, mode_t}, +}; +use std::{ + ffi::CString, + fs::{File, OpenOptions, hard_link, remove_file}, + io::{ErrorKind, Read, Write}, + os::{fd::AsRawFd, unix::ffi::OsStrExt}, + path::{Path, PathBuf}, + sync::atomic::{AtomicU64, Ordering}, + time::{SystemTime, UNIX_EPOCH}, +}; +use thiserror::Error; + +const STALE_LOCK_REPLACE_ATTEMPTS: usize = 3; +const LOCK_TEMP_CREATE_ATTEMPTS: usize = 8; + +static TEMP_LOCK_SEQUENCE: AtomicU64 = AtomicU64::new(0); + +/// Error returned while acquiring or inspecting a process lock. +#[derive(Debug, Error)] +pub enum ProcessLockError { + /// The lock file exists and appears to belong to a live process. + #[error("{code}: {message}")] + Contended { + /// Stable machine-readable contention code. + code: &'static str, + /// Human-readable contention detail. + message: String, + }, + /// The lock file is malformed or missing required metadata. + #[error("Invalid process lock metadata in {path}: {source}")] + InvalidMetadata { + /// Lock path whose metadata could not be parsed. + path: PathBuf, + /// Parsing failure source. + source: std::num::ParseIntError, + }, + /// The lock file does not contain a process id. + #[error("Invalid process lock metadata in {path}: missing process id")] + MissingPid { + /// Lock path whose metadata did not contain a process id. + path: PathBuf, + }, + /// The lock file contains a process id that cannot identify one process. + #[error("Invalid process lock metadata in {path}: process id must be positive, got {pid}")] + InvalidPid { + /// Lock path whose metadata contained the invalid process id. + path: PathBuf, + /// Invalid process id value. + pid: i32, + }, + /// A filesystem or operating-system call failed. + #[error("{context}: {source}")] + Io { + /// Operation being attempted when the error occurred. + context: &'static str, + /// Underlying I/O error. + source: std::io::Error, + }, + /// A path could not be represented as a C string for libc calls. + #[error("Path contains an interior NUL byte: {path}")] + InvalidPathCString { + /// Path that could not be converted. + path: PathBuf, + }, + /// The lock could not be acquired after replacing stale metadata. + #[error("{message}")] + AcquisitionFailed { + /// Human-readable acquisition failure detail. + message: String, + }, +} + +impl ProcessLockError { + fn io(context: &'static str, source: std::io::Error) -> Self { + Self::Io { context, source } + } +} + +/// Configuration for acquiring a [`ProcessFileLock`]. +#[derive(Clone, Debug)] +pub struct ProcessLockConfig { + /// Lock file path. + pub lock_path: PathBuf, + /// Directory that contains the lock file. + pub lock_dir: PathBuf, + /// Advisory guard file used to serialize stale-lock replacement. + pub guard_path: PathBuf, + /// Diagnostic operation recorded in the lock file. + pub operation: String, + /// Process names accepted as active holders of this lock. + pub valid_process_name_contains: Option, + /// Whether new lock files should use the legacy PID-only format. + pub write_pid_only: bool, + /// Whether unreadable or malformed metadata should be reported as lock + /// contention. + pub metadata_errors_are_contention: bool, + /// Stable machine-readable contention code. + pub contention_code: &'static str, + /// Human-readable name for the locked resource. + pub resource_name: String, +} + +impl ProcessLockConfig { + /// Creates lock configuration for a lock file under `lock_dir`. + pub fn new( + lock_path: impl Into, + lock_dir: impl Into, + guard_path: impl Into, + operation: impl Into, + contention_code: &'static str, + resource_name: impl Into, + ) -> Self { + Self { + lock_path: lock_path.into(), + lock_dir: lock_dir.into(), + guard_path: guard_path.into(), + operation: operation.into(), + valid_process_name_contains: None, + write_pid_only: false, + metadata_errors_are_contention: true, + contention_code, + resource_name: resource_name.into(), + } + } + + /// Restricts live-lock detection to processes whose command name contains + /// `needle`. + pub fn with_valid_process_name_contains(mut self, needle: impl Into) -> Self { + self.valid_process_name_contains = Some(needle.into()); + self + } + + /// Writes new lock files as a bare PID for compatibility with existing + /// tooling. + pub fn with_pid_only_lock_file(mut self) -> Self { + self.write_pid_only = true; + self + } + + /// Returns malformed metadata as the original acquisition error instead of + /// converting it to contention. + pub fn with_strict_metadata_errors(mut self) -> Self { + self.metadata_errors_are_contention = false; + self + } +} + +/// Cross-process lock represented by an on-disk PID file. +/// +/// The lock writes structured metadata atomically through a temporary file and +/// hard link. Dropping the guard removes the lock file. Acquisition uses a +/// secondary `flock` guard so stale-lock replacement is serialized between +/// competing processes. +#[derive(Debug)] +pub struct ProcessFileLock { + lock_path: PathBuf, +} + +#[derive(Debug)] +struct AcquisitionGuard { + file: File, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +struct LockMetadata { + pid: i32, + process: Option, + operation: Option, + created_unix: Option, +} + +impl LockMetadata { + fn current(operation: &str) -> Self { + Self { + pid: unsafe { getpid() }, + process: current_process_name(), + operation: Some(sanitize_lock_field(operation)), + created_unix: SystemTime::now() + .duration_since(UNIX_EPOCH) + .ok() + .map(|duration| duration.as_secs()), + } + } + + fn parse(contents: &str, path: &Path) -> Result { + let trimmed = contents.trim(); + if let Ok(pid) = trimmed.parse::() { + validate_pid(pid, path)?; + return Ok(Self { + pid, + process: None, + operation: None, + created_unix: None, + }); + } + + let mut pid = None; + let mut process = None; + let mut operation = None; + let mut created_unix = None; + for line in contents.lines() { + let Some((key, value)) = line.split_once('=') else { + continue; + }; + match key.trim() { + "pid" => { + let parsed = value.trim().parse::().map_err(|source| { + ProcessLockError::InvalidMetadata { + path: path.to_path_buf(), + source, + } + })?; + validate_pid(parsed, path)?; + pid = Some(parsed); + } + "process" => process = Some(value.trim().to_string()), + "operation" => { + operation = Some(value.trim().to_string()); + } + "created_unix" => { + created_unix = Some(value.trim().parse::().map_err(|source| { + ProcessLockError::InvalidMetadata { + path: path.to_path_buf(), + source, + } + })?) + } + _ => {} + } + } + + let Some(pid) = pid else { + return Err(ProcessLockError::MissingPid { + path: path.to_path_buf(), + }); + }; + + Ok(Self { + pid, + process, + operation, + created_unix, + }) + } + + fn serialize(&self) -> String { + let process = self.process.as_deref().unwrap_or("unknown"); + let operation = self.operation.as_deref().unwrap_or("unknown"); + let created_unix = self + .created_unix + .map(|seconds| seconds.to_string()) + .unwrap_or_else(|| "unknown".to_string()); + format!( + "pid={}\nprocess={}\noperation={}\ncreated_unix={}\n", + self.pid, process, operation, created_unix + ) + } + + fn describe_holder(&self) -> String { + let mut parts = vec![format!("pid={}", self.pid)]; + if let Some(process) = self.process.as_deref().filter(|value| !value.is_empty()) { + parts.push(format!("process={process}")); + } + if let Some(operation) = self.operation.as_deref().filter(|value| !value.is_empty()) { + parts.push(format!("operation={operation}")); + } + if let Some(created_unix) = self.created_unix { + parts.push(format!("created_unix={created_unix}")); + } + parts.join(", ") + } +} + +impl ProcessFileLock { + /// Acquires a process lock using `config`. + /// + /// This function creates the lock directory when missing, writes the current + /// process metadata to the lock file, and removes stale lock files whose PID + /// no longer belongs to a valid holder. + pub fn acquire(config: &ProcessLockConfig) -> Result { + Self::check_directory(&config.lock_dir)?; + let _guard = Self::acquire_guard(&config.guard_path)?; + for _ in 0..STALE_LOCK_REPLACE_ATTEMPTS { + if Self::create_lock( + &config.lock_path, + &config.lock_dir, + &config.operation, + config.write_pid_only, + )? { + return Ok(Self { + lock_path: config.lock_path.clone(), + }); + } + + let metadata = match Self::read_lock_metadata(&config.lock_path) { + Ok(metadata) => metadata, + Err(ProcessLockError::Io { source, .. }) + if source.kind() == ErrorKind::NotFound => + { + continue; + } + Err(ProcessLockError::InvalidPid { .. }) => { + Self::remove_stale_lock(&config.lock_path)?; + continue; + } + Err(err) if !config.metadata_errors_are_contention => return Err(err), + Err(err) => { + return Err(ProcessLockError::Contended { + code: config.contention_code, + message: format!( + "{} is locked by another process (lock metadata unreadable: {err}).", + config.resource_name + ), + }); + } + }; + if Self::is_lock_valid(&metadata, config.valid_process_name_contains.as_deref()) { + return Err(ProcessLockError::Contended { + code: config.contention_code, + message: format!( + "{} is locked by another process ({}).", + config.resource_name, + metadata.describe_holder() + ), + }); + } + + Self::remove_stale_lock(&config.lock_path)?; + } + + Err(ProcessLockError::AcquisitionFailed { + message: format!( + "Unable to acquire {} after replacing a stale lock.", + config.resource_name + ), + }) + } + + fn acquire_guard(guard_path: &Path) -> Result { + let file = OpenOptions::new() + .read(true) + .write(true) + .create(true) + .truncate(false) + .open(guard_path) + .map_err(|err| ProcessLockError::io("open process lock guard", err))?; + let _ = chmod_path(guard_path, 0o666); + let ret = unsafe { nix::libc::flock(file.as_raw_fd(), nix::libc::LOCK_EX) }; + if ret == 0 { + Ok(AcquisitionGuard { file }) + } else { + Err(ProcessLockError::io( + "acquire process lock guard", + std::io::Error::from_raw_os_error(Errno::last_raw()), + )) + } + } + + fn remove_stale_lock(lock_path: &Path) -> Result<(), ProcessLockError> { + match remove_file(lock_path) { + Ok(()) => Ok(()), + Err(err) if err.kind() == ErrorKind::NotFound => Ok(()), + Err(err) => Err(ProcessLockError::io("remove stale process lock", err)), + } + } + + fn read_lock_metadata(lock_path: &Path) -> Result { + let mut f = File::open(lock_path) + .map_err(|err| ProcessLockError::io("open process lock metadata", err))?; + let mut contents = String::new(); + f.read_to_string(&mut contents) + .map_err(|err| ProcessLockError::io("read process lock metadata", err))?; + LockMetadata::parse(&contents, lock_path) + } + + fn is_lock_valid(metadata: &LockMetadata, process_name_contains: Option<&str>) -> bool { + let ret = unsafe { nix::libc::kill(metadata.pid, 0) }; + if ret != 0 { + return Errno::last() != Errno::ESRCH; + } + + let Some(needle) = process_name_contains else { + return true; + }; + process_name_matches_pid(metadata.pid, needle) + } + + fn create_lock( + lock_path: &Path, + lock_dir: &Path, + operation: &str, + write_pid_only: bool, + ) -> Result { + let (mut f, temp_path) = Self::create_temp_lock_file(lock_dir)?; + let serialized = if write_pid_only { + format!("{}\n", unsafe { getpid() }) + } else { + LockMetadata::current(operation).serialize() + }; + if let Err(err) = f.write_all(serialized.as_bytes()) { + let _ = remove_file(&temp_path); + return Err(ProcessLockError::io("write process lock metadata", err)); + } + if let Err(err) = f.sync_all() { + let _ = remove_file(&temp_path); + return Err(ProcessLockError::io("sync process lock metadata", err)); + } + drop(f); + let link_result = hard_link(&temp_path, lock_path); + let _ = remove_file(&temp_path); + match link_result { + Ok(()) => {} + Err(err) if err.kind() == ErrorKind::AlreadyExists => return Ok(false), + Err(err) => return Err(ProcessLockError::io("link process lock", err)), + } + let _ = chmod_path(lock_path, 0o666); + Ok(true) + } + + fn create_temp_lock_file(lock_dir: &Path) -> Result<(File, PathBuf), ProcessLockError> { + let nanos = SystemTime::now() + .duration_since(UNIX_EPOCH) + .ok() + .map(|duration| duration.as_nanos()) + .unwrap_or_default(); + for _ in 0..LOCK_TEMP_CREATE_ATTEMPTS { + let sequence = TEMP_LOCK_SEQUENCE.fetch_add(1, Ordering::Relaxed); + let temp_path = lock_dir.join(format!( + ".libreqos-process-lock.{}.{}.{}.tmp", + std::process::id(), + nanos, + sequence + )); + match OpenOptions::new() + .write(true) + .create_new(true) + .open(&temp_path) + { + Ok(file) => return Ok((file, temp_path)), + Err(err) if err.kind() == ErrorKind::AlreadyExists => continue, + Err(err) => { + return Err(ProcessLockError::io( + "create temporary process lock file", + err, + )); + } + } + } + + Err(ProcessLockError::AcquisitionFailed { + message: format!( + "Unable to create a unique temporary process lock file after {LOCK_TEMP_CREATE_ATTEMPTS} attempts." + ), + }) + } + + fn check_directory(lock_dir: &Path) -> Result<(), ProcessLockError> { + if lock_dir.exists() && lock_dir.is_dir() { + Ok(()) + } else { + std::fs::create_dir(lock_dir) + .map_err(|err| ProcessLockError::io("create process lock directory", err))?; + let _ = chmod_path(lock_dir, 0o777); + Ok(()) + } + } +} + +impl Drop for ProcessFileLock { + fn drop(&mut self) { + let _ = remove_file(&self.lock_path); + } +} + +impl Drop for AcquisitionGuard { + fn drop(&mut self) { + let _ = unsafe { nix::libc::flock(self.file.as_raw_fd(), nix::libc::LOCK_UN) }; + } +} + +fn chmod_path(path: &Path, mode: mode_t) -> Result<(), ProcessLockError> { + let unix_path = CString::new(path.as_os_str().as_bytes()).map_err(|_| { + ProcessLockError::InvalidPathCString { + path: path.to_path_buf(), + } + })?; + let ret = unsafe { nix::libc::chmod(unix_path.as_ptr(), mode) }; + if ret == 0 { + Ok(()) + } else { + Err(ProcessLockError::io( + "chmod process lock path", + std::io::Error::from_raw_os_error(Errno::last_raw()), + )) + } +} + +fn current_process_name() -> Option { + std::fs::read_to_string("/proc/self/comm") + .ok() + .and_then(|name| non_empty_sanitized(name.trim())) + .or_else(|| { + std::env::args() + .next() + .and_then(|arg| non_empty_sanitized(&arg)) + }) +} + +fn process_name_matches_pid(pid: i32, needle: &str) -> bool { + process_name_matches( + process_argv0_for_pid(pid).as_deref(), + process_comm_for_pid(pid).as_deref(), + needle, + ) +} + +fn process_name_matches(argv0: Option<&str>, comm: Option<&str>, needle: &str) -> bool { + argv0.is_some_and(|name| argv0_name_matches(name, needle)) + || comm.is_some_and(|name| name.contains(needle)) +} + +fn argv0_name_matches(argv0: &str, needle: &str) -> bool { + Path::new(argv0) + .file_name() + .and_then(|name| name.to_str()) + .is_some_and(|name| name.contains(needle)) +} + +fn process_argv0_for_pid(pid: i32) -> Option { + std::fs::read(format!("/proc/{pid}/cmdline")) + .ok() + .and_then(|raw| process_argv0_from_cmdline_bytes(&raw)) +} + +fn process_comm_for_pid(pid: i32) -> Option { + std::fs::read_to_string(format!("/proc/{pid}/comm")) + .ok() + .and_then(|name| non_empty_sanitized(name.trim())) +} + +fn process_argv0_from_cmdline_bytes(raw: &[u8]) -> Option { + raw.split(|byte| *byte == 0) + .next() + .filter(|arg| !arg.is_empty()) + .map(|arg| String::from_utf8_lossy(arg).to_string()) + .and_then(|arg0| non_empty_sanitized(&arg0)) +} + +fn validate_pid(pid: i32, path: &Path) -> Result<(), ProcessLockError> { + if pid > 0 { + Ok(()) + } else { + Err(ProcessLockError::InvalidPid { + path: path.to_path_buf(), + pid, + }) + } +} + +fn non_empty_sanitized(value: &str) -> Option { + let trimmed = sanitize_lock_field(value); + if trimmed.is_empty() { + None + } else { + Some(trimmed) + } +} + +fn sanitize_lock_field(value: &str) -> String { + value + .chars() + .filter(|character| *character != '\n' && *character != '\r') + .collect() +} + +#[cfg(test)] +mod tests { + use super::{ + LockMetadata, ProcessFileLock, ProcessLockConfig, ProcessLockError, + process_argv0_from_cmdline_bytes, process_name_matches, + }; + use std::{ + fs::{create_dir_all, read_to_string, remove_dir_all, write}, + os::unix::ffi::OsStringExt, + path::PathBuf, + sync::mpsc, + thread, + time::{SystemTime, UNIX_EPOCH}, + }; + + fn unique_test_dir() -> PathBuf { + let nanos = SystemTime::now() + .duration_since(UNIX_EPOCH) + .expect("system clock before UNIX_EPOCH") + .as_nanos(); + std::env::temp_dir().join(format!( + "libreqos-process-lock-test-{}-{nanos}", + std::process::id() + )) + } + + fn config_for(dir: &std::path::Path) -> ProcessLockConfig { + ProcessLockConfig::new( + dir.join("test.lock"), + dir, + dir.join("test.lock.guard"), + "load effective overrides", + "TEST_LOCKED", + "Test resource", + ) + } + + fn pid_only_config_for(dir: &std::path::Path) -> ProcessLockConfig { + config_for(dir).with_pid_only_lock_file() + } + + fn unique_non_utf8_test_dir() -> PathBuf { + let nanos = SystemTime::now() + .duration_since(UNIX_EPOCH) + .expect("system clock before UNIX_EPOCH") + .as_nanos(); + let mut bytes = + format!("libreqos-process-lock-test-{}-{nanos}-", std::process::id()).into_bytes(); + bytes.push(0xff); + std::env::temp_dir().join(std::ffi::OsString::from_vec(bytes)) + } + + #[test] + fn parses_legacy_pid_only_lock_file() { + let metadata = LockMetadata::parse("12345\n", std::path::Path::new("test.lock")) + .expect("legacy pid lock should parse"); + + assert_eq!(metadata.pid, 12345); + assert_eq!(metadata.process, None); + assert_eq!(metadata.operation, None); + assert_eq!(metadata.created_unix, None); + } + + #[test] + fn rejects_nonpositive_legacy_pid() { + let error = LockMetadata::parse("0\n", std::path::Path::new("test.lock")) + .expect_err("PID zero should be rejected"); + + assert!(matches!(error, ProcessLockError::InvalidPid { pid: 0, .. })); + } + + #[test] + fn rejects_nonpositive_structured_pid() { + let error = LockMetadata::parse( + "pid=-1\nprocess=old-holder\noperation=save overrides\ncreated_unix=1800000000\n", + std::path::Path::new("test.lock"), + ) + .expect_err("negative PID should be rejected"); + + assert!(matches!( + error, + ProcessLockError::InvalidPid { pid: -1, .. } + )); + } + + #[test] + fn parses_metadata_lock_file() { + let metadata = LockMetadata::parse( + "pid=12345\nprocess=lqosd\noperation=load effective overrides\ncreated_unix=1800000000\n", + std::path::Path::new("test.lock"), + ) + .expect("metadata lock should parse"); + + assert_eq!(metadata.pid, 12345); + assert_eq!(metadata.process.as_deref(), Some("lqosd")); + assert_eq!( + metadata.operation.as_deref(), + Some("load effective overrides") + ); + assert_eq!(metadata.created_unix, Some(1_800_000_000)); + } + + #[test] + fn holder_description_includes_available_metadata() { + let metadata = LockMetadata::parse( + "pid=12345\nprocess=node_manager\noperation=save overrides\ncreated_unix=1800000000\n", + std::path::Path::new("test.lock"), + ) + .expect("metadata lock should parse"); + + assert_eq!( + metadata.describe_holder(), + "pid=12345, process=node_manager, operation=save overrides, created_unix=1800000000" + ); + } + + #[test] + fn lock_file_records_operation_metadata_and_cleans_up_on_drop() { + let dir = unique_test_dir(); + create_dir_all(&dir).expect("failed to create temp test dir"); + let path = dir.join("test.lock"); + + { + let _lock = ProcessFileLock::acquire(&config_for(&dir)) + .expect("failed to create lock in temp dir"); + let contents = read_to_string(&path).expect("failed to read temp lock"); + + assert!(contents.contains(&format!("pid={}", std::process::id()))); + assert!(contents.contains("process=")); + assert!(contents.contains("operation=load effective overrides")); + assert!(contents.contains("created_unix=")); + } + + assert!(!path.exists()); + remove_dir_all(&dir).expect("failed to clean up temp test dir"); + } + + #[test] + fn pid_only_lock_file_preserves_legacy_format() { + let dir = unique_test_dir(); + create_dir_all(&dir).expect("failed to create temp test dir"); + let path = dir.join("test.lock"); + + { + let _lock = ProcessFileLock::acquire(&pid_only_config_for(&dir)) + .expect("failed to create PID-only lock in temp dir"); + let contents = read_to_string(&path).expect("failed to read temp lock"); + + assert_eq!(contents, format!("{}\n", std::process::id())); + } + + assert!(!path.exists()); + remove_dir_all(&dir).expect("failed to clean up temp test dir"); + } + + #[test] + fn lock_acquire_supports_non_utf8_paths() { + let dir = unique_non_utf8_test_dir(); + let path = dir.join("test.lock"); + + { + let _lock = ProcessFileLock::acquire(&config_for(&dir)) + .expect("failed to create lock under non-UTF8 path"); + let contents = read_to_string(&path).expect("failed to read non-UTF8 temp lock"); + + assert!(contents.contains(&format!("pid={}", std::process::id()))); + assert!(contents.contains("operation=load effective overrides")); + } + + assert!(!path.exists()); + remove_dir_all(&dir).expect("failed to clean up temp test dir"); + } + + #[test] + fn live_lock_error_reports_existing_holder_metadata() { + let dir = unique_test_dir(); + create_dir_all(&dir).expect("failed to create temp test dir"); + let path = dir.join("test.lock"); + write( + &path, + format!( + "pid={}\nprocess=test-holder\noperation=save overrides\ncreated_unix=1800000000\n", + std::process::id() + ), + ) + .expect("failed to write temp lock"); + + let error = ProcessFileLock::acquire(&config_for(&dir)) + .expect_err("live lock should reject a second holder"); + let ProcessLockError::Contended { code, message } = error else { + panic!("expected contention error"); + }; + + assert_eq!(code, "TEST_LOCKED"); + assert!(message.contains("pid=")); + assert!(message.contains("process=test-holder")); + assert!(message.contains("operation=save overrides")); + assert!(message.contains("created_unix=1800000000")); + + remove_dir_all(&dir).expect("failed to clean up temp test dir"); + } + + #[test] + fn malformed_lock_file_is_reported_as_lock_contention() { + let dir = unique_test_dir(); + create_dir_all(&dir).expect("failed to create temp test dir"); + let path = dir.join("test.lock"); + write(&path, "pid=").expect("failed to write malformed temp lock"); + + let error = ProcessFileLock::acquire(&config_for(&dir)) + .expect_err("malformed lock metadata should be reported as contention"); + let message = error.to_string(); + + assert!(message.contains("locked by another process")); + assert!(message.contains("lock metadata unreadable")); + + remove_dir_all(&dir).expect("failed to clean up temp test dir"); + } + + #[test] + fn invalid_pid_file_is_treated_as_stale() { + let dir = unique_test_dir(); + create_dir_all(&dir).expect("failed to create temp test dir"); + let path = dir.join("test.lock"); + write(&path, "0\n").expect("failed to write invalid PID temp lock"); + + { + let _lock = ProcessFileLock::acquire(&config_for(&dir)) + .expect("invalid PID metadata should be treated as stale"); + let contents = read_to_string(&path).expect("failed to read temp lock"); + + assert!(contents.contains(&format!("pid={}", std::process::id()))); + assert!(contents.contains("operation=load effective overrides")); + } + + remove_dir_all(&dir).expect("failed to clean up temp test dir"); + } + + #[test] + fn strict_metadata_errors_preserve_parse_failure() { + let dir = unique_test_dir(); + create_dir_all(&dir).expect("failed to create temp test dir"); + let path = dir.join("test.lock"); + write(&path, "pid=").expect("failed to write malformed temp lock"); + + let error = ProcessFileLock::acquire(&config_for(&dir).with_strict_metadata_errors()) + .expect_err("strict metadata errors should not be reported as contention"); + + assert!(matches!(error, ProcessLockError::InvalidMetadata { .. })); + + remove_dir_all(&dir).expect("failed to clean up temp test dir"); + } + + #[test] + fn strict_metadata_errors_preserve_created_unix_parse_failure() { + let dir = unique_test_dir(); + create_dir_all(&dir).expect("failed to create temp test dir"); + let path = dir.join("test.lock"); + write( + &path, + "pid=12345\nprocess=test-holder\noperation=save overrides\ncreated_unix=not-a-number\n", + ) + .expect("failed to write malformed created_unix temp lock"); + + let error = ProcessFileLock::acquire(&config_for(&dir).with_strict_metadata_errors()) + .expect_err("strict metadata errors should preserve created_unix parse failures"); + + assert!(matches!(error, ProcessLockError::InvalidMetadata { .. })); + + remove_dir_all(&dir).expect("failed to clean up temp test dir"); + } + + #[test] + fn strict_metadata_errors_preserve_missing_pid_failure() { + let dir = unique_test_dir(); + create_dir_all(&dir).expect("failed to create temp test dir"); + let path = dir.join("test.lock"); + write( + &path, + "process=test-holder\noperation=save overrides\ncreated_unix=1800000000\n", + ) + .expect("failed to write truncated temp lock"); + + let error = ProcessFileLock::acquire(&config_for(&dir).with_strict_metadata_errors()) + .expect_err("strict metadata errors should preserve missing PID"); + + assert!(matches!(error, ProcessLockError::MissingPid { .. })); + + remove_dir_all(&dir).expect("failed to clean up temp test dir"); + } + + #[test] + fn strict_metadata_errors_still_replace_invalid_pid() { + let dir = unique_test_dir(); + create_dir_all(&dir).expect("failed to create temp test dir"); + let path = dir.join("test.lock"); + write(&path, "-1\n").expect("failed to write invalid PID temp lock"); + + { + let _lock = ProcessFileLock::acquire(&config_for(&dir).with_strict_metadata_errors()) + .expect("strict metadata should still replace invalid PID"); + let contents = read_to_string(&path).expect("failed to read temp lock"); + + assert!(contents.contains(&format!("pid={}", std::process::id()))); + assert!(contents.contains("operation=load effective overrides")); + } + + remove_dir_all(&dir).expect("failed to clean up temp test dir"); + } + + #[test] + fn truncated_metadata_lock_missing_pid_is_reported_as_contention() { + let dir = unique_test_dir(); + create_dir_all(&dir).expect("failed to create temp test dir"); + let path = dir.join("test.lock"); + write( + &path, + "process=test-holder\noperation=save overrides\ncreated_unix=1800000000\n", + ) + .expect("failed to write truncated temp lock"); + + let error = ProcessFileLock::acquire(&config_for(&dir)) + .expect_err("truncated lock metadata should be reported as contention"); + let message = error.to_string(); + + assert!(message.contains("locked by another process")); + assert!(message.contains("lock metadata unreadable")); + + remove_dir_all(&dir).expect("failed to clean up temp test dir"); + } + + #[test] + fn stale_legacy_lock_is_replaced_with_metadata_lock() { + let dir = unique_test_dir(); + create_dir_all(&dir).expect("failed to create temp test dir"); + let path = dir.join("test.lock"); + write(&path, "2147483647\n").expect("failed to write stale temp lock"); + + { + let _lock = ProcessFileLock::acquire(&config_for(&dir)) + .expect("stale legacy lock should be replaceable"); + let contents = read_to_string(&path).expect("failed to read temp lock"); + + assert!(contents.contains(&format!("pid={}", std::process::id()))); + assert!(contents.contains("operation=load effective overrides")); + } + + remove_dir_all(&dir).expect("failed to clean up temp test dir"); + } + + #[test] + fn stale_structured_lock_is_replaced_with_metadata_lock() { + let dir = unique_test_dir(); + create_dir_all(&dir).expect("failed to create temp test dir"); + let path = dir.join("test.lock"); + write( + &path, + "pid=2147483647\nprocess=old-holder\noperation=save overrides\ncreated_unix=1800000000\n", + ) + .expect("failed to write stale structured temp lock"); + + { + let _lock = ProcessFileLock::acquire(&config_for(&dir)) + .expect("stale structured lock should be replaceable"); + let contents = read_to_string(&path).expect("failed to read temp lock"); + + assert!(contents.contains(&format!("pid={}", std::process::id()))); + assert!(contents.contains("operation=load effective overrides")); + } + + remove_dir_all(&dir).expect("failed to clean up temp test dir"); + } + + #[test] + fn guard_blocks_other_acquirers() { + let dir = unique_test_dir(); + create_dir_all(&dir).expect("failed to create temp test dir"); + let guard_path = dir.join("test.lock.guard"); + let primary_guard = + ProcessFileLock::acquire_guard(&guard_path).expect("failed to acquire primary guard"); + let (sender, receiver) = mpsc::channel(); + thread::scope(|scope| { + let sender = sender.clone(); + let guard_path = guard_path.clone(); + let handle = scope.spawn(move || { + let _blocked_guard = ProcessFileLock::acquire_guard(&guard_path) + .expect("failed to acquire secondary guard"); + sender.send(()).expect("failed to send guard status"); + }); + assert!(receiver.try_recv().is_err()); + drop(primary_guard); + receiver.recv().expect("secondary guard did not unblock"); + handle.join().expect("secondary guard thread panicked"); + }); + + remove_dir_all(&dir).expect("failed to clean up temp test dir"); + } + + #[test] + fn process_name_filter_rejects_unrelated_live_holder_as_stale() { + let dir = unique_test_dir(); + create_dir_all(&dir).expect("failed to create temp test dir"); + let path = dir.join("test.lock"); + write(&path, format!("{}\n", std::process::id())).expect("failed to write temp lock"); + + { + let config = config_for(&dir) + .with_valid_process_name_contains("name-that-should-not-match-this-test-process"); + let _lock = ProcessFileLock::acquire(&config) + .expect("unmatched live process name should be treated as stale"); + } + + remove_dir_all(&dir).expect("failed to clean up temp test dir"); + } + + #[test] + fn process_name_filter_accepts_current_process_lookup() { + let dir = unique_test_dir(); + create_dir_all(&dir).expect("failed to create temp test dir"); + let path = dir.join("test.lock"); + write(&path, format!("{}\n", std::process::id())).expect("failed to write temp lock"); + + let current_exe = std::env::current_exe().expect("failed to read current executable path"); + let process_name = current_exe + .file_name() + .and_then(|name| name.to_str()) + .and_then(|name| name.split('-').next()) + .expect("test executable should have a UTF-8 name"); + let config = config_for(&dir).with_valid_process_name_contains(process_name); + let error = ProcessFileLock::acquire(&config) + .expect_err("matched live process name should be treated as contention"); + assert!(matches!(error, ProcessLockError::Contended { .. })); + + remove_dir_all(&dir).expect("failed to clean up temp test dir"); + } + + #[test] + fn process_name_lookup_uses_only_cmdline_argv0() { + let process_name = process_argv0_from_cmdline_bytes( + b"/opt/libreqos/bin/lqosd\0--label\0unrelated-lqosd-marker\0", + ) + .expect("cmdline should expose argv0"); + + assert_eq!(process_name, "/opt/libreqos/bin/lqosd"); + } + + #[test] + fn process_name_lookup_rejects_marker_after_empty_argv0() { + assert_eq!( + process_argv0_from_cmdline_bytes(b"\0--label\0unrelated-lqosd-marker\0"), + None + ); + } + + #[test] + fn process_name_match_accepts_argv0_or_comm() { + assert!(process_name_matches( + Some("/opt/libreqos/bin/lqosd"), + Some("generic-wrapper"), + "lqosd" + )); + assert!(process_name_matches( + Some("generic-wrapper"), + Some("lqosd"), + "lqosd" + )); + assert!(!process_name_matches( + Some("generic-wrapper"), + Some("unrelated"), + "lqosd" + )); + } + + #[test] + fn process_name_match_ignores_argv0_directory_names() { + assert!(!process_name_matches( + Some("/tmp/lqosd-wrapper/custom-daemon"), + Some("unrelated"), + "lqosd" + )); + } +} diff --git a/src/rust/lqosd/src/file_lock.rs b/src/rust/lqosd/src/file_lock.rs index 7fff96a0..cba4eb76 100644 --- a/src/rust/lqosd/src/file_lock.rs +++ b/src/rust/lqosd/src/file_lock.rs @@ -1,93 +1,170 @@ -use anyhow::{Error, Result}; -use nix::libc::{getpid, mode_t}; -use std::{ - ffi::CString, - fs::{File, remove_file}, - io::{Read, Write}, - path::Path, -}; -use sysinfo::System; +use anyhow::Result; +use lqos_utils::process_lock::{ProcessFileLock, ProcessLockConfig}; +#[cfg(test)] +use std::cell::RefCell; const LOCK_PATH: &str = "/run/lqos/lqosd.lock"; const LOCK_DIR: &str = "/run/lqos"; -const LOCK_DIR_PERMS: &str = "/run/lqos"; +const LOCK_GUARD_PATH: &str = "/run/lqos/lqosd.lock.guard"; -pub struct FileLock {} +#[cfg(test)] +thread_local! { + static TEST_LOCK_CONFIG: RefCell> = const { RefCell::new(None) }; +} + +/// Process lock used to prevent multiple `lqosd` instances from running. +/// +/// Dropping this guard removes `/run/lqos/lqosd.lock`. +#[derive(Debug)] +pub struct FileLock { + _lock: ProcessFileLock, +} impl FileLock { + /// Acquires the `lqosd` process lock. + /// + /// A stale lock is replaced unless the recorded PID still belongs to a + /// process whose command name contains `lqosd`. pub fn new() -> Result { - Self::check_directory()?; - let lock_path = Path::new(LOCK_PATH); - if lock_path.exists() { - if Self::is_lock_valid()? { - return Err(Error::msg("lqosd is already running")); - } - - // It's a stale pid, so we need to replace it - Self::create_lock()?; - - Ok(Self {}) - } else { - Self::create_lock()?; - Ok(Self {}) - } + let config = lock_config(); + Self::new_with_config(&config) } - fn is_lock_valid() -> Result { - let mut f = File::open(LOCK_PATH)?; - let mut contents = String::new(); - f.read_to_string(&mut contents)?; - let pid: i32 = contents.parse()?; - - let sys = System::new_all(); - let pid = sysinfo::Pid::from(pid as usize); - if let Some(process) = sys.processes().get(&pid) - && process - .name() - .to_str() - .unwrap_or_default() - .contains("lqosd") - { - return Ok(true); - } - Ok(false) + fn new_with_config(config: &ProcessLockConfig) -> Result { + let lock = ProcessFileLock::acquire(config)?; + Ok(Self { _lock: lock }) } +} - fn create_lock() -> Result<()> { - let pid = unsafe { getpid() }; - let pid_format = format!("{pid}"); - { - let mut f = File::create(LOCK_PATH)?; - f.write_all(pid_format.as_bytes())?; +fn lock_config() -> ProcessLockConfig { + #[cfg(test)] + if let Some(config) = TEST_LOCK_CONFIG.with(|config| config.borrow().clone()) { + return config; + } + + ProcessLockConfig::new( + LOCK_PATH, + LOCK_DIR, + LOCK_GUARD_PATH, + "start lqosd", + "LQOSD_LOCKED", + "lqosd", + ) + .with_valid_process_name_contains("lqosd") + .with_pid_only_lock_file() + .with_strict_metadata_errors() +} + +#[cfg(test)] +mod tests { + use super::{FileLock, LOCK_DIR, LOCK_GUARD_PATH, LOCK_PATH, lock_config}; + use lqos_utils::process_lock::ProcessLockConfig; + use std::{ + fs::{create_dir_all, read_to_string, remove_dir_all, write}, + path::PathBuf, + time::{SystemTime, UNIX_EPOCH}, + }; + + fn unique_test_dir() -> PathBuf { + let nanos = SystemTime::now() + .duration_since(UNIX_EPOCH) + .expect("system clock before UNIX_EPOCH") + .as_nanos(); + std::env::temp_dir().join(format!( + "libreqos-lqosd-lock-test-{}-{nanos}", + std::process::id() + )) + } + + fn test_config_for(dir: &std::path::Path) -> ProcessLockConfig { + ProcessLockConfig::new( + dir.join("lqosd.lock"), + dir, + dir.join("lqosd.lock.guard"), + "start lqosd", + "LQOSD_LOCKED", + "lqosd", + ) + .with_valid_process_name_contains("lqosd") + .with_pid_only_lock_file() + .with_strict_metadata_errors() + } + + struct TestLockConfigGuard; + + impl TestLockConfigGuard { + fn set(config: ProcessLockConfig) -> Self { + super::TEST_LOCK_CONFIG.with(|stored| { + *stored.borrow_mut() = Some(config); + }); + Self } - let unix_path = CString::new(LOCK_PATH)?; - unsafe { - nix::libc::chmod(unix_path.as_ptr(), mode_t::from_le(666)); + } + + impl Drop for TestLockConfigGuard { + fn drop(&mut self) { + super::TEST_LOCK_CONFIG.with(|stored| { + *stored.borrow_mut() = None; + }); } - Ok(()) } - fn check_directory() -> Result<()> { - let dir_path = std::path::Path::new(LOCK_DIR); - if dir_path.exists() && dir_path.is_dir() { - Ok(()) - } else { - std::fs::create_dir(dir_path)?; - let unix_path = CString::new(LOCK_DIR_PERMS)?; - unsafe { - nix::libc::chmod(unix_path.as_ptr(), 777); - } - Ok(()) + #[test] + fn lock_config_preserves_lqosd_contract() { + let config = lock_config(); + + assert_eq!(config.lock_path.to_string_lossy(), LOCK_PATH); + assert_eq!(config.lock_dir.to_string_lossy(), LOCK_DIR); + assert_eq!(config.guard_path.to_string_lossy(), LOCK_GUARD_PATH); + assert_eq!(config.operation, "start lqosd"); + assert_eq!(config.contention_code, "LQOSD_LOCKED"); + assert_eq!(config.resource_name, "lqosd"); + assert_eq!(config.valid_process_name_contains.as_deref(), Some("lqosd")); + assert!(config.write_pid_only); + assert!(!config.metadata_errors_are_contention); + } + + #[test] + fn file_lock_new_preserves_pid_only_lock_format() { + let dir = unique_test_dir(); + let path = dir.join("lqosd.lock"); + let _config_guard = TestLockConfigGuard::set(test_config_for(&dir)); + + { + let _lock = FileLock::new().expect("failed to create lqosd temp lock"); + let contents = read_to_string(&path).expect("failed to read lqosd temp lock"); + + assert_eq!(contents, format!("{}\n", std::process::id())); } + + assert!(!path.exists()); + remove_dir_all(&dir).expect("failed to clean up temp test dir"); } - pub fn remove_lock() { - let _ = remove_file(LOCK_PATH); // Ignore result + #[test] + fn file_lock_new_preserves_strict_metadata_errors() { + let dir = unique_test_dir(); + create_dir_all(&dir).expect("failed to create temp test dir"); + let _config_guard = TestLockConfigGuard::set(test_config_for(&dir)); + write(dir.join("lqosd.lock"), "pid=").expect("failed to write malformed temp lock"); + + let error = FileLock::new().expect_err("malformed lqosd lock should remain a strict error"); + + assert!(error.to_string().contains("Invalid process lock metadata")); + remove_dir_all(&dir).expect("failed to clean up temp test dir"); } -} -impl Drop for FileLock { - fn drop(&mut self) { - Self::remove_lock(); + #[test] + fn file_lock_new_reports_live_lqosd_holder() { + let dir = unique_test_dir(); + create_dir_all(&dir).expect("failed to create temp test dir"); + let _config_guard = TestLockConfigGuard::set(test_config_for(&dir)); + write(dir.join("lqosd.lock"), format!("{}\n", std::process::id())) + .expect("failed to write live-holder temp lock"); + + let error = FileLock::new().expect_err("live lqosd lock should reject a second holder"); + + assert!(error.to_string().contains("LQOSD_LOCKED")); + remove_dir_all(&dir).expect("failed to clean up temp test dir"); } } -- knotmirror 0.0.1