diff options
Diffstat (limited to 'src/sandbox/kata.rs')
| -rw-r--r-- | src/sandbox/kata.rs | 125 |
1 files changed, 75 insertions, 50 deletions
diff --git a/src/sandbox/kata.rs b/src/sandbox/kata.rs index 5c92557..c7d717f 100644 --- a/src/sandbox/kata.rs +++ b/src/sandbox/kata.rs @@ -9,13 +9,11 @@ //! the wrong build, and a sandbox that never dials in is a TTL expiry — the //! same vocabulary every other failure in this system speaks (I5). //! -//! Two payload shapes are constructed here because both are real deployment -//! targets: an agent-sandbox-style Kubernetes CR (`runtimeClass: kata`, -//! `activeDeadlineSeconds` as the TTL the orchestrator enforces) and a -//! direct containerd/`nerdctl` argv for hosts without a cluster. Both are -//! pure functions, unit-tested; the network calls that would send them are -//! exercised only by the gated live tier, which skips — with a printed note, -//! never a silent pass — wherever `/dev/kvm` or a cluster is absent. +//! The payload is an agent-sandbox-style Kubernetes CR (`runtimeClass: kata`, +//! `activeDeadlineSeconds` as the TTL the orchestrator enforces). It is a pure +//! function, unit-tested; the network call that sends it is exercised only by +//! the gated live tier, which skips — with a printed note, never a silent +//! pass — wherever a cluster is absent. //! //! The `LocalAgentProvisioner` is the shape this tier is tested with: a real //! `sandbox-agent` process, real rendezvous, no VM. It is to kata what the @@ -28,7 +26,7 @@ use std::net::{TcpListener, TcpStream}; use std::path::PathBuf; use std::process::{Child, Command}; use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::{Arc, Mutex}; +use std::sync::{Arc, Mutex, OnceLock}; use std::time::Duration; use crossbeam_channel::{bounded, Receiver, Sender}; @@ -100,32 +98,20 @@ pub fn sandbox_cr(req: &ProvisionRequest) -> serde_json::Value { }) } -/// The no-cluster shape: `nerdctl run` against containerd's kata runtime. -/// `--rm` is the TTL's poor cousin; the agent's own watchdog is the floor. -pub fn nerdctl_argv(req: &ProvisionRequest) -> Vec<String> { - vec![ - "nerdctl".into(), - "run".into(), - "-d".into(), - "--rm".into(), - "--name".into(), - req.sandbox_id.clone(), - "--runtime".into(), - "io.containerd.kata.v2".into(), - "--label".into(), - format!("aur-build.io/profile={}", req.profile), - req.image.clone(), - "--hub".into(), - req.hub_addr.clone(), - "--token".into(), - req.token.clone(), - "--agent-id".into(), - req.sandbox_id.clone(), - "--profile".into(), - req.profile.clone(), - "--ttl".into(), - req.ttl.as_secs().to_string(), - ] +impl K8sSandboxProvisioner { + /// The provisioner an `agent-sandbox` configuration names. Split out so a + /// test can assert the cluster coordinates reach it from a parsed config, + /// and so `shared_for` and any later caller build it the same way. + pub fn for_config(cfg: &Config) -> Option<Self> { + match &cfg.sandbox { + crate::config::Sandbox::AgentSandbox { api, namespace, bearer, .. } => Some(Self { + api: api.clone(), + namespace: namespace.clone(), + bearer: bearer.clone(), + }), + _ => None, + } + } } /// Talks to a Kubernetes API serving an agent-sandbox-style CRD. Real code, @@ -228,6 +214,59 @@ pub struct KataBackend { } impl KataBackend { + /// The one Kata backend this process should use for this configuration. + /// + /// A Kata backend cannot share only its listener the way the plain remote + /// backend does: it routes every dial-in by the nonce in its `Hello` into a + /// map that belongs to it, so two backends on one address would each see + /// half the dial-ins and neither could complete a rendezvous. So the whole + /// backend is shared, not just the socket — which is also what makes + /// "one listener per process" true here, since binding happens exactly once + /// per distinct configuration. + /// + /// The key is a digest of everything that distinguishes one backend from + /// another, so the rendezvous token and the cluster bearer are not sitting + /// around in a second place, and two configurations that differ only in + /// unrelated hub settings still get their own backend. + pub 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) + } + + /// The request a lease turns into, for one nonce. Split out of `acquire` so + /// a test can assert what a *configuration* becomes without a cluster in + /// the loop. + pub 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, @@ -305,14 +344,7 @@ impl SandboxBackend for KataBackend { let id = self.nonce(); let (tx, rx): (Sender<TcpStream>, Receiver<TcpStream>) = bounded(1); self.pending.lock().unwrap().insert(id.clone(), tx); - let req = ProvisionRequest { - sandbox_id: id.clone(), - profile: spec.profile.clone(), - hub_addr: self.addr.clone(), - token: self.token.clone(), - ttl: spec.ttl, - image: self.cfg.sandbox_image(), - }; + let req = self.provision_request(spec, &id); if let Err(e) = self.provisioner.provision(&req) { self.pending.lock().unwrap().remove(&id); return Err(e); @@ -378,12 +410,5 @@ mod tests { assert!(args.windows(2).any(|w| w[0] == "--token" && w[1] == "t0ken")); } - #[test] - fn the_containerd_shape_names_the_kata_runtime() { - let argv = nerdctl_argv(&req()); - let rt = argv.windows(2).find(|w| w[0] == "--runtime").expect("--runtime present"); - assert_eq!(rt[1], "io.containerd.kata.v2"); - assert!(argv.contains(&"--rm".to_string()), "no-cluster TTL floor: --rm"); - assert!(argv.windows(2).any(|w| w[0] == "--agent-id" && w[1] == "sbx-abc123")); - } + } |
