Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
118 changes: 105 additions & 13 deletions crates/kiri-image/src/registry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1137,7 +1137,7 @@ impl Client {
let _on = cancel.enter();
let stopped = |e: Error| if cancel.is_cancelled() { Error::Cancelled } else { e };
self.warm_up(r, "pull").map_err(stopped)?;
let (bytes, media_type) = self.manifest(r, &r.reference).map_err(stopped)?;
let (bytes, media_type) = self.manifest_with(r, &r.reference, Some(cancel)).map_err(stopped)?;
// A pull by digest must get exactly that content, whether it is a
// single manifest or a multi-arch index. Without this, a registry
// could answer a pinned digest with any index naming any children.
Expand All @@ -1163,7 +1163,7 @@ impl Client {
.collect(),
});
};
let (entry_bytes, _) = self.manifest(r, &entry.digest).map_err(stopped)?;
let (entry_bytes, _) = self.manifest_with(r, &entry.digest, Some(cancel)).map_err(stopped)?;
if sha256_digest(&entry_bytes) != entry.digest {
return Err(Error::Manifest(format!("manifest {} failed digest check", entry.digest)));
}
Expand Down Expand Up @@ -1358,24 +1358,54 @@ impl Client {
}

fn manifest(&self, r: &Reference, reference: &str) -> Result<(Vec<u8>, String), Error> {
self.manifest_with(r, reference, None)
}

