Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions src/commands/start/curio/constants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
78 changes: 50 additions & 28 deletions src/commands/start/curio/daemon.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -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<u16, Box<dyn Error>> {
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,
Expand All @@ -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(
Expand Down
16 changes: 2 additions & 14 deletions src/commands/start/curio/pre_execute.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down
83 changes: 33 additions & 50 deletions src/commands/start/step/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -293,43 +293,52 @@ pub struct StepExecutionConfig {
pub endorsed_pdp_sp_count: usize,
}

pub fn execute_steps(
steps: Vec<&dyn Step>,
config: StepExecutionConfig,
) -> Result<SetupContext, Box<dyn Error>> {
// 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<u16>,
) -> Result<PortAllocator, Box<dyn Error>> {
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<SetupContext, Box<dyn Error>> {
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);

Expand Down Expand Up @@ -392,34 +401,8 @@ pub fn execute_steps_parallel(
step_epochs: Vec<Vec<&dyn Step>>,
config: StepExecutionConfig,
) -> Result<SetupContext, Box<dyn Error>> {
// 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,
Expand Down
42 changes: 42 additions & 0 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 ({})",
Expand Down Expand Up @@ -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());
}
}
43 changes: 42 additions & 1 deletion src/docker/core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,8 +82,20 @@ pub fn get_container_logs(container_name: &str) -> Result<String, Box<dyn Error>
}

/// 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.
Expand Down Expand Up @@ -243,3 +255,32 @@ pub fn chown_command(args: &[&str]) -> Result<Output, Box<dyn Error>> {
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));
}
}
Loading