use std::collections::HashMap; use std::io::Read; use std::net::{TcpListener, TcpStream}; use std::path::PathBuf; use std::sync::{Arc, Mutex, OnceLock}; use std::time::Duration; use crossbeam_channel::{Receiver, Sender}; use crate::config::Config; use crate::error::Result; pub mod agent; pub mod kata; pub mod loopback; pub mod remote; pub mod wire; #[derive(Debug, Clone)] pub struct Cmd { pub argv: Vec, pub cwd: Option, } impl Cmd { pub fn new(argv: I) -> Self where I: IntoIterator, S: Into, { Self { argv: argv.into_iter().map(Into::into).collect(), cwd: None } } pub fn in_dir(mut self, dir: impl Into) -> Self { self.cwd = Some(dir.into()); self } pub fn name(&self) -> &str { self.argv.first().map(String::as_str).unwrap_or("") } } mod exit { #[derive(Debug)] pub struct Exit { pub code: Option, pub stdout: Vec, pub stderr: Vec, } impl Exit { pub fn success(&self) -> bool { self.code == Some(0) } } } #[cfg(feature = "test-support")] pub use exit::Exit; #[cfg(not(feature = "test-support"))] pub(crate) use exit::Exit; #[derive(Debug, Clone)] pub struct SandboxSpec { pub profile: String, pub task: String, pub ttl: Duration, pub disk_mb: u64, } impl SandboxSpec { pub fn new(profile: impl Into, task: impl Into, ttl: Duration) -> Self { Self { profile: profile.into(), task: task.into(), ttl, disk_mb: 0 } } } /// The real definition. The module is private, so this `pub` /// is not a nameable path from outside; the alias below is the /// only way to reach it, and the alias is what carries the /// feature-conditional visibility. mod sandbox_info { #[derive(Debug, Clone)] pub struct SandboxInfo { pub id: String, pub profile: String, pub warm: bool, } } /// The return type of `SandboxBackend::status`. No production module outside `sandbox` names it; the backend tests do. /// /// `pub` only under `test-support`. Production reaches the type /// through its own module and never names it from outside; the /// outside reader that needs the name is a test. #[cfg(feature = "test-support")] pub use sandbox_info::SandboxInfo; #[cfg(not(feature = "test-support"))] pub(crate) use sandbox_info::SandboxInfo; pub trait Sandbox: Send + Sync { fn id(&self) -> &str; fn run(&self, cmd: &Cmd, on_log: &mut dyn FnMut(&[u8])) -> Result; fn put(&self, digest: &str, r: &mut dyn Read) -> Result<()>; fn get(&self, digest: &str) -> Result>; fn destroy(&self) -> Result<()>; } pub trait SandboxBackend: Send + Sync { fn acquire(&self, spec: &SandboxSpec) -> Result>; fn status(&self) -> Result>; } pub fn backend_for(cfg: &Config) -> Result> { 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 { .. } => { let backend: Arc = kata::KataBackend::shared_for(cfg)?; Ok(backend) } } } #[derive(Clone)] pub(crate) struct Bound { pub local: String, pub rx: Receiver, } pub(crate) fn bound_listener(addr: &str, token: &str) -> Result { static REGISTRY: OnceLock>> = OnceLock::new(); let registry = REGISTRY.get_or_init(|| Mutex::new(HashMap::new())); let key = (addr.to_string(), token.to_string()); // A poisoned registry means a panic in another thread's bind; the map is // still sound, so recover rather than wedge every later build. let mut reg = registry.lock().unwrap_or_else(|p| p.into_inner()); if let Some(b) = reg.get(&key) { return Ok(b.clone()); } let listener = TcpListener::bind(addr)?; let local = listener.local_addr()?.to_string(); let (tx, rx): (Sender, Receiver) = 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.clone()); Ok(bound) }