fn manifest_with(&self, r: &Reference, reference: &str, cancel: Option<&Cancel>) -> Result<(Vec<u8>, String), Error> {
let by_digest = reference.starts_with("sha256:");
let key = self.manifest_key(r, reference);
if by_digest && let Some(hit) = MANIFESTS.lock().unwrap_or_else(|e| e.into_inner()).get(&key) {
return Ok(hit);
}
let url = format!("{}/v2/{}/manifests/{reference}", self.base(r.api_host()), r.repository);
let mut resp = self.get(r, &url, Some(ACCEPT))?;
let media_type = resp
.headers()
.get("content-type")
.and_then(|v| v.to_str().ok())
.unwrap_or_default()
.to_owned();
let bytes = resp.body_mut().with_config().limit(4 << 20).read_to_vec()?;
if by_digest {
MANIFESTS.lock().unwrap_or_else(|e| e.into_inner()).put(&key, reference, &bytes, &media_type);
let mut failed = 0;
loop {
if cancel.is_some_and(Cancel::is_cancelled) {
return Err(Error::Cancelled);
}
let attempt = (|| -> Result<(Vec<u8>, String), Error> {
let mut resp = self.get(r, &url, Some(ACCEPT))?;
let media_type = resp
.headers()
.get("content-type")
.and_then(|v| v.to_str().ok())
.unwrap_or_default()
.to_owned();
let bytes = resp.body_mut().with_config().limit(4 << 20).read_to_vec()?;
Ok((bytes, media_type))
})();
match attempt {
Ok((bytes, media_type)) => {
if by_digest {
MANIFESTS.lock().unwrap_or_else(|e| e.into_inner()).put(&key, reference, &bytes, &media_type);
}
return Ok((bytes, media_type));
}
Err(_) if cancel.is_some_and(Cancel::is_cancelled) => return Err(Error::Cancelled),
Err(e) if transient(&e) => {
failed += 1;
if failed >= BLOB_TRIES {
return Err(e);
}
let wait = Duration::from_millis(500 << (failed - 1).min(4));
match cancel {
Some(c) => c.sleep(wait),
None => std::thread::sleep(wait),
}
}
Err(e) => return Err(e),
}
}
Ok((bytes, media_type))
}

/// Streams one blob into the store, verifying its digest. Returns its size.
Expand Down Expand Up @@ -4189,4 +4219,66 @@ mod tests {
assert_eq!(certs.len(), roots.len());
assert!(certs.iter().zip(roots.iter()).all(|(a, b)| a.der() == b.as_ref()));
}

#[test]
fn manifest_retries_transient_429_before_succeeding() {
use std::io::{Read, Write};
use std::sync::atomic::{AtomicBool, Ordering};
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
let host = addr.to_string();
let stop = std::sync::Arc::new(AtomicBool::new(false));
let stop_srv = stop.clone();
let body = br#"{"schemaVersion":2,"mediaType":"application/vnd.oci.image.manifest.v2+json"}"#.to_vec();
let server = std::thread::spawn(move || {
let mut manifests = 0u32;
for c in listener.incoming().flatten() {
if stop_srv.load(Ordering::Relaxed) {
break;
}
let mut c = c;
let mut buf = [0u8; 2048];
let n = c.read(&mut buf).unwrap_or(0);
let head = String::from_utf8_lossy(&buf[..n]);
if !head.starts_with("GET ") && !head.starts_with("HEAD ") {
continue;
}
let path = head.lines().next().and_then(|l| l.split_whitespace().nth(1)).unwrap_or("");
if path == "/v2/" {
let _ = c.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\n{}");
continue;
}
if !path.contains("/manifests/") {
continue;
}
manifests += 1;
if manifests < 3 {
let msg = br#"{"errors":[{"code":"TOO_MANY_REQUEST"}]}"#;
let reply = format!(
"HTTP/1.1 429 Too Many Requests\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
msg.len()
);
let _ = c.write_all(reply.as_bytes());
let _ = c.write_all(msg);
} else {
let reply = format!(
"HTTP/1.1 200 OK\r\nContent-Type: application/vnd.oci.image.manifest.v2+json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
body.len()
);
let _ = c.write_all(reply.as_bytes());
let _ = c.write_all(&body);
}
let _ = c.flush();
}
manifests
});
let client = Client::new();
let r = Reference::parse(&format!("{host}/library/alpine:3.18")).unwrap();
let (got, media_type) = client.manifest(&r, &r.reference).unwrap();
stop.store(true, Ordering::Relaxed);
let _ = std::net::TcpStream::connect(addr);
assert_eq!(media_type, "application/vnd.oci.image.manifest.v2+json");
assert!(got.starts_with(b"{\"schemaVersion\":2"));
assert_eq!(server.join().unwrap(), 3);
}
}
91 changes: 72 additions & 19 deletions crates/kiri-init/src/linux/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -222,12 +222,25 @@ fn mount_kernel_filesystems() -> io::Result<()> {
fn host_dirs() -> io::Result<container::Paths> {
// SAFETY: umask only changes this process's file-creation mask.
unsafe { libc::umask(0o022) };
// Claim the network namespace BEFORE touching `/var/lib/kiri` mounts so a
// second engine never detaches a running engine's mount before failing.
net::claim_host_netns()?;
let root = PathBuf::from(DATA);
if let Some(data) = std::env::var_os("KIRI_AGENT_DATA").map(PathBuf::from).filter(|p| p.is_absolute() && p != &root) {
mount_agent_data(&data, &root)?;
let data = std::env::var_os("KIRI_AGENT_DATA").map(PathBuf::from).filter(|p| p.is_absolute() && p != &root);
let own_root = data.as_deref().unwrap_or(&root);
// Claim the network namespace BEFORE touching `/var/lib/kiri` mounts so a
// second engine never detaches a running engine's mount before failing (#443).
// When this data directory's own `agent.lock` is held (for example by a
// frozen container child that inherited `@kiri-engine-netns` before closing
// descriptors when the old agent died), reclaim our own lock and sweep our
// own recorded cgroup first, then claim the network namespace.
if let Err(e) = net::claim_host_netns() {
if e.kind() == io::ErrorKind::AddrInUse && is_file_locked(&own_root.join("agent.lock")) {
take_over(own_root, || sweep_recorded_cgroup(own_root))?;
net::claim_host_netns()?;
} else {
return Err(e);
}
}
if let Some(data) = &data {
mount_agent_data(data, &root)?;
} else {
detach_deleted_bind_mount(&root);
}
Expand All @@ -241,20 +254,9 @@ fn host_dirs() -> io::Result<container::Paths> {
mkdir(&root, 0o710)?;
mkdir(&root.join("volumes"), 0o700)?;
// What a dead agent left running can hold its lock (see `take_over`).
let leftovers = || {
let Ok(old) = std::fs::read_to_string(root.join("agent.cgroup")) else { return };
let old = PathBuf::from(old.trim());
if is_cgroup2_dir(&old) {
let paths = container::Paths {
layers: root.join("layers"),
containers: root.join("containers"),
cgroup: old.clone(),
cgroup_root: old.clone(),
};
container::sweep(&paths, &old);
}
};
take_over(&root, leftovers)?;
if AGENT_LOCK.get().is_none() {
take_over(&root, || sweep_recorded_cgroup(&root))?;
}
let (cgroup_root, cgroup) = host_cgroup()?;
let paths = container::Paths {
layers: root.join("layers"),
Expand Down Expand Up @@ -341,6 +343,38 @@ fn is_mounted_at(mountinfo: &str, target: &std::path::Path) -> bool {
/// The lock on a Linux host's data directory, held while the agent runs.
static AGENT_LOCK: std::sync::OnceLock<File> = std::sync::OnceLock::new();

/// Whether `path` exists and another open file description currently holds an
/// exclusive `flock` on it, without creating `path` or keeping a lock.
fn is_file_locked(path: &std::path::Path) -> bool {
use std::os::fd::AsRawFd;
let Ok(file) = File::open(path) else {
return false;
};
// SAFETY: non-blocking `flock` probe on a descriptor we own.
if unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } == 0 {
unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_UN) };
false
} else {
io::Error::last_os_error().raw_os_error() == Some(libc::EWOULDBLOCK)
}
}

/// Sweeps containers recorded in `root/agent.cgroup` by a previous agent of
/// this data directory.
fn sweep_recorded_cgroup(root: &std::path::Path) {
let Ok(old) = std::fs::read_to_string(root.join("agent.cgroup")) else { return };
let old = PathBuf::from(old.trim());
if is_cgroup2_dir(&old) {
let paths = container::Paths {
layers: root.join("layers"),
containers: root.join("containers"),
cgroup: old.clone(),
cgroup_root: old.clone(),
};
container::sweep(&paths, &old);
}
}

/// One agent per data directory on a Linux host: takes `agent.lock` (an
/// flock, released when the process ends however it ends). An agent that
/// still holds it is stopped if its daemon is gone (an orphan: SIGTERM, so
Expand Down Expand Up @@ -991,6 +1025,25 @@ mod cgroup_discovery_tests {
assert!(!super::is_mounted_at(mountinfo, Path::new("/var/lib")));
assert!(!super::is_mounted_at(mountinfo, Path::new("/media/ssd")));
}

#[test]
fn is_file_locked_detects_held_flock_without_creating_missing_file() {
use std::os::fd::AsRawFd;
let dir = std::env::temp_dir().join(format!("kiri-lock-probe-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let lock_path = dir.join("agent.lock");
assert!(!super::is_file_locked(&lock_path));
assert!(!lock_path.exists(), "missing lock file must not be created");

let holder = std::fs::File::create(&lock_path).unwrap();
assert!(!super::is_file_locked(&lock_path));
assert_eq!(unsafe { libc::flock(holder.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) }, 0);
assert!(super::is_file_locked(&lock_path));
drop(holder);
assert!(!super::is_file_locked(&lock_path));
let _ = std::fs::remove_dir_all(&dir);
}
}

#[cfg(test)]
Expand Down
4 changes: 3 additions & 1 deletion crates/kiri-win/src/wslsync.rs
Original file line number Diff line number Diff line change
Expand Up @@ -305,7 +305,7 @@ pub fn wsl_readonly_message(kind: WslReadOnly, vhdx_path: Option<&Path>) -> Stri
}

/// SHA-256 of `"kiri"`, used by the Docker CLI for `~/.docker/contexts/meta/<hash>/meta.json`.
const KIRI_CONTEXT_HASH: &str = "c288b06224b0bc4af8a3d80f683a27a8fc72e45f901a7e6766109e2fc1d5c2b9";
const KIRI_CONTEXT_HASH: &str = "80d7688032dda428a5d1e0eea7ad434d219b770b7d3a0646fd58695e40107755";

const DEFAULT_USER_AWK: &str = "function k(s) { sub(/#.*/, \"\", s); gsub(/[[:space:]]/, \"\", s); return s } \
substr(k($0), 1, 1) == \"[\" { u = tolower(k($0)) == \"[user]\"; next } \
Expand Down Expand Up @@ -662,6 +662,8 @@ mod tests {
fn wsl_integration_scripts_have_no_backslash() {
assert!(!wsl_enable_script("Ubuntu", "").contains('\\'));
assert!(!wsl_disable_script("Ubuntu", "").contains('\\'));
assert_eq!(KIRI_CONTEXT_HASH.len(), 64);
assert!(KIRI_CONTEXT_HASH.starts_with("80d7688032dda428"));
}

#[test]
Expand Down
Loading
Loading