From b0122aae25dc56039f659ab3fba5b0f58286bf75 Mon Sep 17 00:00:00 2001 From: OzzyHelper <346962152+OzzyHelper@users.noreply.github.com> Date: Thu, 19 Nov 2026 16:51:17 +0000 Subject: [PATCH] fix: make port allocation conflict-safe and overflow-free - PortAllocator stores the inclusive end port instead of a count, so no code path computes start + count (which overflowed u16 for ranges ending at 65535 and panicked in debug builds). - allocate() now probes the host and skips ports that are already bound, instead of handing out ports another process owns. - is_port_available probes the wildcard address Docker binds and treats port 0 as unavailable. - Range setup is one shared helper; the parallel executor no longer fails when the Portainer port is outside the configured range. - Config::validate rejects empty, port-0, and overflowing ranges. - Curio re-checks its published ports right before container create. --- src/commands/start/curio/constants.rs | 7 ++ src/commands/start/curio/daemon.rs | 78 +++++++----- src/commands/start/curio/pre_execute.rs | 16 +-- src/commands/start/step/mod.rs | 83 +++++-------- src/config.rs | 42 +++++++ src/docker/core.rs | 43 ++++++- src/port_allocator.rs | 159 ++++++++++++++++-------- 7 files changed, 282 insertions(+), 146 deletions(-) diff --git a/src/commands/start/curio/constants.rs b/src/commands/start/curio/constants.rs index b735012c..bcc537c2 100644 --- a/src/commands/start/curio/constants.rs +++ b/src/commands/start/curio/constants.rs @@ -3,6 +3,13 @@ /// Curio Web RPC API port pub const CURIO_WEB_RPC_PORT: u16 = 4701; +/// Curio RPC API port inside the container +pub const CURIO_API_CONTAINER_PORT: u16 = 12300; +/// Curio alternate RPC API port inside the container +pub const CURIO_API_ALT_CONTAINER_PORT: u16 = 12301; +/// Curio PDP layer port inside the container (keep in sync with the [`PDP_LAYER_CONFIG_TEMPLATE`] listen address) +pub const CURIO_PDP_CONTAINER_PORT: u16 = 4702; + /// Curio storage path inside container (fast) pub const CURIO_FAST_STORAGE_PATH: &str = "/home/foc-user/curio/fast-storage"; /// Curio storage path inside container (long-term) diff --git a/src/commands/start/curio/daemon.rs b/src/commands/start/curio/daemon.rs index 059d40ad..ab5e1a9b 100644 --- a/src/commands/start/curio/daemon.rs +++ b/src/commands/start/curio/daemon.rs @@ -6,7 +6,10 @@ use super::super::step::SetupContext; use super::db_setup::{build_db_env_vars, build_foc_contract_env_vars, build_lotus_env_vars}; use super::storage; use super::CurioStep; -use crate::commands::start::curio::constants::CURIO_LAYERS; +use crate::commands::start::curio::constants::{ + CURIO_API_ALT_CONTAINER_PORT, CURIO_API_CONTAINER_PORT, CURIO_LAYERS, CURIO_PDP_CONTAINER_PORT, + CURIO_WEB_RPC_PORT, +}; use crate::docker::command_logger::run_and_log_command_strings; use crate::docker::init::set_volume_ownership; use crate::docker::network::{lotus_network_name, pdp_miner_network_name}; @@ -143,6 +146,16 @@ fn start_curio_container( Ok(container_id) } +/// Read a dynamically allocated port for an SP from the step context. +fn read_port(context: &SetupContext, sp_index: usize, name: &str) -> Result> { + let key = format!("pdp_sp_{}_{}", sp_index, name); + let raw = context + .get(&key) + .ok_or_else(|| format!("Curio port '{}' not found in step context", key))?; + raw.parse() + .map_err(|e| format!("Invalid value '{}' for {}: {}", raw, key, e).into()) +} + /// Build docker create arguments for Curio fn build_docker_create_args( context: &SetupContext, @@ -166,33 +179,42 @@ fn build_docker_create_args( ]; // Port mappings - get dynamically allocated ports from context - let api_port: u16 = context - .get(&format!("pdp_sp_{}_api_port", sp_index)) - .ok_or("Curio API port not found in context")? - .parse()?; - let api_port_alt: u16 = context - .get(&format!("pdp_sp_{}_api_port_alt", sp_index)) - .ok_or("Curio API alt port not found in context")? - .parse()?; - let gui_port: u16 = context - .get(&format!("pdp_sp_{}_gui_port", sp_index)) - .ok_or("Curio GUI port not found in context")? - .parse()?; - let pdp_port: u16 = context - .get(&format!("pdp_sp_{}_pdp_port", sp_index)) - .ok_or("Curio PDP port not found in context")? - .parse()?; - - docker_args.extend_from_slice(&[ - "-p".to_string(), - format!("{}:12300", api_port), - "-p".to_string(), - format!("{}:12301", api_port_alt), - "-p".to_string(), - format!("{}:4701", gui_port), - "-p".to_string(), - format!("{}:4702", pdp_port), - ]); + let host_ports = [ + ( + "API", + read_port(context, sp_index, "api_port")?, + CURIO_API_CONTAINER_PORT, + ), + ( + "API Alt", + read_port(context, sp_index, "api_port_alt")?, + CURIO_API_ALT_CONTAINER_PORT, + ), + ( + "GUI", + read_port(context, sp_index, "gui_port")?, + CURIO_WEB_RPC_PORT, + ), + ( + "PDP", + read_port(context, sp_index, "pdp_port")?, + CURIO_PDP_CONTAINER_PORT, + ), + ]; + + for (label, host_port, container_port) in host_ports { + // Re-check right before create: the ports were allocated in pre-execute, + // which may be minutes earlier while other steps ran. + if !crate::docker::is_port_available(host_port) { + return Err(format!( + "Port {} ({}) for Curio SP {} is no longer available", + host_port, label, sp_index + ) + .into()); + } + docker_args.push("-p".to_string()); + docker_args.push(format!("{}:{}", host_port, container_port)); + } // Validated bind mounts push_bind_mount( diff --git a/src/commands/start/curio/pre_execute.rs b/src/commands/start/curio/pre_execute.rs index 544b3ae5..233ab35b 100644 --- a/src/commands/start/curio/pre_execute.rs +++ b/src/commands/start/curio/pre_execute.rs @@ -64,20 +64,8 @@ pub fn verify_prerequisites(context: &SetupContext, sp_count: usize) -> Result<( pdp_port.to_string(), ); - for (port, desc) in [ - (api_port, "API"), - (api_port_alt, "API Alt"), - (gui_port, "GUI"), - (pdp_port, "PDP"), - ] { - if !crate::docker::is_port_available(port) { - return Err(format!( - "Port {} ({}) for Curio SP {} is already in use", - port, desc, sp_index - ) - .into()); - } - } + // PortAllocator only hands out ports that are free on the host, so no + // separate availability check is needed here. } info!("Prerequisites verified: Lotus is running and producing blocks"); diff --git a/src/commands/start/step/mod.rs b/src/commands/start/step/mod.rs index 7646578b..4ca36fe0 100644 --- a/src/commands/start/step/mod.rs +++ b/src/commands/start/step/mod.rs @@ -293,43 +293,52 @@ pub struct StepExecutionConfig { pub endorsed_pdp_sp_count: usize, } -pub fn execute_steps( - steps: Vec<&dyn Step>, - config: StepExecutionConfig, -) -> Result> { - // Create port allocator and verify all ports are available - let mut port_allocator = PortAllocator::new(config.port_start, config.port_count)?; +/// Build the port allocator for a run and verify the whole range is free. +/// +/// The Portainer port is excluded from the availability check because Portainer +/// was started by us and is already listening inside the range. +fn build_port_allocator( + port_start: u16, + port_count: u16, + portainer_port: Option, +) -> Result> { + let mut allocator = PortAllocator::new(port_start, port_count)?; + let (range_start, range_end) = allocator.range(); info!( "Port range check: {}-{} ({} ports)", - config.port_start, - config.port_start + config.port_count - 1, - config.port_count + range_start, range_end, port_count ); - // If Portainer is using a port in our range, we don't want to fail the availability check - // because Portainer is already running (started by us). - // So we verify all ports EXCEPT the portainer port if it's in range. - for port in config.port_start..(config.port_start + config.port_count) { - if let Some(p_port) = config.portainer_port { - if port == p_port { - continue; - } + for port in range_start..=range_end { + if portainer_port == Some(port) { + continue; } + // Fail fast so we don't start containers whose host ports are taken. if !crate::docker::core::is_port_available(port) { - // Check port availability directly to ensure no conflicts before starting containers return Err(format!("Port {} is already in use", port).into()); } } info!("All ports in range are available"); - // If Portainer port was provided, mark it as allocated in our allocator - if let Some(p_port) = config.portainer_port { - if p_port >= config.port_start && p_port < (config.port_start + config.port_count) { - port_allocator.mark_allocated(p_port)?; + // Reserve the Portainer port so steps never allocate it again. Ports outside + // the range are ignored: Portainer may itself have been given one. + if let Some(port) = portainer_port { + if (range_start..=range_end).contains(&port) { + allocator.mark_allocated(port)?; } } + Ok(allocator) +} + +pub fn execute_steps( + steps: Vec<&dyn Step>, + config: StepExecutionConfig, +) -> Result> { + let port_allocator = + build_port_allocator(config.port_start, config.port_count, config.portainer_port)?; + let context = SetupContext::with_run_id_and_ports(config.run_id, config.run_dir, port_allocator); @@ -392,34 +401,8 @@ pub fn execute_steps_parallel( step_epochs: Vec>, config: StepExecutionConfig, ) -> Result> { - // Create port allocator and verify all ports are available - let mut port_allocator = PortAllocator::new(config.port_start, config.port_count)?; - - info!( - "Port range check: {}-{} ({} ports)", - config.port_start, - config.port_start + config.port_count - 1, - config.port_count - ); - - // If Portainer is using a port in our range, we don't want to fail the availability check - // because Portainer is already running (started by us). - for port in config.port_start..(config.port_start + config.port_count) { - if let Some(p_port) = config.portainer_port { - if port == p_port { - continue; - } - } - if !crate::docker::core::is_port_available(port) { - return Err(format!("Port {} is already in use", port).into()); - } - } - info!("✓ All ports in range are available"); - - // Mark portainer port as allocated if provided - if let Some(port) = config.portainer_port { - port_allocator.mark_allocated(port)?; - } + let port_allocator = + build_port_allocator(config.port_start, config.port_count, config.portainer_port)?; let context = Arc::new(SetupContext::with_run_id_and_ports( config.run_id, diff --git a/src/config.rs b/src/config.rs index 3101dd6a..f31fb9c3 100644 --- a/src/config.rs +++ b/src/config.rs @@ -311,9 +311,14 @@ impl Config { /// /// Ensures that: /// - ENDORSED_PDP_SP_COUNT <= APPROVED_PDP_SP_COUNT <= ACTIVE_PDP_SP_COUNT <= MAX_PDP_SP_COUNT + /// - the port range is non-empty, does not include port 0, and fits in u16 pub fn validate(&self) -> Result<(), String> { const MAX_PDP_SP_COUNT: usize = crate::constants::MAX_PDP_SP_COUNT; + // Reuse the allocator's constructor so the range rules live in one place. + crate::port_allocator::PortAllocator::new(self.port_range_start, self.port_range_count) + .map_err(|e| format!("invalid port range: {}", e))?; + if self.endorsed_pdp_sp_count > self.approved_pdp_sp_count { return Err(format!( "endorsed_pdp_sp_count ({}) cannot exceed approved_pdp_sp_count ({})", @@ -492,4 +497,41 @@ mod tests { assert!(serialized.contains("pdp")); assert!(serialized.contains("https://github.com/FilOzone/pdp.git")); } + + #[test] + fn default_config_validates() { + assert!(Config::default().validate().is_ok()); + } + + #[test] + fn empty_port_range_is_rejected() { + let config = Config { + port_range_count: 0, + ..Default::default() + }; + let err = config.validate().unwrap_err(); + assert!(err.contains("port range"), "unexpected error: {}", err); + } + + #[test] + fn overflowing_port_range_is_rejected() { + // 65500 + 100 - 1 = 65599 does not fit in u16. + let config = Config { + port_range_start: 65500, + port_range_count: 100, + ..Default::default() + }; + let err = config.validate().unwrap_err(); + assert!(err.contains("port range"), "unexpected error: {}", err); + } + + #[test] + fn range_ending_at_max_port_is_accepted() { + let config = Config { + port_range_start: 65500, + port_range_count: 36, + ..Default::default() + }; + assert!(config.validate().is_ok()); + } } diff --git a/src/docker/core.rs b/src/docker/core.rs index a8d0f1f2..0827db25 100644 --- a/src/docker/core.rs +++ b/src/docker/core.rs @@ -82,8 +82,20 @@ pub fn get_container_logs(container_name: &str) -> Result } /// Check if a port is available (not in use) +/// +/// Docker publishes ports on all interfaces, so a listener bound to any host +/// address makes the port unusable. Probe the wildcard address as well as +/// loopback so that services bound to a specific non-loopback interface are +/// detected too. Port 0 is never a usable service port (bind picks an +/// ephemeral port instead), so it always reports unavailable. pub fn is_port_available(port: u16) -> bool { - TcpListener::bind(format!("127.0.0.1:{}", port)).is_ok() + if port == 0 { + return false; + } + ["0.0.0.0", "127.0.0.1"].iter().all(|addr| { + // The listener is dropped immediately, releasing the probe bind. + TcpListener::bind((*addr, port)).is_ok() + }) } /// Check if a Docker image exists locally. @@ -243,3 +255,32 @@ pub fn chown_command(args: &[&str]) -> Result> { command.args(args); command.output().map_err(|e| e.into()) } + +#[cfg(test)] +mod tests { + use super::is_port_available; + use std::net::TcpListener; + + #[test] + fn test_port_zero_is_never_available() { + assert!(!is_port_available(0)); + } + + #[test] + fn test_listener_on_loopback_marks_port_unavailable() { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + assert!(!is_port_available(port)); + } + + #[test] + fn test_free_port_is_available() { + // Bind an ephemeral port, learn its number, then release it. + let port = TcpListener::bind("127.0.0.1:0") + .unwrap() + .local_addr() + .unwrap() + .port(); + assert!(is_port_available(port)); + } +} diff --git a/src/port_allocator.rs b/src/port_allocator.rs index 661a76f1..9d89731d 100644 --- a/src/port_allocator.rs +++ b/src/port_allocator.rs @@ -7,19 +7,24 @@ use std::collections::HashSet; use std::error::Error; -use std::net::TcpListener; + +use crate::docker::core::is_port_available; /// Manages dynamic allocation of ports from a contiguous range. /// /// The allocator tracks which ports have been assigned and ensures -/// that each allocation is unique and within the configured range. +/// that each allocation is unique, within the configured range, and +/// actually free on the host at allocation time. #[derive(Debug)] pub struct PortAllocator { /// Starting port of the range start: u16, - /// Total number of ports in the range - count: u16, + /// Last (inclusive) port of the range. + /// + /// Stored instead of a count so that no code path has to compute + /// `start + count`, which would overflow u16 for ranges ending at 65535. + end: u16, /// Set of already allocated ports allocated: HashSet, @@ -44,28 +49,41 @@ impl PortAllocator { /// /// Returns an error if: /// - `count` is 0 - /// - The range would overflow u16 (start + count > 65535) + /// - `start` is 0 (port 0 means "pick any port" and cannot be published) + /// - The range would overflow u16 (start + count - 1 > 65535) pub fn new(start: u16, count: u16) -> Result> { if count == 0 { return Err("Port range count must be greater than 0".into()); } - // Check for overflow - let _end = start - .checked_add(count.saturating_sub(1)) + if start == 0 { + return Err("Port range must not start at port 0".into()); + } + + // `count` is non-zero, so `count - 1` is safe; the sum is checked. + let end = start + .checked_add(count - 1) .ok_or("Port range exceeds maximum port number (65535)")?; Ok(Self { start, - count, + end, allocated: HashSet::new(), next: start, }) } + /// Number of ports in the range. + fn size(&self) -> u16 { + // `start >= 1`, so `end - start + 1` can never overflow. + self.end - self.start + 1 + } + /// Allocate a single port from the range. /// /// This method finds the next available port in the range and marks it as allocated. + /// Ports already bound on the host are skipped (and permanently marked allocated) so + /// that the allocator never hands out a port that is in use by another process. /// /// # Returns /// @@ -73,33 +91,48 @@ impl PortAllocator { /// /// # Errors /// - /// Returns an error if all ports in the range have been allocated. + /// Returns an error if all ports in the range are already allocated or in use. pub fn allocate(&mut self) -> Result> { - // Try to find an available port starting from `next` - let end = self.start + self.count; + let mut in_use = Vec::new(); - for _ in 0..self.count { + for _ in 0..self.size() { let port = self.next; - // Advance next port (wrap around if needed) - self.next += 1; - if self.next >= end { - self.next = self.start; - } + // Advance next port (wrap around at the end of the range) + self.next = if port == self.end { + self.start + } else { + port + 1 + }; // Check if this port is already allocated - if !self.allocated.contains(&port) { + if self.allocated.contains(&port) { + continue; + } + + if !is_port_available(port) { + // Reserve it so we neither return it nor retry it on the next call. self.allocated.insert(port); - return Ok(port); + in_use.push(port); + continue; } + + self.allocated.insert(port); + return Ok(port); } - Err(format!( - "No available ports in range {}-{}", - self.start, - self.start + self.count - 1 - ) - .into()) + let mut msg = format!("No available ports in range {}-{}", self.start, self.end); + if !in_use.is_empty() { + msg.push_str(&format!( + " (in use by other processes: {})", + in_use + .iter() + .map(|p| p.to_string()) + .collect::>() + .join(", ") + )); + } + Err(msg.into()) } /// Allocate multiple ports from the range. @@ -121,12 +154,10 @@ impl PortAllocator { /// /// Returns an error if the port is outside the managed range. pub fn mark_allocated(&mut self, port: u16) -> Result<(), Box> { - if port < self.start || port >= self.start + self.count { + if port < self.start || port > self.end { return Err(format!( "Port {} is outside the range {}-{}", - port, - self.start, - self.start + self.count - 1 + port, self.start, self.end ) .into()); } @@ -141,12 +172,12 @@ impl PortAllocator { /// Get the number of remaining available ports. pub fn available_count(&self) -> usize { - self.count as usize - self.allocated.len() + self.size() as usize - self.allocated.len() } - /// Get the port range (start, end). + /// Get the port range (start, end), both inclusive. pub fn range(&self) -> (u16, u16) { - (self.start, self.start + self.count - 1) + (self.start, self.end) } /// Check if all ports in the range are available on the system. @@ -160,7 +191,7 @@ impl PortAllocator { pub fn verify_all_ports_available(&self) -> Result<(), Box> { let mut unavailable_ports = Vec::new(); - for port in self.start..(self.start + self.count) { + for port in self.start..=self.end { if !is_port_available(port) { unavailable_ports.push(port); } @@ -182,19 +213,6 @@ impl PortAllocator { } } -/// Check if a port is available (not in use). -/// -/// # Arguments -/// -/// * `port` - The port number to check -/// -/// # Returns -/// -/// `true` if the port is available, `false` if it's in use. -fn is_port_available(port: u16) -> bool { - TcpListener::bind(format!("127.0.0.1:{}", port)).is_ok() -} - /// Format a list of ports for display in error messages. /// /// Formats up to 10 ports, showing "... and N more" if there are more. @@ -220,6 +238,7 @@ fn format_port_list(ports: &[u16]) -> String { #[cfg(test)] mod tests { use super::*; + use std::net::TcpListener; #[test] fn test_allocator_creation() { @@ -229,31 +248,33 @@ mod tests { assert_eq!(allocator.allocated_count(), 0); } + // Allocation probes the host, so each allocating test uses its own range + // below the ephemeral port range to stay independent of other tests. #[test] fn test_allocate_single() { - let mut allocator = PortAllocator::new(5700, 10).unwrap(); + let mut allocator = PortAllocator::new(15800, 10).unwrap(); let port1 = allocator.allocate().unwrap(); let port2 = allocator.allocate().unwrap(); - assert_eq!(port1, 5700); - assert_eq!(port2, 5701); + assert_eq!(port1, 15800); + assert_eq!(port2, 15801); assert_eq!(allocator.allocated_count(), 2); assert_eq!(allocator.available_count(), 8); } #[test] fn test_allocate_multiple() { - let mut allocator = PortAllocator::new(5700, 20).unwrap(); + let mut allocator = PortAllocator::new(15820, 20).unwrap(); let ports = allocator.allocate_multiple(5).unwrap(); assert_eq!(ports.len(), 5); - assert_eq!(ports, vec![5700, 5701, 5702, 5703, 5704]); + assert_eq!(ports, vec![15820, 15821, 15822, 15823, 15824]); assert_eq!(allocator.allocated_count(), 5); } #[test] fn test_allocate_exhaustion() { - let mut allocator = PortAllocator::new(5700, 3).unwrap(); + let mut allocator = PortAllocator::new(15850, 3).unwrap(); assert!(allocator.allocate().is_ok()); assert!(allocator.allocate().is_ok()); @@ -268,7 +289,39 @@ mod tests { // Zero count assert!(PortAllocator::new(5700, 0).is_err()); + // Port 0 is not a usable service port + assert!(PortAllocator::new(0, 10).is_err()); + // Overflow assert!(PortAllocator::new(65500, 100).is_err()); } + + #[test] + fn test_range_reaching_max_port() { + // start + (count - 1) == 65535 must be accepted even though + // start + count would overflow u16. + let allocator = PortAllocator::new(65535, 1).unwrap(); + assert_eq!(allocator.range(), (65535, 65535)); + assert_eq!(allocator.available_count(), 1); + + // A large range ending exactly at 65535 also works and wraps correctly. + let allocator = PortAllocator::new(65000, 536).unwrap(); + assert_eq!(allocator.range(), (65000, 65535)); + assert_eq!(allocator.available_count(), 536); + } + + #[test] + fn test_allocate_skips_port_in_use() { + // Prove the allocator never hands out a port another process holds. + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let busy = listener.local_addr().unwrap().port(); + if busy == u16::MAX { + return; // No room for a second port above the busy one. + } + + let mut allocator = PortAllocator::new(busy, 2).unwrap(); + assert_eq!(allocator.allocate().unwrap(), busy + 1); + assert_eq!(allocator.available_count(), 0); + assert!(allocator.allocate().is_err()); + } }