feat(containers): upload and load container images in parts
Jason Schwarzenberger authored 1 parent 3962d40commit 5b019f8c57e646e1e400902bec432159bdcb2edfBrowse files
5 files changed+358−16
Files (5)
- HOMEFLARE.md+1−0
- crates/celld/bucket.rs+189−0
- crates/celld/container.rs+16−3
- crates/celld/deploy.rs+100−13
- crates/celld/docker.rs+52−0
modifiedHOMEFLARE.md+1−0View file
| @@ -27,6 +27,7 @@ | ||
| 27 | 27 | | `version_metadata` binding | Upstream celld had none, so Homeflare passed the version ID as a plain string. The binding is now Cloudflare's frozen `{ id, tag, timestamp }`. The config may set all three (Homeflare passes its own version ID, tag and time, so they match its Dashboard and `wrangler versions`); otherwise the id is the deployment's version, the tag is empty and the timestamp is the deploy time. | |
| 28 | 28 | | `ratelimits` binding | Diffinery limits sign-ins and API calls with `env.RL_*.limit({ key })`. Each entry becomes a binding counted on the node by a `__ratelimit` op: fixed windows of the period (10 or 60 s), keyed by namespace id and key and shared by the node's isolates, as each Cloudflare location counts on its own. | |
| 29 | 29 | | `send_email` binding (Email Sending) | Diffinery sends sign-up codes, invitations and notifications with `env.EMAIL.send({ from, to, subject, html, text })`. The binding checks the message and the binding's `allowed_sender_addresses` / `destination_address` / `allowed_destination_addresses`, then posts it in the REST API's shape (`{address, name}`, `reply_to`, base64 attachments) to `CELLD_EMAIL_URL/send` with `CELLD_EMAIL_TOKEN` as a bearer. Homeflare relays it to Cloudflare's Email Sending API. The result is `{ messageId, delivered, queued, permanent_bounces, suppressed_recipients }`; API errors become the binding's `E_*` codes. The legacy raw `EmailMessage` isn't supported (celld has no `cloudflare:email`). | |
| 30 | +| Container images in parts | `celld deploy` read the whole `docker save` output into memory and wrote it in one `PUT`, which has to finish within the bucket client's 30 s; Diffinery's multi-GB runner image timed out against RustFS, failing every redeploy. The save now streams into a multipart upload of 16 MiB parts (`Bucket::put_large`), completed only once the save exits successfully. A node loading the image downloads it in 16 MiB ranges to a temporary file (`Bucket::get_large`) and streams that to the engine's `images/load` (`Docker::post_file`). Test: `CELLD_TEST_S3_ENDPOINT=... cargo test -p celld --lib large_object_round_trip -- --ignored` against any S3 (moto_server works). | | |
| 30 | 31 | | `homeflare:` line in `celld --version` | Lists what this build adds (`HOMEFLARE_FEATURES` in `lib.rs`), so Homeflare sends a config key only to a celld that accepts it. Add a feature there with each patch. | |
| 31 | 32 | |
| 32 | 33 | ## Building |
modifiedcrates/celld/bucket.rs+189−0View file
| @@ -64,6 +64,14 @@ | ||
| 64 | 64 | include!(env!("CELLD_INTERNAL_BUCKET_TESTS")); |
| 65 | 65 | } |
| 66 | 66 | |
| 67 | +/// The part size of [`Bucket::put_large`] and the range size of | |
| 68 | +/// [`Bucket::get_large`]: comfortably above S3's 5 MiB part minimum, small | |
| 69 | +/// enough that one part fits the client's per-request timeout on a slow link. | |
| 70 | +const LARGE_PART: usize = 16 << 20; | |
| 71 | +/// Parts uploading at once in [`Bucket::put_large`]; with [`LARGE_PART`] this | |
| 72 | +/// bounds the memory an upload holds. | |
| 73 | +const LARGE_PARTS_IN_FLIGHT: usize = 4; | |
| 74 | + | |
| 67 | 75 | /// The stored form of an empty blob key segment. See [`Bucket::blob_path`]. |
| 68 | 76 | const EMPTY_SEGMENT: &str = "%"; |
| 69 | 77 | |
| @@ -957,6 +965,101 @@ | ||
| 957 | 965 | } |
| 958 | 966 | } |
| 959 | 967 | |
| 968 | + /// Write a large object from a stream in parts (homeflare: container | |
| 969 | + /// image tars, which are gigabytes). A single `put` has to finish within | |
| 970 | + /// the client's per-request timeout and holds the whole body in memory; | |
| 971 | + /// a part is one request of [`LARGE_PART`] bytes. The upload completes | |
| 972 | + /// only when `reader` reaches its end; an error aborts it, so a reader | |
| 973 | + /// cut short leaves nothing under the key. | |
| 974 | + pub async fn put_large( | |
| 975 | + &self, | |
| 976 | + key: &str, | |
| 977 | + mut reader: impl tokio::io::AsyncRead + Unpin, | |
| 978 | + ) -> anyhow::Result<u64> { | |
| 979 | + use tokio::io::AsyncReadExt; | |
| 980 | + let path = Path::from(self.key(key).as_str()); | |
| 981 | + let scoped = self.key(key); | |
| 982 | + let upload = self.store.put_multipart(&path).await.with_context(|| { | |
| 983 | + format!("begin multipart {}://{}/{scoped}", self.scheme(), self.name) | |
| 984 | + })?; | |
| 985 | + let mut writer = object_store::WriteMultipart::new_with_chunk_size(upload, LARGE_PART); | |
| 986 | + let mut buf = vec![0u8; 1 << 20]; | |
| 987 | + let mut total = 0u64; | |
| 988 | + let result: anyhow::Result<()> = async { | |
| 989 | + loop { | |
| 990 | + let n = reader.read(&mut buf).await.context("read the upload")?; | |
| 991 | + if n == 0 { | |
| 992 | + return Ok(()); | |
| 993 | + } | |
| 994 | + total += n as u64; | |
| 995 | + writer | |
| 996 | + .wait_for_capacity(LARGE_PARTS_IN_FLIGHT) | |
| 997 | + .await | |
| 998 | + .with_context(|| format!("write {}://{}/{scoped}", self.scheme(), self.name))?; | |
| 999 | + writer.write(&buf[..n]); | |
| 1000 | + } | |
| 1001 | + } | |
| 1002 | + .await; | |
| 1003 | + match result { | |
| 1004 | + Ok(()) => { | |
| 1005 | + writer.finish().await.with_context(|| { | |
| 1006 | + format!("complete {}://{}/{scoped}", self.scheme(), self.name) | |
| 1007 | + })?; | |
| 1008 | + Ok(total) | |
| 1009 | + } | |
| 1010 | + Err(error) => { | |
| 1011 | + let _ = writer.abort().await; | |
| 1012 | + Err(error) | |
| 1013 | + } | |
| 1014 | + } | |
| 1015 | + } | |
| 1016 | + | |
| 1017 | + /// Read a large object into `file` with ranged reads of [`LARGE_PART`] | |
| 1018 | + /// bytes, each its own request, so no one request has to carry the | |
| 1019 | + /// whole object within the client's timeout. `None` when the key does | |
| 1020 | + /// not exist. | |
| 1021 | + pub async fn get_large( | |
| 1022 | + &self, | |
| 1023 | + key: &str, | |
| 1024 | + file: &mut tokio::fs::File, | |
| 1025 | + ) -> anyhow::Result<Option<u64>> { | |
| 1026 | + use tokio::io::AsyncWriteExt; | |
| 1027 | + let Some((size, _)) = self.head(key).await? else { | |
| 1028 | + return Ok(None); | |
| 1029 | + }; | |
| 1030 | + let path = Path::from(self.key(key).as_str()); | |
| 1031 | + let scoped = self.key(key); | |
| 1032 | + let mut offset = 0u64; | |
| 1033 | + while offset < size { | |
| 1034 | + let end = (offset + LARGE_PART as u64).min(size); | |
| 1035 | + let options = GetOptions { | |
| 1036 | + range: Some(GetRange::Bounded(offset..end)), | |
| 1037 | + ..GetOptions::default() | |
| 1038 | + }; | |
| 1039 | + let bytes = self | |
| 1040 | + .store | |
| 1041 | + .get_opts(&path, options) | |
| 1042 | + .await | |
| 1043 | + .with_context(|| format!("read {}://{}/{scoped}", self.scheme(), self.name))? | |
| 1044 | + .bytes() | |
| 1045 | + .await | |
| 1046 | + .with_context(|| format!("read {}://{}/{scoped}", self.scheme(), self.name))?; | |
| 1047 | + if bytes.is_empty() { | |
| 1048 | + anyhow::bail!( | |
| 1049 | + "read {}://{}/{scoped}: empty range at {offset} of {size}", | |
| 1050 | + self.scheme(), | |
| 1051 | + self.name | |
| 1052 | + ); | |
| 1053 | + } | |
| 1054 | + file.write_all(&bytes) | |
| 1055 | + .await | |
| 1056 | + .context("write the downloaded object")?; | |
| 1057 | + offset += bytes.len() as u64; | |
| 1058 | + } | |
| 1059 | + file.flush().await.context("write the downloaded object")?; | |
| 1060 | + Ok(Some(size)) | |
| 1061 | + } | |
| 1062 | + | |
| 960 | 1063 | pub async fn put(&self, key: &str, body: impl Into<PutPayload>) -> anyhow::Result<()> { |
| 961 | 1064 | let key = self.key(key); |
| 962 | 1065 | self.store |
| @@ -2148,3 +2251,89 @@ | ||
| 2148 | 2251 | || text.contains("status code: 401 Unauthorized") |
| 2149 | 2252 | }) |
| 2150 | 2253 | } |
| 2254 | + | |
| 2255 | +/// homeflare: `put_large` and `get_large` against a real S3 endpoint. Run | |
| 2256 | +/// with `CELLD_TEST_S3_ENDPOINT` set (e.g. moto_server) and `--ignored`. | |
| 2257 | +#[cfg(test)] | |
| 2258 | +mod large_object_tests { | |
| 2259 | + use super::*; | |
| 2260 | + | |
| 2261 | + #[tokio::test] | |
| 2262 | + #[ignore] | |
| 2263 | + #[allow(clippy::disallowed_methods)] | |
| 2264 | + async fn large_object_round_trip() { | |
| 2265 | + let endpoint = std::env::var("CELLD_TEST_S3_ENDPOINT").expect("CELLD_TEST_S3_ENDPOINT"); | |
| 2266 | + let bucket = Bucket::open( | |
| 2267 | + "s3://celld-large/fleet", | |
| 2268 | + Some(&endpoint), | |
| 2269 | + "us-east-1", | |
| 2270 | + Some(StaticCredentials { | |
| 2271 | + access_key_id: "test".into(), | |
| 2272 | + secret_access_key: "test".into(), | |
| 2273 | + session_token: None, | |
| 2274 | + }), | |
| 2275 | + None, | |
| 2276 | + ) | |
| 2277 | + .unwrap(); | |
| 2278 | + // Two and a half parts, with bytes that differ by position. | |
| 2279 | + let size = LARGE_PART * 2 + LARGE_PART / 2; | |
| 2280 | + let body: Vec<u8> = (0..size).map(|i| (i % 251) as u8).collect(); | |
| 2281 | + let written = bucket | |
| 2282 | + .put_large("deploy/images/x.tar", std::io::Cursor::new(body.clone())) | |
| 2283 | + .await | |
| 2284 | + .unwrap(); | |
| 2285 | + assert_eq!(written, size as u64); | |
| 2286 | + let (stored, _) = bucket.head("deploy/images/x.tar").await.unwrap().unwrap(); | |
| 2287 | + assert_eq!(stored, size as u64); | |
| 2288 | + | |
| 2289 | + let temp = tempfile::NamedTempFile::new().unwrap(); | |
| 2290 | + let mut file = tokio::fs::File::from_std(temp.reopen().unwrap()); | |
| 2291 | + let read = bucket | |
| 2292 | + .get_large("deploy/images/x.tar", &mut file) | |
| 2293 | + .await | |
| 2294 | + .unwrap(); | |
| 2295 | + assert_eq!(read, Some(size as u64)); | |
| 2296 | + drop(file); | |
| 2297 | + assert!( | |
| 2298 | + std::fs::read(temp.path()).unwrap() == body, | |
| 2299 | + "downloaded bytes differ" | |
| 2300 | + ); | |
| 2301 | + assert_eq!( | |
| 2302 | + bucket | |
| 2303 | + .get_large( | |
| 2304 | + "deploy/images/none.tar", | |
| 2305 | + &mut tokio::fs::File::from_std(temp.reopen().unwrap()) | |
| 2306 | + ) | |
| 2307 | + .await | |
| 2308 | + .unwrap(), | |
| 2309 | + None | |
| 2310 | + ); | |
| 2311 | + | |
| 2312 | + // A reader that fails partway leaves nothing behind. | |
| 2313 | + struct Failing(usize); | |
| 2314 | + impl tokio::io::AsyncRead for Failing { | |
| 2315 | + fn poll_read( | |
| 2316 | + mut self: std::pin::Pin<&mut Self>, | |
| 2317 | + _: &mut std::task::Context<'_>, | |
| 2318 | + buf: &mut tokio::io::ReadBuf<'_>, | |
| 2319 | + ) -> std::task::Poll<std::io::Result<()>> { | |
| 2320 | + if self.0 == 0 { | |
| 2321 | + return std::task::Poll::Ready(Err(std::io::Error::other("save failed"))); | |
| 2322 | + } | |
| 2323 | + let n = self.0.min(buf.remaining()).min(1 << 20); | |
| 2324 | + buf.put_slice(&vec![7u8; n]); | |
| 2325 | + self.0 -= n; | |
| 2326 | + std::task::Poll::Ready(Ok(())) | |
| 2327 | + } | |
| 2328 | + } | |
| 2329 | + assert!(bucket | |
| 2330 | + .put_large("deploy/images/bad.tar", Failing(LARGE_PART + 5)) | |
| 2331 | + .await | |
| 2332 | + .is_err()); | |
| 2333 | + assert!(bucket | |
| 2334 | + .head("deploy/images/bad.tar") | |
| 2335 | + .await | |
| 2336 | + .unwrap() | |
| 2337 | + .is_none()); | |
| 2338 | + } | |
| 2339 | +} |
modifiedcrates/celld/container.rs+16−3View file
| @@ -575,14 +575,27 @@ | ||
| 575 | 575 | .as_ref() |
| 576 | 576 | .ok_or_else(|| anyhow!("image {image} is not present in the container engine"))?; |
| 577 | 577 | let key = image_key(image); |
| 578 | - let (tar, _) = bucket.get(&key).await?.ok_or_else(|| { | |
| 578 | + // homeflare: download in ranges to a temporary file and stream it to | |
| 579 | + // the engine. An image tar is often gigabytes: one `get` would hold | |
| 580 | + // it all in memory and has to finish within the bucket client's | |
| 581 | + // per-request timeout. | |
| 582 | + let temp = tempfile::NamedTempFile::new().context("temporary file for the image")?; | |
| 583 | + let mut file = tokio::fs::File::from_std(temp.reopen().context("open the image file")?); | |
| 584 | + let bytes = bucket.get_large(&key, &mut file).await?.ok_or_else(|| { | |
| 579 | 585 | anyhow!("image {image} is not in the bucket at {key}; run `celld deploy`") |
| 580 | 586 | })?; |
| 581 | - let bytes = tar.len(); | |
| 587 | + drop(file); | |
| 588 | + let file = tokio::fs::File::from_std(temp.reopen().context("open the image file")?); | |
| 582 | 589 | let reply = self |
| 583 | 590 | .docker |
| 584 | - .post_octets("/images/load?quiet=true", tar, "load image") | |
| 591 | + .post_file( | |
| 592 | + "/images/load?quiet=true", | |
| 593 | + file, | |
| 594 | + "application/x-tar", | |
| 595 | + "load image", | |
| 596 | + ) | |
| 585 | 597 | .await?; |
| 598 | + drop(temp); | |
| 586 | 599 | tracing::info!( |
| 587 | 600 | image, |
| 588 | 601 | bytes, |
modifiedcrates/celld/deploy.rs+100−13View file
| @@ -571,10 +571,9 @@ | ||
| 571 | 571 | binding.get("period").and_then(Value::as_u64).unwrap_or(0) |
| 572 | 572 | ), |
| 573 | 573 | )), |
| 574 | - Some("send_email") => Some(( | |
| 575 | - format!("env.{name} (Email)"), | |
| 576 | - "Email Sending".to_string(), | |
| 577 | - )), | |
| 574 | + Some("send_email") => { | |
| 575 | + Some((format!("env.{name} (Email)"), "Email Sending".to_string())) | |
| 576 | + } | |
| 578 | 577 | Some("plain_text") => Some(( |
| 579 | 578 | format!("env.{name} (Text)"), |
| 580 | 579 | "Environment Variable".to_string(), |
| @@ -892,20 +891,103 @@ | ||
| 892 | 891 | if bucket.head(&key).await?.is_some() { |
| 893 | 892 | return Ok(()); |
| 894 | 893 | } |
| 895 | - let output = Command::new(engine_cli()) | |
| 894 | + // homeflare: stream the tar into a multipart upload. An image is often | |
| 895 | + // gigabytes, and one `put` would hold it all in memory and has to finish | |
| 896 | + // within the bucket client's per-request timeout. | |
| 897 | + let mut child = tokio::process::Command::new(engine_cli()) | |
| 896 | 898 | .args(["save", image]) |
| 897 | 899 | .stdin(std::process::Stdio::null()) |
| 898 | - .output() | |
| 900 | + .stdout(std::process::Stdio::piped()) | |
| 901 | + .stderr(std::process::Stdio::piped()) | |
| 902 | + .kill_on_drop(true) | |
| 903 | + .spawn() | |
| 899 | 904 | .context("save container image")?; |
| 900 | - if !output.status.success() { | |
| 901 | - bail!( | |
| 905 | + let stdout = child | |
| 906 | + .stdout | |
| 907 | + .take() | |
| 908 | + .context("save container image: no stdout")?; | |
| 909 | + let stderr = child | |
| 910 | + .stderr | |
| 911 | + .take() | |
| 912 | + .context("save container image: no stderr")?; | |
| 913 | + let errors = tokio::spawn(async move { | |
| 914 | + use tokio::io::AsyncReadExt; | |
| 915 | + let mut text = String::new(); | |
| 916 | + let mut stderr = stderr; | |
| 917 | + let _ = stderr.read_to_string(&mut text).await; | |
| 918 | + text | |
| 919 | + }); | |
| 920 | + // A save that fails partway ends its stdout early, which would complete | |
| 921 | + // a truncated tar. So the upload reads through a gate that holds the end | |
| 922 | + // of the stream until the save has exited successfully. | |
| 923 | + let gate = SaveGate { | |
| 924 | + stdout, | |
| 925 | + child: Some(child), | |
| 926 | + exit: None, | |
| 927 | + ended: false, | |
| 928 | + }; | |
| 929 | + let uploaded = bucket.put_large(&key, gate).await; | |
| 930 | + let stderr = errors.await.unwrap_or_default(); | |
| 931 | + match uploaded { | |
| 932 | + Ok(_) => Ok(()), | |
| 933 | + Err(error) if !stderr.trim().is_empty() => Err(error.context(format!( | |
| 902 | 934 | "save container image failed:\n{}", |
| 903 | - String::from_utf8_lossy(&output.stderr).trim_end() | |
| 904 | - ); | |
| 935 | + stderr.trim_end() | |
| 936 | + ))), | |
| 937 | + Err(error) => Err(error.context("save container image")), | |
| 905 | 938 | } |
| 906 | - bucket.put(&key, output.stdout).await | |
| 907 | 939 | } |
| 908 | 940 | |
| 941 | +/// `podman save`'s stdout, ending only once the save has exited with | |
| 942 | +/// success; a failed save turns its end of stream into an error, which | |
| 943 | +/// aborts the multipart upload instead of completing a truncated tar. | |
| 944 | +struct SaveGate { | |
| 945 | + stdout: tokio::process::ChildStdout, | |
| 946 | + child: Option<tokio::process::Child>, | |
| 947 | + exit: Option< | |
| 948 | + std::pin::Pin< | |
| 949 | + Box<dyn std::future::Future<Output = std::io::Result<std::process::ExitStatus>> + Send>, | |
| 950 | + >, | |
| 951 | + >, | |
| 952 | + /// The save exited successfully: every further read is end of stream. | |
| 953 | + ended: bool, | |
| 954 | +} | |
| 955 | + | |
| 956 | +impl tokio::io::AsyncRead for SaveGate { | |
| 957 | + fn poll_read( | |
| 958 | + mut self: std::pin::Pin<&mut Self>, | |
| 959 | + cx: &mut std::task::Context<'_>, | |
| 960 | + buf: &mut tokio::io::ReadBuf<'_>, | |
| 961 | + ) -> std::task::Poll<std::io::Result<()>> { | |
| 962 | + use std::task::Poll; | |
| 963 | + let this = &mut *self; | |
| 964 | + if this.ended { | |
| 965 | + return Poll::Ready(Ok(())); | |
| 966 | + } | |
| 967 | + if this.exit.is_none() { | |
| 968 | + let before = buf.filled().len(); | |
| 969 | + match std::pin::Pin::new(&mut this.stdout).poll_read(cx, buf) { | |
| 970 | + Poll::Ready(Ok(())) if buf.filled().len() == before => { | |
| 971 | + let mut child = this.child.take().expect("save child"); | |
| 972 | + this.exit = Some(Box::pin(async move { child.wait().await })); | |
| 973 | + } | |
| 974 | + other => return other, | |
| 975 | + } | |
| 976 | + } | |
| 977 | + match this.exit.as_mut().expect("exit future").as_mut().poll(cx) { | |
| 978 | + Poll::Pending => Poll::Pending, | |
| 979 | + Poll::Ready(Ok(status)) if status.success() => { | |
| 980 | + this.ended = true; | |
| 981 | + Poll::Ready(Ok(())) | |
| 982 | + } | |
| 983 | + Poll::Ready(Ok(status)) => Poll::Ready(Err(std::io::Error::other(format!( | |
| 984 | + "the image save exited with {status}" | |
| 985 | + )))), | |
| 986 | + Poll::Ready(Err(error)) => Poll::Ready(Err(error)), | |
| 987 | + } | |
| 988 | + } | |
| 989 | +} | |
| 990 | + | |
| 909 | 991 | pub async fn write(bucket: &Bucket, built: &Built) -> anyhow::Result<()> { |
| 910 | 992 | // Read every attachment before uploading immutable deployment objects. |
| 911 | 993 | // A competing consumer is a deploy refusal, so it must not leave a new |
| @@ -2009,12 +2091,17 @@ | ||
| 2009 | 2091 | .get("limit") |
| 2010 | 2092 | .and_then(Value::as_u64) |
| 2011 | 2093 | .filter(|limit| *limit > 0) |
| 2012 | - .ok_or_else(|| anyhow!("ratelimit {name}: `simple.limit` must be a positive integer"))?; | |
| 2094 | + .ok_or_else(|| { | |
| 2095 | + anyhow!("ratelimit {name}: `simple.limit` must be a positive integer") | |
| 2096 | + })?; | |
| 2013 | 2097 | let period = simple.get("period").and_then(Value::as_u64); |
| 2014 | 2098 | if !matches!(period, Some(10 | 60)) { |
| 2015 | 2099 | bail!("ratelimit {name}: `simple.period` must be 10 or 60 (seconds), as on Cloudflare"); |
| 2016 | 2100 | } |
| 2017 | - if let Some(key) = simple.keys().find(|key| !matches!(key.as_str(), "limit" | "period")) { | |
| 2101 | + if let Some(key) = simple | |
| 2102 | + .keys() | |
| 2103 | + .find(|key| !matches!(key.as_str(), "limit" | "period")) | |
| 2104 | + { | |
| 2018 | 2105 | bail!("ratelimit {name} sets `simple.{key}`, which celld does not support"); |
| 2019 | 2106 | } |
| 2020 | 2107 | if let Some(key) = entry |
modifiedcrates/celld/docker.rs+52−0View file
| @@ -207,6 +207,58 @@ | ||
| 207 | 207 | Ok(reply) |
| 208 | 208 | } |
| 209 | 209 | |
| 210 | + /// POST a file as the request body, streamed rather than read into | |
| 211 | + /// memory (homeflare: `images/load` of a tar that can be gigabytes). | |
| 212 | + /// The connection is driven by the ambient runtime, as [`drive`] does. | |
| 213 | + #[allow(clippy::disallowed_methods)] | |
| 214 | + pub async fn post_file( | |
| 215 | + &self, | |
| 216 | + path: &str, | |
| 217 | + file: tokio::fs::File, | |
| 218 | + content_type: &str, | |
| 219 | + what: &str, | |
| 220 | + ) -> anyhow::Result<Reply> { | |
| 221 | + use futures_util::TryStreamExt; | |
| 222 | + use http_body_util::StreamBody; | |
| 223 | + use hyper::body::Frame; | |
| 224 | + let stream = tokio_util::io::ReaderStream::with_capacity(file, 1 << 20).map_ok(Frame::data); | |
| 225 | + let body = http_body_util::combinators::BoxBody::new(StreamBody::new(stream)); | |
| 226 | + let request = Request::builder() | |
| 227 | + .method("POST") | |
| 228 | + .uri(format!("{API}{path}")) | |
| 229 | + .header(HOST, "docker") | |
| 230 | + .header(CONTENT_TYPE, content_type) | |
| 231 | + .body(body) | |
| 232 | + .context("build Docker request")?; | |
| 233 | + let stream = self.connect().await?; | |
| 234 | + let (mut sender, connection) = hyper::client::conn::http1::handshake(TokioIo::new(stream)) | |
| 235 | + .await | |
| 236 | + .context("HTTP handshake with the container engine")?; | |
| 237 | + tokio::spawn(async move { | |
| 238 | + let _ = connection.await; | |
| 239 | + }); | |
| 240 | + let response = sender | |
| 241 | + .send_request(request) | |
| 242 | + .await | |
| 243 | + .context("send request to the container engine")?; | |
| 244 | + let status = response.status(); | |
| 245 | + let body = response | |
| 246 | + .into_body() | |
| 247 | + .collect() | |
| 248 | + .await | |
| 249 | + .context("read Docker response")? | |
| 250 | + .to_bytes(); | |
| 251 | + let reply = Reply { status, body }; | |
| 252 | + if !reply.status.is_success() { | |
| 253 | + return Err(anyhow!( | |
| 254 | + "{what} failed with [{}] {}", | |
| 255 | + reply.status.as_u16(), | |
| 256 | + reply.message() | |
| 257 | + )); | |
| 258 | + } | |
| 259 | + Ok(reply) | |
| 260 | + } | |
| 261 | + | |
| 210 | 262 | /// `POST /exec/{id}/start` with `Upgrade: tcp`: the daemon answers 101 |
| 211 | 263 | /// and the connection becomes the process's stdin and its multiplexed |
| 212 | 264 | /// stdout/stderr. The returned stream is that connection. |