use std::io::BufReader; 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}; /// The real definition; the alias below carries the visibility. mod remote_backend { use super::{Config, Receiver}; // `pub` inside a private module is still unreadable from outside it. pub struct RemoteBackend { pub cfg: Config, pub token: String, pub addr: String, pub queue: Receiver, } } /// The remote backend, built by `backend_for`. #[cfg(feature = "test-support")] pub use remote_backend::RemoteBackend; #[cfg(not(feature = "test-support"))] pub(crate) use remote_backend::RemoteBackend; impl RemoteBackend { pub fn bind(cfg: &Config, addr: &str, token: &str) -> Result { let bound = super::bound_listener(addr, token)?; Ok(Self { cfg: cfg.clone(), token: token.to_string(), addr: bound.local, queue: bound.rx }) } /// The address the rendezvous listener actually bound to, so a test can /// point a real agent at the socket. #[cfg(feature = "test-support")] 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)))?; 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() }]) } } pub(crate) struct RemoteSandbox { cfg: Config, id: String, ttl: std::time::Duration, reader: Mutex>, writer: Mutex, req: AtomicU64, } impl RemoteSandbox { 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) } fn pump(&self, req: u64, sink: &mut dyn FnMut(&str, &[u8])) -> Result { loop { let Some(frame) = wire::read_frame(&mut *self.reader.lock().unwrap())? else { 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) } _ => {} } } } } 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(), })?; 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(crate::time::inherit(move || { while !stop.load(Ordering::SeqCst) { crate::time::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| { 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<()> { let _ = self.send(&Frame::Destroy {}); Ok(()) } }