diff options
Diffstat (limited to 'src/sandbox')
| -rw-r--r-- | src/sandbox/agent.rs | 52 | ||||
| -rw-r--r-- | src/sandbox/kata.rs | 92 | ||||
| -rw-r--r-- | src/sandbox/loopback.rs | 13 | ||||
| -rw-r--r-- | src/sandbox/mod.rs | 4 | ||||
| -rw-r--r-- | src/sandbox/remote.rs | 41 | ||||
| -rw-r--r-- | src/sandbox/wire.rs | 9 |
6 files changed, 79 insertions, 132 deletions
diff --git a/src/sandbox/agent.rs b/src/sandbox/agent.rs index 3eaa799..fa813cf 100644 --- a/src/sandbox/agent.rs +++ b/src/sandbox/agent.rs @@ -22,17 +22,10 @@ pub struct AgentOptions { pub fn serve(opts: &AgentOptions) -> Result<()> { let stream = connect_with_retry(&opts.hub, Duration::from_secs(15))?; - let agent_id = opts - .agent_id - .clone() - .unwrap_or_else(|| format!("sandbox-{}", std::process::id())); + let agent_id = opts.agent_id.clone().unwrap_or_else(|| format!("sandbox-{}", std::process::id())); wire::write_frame( &mut stream.try_clone()?, - &Frame::Hello { - token: opts.token.clone(), - agent_id: agent_id.clone(), - profiles: vec![opts.profile.clone()], - }, + &Frame::Hello { token: opts.token.clone(), agent_id: agent_id.clone(), profiles: vec![opts.profile.clone()] }, )?; let mut reader = BufReader::new(stream.try_clone()?); @@ -50,8 +43,7 @@ pub fn serve(opts: &AgentOptions) -> Result<()> { let child = Arc::new(Mutex::new(None::<u32>)); let alive = Arc::new(AtomicBool::new(true)); { - let (last, child, alive, ttl) = - (last_inbound.clone(), child.clone(), alive.clone(), ttl); + let (last, child, alive, ttl) = (last_inbound.clone(), child.clone(), alive.clone(), ttl); std::thread::spawn(crate::time::inherit(move || loop { crate::time::sleep(Duration::from_secs(1)); let quiet = last.lock().unwrap().elapsed(); @@ -102,17 +94,12 @@ pub fn serve(opts: &AgentOptions) -> Result<()> { outcome } -fn handle( - frame: Frame, - writer: &Arc<Mutex<TcpStream>>, - blobs: &Path, - child: &Arc<Mutex<Option<u32>>>, -) -> Result<bool> { +fn handle(frame: Frame, writer: &Arc<Mutex<TcpStream>>, blobs: &Path, child: &Arc<Mutex<Option<u32>>>) -> Result<bool> { match frame { Frame::Destroy {} => Ok(true), Frame::Ping {} => Ok(false), Frame::Put { req, digest, data } => { - let bytes = wire::unhex(&data).map_err(io_err)?; + let bytes = wire::unhex(&data).map_err(|e| Error::other(e.to_string()))?; if crate::hash::hex(&bytes) != digest { reply(writer, req, Err("put: data does not hash to the claimed digest"))?; return Ok(false); @@ -121,16 +108,18 @@ fn handle( reply(writer, req, Ok(()))?; Ok(false) } - Frame::Get { req, digest } => match std::fs::read(safe_blob_path(blobs, &digest)?) { - Ok(bytes) => { - wire::write_frame(writer.lock().unwrap().deref_mut(), &Frame::Blob { req, data: wire::hex_bytes(&bytes) })?; + Frame::Get { req, digest } => { + if let Ok(bytes) = std::fs::read(safe_blob_path(blobs, &digest)?) { + wire::write_frame( + writer.lock().unwrap().deref_mut(), + &Frame::Blob { req, data: wire::hex_bytes(&bytes) }, + )?; Ok(false) - } - Err(_) => { + } else { reply(writer, req, Err("get: no such blob"))?; Ok(false) } - }, + } Frame::Run { req, argv, cwd, env } => { run_child(req, argv, cwd, env, writer, blobs, child)?; Ok(false) @@ -149,16 +138,14 @@ fn run_child( child: &Arc<Mutex<Option<u32>>>, ) -> Result<()> { let mut argv = argv; - for a in argv.iter_mut() { + for a in &mut argv { if let Some(digest) = a.strip_prefix("blob:") { *a = safe_blob_path(blobs, digest)?.display().to_string(); } } let program = argv.first().ok_or_else(|| Error::invalid("run: empty argv"))?; let mut c = std::process::Command::new(program); - c.args(&argv[1..]) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()); + c.args(&argv[1..]).stdout(Stdio::piped()).stderr(Stdio::piped()); if let Some(dir) = cwd { c.current_dir(dir); } @@ -205,10 +192,7 @@ fn run_child( } let status = proc.wait()?; *child.lock().unwrap() = None; - wire::write_frame( - writer.lock().unwrap().deref_mut(), - &Frame::Exit { req, code: status.code() }, - )?; + wire::write_frame(writer.lock().unwrap().deref_mut(), &Frame::Exit { req, code: status.code() })?; Ok(()) } @@ -246,8 +230,4 @@ fn safe_blob_path(blobs: &Path, digest: &str) -> Result<PathBuf> { Ok(blobs.join(digest)) } -fn io_err(e: std::io::Error) -> Error { - Error::other(e.to_string()) -} - use std::ops::DerefMut; diff --git a/src/sandbox/kata.rs b/src/sandbox/kata.rs index cfc3bd6..ca39c6b 100644 --- a/src/sandbox/kata.rs +++ b/src/sandbox/kata.rs @@ -77,11 +77,9 @@ fn sandbox_cr(req: &ProvisionRequest) -> serde_json::Value { impl K8sSandboxProvisioner { 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(), - }), + crate::config::Sandbox::AgentSandbox { api, namespace, bearer, .. } => { + Some(Self { api: api.clone(), namespace: namespace.clone(), bearer: bearer.clone() }) + } _ => None, } } @@ -120,7 +118,7 @@ impl Provisioner for K8sSandboxProvisioner { Ok(()) } - fn name(&self) -> &str { + fn name(&self) -> &'static str { "k8s-sandbox-crd" } } @@ -173,7 +171,7 @@ impl Provisioner for LocalAgentProvisioner { Ok(()) } - fn name(&self) -> &str { + fn name(&self) -> &'static str { "local-agent" } } @@ -182,7 +180,11 @@ impl Provisioner for LocalAgentProvisioner { /// 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::*; + use super::{ + bounded, route_dial_in, wire, Arc, AtomicU64, Config, Duration, Error, Frame, HashMap, K8sSandboxProvisioner, + Mutex, OnceLock, Ordering, PoolFull, ProvisionRequest, Provisioner, Receiver, RemoteSandbox, Result, Sandbox, + SandboxBackend, SandboxInfo, SandboxSpec, Sender, TcpListener, TcpStream, + }; pub struct KataBackend { cfg: Config, @@ -198,22 +200,19 @@ mod kata_backend { 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", - )); + 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(), - ); + 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()); + let mut guard = cache.lock().unwrap_or_else(std::sync::PoisonError::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 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) @@ -230,12 +229,7 @@ mod kata_backend { } } - pub fn bind( - cfg: &Config, - listen: &str, - token: &str, - provisioner: Arc<dyn Provisioner>, - ) -> Result<Self> { + 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())); @@ -267,10 +261,7 @@ mod kata_backend { 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); + let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_nanos()); crate::hash::hex_str(&format!("{}-{n}-{nanos}", std::process::id()))[..20].to_string() } } @@ -285,19 +276,13 @@ mod kata_backend { 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 Ok(stream) = rx.recv_timeout(spec.ttl) else { + 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() })?; @@ -322,11 +307,7 @@ 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<Mutex<HashMap<String, Sender<TcpStream>>>>, -) { +fn route_dial_in(stream: TcpStream, token: &str, pending: &Arc<Mutex<HashMap<String, Sender<TcpStream>>>>) { let _ = stream.set_read_timeout(Some(Duration::from_secs(10))); let mut reader = match stream.try_clone() { Ok(s) => BufReader::new(s), @@ -361,8 +342,10 @@ mod tests { 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"]["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() @@ -455,17 +438,15 @@ mod tests { fn reclaim(&self, _id: &str) -> Result<()> { Ok(()) } - fn name(&self) -> &str { + fn name(&self) -> &'static str { "null" } } let cfg = Config::default(); - let backend = - KataBackend::bind(&cfg, "127.0.0.1:0", "tok", Arc::new(NullProvisioner)).unwrap(); + 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, + let Err(err) = backend.acquire(&SandboxSpec::new("extra-x86_64", "ghost", Duration::from_secs(1))) else { + panic!("nobody provisioned anything; the lease must not succeed") }; assert!(started.elapsed() >= Duration::from_millis(900), "acquire gave up before the TTL"); assert!(err.to_string().contains("never dialed in"), "{err}"); @@ -495,7 +476,8 @@ mod tests { 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 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"); diff --git a/src/sandbox/loopback.rs b/src/sandbox/loopback.rs index 64875c6..fb97660 100644 --- a/src/sandbox/loopback.rs +++ b/src/sandbox/loopback.rs @@ -12,7 +12,7 @@ use crate::sandbox::{Cmd, Exit, Sandbox, SandboxBackend, SandboxInfo, SandboxSpe /// only way to reach it, and the alias is what carries the /// feature-conditional visibility. mod loopback_backend { - use super::*; + use super::Config; // `pub` fields inside a private module are not nameable from // outside; they stay readable by the impls below. @@ -42,18 +42,11 @@ impl SandboxBackend for LoopbackBackend { fn acquire(&self, spec: &SandboxSpec) -> Result<Arc<dyn Sandbox>> { let blobs = blob_root(&self.cfg).join(safe_name(&spec.task)); fs::create_dir_all(&blobs)?; - Ok(Arc::new(LoopbackSandbox { - id: format!("loopback:{}", spec.task), - blobs, - cfg: self.cfg.clone(), - })) + Ok(Arc::new(LoopbackSandbox { id: format!("loopback:{}", spec.task), blobs, cfg: self.cfg.clone() })) } fn status(&self) -> Result<Vec<SandboxInfo>> { - Ok(vec![SandboxInfo { - id: "loopback".into(), - profile: self.cfg.build_profile.clone(), - }]) + Ok(vec![SandboxInfo { id: "loopback".into(), profile: self.cfg.build_profile.clone() }]) } } diff --git a/src/sandbox/mod.rs b/src/sandbox/mod.rs index bb6ab60..1c73e40 100644 --- a/src/sandbox/mod.rs +++ b/src/sandbox/mod.rs @@ -35,7 +35,7 @@ impl Cmd { self } pub fn name(&self) -> &str { - self.argv.first().map(String::as_str).unwrap_or("") + self.argv.first().map_or("", String::as_str) } } @@ -134,7 +134,7 @@ fn bound_listener(addr: &str, token: &str) -> Result<Bound> { 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()); + let mut reg = registry.lock().unwrap_or_else(std::sync::PoisonError::into_inner); if let Some(b) = reg.get(&key) { return Ok(b.clone()); } diff --git a/src/sandbox/remote.rs b/src/sandbox/remote.rs index 8366e97..f881eb0 100644 --- a/src/sandbox/remote.rs +++ b/src/sandbox/remote.rs @@ -14,7 +14,7 @@ use crate::sandbox::{Exit, Sandbox, SandboxBackend, SandboxInfo, SandboxSpec}; /// only way to reach it, and the alias is what carries the /// feature-conditional visibility. mod remote_backend { - use super::*; + use super::{Config, Receiver}; // `pub` fields inside a private module are not nameable from // outside; they stay readable by the impls below. @@ -61,20 +61,16 @@ impl RemoteBackend { impl SandboxBackend for RemoteBackend { fn acquire(&self, spec: &SandboxSpec) -> Result<Arc<dyn Sandbox>> { - let stream = self.queue.recv_timeout(spec.ttl).map_err(|_| { - Error::other(format!( - "no sandbox connected to {} within the lease window", - self.addr - )) - })?; + let stream = self + .queue + .recv_timeout(spec.ttl) + .map_err(|_| Error::other(format!("no sandbox connected to {} within the lease window", self.addr)))?; let _ = stream.set_read_timeout(Some(spec.ttl)); let mut reader = BufReader::new(stream.try_clone()?); let agent_id = match wire::read_frame(&mut reader)? { Some(Frame::Hello { token, agent_id, profiles }) => { if token != self.token { - return Err(Error::fail_closed(format!( - "sandbox {agent_id} presented the wrong token" - ))); + return Err(Error::fail_closed(format!("sandbox {agent_id} presented the wrong token"))); } if !profiles.is_empty() && !profiles.contains(&spec.profile) { return Err(Error::fail_closed(format!( @@ -89,16 +85,11 @@ impl SandboxBackend for RemoteBackend { }; wire::write_frame(&mut stream.try_clone()?, &Frame::HelloAck { ttl_secs: spec.ttl.as_secs().max(1) })?; let _ = stream.set_read_timeout(None); - Ok(Arc::new(RemoteSandbox::after_hello( - &self.cfg, stream, agent_id, spec.ttl, - ))) + Ok(Arc::new(RemoteSandbox::after_hello(&self.cfg, stream, agent_id, spec.ttl))) } fn status(&self) -> Result<Vec<SandboxInfo>> { - Ok(vec![SandboxInfo { - id: format!("remote@{}", self.addr), - profile: self.cfg.build_profile.clone(), - }]) + Ok(vec![SandboxInfo { id: format!("remote@{}", self.addr), profile: self.cfg.build_profile.clone() }]) } } @@ -112,10 +103,13 @@ pub(crate) struct RemoteSandbox { } impl RemoteSandbox { - pub(crate) fn after_hello(cfg: &Config, stream: std::net::TcpStream, agent_id: String, ttl: std::time::Duration) -> Self { - let reader = BufReader::new( - stream.try_clone().expect("cloning a connected tcp stream cannot fail"), - ); + pub(crate) fn after_hello( + cfg: &Config, + stream: std::net::TcpStream, + agent_id: String, + ttl: std::time::Duration, + ) -> Self { + let reader = BufReader::new(stream.try_clone().expect("cloning a connected tcp stream cannot fail")); Self { cfg: cfg.clone(), id: agent_id, @@ -132,9 +126,8 @@ impl RemoteSandbox { fn pump(&self, req: u64, sink: &mut dyn FnMut(&str, &[u8])) -> Result<Frame> { loop { - let frame = match wire::read_frame(&mut *self.reader.lock().unwrap())? { - Some(f) => f, - None => return Err(Error::other(format!("sandbox {} vanished", self.id))), + let Some(frame) = wire::read_frame(&mut *self.reader.lock().unwrap())? else { + return Err(Error::other(format!("sandbox {} vanished", self.id))); }; match frame { Frame::Log { req: r, ref stream, ref data } if r == req => { diff --git a/src/sandbox/wire.rs b/src/sandbox/wire.rs index 4ae1ec0..75fc0a5 100644 --- a/src/sandbox/wire.rs +++ b/src/sandbox/wire.rs @@ -36,8 +36,7 @@ pub(crate) enum Frame { } pub(crate) fn write_frame(w: &mut impl Write, f: &Frame) -> io::Result<()> { - let body = serde_json::to_vec(f) - .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?; + let body = serde_json::to_vec(f).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?; if body.len() as u64 > MAX_FRAME_BYTES as u64 { return Err(io::Error::new(io::ErrorKind::InvalidInput, "frame too large")); } @@ -59,8 +58,7 @@ pub(crate) fn read_frame(r: &mut impl BufRead) -> io::Result<Option<Frame>> { } let mut body = vec![0u8; n]; r.read_exact(&mut body)?; - let f: Frame = serde_json::from_slice(&body) - .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?; + let f: Frame = serde_json::from_slice(&body).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?; Ok(Some(f)) } @@ -79,7 +77,8 @@ mod tests { #[test] fn frames_round_trip_through_a_byte_stream() { let mut buf = Vec::new(); - write_frame(&mut buf, &Frame::Hello { token: "t".into(), agent_id: "a".into(), profiles: vec!["p".into()] }).unwrap(); + write_frame(&mut buf, &Frame::Hello { token: "t".into(), agent_id: "a".into(), profiles: vec!["p".into()] }) + .unwrap(); write_frame(&mut buf, &Frame::Log { req: 7, stream: "stdout".into(), data: hex_bytes(b"hello") }).unwrap(); write_frame(&mut buf, &Frame::Exit { req: 7, code: Some(0) }).unwrap(); let mut cur = std::io::BufReader::new(std::io::Cursor::new(buf)); |
