summaryrefslogtreecommitdiffstats
path: root/src/sandbox/kata.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/sandbox/kata.rs')
-rw-r--r--src/sandbox/kata.rs250
1 files changed, 133 insertions, 117 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::*;