diff options
Diffstat (limited to 'src/sandbox')
| -rw-r--r-- | src/sandbox/agent.rs | 20 | ||||
| -rw-r--r-- | src/sandbox/kata.rs | 42 | ||||
| -rw-r--r-- | src/sandbox/loopback.rs | 14 | ||||
| -rw-r--r-- | src/sandbox/mod.rs | 35 | ||||
| -rw-r--r-- | src/sandbox/remote.rs | 23 | ||||
| -rw-r--r-- | src/sandbox/wire.rs | 7 |
6 files changed, 2 insertions, 139 deletions
diff --git a/src/sandbox/agent.rs b/src/sandbox/agent.rs index d7b841c..e9626f6 100644 --- a/src/sandbox/agent.rs +++ b/src/sandbox/agent.rs @@ -11,16 +11,12 @@ use crossbeam_channel::unbounded; use crate::error::{Error, Result}; use crate::sandbox::wire::{self, Frame}; -/// CLI-shaped arguments for the `sandbox-agent` binary. #[derive(Debug, Clone)] pub struct AgentOptions { pub hub: String, pub token: String, pub profile: String, pub ttl: Duration, - /// The identity the hub knows this sandbox by. A provisioner (Kata CR, - /// containerd run, a test) passes the nonce it registered with the hub; - /// the hello frame carries it back so the rendezvous can be matched. pub agent_id: Option<String>, } @@ -50,8 +46,6 @@ pub fn serve(opts: &AgentOptions) -> Result<()> { let blobs = blob_dir(&agent_id); std::fs::create_dir_all(&blobs)?; - // Shared watchdog state: the reader thread stamps every inbound frame; - // the watchdog exits (killing the child) when the hub goes silent. let last_inbound = Arc::new(Mutex::new(Instant::now())); let child = Arc::new(Mutex::new(None::<u32>)); let alive = Arc::new(AtomicBool::new(true)); @@ -80,7 +74,7 @@ pub fn serve(opts: &AgentOptions) -> Result<()> { loop { let frame = match wire::read_frame(&mut reader) { Ok(Some(f)) => f, - Ok(None) => break, // hub hung up: the lease is over + Ok(None) => break, Err(e) => { outcome = Err(e.into()); break; @@ -99,7 +93,6 @@ pub fn serve(opts: &AgentOptions) -> Result<()> { } } alive.store(false, Ordering::Relaxed); - // Whatever we were running dies with us, always. if let Some(pid) = *child.lock().unwrap() { unsafe { libc::kill(pid as i32, libc::SIGKILL); @@ -109,7 +102,6 @@ pub fn serve(opts: &AgentOptions) -> Result<()> { outcome } -/// Returns true when the agent should stop (Destroy / fatal child loss). fn handle( frame: Frame, writer: &Arc<Mutex<TcpStream>>, @@ -121,8 +113,6 @@ fn handle( Frame::Ping {} => Ok(false), Frame::Put { req, digest, data } => { let bytes = wire::unhex(&data).map_err(io_err)?; - // The agent verifies content-addressing on its side too: a blob - // that does not hash to its name is refused, not staged. if crate::hash::hex(&bytes) != digest { reply(writer, req, Err("put: data does not hash to the claimed digest"))?; return Ok(false); @@ -159,7 +149,6 @@ fn run_child( child: &Arc<Mutex<Option<u32>>>, ) -> Result<()> { let mut argv = argv; - // Expand `blob:<digest>` argv elements, like the loopback backend does. for a in argv.iter_mut() { if let Some(digest) = a.strip_prefix("blob:") { *a = safe_blob_path(blobs, digest)?.display().to_string(); @@ -179,9 +168,6 @@ fn run_child( let mut proc = c.spawn()?; *child.lock().unwrap() = Some(proc.id()); - // Stream both pipes as they fill: readers hand chunks to the frame writer - // over a channel, so a chatty build never blocks on the socket and vice - // versa. let (tx, rx) = unbounded::<(&'static str, Vec<u8>)>(); let mut pipes = Vec::new(); let pipes_spec: [(&'static str, Option<Box<dyn std::io::Read + Send>>); 2] = [ @@ -246,14 +232,10 @@ fn connect_with_retry(hub: &str, for_long: Duration) -> std::result::Result<TcpS } } -/// Blob scratch, removed when the lease ends. fn blob_dir(agent_id: &str) -> PathBuf { std::env::temp_dir().join(format!("aur-{agent_id}-blobs")) } -/// Digests are the only blob names, and they must stay path-safe — the same -/// rule the loopback backend enforces, so a hostile frame cannot escape the -/// blob directory. fn safe_blob_path(blobs: &Path, digest: &str) -> Result<PathBuf> { if digest.is_empty() || digest.len() > 128 diff --git a/src/sandbox/kata.rs b/src/sandbox/kata.rs index 9169f9f..fafe858 100644 --- a/src/sandbox/kata.rs +++ b/src/sandbox/kata.rs @@ -15,9 +15,6 @@ use crate::sandbox::remote::RemoteSandbox; use crate::sandbox::wire::{self, Frame}; use crate::sandbox::{Sandbox, SandboxBackend, SandboxInfo, SandboxSpec}; -/// What any provisioner needs to know to start one sandbox pointed at this -/// hub. `sandbox_id` is the rendezvous nonce: the hub will only lease the -/// connection whose hello carries it back. #[derive(Debug, Clone)] pub struct ProvisionRequest { pub sandbox_id: String, @@ -29,10 +26,7 @@ pub struct ProvisionRequest { } pub trait Provisioner: Send + Sync { - /// Start a sandbox for `req`. Must return quickly; the sandbox dials in - /// asynchronously and `acquire` waits on the dial. fn provision(&self, req: &ProvisionRequest) -> Result<()>; - /// Reclaim a sandbox out of band (TTL would also do it eventually). fn reclaim(&self, sandbox_id: &str) -> Result<()>; fn name(&self) -> &str; } @@ -77,9 +71,6 @@ pub fn sandbox_cr(req: &ProvisionRequest) -> serde_json::Value { } impl K8sSandboxProvisioner { - /// The provisioner an `agent-sandbox` configuration names. Split out so a - /// test can assert the cluster coordinates reach it from a parsed config, - /// and so `shared_for` and any later caller build it the same way. pub fn for_config(cfg: &Config) -> Option<Self> { match &cfg.sandbox { crate::config::Sandbox::AgentSandbox { api, namespace, bearer, .. } => Some(Self { @@ -92,9 +83,6 @@ impl K8sSandboxProvisioner { } } -/// Talks to a Kubernetes API serving an agent-sandbox-style CRD. Real code, -/// exercised only by the gated live tier — this repository's philosophy is -/// that a gated tier is recorded as skipped, never silently absent. pub struct K8sSandboxProvisioner { pub api: String, pub bearer: String, @@ -133,9 +121,6 @@ impl Provisioner for K8sSandboxProvisioner { } } -/// The test/dev provisioner: a real `sandbox-agent` process, no VM. This is -/// what keeps the kata rendezvous and TTL logic under honest test on a -/// machine with neither root nor `/dev/kvm`. pub struct LocalAgentProvisioner { pub bin: PathBuf, children: Mutex<HashMap<String, Child>>, @@ -184,24 +169,11 @@ pub struct KataBackend { token: String, addr: String, provisioner: Arc<dyn Provisioner>, - /// Nonce → the waiting `acquire`. The accept thread routes dial-ins by - /// the `agent_id` the hello frame carries; anything unknown is dropped, - /// because a sandbox the hub did not ask for is a sandbox to not lease. pending: Arc<Mutex<HashMap<String, Sender<TcpStream>>>>, counter: AtomicU64, } impl KataBackend { - /// The one Kata backend this process should use for this configuration. - /// - /// A Kata backend cannot share only its listener the way the plain remote - /// backend does: it routes every dial-in by the nonce in its `Hello` into a - /// map that belongs to it, so two backends on one address would each see half - /// the dial-ins. The whole backend is therefore shared, and binding happens - /// exactly once per distinct configuration. - /// - /// The key is a digest of everything that distinguishes one backend from - /// another, so the tokens are not sitting around in a second place. pub fn shared_for(cfg: &Config) -> Result<Arc<KataBackend>> { let crate::config::Sandbox::AgentSandbox { api, namespace, bearer, image, listen, token, .. } = &cfg.sandbox @@ -227,9 +199,6 @@ impl KataBackend { Ok(backend) } - /// The request a lease turns into, for one nonce. Split out of `acquire` so - /// a test can assert what a *configuration* becomes without a cluster in - /// the loop. pub fn provision_request(&self, spec: &SandboxSpec, id: &str) -> ProvisionRequest { ProvisionRequest { sandbox_id: id.to_string(), @@ -269,8 +238,6 @@ impl KataBackend { }) } - /// Reclaim a sandbox out of band. The TTL would also do this eventually; - /// this is just not making someone else pay for the wait. pub fn reclaim(&self, sandbox_id: &str) -> Result<()> { self.provisioner.reclaim(sandbox_id) } @@ -289,15 +256,11 @@ impl KataBackend { } } -/// Read one hello and route it. A connection that greets with a nonce nobody -/// asked for is dropped unread — the TTL on the provisioner cleans that box -/// up, and the hub never leases a sandbox it did not order. fn route_dial_in( stream: TcpStream, token: &str, pending: &Arc<Mutex<HashMap<String, Sender<TcpStream>>>>, ) { - // Bounded so a box that connects and says nothing cannot park the loop. let _ = stream.set_read_timeout(Some(Duration::from_secs(10))); let mut reader = match stream.try_clone() { Ok(s) => BufReader::new(s), @@ -323,8 +286,6 @@ impl SandboxBackend for KataBackend { self.pending.lock().unwrap().remove(&id); return Err(e); } - // The TTL is the wait bound *and* the sandbox's own deadline: nobody - // dials in by then, and nobody ever will — the box is dying or dead. let stream = match rx.recv_timeout(spec.ttl) { Ok(s) => s, Err(_) => { @@ -378,11 +339,8 @@ mod tests { .iter() .map(|v| v.as_str().unwrap().to_string()) .collect::<Vec<_>>(); - // The rendezvous nonce and the hub coordinates must reach the agent. assert!(args.windows(2).any(|w| w[0] == "--agent-id" && w[1] == "sbx-abc123")); assert!(args.windows(2).any(|w| w[0] == "--hub" && w[1] == "10.0.0.5:9443")); assert!(args.windows(2).any(|w| w[0] == "--token" && w[1] == "t0ken")); } - - } diff --git a/src/sandbox/loopback.rs b/src/sandbox/loopback.rs index 8a3c229..1173562 100644 --- a/src/sandbox/loopback.rs +++ b/src/sandbox/loopback.rs @@ -19,9 +19,6 @@ impl LoopbackBackend { impl SandboxBackend for LoopbackBackend { fn acquire(&self, spec: &SandboxSpec) -> Result<Arc<dyn Sandbox>> { - // The "pool" is this machine: acquire always succeeds, instantly, and - // the TTL is a promise the loopback sandbox does not have to keep - // because there is nothing to leak — the process dies with the hub. let blobs = blob_root(&self.cfg).join(safe_name(&spec.task)); fs::create_dir_all(&blobs)?; Ok(Arc::new(LoopbackSandbox { @@ -55,9 +52,6 @@ impl Sandbox for LoopbackSandbox { if cmd.argv.is_empty() { return Err(Error::invalid("sandbox command has no argv[0]")); } - // Expand `blob:<digest>` argv elements to the staged blob's path — - // the loopback sandbox's blob dir is "inside the sandbox" as much as - // anything here is. An unstaged blob is a caller bug and fails closed. let mut argv: Vec<String> = Vec::with_capacity(cmd.argv.len()); for a in &cmd.argv { match a.strip_prefix("blob:") { @@ -79,8 +73,6 @@ impl Sandbox for LoopbackSandbox { if let Some(dir) = &cmd.cwd { c.current_dir(dir); } - // The shim protocol lives here, not in the steps: a step that cannot - // tell loopback from a remote sandbox is the property under test. self.cfg.child_env(&mut c); let out = c.output()?; on_log(&out.stdout); @@ -101,16 +93,11 @@ impl Sandbox for LoopbackSandbox { } fn destroy(&self) -> Result<()> { - // Nothing to reclaim: the sandbox is this process. Blob scratch is - // disposable staging and falls to `gc` like the rest of `staging/`. Ok(()) } } impl LoopbackSandbox { - /// Digests double as blob filenames, so they must be path-safe. The digests - /// this codebase produces are hex or `hex-sig`; anything else is a caller - /// bug (or, later, a hostile sandbox) and fails closed. fn blob_path(&self, digest: &str) -> Result<PathBuf> { if digest.is_empty() || digest.len() > 128 { return Err(Error::invalid(format!("blob digest {digest:?} is not usable"))); @@ -126,7 +113,6 @@ fn blob_root(cfg: &Config) -> PathBuf { cfg.staging_dir().join("blobs") } -/// Filesystem-safe name for a task id, same spirit as `config::slug`. fn safe_name(s: &str) -> String { s.chars() .map(|c| if c.is_ascii_alphanumeric() { c.to_ascii_lowercase() } else { '-' }) diff --git a/src/sandbox/mod.rs b/src/sandbox/mod.rs index ea3e126..3bd4b3b 100644 --- a/src/sandbox/mod.rs +++ b/src/sandbox/mod.rs @@ -16,14 +16,6 @@ pub mod loopback; pub mod remote; pub mod wire; -/// A command to run inside a sandbox. Deliberately argv-shaped, never -/// shell-shaped: a remote sandbox must not be handed a shell string. The -/// environment is the backend's business (see `Config::child_env`). -/// -/// An argv element of the form `blob:<digest>` names a blob staged with -/// [`Sandbox::put`]; the backend expands it to wherever the blob materializes -/// inside the sandbox. Callers never name sandbox-local paths, which is what -/// keeps a loopback step byte-identical to a remote one. #[derive(Debug, Clone)] pub struct Cmd { pub argv: Vec<String>, @@ -47,7 +39,6 @@ impl Cmd { } } -/// A finished command. `code` is `None` when the child died by signal. #[derive(Debug)] pub struct Exit { pub code: Option<i32>, @@ -61,10 +52,6 @@ impl Exit { } } -/// What a caller asks the pool for. `profile` is the only affinity key warm -/// pools need today (§8.3); `ttl` is the guarantee that the sandbox is dead no -/// matter what this process then does; `disk_mb` replaces the hub's local -/// disk-headroom check (§8.2) once builds leave the hub's filesystem. #[derive(Debug, Clone)] pub struct SandboxSpec { pub profile: String, @@ -79,7 +66,6 @@ impl SandboxSpec { } } -/// Pool state for the UI and notices. #[derive(Debug, Clone)] pub struct SandboxInfo { pub id: String, @@ -87,32 +73,19 @@ pub struct SandboxInfo { pub warm: bool, } -/// A leased sandbox. `run` streams output through `on_log` as it arrives and -/// also returns it captured, so a step can parse stdout while the build log -/// stays complete. `put`/`get` move content-addressed blobs and never accept a -/// destination path from a sandbox — the same I9 posture the local staging -/// containment checks enforce. pub trait Sandbox: Send + Sync { fn id(&self) -> &str; fn run(&self, cmd: &Cmd, on_log: &mut dyn FnMut(&[u8])) -> Result<Exit>; fn put(&self, digest: &str, r: &mut dyn Read) -> Result<()>; fn get(&self, digest: &str) -> Result<Box<dyn Read>>; - /// Idempotent, and also happens by itself when the TTL bites. fn destroy(&self) -> Result<()>; } -/// The pool. `acquire` may return a pre-warmed sandbox, cold-start one, or fail -/// when at quota; a failed acquire is a blocked build, not a broken one. 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. -/// -/// `Config::validate` runs here as well as at startup: a guard that only exists -/// in the CLI is a guard a test or a future daemon can walk past. An unknown or -/// unwired kind is an error, never a fallthrough. pub fn backend_for(cfg: &Config) -> Result<Arc<dyn SandboxBackend>> { cfg.validate()?; match &cfg.sandbox { @@ -127,20 +100,12 @@ pub fn backend_for(cfg: &Config) -> Result<Arc<dyn SandboxBackend>> { } } -/// A listener shared by every backend built from the same `(addr, token)`. #[derive(Clone)] pub(crate) struct Bound { pub local: String, pub rx: Receiver<TcpStream>, } -/// One bound listener per `(address, token)` per process. -/// -/// The listener belongs to the process, not to a build: binding it per build -/// meant a second concurrent build hit `EADDRINUSE` for a reason unrelated to -/// its package. The token is part of the key because two different tokens -/// cannot share a listener, and silently reusing the first one's listener would -/// be a fail-open surprise. pub(crate) fn bound_listener(addr: &str, token: &str) -> Result<Bound> { static REGISTRY: OnceLock<Mutex<HashMap<(String, String), Bound>>> = OnceLock::new(); let registry = REGISTRY.get_or_init(|| Mutex::new(HashMap::new())); diff --git a/src/sandbox/remote.rs b/src/sandbox/remote.rs index 1f9514f..ba70155 100644 --- a/src/sandbox/remote.rs +++ b/src/sandbox/remote.rs @@ -13,17 +13,10 @@ pub struct RemoteBackend { cfg: Config, token: String, addr: String, - /// Connections the accept thread has taken off the listener but not yet - /// rendezvoused. `acquire` waits on this up to the spec's TTL. queue: Receiver<std::net::TcpStream>, } impl RemoteBackend { - /// Bind the agent listener — or share the one this process already bound for - /// the same `(addr, token)`; see [`crate::sandbox::bound_listener`]. `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 bound = super::bound_listener(addr, token)?; Ok(Self { cfg: cfg.clone(), token: token.to_string(), addr: bound.local, queue: bound.rx }) @@ -42,8 +35,6 @@ impl SandboxBackend for RemoteBackend { self.addr )) })?; - // The rendezvous itself is bounded; the run loop is not (pings keep - // the agent's watchdog fed, and a dead agent fails the step anyway). let _ = stream.set_read_timeout(Some(spec.ttl)); let mut reader = BufReader::new(stream.try_clone()?); let agent_id = match wire::read_frame(&mut reader)? { @@ -90,9 +81,6 @@ pub struct RemoteSandbox { } impl RemoteSandbox { - /// Wrap a stream whose `Hello` has been verified and answered. Split out - /// so the kata backend can lease a rendezvoused connection with its own - /// accept loop without duplicating the sandbox half. pub(crate) fn after_hello(cfg: &Config, stream: std::net::TcpStream, agent_id: String, ttl: std::time::Duration) -> Self { let reader = BufReader::new( stream.try_clone().expect("cloning a connected tcp stream cannot fail"), @@ -111,9 +99,6 @@ impl RemoteSandbox { wire::write_frame(&mut *self.writer.lock().unwrap(), frame).map_err(Into::into) } - /// Read frames until a reply for `req` arrives. `Log` frames for that - /// request are handed to `sink` (stream name + bytes) as they arrive, so - /// the caller gets live streaming *and* can accumulate what it needs. fn pump(&self, req: u64, sink: &mut dyn FnMut(&str, &[u8])) -> Result<Frame> { loop { let frame = match wire::read_frame(&mut *self.reader.lock().unwrap())? { @@ -132,7 +117,7 @@ impl RemoteSandbox { { return Ok(frame) } - _ => {} // Ping echoes and foreign requests are not ours + _ => {} } } } @@ -151,8 +136,6 @@ impl Sandbox for RemoteSandbox { cwd: cmd.cwd.as_ref().map(|p| p.display().to_string()), env: self.cfg.child_env_pairs(), })?; - // Keepalive: the agent's watchdog expects a frame at least every TTL; - // a long build produces none of its own on the control connection. let stop = Arc::new(std::sync::atomic::AtomicBool::new(false)); let mut writer = self.writer.lock().unwrap().try_clone()?; { @@ -172,9 +155,6 @@ impl Sandbox for RemoteSandbox { let mut stdout = Vec::new(); let mut stderr = Vec::new(); let result = self.pump(req, &mut |stream, bytes| { - // The build log gets bytes in arrival order; the captured halves - // keep stdout and stderr apart so error tails name the right one, - // exactly like the loopback sandbox's Exit. on_log(bytes); if stream == "stderr" { stderr.extend_from_slice(bytes); @@ -213,7 +193,6 @@ impl Sandbox for RemoteSandbox { } fn destroy(&self) -> Result<()> { - // Best effort: a sandbox that is already gone has nothing to destroy. let _ = self.send(&Frame::Destroy {}); Ok(()) } diff --git a/src/sandbox/wire.rs b/src/sandbox/wire.rs index 8f03063..a0d06ca 100644 --- a/src/sandbox/wire.rs +++ b/src/sandbox/wire.rs @@ -2,13 +2,8 @@ use std::io::{self, BufRead, Write}; use serde::{Deserialize, Serialize}; -/// Refuse absurd frames before allocating for them. Blobs ride as hex inside -/// the frame, so this bounds a real package at ~2 GiB of hex — far above -/// anything legitimate, far below "accept whatever the sandbox sends". pub const MAX_FRAME_BYTES: u32 = 2 * 1024 * 1024 * 1024; -/// One protocol frame. `req` correlates a reply with a request; unsolicited -/// frames (`Ping`, `Hello`, `HelloAck`) carry none. #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(tag = "t", rename_all = "snake_case")] pub enum Frame { @@ -51,8 +46,6 @@ pub fn write_frame(w: &mut impl Write, f: &Frame) -> io::Result<()> { w.flush() } -/// Read one frame. `Ok(None)` means a clean close, which for a sandbox means -/// the lease expired and the build should requeue. pub fn read_frame(r: &mut impl BufRead) -> io::Result<Option<Frame>> { let mut len = [0u8; 4]; match r.read_exact(&mut len) { |
