use std::collections::HashMap; use std::io::BufReader; use std::net::{TcpListener, TcpStream}; #[cfg(feature = "test-support")] use std::path::PathBuf; #[cfg(feature = "test-support")] use std::process::{Child, Command}; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Mutex, OnceLock}; use std::time::Duration; use crossbeam_channel::{bounded, Receiver, Sender}; use crate::config::Config; use crate::error::{Error, PoolFull, Result}; use crate::sandbox::remote::RemoteSandbox; use crate::sandbox::wire::{self, Frame}; use crate::sandbox::{Sandbox, SandboxBackend, SandboxInfo, SandboxSpec}; #[derive(Debug, Clone)] // ProvisionRequest stays `pub`: the argument of `Provisioner::provision`, the trait the public `LocalAgentProvisioner` implements. pub struct ProvisionRequest { pub sandbox_id: String, pub profile: String, pub hub_addr: String, pub token: String, pub ttl: Duration, pub image: String, } // Provisioner stays `pub`: implemented by the test-gated public `LocalAgentProvisioner`; a private trait on a public impl is E0445. pub trait Provisioner: Send + Sync { fn provision(&self, req: &ProvisionRequest) -> Result<()>; fn reclaim(&self, sandbox_id: &str) -> Result<()>; fn name(&self) -> &str; } /// The agent-sandbox-style CR: one disposable Sandbox per build, Kata for the /// VM boundary, `activeDeadlineSeconds` so the *orchestrator* enforces the /// TTL even if the hub dies. The token rides in args for v1; a production /// deployment should mount it from a Secret, and this comment is the honest /// place that says so. pub(crate) fn sandbox_cr(req: &ProvisionRequest) -> serde_json::Value { serde_json::json!({ "apiVersion": "agents.x-k8s.io/v1alpha1", "kind": "Sandbox", "metadata": { "name": req.sandbox_id, "labels": { "aur-build.io/managed-by": "aur-build", "aur-build.io/profile": req.profile, }, }, "spec": { "runtimeClass": "kata", "shutdownPolicy": "Delete", "activeDeadlineSeconds": req.ttl.as_secs(), "template": { "spec": { "containers": [{ "name": "build-agent", "image": req.image, "args": [ "--hub", req.hub_addr, "--token", req.token, "--agent-id", req.sandbox_id, "--profile", req.profile, "--ttl", req.ttl.as_secs().to_string(), ], }], }, }, }, }) } impl K8sSandboxProvisioner { pub(crate) fn for_config(cfg: &Config) -> Option { match &cfg.sandbox { crate::config::Sandbox::AgentSandbox { api, namespace, bearer, .. } => Some(Self { api: api.clone(), namespace: namespace.clone(), bearer: bearer.clone(), }), _ => None, } } } pub(crate) struct K8sSandboxProvisioner { pub api: String, pub bearer: String, pub namespace: String, } impl Provisioner for K8sSandboxProvisioner { fn provision(&self, req: &ProvisionRequest) -> Result<()> { let url = format!( "{}/apis/agents.x-k8s.io/v1alpha1/namespaces/{}/sandboxes", self.api.trim_end_matches('/'), self.namespace ); ureq::post(&url) .set("Authorization", &format!("Bearer {}", self.bearer)) .send_json(sandbox_cr(req)) .map_err(|e| Error::other(format!("kata provision failed: {e}")))?; Ok(()) } fn reclaim(&self, sandbox_id: &str) -> Result<()> { let url = format!( "{}/apis/agents.x-k8s.io/v1alpha1/namespaces/{}/sandboxes/{sandbox_id}", self.api.trim_end_matches('/'), self.namespace ); ureq::delete(&url) .set("Authorization", &format!("Bearer {}", self.bearer)) .call() .map_err(|e| Error::other(format!("kata reclaim failed: {e}")))?; Ok(()) } fn name(&self) -> &str { "k8s-sandbox-crd" } } /// Provisions sandboxes by running the local `sandbox-agent` binary. /// /// Test-tier only. Production selects `K8sSandboxProvisioner` when the config /// names an agent-sandbox backend (kata.rs:193); nothing in the crate ever /// constructs this type. It exists so tests can drive the real agent protocol /// against the shim binary without a cluster, which is a more valuable test /// than the absence of one — so it is gated rather than deleted. #[cfg(feature = "test-support")] pub struct LocalAgentProvisioner { pub bin: PathBuf, children: Mutex>, } #[cfg(feature = "test-support")] impl LocalAgentProvisioner { pub fn new(bin: impl Into) -> Self { Self { bin: bin.into(), children: Mutex::new(HashMap::new()) } } } #[cfg(feature = "test-support")] impl Provisioner for LocalAgentProvisioner { fn provision(&self, req: &ProvisionRequest) -> Result<()> { let child = Command::new(&self.bin) .arg("--hub") .arg(&req.hub_addr) .arg("--token") .arg(&req.token) .arg("--agent-id") .arg(&req.sandbox_id) .arg("--profile") .arg(&req.profile) .arg("--ttl") .arg(req.ttl.as_secs().to_string()) .spawn() .map_err(|e| Error::other(format!("local agent spawn failed: {e}")))?; self.children.lock().unwrap().insert(req.sandbox_id.clone(), child); Ok(()) } fn reclaim(&self, sandbox_id: &str) -> Result<()> { if let Some(mut child) = self.children.lock().unwrap().remove(sandbox_id) { let _ = child.kill(); let _ = child.wait(); } Ok(()) } fn name(&self) -> &str { "local-agent" } } /// 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::*; pub struct KataBackend { cfg: Config, token: String, addr: String, provisioner: Arc, pending: Arc>>>, counter: AtomicU64, } impl KataBackend { pub(crate) fn shared_for(cfg: &Config) -> Result> { 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>>> = 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, ) -> Result { let listener = TcpListener::bind(listen)?; let addr = listener.local_addr()?.to_string(); let pending: Arc>>> = 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() } } impl SandboxBackend for KataBackend { fn acquire(&self, spec: &SandboxSpec) -> Result> { let id = self.nonce(); let (tx, rx): (Sender, Receiver) = 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> { Ok(vec![SandboxInfo { id: format!("kata@{} via {}", self.addr, self.provisioner.name()), profile: self.cfg.build_profile.clone(), }]) } } } /// 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, pending: &Arc>>>, ) { let _ = stream.set_read_timeout(Some(Duration::from_secs(10))); let mut reader = match stream.try_clone() { Ok(s) => BufReader::new(s), Err(_) => return, }; let hello = match wire::read_frame(&mut reader) { Ok(Some(Frame::Hello { token: t, agent_id, .. })) if t == token => agent_id, _ => return, }; let slot = pending.lock().unwrap().remove(&hello).map(|tx| (tx, stream)); if let Some((tx, stream)) = slot { let _ = tx.send(stream); } } #[cfg(test)] mod tests { use super::*; fn req() -> ProvisionRequest { ProvisionRequest { sandbox_id: "sbx-abc123".into(), profile: "extra-x86_64".into(), hub_addr: "10.0.0.5:9443".into(), token: "t0ken".into(), ttl: Duration::from_secs(120), image: "aur-build-sandbox:latest".into(), } } #[test] fn the_cr_asks_kata_for_a_vm_that_dies_on_its_own_by_ttl() { let cr = sandbox_cr(&req()); assert_eq!(cr["spec"]["runtimeClass"], "kata"); assert_eq!(cr["spec"]["activeDeadlineSeconds"], 120, "the orchestrator must enforce the TTL even if the hub dies"); assert_eq!(cr["spec"]["shutdownPolicy"], "Delete"); let args = cr["spec"]["template"]["spec"]["containers"][0]["args"] .as_array() .unwrap() .iter() .map(|v| v.as_str().unwrap().to_string()) .collect::>(); assert!(args.windows(2).any(|w| w[0] == "--agent-id" && w[1] == "sbx-abc123")); assert!(args.windows(2).any(|w| w[0] == "--hub" && w[1] == "10.0.0.5:9443")); assert!(args.windows(2).any(|w| w[0] == "--token" && w[1] == "t0ken")); } // ------------------------------------------------------------------ // Moved verbatim from tests/kata.rs. Neither test builds a fixture or // touches a database: one asserts the shape of the container record a // lease provisions, the other that a sandbox which never dials in expires // by TTL rather than hanging. Both are about this module's own machinery, // which is what let `KataBackend`, `sandbox_cr`, `provision_request`, // `shared_for` and `for_config` stop being part of the crate's interface. // // `Provisioner` and `ProvisionRequest` stayed public, and not by // oversight: a `pub` implementor cannot implement a `pub(crate)` trait, // and a `pub` trait method cannot take a `pub(crate)` parameter. Narrowing // them would force `LocalAgentProvisioner` private, and the two tests that // construct it drive a real sandbox agent through a fixture. // ------------------------------------------------------------------ fn agent_sandbox_config() -> Config { let tmp = tempfile::tempdir().unwrap(); std::fs::write( tmp.path().join("config.json"), r#"{ "sandbox": { "kind": "agent-sandbox", "api": "https://k8s.test:6443", "namespace": "builds", "bearer": "kube-bearer", "image": "aur-build-sandbox:test", "listen": "127.0.0.1:0", "token": "kata-cfg-token", "shared_workspace": true } }"#, ) .unwrap(); let cfg = Config::load(tmp.path()).unwrap(); cfg.validate().expect("the config must survive the startup guard"); cfg } #[test] fn an_agent_sandbox_config_provisions_a_kata_vm_per_lease() { let cfg = agent_sandbox_config(); let backend = KataBackend::shared_for(&cfg).unwrap(); let spec = SandboxSpec::new("extra-x86_64", "build-9", Duration::from_secs(77)); let cr = sandbox_cr(&backend.provision_request(&spec, "sbx-nonce-9")); assert_eq!(cr["spec"]["runtimeClass"], "kata", "the VM boundary is the point"); assert_eq!( cr["spec"]["activeDeadlineSeconds"], 77, "the orchestrator enforces the lease TTL even if the hub dies" ); assert_eq!( cr["metadata"]["name"], "sbx-nonce-9", "the nonce names the box, so a stray sandbox cannot be leased to the wrong build" ); assert_eq!(cr["spec"]["template"]["spec"]["containers"][0]["image"], "aur-build-sandbox:test"); let args: Vec = cr["spec"]["template"]["spec"]["containers"][0]["args"] .as_array() .unwrap() .iter() .map(|v| v.as_str().unwrap().to_string()) .collect(); assert!(args.windows(2).any(|w| w[0] == "--agent-id" && w[1] == "sbx-nonce-9")); assert!(args.windows(2).any(|w| w[0] == "--ttl" && w[1] == "77")); let prov = K8sSandboxProvisioner::for_config(&cfg).unwrap(); assert_eq!(prov.api, "https://k8s.test:6443"); assert_eq!(prov.namespace, "builds"); assert_eq!(prov.bearer, "kube-bearer"); } #[test] fn a_sandbox_that_never_dials_in_is_a_ttl_expiry_not_a_hang() { struct NullProvisioner; impl Provisioner for NullProvisioner { fn provision(&self, _req: &ProvisionRequest) -> Result<()> { Ok(()) } fn reclaim(&self, _id: &str) -> Result<()> { Ok(()) } fn name(&self) -> &str { "null" } } let cfg = Config::default(); let backend = KataBackend::bind(&cfg, "127.0.0.1:0", "tok", Arc::new(NullProvisioner)).unwrap(); let started = std::time::Instant::now(); let err = match backend.acquire(&SandboxSpec::new("extra-x86_64", "ghost", Duration::from_secs(1))) { Ok(_) => panic!("nobody provisioned anything; the lease must not succeed"), Err(e) => e, }; assert!(started.elapsed() >= Duration::from_millis(900), "acquire gave up before the TTL"); assert!(err.to_string().contains("never dialed in"), "{err}"); } // ------------------------------------------------------------------ // Moved verbatim from tests/kata.rs. It is an opt-in live tier, not a // fixture test: it records its own absence when there is no /dev/kvm or no // AUR_KATA_API, exactly as the vercmp live tier does. It constructs the // provisioner field by field, which is the only reason that struct was // nameable from outside; with the test here, it no longer needs to be. // ------------------------------------------------------------------ #[test] fn the_live_kata_tier_is_recorded_not_silently_absent() { if !std::path::Path::new("/dev/kvm").exists() { println!("note: no /dev/kvm on this host; the live kata tier is skipped, not passed"); return; } let Ok(api) = std::env::var("AUR_KATA_API") else { println!("note: /dev/kvm present but AUR_KATA_API unset; live kata tier still skipped"); return; }; let cfg = Config::default(); let prov = Arc::new(K8sSandboxProvisioner { api, bearer: std::env::var("AUR_KATA_TOKEN").unwrap_or_default(), namespace: std::env::var("AUR_KATA_NS").unwrap_or_else(|_| "default".into()), }); let backend = KataBackend::bind(&cfg, "0.0.0.0:9443", &std::env::var("AUR_AGENT_TOKEN").unwrap(), prov).unwrap(); let sbx = backend .acquire(&SandboxSpec::new("extra-x86_64", "live", Duration::from_secs(300))) .expect("live kata sandbox should lease"); let out = sbx.run(&crate::sandbox::Cmd::new(["/bin/echo", "kata"]), &mut |_| {}).unwrap(); assert!(out.success() && String::from_utf8_lossy(&out.stdout).contains("kata")); sbx.destroy().unwrap(); } }