Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

fix(spaces): Windows Space image pull continues after a broken download (CUA-1856) (#5408)

Francesco Bonacci15ac317bf21d
diff --git a/libs/cua/crates/cua-image/src/registry.rs b/libs/cua/crates/cua-image/src/registry.rs
index 3b542d0614..9d24685134 100644
--- a/libs/cua/crates/cua-image/src/registry.rs
+++ b/libs/cua/crates/cua-image/src/registry.rs
@@ -341,12 +341,20 @@ impl RegistryClient {
/// [`RegistryClient::blob_to_file`], calling `on_bytes` with the bytes
/// written so far as the blob arrives.
+ ///
+ /// A connection that breaks mid-blob does not lose what arrived: the
+ /// download continues from `<dest>.partial` with a `Range` request, up to
+ /// [`BLOB_ATTEMPTS`] times, and a pull that still fails leaves the
+ /// partial file for the next pull to continue. A 6 GB single-layer
+ /// image (the Windows containerDisk) on a slow or flaky link used to
+ /// start from zero on every try. The whole file is checked against the
+ /// descriptor's digest before it is renamed to `dest`.
pub async fn blob_to_file_with_progress(
&self,
reference: &str,
desc: &Descriptor,
dest: &Path,
- on_bytes: impl FnMut(u64) + Send + Unpin,
+ mut on_bytes: impl FnMut(u64) + Send + Unpin,
) -> Result<()> {
let r = pull_ref(reference)?;
// The blob's manifest was read first, which found out whether this
@@ -356,24 +364,45 @@ impl RegistryClient {
tokio::fs::create_dir_all(p).await?;
}
let partial = dest.with_extension("partial");
- let file = tokio::fs::File::create(&partial).await?;
- let mut w = Counting {
- inner: tokio::io::BufWriter::with_capacity(1 << 20, file),
- written: 0,
- on_bytes,
- };
let layer = oci_client::manifest::OciDescriptor {
media_type: desc.media_type.clone(),
digest: desc.digest.clone(),
size: desc.size as i64,
..Default::default()
};
- let res = client.pull_blob(&r, &layer, &mut w).await;
- if let Err(e) = res {
+ let mut attempt = 1;
+ loop {
+ match download_blob(&client, &r, &layer, desc.size, &partial, &mut on_bytes).await {
+ Ok(()) => break,
+ Err(e) if attempt < BLOB_ATTEMPTS && continues_after(&e) => {
+ let have = tokio::fs::metadata(&partial).await.map_or(0, |m| m.len());
+ tracing::warn!(reference, digest = %desc.digest, attempt, have, size = desc.size, error = %e, "blob download broke; continuing it");
+ tokio::time::sleep(blob_retry_delay(attempt)).await;
+ attempt += 1;
+ }
+ Err(e) => {
+ // Kept when the next pull can continue it.
+ if !continues_after(&e) {
+ let _ = tokio::fs::remove_file(&partial).await;
+ }
+ return Err(e);
+ }
+ }
+ }
+ // oci-client checks a whole-blob response only; a continued one is
+ // checked here, from the file.
+ let check = partial.clone();
+ let (actual, _) = tokio::task::spawn_blocking(move || crate::digest::sha256_file(&check))
+ .await
+ .map_err(|e| ImageError::Registry(e.to_string()))??;
+ if desc.digest.starts_with("sha256:") && actual != desc.digest {
let _ = tokio::fs::remove_file(&partial).await;
- return Err(e.into());
+ return Err(ImageError::Digest {
+ what: format!("blob of {reference}"),
+ expected: desc.digest.clone(),
+ actual,
+ });
}
- w.flush().await?;
tokio::fs::rename(&partial, dest).await?;
Ok(())
}
@@ -488,42 +517,87 @@ impl RegistryClient {
}
/// An `AsyncWrite` that reports the bytes written through it.
-struct Counting<W, F> {
- inner: W,
- written: u64,
- on_bytes: F,
+/// How many times one pull asks for a blob: the first request, then a
+/// continuation (`Range`) after each break.
+pub const BLOB_ATTEMPTS: u32 = 5;
+
+/// The pause before continuation `attempt` (1 s, 2 s, 4 s, ...; at most 15 s).
+fn blob_retry_delay(attempt: u32) -> Duration {
+ Duration::from_secs((1u64 << attempt.saturating_sub(1).min(4)).min(15))
}
-impl<W: tokio::io::AsyncWrite + Unpin, F: FnMut(u64) + Unpin> tokio::io::AsyncWrite
- for Counting<W, F>
-{
- fn poll_write(
- self: std::pin::Pin<&mut Self>,
- cx: &mut std::task::Context<'_>,
- buf: &[u8],
- ) -> std::task::Poll<std::io::Result<usize>> {
- let this = self.get_mut();
- let polled = std::pin::Pin::new(&mut this.inner).poll_write(cx, buf);
- if let std::task::Poll::Ready(Ok(n)) = &polled {
- this.written += *n as u64;
- (this.on_bytes)(this.written);
- }
- polled
- }
+/// Whether a failed blob download may continue from what arrived: a broken
+/// connection, a short body, a server error. Not a refusal (not found, not
+/// authorized) or wrong content.
+fn continues_after(e: &ImageError) -> bool {
+ matches!(e, ImageError::Io(_) | ImageError::Registry(_))
+}
- fn poll_flush(
- self: std::pin::Pin<&mut Self>,
- cx: &mut std::task::Context<'_>,
- ) -> std::task::Poll<std::io::Result<()>> {
- std::pin::Pin::new(&mut self.get_mut().inner).poll_flush(cx)
+/// One request for the blob into `partial`: continues after the bytes it
+/// already holds (a `206` answer) or starts again (a `200` answer, or a
+/// file longer than the blob). `on_bytes` gets the blob bytes on disk so far.
+async fn download_blob(
+ client: &Client,
+ r: &Reference,
+ layer: &oci_client::manifest::OciDescriptor,
+ size: u64,
+ partial: &Path,
+ on_bytes: &mut (impl FnMut(u64) + Send),
+) -> Result<()> {
+ use oci_client::client::BlobResponse;
+ let mut have = tokio::fs::metadata(partial).await.map_or(0, |m| m.len());
+ if size > 0 && have > size {
+ have = 0;
}
-
- fn poll_shutdown(
- self: std::pin::Pin<&mut Self>,
- cx: &mut std::task::Context<'_>,
- ) -> std::task::Poll<std::io::Result<()>> {
- std::pin::Pin::new(&mut self.get_mut().inner).poll_shutdown(cx)
+ if size > 0 && have == size {
+ on_bytes(have);
+ return Ok(());
+ }
+ let (stream, append) = if have == 0 {
+ (client.pull_blob_stream(r, layer).await?, false)
+ } else {
+ match client
+ .pull_blob_stream_partial(r, layer, have, None)
+ .await?
+ {
+ BlobResponse::Partial(s) => (s, true),
+ // The registry sent the whole blob: start the file again.
+ BlobResponse::Full(s) => (s, false),
+ }
+ };
+ let mut written = if append { have } else { 0 };
+ let file = tokio::fs::OpenOptions::new()
+ .create(true)
+ .write(true)
+ .append(append)
+ .truncate(!append)
+ .open(partial)
+ .await?;
+ let mut out = tokio::io::BufWriter::with_capacity(1 << 20, file);
+ on_bytes(written);
+ let mut stream = stream.stream;
+ let res: Result<()> = async {
+ while let Some(chunk) = stream.try_next().await? {
+ out.write_all(&chunk).await?;
+ written += chunk.len() as u64;
+ on_bytes(written);
+ }
+ Ok(())
+ }
+ .await;
+ // What arrived stays on disk for the next request, also on a break.
+ out.flush().await?;
+ res?;
+ if size > 0 && written < size {
+ return Err(ImageError::Io(std::io::Error::new(
+ std::io::ErrorKind::UnexpectedEof,
+ format!(
+ "blob {} ended after {written} of {size} bytes",
+ layer.digest
+ ),
+ )));
}
+ Ok(())
}
#[cfg(test)]
diff --git a/libs/cua/crates/cua-image/tests/blob_resume.rs b/libs/cua/crates/cua-image/tests/blob_resume.rs
new file mode 100644
index 0000000000..4c4c1811fc
--- /dev/null
+++ b/libs/cua/crates/cua-image/tests/blob_resume.rs
@@ -0,0 +1,189 @@
+//! A blob download that breaks mid-way continues from the bytes that
+//! arrived (`Range`), within one pull and across pulls, and the result is
+//! checked against the digest. Against a loopback plain-HTTP registry that
+//! cuts its answers short. Its own test binary, since it sets env vars.
+
+use std::sync::{Arc, Mutex};
+
+use cua_image::RegistryClient;
+use cua_image::digest::sha256_bytes;
+use cua_image::manifest::Descriptor;
+use tokio::io::{AsyncReadExt, AsyncWriteExt};
+use tokio::net::TcpListener;
+
+/// What the registry did with each blob request: the `Range` start asked
+/// for (0 without one).
+type Seen = Arc<Mutex<Vec<u64>>>;
+
+/// Serves `blob` at any `/v2/<repo>/blobs/<digest>` path, honouring
+/// `Range: bytes=N-`, and closes each answer after at most `cut` body bytes
+/// (the header still promises the rest).
+async fn serve(listener: TcpListener, blob: Arc<Vec<u8>>, cut: usize, seen: Seen) {
+ for _ in 0..50 {
+ let Ok((mut s, _)) = listener.accept().await else {
+ return;
+ };
+ let (blob, seen) = (blob.clone(), seen.clone());
+ tokio::spawn(async move {
+ let mut buf = vec![0u8; 16 << 10];
+ let mut n = 0;
+ while n < buf.len() {
+ let Ok(k) = s.read(&mut buf[n..]).await else {
+ return;
+ };
+ if k == 0 {
+ return;
+ }
+ n += k;
+ if buf[..n].windows(4).any(|w| w == b"\r\n\r\n") {
+ break;
+ }
+ }
+ let req = String::from_utf8_lossy(&buf[..n]).to_string();
+ let path = req.split_whitespace().nth(1).unwrap_or("").to_string();
+ if path == "/v2/" {
+ let _ = s
+ .write_all(
+ b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\n{}",
+ )
+ .await;
+ return;
+ }
+ if !path.contains("/blobs/") {
+ let _ = s
+ .write_all(
+ b"HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
+ )
+ .await;
+ return;
+ }
+ let from = req
+ .lines()
+ .find_map(|l| {
+ let l = l.to_ascii_lowercase();
+ l.strip_prefix("range: bytes=")
+ .and_then(|r| r.trim().trim_end_matches('-').parse::<u64>().ok())
+ })
+ .unwrap_or(0);
+ seen.lock().unwrap().push(from);
+ let rest = &blob[from as usize..];
+ let head = if from > 0 {
+ format!(
+ "HTTP/1.1 206 Partial Content\r\nContent-Range: bytes {from}-{}/{}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
+ blob.len() - 1,
+ blob.len(),
+ rest.len()
+ )
+ } else {
+ format!(
+ "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
+ rest.len()
+ )
+ };
+ let _ = s.write_all(head.as_bytes()).await;
+ let _ = s.write_all(&rest[..rest.len().min(cut)]).await;
+ let _ = s.flush().await;
+ // Dropping the socket cuts the answer short.
+ });
+ }
+}
+
+async fn registry(blob: &[u8], cut: usize) -> (String, Seen, tokio::task::JoinHandle<()>) {
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let host = format!("127.0.0.1:{}", listener.local_addr().unwrap().port());
+ let seen = Seen::default();
+ let server = tokio::spawn(serve(listener, Arc::new(blob.to_vec()), cut, seen.clone()));
+ let empty = tempfile::tempdir().unwrap().keep();
+ unsafe {
+ std::env::set_var("DOCKER_CONFIG", &empty);
+ std::env::set_var("CUA_REGISTRY_CRED_HELPERS", "0");
+ std::env::remove_var("CUA_REGISTRY_USERNAME");
+ std::env::set_var("CUA_INSECURE_REGISTRIES", &host);
+ }
+ (host, seen, server)
+}
+
+fn descriptor(blob: &[u8]) -> Descriptor {
+ Descriptor {
+ media_type: "application/vnd.oci.image.layer.v1.tar+gzip".into(),
+ digest: sha256_bytes(blob),
+ size: blob.len() as u64,
+ ..Default::default()
+ }
+}
+
+/// Tests share the process env (`CUA_INSECURE_REGISTRIES`): one at a time.
+static SERIAL: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
+
+#[tokio::test]
+async fn a_broken_download_continues_where_it_stopped() {
+ let _g = SERIAL.lock().await;
+ let blob: Vec<u8> = (0..30u8).collect();
+ // Every answer stops after 10 bytes: three requests, each continuing.
+ let (host, seen, server) = registry(&blob, 10).await;
+ let dir = tempfile::tempdir().unwrap();
+ let dest = dir.path().join("blob");
+ let mut progress = Vec::new();
+ RegistryClient::new(vec![host.clone()])
+ .blob_to_file_with_progress(
+ &format!("{host}/team/disk:1"),
+ &descriptor(&blob),
+ &dest,
+ |n| progress.push(n),
+ )
+ .await
+ .unwrap();
+ assert_eq!(std::fs::read(&dest).unwrap(), blob);
+ assert_eq!(
+ *seen.lock().unwrap(),
+ vec![0, 10, 20],
+ "never downloads a byte twice"
+ );
+ assert_eq!(progress.last(), Some(&30));
+ assert!(
+ progress.windows(2).all(|w| w[0] <= w[1]),
+ "progress never goes back: {progress:?}"
+ );
+ assert!(!dest.with_extension("partial").exists());
+ server.abort();
+}
+
+#[tokio::test]
+async fn a_later_pull_continues_what_an_earlier_one_left() {
+ let _g = SERIAL.lock().await;
+ let blob: Vec<u8> = (0..40u8).collect();
+ let (host, seen, server) = registry(&blob, usize::MAX).await;
+ let dir = tempfile::tempdir().unwrap();
+ let dest = dir.path().join("blob");
+ // An earlier pull that gave up after 25 bytes.
+ std::fs::write(dest.with_extension("partial"), &blob[..25]).unwrap();
+ RegistryClient::new(vec![host.clone()])
+ .blob_to_file(&format!("{host}/team/disk:1"), &descriptor(&blob), &dest)
+ .await
+ .unwrap();
+ assert_eq!(std::fs::read(&dest).unwrap(), blob);
+ assert_eq!(*seen.lock().unwrap(), vec![25]);
+ server.abort();
+}
+
+#[tokio::test]
+async fn a_continued_blob_that_does_not_match_its_digest_is_refused_and_dropped() {
+ let _g = SERIAL.lock().await;
+ let blob: Vec<u8> = (0..40u8).collect();
+ let (host, _seen, server) = registry(&blob, usize::MAX).await;
+ let dir = tempfile::tempdir().unwrap();
+ let dest = dir.path().join("blob");
+ // Left by an earlier pull, but not the blob's first bytes.
+ std::fs::write(dest.with_extension("partial"), [9u8; 25]).unwrap();
+ let err = RegistryClient::new(vec![host.clone()])
+ .blob_to_file(&format!("{host}/team/disk:1"), &descriptor(&blob), &dest)
+ .await
+ .unwrap_err();
+ assert!(err.to_string().contains("digest mismatch"), "{err}");
+ assert!(!dest.exists());
+ assert!(
+ !dest.with_extension("partial").exists(),
+ "a bad partial is not kept"
+ );
+ server.abort();
+}