diff options
Diffstat (limited to 'src/sandbox')
| -rw-r--r-- | src/sandbox/kata.rs | 250 | ||||
| -rw-r--r-- | src/sandbox/loopback.rs | 25 | ||||
| -rw-r--r-- | src/sandbox/remote.rs | 31 |
3 files changed, 182 insertions, 124 deletions
diff --git a/src/sandbox/kata.rs b/src/sandbox/kata.rs index 27005bd..1f24ce7 100644 --- a/src/sandbox/kata.rs +++ b/src/sandbox/kata.rs @@ -176,97 +176,151 @@ impl Provisioner for LocalAgentProvisioner { } } -pub struct KataBackend { - cfg: Config, - token: String, - addr: String, - provisioner: Arc<dyn Provisioner>, - pending: Arc<Mutex<HashMap<String, Sender<TcpStream>>>>, - counter: AtomicU64, -} +/// The real definition and its impls. 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 kata_backend { + use super::*; -impl KataBackend { - pub(crate) fn shared_for(cfg: &Config) -> Result<Arc<KataBackend>> { - let crate::config::Sandbox::AgentSandbox { api, namespace, bearer, image, listen, token, .. } = - &cfg.sandbox - else { - return Err(Error::invalid( - "KataBackend::shared_for needs an agent-sandbox configuration", - )); - }; - let key = crate::hash::hex( - format!("{listen}\n{token}\n{api}\n{namespace}\n{bearer}\n{image}").as_bytes(), - ); - static CACHE: OnceLock<Mutex<HashMap<String, Arc<KataBackend>>>> = OnceLock::new(); - let cache = CACHE.get_or_init(|| Mutex::new(HashMap::new())); - let mut guard = cache.lock().unwrap_or_else(|p| p.into_inner()); - if let Some(existing) = guard.get(&key) { - return Ok(existing.clone()); - } - let provisioner = Arc::new(K8sSandboxProvisioner::for_config(cfg).ok_or_else(|| { - Error::invalid("KataBackend::shared_for needs an agent-sandbox configuration") - })?); - let backend = Arc::new(Self::bind(cfg, listen, token, provisioner)?); - guard.insert(key, backend.clone()); - Ok(backend) + pub struct KataBackend { + cfg: Config, + token: String, + addr: String, + provisioner: Arc<dyn Provisioner>, + pending: Arc<Mutex<HashMap<String, Sender<TcpStream>>>>, + counter: AtomicU64, } - pub(crate) fn provision_request(&self, spec: &SandboxSpec, id: &str) -> ProvisionRequest { - ProvisionRequest { - sandbox_id: id.to_string(), - profile: spec.profile.clone(), - hub_addr: self.addr.clone(), - token: self.token.clone(), - ttl: spec.ttl, - image: self.cfg.sandbox_image(), + impl KataBackend { + pub(crate) fn shared_for(cfg: &Config) -> Result<Arc<KataBackend>> { + let crate::config::Sandbox::AgentSandbox { api, namespace, bearer, image, listen, token, .. } = + &cfg.sandbox + else { + return Err(Error::invalid( + "KataBackend::shared_for needs an agent-sandbox configuration", + )); + }; + let key = crate::hash::hex( + format!("{listen}\n{token}\n{api}\n{namespace}\n{bearer}\n{image}").as_bytes(), + ); + static CACHE: OnceLock<Mutex<HashMap<String, Arc<KataBackend>>>> = OnceLock::new(); + let cache = CACHE.get_or_init(|| Mutex::new(HashMap::new())); + let mut guard = cache.lock().unwrap_or_else(|p| p.into_inner()); + if let Some(existing) = guard.get(&key) { + return Ok(existing.clone()); + } + let provisioner = Arc::new(K8sSandboxProvisioner::for_config(cfg).ok_or_else(|| { + Error::invalid("KataBackend::shared_for needs an agent-sandbox configuration") + })?); + let backend = Arc::new(Self::bind(cfg, listen, token, provisioner)?); + guard.insert(key, backend.clone()); + Ok(backend) + } + + pub(crate) fn provision_request(&self, spec: &SandboxSpec, id: &str) -> ProvisionRequest { + ProvisionRequest { + sandbox_id: id.to_string(), + profile: spec.profile.clone(), + hub_addr: self.addr.clone(), + token: self.token.clone(), + ttl: spec.ttl, + image: self.cfg.sandbox_image(), + } + } + + pub fn bind( + cfg: &Config, + listen: &str, + token: &str, + provisioner: Arc<dyn Provisioner>, + ) -> Result<Self> { + let listener = TcpListener::bind(listen)?; + let addr = listener.local_addr()?.to_string(); + let pending: Arc<Mutex<HashMap<String, Sender<TcpStream>>>> = Arc::new(Mutex::new(HashMap::new())); + { + let (token, pending) = (token.to_string(), pending.clone()); + std::thread::spawn(move || { + for stream in listener.incoming() { + let Ok(stream) = stream else { break }; + route_dial_in(stream, &token, &pending); + } + }); + } + Ok(Self { + cfg: cfg.clone(), + token: token.to_string(), + addr, + provisioner, + pending, + counter: AtomicU64::new(1), + }) + } + + // NOTE: `KataBackend::reclaim` used to sit here and called nothing but + // `self.provisioner.reclaim`, which the pool already calls itself at the + // reaping site. Nothing — not a test — ever called the wrapper, so it is + // gone rather than gated. The census had credited it to `tests/kata.rs`, + // where the TTL test implements the *trait's* `reclaim` on a null + // provisioner: same word, different function. + + fn nonce(&self) -> String { + let n = self.counter.fetch_add(1, Ordering::SeqCst); + let nanos = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_nanos()) + .unwrap_or(0); + crate::hash::hex_str(&format!("{}-{n}-{nanos}", std::process::id()))[..20].to_string() } } - pub fn bind( - cfg: &Config, - listen: &str, - token: &str, - provisioner: Arc<dyn Provisioner>, - ) -> Result<Self> { - let listener = TcpListener::bind(listen)?; - let addr = listener.local_addr()?.to_string(); - let pending: Arc<Mutex<HashMap<String, Sender<TcpStream>>>> = Arc::new(Mutex::new(HashMap::new())); - { - let (token, pending) = (token.to_string(), pending.clone()); - std::thread::spawn(move || { - for stream in listener.incoming() { - let Ok(stream) = stream else { break }; - route_dial_in(stream, &token, &pending); + impl SandboxBackend for KataBackend { + fn acquire(&self, spec: &SandboxSpec) -> Result<Arc<dyn Sandbox>> { + let id = self.nonce(); + let (tx, rx): (Sender<TcpStream>, Receiver<TcpStream>) = bounded(1); + self.pending.lock().unwrap().insert(id.clone(), tx); + let req = self.provision_request(spec, &id); + if let Err(e) = self.provisioner.provision(&req) { + self.pending.lock().unwrap().remove(&id); + return Err(e); + } + let stream = match rx.recv_timeout(spec.ttl) { + Ok(s) => s, + Err(_) => { + self.pending.lock().unwrap().remove(&id); + let _ = self.provisioner.reclaim(&id); + return Err(Error::pool_exhausted(PoolFull::Backend { + backend: "kata", + detail: format!( + "sandbox {id} for profile {} never dialed in within its TTL", + spec.profile + ), + })); } - }); + }; + let ttl = spec.ttl.max(Duration::from_secs(1)); + wire::write_frame(&mut stream.try_clone()?, &Frame::HelloAck { ttl_secs: ttl.as_secs() })?; + Ok(Arc::new(RemoteSandbox::after_hello(&self.cfg, stream, id, ttl))) } - Ok(Self { - cfg: cfg.clone(), - token: token.to_string(), - addr, - provisioner, - pending, - counter: AtomicU64::new(1), - }) - } - // NOTE: `KataBackend::reclaim` used to sit here and called nothing but - // `self.provisioner.reclaim`, which the pool already calls itself at the - // reaping site. Nothing — not a test — ever called the wrapper, so it is - // gone rather than gated. The census had credited it to `tests/kata.rs`, - // where the TTL test implements the *trait's* `reclaim` on a null - // provisioner: same word, different function. - - fn nonce(&self) -> String { - let n = self.counter.fetch_add(1, Ordering::SeqCst); - let nanos = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map(|d| d.as_nanos()) - .unwrap_or(0); - crate::hash::hex_str(&format!("{}-{n}-{nanos}", std::process::id()))[..20].to_string() + fn status(&self) -> Result<Vec<SandboxInfo>> { + Ok(vec![SandboxInfo { + id: format!("kata@{} via {}", self.addr, self.provisioner.name()), + profile: self.cfg.build_profile.clone(), + warm: !self.pending.lock().unwrap().is_empty(), + }]) + } } } +/// Selected by `backend_for`. The kata tests drive it directly and need a +/// fixture, so they cannot move into the module. +/// `pub` only under `test-support`. Production reaches the backend through +/// `backend_for` and never names the type from outside `sandbox`. +#[cfg(feature = "test-support")] +pub use kata_backend::KataBackend; + +#[cfg(not(feature = "test-support"))] +pub(crate) use kata_backend::KataBackend; fn route_dial_in( stream: TcpStream, token: &str, @@ -287,44 +341,6 @@ fn route_dial_in( } } -impl SandboxBackend for KataBackend { - fn acquire(&self, spec: &SandboxSpec) -> Result<Arc<dyn Sandbox>> { - let id = self.nonce(); - let (tx, rx): (Sender<TcpStream>, Receiver<TcpStream>) = bounded(1); - self.pending.lock().unwrap().insert(id.clone(), tx); - let req = self.provision_request(spec, &id); - if let Err(e) = self.provisioner.provision(&req) { - self.pending.lock().unwrap().remove(&id); - return Err(e); - } - let stream = match rx.recv_timeout(spec.ttl) { - Ok(s) => s, - Err(_) => { - self.pending.lock().unwrap().remove(&id); - let _ = self.provisioner.reclaim(&id); - return Err(Error::pool_exhausted(PoolFull::Backend { - backend: "kata", - detail: format!( - "sandbox {id} for profile {} never dialed in within its TTL", - spec.profile - ), - })); - } - }; - let ttl = spec.ttl.max(Duration::from_secs(1)); - wire::write_frame(&mut stream.try_clone()?, &Frame::HelloAck { ttl_secs: ttl.as_secs() })?; - Ok(Arc::new(RemoteSandbox::after_hello(&self.cfg, stream, id, ttl))) - } - - fn status(&self) -> Result<Vec<SandboxInfo>> { - Ok(vec![SandboxInfo { - id: format!("kata@{} via {}", self.addr, self.provisioner.name()), - profile: self.cfg.build_profile.clone(), - warm: !self.pending.lock().unwrap().is_empty(), - }]) - } -} - #[cfg(test)] mod tests { use super::*; diff --git a/src/sandbox/loopback.rs b/src/sandbox/loopback.rs index 7847fdc..9629206 100644 --- a/src/sandbox/loopback.rs +++ b/src/sandbox/loopback.rs @@ -7,10 +7,31 @@ use crate::config::Config; use crate::error::{Error, Result}; use crate::sandbox::{Cmd, Exit, Sandbox, SandboxBackend, SandboxInfo, SandboxSpec}; -pub struct LoopbackBackend { - cfg: Config, +/// 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 loopback_backend { + use super::*; + // `pub` fields inside a private module are not nameable from + // outside; they stay readable by the impls below. + + pub struct LoopbackBackend { + pub cfg: Config, + } } +/// The default backend, built by `backend_for`. A failure test builds one to inject a fault. +/// +/// `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 loopback_backend::LoopbackBackend; + +#[cfg(not(feature = "test-support"))] +pub(crate) use loopback_backend::LoopbackBackend; + impl LoopbackBackend { pub fn new(cfg: &Config) -> Self { Self { cfg: cfg.clone() } diff --git a/src/sandbox/remote.rs b/src/sandbox/remote.rs index c648843..6d369e2 100644 --- a/src/sandbox/remote.rs +++ b/src/sandbox/remote.rs @@ -9,13 +9,34 @@ 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, - queue: Receiver<std::net::TcpStream>, +/// 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 remote_backend { + use super::*; + // `pub` fields inside a private module are not nameable from + // outside; they stay readable by the impls below. + + pub struct RemoteBackend { + pub cfg: Config, + pub token: String, + pub addr: String, + pub queue: Receiver<std::net::TcpStream>, + } } +/// The remote backend, built by `backend_for`. A fixture test builds one to drive the agent protocol. +/// +/// `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 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<Self> { let bound = super::bound_listener(addr, token)?; |
