//! The hub side of the agent protocol: a [`SandboxBackend`] that leases //! sandboxes which dial in from outside. //! //! The rendezvous is outbound-only: `acquire` waits for an agent to connect //! and present the shared token, and every command since then is a frame on //! the connection *the agent initiated*. A sandbox that vanishes mid-run is //! not an error this code invents — a closed connection reads as a failed //! step, which reads as an expired lease, which the reaper already turns into //! a requeue (I5). The remote backend adds no new failure vocabulary. //! //! One connection is one lease: after `destroy` (or a drop of the hub side), //! the agent dies and the next `acquire` waits for a fresh one. That matches //! the disposable-sandbox model — warm pooling across steps of one build is //! a backend optimization, not an interface requirement. //! //! Workspace note: `Run` frames carry a hub-side `cwd`, which is honest for //! loopback-shaped deployments and the test tier where hub and sandbox share //! a filesystem. A remote-over-the-network deployment needs the workspace //! manifest/tar sync from the design sketch; that is deliberately not here //! yet, and nothing should pretend otherwise. use std::io::BufReader; use std::net::TcpListener; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Mutex}; use crossbeam_channel::Receiver; use crate::config::Config; use crate::error::{Error, Result}; use crate::sandbox::wire::{self, Frame}; use crate::sandbox::{Exit, Sandbox, SandboxBackend, SandboxInfo, SandboxSpec}; 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, } impl RemoteBackend { /// Bind the agent 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 { 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 }) } pub fn local_addr(&self) -> &str { &self.addr } } impl SandboxBackend for RemoteBackend { fn acquire(&self, spec: &SandboxSpec) -> Result> { let stream = self.queue.recv_timeout(spec.ttl).map_err(|_| { Error::other(format!( "no sandbox connected to {} within the lease window", 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)? { Some(Frame::Hello { token, agent_id, profiles }) => { if token != self.token { return Err(Error::fail_closed(format!( "sandbox {agent_id} presented the wrong token" ))); } if !profiles.is_empty() && !profiles.contains(&spec.profile) { return Err(Error::fail_closed(format!( "sandbox {agent_id} serves {profiles:?}, not profile {}", spec.profile ))); } agent_id } Some(other) => return Err(Error::invalid(format!("expected hello, got {other:?}"))), None => return Err(Error::other("sandbox disconnected at rendezvous")), }; wire::write_frame(&mut stream.try_clone()?, &Frame::HelloAck { ttl_secs: spec.ttl.as_secs().max(1) })?; let _ = stream.set_read_timeout(None); Ok(Arc::new(RemoteSandbox::after_hello( &self.cfg, stream, agent_id, spec.ttl, ))) } fn status(&self) -> Result> { Ok(vec![SandboxInfo { id: format!("remote@{}", self.addr), profile: self.cfg.build_profile.clone(), warm: !self.queue.is_empty(), }]) } } pub struct RemoteSandbox { cfg: Config, id: String, ttl: std::time::Duration, reader: Mutex>, writer: Mutex, req: AtomicU64, } 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"), ); Self { cfg: cfg.clone(), id: agent_id, ttl, reader: Mutex::new(reader), writer: Mutex::new(stream), req: AtomicU64::new(1), } } fn send(&self, frame: &Frame) -> Result<()> { 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 { loop { let frame = match wire::read_frame(&mut *self.reader.lock().unwrap())? { Some(f) => f, None => return Err(Error::other(format!("sandbox {} vanished", self.id))), }; match frame { Frame::Log { req: r, ref stream, ref data } if r == req => { sink(stream, &wire::unhex(data)?); } Frame::Exit { req: r, .. } | Frame::Blob { req: r, .. } | Frame::Ok { req: r } | Frame::Err { req: r, .. } if r == req => { return Ok(frame) } _ => {} // Ping echoes and foreign requests are not ours } } } } impl Sandbox for RemoteSandbox { fn id(&self) -> &str { &self.id } fn run(&self, cmd: &crate::sandbox::Cmd, on_log: &mut dyn FnMut(&[u8])) -> Result { let req = self.req.fetch_add(1, Ordering::SeqCst); self.send(&Frame::Run { req, argv: cmd.argv.clone(), 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()?; { let (stop, interval) = (stop.clone(), self.ttl / 3); std::thread::spawn(move || { while !stop.load(Ordering::SeqCst) { std::thread::sleep(interval.max(std::time::Duration::from_millis(50))); if stop.load(Ordering::SeqCst) { break; } if wire::write_frame(&mut writer, &Frame::Ping {}).is_err() { break; } } }); } 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); } else { stdout.extend_from_slice(bytes); } }); stop.store(true, Ordering::SeqCst); match result? { Frame::Exit { code, .. } => Ok(Exit { code, stdout, stderr }), Frame::Err { msg, .. } => Err(Error::other(format!("sandbox {}: {msg}", self.id))), other => Err(Error::invalid(format!("sandbox {}: unexpected {other:?}", self.id))), } } fn put(&self, digest: &str, r: &mut dyn std::io::Read) -> Result<()> { let req = self.req.fetch_add(1, Ordering::SeqCst); let mut buf = Vec::new(); r.read_to_end(&mut buf)?; self.send(&Frame::Put { req, digest: digest.to_string(), data: wire::hex_bytes(&buf) })?; match self.pump(req, &mut |_, _| {})? { Frame::Ok { .. } => Ok(()), Frame::Err { msg, .. } => Err(Error::fail_closed(format!("sandbox {}: {msg}", self.id))), other => Err(Error::invalid(format!("sandbox {}: unexpected {other:?}", self.id))), } } fn get(&self, digest: &str) -> Result> { let req = self.req.fetch_add(1, Ordering::SeqCst); self.send(&Frame::Get { req, digest: digest.to_string() })?; match self.pump(req, &mut |_, _| {})? { Frame::Blob { data, .. } => Ok(Box::new(std::io::Cursor::new(wire::unhex(&data)?))), Frame::Err { msg, .. } => Err(Error::other(format!("sandbox {}: {msg}", self.id))), other => Err(Error::invalid(format!("sandbox {}: unexpected {other:?}", self.id))), } } fn destroy(&self) -> Result<()> { // Best effort: a sandbox that is already gone has nothing to destroy. let _ = self.send(&Frame::Destroy {}); Ok(()) } }