diff options
| -rw-r--r-- | src/pipeline/mod.rs | 28 | ||||
| -rw-r--r-- | src/sandbox/mod.rs | 25 | ||||
| -rw-r--r-- | src/sandbox/remote.rs | 73 | ||||
| -rw-r--r-- | tests/remote_agent.rs | 107 |
4 files changed, 190 insertions, 43 deletions
diff --git a/src/pipeline/mod.rs b/src/pipeline/mod.rs index 350df0c..6729605 100644 --- a/src/pipeline/mod.rs +++ b/src/pipeline/mod.rs @@ -171,36 +171,10 @@ impl Ctx { log: cfg.build_log_path(build_id), profile, attempt, - backend: Self::backend_for(cfg)?, + backend: crate::sandbox::backend_for(cfg)?, }) } - /// Which backend a build runs on is configuration, not code: the step - /// machine cannot tell loopback from remote, which is the seam's whole - /// point. `remote` binds the agent listener for the lifetime of this - /// run's context. - fn backend_for(cfg: &Config) -> Result<Arc<dyn SandboxBackend>> { - // The startup guard in the CLI catches this first; repeating it here is - // what makes "the config was never validated" impossible for anything - // that constructs a backend — a test, a future daemon, a tool. - cfg.validate()?; - match &cfg.sandbox { - crate::config::Sandbox::Loopback => { - Ok(Arc::new(crate::sandbox::loopback::LoopbackBackend::new(cfg))) - } - crate::config::Sandbox::Remote { listen, token, .. } => Ok(Arc::new( - crate::sandbox::remote::RemoteBackend::bind(cfg, listen, token)?, - )), - // A valid kind that is not wired up yet is an error, never a - // fallthrough: a build configured for a Kata VM that silently ran - // as the hub's own user is the failure this enum was added to stop. - crate::config::Sandbox::AgentSandbox { .. } => Err(Error::invalid(concat!( - "sandbox kind \"agent-sandbox\" is not wired up yet; refusing to run this build ", - "on a backend it was not configured for", - ))), - } - } - /// Lease a sandbox for this build's profile. Today every step acquires and /// releases around itself; a remote backend will hold one sandbox across /// the sandbox-bearing steps of a build, and steps stay idempotent either diff --git a/src/sandbox/mod.rs b/src/sandbox/mod.rs index b20788d..cdbfa02 100644 --- a/src/sandbox/mod.rs +++ b/src/sandbox/mod.rs @@ -29,6 +29,7 @@ use std::path::PathBuf; use std::sync::Arc; use std::time::Duration; +use crate::config::Config; use crate::error::Result; pub mod agent; @@ -138,3 +139,27 @@ pub trait SandboxBackend: Send + Sync { fn acquire(&self, spec: &SandboxSpec) -> Result<Arc<dyn Sandbox>>; fn status(&self) -> Result<Vec<SandboxInfo>>; } + +/// Turn a configuration into the backend it names — the only place that does, +/// so "which backend" has exactly one answer. +/// +/// `Config::validate` runs here as well as at startup: a guard that only exists +/// in the CLI is a guard a test, a tool, or a future daemon can walk past. +/// And an unknown or unwired kind is an error, never a fallthrough — a build +/// configured for a Kata VM that quietly ran as the hub's own user is the +/// failure this function used to have. +pub fn backend_for(cfg: &Config) -> Result<Arc<dyn SandboxBackend>> { + cfg.validate()?; + match &cfg.sandbox { + crate::config::Sandbox::Loopback => { + Ok(Arc::new(loopback::LoopbackBackend::new(cfg))) + } + crate::config::Sandbox::Remote { listen, token, .. } => { + Ok(Arc::new(remote::RemoteBackend::bind(cfg, listen, token)?)) + } + crate::config::Sandbox::AgentSandbox { .. } => Err(crate::error::Error::invalid(concat!( + "sandbox kind \"agent-sandbox\" is not wired up yet; refusing to run this build ", + "on a backend it was not configured for", + ))), + } +} diff --git a/src/sandbox/remote.rs b/src/sandbox/remote.rs index e68ea0f..96b1ee6 100644 --- a/src/sandbox/remote.rs +++ b/src/sandbox/remote.rs @@ -19,10 +19,11 @@ //! manifest/tar sync from the design sketch; that is deliberately not here //! yet, and nothing should pretend otherwise. +use std::collections::HashMap; use std::io::BufReader; use std::net::TcpListener; use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::{Arc, Mutex}; +use std::sync::{Arc, Mutex, OnceLock}; use crossbeam_channel::Receiver; @@ -40,25 +41,65 @@ pub struct RemoteBackend { queue: Receiver<std::net::TcpStream>, } +/// A listener shared by every backend built from the same `(addr, token)`. +struct Bound { + local: String, + rx: Receiver<std::net::TcpStream>, +} + +/// One bound listener per `(address, token)` per process. +/// +/// The listener is a property of the *process*, not of a build. Binding it per +/// build — which is what happened while `Ctx::new` constructed a backend for +/// every build — meant a second concurrent build hit `EADDRINUSE` on a fixed +/// `listen` and failed for a reason that had nothing to do with its package. +/// Sharing the queue is also exactly the semantics `remote` already has: an +/// agent dials in when the operator boots one, and whichever build is waiting +/// takes it. +/// +/// The token is part of the key on purpose. Two different tokens cannot share a +/// listener, and reusing the first one's listener for a second, different token +/// would be a fail-open surprise; forcing a real bind makes the mistake loud. +fn registry() -> &'static Mutex<HashMap<(String, String), Bound>> { + static REGISTRY: OnceLock<Mutex<HashMap<(String, String), Bound>>> = OnceLock::new(); + REGISTRY.get_or_init(|| Mutex::new(HashMap::new())) +} + +fn bound_listener(addr: &str, token: &str) -> Result<Bound> { + let key = (addr.to_string(), token.to_string()); + // A poisoned registry means a panic in some other thread's bind; the map + // itself is still sound, so recover rather than wedge every later build — + // the same posture as the publish lock. + let mut reg = registry().lock().unwrap_or_else(|p| p.into_inner()); + if let Some(b) = reg.get(&key) { + return Ok(Bound { local: b.local.clone(), rx: b.rx.clone() }); + } + let listener = TcpListener::bind(addr)?; + let local = listener.local_addr()?.to_string(); + let (tx, rx) = crossbeam_channel::unbounded(); + std::thread::spawn(move || { + for stream in listener.incoming() { + match stream { + Ok(s) => { + let _ = tx.send(s); + } + Err(_) => break, + } + } + }); + let bound = Bound { local, rx }; + reg.insert(key, Bound { local: bound.local.clone(), rx: bound.rx.clone() }); + Ok(bound) +} + impl RemoteBackend { - /// Bind the agent listener. `addr` may name port 0; [`Self::local_addr`] + /// Bind the agent listener — or share the one this process already bound for + /// the same `(addr, token)`. `addr` may name port 0; [`Self::local_addr`] /// reports what actually got bound, which is how a test (or a supervisor) /// hands the address to the agent without a port negotiation dance. pub fn bind(cfg: &Config, addr: &str, token: &str) -> Result<Self> { - let listener = TcpListener::bind(addr)?; - let local = listener.local_addr()?.to_string(); - let (tx, rx) = crossbeam_channel::unbounded(); - std::thread::spawn(move || { - for stream in listener.incoming() { - match stream { - Ok(s) => { - let _ = tx.send(s); - } - Err(_) => break, - } - } - }); - Ok(Self { cfg: cfg.clone(), token: token.to_string(), addr: local, queue: rx }) + let bound = bound_listener(addr, token)?; + Ok(Self { cfg: cfg.clone(), token: token.to_string(), addr: bound.local, queue: bound.rx }) } pub fn local_addr(&self) -> &str { diff --git a/tests/remote_agent.rs b/tests/remote_agent.rs index 74a227b..22e803a 100644 --- a/tests/remote_agent.rs +++ b/tests/remote_agent.rs @@ -94,3 +94,110 @@ fn blobs_round_trip_over_the_wire_and_a_bad_token_is_refused() { assert!(err.to_string().contains("token"), "{err}"); let _ = bad.wait(); } + +// --------------------------------------------------------------------------- +// One listener per process. +// +// `Ctx::new` used to construct a backend for every build, and constructing a +// remote backend bound the agent listener. So a second concurrent build on a +// fixed `listen` died of EADDRINUSE — a build failing for a reason that had +// nothing to do with its package. The listener is a property of the process now. +// --------------------------------------------------------------------------- + +fn remote_cfg(listen: &str, token: &str) -> aur_build::config::Config { + aur_build::config::Config { + sandbox: aur_build::config::Sandbox::Remote { + listen: listen.into(), + token: token.into(), + shared_workspace: true, + }, + ..aur_build::config::Config::default() + } +} + +/// A port nothing is holding, so two backends can be asked for the *same* fixed +/// address — which is the only case where double-binding shows up. +fn free_port() -> u16 { + let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let port = l.local_addr().unwrap().port(); + drop(l); + port +} + +#[test] +fn two_builds_share_one_agent_listener() { + let addr = format!("127.0.0.1:{}", free_port()); + let cfg = remote_cfg(&addr, "shared-token"); + let a = aur_build::sandbox::backend_for(&cfg).unwrap(); + let b = aur_build::sandbox::backend_for(&cfg).unwrap(); + let (sa, sb) = (&a.status().unwrap()[0].id, &b.status().unwrap()[0].id); + assert_eq!(sa, sb, "both must report the one listener: {sa} vs {sb}"); + assert!(sa.contains(&addr), "and it must be the configured address: {sa}"); + // Why the sharing matters, asserted rather than assumed: a raw second bind + // on a listening address is EADDRINUSE (Rust binds and listens together, so + // SO_REUSEADDR does not rescue it). If this ever passes, the test above is + // vacuous and the regression it guards is back. + assert!( + std::net::TcpListener::bind(&addr).is_err(), + "a second bind on {addr} must fail, or nothing here proves anything" + ); +} + +/// Sharing the listener means sharing the queue of dial-ins, which is exactly +/// the semantics `remote` already has: an agent dials in when the operator +/// boots one, and whichever build is waiting takes it. +#[test] +fn a_dial_in_goes_to_whichever_backend_is_waiting() { + let addr = format!("127.0.0.1:{}", free_port()); + let cfg = remote_cfg(&addr, "shared-queue"); + let _first = aur_build::sandbox::backend_for(&cfg).unwrap(); + let second = aur_build::sandbox::backend_for(&cfg).unwrap(); + + let mut agent = std::process::Command::new(agent_bin()) + .args(["--hub", &addr, "--token", "shared-queue", "--ttl", "30"]) + .spawn() + .expect("spawn sandbox-agent"); + + let spec = SandboxSpec::new("extra-x86_64", "task", Duration::from_secs(10)); + let sbx = second.acquire(&spec); + let _ = agent.kill(); + assert!(sbx.is_ok(), "the second backend must be able to take the dial-in: {:?}", sbx.err()); +} + +/// Two tokens cannot share a listener, and quietly reusing the first one's would +/// be a fail-open surprise — so the second bind is attempted and fails loudly. +#[test] +fn a_different_token_on_the_same_address_is_refused_not_shared() { + let addr = format!("127.0.0.1:{}", free_port()); + assert!(aur_build::sandbox::backend_for(&remote_cfg(&addr, "one")).is_ok()); + let second = aur_build::sandbox::backend_for(&remote_cfg(&addr, "two")); + assert!(second.is_err(), "two tokens on one address must not silently share a listener"); +} + +/// The contract in its literal shape: two workers, two builds, one listener. +/// Each worker builds a `Ctx`, and building a `Ctx` used to bind the listener — +/// so the second worker's build died of EADDRINUSE before it looked at its +/// package at all. +#[test] +fn two_concurrent_builds_do_not_fight_over_the_listener() { + let addr = format!("127.0.0.1:{}", free_port()); + let (mut env, _fa, _fb) = env_with_two_fixtures("plain-make", "install-hooks"); + env.cfg.max_concurrent_builds = 2; + env.cfg.sandbox = aur_build::config::Sandbox::Remote { + listen: addr.clone(), + token: "concurrent".into(), + shared_workspace: true, + }; + + let mut ids = Vec::new(); + for name in ["plain-make", "install-hooks"] { + let c = approve_fixture(&env, name); + ids.push(pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c).unwrap()); + } + assert_eq!(ids.len(), 2); + + let first = Ctx::new(&env.cfg, &env.db, &ids[0]); + let second = Ctx::new(&env.cfg, &env.db, &ids[1]); + assert!(first.is_ok(), "first build: {:?}", first.err()); + assert!(second.is_ok(), "second concurrent build must not lose the port race"); +} |
